ez-ffmpeg 0.13.1

A safe and ergonomic Rust interface for FFmpeg integration, designed for ease of use.
Documentation
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
use super::*;

pub(super) fn fg_bind_inputs(
    filter_graphs: &mut Vec<FilterGraph>,
    demuxs: &mut Vec<Demuxer>,
) -> Result<()> {
    if filter_graphs.is_empty() {
        return Ok(());
    }
    bind_fg_inputs_by_fg(filter_graphs)?;

    for filter_graph in filter_graphs.iter_mut() {
        for i in 0..filter_graph.inputs.len() {
            fg_complex_bind_input(filter_graph, i, demuxs)?;
        }
    }

    Ok(())
}

struct FilterLabel {
    linklabel: String,
    media_type: AVMediaType,
}

pub(super) fn bind_fg_inputs_by_fg(filter_graphs: &mut Vec<FilterGraph>) -> Result<()> {
    let fg_labels = filter_graphs
        .iter()
        .map(|filter_graph| {
            let inputs = filter_graph
                .inputs
                .iter()
                .map(|input| FilterLabel {
                    linklabel: input.linklabel.clone(),
                    media_type: input.media_type,
                })
                .collect::<Vec<_>>();
            let outputs = filter_graph
                .outputs
                .iter()
                .map(|output| FilterLabel {
                    linklabel: output.linklabel.clone(),
                    media_type: output.media_type,
                })
                .collect::<Vec<_>>();
            (inputs, outputs)
        })
        .collect::<Vec<_>>();

    for (i, (inputs, _outputs)) in fg_labels.iter().enumerate() {
        for (input_pad_idx, input_filter_label) in inputs.iter().enumerate() {
            if input_filter_label.linklabel.is_empty() {
                continue;
            }

            'outer: for (j, (_inputs, outputs)) in fg_labels.iter().enumerate() {
                if i == j {
                    continue;
                }

                for (output_idx, output_filter_label) in outputs.iter().enumerate() {
                    if output_filter_label.linklabel != input_filter_label.linklabel {
                        continue;
                    }
                    if output_filter_label.media_type != input_filter_label.media_type {
                        warn!(target: LOG_TARGET,
                            "Tried to connect {:?} output to {:?} input",
                            output_filter_label.media_type, input_filter_label.media_type
                        );
                        return Err(FilterGraphParseError::InvalidArgument.into());
                    }

                    {
                        let filter_graph = &filter_graphs[j];
                        let output_filter = &filter_graph.outputs[output_idx];
                        if output_filter.has_dst() {
                            continue;
                        }
                    }

                    let (sender, finished_flag_list) = {
                        let filter_graph = &mut filter_graphs[i];
                        filter_graph.get_src_sender()
                    };

                    {
                        let filter_graph = &mut filter_graphs[j];
                        filter_graph.outputs[output_idx].set_dst(sender);
                        // The consumer routes frames and indexes its per-pad
                        // finished_flag_list by INPUT PAD index, not by the
                        // consumer's graph index.
                        filter_graph.outputs[output_idx].fg_input_index = input_pad_idx;
                        filter_graph.outputs[output_idx].finished_flag_list = finished_flag_list;
                    }
                    // Mark the pad so fg_complex_bind_input does not bind it
                    // to a demuxer stream on top of this connection.
                    filter_graphs[i].inputs[input_pad_idx].bound = true;

                    break 'outer;
                }
            }
        }
    }
    Ok(())
}

