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
// Copyright (C) 2021 Scott Lamb <slamb@slamb.org>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::convert::TryFrom;
use std::ffi::CStr;
use std::ptr;

//#[link(name = "avutil")]
extern "C" {
    pub(crate) fn av_version_info() -> *mut libc::c_char;
    pub(crate) fn avutil_version() -> libc::c_int;
    pub(crate) fn avutil_configuration() -> *mut libc::c_char;

    #[cfg(test)]
    pub(crate) fn av_log(
        avcl: *const libc::c_void,
        level: libc::c_int,
        fmt: *const libc::c_char,
        ...
    );

    fn av_strerror(e: libc::c_int, b: *mut libc::c_char, s: libc::size_t) -> libc::c_int;
    fn av_dict_count(d: *const AVDictionary) -> libc::c_int;
    fn av_dict_get(
        d: *const AVDictionary,
        key: *const libc::c_char,
        prev: *mut AVDictionaryEntry,
        flags: libc::c_int,
    ) -> *mut AVDictionaryEntry;
    fn av_dict_set(
        d: *mut *mut AVDictionary,
        key: *const libc::c_char,
        value: *const libc::c_char,
        flags: libc::c_int,
    ) -> libc::c_int;
    fn av_dict_free(d: *mut *mut AVDictionary);
    fn av_frame_alloc() -> *mut AVFrame;
    fn av_frame_free(f: *mut *mut AVFrame);
    fn av_get_pix_fmt_name(fmt: libc::c_int) -> *const libc::c_char;
    fn av_malloc(len: usize) -> *mut libc::c_void;
    fn av_free(ptr: *mut libc::c_void);
}

pub(crate) struct Alloc(ptr::NonNull<libc::c_void>);

impl Alloc {
    pub(crate) fn new(len: usize) -> Result<Self, Error> {
        Ok(Alloc(
            ptr::NonNull::new(unsafe { av_malloc(len) }).ok_or_else(Error::enomem)?,
        ))
    }

    pub(crate) fn as_ptr(&mut self) -> *mut libc::c_void {
        self.0.as_ptr()
    }
}

impl Drop for Alloc {
    fn drop(&mut self) {
        unsafe { av_free(self.0.as_ptr()) }
    }
}

//#[link(name = "wrapper")]
extern "C" {
    pub(crate) static moonfire_ffmpeg_compiled_libavutil_version: libc::c_int;
    static moonfire_ffmpeg_av_dict_ignore_suffix: libc::c_int;
    pub(crate) static moonfire_ffmpeg_av_nopts_value: i64;

    static moonfire_ffmpeg_averror_eof: libc::c_int;
    static moonfire_ffmpeg_averror_enomem: libc::c_int;
    static moonfire_ffmpeg_averror_enosys: libc::c_int;
    static moonfire_ffmpeg_averror_decoder_not_found: libc::c_int;
    static moonfire_ffmpeg_averror_invalid_data: libc::c_int;
    static moonfire_ffmpeg_averror_unknown: libc::c_int;

    static moonfire_ffmpeg_avmedia_type_audio: libc::c_int;
    static moonfire_ffmpeg_avmedia_type_data: libc::c_int;
    static moonfire_ffmpeg_avmedia_type_video: libc::c_int;

    static moonfire_ffmpeg_pix_fmt_rgb24: libc::c_int;
    static moonfire_ffmpeg_pix_fmt_bgr24: libc::c_int;

    fn moonfire_ffmpeg_frame_image_alloc(
        f: *mut AVFrame,
        dims: *const ImageDimensions,
    ) -> libc::c_int;
    pub(crate) fn moonfire_ffmpeg_frame_stuff(frame: *const AVFrame, stuff: *mut FrameStuff);
}

// No accessors here; seems reasonable to assume ABI stability of this simple struct.
#[repr(C)]
struct AVDictionaryEntry {
    key: *mut libc::c_char,
    value: *mut libc::c_char,
}

// Likewise, seems reasonable to assume this struct has a stable ABI.
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct Rational {
    // aka AVRational
    pub num: libc::c_int,
    pub den: libc::c_int,
}

// No ABI stability assumption here; use heap allocation/deallocation and accessors only.
#[repr(C)]
struct AVDictionary {
    _private: [u8; 0],
}
#[repr(C)]
pub(crate) struct AVFrame {
    _private: [u8; 0],
}

#[repr(C)]
pub(crate) struct FrameStuff {
    dims: ImageDimensions,
    pub(crate) data: *const *mut u8,
    pub(crate) linesizes: *const libc::c_int,
    pts: i64,
}

