-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpipeline.rs
More file actions
2908 lines (2618 loc) · 116 KB
/
Copy pathpipeline.rs
File metadata and controls
2908 lines (2618 loc) · 116 KB
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
//! GStreamer pipeline management.
use crate::blocks::BlockRegistry;
use crate::events::EventBroadcaster;
use crate::gst::thread_priority::{self, ThreadPriorityState};
use gstreamer as gst;
use gstreamer::glib;
use gstreamer::prelude::*;
use gstreamer_net as gst_net;
use std::collections::HashMap;
use strom_types::flow::ThreadPriorityStatus;
use strom_types::{Element, Flow, FlowId, Link, PipelineState, PropertyValue, StromEvent};
use thiserror::Error;
use tracing::{debug, error, info, trace, warn};
/// Result of processing links with automatic tee insertion.
struct ProcessedLinks {
/// Final list of links (including links to/from tees)
links: Vec<Link>,
/// Map of tee element IDs to their source spec (element:pad they're connected to)
tees: HashMap<String, String>,
}
#[derive(Error, Debug)]
pub enum PipelineError {
#[error("GStreamer error: {0}")]
GStreamer(#[from] gst::glib::Error),
#[error("GStreamer boolean error: {0}")]
BoolError(#[from] gst::glib::BoolError),
#[error("Element not found: {0}")]
ElementNotFound(String),
#[error("Failed to create element: {0}")]
ElementCreation(String),
#[error("Failed to link elements: {0} -> {1}")]
LinkError(String, String),
#[error("Invalid property value for {element}.{property}: {reason}")]
InvalidProperty {
element: String,
property: String,
reason: String,
},
#[error("Pipeline state change failed: {0}")]
StateChange(String),
#[error("Invalid flow: {0}")]
InvalidFlow(String),
#[error("Property {property} on element {element} cannot be changed in {state:?} state")]
PropertyNotMutable {
element: String,
property: String,
state: PipelineState,
},
#[error("Pad not found: {element}:{pad}")]
PadNotFound { element: String, pad: String },
}
/// Manages a single GStreamer pipeline for a flow.
pub struct PipelineManager {
flow_id: FlowId,
flow_name: String,
pipeline: gst::Pipeline,
elements: HashMap<String, gst::Element>,
bus_watch: Option<gst::bus::BusWatchGuard>,
events: EventBroadcaster,
/// Pending links that couldn't be made because source pads don't exist yet (dynamic pads)
pending_links: Vec<Link>,
/// Flow properties (clock configuration, etc.)
properties: strom_types::flow::FlowProperties,
/// Pad properties to apply after pads are created (element_id -> (pad_name -> properties))
pad_properties: HashMap<String, HashMap<String, HashMap<String, PropertyValue>>>,
/// Block-specific bus watches (allows blocks to register their own bus message handlers)
block_bus_watches: Vec<gst::bus::BusWatchGuard>,
/// Bus watch setup functions from blocks (called when pipeline starts)
block_bus_watch_setups: Vec<crate::blocks::BusWatchSetupFn>,
/// Thread priority state tracker (tracks whether priority was successfully set)
thread_priority_state: Option<ThreadPriorityState>,
}
impl PipelineManager {
/// Create a new pipeline from a flow definition.
pub fn new(
flow: &Flow,
events: EventBroadcaster,
_block_registry: &BlockRegistry,
) -> Result<Self, PipelineError> {
info!("Creating pipeline for flow: {} ({})", flow.name, flow.id);
info!(
"Flow has {} elements, {} blocks, {} links",
flow.elements.len(),
flow.blocks.len(),
flow.links.len()
);
let pipeline = gst::Pipeline::builder()
.name(format!("flow-{}", flow.id))
.build();
info!("Created GStreamer pipeline object");
let mut manager = Self {
flow_id: flow.id,
flow_name: flow.name.clone(),
pipeline,
elements: HashMap::new(),
bus_watch: None,
events,
pending_links: Vec::new(),
properties: flow.properties.clone(),
pad_properties: HashMap::new(),
block_bus_watches: Vec::new(),
block_bus_watch_setups: Vec::new(),
thread_priority_state: None,
};
// Expand blocks into GStreamer elements
info!("Starting block expansion (block_in_place)...");
let expanded = tokio::task::block_in_place(|| {
info!("Inside block_in_place, calling block_on...");
tokio::runtime::Handle::current().block_on(async {
info!("Inside block_on, calling expand_blocks...");
let result = super::block_expansion::expand_blocks(&flow.blocks, &flow.links).await;
info!("expand_blocks completed");
result
})
})?;
info!("Block expansion completed");
// Add regular elements from flow
info!(
"Adding {} regular elements from flow...",
flow.elements.len()
);
for (idx, element) in flow.elements.iter().enumerate() {
info!(
"Adding element {}/{}: {} (type: {})",
idx + 1,
flow.elements.len(),
element.id,
element.element_type
);
manager.add_element(element)?;
info!("Successfully added element: {}", element.id);
}
info!("All regular elements added");
// Add GStreamer elements from expanded blocks
let block_element_count = expanded.gst_elements.len();
info!("Adding {} block elements...", block_element_count);
let mut idx = 0;
for (element_id, gst_element) in expanded.gst_elements {
idx += 1;
info!(
"Adding block element {}/{}: {}",
idx, block_element_count, element_id
);
manager.pipeline.add(&gst_element).map_err(|e| {
PipelineError::ElementCreation(format!(
"Failed to add block element {} to pipeline: {}",
element_id, e
))
})?;
manager.elements.insert(element_id.clone(), gst_element);
info!("Successfully added block element: {}", element_id);
}
info!("All block elements added");
// Store bus watch setup functions from blocks
info!(
"Storing {} bus watch setup function(s) from blocks",
expanded.bus_watch_setups.len()
);
manager.block_bus_watch_setups = expanded.bus_watch_setups;
// Analyze links and auto-insert tee elements where needed
info!("Analyzing links and inserting tee elements if needed...");
let processed_links = Self::insert_tees_if_needed(&expanded.links);
info!(
"Link analysis complete: {} links, {} tees",
processed_links.links.len(),
processed_links.tees.len()
);
// Create tee elements
info!("Creating {} tee elements...", processed_links.tees.len());
for (idx, tee_id) in processed_links.tees.keys().enumerate() {
info!(
"Creating tee {}/{}: {}",
idx + 1,
processed_links.tees.len(),
tee_id
);
manager.add_tee_element(tee_id)?;
info!("Successfully created tee: {}", tee_id);
}
info!("All tee elements created");
// Link elements according to processed links
info!("Linking {} elements...", processed_links.links.len());
for (idx, link) in processed_links.links.iter().enumerate() {
info!(
"Linking {}/{}: {} -> {}",
idx + 1,
processed_links.links.len(),
link.from,
link.to
);
if let Err(e) = manager.try_link_elements(link) {
info!(
"Could not link immediately: {} - will try when pad becomes available ({})",
e, link.from
);
// Store as pending link
manager.pending_links.push(link.clone());
} else {
info!("Successfully linked: {} -> {}", link.from, link.to);
}
}
info!(
"Linking phase complete ({} pending links)",
manager.pending_links.len()
);
// Set up dynamic pad handlers for all elements that might have dynamic pads
info!("Setting up dynamic pad handlers...");
manager.setup_dynamic_pad_handlers();
info!("Dynamic pad handlers set up");
// Apply pad properties now that pads have been created (during linking)
// Note: Request pads (like audiomixer sink_%u) are created during linking
info!("Applying pad properties...");
manager.apply_pad_properties();
info!("Pad properties applied");
// Note: Bus watch is set up when pipeline starts, not here
info!("Pipeline created successfully for flow: {}", flow.name);
Ok(manager)
}
/// Set up the bus watch to monitor pipeline messages.
fn setup_bus_watch(&mut self) {
// Clean up any existing watches first
if self.bus_watch.is_some() {
debug!("Removing existing bus watch for flow: {}", self.flow_name);
self.bus_watch = None;
}
self.block_bus_watches.clear();
let Some(bus) = self.pipeline.bus() else {
error!(
"Pipeline '{}' does not have a bus - cannot set up message watch",
self.flow_name
);
return;
};
// Set up block-specific bus watches
info!(
"Setting up {} block bus watch(es) for flow: {}",
self.block_bus_watch_setups.len(),
self.flow_name
);
let flow_id = self.flow_id;
let events_for_blocks = self.events.clone();
// Take the setup functions (they're FnOnce, so we consume them)
let setups = std::mem::take(&mut self.block_bus_watch_setups);
for setup_fn in setups {
match setup_fn(&bus, flow_id, events_for_blocks.clone()) {
Ok(guard) => {
debug!("Successfully set up block bus watch");
self.block_bus_watches.push(guard);
}
Err(e) => {
error!("Failed to set up block bus watch: {}", e);
}
}
}
// Set up main pipeline bus watch for standard messages
let flow_name = self.flow_name.clone();
let events = self.events.clone();
let watch = match bus
.add_watch(move |_bus, msg| {
use gst::MessageView;
// Log ALL bus messages to debug
debug!("Bus message type: {:?}", msg.type_());
match msg.view() {
MessageView::Error(err) => {
let error_msg = err.error().to_string();
let debug_info = err.debug();
let source = err.src().map(|s| s.name().to_string());
error!(
"Pipeline error in flow '{}': {} (debug: {:?}, source: {:?})",
flow_name, error_msg, debug_info, source
);
events.broadcast(StromEvent::PipelineError {
flow_id,
error: error_msg,
source,
});
}
MessageView::Warning(warn) => {
let warning_msg = warn.error().to_string();
let debug_info = warn.debug();
let source = warn.src().map(|s| s.name().to_string());
warn!(
"Pipeline warning in flow '{}': {} (debug: {:?}, source: {:?})",
flow_name, warning_msg, debug_info, source
);
events.broadcast(StromEvent::PipelineWarning {
flow_id,
warning: warning_msg,
source,
});
}
MessageView::Info(inf) => {
let info_msg = inf.error().to_string();
let source = inf.src().map(|s| s.name().to_string());
info!(
"Pipeline info in flow '{}': {} (source: {:?})",
flow_name, info_msg, source
);
events.broadcast(StromEvent::PipelineInfo {
flow_id,
message: info_msg,
source,
});
}
MessageView::Eos(_) => {
info!("Pipeline '{}' reached end of stream", flow_name);
events.broadcast(StromEvent::PipelineEos { flow_id });
}
MessageView::StateChanged(state_changed) => {
// Log state changes from all elements to debug pausing issues
if let Some(source) = msg.src() {
let source_name = source.name();
let old_state = state_changed.old();
let new_state = state_changed.current();
let pending_state = state_changed.pending();
if source.type_() == gst::Pipeline::static_type() {
info!(
"Pipeline '{}' state changed: {:?} -> {:?} (pending: {:?})",
flow_name,
old_state,
new_state,
pending_state
);
} else {
// Log all element state changes for debugging
info!(
"Element '{}' in pipeline '{}' state changed: {:?} -> {:?} (pending: {:?})",
source_name,
flow_name,
old_state,
new_state,
pending_state
);
}
}
}
_ => {
// Ignore other message types
}
}
glib::ControlFlow::Continue
}) {
Ok(watch) => watch,
Err(e) => {
error!("Failed to add bus watch for flow '{}': {}", self.flow_name, e);
return;
}
};
self.bus_watch = Some(watch);
debug!("Bus watch set up for flow: {}", self.flow_name);
}
/// Remove the bus watches (both main and block-specific).
fn remove_bus_watch(&mut self) {
if self.bus_watch.is_some() {
debug!("Removing main bus watch for flow: {}", self.flow_name);
self.bus_watch = None;
}
if !self.block_bus_watches.is_empty() {
debug!(
"Removing {} block bus watch(es) for flow: {}",
self.block_bus_watches.len(),
self.flow_name
);
self.block_bus_watches.clear();
}
}
/// Add an element to the pipeline.
fn add_element(&mut self, element_def: &Element) -> Result<(), PipelineError> {
info!(
"add_element: Creating element {} (type: {})",
element_def.id, element_def.element_type
);
// Create the element
info!(
"add_element: Calling ElementFactory::make for {}",
element_def.element_type
);
let element = gst::ElementFactory::make(&element_def.element_type)
.name(&element_def.id)
.build()
.map_err(|e| {
error!(
"add_element: Failed to create element {}: {}",
element_def.id, e
);
PipelineError::ElementCreation(format!(
"{}: {} - {}",
element_def.id, element_def.element_type, e
))
})?;
info!(
"add_element: Element {} created successfully",
element_def.id
);
// Set properties
info!(
"add_element: Setting {} properties for element {}",
element_def.properties.len(),
element_def.id
);
for (prop_name, prop_value) in &element_def.properties {
info!(
"add_element: Setting property {}.{} = {:?}",
element_def.id, prop_name, prop_value
);
self.set_property(&element, &element_def.id, prop_name, prop_value)?;
info!(
"add_element: Property {}.{} set successfully",
element_def.id, prop_name
);
}
info!(
"add_element: All properties set for element {}",
element_def.id
);
// Store pad properties for later application (after pads are created)
if !element_def.pad_properties.is_empty() {
info!(
"add_element: Storing {} pad properties for element {}",
element_def.pad_properties.len(),
element_def.id
);
self.pad_properties
.insert(element_def.id.clone(), element_def.pad_properties.clone());
}
// Add to pipeline
info!(
"add_element: Adding element {} to pipeline (this may block)...",
element_def.id
);
self.pipeline.add(&element).map_err(|e| {
error!(
"add_element: Failed to add {} to pipeline: {}",
element_def.id, e
);
PipelineError::ElementCreation(format!(
"Failed to add {} to pipeline: {}",
element_def.id, e
))
})?;
info!(
"add_element: Element {} added to pipeline successfully",
element_def.id
);
info!(
"add_element: Inserting {} into elements map",
element_def.id
);
self.elements.insert(element_def.id.clone(), element);
info!(
"add_element: Successfully completed adding element {}",
element_def.id
);
Ok(())
}
/// Set a property on an element.
fn set_property(
&self,
element: &gst::Element,
element_id: &str,
prop_name: &str,
prop_value: &PropertyValue,
) -> Result<(), PipelineError> {
debug!(
"Setting property: {}.{} = {:?}",
element_id, prop_name, prop_value
);
// Set property based on type
match prop_value {
PropertyValue::String(v) => {
element.set_property_from_str(prop_name, v);
}
PropertyValue::Int(v) => {
// Check property type to determine if we need i32 or i64
if let Some(pspec) = element.find_property(prop_name) {
let type_name = pspec.value_type().name();
if type_name == "gint" || type_name == "glong" {
// Property expects i32
if let Ok(v32) = i32::try_from(*v) {
element.set_property(prop_name, v32);
} else {
return Err(PipelineError::InvalidProperty {
element: element_id.to_string(),
property: prop_name.to_string(),
reason: format!("Value {} doesn't fit in i32", v),
});
}
} else if type_name == "gint64" {
// Property expects i64
element.set_property(prop_name, *v);
} else {
// Try i64, might work
element.set_property(prop_name, *v);
}
} else {
// Property not found, try anyway
element.set_property(prop_name, *v);
}
}
PropertyValue::UInt(v) => {
// Check property type to determine if we need u32 or u64
if let Some(pspec) = element.find_property(prop_name) {
let type_name = pspec.value_type().name();
if type_name == "guint" || type_name == "gulong" {
// Property expects u32
if let Ok(v32) = u32::try_from(*v) {
element.set_property(prop_name, v32);
} else {
return Err(PipelineError::InvalidProperty {
element: element_id.to_string(),
property: prop_name.to_string(),
reason: format!("Value {} doesn't fit in u32", v),
});
}
} else if type_name == "guint64" {
// Property expects u64
element.set_property(prop_name, *v);
} else {
// Try u64, might work
element.set_property(prop_name, *v);
}
} else {
// Property not found, try anyway
element.set_property(prop_name, *v);
}
}
PropertyValue::Float(v) => {
element.set_property(prop_name, *v);
}
PropertyValue::Bool(v) => {
element.set_property(prop_name, *v);
}
}
Ok(())
}
/// Try to link two elements according to a link definition.
/// Returns Ok if successful, Err if pads don't exist yet (dynamic pads).
fn try_link_elements(&self, link: &Link) -> Result<(), PipelineError> {
debug!("Trying to link: {} -> {}", link.from, link.to);
// Parse element:pad format (e.g., "src" or "src:pad_name")
let (from_element, from_pad) = Self::parse_element_pad(&link.from);
let (to_element, to_pad) = Self::parse_element_pad(&link.to);
let src = self
.elements
.get(from_element)
.ok_or_else(|| PipelineError::ElementNotFound(from_element.to_string()))?;
let sink = self
.elements
.get(to_element)
.ok_or_else(|| PipelineError::ElementNotFound(to_element.to_string()))?;
// Link with or without specific pads
if let (Some(src_pad_name), Some(sink_pad_name)) = (from_pad, to_pad) {
// Try to get the pad - try static first, then request if not found
let src_pad_obj = if let Some(pad) = src.static_pad(src_pad_name) {
pad
} else {
// Pad not static - try to request it
// First try request_pad_simple with the exact name
if let Some(pad) = src.request_pad_simple(src_pad_name) {
pad
} else {
// If that didn't work, try finding a compatible pad template
// This handles cases like "src_0" needing the "src_%u" template (e.g., tee)
// IMPORTANT: We get pad templates directly from the element, not from the factory.
// Accessing static_pad_templates from the factory can corrupt GStreamer state
// for aggregator elements like mpegtsmux (see discovery.rs:533-538).
let element_pad_templates = src.pad_template_list();
let pad_template = element_pad_templates
.iter()
.filter(|tmpl| {
tmpl.presence() == gst::PadPresence::Request
&& tmpl.direction() == gst::PadDirection::Src
})
.find(|tmpl| {
let name_template = tmpl.name_template();
// Check if this template could produce the requested pad name
if name_template.contains("%u") || name_template.contains("%d") {
let prefix = name_template.split('%').next().unwrap_or("");
src_pad_name.starts_with(prefix)
} else {
name_template == src_pad_name
}
});
if let Some(pad_tmpl) = pad_template {
let tmpl_name = pad_tmpl.name_template();
debug!(
"Found matching pad template '{}' for pad name '{}'",
tmpl_name, src_pad_name
);
// Request a new pad from the template - let GStreamer auto-name it
if let Some(pad) = src.request_pad(pad_tmpl, None, None) {
debug!(
"Successfully requested pad '{}' for requested name '{}'",
pad.name(),
src_pad_name
);
pad
} else {
// Couldn't get pad from template
return Err(PipelineError::LinkError(
link.from.clone(),
format!(
"Source pad {} not available (tried template '{}')",
src_pad_name, tmpl_name
),
));
}
} else {
// No compatible template found - might be a dynamic pad
return Err(PipelineError::LinkError(
link.from.clone(),
format!(
"Source pad {} not available yet (dynamic pad)",
src_pad_name
),
));
}
}
};
// Try to get sink pad - try static first, then request if not found
info!(
"Trying to get sink pad '{}' on element '{}'",
sink_pad_name, to_element
);
// Special handling for mpegtsmux - use direct element-to-element linking to avoid request_pad() deadlock
let element_type_name = sink
.factory()
.map(|f| f.name().to_string())
.unwrap_or_default();
if element_type_name == "mpegtsmux" {
info!("Detected mpegtsmux - using element-level linking to avoid request_pad deadlock");
// For mpegtsmux, link directly at element level using the source element
// GStreamer will internally handle pad requesting without us having to call request_pad()
// We need to link from source element, not from the source pad object
if let Err(e) = src.link(sink) {
return Err(PipelineError::LinkError(
link.from.clone(),
format!("Failed to auto-link to mpegtsmux: {}", e),
));
}
info!(
"Successfully auto-linked to mpegtsmux: {} -> {}",
link.from, link.to
);
return Ok(());
}
let sink_pad_obj = if let Some(pad) = sink.static_pad(sink_pad_name) {
info!("Found static sink pad: {}", sink_pad_name);
pad
} else {
info!(
"Sink pad '{}' not static, trying to request it...",
sink_pad_name
);
// Pad not static - try to request it
// First try request_pad_simple with the exact name
info!(
"Calling request_pad_simple('{}') on {} (this may block)...",
sink_pad_name, to_element
);
if let Some(pad) = sink.request_pad_simple(sink_pad_name) {
info!("Successfully requested sink pad: {}", sink_pad_name);
pad
} else {
info!("request_pad_simple returned None, trying pad template matching...");
// If that didn't work, try finding a compatible pad template
// This handles cases like "sink_0" needing the "sink_%u" template
// IMPORTANT: We get pad templates directly from the element, not from the factory.
// Accessing static_pad_templates from the factory can corrupt GStreamer state
// for aggregator elements like mpegtsmux (see discovery.rs:533-538).
info!("Trying to find matching pad template on element...");
// Get pad template list directly from the element (not factory)
let element_pad_templates = sink.pad_template_list();
debug!(
"Available pad templates from element: {:?}",
element_pad_templates
.iter()
.map(|t| format!(
"{} (direction: {:?}, presence: {:?})",
t.name_template(),
t.direction(),
t.presence()
))
.collect::<Vec<_>>()
);
let pad_template = element_pad_templates
.iter()
.filter(|tmpl| {
tmpl.presence() == gst::PadPresence::Request
&& tmpl.direction() == gst::PadDirection::Sink
})
.find(|tmpl| {
let name_template = tmpl.name_template();
// Check if this template could produce the requested pad name
// e.g., "sink_%u" can produce "sink_0", "sink_1", etc.
if name_template.contains("%u") || name_template.contains("%d") {
let prefix = name_template.split('%').next().unwrap_or("");
let matches = sink_pad_name.starts_with(prefix);
debug!(
"Checking template '{}': prefix='{}', pad_name='{}', matches={}",
name_template, prefix, sink_pad_name, matches
);
matches
} else {
name_template == sink_pad_name
}
});
if let Some(pad_tmpl) = pad_template {
let tmpl_name = pad_tmpl.name_template();
info!(
"Found matching pad template '{}' for pad name '{}'",
tmpl_name, sink_pad_name
);
// Request a new pad from the template - let GStreamer auto-name it
info!("Calling request_pad on element with template (this may block)...");
if let Some(pad) = sink.request_pad(pad_tmpl, None, None) {
info!(
"Successfully requested pad '{}' for requested name '{}'",
pad.name(),
sink_pad_name
);
pad
} else {
// Couldn't get pad from template
return Err(PipelineError::LinkError(
link.to.clone(),
format!(
"Sink pad {} not available (tried template '{}')",
sink_pad_name, tmpl_name
),
));
}
} else {
// No compatible template found - might be a dynamic pad
return Err(PipelineError::LinkError(
link.to.clone(),
format!("Sink pad {} not available yet (dynamic pad)", sink_pad_name),
));
}
}
};
src_pad_obj.link(&sink_pad_obj).map_err(|e| {
PipelineError::LinkError(link.from.clone(), format!("{} - {}", link.to, e))
})?;
debug!("Successfully linked: {} -> {}", link.from, link.to);
} else {
// Simple link without pad names
src.link(sink).map_err(|e| {
PipelineError::LinkError(link.from.clone(), format!("{} - {}", link.to, e))
})?;
debug!("Successfully linked: {} -> {}", link.from, link.to);
}
Ok(())
}
/// Parse element:pad format into (element_id, optional pad_name).
/// Handles namespaced block elements like "block_0:rtpL24pay:sink".
/// Splits from the right to get the last colon-separated part as the pad name.
fn parse_element_pad(spec: &str) -> (&str, Option<&str>) {
if let Some((element, pad)) = spec.rsplit_once(':') {
(element, Some(pad))
} else {
(spec, None)
}
}
/// Set up pad-added signal handlers for elements with dynamic pads.
fn setup_dynamic_pad_handlers(&mut self) {
if self.pending_links.is_empty() {
return;
}
info!(
"Setting up dynamic pad handlers for {} pending link(s)",
self.pending_links.len()
);
// For each element that might have dynamic pads, connect to pad-added signal
let elements_map = self.elements.clone();
let pending_links = self.pending_links.clone();
for (element_id, element) in &self.elements {
let element_id = element_id.clone();
let elements_map = elements_map.clone();
let pending_links = pending_links.clone();
// Connect to pad-added signal
element.connect_pad_added(move |_elem, new_pad| {
let new_pad_name = new_pad.name();
debug!("Pad added on element {}: {}", element_id, new_pad_name);
// Check if any pending links match this pad
for link in &pending_links {
let (from_elem, from_pad) = Self::parse_element_pad(&link.from);
let (to_elem, to_pad) = Self::parse_element_pad(&link.to);
// Check if this new pad matches a pending source pad
if from_elem == element_id {
if let Some(expected_pad_name) = from_pad {
if new_pad_name == expected_pad_name {
// This is the source pad we're waiting for
if let (Some(_src_elem), Some(sink_elem)) =
(elements_map.get(from_elem), elements_map.get(to_elem))
{
if let Some(sink_pad_name) = to_pad {
// Get the sink pad
let sink_pad = if let Some(pad) =
sink_elem.static_pad(sink_pad_name)
{
pad
} else if let Some(pad) =
sink_elem.request_pad_simple(sink_pad_name)
{
pad
} else {
warn!(
"Sink pad {} not found on {}",
sink_pad_name, to_elem
);
continue;
};
// Try to link
match new_pad.link(&sink_pad) {
Ok(_) => {
info!(
"Successfully linked dynamic pad: {} -> {}",
link.from, link.to
);
}
Err(e) => {
error!(
"Failed to link dynamic pad {} -> {}: {}",
link.from, link.to, e
);
}
}
}
}
}
}
}
}
});
}
}
/// Apply stored pad properties to pads after they've been created.
/// This must be called after all linking is complete, since request pads
/// (like audiomixer sink_%u) don't exist until they're requested during linking.
fn apply_pad_properties(&self) {
if self.pad_properties.is_empty() {
return;
}
info!(
"Applying pad properties for {} element(s)",
self.pad_properties.len()
);
for (element_id, pad_props) in &self.pad_properties {
let Some(element) = self.elements.get(element_id) else {
warn!(
"Element {} not found when trying to apply pad properties",
element_id
);
continue;
};
for (pad_name, properties) in pad_props {
// Try to get the pad - try static first, then request
let pad = if let Some(p) = element.static_pad(pad_name) {
p
} else if let Some(p) = element.request_pad_simple(pad_name) {
p
} else {
warn!(
"Pad {}:{} not found when trying to apply pad properties",
element_id, pad_name
);
continue;
};
debug!(
"Applying {} properties to pad {}:{}",
properties.len(),
element_id,
pad_name
);
// Apply each property
for (prop_name, prop_value) in properties {
if let Err(e) =
self.set_pad_property(&pad, element_id, pad_name, prop_name, prop_value)
{
error!(
"Failed to set pad property {}:{}:{}: {}",
element_id, pad_name, prop_name, e
);
} else {
info!(
"Set pad property {}:{}:{} = {:?}",
element_id, pad_name, prop_name, prop_value
);
}
}
}
}
}
/// Analyze links and insert tee elements where multiple links share the same source.
fn insert_tees_if_needed(original_links: &[Link]) -> ProcessedLinks {
use std::collections::HashMap;
// Count how many times each source spec appears
let mut source_counts: HashMap<String, usize> = HashMap::new();
for link in original_links {
*source_counts.entry(link.from.clone()).or_insert(0) += 1;
}
// Find sources that need a tee (appear more than once)
let sources_needing_tee: Vec<String> = source_counts
.iter()
.filter(|(_, &count)| count > 1)
.map(|(src, _)| src.clone())
.collect();
if sources_needing_tee.is_empty() {
// No tees needed, return original links
info!("No tee elements needed");