ffmpeg-next 9.0.0

Safe FFmpeg wrapper (FFmpeg 4 compatible fork of the ffmpeg crate)
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
pub use crate::util::format::{Pixel, pixel};
pub use crate::util::format::{Sample, sample};
use crate::util::interrupt;

pub mod stream;

pub mod chapter;

pub mod context;
pub use self::context::Context;

pub mod format;
#[cfg(not(feature = "ffmpeg_5_0"))]
pub use self::format::list;
pub use self::format::{Flags, flag};
pub use self::format::{Input, Output};

pub mod network;

use std::ffi::{CStr, CString};
use std::path::Path;
use std::ptr;
use std::str::from_utf8_unchecked;

use crate::ffi::*;
use crate::{Dictionary, Error, Format};

#[cfg(not(feature = "ffmpeg_5_0"))]
pub fn register_all() {
    unsafe {
        av_register_all();
    }
}

#[cfg(not(feature = "ffmpeg_5_0"))]
pub fn register(format: &Format) {
    match *format {
        Format::Input(ref format) => unsafe {
            av_register_input_format(format.as_ptr() as *mut _);
        },

        Format::Output(ref format) => unsafe {
            av_register_output_format(format.as_ptr() as *mut _);
        },
    }
}

pub fn version() -> u32 {
    unsafe { avformat_version() }
}

pub fn configuration() -> &'static str {
    unsafe { from_utf8_unchecked(CStr::from_ptr(avformat_configuration()).to_bytes()) }
}

pub fn license() -> &'static str {
    unsafe { from_utf8_unchecked(CStr::from_ptr(avformat_license()).to_bytes()) }
}

// XXX: use to_cstring when stable
fn from_path<P: AsRef<Path> + ?Sized>(path: &P) -> CString {
    CString::new(path.as_ref().as_os_str().to_str().unwrap()).unwrap()
}

fn opt_cstring(s: Option<&str>) -> Result<Option<CString>, Error> {
    s.map(CString::new)
        .transpose()
        .map_err(|_| Error::Other { errno: EINVAL })
}

// NOTE: this will be better with specialization or anonymous return types
pub fn open<P: AsRef<Path> + ?Sized>(path: &P, format: &Format) -> Result<Context, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);

        match *format {
            Format::Input(ref format) => match avformat_open_input(
                &mut ps,
                path.as_ptr(),
                format.as_ptr() as *mut _,
                ptr::null_mut(),
            ) {
                0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                    r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))),
                    e => Err(Error::from(e)),
                },

                e => Err(Error::from(e)),
            },

            Format::Output(ref format) => match avformat_alloc_output_context2(
                &mut ps,
                format.as_ptr() as *mut _,
                ptr::null(),
                path.as_ptr(),
            ) {
                0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
                    0 => Ok(Context::Output(context::Output::wrap(ps))),
                    e => Err(Error::from(e)),
                },

                e => Err(Error::from(e)),
            },
        }
    }
}

pub fn open_with<P: AsRef<Path> + ?Sized>(
    path: &P,
    format: &Format,
    options: Dictionary,
) -> Result<Context, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);
        let mut opts = options.disown();

        match *format {
            Format::Input(ref format) => {
                let res = avformat_open_input(
                    &mut ps,
                    path.as_ptr(),
                    format.as_ptr() as *mut _,
                    &mut opts,
                );

                Dictionary::own(opts);

                match res {
                    0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                        r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))),
                        e => Err(Error::from(e)),
                    },

                    e => Err(Error::from(e)),
                }
            }

            Format::Output(ref format) => match avformat_alloc_output_context2(
                &mut ps,
                format.as_ptr() as *mut _,
                ptr::null(),
                path.as_ptr(),
            ) {
                0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
                    0 => Ok(Context::Output(context::Output::wrap(ps))),
                    e => Err(Error::from(e)),
                },

                e => Err(Error::from(e)),
            },
        }
    }
}

pub fn input<P: AsRef<Path> + ?Sized>(path: &P) -> Result<context::Input, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);

        match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) {
            0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                r if r >= 0 => Ok(context::Input::wrap(ps)),
                e => {
                    avformat_close_input(&mut ps);
                    Err(Error::from(e))
                }
            },

            e => Err(Error::from(e)),
        }
    }
}

pub fn input_with_dictionary<P: AsRef<Path> + ?Sized>(
    path: &P,
    options: Dictionary,
) -> Result<context::Input, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);
        let mut opts = options.disown();
        let res = avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), &mut opts);

        Dictionary::own(opts);

        match res {
            0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                r if r >= 0 => Ok(context::Input::wrap(ps)),
                e => {
                    avformat_close_input(&mut ps);
                    Err(Error::from(e))
                }
            },

            e => Err(Error::from(e)),
        }
    }
}