pub(super) fn fg_complex_bind_input(
    filter_graph: &mut FilterGraph,
    input_filter_index: usize,
    demuxs: &mut Vec<Demuxer>,
) -> Result<()> {
    // A pad already connected to another filtergraph's output must not also
    // be bound to a demuxer stream (covers labeled pads including the
    // reserved "in" label, which otherwise takes the auto-bind branch).
    if filter_graph.inputs[input_filter_index].bound {
        return Ok(());
    }

    let graph_desc = &filter_graph.graph_desc;
    let input_filter = &mut filter_graph.inputs[input_filter_index];
    let (demux_idx, stream_idx) = if !input_filter.linklabel.is_empty()
        && input_filter.linklabel != "in"
    {
        let (demux_idx, stream_idx) = fg_find_input_idx_by_linklabel(
            &input_filter.linklabel,
            input_filter.media_type,
            demuxs,
            graph_desc,
        )?;

        info!(target: LOG_TARGET,
            "Binding filter input with label '{}' to input stream {stream_idx}:{demux_idx}",
            input_filter.linklabel
        );
        (demux_idx, stream_idx)
    } else {
        let mut demux_idx = -1i32;
        let mut stream_idx = 0;
        for (d_idx, demux) in demuxs.iter().enumerate() {
            for (st_idx, intput_stream) in demux.get_streams().iter().enumerate() {
                if intput_stream.is_used() {
                    continue;
                }
                if intput_stream.codec_type == input_filter.media_type {
                    demux_idx = d_idx as i32;
                    stream_idx = st_idx;
                    break;
                }
            }
            if demux_idx >= 0 {
                break;
            }
        }

        if demux_idx < 0 {
            warn!(target: LOG_TARGET,
                "Cannot find a matching stream for unlabeled input pad {}",
                input_filter.name
            );
            return Err(FilterGraphParseError::InvalidArgument.into());
        }

        debug!(target: LOG_TARGET, "FilterGraph binding unlabeled input {input_filter_index} to input stream {stream_idx}:{demux_idx}");

        (demux_idx as usize, stream_idx)
    };

    let demux = &mut demuxs[demux_idx];

    ifilter_bind_ist(filter_graph, input_filter_index, stream_idx, demux)
}

#[cfg(docsrs)]
pub(super) fn ifilter_bind_ist(
    filter_graph: &mut FilterGraph,
    input_index: usize,
    stream_idx: usize,
    demux: &mut Demuxer,
) -> Result<()> {
    Ok(())
}

