1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
use crate::texture::TextureManager;
use anyhow::{anyhow, Result};
use gst::glib::ControlFlow;
use gst::prelude::*;
use gstreamer as gst;
use gstreamer_app as gst_app;
use gstreamer_video as gst_video;
use log::{debug, error, info, warn};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use wgpu;
#[derive(Debug, Clone, Default)]
pub struct SpectrumData {
/// Number of frequency bands
pub bands: usize,
/// Magnitude values for each frequency band in dB
pub magnitudes: Vec<f32>,
/// Phase values for each frequency band
pub phases: Option<Vec<f32>>,
/// Timestamp of the spectrum data
pub timestamp: Option<gst::ClockTime>,
}
#[derive(Debug, Clone, Default)]
pub struct AudioLevel {
/// RMS in linear scale (0.0 to 1.0)
pub rms: f64,
/// RMS in decibels
pub rms_db: f64,
/// Peak value in linear scale (0.0 to 1.0)
pub peak: f64,
}
/// Here I created a struct to organize the video text mang.
/// Manages a video texture that can be updated frame by frame
pub struct VideoTextureManager {
/// The underlying TextureManager that handles the WGPU resources
texture_manager: TextureManager,
/// The GStreamer pipeline for video decoding
pipeline: gst::Pipeline,
/// The AppSink element that receives decoded frames
appsink: gst_app::AppSink,
/// Whether the video has an audio track
has_audio: bool,
/// Whether this is an audio-only file (no video track)
audio_only: Arc<Mutex<bool>>,
/// Audio volume (0.0 to 1.0)
volume: Arc<Mutex<f64>>,
/// Whether audio is muted
is_muted: Arc<Mutex<bool>>,
/// Current video dimensions
dimensions: (u32, u32),
/// Video duration in nanoseconds (if available)
duration: Option<gst::ClockTime>,
/// Current position in the video
position: Arc<Mutex<gst::ClockTime>>,
/// Frame rate of the video
framerate: Option<gst::Fraction>,
/// Whether the video is currently playing
is_playing: Arc<Mutex<bool>>,
/// Whether to loop the video when it ends
loop_playback: Arc<Mutex<bool>>,
/// Last frame update time
last_update: Instant,
/// Frame buffer for the most recently decoded frame
current_frame: Arc<Mutex<Option<image::RgbaImage>>>,
/// Path to the video file
video_path: String,
/// Whether the video texture has been initialized
texture_initialized: bool,
/// Frame counter for debugging
frame_count: usize,
/// Spectrum analysis enabled
spectrum_enabled: bool,
/// Number of frequency bands for spectrum analysis
spectrum_bands: usize,
/// Threshold in dB for spectrum analysis
spectrum_threshold: i32,
/// Spectrum data from the most recent analysis
spectrum_data: Arc<Mutex<SpectrumData>>,
/// Audio level data (RMS, peak) for normalization
audio_level: Arc<Mutex<AudioLevel>>,
/// bpm
bpm_value: Arc<Mutex<f32>>,
/// Whether video track was found
has_video: Arc<Mutex<bool>>,
}
impl VideoTextureManager {
pub fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
bind_group_layout: &wgpu::BindGroupLayout,
video_path: impl AsRef<Path>,
) -> Result<Self> {
// Create a default 1x1 texture initially, note that, this going to be replaced with first video frame
let default_image = image::RgbaImage::new(1, 1);
let texture_manager = TextureManager::new(device, queue, &default_image, bind_group_layout);
let path_str = video_path
.as_ref()
.to_str()
.ok_or_else(|| anyhow!("Invalid video path"))?
.to_string();
info!("Creating video texture from: {path_str}");
let pipeline = gst::Pipeline::new();
// Source element - read from file
let filesrc = gst::ElementFactory::make("filesrc")
.name("source")
.property("location", &path_str)
.build()
.map_err(|_| anyhow!("Failed to create filesrc element"))?;
// Decoding element
let decodebin = gst::ElementFactory::make("decodebin")
.name("decoder")
.build()
.map_err(|_| anyhow!("Failed to create decodebin element"))?;
// videorate element to enforce correct frame timing
let videorate = gst::ElementFactory::make("videorate")
.name("rate")
.build()
.map_err(|_| anyhow!("Failed to create videorate element"))?;
// Convert to proper format
let videoconvert = gst::ElementFactory::make("videoconvert")
.name("convert")
.build()
.map_err(|_| anyhow!("Failed to create videoconvert element"))?;
//caps filter to force framerate if needed
let capsfilter = gst::ElementFactory::make("capsfilter")
.name("capsfilter")
.build()
.map_err(|_| anyhow!("Failed to create capsfilter element"))?;
// Output sink for video
let appsink = gst::ElementFactory::make("appsink")
.name("sink")
.build()
.map_err(|_| anyhow!("Failed to create appsink element"))?;
let appsink = appsink
.dynamic_cast::<gst_app::AppSink>()
.map_err(|_| anyhow!("Failed to cast to AppSink"))?;
// Configure appsink
appsink.set_caps(Some(
&gst::Caps::builder("video/x-raw")
.field("format", gst_video::VideoFormat::Rgba.to_str())
.build(),
));
appsink.set_max_buffers(2);
// Drop old buffers when full
appsink.set_drop(true);
appsink.set_sync(true);
// video elements goes to the pipeline
pipeline
.add_many([
&filesrc,
&decodebin,
&videorate,
&videoconvert,
&capsfilter,
appsink.upcast_ref(),
])
.map_err(|_| anyhow!("Failed to add video elements to pipeline"))?;
// Link elements that can be linked statically
gst::Element::link_many([&videorate, &videoconvert, &capsfilter, appsink.upcast_ref()])
.map_err(|_| anyhow!("Failed to link video elements"))?;
gst::Element::link_many([&filesrc, &decodebin])
.map_err(|_| anyhow!("Failed to link filesrc to decodebin"))?;
// Set up pad-added signal for dynamic linking from decodebin -> videorate
let videorate_weak = videorate.downgrade();
let has_audio = Arc::new(Mutex::new(false));
let has_audio_clone = has_audio.clone();
let has_video = Arc::new(Mutex::new(false));
let has_video_clone = has_video.clone();
// now audio elements reference holders
let audioconvert_weak = Arc::new(Mutex::new(None));
// Default spectrum configuration
let spectrum_bands = 128;
let spectrum_threshold = -60;
let spectrum_enabled = true;
let spectrum_data = Arc::new(Mutex::new(SpectrumData::default()));
let audio_level = Arc::new(Mutex::new(AudioLevel::default()));
// bus watch for spectrum messages with debug
let bus = pipeline.bus().expect("Pipeline has no bus");
let spectrum_data_clone2 = spectrum_data.clone();
// Bus watch for pipeline messages (errors, warnings, EOS)
let watch_result = bus.add_watch(move |_, message| {
match message.view() {
gst::MessageView::Element(element) => {
if let Some(structure) = element.structure() {
info!("Element message structure name: '{}'", structure.name());
// Explicitly check for spectrum messages
if structure.name() == "spectrum" {
info!("SPECTRUM MESSAGE DETECTED ");
info!("Full structure: {structure}");
// Try ALL possible ways to extract spectrum data
let mut magnitude_values = Vec::new();
// Method 1: Direct indexing
for i in 0..5 {
// Just try first 5 bands initially
let field_name = format!("magnitude[{i}]");
match structure.get::<f32>(&field_name) {
Ok(value) => {
info!("Method 1 - Band {i}: {value} dB");
magnitude_values.push(value);
}
Err(e) => {
info!("Method 1 failed: {e:?}");
break;
}
}
}
// Method 2: Try to access magnitude as array field
if structure.has_field("magnitude") {
info!("Structure has 'magnitude' field");
} else {
info!("Structure does NOT have 'magnitude' field");
}
// Method 3: Parse from structure string
let struct_str = structure.to_string();
info!("Structure string: {struct_str}");
// If we found magnitude values through any method, process them
if !magnitude_values.is_empty() {
// Continue extracting all magnitude values
let mut i = magnitude_values.len();
loop {
let field_name = format!("magnitude[{i}]");
if let Ok(value) = structure.get::<f32>(&field_name) {
magnitude_values.push(value);
i += 1;
} else {
break;
}
}
// Log summary of extracted data
info!("Extracted {} magnitude values", magnitude_values.len());
// Calculate average magnitude
let avg_magnitude = magnitude_values.iter().sum::<f32>()
/ magnitude_values.len() as f32;
info!("Average magnitude: {avg_magnitude:.2} dB");
// Find peak frequency
if let Some((peak_idx, &peak_val)) = magnitude_values
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| {
a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
})
{
info!("Peak frequency: band {peak_idx} at {peak_val:.2} dB");
}
// Update spectrum data
if let Ok(mut data) = spectrum_data_clone2.lock() {
*data = SpectrumData {
bands: magnitude_values.len(),
magnitudes: magnitude_values,
phases: None,
timestamp: structure.get("timestamp").ok(),
};
}
} else {
warn!(
"Failed to extract any magnitude values from spectrum message"
);
}
}
// Handle level messages for RMS/peak/decay
if structure.name() == "level" {
info!("LEVEL MESSAGE DETECTED");
info!("Level structure: {structure}");
// Extract RMS, peak, and decay values
if let Ok(rms_list) = structure.get::<gst::glib::ValueArray>("rms") {
let mut rms_values = Vec::new();
for val in rms_list.iter() {
if let Ok(rms_db) = val.get::<f64>() {
rms_values.push(rms_db);
}
}
if !rms_values.is_empty() {
info!("Level RMS values: {rms_values:?}");
}
}
}
// Note: BPM messages are handled in poll_audio_messages()
}
}
gst::MessageView::Tag(tag) => {
let tags = tag.tags();
// Note: BPM tags are handled in poll_audio_messages()
if let Some(bpm) = tags.get::<gst::tags::BeatsPerMinute>() {
info!("BPM tag detected: {:.1}", bpm.get());
}
}
gst::MessageView::Error(err) => {
error!(
"Pipeline error: {} ({})",
err.error(),
err.debug().unwrap_or_default()
);
}
_ => (),
}
ControlFlow::Continue
});
if let Err(e) = watch_result {
error!("Failed to add bus watch: {e:?}");
}
decodebin.connect_pad_added(move |_, pad| {
let caps = match pad.current_caps() {
Some(caps) => caps,
_ => return,
};
let structure = match caps.structure(0) {
Some(s) => s,
_ => return,
};
// Check if this is a video or audio stream. maybe there could be other way to handle this but I love simpicity
if structure.name().starts_with("video/") {
// Mark that we have a video track
if let Ok(mut has_video_lock) = has_video_clone.lock() {
*has_video_lock = true;
info!("Video track detected");
}
// Handle video path
if let Some(videorate) = videorate_weak.upgrade() {
let sink_pad = match videorate.static_pad("sink") {
Some(pad) => pad,
_ => return,
};
if !sink_pad.is_linked() {
let _ = pad.link(&sink_pad);
info!("Linked decoder to videorate successfully");
}
}
} else if structure.name().starts_with("audio/") {
// has_audio flag to true - we've detected an audio stream
if let Ok(mut has_audio_lock) = has_audio_clone.lock() {
*has_audio_lock = true;
info!("Audio track detected in video");
}
// Now lets dynamically create the audio processing chain
if let Ok(mut audioconvert_lock) = audioconvert_weak.lock() {
// Only create audio elements once when first audio pad is detected
if audioconvert_lock.is_none() {
// Create audio elements
let audioconvert = match gst::ElementFactory::make("audioconvert")
.name("audioconvert")
.build()
{
Ok(e) => e,
Err(_) => {
warn!("Failed to create audioconvert");
return;
}
};
let audioresample = match gst::ElementFactory::make("audioresample")
.name("audioresample")
.build()
{
Ok(e) => e,
Err(_) => {
warn!("Failed to create audioresample");
return;
}
};
// level element for RMS/peak/decay analysis
let level = match gst::ElementFactory::make("level")
.name("level")
.property("interval", 50000000u64) // 50ms intervals (matches spectrum)
.property("message", true)
.property("post-messages", true)
.build()
{
Ok(e) => {
info!("Created level analyzer element");
e
}
Err(_) => {
warn!("Failed to create level element");
return;
}
};
let bpmdetect = match gst::ElementFactory::make("bpmdetect")
.name("bpmdetect")
.build()
{
Ok(e) => {
info!("Created BPM detector");
e
}
Err(_) => {
warn!("Failed to create BPM detector");
return;
}
};
let spectrum = match gst::ElementFactory::make("spectrum")
.name("spectrum")
.property("bands", spectrum_bands as u32)
.property("threshold", spectrum_threshold)
.property("post-messages", true)
.property("message-magnitude", true)
.property("message-phase", false)
.property("interval", 50000000u64)
.build()
{
Ok(e) => {
info!(
"Created spectrum analyzer with {spectrum_bands} bands and threshold {spectrum_threshold}dB"
);
e
}
Err(_) => {
warn!("Failed to create spectrum analyzer");
return;
}
};
let volume = match gst::ElementFactory::make("volume")
.name("volume")
.property("volume", 1.0)
.build()
{
Ok(e) => e,
Err(_) => {
warn!("Failed to create volume");
return;
}
};
// autoaudiosink should works on all platforms: https://gstreamer.freedesktop.org/documentation/autodetect/autoaudiosink.html?gi-language=c
let audio_sink = match gst::ElementFactory::make("autoaudiosink")
.name("audiosink")
.build()
{
Ok(e) => e,
Err(_) => {
warn!("Failed to create autoaudiosink");
return;
}
};
// Add elements to pipeline
if let Err(e) = pad
.parent_element()
.unwrap()
.parent()
.unwrap()
.downcast_ref::<gst::Pipeline>()
.unwrap()
.add_many([
&audioconvert,
&audioresample,
&level,
&bpmdetect,
&spectrum,
&volume,
&audio_sink,
])
{
warn!("Failed to add audio elements: {e:?}");
return;
}
// Link audio elements
if let Err(e) = gst::Element::link_many([
&audioconvert,
&audioresample,
&level,
&bpmdetect,
&spectrum,
&volume,
&audio_sink,
]) {
warn!("Failed to link audio elements: {e:?}");
return;
}
// Set elements to PAUSED state
let _ = audioconvert.sync_state_with_parent();
let _ = audioresample.sync_state_with_parent();
let _ = level.sync_state_with_parent();
let _ = bpmdetect.sync_state_with_parent();
let _ = spectrum.sync_state_with_parent();
let _ = volume.sync_state_with_parent();
let _ = audio_sink.sync_state_with_parent();
*audioconvert_lock = Some(audioconvert.clone());
}
// Link decoder pad to audioconvert
if let Some(audioconvert) = &*audioconvert_lock {
let sink_pad = match audioconvert.static_pad("sink") {
Some(pad) => pad,
_ => return,
};
if !sink_pad.is_linked() {
match pad.link(&sink_pad) {
Ok(_) => {
info!("Linked decoder to audioconvert successfully");
}
Err(err) => {
warn!("Failed to link audio pad: {err:?}");
}
}
}
}
}
}
});
// Create shared state
let current_frame = Arc::new(Mutex::new(None));
let current_frame_clone = current_frame.clone();
let position = Arc::new(Mutex::new(gst::ClockTime::ZERO));
let is_playing = Arc::new(Mutex::new(false));
let volume_val = Arc::new(Mutex::new(1.0));
let is_muted = Arc::new(Mutex::new(false));
// Setup callbacks to receive frames
appsink.set_callbacks(
gst_app::AppSinkCallbacks::builder()
.new_sample(move |sink| {
let sample = match sink.pull_sample() {
Ok(sample) => sample,
Err(_) => return Err(gst::FlowError::Eos),
};
let buffer = match sample.buffer() {
Some(buffer) => buffer,
_ => return Err(gst::FlowError::Error),
};
let caps = match sample.caps() {
Some(caps) => caps,
_ => return Err(gst::FlowError::Error),
};
let video_info = match gst_video::VideoInfo::from_caps(caps) {
Ok(info) => info,
Err(_) => return Err(gst::FlowError::Error),
};
let map = match buffer.map_readable() {
Ok(map) => map,
Err(_) => return Err(gst::FlowError::Error),
};
// Access the raw frame data
let frame_data = map.as_slice();
let width = video_info.width() as usize;
let height = video_info.height() as usize;
// Create an RgbaImage from the frame data
// (We need to copy the data because buffer will be unmapped after this function)
let mut rgba_image = image::RgbaImage::new(width as u32, height as u32);
// Stride might be larger than width * 4
let stride = video_info.stride()[0] as usize;
for y in 0..height {
let src_start = y * stride;
let src_end = src_start + width * 4;
let dst_start = y * width * 4;
let dst_end = dst_start + width * 4;
// Copy row by row to handle stride correctly
let dst_buffer = rgba_image.as_mut();
if src_end <= frame_data.len() && dst_end <= dst_buffer.len() {
dst_buffer[dst_start..dst_end]
.copy_from_slice(&frame_data[src_start..src_end]);
}
}
// Store the frame
if let Ok(mut frame_lock) = current_frame_clone.lock() {
*frame_lock = Some(rgba_image);
}
Ok(gst::FlowSuccess::Ok)
})
.build(),
);
// init the object
let mut video_texture = Self {
texture_manager,
pipeline,
appsink,
has_audio: false,
audio_only: Arc::new(Mutex::new(false)),
volume: volume_val,
is_muted,
dimensions: (1, 1),
duration: None,
position,
framerate: None,
is_playing,
loop_playback: Arc::new(Mutex::new(true)),
last_update: Instant::now(),
current_frame,
video_path: path_str,
texture_initialized: false,
frame_count: 0,
spectrum_enabled,
spectrum_bands,
spectrum_threshold,
spectrum_data,
audio_level,
bpm_value: Arc::new(Mutex::new(0.0)),
has_video: has_video.clone(),
};
// Start pipeline in paused state to get video info
if video_texture
.pipeline
.set_state(gst::State::Paused)
.is_err()
{
return Err(anyhow!("Failed to set pipeline to PAUSED state"));
}
// Wait a bit for pipeline to settle
std::thread::sleep(Duration::from_millis(200));
let state_result = video_texture
.pipeline
.state(gst::ClockTime::from_seconds(1));
if let (_, gst::State::Paused, _) = state_result {
video_texture.query_video_info()?;
} else {
warn!("Pipeline not in PAUSED state, may not be able to query info");
}
// Set specific framerate in the caps filter if we detected one
if let Some(framerate) = video_texture.framerate {
if let Some(capsfilter_elem) = video_texture.pipeline.by_name("capsfilter") {
let caps = gst::Caps::builder("video/x-raw")
.field("framerate", framerate)
.build();
capsfilter_elem.set_property("caps", &caps);
info!(
"Set capsfilter to force framerate {}/{}",
framerate.numer(),
framerate.denom()
);
}
}
video_texture.has_audio = *has_audio.lock().unwrap();
let has_video_track = *has_video.lock().unwrap();
// Determine if this is an audio-only file
if video_texture.has_audio && !has_video_track {
*video_texture.audio_only.lock().unwrap() = true;
info!("Audio-only file detected - no video track present");
// For audio-only files, remove unlinked video elements from the pipeline
if let Some(videorate_elem) = video_texture.pipeline.by_name("rate") {
let _ = videorate_elem.set_state(gst::State::Null);
let _ = video_texture.pipeline.remove(&videorate_elem);
info!("Removed unused videorate element");
}
if let Some(convert_elem) = video_texture.pipeline.by_name("convert") {
let _ = convert_elem.set_state(gst::State::Null);
let _ = video_texture.pipeline.remove(&convert_elem);
info!("Removed unused videoconvert element");
}
if let Some(capsfilter_elem) = video_texture.pipeline.by_name("capsfilter") {
let _ = capsfilter_elem.set_state(gst::State::Null);
let _ = video_texture.pipeline.remove(&capsfilter_elem);
info!("Removed unused capsfilter element");
}
if let Some(sink_elem) = video_texture.pipeline.by_name("sink") {
let _ = sink_elem.set_state(gst::State::Null);
let _ = video_texture.pipeline.remove(&sink_elem);
info!("Removed unused appsink element");
}
}
info!("Video has audio: {}, has video: {}, audio_only: {}",
video_texture.has_audio,
has_video_track,
*video_texture.audio_only.lock().unwrap());
info!("Video texture manager created successfully");
Ok(video_texture)
}
/// Query video information (dimensions, duration, framerate)
fn query_video_info(&mut self) -> Result<()> {
// Query duration
if let Some(duration) = self.pipeline.query_duration::<gst::ClockTime>() {
self.duration = Some(duration);
info!(
"Video duration: {:?} ({:.2} seconds)",
duration,
duration.seconds() as f64
);
}
// Now try to get video info
if let Some(pad) = self.appsink.static_pad("sink") {
if let Some(caps) = pad.current_caps() {
if let Some(s) = caps.structure(0) {
// dims
if let (Ok(width), Ok(height)) = (s.get::<i32>("width"), s.get::<i32>("height"))
{
self.dimensions = (width as u32, height as u32);
info!("Video dimensions: {width}x{height}");
}
// framerate
if let Ok(framerate) = s.get::<gst::Fraction>("framerate") {
self.framerate = Some(framerate);
info!(
"Video framerate: {}/{} (approx. {:.2} fps)",
framerate.numer(),
framerate.denom(),
framerate.numer() as f64 / framerate.denom() as f64
);
}
}
}
}
Ok(())
}
/// Get the texture manager (for binding to shaders)
pub fn texture_manager(&self) -> &TextureManager {
&self.texture_manager
}
/// Update the texture with the current video frame
pub fn update_texture(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
bind_group_layout: &wgpu::BindGroupLayout,
) -> Result<bool> {
// No update needed if video is not playing
if !*self.is_playing.lock().unwrap() {
return Ok(false);
}
let is_audio_only = *self.audio_only.lock().unwrap();
let mut audio_updated = false;
// ALWAYS poll for audio messages, regardless of video frame availability
// This decouples audio processing from video frame rate
if self.has_audio && self.spectrum_enabled {
audio_updated = self.poll_audio_messages();
}
// Check if we have a NEW frame to process
let frame_to_process = {
let mut frame_lock = self.current_frame.lock().unwrap();
frame_lock.take()
};
// If we have a frame, update the texture
if let Some(frame) = frame_to_process {
self.frame_count += 1;
// Get frame dimensions
let width = frame.width();
let height = frame.height();
// Log less frequently to reduce spam
if self.frame_count % 30 == 0 {
debug!(
"Processing video frame #{} (dimensions: {}x{})",
self.frame_count, width, height
);
}
// ALWAYS recreate the texture for the first frame or if dimensions don't match
let should_recreate = !self.texture_initialized
|| self.dimensions != (width, height)
|| self.dimensions.0 <= 1
|| self.dimensions.1 <= 1
|| self.frame_count <= 3;
if should_recreate {
info!("Creating new texture with dimensions: {width}x{height}");
// Create a completely new texture with the frame's dimensions
let new_texture_manager =
TextureManager::new(device, queue, &frame, bind_group_layout);
self.texture_manager = new_texture_manager;
self.dimensions = (width, height);
self.texture_initialized = true;
} else {
self.texture_manager.update(queue, &frame);
}
// Get current position
if let Some(position) = self.pipeline.query_position::<gst::ClockTime>() {
*self.position.lock().unwrap() = position;
// Check if we reached the end of the video
if let Some(duration) = self.duration {
let near_end_threshold =
duration.saturating_sub(gst::ClockTime::from_mseconds(100));
if position >= near_end_threshold {
debug!(
"Near end of video (position: {position:?}, duration: {duration:?})"
);
if *self.loop_playback.lock().unwrap() {
debug!("Looping video");
self.seek(gst::ClockTime::ZERO)?;
} else {
debug!("Pausing at end of video");
self.pause()?;
}
}
}
}
// Update the last update time
self.last_update = Instant::now();
Ok(true) // Texture was updated
} else {
// For audio-only files or when audio data was updated, return true
// to signal that the shader should re-render (even without new video frames)
if is_audio_only && audio_updated {
// Update position for audio-only files
if let Some(position) = self.pipeline.query_position::<gst::ClockTime>() {
*self.position.lock().unwrap() = position;
// Check if we reached the end
if let Some(duration) = self.duration {
let near_end_threshold =
duration.saturating_sub(gst::ClockTime::from_mseconds(100));
if position >= near_end_threshold {
if *self.loop_playback.lock().unwrap() {
debug!("Looping audio");
self.seek(gst::ClockTime::ZERO)?;
} else {
debug!("Pausing at end of audio");
self.pause()?;
}
}
}
}
self.last_update = Instant::now();
return Ok(true);
}
// For video with low FPS but audio updated, still signal update
if audio_updated {
return Ok(true);
}
Ok(false) // No update
}
}
/// Poll the GStreamer bus for audio-related messages (spectrum, level, BPM)
/// Returns true if any audio data was updated
fn poll_audio_messages(&mut self) -> bool {
let mut updated = false;
if let Some(bus) = self.pipeline.bus() {
// Poll for pending messages
while let Some(message) = bus.pop() {
match message.view() {
gst::MessageView::Element(element) => {
if let Some(structure) = element.structure() {
// spectrum data
if structure.name() == "spectrum" {
// Extract magnitude values - two possible approaches
let mut magnitude_values = Vec::with_capacity(128);
// APPROACH 1: Parse from structure string
let struct_str = structure.to_string();
if struct_str.contains("magnitude=(float){") {
// Extract magnitude values from string
if let Some(start_idx) =
struct_str.find("magnitude=(float){")
{
if let Some(end_idx) =
struct_str[start_idx..].find("}")
{
let magnitude_str = &struct_str[start_idx
+ "magnitude=(float){".len()
..start_idx + end_idx];
let values: Vec<&str> =
magnitude_str.split(',').collect();
for value_str in values {
if let Ok(value) =
value_str.trim().parse::<f32>()
{
magnitude_values.push(value);
}
}
}
}
}
// APPROACH 2: Try to access directly by index if approach 1 fails
if magnitude_values.is_empty() {
for i in 0..128 {
let field_name = format!("magnitude[{i}]");
if let Ok(value) = structure.get::<f32>(&field_name)
{
magnitude_values.push(value);
} else {
break;
}
}
}
// Process spectrum data if we have it
if !magnitude_values.is_empty() {
let bands = magnitude_values.len();
// Update spectrum data
if let Ok(mut data) = self.spectrum_data.lock() {
*data = SpectrumData {
bands,
magnitudes: magnitude_values,
phases: None,
timestamp: structure.get("timestamp").ok(),
};
}
updated = true;
}
}
// Check for level messages (RMS/peak/decay)
if structure.name() == "level" {
// Extract RMS and peak values
let mut rms_db_val = None;
let mut peak_val = None;
if let Ok(rms_list) =
structure.get::<gst::glib::ValueArray>("rms")
{
for val in rms_list.iter() {
if let Ok(rms_db) = val.get::<f64>() {
rms_db_val = Some(rms_db);
break; // Use first channel
}
}
}
if let Ok(peak_list) =
structure.get::<gst::glib::ValueArray>("peak")
{
for val in peak_list.iter() {
if let Ok(peak_db) = val.get::<f64>() {
// Convert dB to linear (0.0 to 1.0)
peak_val = Some(10.0_f64.powf(peak_db / 20.0));
break; // Use first channel
}
}
}
if let (Some(rms_db), Some(peak)) = (rms_db_val, peak_val) {
// Convert RMS from dB to linear
let rms_linear = 10.0_f64.powf(rms_db / 20.0);
// Update audio_level data with level element values
if let Ok(mut level) = self.audio_level.lock() {
*level = AudioLevel {
rms: rms_linear,
rms_db,
peak,
};
}
updated = true;
}
}
// Check for BPM messages from bpmdetect (structure name is "tempo")
if structure.name() == "tempo" {
if let Ok(bpm_val) = structure.get::<f64>("tempo") {
let bpm_val = bpm_val as f32;
if bpm_val > 0.0 {
if let Ok(mut bpm_lock) = self.bpm_value.lock() {
*bpm_lock = bpm_val;
info!("BPM detected: {:.1}", bpm_val);
}
updated = true;
}
}
}
}
}
// Also check for tag messages - bpmdetect posts BPM as tags!
gst::MessageView::Tag(tag) => {
let tags = tag.tags();
// Check for BPM tag from bpmdetect
if let Some(bpm) = tags.get::<gst::tags::BeatsPerMinute>() {
let bpm_val = bpm.get() as f32;
if bpm_val > 0.0 {
if let Ok(mut bpm_lock) = self.bpm_value.lock() {
*bpm_lock = bpm_val;
info!("BPM tag detected: {:.1}", bpm_val);
}
updated = true;
}
}
}
_ => (),
}
}
}
updated
}
/// Returns true if this is an audio-only file (no video track)
pub fn is_audio_only(&self) -> bool {
*self.audio_only.lock().unwrap()
}
/// Returns true if the media has a video track
pub fn has_video(&self) -> bool {
*self.has_video.lock().unwrap()
}
/// Start playing the video
pub fn play(&mut self) -> Result<()> {
info!("Playing video");
match self.pipeline.set_state(gst::State::Playing) {
Ok(_) => {
*self.is_playing.lock().unwrap() = true;
Ok(())
}
Err(e) => Err(anyhow!("Failed to start playback: {:?}", e)),
}
}
/// Pause the video
pub fn pause(&mut self) -> Result<()> {
info!("Pausing video");
match self.pipeline.set_state(gst::State::Paused) {
Ok(_) => {
*self.is_playing.lock().unwrap() = false;
Ok(())
}
Err(e) => Err(anyhow!("Failed to pause playback: {:?}", e)),
}
}
/// Seek to a specific position in the video
pub fn seek(&mut self, position: gst::ClockTime) -> Result<()> {
debug!("Seeking to position: {position:?}");
// are we sure the pipeline is in a state that can handle seeking??
let current_state = self.pipeline.current_state();
if current_state == gst::State::Null || current_state == gst::State::Ready {
warn!("Cannot seek in current state: {current_state:?}");
return Ok(());
}
// exec the seek operation
let seek_flags = gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT;
if self.pipeline.seek_simple(seek_flags, position).is_ok() {
debug!("Seek successful");
*self.position.lock().unwrap() = position;
Ok(())
} else {
let err = anyhow!("Failed to seek to {:?}", position);
error!("{err}");
Err(err)
}
}
pub fn set_loop(&mut self, should_loop: bool) {
*self.loop_playback.lock().unwrap() = should_loop;
info!("Video loop set to: {should_loop}");
}
/// audio volume (between 0.0 and 1.0)
pub fn set_volume(&mut self, volume: f64) -> Result<()> {
if !self.has_audio {
debug!("Ignoring volume change request - video has no audio");
return Ok(());
}
let clamped_volume = volume.max(0.0).min(1.0);
*self.volume.lock().unwrap() = clamped_volume;
if let Some(volume_elem) = self.pipeline.by_name("volume") {
volume_elem.set_property("volume", clamped_volume);
debug!("Set volume to {clamped_volume:.2}");
Ok(())
} else {
warn!("Volume element not found in pipeline");
Ok(()) // Don't fail if element not found - video might still work
}
}
/// Mutes or unmutes the audio
pub fn set_mute(&mut self, muted: bool) -> Result<()> {
if !self.has_audio {
debug!("Ignoring mute request - video has no audio");
return Ok(());
}
*self.is_muted.lock().unwrap() = muted;
if let Some(volume_elem) = self.pipeline.by_name("volume") {
volume_elem.set_property("mute", muted);
debug!("Set mute to {muted}");
Ok(())
} else {
warn!("Volume element not found in pipeline");
Ok(()) // Don't fail if element not found - video might still work
}
}
pub fn toggle_mute(&mut self) -> Result<()> {
let current_mute = *self.is_muted.lock().unwrap();
self.set_mute(!current_mute)
}
/// Returns true if the video has an audio track
pub fn has_audio(&self) -> bool {
self.has_audio
}
/// Gets the current volume (0.0 to 1.0)
pub fn volume(&self) -> f64 {
*self.volume.lock().unwrap()
}
/// Returns true if audio is currently muted
pub fn is_muted(&self) -> bool {
*self.is_muted.lock().unwrap()
}
pub fn position(&self) -> gst::ClockTime {
*self.position.lock().unwrap()
}
pub fn duration(&self) -> Option<gst::ClockTime> {
self.pipeline.query_duration::<gst::ClockTime>().or(self.duration)
}
pub fn dimensions(&self) -> (u32, u32) {
self.dimensions
}
pub fn framerate(&self) -> Option<(i32, i32)> {
self.framerate.map(|f| (f.numer(), f.denom()))
}
pub fn is_playing(&self) -> bool {
*self.is_playing.lock().unwrap()
}
pub fn is_looping(&self) -> bool {
*self.loop_playback.lock().unwrap()
}
pub fn path(&self) -> &str {
&self.video_path
}
/// Configure spectrum analysis parameters
pub fn configure_spectrum(&mut self, bands: usize, threshold: i32) -> Result<()> {
if !self.has_audio {
debug!("Ignoring spectrum configuration - video has no audio");
return Ok(());
}
self.spectrum_bands = bands;
self.spectrum_threshold = threshold;
if let Some(spectrum_elem) = self.pipeline.by_name("spectrum") {
spectrum_elem.set_property("bands", bands as u32);
spectrum_elem.set_property("threshold", threshold);
info!("Configured spectrum: {bands} bands, {threshold}dB threshold");
Ok(())
} else {
warn!("Spectrum element not found in pipeline");
Ok(()) // Don't fail if element not found
}
}
/// Enable or disable spectrum analysis
pub fn enable_spectrum(&mut self, enabled: bool) -> Result<()> {
if !self.has_audio {
debug!("Ignoring spectrum enable request - video has no audio");
return Ok(());
}
self.spectrum_enabled = enabled;
if let Some(spectrum_elem) = self.pipeline.by_name("spectrum") {
spectrum_elem.set_property("post-messages", enabled);
info!(
"Spectrum analysis {} ",
if enabled { "enabled" } else { "disabled" }
);
Ok(())
} else {
warn!("Spectrum element not found in pipeline");
Ok(()) // Don't fail if element not found
}
}
/// Get current spectrum data
pub fn spectrum_data(&self) -> SpectrumData {
match self.spectrum_data.lock() {
Ok(data) => data.clone(),
Err(_) => SpectrumData::default(),
}
}
/// Get current audio level data (RMS, peak)
pub fn audio_level(&self) -> AudioLevel {
match self.audio_level.lock() {
Ok(data) => data.clone(),
Err(_) => AudioLevel::default(),
}
}
pub fn get_bpm(&self) -> f32 {
if !self.has_audio {
return 0.0;
}
match self.bpm_value.lock() {
Ok(bpm) => *bpm,
Err(_) => 0.0,
}
}
/// Set interval between spectrum updates in milliseconds
pub fn set_spectrum_interval(&mut self, interval_ms: u64) -> Result<()> {
if !self.has_audio {
debug!("Ignoring spectrum interval request - video has no audio");
return Ok(());
}
if let Some(spectrum_elem) = self.pipeline.by_name("spectrum") {
// Convert milliseconds to nanoseconds for GStreamer
let interval_ns = interval_ms * 1_000_000;
spectrum_elem.set_property("interval", interval_ns);
info!("Set spectrum interval to {interval_ms}ms");
Ok(())
} else {
warn!("Spectrum element not found in pipeline");
Ok(()) // Don't fail if element not found
}
}
}
impl Drop for VideoTextureManager {
fn drop(&mut self) {
info!("Shutting down video pipeline");
let _ = self.pipeline.set_state(gst::State::Null);
}
}