#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct VideoParameters {
    width: libc::c_int,
    height: libc::c_int,
    sample_aspect_ratio: Rational,
    pix_fmt: PixelFormat,
    time_base: Rational,
}

#[derive(Copy, Clone, Debug)]
#[repr(transparent)]
pub struct MediaType(libc::c_int);

impl MediaType {
    pub fn is_audio(self) -> bool {
        self.0 == unsafe { moonfire_ffmpeg_avmedia_type_audio }
    }

    pub fn is_data(self) -> bool {
        self.0 == unsafe { moonfire_ffmpeg_avmedia_type_data }
    }

    pub fn is_video(self) -> bool {
        self.0 == unsafe { moonfire_ffmpeg_avmedia_type_video }
    }
}

pub struct VideoFrame {
    pub(crate) frame: ptr::NonNull<AVFrame>,
    pub(crate) stuff: FrameStuff,
}

pub struct Plane<'f> {
    pub data: &'f [u8],
    pub linesize: usize,
    pub width: usize,
    pub height: usize,
}

impl VideoFrame {
    /// Creates a new `VideoFrame` which is empty: no allocated storage (reference-counted or
    /// otherwise). Can be filled via `DecodeContext::decode_video`.
    pub fn empty() -> Result<Self, Error> {
        let frame = ptr::NonNull::new(unsafe { av_frame_alloc() }).ok_or_else(Error::enomem)?;
        Ok(VideoFrame {
            frame,
            stuff: FrameStuff {
                dims: ImageDimensions {
                    width: 0,
                    height: 0,
                    pix_fmt: PixelFormat(-1),
                },
                data: ptr::null(),
                linesizes: ptr::null(),
                pts: 0,
            },
        })
    }

    /// Creates a new `VideoFrame` with an owned (not reference-counted) buffer of the specified
    /// dimensions.
    pub fn owned(dims: ImageDimensions) -> Result<Self, Error> {
        let mut frame = VideoFrame::empty()?;
        Error::wrap(unsafe { moonfire_ffmpeg_frame_image_alloc(frame.frame.as_mut(), &dims) })?;
        unsafe { moonfire_ffmpeg_frame_stuff(frame.frame.as_ptr(), &mut frame.stuff) };
        Ok(frame)
    }

    pub fn plane(&self, plane: usize) -> Plane {
        assert!(plane < 8);
        let plane_off = isize::try_from(plane).unwrap();
        let d = unsafe { *self.stuff.data.offset(plane_off) };
        let l = unsafe { *self.stuff.linesizes.offset(plane_off) };
        assert!(!d.is_null());
        assert!(l > 0);
        let l = l as usize;
        let width = self.stuff.dims.width as usize;
        let height = self.stuff.dims.height as usize;
        Plane {
            data: unsafe { std::slice::from_raw_parts(d, l * height) },
            linesize: l,
            width,
            height,
        }
    }

    pub fn dims(&self) -> ImageDimensions {
        self.stuff.dims
    }
    pub fn pts(&self) -> i64 {
        self.stuff.pts
    }
}

impl Drop for VideoFrame {
    fn drop(&mut self) {
        unsafe {
            let mut f = self.frame.as_ptr();
            av_frame_free(&mut f);
            // This leaves self.frame dangling, but it's being dropped.
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct PixelFormat(libc::c_int);

impl PixelFormat {
    pub fn rgb24() -> Self {
        PixelFormat(unsafe { moonfire_ffmpeg_pix_fmt_rgb24 })
    }
    pub fn bgr24() -> Self {
        PixelFormat(unsafe { moonfire_ffmpeg_pix_fmt_bgr24 })
    }
}

impl std::fmt::Debug for PixelFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "PixelFormat({} /* {} */)", self.0, self)
    }
}

impl std::fmt::Display for PixelFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let s = unsafe {
            let n = av_get_pix_fmt_name(self.0);
            if n.is_null() {
                return write!(f, "PixelFormat({})", self.0);
            }
            CStr::from_ptr(n)
        };
        f.write_str(&s.to_string_lossy())
    }
}

#[derive(Copy, Clone)]
pub struct Error(libc::c_int);

impl Error {
    pub fn eof() -> Self {
        Error(unsafe { moonfire_ffmpeg_averror_eof })
    }
    pub fn enomem() -> Self {
        Error(unsafe { moonfire_ffmpeg_averror_enomem })
    }
    pub fn enosys() -> Self {
        Error(unsafe { moonfire_ffmpeg_averror_enosys })
    }
    pub fn unknown() -> Self {
        Error(unsafe { moonfire_ffmpeg_averror_unknown })
    }
    pub fn decoder_not_found() -> Self {
        Error(unsafe { moonfire_ffmpeg_averror_decoder_not_found })
    }
    pub fn invalid_data() -> Self {
        Error(unsafe { moonfire_ffmpeg_averror_invalid_data })
    }