#[cfg(not(docsrs))]
pub(super) fn ifilter_bind_ist(
    filter_graph: &mut FilterGraph,
    input_index: usize,
    stream_idx: usize,
    demux: &mut Demuxer,
) -> Result<()> {
    unsafe {
        let input_filter = &mut filter_graph.inputs[input_index];
        let ist = *(*demux.in_fmt_ctx_ptr()).streams.add(stream_idx);
        let par = (*ist).codecpar;
        if (*par).codec_type == AVMEDIA_TYPE_VIDEO {
            // A user-forced input framerate feeds the filtergraph directly;
            // only guess from the container when none was forced
            // (ffmpeg_demux.c ist_filter_add: ist->framerate ?: guess).
            let framerate = if demux.framerate.num > 0 && demux.framerate.den > 0 {
                demux.framerate
            } else {
                av_guess_frame_rate(demux.in_fmt_ctx_ptr(), ist, null_mut())
            };
            input_filter.opts.framerate = framerate;
        } else if (*par).codec_type == AVMEDIA_TYPE_SUBTITLE {
            input_filter.opts.sub2video_width = (*par).width;
            input_filter.opts.sub2video_height = (*par).height;

            if input_filter.opts.sub2video_width <= 0 || input_filter.opts.sub2video_height <= 0 {
                let nb_streams = (*demux.in_fmt_ctx_ptr()).nb_streams;
                for j in 0..nb_streams {
                    let par1 = (**(*demux.in_fmt_ctx_ptr()).streams.add(j as usize)).codecpar;
                    if (*par1).codec_type == AVMEDIA_TYPE_VIDEO {
                        input_filter.opts.sub2video_width =
                            std::cmp::max(input_filter.opts.sub2video_width, (*par1).width);
                        input_filter.opts.sub2video_height =
                            std::cmp::max(input_filter.opts.sub2video_height, (*par1).height);
                    }
                }
            }

            if input_filter.opts.sub2video_width <= 0 || input_filter.opts.sub2video_height <= 0 {
                input_filter.opts.sub2video_width =
                    std::cmp::max(input_filter.opts.sub2video_width, 720);
                input_filter.opts.sub2video_height =
                    std::cmp::max(input_filter.opts.sub2video_height, 576);
            }

            demux.get_stream_mut(stream_idx).have_sub2video = true;
        }

        let dec_ctx = {
            let input_stream = demux.get_stream_mut(stream_idx);
            avcodec_alloc_context3(input_stream.codec.as_ptr())
        };
        if dec_ctx.is_null() {
            return Err(FilterGraphParseError::OutOfMemory.into());
        }
        let _codec_ctx = CodecContext::new(dec_ctx);

        // A freshly allocated context only carries codec defaults (format
        // -1, 0x0, timebase 0/1), which made the fallback below useless: the
        // EOF-before-first-frame path could never configure the graph
        // ("Cannot determine format of input ... after EOF"). fftools fills
        // the fallback from the opened decoder (dec_open's param_out); at
        // bind time no decoder is open, so the stream's codecpar — the same
        // values a decoder would start from — is the faithful source.
        let ret = avcodec_parameters_to_context(dec_ctx, par);
        if ret < 0 {
            return Err(FilterGraphParseError::from(ret).into());
        }
        (*dec_ctx).pkt_timebase = (*ist).time_base;

        let fallback = input_filter.opts.fallback.as_mut_ptr();
        if (*dec_ctx).codec_type == AVMEDIA_TYPE_AUDIO {
            (*fallback).format = (*dec_ctx).sample_fmt as i32;
            (*fallback).sample_rate = (*dec_ctx).sample_rate;

            let ret = av_channel_layout_copy(&mut (*fallback).ch_layout, &(*dec_ctx).ch_layout);
            if ret < 0 {
                return Err(FilterGraphParseError::from(ret).into());
            }
        } else if (*dec_ctx).codec_type == AVMEDIA_TYPE_VIDEO {
            (*fallback).format = (*dec_ctx).pix_fmt as i32;
            (*fallback).width = (*dec_ctx).width;
            (*fallback).height = (*dec_ctx).height;
            (*fallback).sample_aspect_ratio = (*dec_ctx).sample_aspect_ratio;
            (*fallback).colorspace = (*dec_ctx).colorspace;
            (*fallback).color_range = (*dec_ctx).color_range;
        }
        (*fallback).time_base = (*dec_ctx).pkt_timebase;

        // Set autorotate flag based on demuxer configuration
        // FFmpeg source: ffmpeg_demux.c:1137, ffmpeg_filter.c:1744-1778 (FFmpeg 7.x)
        if demux.autorotate {
            input_filter.opts.flags |= IFILTER_FLAG_AUTOROTATE;
        }

        let tsoffset = if demux.copy_ts {
            let mut tsoffset = if demux.start_time_us.is_some() {
                demux.start_time_us.unwrap()
            } else {
                0
            };
            if (*demux.in_fmt_ctx_ptr()).start_time != ffmpeg_sys_next::AV_NOPTS_VALUE {
                tsoffset += (*demux.in_fmt_ctx_ptr()).start_time
            }
            tsoffset
        } else {
            0
        };
        if demux.start_time_us.is_some() {
            input_filter.opts.trim_start_us = Some(tsoffset);
        }
        input_filter.opts.trim_end_us = demux.recording_time_us;

        let (sender, finished_flag_list) = filter_graph.get_src_sender();
        {
            let input_stream = demux.get_stream_mut(stream_idx);
            input_stream.add_fg_dst(sender, input_index, finished_flag_list);
        };

        let node = Arc::make_mut(&mut filter_graph.node);
        let SchNode::Filter { inputs, .. } = node else {
            unreachable!()
        };
        // Assign into the pad-indexed slot (pre-sized to the pad count in
        // FilterGraph::new, so `input_index` is always in range — the function
        // already indexed `filter_graph.inputs[input_index]` above). A
        // `Vec::insert` here used to panic when a cross-graph-bound pad earlier
        // in the list was skipped, leaving `input_index` past the list length;
        // pads that stay cross-graph-bound remain `None` holes. A length
        // mismatch here would be an internal invariant break, so surface it as a
        // bug rather than silently leaving a hole.
        let Some(slot) = inputs.get_mut(input_index) else {
            return Err(Error::Bug);
        };
        *slot = Some(demux.node.clone());

        demux.connect_stream(stream_idx);
        Ok(())
    }
}