pub fn input_with_interrupt<P: AsRef<Path> + ?Sized, F>(
    path: &P,
    closure: F,
) -> Result<context::Input, Error>
where
    F: FnMut() -> bool + Send + 'static,
{
    unsafe {
        let mut ps = avformat_alloc_context();
        if ps.is_null() {
            return Err(Error::Other { errno: ENOMEM });
        }
        let path = from_path(path);
        let interrupt = interrupt::new(Box::new(closure));
        (*ps).interrupt_callback = interrupt.interrupt;

        match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) {
            0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                r if r >= 0 => Ok(context::Input::wrap_with_interrupt(ps, interrupt.guard)),
                e => {
                    avformat_close_input(&mut ps);
                    Err(Error::from(e))
                }
            },

            e => Err(Error::from(e)),
        }
    }
}

pub fn input_with_interrupt_and_dictionary<P: AsRef<Path> + ?Sized, F>(
    path: &P,
    closure: F,
    options: Dictionary,
) -> Result<context::Input, Error>
where
    F: FnMut() -> bool + Send + 'static,
{
    unsafe {
        let mut ps = avformat_alloc_context();
        if ps.is_null() {
            return Err(Error::Other { errno: ENOMEM });
        }
        let interrupt = interrupt::new(Box::new(closure));
        (*ps).interrupt_callback = interrupt.interrupt;
        let path = from_path(path);

        let mut opts = options.disown();
        let res = avformat_open_input(&raw mut ps, path.as_ptr(), ptr::null_mut(), &raw mut opts);
        Dictionary::own(opts);

        match res {
            0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                r if r >= 0 => Ok(context::Input::wrap_with_interrupt(ps, interrupt.guard)),
                e => {
                    avformat_close_input(&raw mut ps);
                    Err(Error::from(e))
                }
            },

            e => Err(Error::from(e)),
        }
    }
}
/// Opens an input from a readable `context::StreamIo` (created with
/// `StreamIo::from_read` or `StreamIo::from_read_seek`).
///
/// An optional filename helps with format detection; options configure the
/// format context. Fails with `EINVAL` if `custom_io` is a write context or
/// `filename` contains an interior NUL byte.
pub fn input_from_stream(
    custom_io: context::StreamIo,
    filename: Option<&str>,
    options: Option<Dictionary>,
) -> Result<context::Input, Error> {
    input_from_stream_impl(custom_io, filename, options, None)
}

/// Like [`input_from_stream`], with an interrupt callback FFmpeg polls to
/// cancel a stalled open or read. `closure` returns `true` to abort; a
/// cancelled blocking read then surfaces as `Error::Exit`. To resume the same
/// context afterward, re-arm the token and either seek (seekable streams) or
/// call [`context::Input::clear_interrupt`] (non-seekable streams).
///
/// Fails with `EINVAL` if `custom_io` is a write context or `filename`
/// contains an interior NUL byte.
pub fn input_from_stream_with_interrupt<F>(
    custom_io: context::StreamIo,
    filename: Option<&str>,
    options: Option<Dictionary>,
    closure: F,
) -> Result<context::Input, Error>
where
    F: FnMut() -> bool + Send + 'static,
{
    input_from_stream_impl(
        custom_io,
        filename,
        options,
        Some(interrupt::new(Box::new(closure))),
    )
}

/// Shared body for [`input_from_stream`] / [`input_from_stream_with_interrupt`].
///
/// When `interrupt` is present it is installed on the format context BEFORE
/// open (so a stalled probe/connect is cancellable) AND mirrored into the
/// `StreamIo` opaque — both in one place, so the mirror is impossible to forget
/// when adding another `_with_interrupt` variant. The mirror is required
/// because FFmpeg's custom-AVIO read path (`fill_buffer` → `read_packet`) never
/// polls `AVFormatContext.interrupt_callback` itself — unlike its URL
/// protocols' `retry_transfer_wrapper` — so the `StreamIo` read/write/seek
/// callbacks poll the mirrored copy at the top of each attempt (see
/// `StreamIo::set_interrupt`).
fn input_from_stream_impl(
    mut custom_io: context::StreamIo,
    filename: Option<&str>,
    options: Option<Dictionary>,
    interrupt: Option<interrupt::Interrupt>,
) -> Result<context::Input, Error> {
    if custom_io.is_writable() {
        return Err(Error::Other { errno: EINVAL });
    }

    let filename = opt_cstring(filename)?;
    let filename_ptr = filename.as_ref().map_or(ptr::null(), |f| f.as_ptr());

    unsafe {
        let mut ps = avformat_alloc_context();
        if ps.is_null() {
            return Err(Error::Other { errno: ENOMEM });
        }
        if let Some(ref it) = interrupt {
            (*ps).interrupt_callback = it.interrupt;
            custom_io.set_interrupt(it.interrupt);
        }
        (*ps).pb = custom_io.as_mut_ptr();
        (*ps).flags |= AVFMT_FLAG_CUSTOM_IO;

        let result = if let Some(opts) = options {
            let mut opts = opts.disown();
            let res = avformat_open_input(&mut ps, filename_ptr, ptr::null_mut(), &mut opts);
            Dictionary::own(opts);
            res
        } else {
            avformat_open_input(&mut ps, filename_ptr, ptr::null_mut(), ptr::null_mut())
        };

        match result {
            0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
                r if r >= 0 => Ok(match interrupt {
                    Some(it) => {
                        context::Input::wrap_with_custom_io_and_interrupt(ps, custom_io, it.guard)
                    }
                    None => context::Input::wrap_with_custom_io(ps, custom_io),
                }),
                e => {
                    avformat_close_input(&mut ps);
                    Err(Error::from(e))
                }
            },

            e => Err(Error::from(e)),
        }
    }
}