    /// Wraps the given return code as a Result: positive values are propagated through; negative
    /// values are turned into an `Error`.
    pub(crate) fn wrap(raw: libc::c_int) -> Result<libc::c_int, Error> {
        if raw < 0 {
            return Err(Error(raw));
        }
        Ok(raw)
    }

    /// Returns the error value, which is guaranteed to be < 0.
    pub(crate) fn get(self) -> libc::c_int {
        self.0
    }

    pub fn is_eof(self) -> bool {
        self.0 == unsafe { moonfire_ffmpeg_averror_eof }
    }
}

impl std::error::Error for Error {}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Error({} /* {} */)", self.0, self)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        const ARRAYLEN: usize = 64;
        let mut buf = [0; ARRAYLEN];
        let s = unsafe {
            // Note av_strerror uses strlcpy, so it guarantees a trailing NUL byte.
            av_strerror(self.0, buf.as_mut_ptr(), ARRAYLEN);
            CStr::from_ptr(buf.as_ptr())
        };
        f.write_str(&s.to_string_lossy())
    }
}

#[repr(transparent)]
pub struct Dictionary(*mut AVDictionary);

impl Dictionary {
    pub fn new() -> Dictionary {
        Dictionary(ptr::null_mut())
    }
    pub fn size(&self) -> usize {
        (unsafe { av_dict_count(self.0) }) as usize
    }
    pub fn empty(&self) -> bool {
        self.size() == 0
    }
    pub fn set(&mut self, key: &CStr, value: &CStr) -> Result<(), Error> {
        Error::wrap(unsafe { av_dict_set(&mut self.0, key.as_ptr(), value.as_ptr(), 0) })?;
        Ok(())
    }
}

impl Default for Dictionary {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for Dictionary {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let mut ent = ptr::null_mut();
        let mut first = true;
        loop {
            unsafe {
                let c = 0;
                ent = av_dict_get(self.0, &c, ent, moonfire_ffmpeg_av_dict_ignore_suffix);
                if ent.is_null() {
                    break;
                }
                if first {
                    first = false;
                } else {
                    write!(f, ", ")?;
                }
                write!(
                    f,
                    "{}={}",
                    CStr::from_ptr((*ent).key).to_string_lossy(),
                    CStr::from_ptr((*ent).value).to_string_lossy()
                )?;
            }
        }
        Ok(())
    }
}

impl Drop for Dictionary {
    fn drop(&mut self) {
        unsafe { av_dict_free(&mut self.0) }
    }
}

// Must match moonfire_ffmpeg_image_dimensions.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C)]
pub struct ImageDimensions {
    pub width: libc::c_int,
    pub height: libc::c_int,
    pub pix_fmt: PixelFormat,
}

impl std::fmt::Display for ImageDimensions {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}x{}/{}", self.width, self.height, self.pix_fmt)
    }
}

// const AV_LOG_PANIC: libc::c_int = 0;
// const AV_LOG_FATAL: libc::c_int = 8;
pub(crate) const AV_LOG_ERROR: libc::c_int = 16;
pub(crate) const AV_LOG_WARNING: libc::c_int = 24;
pub(crate) const AV_LOG_INFO: libc::c_int = 32;
// const AV_LOG_VERBOSE: libc::c_int = 40;
pub(crate) const AV_LOG_DEBUG: libc::c_int = 48;
// const AV_LOG_TRACE: libc::c_int = 56;

pub(crate) fn convert_level(level: libc::c_int) -> log::Level {
    // Match av_log_default_callback.
    let level = if level >= 0 { level & 0xFF } else { level };

    if level <= AV_LOG_ERROR {
        log::Level::Error
    } else if level <= AV_LOG_WARNING {
        log::Level::Warn
    } else if level <= AV_LOG_INFO {
        log::Level::Info
    } else if level <= AV_LOG_DEBUG {
        log::Level::Debug
    } else {
        log::Level::Trace
    }
}

#[cfg(test)]
mod tests {
    use super::Error;
    use std::ffi::CString;

    #[test]
    fn test_error() {
        let eof_formatted = format!("{}", Error::eof());
        assert!(
            eof_formatted.contains("End of file"),
            "eof formatted is: {}",
            eof_formatted
        );
        let eof_debug = format!("{:?}", Error::eof());
        assert!(
            eof_debug.contains("End of file"),
            "eof debug is: {}",
            eof_debug
        );

        // Errors should be round trippable to a CString. (This will fail if they contain NUL
        // bytes.)
        CString::new(eof_formatted).unwrap();
    }
}