/// Find input stream index by filter graph linklabel
/// FFmpeg reference: ffmpeg_filter.c - fg_create logic for parsing filter input specifiers
/// Uses StreamSpecifier for complete stream specifier parsing
fn fg_find_input_idx_by_linklabel(
    linklabel: &str,
    filter_media_type: AVMediaType,
    demuxs: &mut Vec<Demuxer>,
    desc: &str,
) -> Result<(usize, usize)> {
    // Remove brackets if present
    let new_linklabel = if linklabel.starts_with("[") && linklabel.ends_with("]") {
        if linklabel.len() <= 2 {
            warn!(target: LOG_TARGET, "Filter linklabel is empty");
            return Err(InvalidFilterSpecifier(desc.to_string()).into());
        } else {
            &linklabel[1..linklabel.len() - 1]
        }
    } else {
        linklabel
    };

    // Parse file index using strtol (FFmpeg reference: ffmpeg_opt.c:512)
    let (file_idx, remainder) =
        strtol(new_linklabel).map_err(|_| FilterGraphParseError::InvalidArgument)?;

    if file_idx < 0 || file_idx as usize >= demuxs.len() {
        return Err(InvalidFileIndexInFg(file_idx as usize, desc.to_string()).into());
    }
    let file_idx = file_idx as usize;

    // Parse stream specifier using StreamSpecifier
    let spec_str = if remainder.is_empty() {
        // No specifier - will match by media type
        ""
    } else if remainder.starts_with(':') {
        &remainder[1..]
    } else {
        remainder
    };

    let stream_spec = if spec_str.is_empty() {
        // No specifier: create one matching the filter's media type
        let mut spec = StreamSpecifier::default();
        spec.media_type = Some(filter_media_type);
        spec
    } else {
        // Parse the specifier
        StreamSpecifier::parse(spec_str).map_err(|e| {
            warn!(target: LOG_TARGET,
                "Invalid stream specifier in filter linklabel '{}': {}",
                linklabel, e
            );
            FilterGraphParseError::InvalidArgument
        })?
    };

    // Find first matching stream
    let demux = &demuxs[file_idx];
    unsafe {
        let fmt_ctx = demux.in_fmt_ctx_ptr();

        let mut subtitle_only_match = false;
        for (idx, _) in demux.get_streams().iter().enumerate() {
            let avstream = *(*fmt_ctx).streams.add(idx);

            if stream_spec.matches(fmt_ctx, avstream) {
                // Additional check: must match filter's media type
                let codec_type = (*avstream).codecpar.as_ref().unwrap().codec_type;
                if codec_type == filter_media_type {
                    return Ok((file_idx, idx));
                }
                if codec_type == AVMEDIA_TYPE_SUBTITLE && filter_media_type == AVMEDIA_TYPE_VIDEO {
                    subtitle_only_match = true;
                }
            }
        }

        if subtitle_only_match {
            // The spec names a subtitle stream feeding a VIDEO pad: that is
            // fftools' sub2video hack, which this crate does not implement.
            // Fail with a specific message instead of "matches no streams".
            error!(target: LOG_TARGET,
                "Stream specifier '{remainder}' in filtergraph description {desc} \
                 matches a subtitle stream, but subtitle streams as filtergraph \
                 inputs (sub2video) are not supported"
            );
            return Err(FilterGraphParseError::InvalidArgument.into());
        }
    }

    // No matching stream found
    warn!(target: LOG_TARGET,
        "Stream specifier '{}' in filtergraph description {} matches no streams.",
        remainder, desc
    );
    Err(FilterGraphParseError::InvalidArgument.into())
}

pub(super) fn init_filter_graphs(filter_complexs: Vec<FilterComplex>) -> Result<Vec<FilterGraph>> {
    let mut filter_graphs = Vec::with_capacity(filter_complexs.len());
    for (i, filter) in filter_complexs.iter().enumerate() {
        let filter_graph = init_filter_graph(
            i,
            &filter.filter_descs,
            filter.hw_device.clone(),
            filter.sws_opts.clone(),
            filter.swr_opts.clone(),
        )?;
        filter_graphs.push(filter_graph);
    }
    Ok(filter_graphs)
}