pub fn output<P: AsRef<Path> + ?Sized>(path: &P) -> Result<context::Output, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);

        match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) {
            0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
                0 => Ok(context::Output::wrap(ps)),
                e => Err(Error::from(e)),
            },

            e => Err(Error::from(e)),
        }
    }
}

pub fn output_with<P: AsRef<Path> + ?Sized>(
    path: &P,
    options: Dictionary,
) -> Result<context::Output, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);
        let mut opts = options.disown();

        match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) {
            0 => {
                let res = avio_open2(
                    &mut (*ps).pb,
                    path.as_ptr(),
                    AVIO_FLAG_WRITE,
                    ptr::null(),
                    &mut opts,
                );

                Dictionary::own(opts);

                match res {
                    0 => Ok(context::Output::wrap(ps)),
                    e => Err(Error::from(e)),
                }
            }

            e => Err(Error::from(e)),
        }
    }
}

pub fn output_as<P: AsRef<Path> + ?Sized>(
    path: &P,
    format: &str,
) -> Result<context::Output, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);
        let format = CString::new(format).unwrap();

        match avformat_alloc_output_context2(
            &mut ps,
            ptr::null_mut(),
            format.as_ptr(),
            path.as_ptr(),
        ) {
            0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
                0 => Ok(context::Output::wrap(ps)),
                e => Err(Error::from(e)),
            },

            e => Err(Error::from(e)),
        }
    }
}

pub fn output_as_with<P: AsRef<Path> + ?Sized>(
    path: &P,
    format: &str,
    options: Dictionary,
) -> Result<context::Output, Error> {
    unsafe {
        let mut ps = ptr::null_mut();
        let path = from_path(path);
        let format = CString::new(format).unwrap();
        let mut opts = options.disown();

        match avformat_alloc_output_context2(
            &mut ps,
            ptr::null_mut(),
            format.as_ptr(),
            path.as_ptr(),
        ) {
            0 => {
                let res = avio_open2(
                    &mut (*ps).pb,
                    path.as_ptr(),
                    AVIO_FLAG_WRITE,
                    ptr::null(),
                    &mut opts,
                );

                Dictionary::own(opts);

                match res {
                    0 => Ok(context::Output::wrap(ps)),
                    e => Err(Error::from(e)),
                }
            }

            e => Err(Error::from(e)),
        }
    }
}

/// Creates an output context that writes to a writable `context::StreamIo`
/// (created with `StreamIo::from_write` or `StreamIo::from_write_seek`).
///
/// The output format is inferred from `filename` or given explicitly via
/// `format`; most muxers need a seekable stream for well-formed output. Call
/// `write_trailer` before dropping the returned context — dropping only
/// flushes what the muxer already emitted, it cannot finalize the file.
/// Fails with `EINVAL` if `custom_io` is not a write context, if `filename` /
/// `format` contain an interior NUL byte, or if the resolved muxer does its
/// own I/O and would never write to the stream (`AVFMT_NOFILE` formats like
/// `image2` or output devices).
pub fn output_to_stream(
    mut custom_io: context::StreamIo,
    filename: Option<&str>,
    format: Option<&str>,
) -> Result<context::Output, Error> {
    if !custom_io.is_writable() {
        return Err(Error::Other { errno: EINVAL });
    }

    let filename = opt_cstring(filename)?;
    let filename_ptr = filename.as_ref().map_or(ptr::null(), |f| f.as_ptr());

    let format = opt_cstring(format)?;
    let format_ptr = format.as_ref().map_or(ptr::null(), |f| f.as_ptr());

    unsafe {
        let mut ps = ptr::null_mut();

        match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), format_ptr, filename_ptr) {
            0 => {
                // AVFMT_NOFILE muxers (image2's one-file-per-frame, devices,
                // ...) do their own I/O, and `AVFormatContext.pb` is
                // documented to stay NULL for them; the caller's stream would
                // silently never receive the muxed output.
                if (*(*ps).oformat).flags & AVFMT_NOFILE != 0 {
                    avformat_free_context(ps);
                    return Err(Error::Other { errno: EINVAL });
                }

                (*ps).pb = custom_io.as_mut_ptr();
                (*ps).flags |= AVFMT_FLAG_CUSTOM_IO;

                Ok(context::Output::wrap_with_custom_io(ps, custom_io))
            }

            e => Err(Error::from(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn input_with_interrupt_and_dictionary_accepts_str_path() {
        let result = input_with_interrupt_and_dictionary(
            "/ffmpeg-next-input-does-not-exist",
            || false,
            Dictionary::new(),
        );

        assert!(result.is_err());
    }
}