Skip to main content

ez_ffmpeg/core/context/ffmpeg_context/
mod.rs

1use crate::core::context::demuxer::{CopyMuxHandle, Demuxer};
2use crate::core::context::ffmpeg_context_builder::FfmpegContextBuilder;
3use crate::core::context::filter_complex::FilterComplex;
4use crate::core::context::filter_graph::FilterGraph;
5use crate::core::context::input::Input;
6use crate::core::context::input_filter::{InputFilter, IFILTER_FLAG_AUTOROTATE};
7use crate::core::context::muxer::Muxer;
8use crate::core::context::output::{Output, StreamMap};
9use crate::core::context::output_filter::{
10    OutputFilter, OFILTER_FLAG_AUDIO_24BIT, OFILTER_FLAG_AUTOSCALE, OFILTER_FLAG_DISABLE_CONVERT,
11};
12use crate::core::context::{frame_alloc, CodecContext};
13use crate::core::metadata::StreamSpecifier;
14use crate::core::scheduler::ffmpeg_scheduler;
15use crate::core::scheduler::ffmpeg_scheduler::{FfmpegScheduler, Initialization};
16#[cfg(not(docsrs))]
17use crate::core::scheduler::filter_task::graph_opts_apply;
18use crate::core::scheduler::input_controller::SchNode;
19use crate::error::Error::{
20    FileSameAsInput, FilterZeroInputs, FilterZeroOutputs, FrameFilterStreamTypeNoMatched,
21    FrameFilterTypeNoMatched, ParseInteger,
22};
23use crate::error::FilterGraphParseError::{
24    InvalidFileIndexInFg, InvalidFilterSpecifier, OutputUnconnected,
25};
26use crate::error::{
27    AllocOutputContextError, FilterGraphOperationError, FilterGraphParseError, FindStreamError,
28    OpenInputError, OpenOutputError,
29};
30use crate::error::{Error, Result};
31use crate::filter::frame_pipeline::FramePipeline;
32use crate::hwaccel::{hw_device_for_filter, init_filter_hw_device};
33use crate::util::ffmpeg_utils::{hashmap_to_avdictionary, DictGuard};
34#[cfg(not(docsrs))]
35use ffmpeg_sys_next::AVChannelOrder::AV_CHANNEL_ORDER_UNSPEC;
36#[cfg(not(docsrs))]
37use ffmpeg_sys_next::AVCodecConfig::*;
38use ffmpeg_sys_next::AVCodecID::{AV_CODEC_ID_AC3, AV_CODEC_ID_MP3, AV_CODEC_ID_NONE};
39use ffmpeg_sys_next::AVColorRange::AVCOL_RANGE_UNSPECIFIED;
40use ffmpeg_sys_next::AVColorSpace::AVCOL_SPC_UNSPECIFIED;
41use ffmpeg_sys_next::AVMediaType::{
42    AVMEDIA_TYPE_ATTACHMENT, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA, AVMEDIA_TYPE_SUBTITLE,
43    AVMEDIA_TYPE_VIDEO,
44};
45use ffmpeg_sys_next::AVPixelFormat::AV_PIX_FMT_NONE;
46use ffmpeg_sys_next::AVSampleFormat::AV_SAMPLE_FMT_NONE;
47use ffmpeg_sys_next::{
48    av_add_q, av_channel_layout_default, av_codec_get_id, av_codec_get_tag2, av_freep,
49    av_get_exact_bits_per_sample, av_get_pix_fmt, av_guess_codec, av_guess_format,
50    av_guess_frame_rate, av_inv_q, av_malloc, av_rescale_q, av_seek_frame, avcodec_alloc_context3,
51    avcodec_descriptor_get, avcodec_descriptor_get_by_name, avcodec_find_encoder,
52    avcodec_find_encoder_by_name, avcodec_get_name, avcodec_parameters_from_context,
53    avcodec_parameters_to_context, avformat_alloc_context, avformat_alloc_output_context2,
54    avformat_close_input, avformat_find_stream_info, avformat_flush, avformat_free_context,
55    avformat_open_input, avio_alloc_context, AVCodec, AVCodecID, AVColorRange, AVColorSpace,
56    AVFormatContext, AVMediaType, AVOutputFormat, AVPixelFormat, AVRational, AVSampleFormat,
57    AVStream, AVERROR_ENCODER_NOT_FOUND, AVFMT_FLAG_CUSTOM_IO, AVFMT_GLOBALHEADER,
58    AVFMT_NOBINSEARCH, AVFMT_NOFILE, AVFMT_NOGENSEARCH, AVFMT_NOSTREAMS, AVSEEK_FLAG_BACKWARD,
59    AV_CODEC_PROP_BITMAP_SUB, AV_CODEC_PROP_TEXT_SUB, AV_TIME_BASE,
60};
61#[cfg(not(docsrs))]
62use ffmpeg_sys_next::{
63    av_buffer_ref, av_channel_layout_copy, av_packet_side_data_new, avcodec_get_supported_config,
64    avfilter_graph_segment_create_filters, avfilter_graph_segment_free,
65    avfilter_graph_segment_parse, AVChannelLayout, AVFILTER_FLAG_HWDEVICE,
66};
67#[cfg(not(docsrs))]
68use ffmpeg_sys_next::{
69    avformat_query_codec, AVSTREAM_EVENT_FLAG_NEW_PACKETS, AV_DISPOSITION_ATTACHED_PIC,
70    AV_DISPOSITION_DEFAULT,
71};
72use log::{debug, error, info, warn};
73use std::collections::HashMap;
74use std::ffi::{c_void, CStr, CString};
75use std::ptr::{null, null_mut};
76use std::sync::Arc;
77
78mod fg_bind;
79#[cfg(not(docsrs))]
80mod fg_probe;
81mod open_input;
82mod open_output;
83mod opt_util;
84mod writer_build;
85
86pub(crate) use writer_build::build_writer_context;
87
88/// Log target held stable across the module split so target-based log
89/// filtering and routing keep observing `ez_ffmpeg::core::context::ffmpeg_context`.
90const LOG_TARGET: &str = module_path!();
91
92use fg_bind::{fg_bind_inputs, init_filter_graphs};
93use open_input::open_input_files;
94use open_output::open_output_files;
95use opt_util::outputs_bind;
96
97pub(super) use open_input::InputOpaque;
98pub(super) use open_output::OutputOpaque;
99
100// Re-exported only so the `#[cfg(test)] mod tests` below can name these
101// relocated items via the crate-absolute `ffmpeg_context::…` path it already used.
102#[cfg(test)]
103use fg_bind::{bind_fg_inputs_by_fg, fg_complex_bind_input};
104#[cfg(test)]
105use open_input::{read_packet_wrapper, seek_input_packet_wrapper};
106#[cfg(test)]
107use open_output::write_packet_wrapper;
108
109pub struct FfmpegContext {
110    pub(crate) independent_readrate: bool,
111    pub(crate) demuxs: Vec<Demuxer>,
112    pub(crate) filter_graphs: Vec<FilterGraph>,
113    pub(crate) muxs: Vec<Muxer>,
114    /// Headless frame-push inputs ([`VideoWriter`](crate::VideoWriter)):
115    /// empty for every demuxer-driven job. `start()` drains this and spawns
116    /// one counted frame-source worker per entry, after every consumer.
117    pub(crate) frame_sources: Vec<crate::core::context::frame_source::FrameSource>,
118    // Created at build time so the AVIO interrupt callbacks installed on the
119    // input/output contexts observe the same atomic the scheduler drives.
120    pub(crate) scheduler_status: Arc<std::sync::atomic::AtomicUsize>,
121    pub(crate) interrupt_state: Arc<crate::core::context::InterruptState>,
122}
123
124// SAFETY: FfmpegContext can be sent to another thread because all its fields
125// are either Send or wrapped in thread-safe containers. The raw FFmpeg pointers
126// are only accessed from the thread that owns the FfmpegContext.
127// Note: FfmpegContext is NOT Sync because it contains non-Sync fields like
128// Box<dyn FrameFilter> which only implements Send.
129unsafe impl Send for FfmpegContext {}
130
131impl FfmpegContext {
132    /// Creates a new [`FfmpegContextBuilder`] which allows you to configure
133    /// and construct an [`FfmpegContext`] with custom inputs, outputs, filters,
134    /// and other parameters.
135    ///
136    /// # Examples
137    /// ```rust,ignore
138    /// let context = FfmpegContext::builder()
139    ///     .input("input.mp4")
140    ///     .output("output.mp4")
141    ///     .build()
142    ///     .unwrap();
143    /// ```
144    pub fn builder() -> FfmpegContextBuilder {
145        FfmpegContextBuilder::new()
146    }
147
148    /// Consumes this [`FfmpegContext`] and starts an FFmpeg job, returning
149    /// an [`FfmpegScheduler<ffmpeg_scheduler::Running>`] for further management.
150    ///
151    /// Internally, this method creates an [`FfmpegScheduler`] from the context
152    /// and immediately calls [`FfmpegScheduler::start()`].
153    ///
154    /// # Returns
155    /// - `Ok(FfmpegScheduler<Running>)` if the scheduling process started successfully.
156    /// - `Err(...)` if there was an error initializing or starting FFmpeg.
157    ///
158    /// # Example
159    /// ```rust,ignore
160    /// let context = FfmpegContext::builder()
161    ///     .input("input.mp4")
162    ///     .output("output.mp4")
163    ///     .build()
164    ///     .unwrap();
165    ///
166    /// // Start the FFmpeg job and get a scheduler to manage it
167    /// let scheduler = context.start().expect("Failed to start Ffmpeg job");
168    ///
169    /// // Optionally, wait for it to finish
170    /// let result = scheduler.wait();
171    /// assert!(result.is_ok());
172    /// ```
173    pub fn start(self) -> Result<FfmpegScheduler<ffmpeg_scheduler::Running>> {
174        let ffmpeg_scheduler = FfmpegScheduler::new(self);
175        ffmpeg_scheduler.start()
176    }
177
178    #[allow(dead_code)]
179    pub(crate) fn new(
180        inputs: Vec<Input>,
181        filter_complexs: Vec<FilterComplex>,
182        outputs: Vec<Output>,
183    ) -> Result<FfmpegContext> {
184        Self::new_with_options(false, inputs, filter_complexs, outputs, false, Vec::new())
185    }
186
187    pub(crate) fn new_with_options(
188        mut independent_readrate: bool,
189        mut inputs: Vec<Input>,
190        mut filter_complexs: Vec<FilterComplex>,
191        mut outputs: Vec<Output>,
192        copy_ts: bool,
193        deferred_filter_descs: Vec<
194            crate::core::context::ffmpeg_context_builder::DeferredFilterDesc,
195        >,
196    ) -> Result<FfmpegContext> {
197        check_duplicate_inputs_outputs(&inputs, &outputs)?;
198
199        crate::core::initialize_ffmpeg();
200
201        // The status atomic exists before any context is opened so every
202        // input/output AVFormatContext can carry an interrupt callback bound
203        // to it (fftools installs decode_interrupt_cb the same way).
204        let scheduler_status = Arc::new(std::sync::atomic::AtomicUsize::new(
205            crate::core::scheduler::ffmpeg_scheduler::STATUS_INIT,
206        ));
207        let interrupt_state = Arc::new(crate::core::context::InterruptState::new(
208            scheduler_status.clone(),
209        ));
210
211        let mut demuxs = open_input_files(&mut inputs, copy_ts, &interrupt_state)?;
212
213        if demuxs.len() <= 1 {
214            independent_readrate = false;
215        }
216
217        // Resolve deferred filter descriptions against the just-opened demuxers
218        // (stream selection, durations, codec parameters) and append them BEFORE
219        // the emptiness check below, so the resulting graph is initialized. These
220        // closures must not consume corrected timing state
221        // (start_time_effective / ts_offset) — that is populated later by
222        // correct_input_start_times.
223        for deferred in deferred_filter_descs {
224            filter_complexs.push(deferred(&demuxs)?);
225        }
226
227        let mut filter_graphs = if !filter_complexs.is_empty() {
228            let mut filter_graphs = init_filter_graphs(filter_complexs)?;
229            fg_bind_inputs(&mut filter_graphs, &mut demuxs)?;
230            filter_graphs
231        } else {
232            Vec::new()
233        };
234
235        let mut muxs = open_output_files(&mut outputs, copy_ts, &interrupt_state)?;
236
237        outputs_bind(&mut muxs, &mut filter_graphs, &mut demuxs)?;
238
239        // Propagate input recording_time to mux as a convenience feature.
240        // This allows users to set recording_time on Input and have it work
241        // correctly for stream-copy scenarios (where the mux-side check in
242        // streamcopy_rescale needs recording_time). Only propagate when all
243        // mapped streams come from the same input file to avoid incorrect
244        // truncation in multi-input scenarios.
245        for mux in muxs.iter_mut() {
246            if mux.recording_time_us.is_none() {
247                let mapping = mux.stream_input_mapping();
248                if !mapping.is_empty() {
249                    let first_input = mapping[0].1 .0;
250                    let all_same_input = mapping.iter().all(|(_, (idx, _))| *idx == first_input);
251                    if all_same_input {
252                        if let Some(demux) = demuxs.get(first_input) {
253                            if let Some(recording_time) = demux.recording_time_us {
254                                mux.recording_time_us = Some(recording_time);
255                            }
256                        }
257                    }
258                }
259            }
260        }
261
262        correct_input_start_times(&mut demuxs, copy_ts);
263
264        check_output_streams(&muxs)?;
265
266        check_fg_bindings(&filter_graphs)?;
267
268        check_frame_filter_pipeline(&muxs, &demuxs)?;
269
270        Ok(Self {
271            independent_readrate,
272            demuxs,
273            filter_graphs,
274            muxs,
275            frame_sources: Vec::new(),
276            scheduler_status,
277            interrupt_state,
278        })
279    }
280}
281
282const START_AT_ZERO: bool = false;
283
284fn correct_input_start_times(demuxs: &mut Vec<Demuxer>, copy_ts: bool) {
285    for (i, demux) in demuxs.iter_mut().enumerate() {
286        unsafe {
287            let is = demux.in_fmt_ctx_ptr();
288
289            demux.start_time_effective = (*is).start_time;
290            if (*is).start_time == ffmpeg_sys_next::AV_NOPTS_VALUE
291                || (*(*is).iformat).flags & ffmpeg_sys_next::AVFMT_TS_DISCONT == 0
292            {
293                continue;
294            }
295
296            let mut new_start_time = i64::MAX;
297            let stream_count = (*is).nb_streams;
298            for j in 0..stream_count {
299                let st = *(*is).streams.add(j as usize);
300                if (*st).discard == ffmpeg_sys_next::AVDiscard::AVDISCARD_ALL
301                    || (*st).start_time == ffmpeg_sys_next::AV_NOPTS_VALUE
302                {
303                    continue;
304                }
305                new_start_time = std::cmp::min(
306                    new_start_time,
307                    av_rescale_q(
308                        (*st).start_time,
309                        (*st).time_base,
310                        ffmpeg_sys_next::AV_TIME_BASE_Q,
311                    ),
312                );
313            }
314            let diff = new_start_time - (*is).start_time;
315            if diff != 0 {
316                debug!("Correcting start time of Input #{i} by {diff}us.");
317                demux.start_time_effective = new_start_time;
318                if copy_ts && START_AT_ZERO {
319                    demux.ts_offset = -new_start_time;
320                } else if !copy_ts {
321                    let abs_start_seek = (*is).start_time + demux.start_time_us.unwrap_or(0);
322                    demux.ts_offset = if abs_start_seek > new_start_time {
323                        -abs_start_seek
324                    } else {
325                        -new_start_time
326                    };
327                } else if copy_ts {
328                    demux.ts_offset = 0;
329                }
330
331                // demux.ts_offset += demux.input_ts_offset;
332            }
333        }
334    }
335}
336
337fn check_pipeline<T>(
338    frame_pipelines: Option<&Vec<FramePipeline>>,
339    streams: &[T],
340    tag: &str,
341    get_stream_index: impl Fn(&T) -> usize,
342    get_codec_type: impl Fn(&T) -> &AVMediaType,
343) -> Result<()> {
344    let tag_cap = {
345        let mut chars = tag.chars();
346        match chars.next() {
347            None => String::new(),
348            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
349        }
350    };
351
352    frame_pipelines
353        .into_iter()
354        .flat_map(|pipelines| pipelines.iter())
355        .try_for_each(|pipeline| {
356            if let Some(idx) = pipeline.stream_index {
357                streams
358                    .iter()
359                    .any(|s| {
360                        get_stream_index(s) == idx && get_codec_type(s) == &pipeline.media_type
361                    })
362                    .then_some(())
363                    .ok_or_else(|| {
364                        Into::<crate::error::Error>::into(FrameFilterStreamTypeNoMatched(
365                            tag_cap.clone(),
366                            idx,
367                            format!("{:?}", pipeline.media_type),
368                        ))
369                    })
370            } else {
371                streams
372                    .iter()
373                    .any(|s| get_codec_type(s) == &pipeline.media_type)
374                    .then_some(())
375                    .ok_or_else(|| {
376                        FrameFilterTypeNoMatched(tag.into(), format!("{:?}", pipeline.media_type))
377                    })
378            }
379        })?;
380    Ok(())
381}
382
383fn check_frame_filter_pipeline(muxs: &[Muxer], demuxs: &[Demuxer]) -> Result<()> {
384    muxs.iter().try_for_each(|mux| {
385        check_pipeline(
386            mux.frame_pipelines.as_ref(),
387            mux.get_streams(),
388            "output",
389            |s| s.stream_index,
390            |s| &s.codec_type,
391        )
392    })?;
393    demuxs.iter().try_for_each(|demux| {
394        check_pipeline(
395            demux.frame_pipelines.as_ref(),
396            demux.get_streams(),
397            "input",
398            |s| s.stream_index,
399            |s| &s.codec_type,
400        )
401    })?;
402    Ok(())
403}
404
405fn check_fg_bindings(filter_graphs: &Vec<FilterGraph>) -> Result<()> {
406    // check that all outputs were bound
407    for filter_graph in filter_graphs {
408        for (i, output_filter) in filter_graph.outputs.iter().enumerate() {
409            if !output_filter.has_dst() {
410                let linklabel = if output_filter.linklabel.is_empty() {
411                    "unlabeled".to_string()
412                } else {
413                    output_filter.linklabel.clone()
414                };
415                return Err(OutputUnconnected(output_filter.name.clone(), i, linklabel).into());
416            }
417        }
418    }
419    Ok(())
420}
421
422impl From<FfmpegContext> for FfmpegScheduler<Initialization> {
423    fn from(val: FfmpegContext) -> Self {
424        FfmpegScheduler::new(val)
425    }
426}
427
428fn check_output_streams(muxs: &Vec<Muxer>) -> Result<()> {
429    for mux in muxs {
430        unsafe {
431            let oformat = (*mux.out_fmt_ctx_ptr()).oformat;
432            if !mux.has_src() && (*oformat).flags & AVFMT_NOSTREAMS == 0 {
433                warn!("Output file does not contain any stream");
434                return Err(OpenOutputError::NotContainStream.into());
435            }
436        }
437    }
438    Ok(())
439}
440
441fn check_duplicate_inputs_outputs(inputs: &[Input], outputs: &[Output]) -> Result<()> {
442    for output in outputs {
443        if let Some(output_url) = &output.url {
444            for input in inputs {
445                if let Some(input_url) = &input.url {
446                    if input_url == output_url {
447                        return Err(FileSameAsInput(input_url.clone()));
448                    }
449                }
450            }
451        }
452    }
453    Ok(())
454}
455
456/// Similar to strtol() in C
457/// FFmpeg reference: ffmpeg_opt.c:512 - strtol(arg, &endptr, 0)
458/// Used for parsing file indices and other integers in stream specifiers
459fn strtol(input: &str) -> Result<(i64, &str)> {
460    let mut chars = input.chars().peekable();
461    let mut negative = false;
462
463    if let Some(&ch) = chars.peek() {
464        if ch == '-' {
465            negative = true;
466            chars.next();
467        } else if !ch.is_ascii_digit() {
468            return Err(ParseInteger);
469        }
470    }
471
472    let number_start = input.len() - chars.clone().collect::<String>().len();
473
474    let number_str: String = chars
475        .by_ref()
476        .take_while(|ch| ch.is_ascii_digit())
477        .collect();
478
479    if number_str.is_empty() {
480        return Err(ParseInteger);
481    }
482
483    let number: i64 = number_str.parse().map_err(|_| ParseInteger)?;
484
485    let remainder_index = number_start + number_str.len();
486    let remainder = &input[remainder_index..];
487
488    if negative {
489        Ok((-number, remainder))
490    } else {
491        Ok((number, remainder))
492    }
493}
494
495fn convert_options(
496    opts: Option<HashMap<String, String>>,
497) -> Result<Option<HashMap<CString, CString>>> {
498    if opts.is_none() {
499        return Ok(None);
500    }
501
502    let converted = opts.map(|map| {
503        map.into_iter()
504            .map(|(k, v)| Ok((CString::new(k)?, CString::new(v)?)))
505            .collect::<Result<HashMap<CString, CString>, _>>() // Collect into a HashMap
506    });
507
508    converted.transpose() // Convert `Result<Option<T>>` into `Option<Result<T>>`
509}
510
511#[cfg(test)]
512mod tests {
513    use std::ffi::{CStr, CString};
514    use std::ptr::null_mut;
515
516    use crate::core::context::ffmpeg_context::{strtol, FfmpegContext, Output};
517    use ffmpeg_sys_next::avfilter_graph_parse_ptr;
518
519    use crate::core::context::ffmpeg_context::{bind_fg_inputs_by_fg, fg_complex_bind_input};
520    use crate::core::context::ffmpeg_context::{
521        read_packet_wrapper, seek_input_packet_wrapper, write_packet_wrapper, InputOpaque,
522        OutputOpaque,
523    };
524    use crate::core::context::filter_graph::FilterGraph;
525    use crate::core::context::input_filter::InputFilter;
526    use crate::core::context::null_frame;
527    use crate::core::context::output_filter::OutputFilter;
528    use ffmpeg_sys_next::AVMediaType::AVMEDIA_TYPE_VIDEO;
529
530    fn test_input(linklabel: &str, name: &str) -> InputFilter {
531        InputFilter::new(
532            linklabel.to_string(),
533            AVMEDIA_TYPE_VIDEO,
534            name.to_string(),
535            null_frame(),
536        )
537    }
538
539    fn test_graph(inputs: Vec<InputFilter>, outputs: Vec<OutputFilter>) -> FilterGraph {
540        FilterGraph::new("null".to_string(), inputs, outputs, None, None)
541    }
542
543    // The REAL builder must leave a cross-graph-bound pad as a `None` hole in the
544    // consumer node's pad-indexed scheduler-input list, with the demuxer-bound
545    // pad in its own slot — not a shifted/dense list. FC0 outputs `[mid]` (the
546    // consumer's pad 0, cross-graph); `[1:v]` is a demuxer stream (pad 1). This
547    // pins the structure the runtime relies on (a shifted list would mis-route
548    // demuxer choke-balancing).
549    #[test]
550    fn builder_leaves_cross_graph_pad_as_a_hole_in_scheduler_inputs() {
551        use crate::core::context::input::Input;
552        use crate::core::scheduler::input_controller::SchNode;
553
554        let out = std::env::temp_dir().join(format!(
555            "ez_ffmpeg_xgraph_struct_{}.mp4",
556            std::process::id()
557        ));
558        let ctx = FfmpegContext::builder()
559            .input(Input::from("color=c=red:s=64x64:r=15:d=0.2").set_format("lavfi"))
560            .input(Input::from("color=c=blue:s=64x64:r=15:d=0.2").set_format("lavfi"))
561            .filter_desc("[0:v]hue=s=0[mid]")
562            .filter_desc("[mid][1:v]overlay[vout]")
563            .output(
564                Output::from(out.to_str().unwrap())
565                    .add_stream_map("vout")
566                    .set_video_codec("mpeg4"),
567            )
568            .build()
569            .expect("cross-graph build");
570
571        let consumer = ctx
572            .filter_graphs
573            .iter()
574            .find(|fg| fg.graph_desc.contains("overlay"))
575            .expect("consumer graph present");
576        let SchNode::Filter { inputs, .. } = consumer.node.as_ref() else {
577            panic!("consumer node must be a Filter");
578        };
579        assert_eq!(inputs.len(), 2, "one scheduler-input slot per filter pad");
580        assert!(inputs[0].is_none(), "pad 0 ([mid]) is a cross-graph hole");
581        assert!(inputs[1].is_some(), "pad 1 ([1:v]) binds a demuxer");
582    }
583
584    #[test]
585    fn cross_graph_binding_uses_input_pad_index_and_marks_bound() {
586        // Producer (graph 0): one output labeled "mid".
587        // Consumer (graph 1): pad 0 labeled "mid", pad 1 unlabeled.
588        // The consumer's GRAPH index (1) differs from the matching PAD
589        // index (0) on purpose: routing and finished_flag_list indexing
590        // work per input pad, not per graph.
591        let producer = test_graph(
592            vec![test_input("", "in0")],
593            vec![OutputFilter::new(
594                "mid".to_string(),
595                AVMEDIA_TYPE_VIDEO,
596                "out0".to_string(),
597            )],
598        );
599        let consumer = test_graph(
600            vec![test_input("mid", "in0"), test_input("", "in1")],
601            vec![OutputFilter::new(
602                String::new(),
603                AVMEDIA_TYPE_VIDEO,
604                "out0".to_string(),
605            )],
606        );
607        let mut graphs = vec![producer, consumer];
608
609        bind_fg_inputs_by_fg(&mut graphs).unwrap();
610
611        assert!(
612            graphs[0].outputs[0].has_dst(),
613            "producer output must be connected to the consumer"
614        );
615        assert_eq!(
616            graphs[0].outputs[0].fg_input_index, 0,
617            "fg_input_index must be the consumer's input PAD index, not its graph index"
618        );
619        assert_eq!(
620            graphs[0].outputs[0].finished_flag_list.len(),
621            2,
622            "the producer must hold the consumer's per-pad finished flags"
623        );
624        assert!(
625            graphs[1].inputs[0].bound,
626            "the cross-connected pad must be marked bound"
627        );
628        assert!(
629            !graphs[1].inputs[1].bound,
630            "unrelated pads must stay unbound"
631        );
632    }
633
634    #[test]
635    fn complex_bind_skips_already_bound_labeled_input() {
636        let mut consumer = test_graph(
637            vec![test_input("mid", "in0")],
638            vec![OutputFilter::new(
639                String::new(),
640                AVMEDIA_TYPE_VIDEO,
641                "out0".to_string(),
642            )],
643        );
644        consumer.inputs[0].bound = true;
645
646        // No demuxers exist: if the pad were (re-)bound to an input stream
647        // this would fail with "stream not found".
648        let result = fg_complex_bind_input(&mut consumer, 0, &mut Vec::new());
649        assert!(
650            result.is_ok(),
651            "a pad already bound to another graph must not be re-bound: {result:?}"
652        );
653    }
654
655    #[test]
656    fn complex_bind_skips_bound_reserved_in_label() {
657        // The reserved label "in" takes the auto-bind branch, which must
658        // also respect an existing cross-graph binding.
659        let mut consumer = test_graph(
660            vec![test_input("in", "in0")],
661            vec![OutputFilter::new(
662                String::new(),
663                AVMEDIA_TYPE_VIDEO,
664                "out0".to_string(),
665            )],
666        );
667        consumer.inputs[0].bound = true;
668
669        let result = fg_complex_bind_input(&mut consumer, 0, &mut Vec::new());
670        assert!(
671            result.is_ok(),
672            "a bound pad labeled 'in' must not fall through to stream auto-binding: {result:?}"
673        );
674    }
675
676    #[test]
677    fn test_filter() {
678        let desc_cstr = CString::new("[1:v][2:v]concat=n=2:v=1:a=0[vout]").unwrap();
679        // let desc_cstr = CString::new("fps=15").unwrap();
680
681        unsafe {
682            let graph = crate::raw::FilterGraph::alloc().unwrap();
683            let mut inputs = crate::raw::FilterInOut::empty();
684            let mut outputs = crate::raw::FilterInOut::empty();
685
686            let ret = avfilter_graph_parse_ptr(
687                graph.as_ptr(),
688                desc_cstr.as_ptr(),
689                inputs.as_out_ptr(),
690                outputs.as_out_ptr(),
691                null_mut(),
692            );
693            if ret < 0 {
694                println!("err ret:{}", crate::util::ffmpeg_utils::av_err2str(ret));
695                return;
696            }
697
698            println!("inputs.is_null:{}", inputs.as_ptr().is_null());
699            println!("outputs.is_null:{}", outputs.as_ptr().is_null());
700
701            let mut cur = inputs.as_ptr();
702            while !cur.is_null() {
703                let input_name = CStr::from_ptr((*cur).name);
704                println!("Input name: {}", input_name.to_str().unwrap());
705                cur = (*cur).next;
706            }
707
708            let output_name = CStr::from_ptr((*outputs.as_ptr()).name);
709            println!("Output name: {}", output_name.to_str().unwrap());
710
711            let filter_ctx = (*outputs.as_ptr()).filter_ctx;
712            println!("filter_ctx.is_null:{}", filter_ctx.is_null());
713        }
714    }
715
716    #[test]
717    fn fallback_frame_carries_real_stream_parameters() {
718        // Regression: the probe dec_ctx used to stay at codec defaults, so
719        // the fallback frame bound to each filtergraph input had format=-1
720        // and the EOF-before-first-frame path could never configure a graph.
721        let ctx = FfmpegContext::new(
722            vec!["test.mp4".into()],
723            vec!["hue=s=0".into()],
724            vec!["output_fallback_probe.mp4".to_string().into()],
725        )
726        .unwrap();
727        let fallback = unsafe { &*ctx.filter_graphs[0].inputs[0].opts.fallback.as_ptr() };
728        assert!(
729            fallback.format >= 0,
730            "fallback must carry the stream's real format, got {}",
731            fallback.format
732        );
733        assert!(
734            fallback.width > 0 && fallback.height > 0,
735            "fallback must carry the stream's dimensions, got {}x{}",
736            fallback.width,
737            fallback.height
738        );
739        assert!(
740            fallback.time_base.num > 0 && fallback.time_base.den > 0,
741            "fallback must carry the stream's packet time base, got {}/{}",
742            fallback.time_base.num,
743            fallback.time_base.den
744        );
745    }
746
747    #[test]
748    fn test_new() {
749        let _ = env_logger::builder()
750            .filter_level(log::LevelFilter::Debug)
751            .is_test(true)
752            .try_init();
753        let _ffmpeg_context = FfmpegContext::new(
754            vec!["test.mp4".to_string().into()],
755            vec!["hue=s=0".to_string().into()],
756            vec!["output.mp4".to_string().into()],
757        )
758        .unwrap();
759        let _ffmpeg_context = FfmpegContext::new(
760            vec!["test.mp4".into()],
761            vec!["[0:v]hue=s=0".into()],
762            vec!["output.mp4".to_string().into()],
763        )
764        .unwrap();
765        let _ffmpeg_context = FfmpegContext::new(
766            vec!["test.mp4".into()],
767            vec!["hue=s=0[my-out]".into()],
768            vec![Output::from("output.mp4").add_stream_map("my-out")],
769        )
770        .unwrap();
771        let result = FfmpegContext::new(
772            vec!["test.mp4".into()],
773            vec!["hue=s=0".into()],
774            vec![Output::from("output.mp4").add_stream_map("0:v?")],
775        );
776        assert!(result.is_err());
777        let result = FfmpegContext::new(
778            vec!["test.mp4".into()],
779            vec!["hue=s=0".into()],
780            vec![Output::from("output.mp4").add_stream_map_with_copy("1:v?")],
781        );
782        assert!(result.is_err());
783        let result = FfmpegContext::new(
784            vec!["test.mp4".into()],
785            vec!["hue=s=0[fg-out]".into()],
786            vec![
787                Output::from("output.mp4").add_stream_map("my-out?"),
788                Output::from("output.mp4").add_stream_map("fg-out"),
789            ],
790        );
791        assert!(result.is_err());
792        // ignore filter
793        let result = FfmpegContext::new(
794            vec!["test.mp4".into()],
795            vec!["hue=s=0".into()],
796            vec![Output::from("output.mp4").add_stream_map_with_copy("1:v")],
797        );
798        assert!(result.is_err());
799        let result = FfmpegContext::new(
800            vec!["test.mp4".into()],
801            vec!["hue=s=0[fg-out]".into()],
802            vec![Output::from("output.mp4").add_stream_map("fg-out?")],
803        );
804        assert!(result.is_err());
805    }
806
807    #[test]
808    fn test_builder() {
809        let _ = env_logger::builder()
810            .filter_level(log::LevelFilter::Debug)
811            .is_test(true)
812            .try_init();
813
814        let _context1 = FfmpegContext::builder()
815            .input("test.mp4")
816            .filter_desc("hue=s=0")
817            .output("output.mp4")
818            .build()
819            .unwrap();
820
821        let _context2 = FfmpegContext::builder()
822            .inputs(vec!["test.mp4"])
823            .filter_descs(vec!["hue=s=0"])
824            .outputs(vec!["output.mp4"])
825            .build()
826            .unwrap();
827    }
828
829    #[test]
830    fn test_strtol() {
831        let input = "-123---abc";
832        let result = strtol(input);
833        assert_eq!(result.unwrap(), (-123, "---abc"));
834
835        let input = "123---abc";
836        let result = strtol(input);
837        assert_eq!(result.unwrap(), (123, "---abc"));
838
839        let input = "-123aa";
840        let result = strtol(input);
841        assert_eq!(result.unwrap(), (-123, "aa"));
842
843        let input = "-aa";
844        let result = strtol(input);
845        assert!(result.is_err());
846
847        let input = "abc";
848        let result = strtol(input);
849        assert!(result.is_err())
850    }
851
852    // ---- custom-IO wrapper hardening (deterministic, no FFmpeg involved) ----
853    //
854    // The wrappers are plain extern "C" fns; driving them directly with a
855    // fabricated opaque pins their exact contract: oversized read lengths are
856    // clamped to EIO, a panicking closure is contained AND poisons the
857    // context, and a poisoned context never re-enters user code.
858
859    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
860    use std::sync::Arc;
861
862    fn eio() -> libc::c_int {
863        ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO)
864    }
865
866    #[test]
867    fn read_wrapper_clamps_oversized_length_and_allows_exact_fit() {
868        let opaque = Box::into_raw(Box::new(InputOpaque {
869            read: Box::new(|buf| buf.len() as i32 + 64),
870            seek: None,
871            poisoned: false,
872        }));
873        let mut buf = [0u8; 32];
874        let ret = unsafe {
875            read_packet_wrapper(
876                opaque as *mut libc::c_void,
877                buf.as_mut_ptr(),
878                buf.len() as libc::c_int,
879            )
880        };
881        assert_eq!(ret, eio(), "a forged over-length must clamp to EIO");
882        unsafe {
883            // Not poisoned by a bogus length: an exact-fit read stays legal.
884            (*opaque).read = Box::new(|buf| buf.len() as i32);
885            let ret = read_packet_wrapper(
886                opaque as *mut libc::c_void,
887                buf.as_mut_ptr(),
888                buf.len() as libc::c_int,
889            );
890            assert_eq!(
891                ret,
892                buf.len() as libc::c_int,
893                "ret == buf_size is within bounds and must pass through"
894            );
895            drop(Box::from_raw(opaque));
896        }
897    }
898
899    #[test]
900    fn read_wrapper_contains_panic_and_poisons() {
901        let calls = Arc::new(AtomicUsize::new(0));
902        let probe = Arc::clone(&calls);
903        let opaque = Box::into_raw(Box::new(InputOpaque {
904            read: Box::new(move |_buf| {
905                probe.fetch_add(1, AtomicOrdering::SeqCst);
906                panic!("test-injected read panic");
907            }),
908            seek: None,
909            poisoned: false,
910        }));
911        let mut buf = [0u8; 32];
912        for _ in 0..3 {
913            let ret = unsafe {
914                read_packet_wrapper(
915                    opaque as *mut libc::c_void,
916                    buf.as_mut_ptr(),
917                    buf.len() as libc::c_int,
918                )
919            };
920            assert_eq!(ret, eio());
921        }
922        assert_eq!(
923            calls.load(AtomicOrdering::SeqCst),
924            1,
925            "the panicking closure must never be re-entered once poisoned"
926        );
927        unsafe { drop(Box::from_raw(opaque)) };
928    }
929
930    #[test]
931    fn write_wrapper_contains_panic_and_poisons() {
932        let calls = Arc::new(AtomicUsize::new(0));
933        let probe = Arc::clone(&calls);
934        let opaque = Box::into_raw(Box::new(OutputOpaque {
935            write: Box::new(move |_buf| {
936                probe.fetch_add(1, AtomicOrdering::SeqCst);
937                panic!("test-injected write panic");
938            }),
939            seek: None,
940            poisoned: false,
941        }));
942        let buf = [0u8; 32];
943        for _ in 0..3 {
944            let ret = unsafe {
945                write_packet_wrapper(
946                    opaque as *mut libc::c_void,
947                    buf.as_ptr(),
948                    buf.len() as libc::c_int,
949                )
950            };
951            assert_eq!(ret, eio());
952        }
953        assert_eq!(
954            calls.load(AtomicOrdering::SeqCst),
955            1,
956            "the panicking closure must never be re-entered once poisoned"
957        );
958        unsafe { drop(Box::from_raw(opaque)) };
959    }
960
961    #[test]
962    fn seek_panic_poisons_the_whole_input_context() {
963        let reads = Arc::new(AtomicUsize::new(0));
964        let read_probe = Arc::clone(&reads);
965        let opaque = Box::into_raw(Box::new(InputOpaque {
966            read: Box::new(move |buf| {
967                read_probe.fetch_add(1, AtomicOrdering::SeqCst);
968                buf.len() as i32
969            }),
970            seek: Some(Box::new(|_offset, _whence| {
971                panic!("test-injected seek panic")
972            })),
973            poisoned: false,
974        }));
975        let mut buf = [0u8; 32];
976        unsafe {
977            // Healthy read before the panic.
978            let ret = read_packet_wrapper(
979                opaque as *mut libc::c_void,
980                buf.as_mut_ptr(),
981                buf.len() as libc::c_int,
982            );
983            assert_eq!(ret, buf.len() as libc::c_int);
984
985            // The panicking seek is contained as EIO (not ESPIPE, which
986            // would let FFmpeg fall back to non-seeking modes and mask it).
987            let ret = seek_input_packet_wrapper(opaque as *mut libc::c_void, 0, 0);
988            assert_eq!(ret, eio() as i64);
989
990            // Cross-callback poison: the read closure must not run again.
991            let ret = read_packet_wrapper(
992                opaque as *mut libc::c_void,
993                buf.as_mut_ptr(),
994                buf.len() as libc::c_int,
995            );
996            assert_eq!(ret, eio());
997            drop(Box::from_raw(opaque));
998        }
999        assert_eq!(
1000            reads.load(AtomicOrdering::SeqCst),
1001            1,
1002            "a seek panic must poison reads on the same context"
1003        );
1004    }
1005
1006    /// H12: a short-writing sink (io::Write-style) must not lose the
1007    /// remainder — the wrapper resubmits until the whole buffer went out.
1008    #[test]
1009    fn write_wrapper_resubmits_short_writes() {
1010        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
1011        let probe = Arc::clone(&seen);
1012        let opaque = Box::into_raw(Box::new(OutputOpaque {
1013            write: Box::new(move |buf| {
1014                // Write at most 10 bytes per call, recording each chunk.
1015                let n = buf.len().min(10);
1016                probe.lock().unwrap().extend_from_slice(&buf[..n]);
1017                n as i32
1018            }),
1019            seek: None,
1020            poisoned: false,
1021        }));
1022        let data: Vec<u8> = (0..64u8).collect();
1023        let ret = unsafe {
1024            write_packet_wrapper(
1025                opaque as *mut libc::c_void,
1026                data.as_ptr(),
1027                data.len() as libc::c_int,
1028            )
1029        };
1030        assert_eq!(
1031            ret,
1032            data.len() as libc::c_int,
1033            "the whole buffer must report written"
1034        );
1035        assert_eq!(
1036            *seen.lock().unwrap(),
1037            data,
1038            "no byte may be lost or reordered"
1039        );
1040        unsafe { drop(Box::from_raw(opaque)) };
1041    }
1042
1043    /// H12: zero progress and over-claimed lengths are I/O faults, not
1044    /// silent success.
1045    #[test]
1046    fn write_wrapper_rejects_zero_progress_and_over_claims() {
1047        let opaque = Box::into_raw(Box::new(OutputOpaque {
1048            write: Box::new(|_buf| 0),
1049            seek: None,
1050            poisoned: false,
1051        }));
1052        let data = [7u8; 16];
1053        let ret = unsafe { write_packet_wrapper(opaque as *mut libc::c_void, data.as_ptr(), 16) };
1054        assert_eq!(
1055            ret,
1056            eio(),
1057            "a zero-progress sink must fail, not spin or succeed"
1058        );
1059        unsafe {
1060            (*opaque).write = Box::new(|buf| buf.len() as i32 + 4);
1061            let ret = write_packet_wrapper(opaque as *mut libc::c_void, data.as_ptr(), 16);
1062            assert_eq!(ret, eio(), "an over-claimed write length must fail");
1063            drop(Box::from_raw(opaque));
1064        }
1065    }
1066
1067    /// A negative error from the sink passes through unchanged.
1068    #[test]
1069    fn write_wrapper_passes_sink_errors_through() {
1070        let opaque = Box::into_raw(Box::new(OutputOpaque {
1071            write: Box::new(|_buf| ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ENOSPC)),
1072            seek: None,
1073            poisoned: false,
1074        }));
1075        let data = [7u8; 8];
1076        let ret = unsafe { write_packet_wrapper(opaque as *mut libc::c_void, data.as_ptr(), 8) };
1077        assert_eq!(ret, ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ENOSPC));
1078        unsafe { drop(Box::from_raw(opaque)) };
1079    }
1080
1081    #[test]
1082    fn absent_seek_callback_stays_espipe() {
1083        let opaque = Box::into_raw(Box::new(InputOpaque {
1084            read: Box::new(|buf| buf.len() as i32),
1085            seek: None,
1086            poisoned: false,
1087        }));
1088        let ret = unsafe { seek_input_packet_wrapper(opaque as *mut libc::c_void, 0, 0) };
1089        assert_eq!(
1090            ret,
1091            ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ESPIPE) as i64,
1092            "no seek callback means genuinely unseekable, not an I/O fault"
1093        );
1094        unsafe { drop(Box::from_raw(opaque)) };
1095    }
1096}