#[cfg(docsrs)]
pub(super) fn init_filter_graph(
    fg_index: usize,
    filter_desc: &str,
    hw_device: Option<String>,
    sws_opts: Option<String>,
    swr_opts: Option<String>,
) -> Result<FilterGraph> {
    Err(Error::Bug)
}

#[cfg(not(docsrs))]
pub(super) fn init_filter_graph(
    fg_index: usize,
    filter_desc: &str,
    hw_device: Option<String>,
    sws_opts: Option<String>,
    swr_opts: Option<String>,
) -> Result<FilterGraph> {
    let desc_cstr = CString::new(filter_desc)?;

    // fftools 0f5592cfc737: hardware devices must exist before fg_create's
    // probe parse, because some HW filters refuse to initialize without one.
    // ez-ffmpeg's equivalent ordering: register the graph's filter device
    // here at build time (it used to happen at filter-task startup, i.e.
    // after this probe had already run — and failed — for such graphs).
    if let Some(hw_device) = &hw_device {
        let err = init_filter_hw_device(hw_device);
        if err < 0 {
            // Keep the pre-move error shape: this used to surface from the
            // filter task as FilterGraph(ParseError(..)) at scheduler start;
            // only the timing moved to build(), not the variant callers
            // match on.
            return Err(Error::FilterGraph(FilterGraphOperationError::ParseError(
                FilterGraphParseError::from(err),
            )));
        }
    }

    unsafe {
        /* this graph is only used for determining the kinds of inputs
        and outputs we have, and is discarded on exit from this function */
        // Owned handle: `raw::FilterGraph`'s Drop frees the graph (and every
        // filter context it holds) on every return path below — including the
        // two `inouts_to_*_filters(..)?` early returns, which the hand-balanced
        // `avfilter_graph_free` calls used to miss, leaking the graph.
        let graph = crate::raw::FilterGraph::alloc().ok_or(FilterGraphParseError::OutOfMemory)?;
        (*graph.as_ptr()).nb_threads = 1;

        let mut seg = null_mut();
        let mut ret = avfilter_graph_segment_parse(graph.as_ptr(), desc_cstr.as_ptr(), 0, &mut seg);
        if ret < 0 {
            return Err(FilterGraphParseError::from(ret).into());
        }

        ret = avfilter_graph_segment_create_filters(seg, 0);
        if ret < 0 {
            avfilter_graph_segment_free(&mut seg);
            return Err(FilterGraphParseError::from(ret).into());
        }

        // Same injection point as the scheduler's graph_parse: the filters
        // exist but are not initialized yet, so a HW-flagged filter can still
        // receive its device — fftools 0f5592cfc737 gave the probe-only parse
        // this ability, and FFmpeg 8 filters may hard-require it in init.
        if let Some(dev) = hw_device_for_filter() {
            for i in 0..(*graph.as_ptr()).nb_filters {
                let f = *(*graph.as_ptr()).filters.add(i as usize);
                if (*(*f).filter).flags & AVFILTER_FLAG_HWDEVICE == 0 {
                    continue;
                }
                (*f).hw_device_ctx = av_buffer_ref(dev.device_ref());
                if (*f).hw_device_ctx.is_null() {
                    avfilter_graph_segment_free(&mut seg);
                    return Err(FilterGraphParseError::OutOfMemory.into());
                }
            }
        }

        #[cfg(not(docsrs))]
        {
            ret = graph_opts_apply(seg);
        }
        if ret < 0 {
            avfilter_graph_segment_free(&mut seg);
            return Err(FilterGraphParseError::from(ret).into());
        }

        let mut inputs = crate::raw::FilterInOut::empty();
        let mut outputs = crate::raw::FilterInOut::empty();
        ret = avfilter_graph_segment_apply(seg, 0, inputs.as_out_ptr(), outputs.as_out_ptr());
        avfilter_graph_segment_free(&mut seg);

        if ret < 0 {
            return Err(FilterGraphParseError::from(ret).into());
        }

        // `inputs`/`outputs` own the parsed AVFilterInOut lists; their Drop frees
        // them on every path below — the two `?` early returns included.
        let input_filters = inouts_to_input_filters(fg_index, inputs.as_ptr())?;
        let output_filters = inouts_to_output_filters(outputs.as_ptr())?;

        // Keep the zero-OUTPUTS check first so a closed zero-in/zero-out graph
        // (e.g. `color=...,nullsink`) keeps returning FilterZeroOutputs as before.
        if output_filters.is_empty() {
            return Err(FilterZeroOutputs);
        }

        // A source-only graph (e.g. `color=...`) has no input pads, so nothing
        // binds it to a demuxer and `unchoke_for_stream` would later index an empty
        // input list. Reject it up front, mirroring the zero-outputs guard (use a
        // lavfi Input for a pure generator instead of a filter_complex).
        if input_filters.is_empty() {
            return Err(FilterZeroInputs);
        }

        let filter_graph = FilterGraph::new(
            filter_desc.to_string(),
            input_filters,
            output_filters,
            sws_opts,
            swr_opts,
        );

        Ok(filter_graph)
    }
}

unsafe fn inouts_to_input_filters(
    fg_index: usize,
    inouts: *mut AVFilterInOut,
) -> Result<Vec<InputFilter>> {
    let mut cur = inouts;
    let mut filterinouts = Vec::new();
    let mut filter_index = 0;
    while !cur.is_null() {
        let linklabel = if (*cur).name.is_null() {
            ""
        } else {
            let linklabel = CStr::from_ptr((*cur).name);
            let result = linklabel.to_str();
            if result.is_err() {
                return Err(FilterDescUtf8);
            }
            result.unwrap()
        };

        let filter_ctx = (*cur).filter_ctx;
        let media_type = avfilter_pad_get_type((*filter_ctx).input_pads, (*cur).pad_idx);

        let pads = (*filter_ctx).input_pads;
        let nb_pads = (*filter_ctx).nb_inputs;

        let name = describe_filter_link(cur, filter_ctx, pads, nb_pads)?;

        let fallback = frame_alloc()?;

        let mut filter = InputFilter::new(linklabel.to_string(), media_type, name, fallback);
        filter.opts.name = format!("fg:{fg_index}:{filter_index}");
        filterinouts.push(filter);

        cur = (*cur).next;
        filter_index += 1;
    }
    Ok(filterinouts)
}

unsafe fn inouts_to_output_filters(inouts: *mut AVFilterInOut) -> Result<Vec<OutputFilter>> {
    let mut cur = inouts;
    let mut output_filters = Vec::new();
    while !cur.is_null() {
        let linklabel = if (*cur).name.is_null() {
            ""
        } else {
            let linklabel = CStr::from_ptr((*cur).name);
            let result = linklabel.to_str();
            if result.is_err() {
                return Err(FilterDescUtf8);
            }
            result.unwrap()
        };

        let filter_ctx = (*cur).filter_ctx;
        let media_type = avfilter_pad_get_type((*filter_ctx).output_pads, (*cur).pad_idx);

        let pads = (*filter_ctx).output_pads;
        let nb_pads = (*filter_ctx).nb_outputs;

        let name = describe_filter_link(cur, filter_ctx, pads, nb_pads)?;

        let filter = OutputFilter::new(linklabel.to_string(), media_type, name);
        output_filters.push(filter);

        cur = (*cur).next;
    }
    Ok(output_filters)
}

unsafe fn describe_filter_link(
    cur: *mut AVFilterInOut,
    filter_ctx: *mut AVFilterContext,
    pads: *mut AVFilterPad,
    nb_pads: c_uint,
) -> Result<String> {
    let filter = (*filter_ctx).filter;
    let name = (*filter).name;
    let name = CStr::from_ptr(name);
    let result = name.to_str();
    if result.is_err() {
        return Err(FilterNameUtf8);
    }
    let name = result.unwrap();

    let name = if nb_pads > 1 {
        name.to_string()
    } else {
        let pad_name = avfilter_pad_get_name(pads, (*cur).pad_idx);
        let pad_name = CStr::from_ptr(pad_name);
        let result = pad_name.to_str();
        if result.is_err() {
            return Err(FilterNameUtf8);
        }
        let pad_name = result.unwrap();
        format!("{name}:{pad_name}")
    };
    Ok(name)
}