threers-codec 0.1.0

Pure-Rust media codecs: H.264/HEVC/VP9 encoders, H.264/HEVC/VP9/AV1 decoders, AAC/MP3/Opus/Vorbis/FLAC/WAV decoders, AAC-LC and MP3 encoders, MP4/WebM/Matroska/Ogg, GIF/APNG, captions, and VideoToolbox acceleration on macOS
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Hardware video *decoding* in-process, through VideoToolbox.
//!
//! The mirror of [`videotoolbox`](crate::videotoolbox), and there for the same
//! reason. Getting a clip *into* a render meant spawning ffmpeg and reading raw
//! frames off a pipe: 8 MB a frame at 1080p, 99 MB at 8K, written by one
//! process and read by another, plus a process boundary in the middle of the
//! frame loop. The system decoder is the same hardware block ffmpeg's
//! `h264_videotoolbox` reaches, and it will hand the frame over directly.
//!
//! Pair it with [`mp4_demux`](crate::mp4_demux), which says where each
//! coded frame is and carries the `avcC`/`hvcC` a session needs to start:
//!
//! ```no_run
//! # #[cfg(all(feature = "videotoolbox", target_os = "macos"))] {
//! use threers_codec::mp4_demux::demux_video;
//! use threers_codec::videotoolbox_decode::VideoToolboxDecoder;
//!
//! let file = std::fs::read("clip.mp4").unwrap();
//! let track = demux_video(&file).unwrap();
//! let mut dec = VideoToolboxDecoder::new(&track).unwrap();
//! for s in &track.samples {
//!     let bytes = &file[s.offset as usize..][..s.size as usize];
//!     dec.push(bytes, s.pts, s.dts, s.duration as i64).unwrap();
//!     // Decode order is not display order, so ask for a frame by its own
//!     // presentation time rather than assuming one came back per push.
//!     if let Some(bgra) = dec.take(s.pts) {
//!         let _ = bgra; // width * height * 4
//!     }
//! }
//! # }
//! ```
//!
//! Frames come back as BGRA because VideoToolbox will do the YUV conversion on
//! the way out if asked, and the hardware does it for nothing. A caller with a
//! GPU to convert on asks for the planes instead,
//! [`new_planar`](VideoToolboxDecoder::new_planar) and
//! [`take_packed`](VideoToolboxDecoder::take_packed): NV12 as a
//! [`PackedFrame`], the decoder's own format, so VideoToolbox converts
//! nothing, and less than half the bytes of BGRA.

#![cfg(all(feature = "videotoolbox", target_os = "macos"))]

use std::ffi::c_void;
use std::ptr;
use std::sync::Mutex;

use crate::decode::{ColorInfo, DecodedFrame, PackedFrame};
use crate::mp4_demux::{TrackCodec, VideoTrack};

type OSStatus = i32;
type CFAllocatorRef = *const c_void;
type CFDictionaryRef = *const c_void;
type CFStringRef = *const c_void;
type CFNumberRef = *const c_void;
type CVPixelBufferRef = *mut c_void;
type CMSampleBufferRef = *mut c_void;
type CMBlockBufferRef = *mut c_void;
type CMFormatDescriptionRef = *const c_void;
type VTDecompressionSessionRef = *mut c_void;

const K_CF_NUMBER_SINT32: i32 = 3;
/// `kCVPixelFormatType_32BGRA`.
const PIXEL_FORMAT_BGRA: i32 = 0x4247_5241;
/// `kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange` (`420v`): NV12, what
/// the hardware decodes to.
const PIXEL_FORMAT_NV12: i32 = 0x3432_3076;

#[repr(C)]
#[derive(Clone, Copy)]
struct CMTime {
    value: i64,
    timescale: i32,
    flags: u32,
    epoch: i64,
}

impl CMTime {
    fn new(value: i64, timescale: u32) -> Self {
        CMTime {
            value,
            timescale: timescale as i32,
            flags: 1, // kCMTimeFlags_Valid
            epoch: 0,
        }
    }
}

/// `kVTDecodeFrame_EnableTemporalProcessing`.
const DECODE_ENABLE_TEMPORAL: u32 = 1 << 3;

/// `CMSampleTimingInfo`. Without one of these a sample buffer carries no
/// timestamps, the callback gets `kCMTimeInvalid` back, and there is no way to
/// tell which picture is which — which matters the moment a stream has
/// B-frames, because then the order they decode in is not the order they show
/// in.
#[repr(C)]
#[derive(Clone, Copy)]
struct CMSampleTimingInfo {
    duration: CMTime,
    presentation: CMTime,
    decode: CMTime,
}

#[repr(C)]
struct VTDecompressionOutputCallbackRecord {
    callback: Option<
        extern "C" fn(*mut c_void, *mut c_void, OSStatus, u32, CVPixelBufferRef, CMTime, CMTime),
    >,
    ref_con: *mut c_void,
}

// One block per framework rather than four `#[link]` attributes on one. Both
// link the same libraries, but the split records which framework each symbol
// actually comes from — and a repeated attribute on a single item reads like a
// mistake.
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
    fn CFRelease(cf: *const c_void);
    fn CFNumberCreate(alloc: CFAllocatorRef, ty: i32, value: *const c_void) -> CFNumberRef;
    fn CFDictionaryCreate(
        alloc: CFAllocatorRef,
        keys: *const *const c_void,
        values: *const *const c_void,
        count: isize,
        key_cb: *const c_void,
        value_cb: *const c_void,
    ) -> CFDictionaryRef;
    fn CFDataCreate(alloc: CFAllocatorRef, bytes: *const u8, len: isize) -> *const c_void;
    fn CFStringCreateWithCString(
        alloc: CFAllocatorRef,
        s: *const std::ffi::c_char,
        encoding: u32,
    ) -> CFStringRef;
    static kCFAllocatorNull: CFAllocatorRef;
    static kCFTypeDictionaryKeyCallBacks: c_void;
    static kCFTypeDictionaryValueCallBacks: c_void;
}

#[link(name = "CoreMedia", kind = "framework")]
unsafe extern "C" {
    fn CMVideoFormatDescriptionCreateFromH264ParameterSets(
        alloc: CFAllocatorRef,
        count: usize,
        pointers: *const *const u8,
        sizes: *const usize,
        nal_header_len: i32,
        out: *mut CMFormatDescriptionRef,
    ) -> OSStatus;
    fn CMVideoFormatDescriptionCreateFromHEVCParameterSets(
        alloc: CFAllocatorRef,
        count: usize,
        pointers: *const *const u8,
        sizes: *const usize,
        nal_header_len: i32,
        extensions: CFDictionaryRef,
        out: *mut CMFormatDescriptionRef,
    ) -> OSStatus;

    fn CMVideoFormatDescriptionCreate(
        alloc: CFAllocatorRef,
        codec: u32,
        width: i32,
        height: i32,
        extensions: CFDictionaryRef,
        out: *mut CMFormatDescriptionRef,
    ) -> OSStatus;
    static kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms: CFStringRef;

    fn CMBlockBufferCreateWithMemoryBlock(
        alloc: CFAllocatorRef,
        memory: *mut c_void,
        length: usize,
        block_alloc: CFAllocatorRef,
        custom: *const c_void,
        offset: usize,
        data_len: usize,
        flags: u32,
        out: *mut CMBlockBufferRef,
    ) -> OSStatus;
    fn CMSampleBufferCreateReady(
        alloc: CFAllocatorRef,
        block: CMBlockBufferRef,
        format: CMFormatDescriptionRef,
        num_samples: isize,
        num_timings: isize,
        timings: *const CMSampleTimingInfo,
        num_sizes: isize,
        sizes: *const usize,
        out: *mut CMSampleBufferRef,
    ) -> OSStatus;
}

#[link(name = "VideoToolbox", kind = "framework")]
unsafe extern "C" {
    fn VTRegisterSupplementalVideoDecoderIfAvailable(codec: u32);
    fn VTDecompressionSessionCreate(
        alloc: CFAllocatorRef,
        format: CMFormatDescriptionRef,
        spec: CFDictionaryRef,
        dest_attrs: CFDictionaryRef,
        output: *const VTDecompressionOutputCallbackRecord,
        out: *mut VTDecompressionSessionRef,
    ) -> OSStatus;
    fn VTDecompressionSessionDecodeFrame(
        session: VTDecompressionSessionRef,
        sample: CMSampleBufferRef,
        flags: u32,
        source_ref_con: *mut c_void,
        info_out: *mut u32,
    ) -> OSStatus;
    fn VTDecompressionSessionWaitForAsynchronousFrames(
        session: VTDecompressionSessionRef,
    ) -> OSStatus;
    fn VTDecompressionSessionInvalidate(session: VTDecompressionSessionRef);
}

#[link(name = "CoreVideo", kind = "framework")]
unsafe extern "C" {
    static kCVPixelBufferPixelFormatTypeKey: CFStringRef;

    fn CVPixelBufferLockBaseAddress(pb: CVPixelBufferRef, flags: u64) -> i32;
    fn CVPixelBufferUnlockBaseAddress(pb: CVPixelBufferRef, flags: u64) -> i32;
    fn CVPixelBufferGetBaseAddress(pb: CVPixelBufferRef) -> *mut c_void;
    fn CVPixelBufferGetBytesPerRow(pb: CVPixelBufferRef) -> usize;
    fn CVPixelBufferGetWidth(pb: CVPixelBufferRef) -> usize;
    fn CVPixelBufferGetHeight(pb: CVPixelBufferRef) -> usize;
    fn CVPixelBufferGetPlaneCount(pb: CVPixelBufferRef) -> usize;
    fn CVPixelBufferGetBaseAddressOfPlane(pb: CVPixelBufferRef, plane: usize) -> *mut c_void;
    fn CVPixelBufferGetBytesPerRowOfPlane(pb: CVPixelBufferRef, plane: usize) -> usize;
    fn CVPixelBufferGetWidthOfPlane(pb: CVPixelBufferRef, plane: usize) -> usize;
    fn CVPixelBufferGetHeightOfPlane(pb: CVPixelBufferRef, plane: usize) -> usize;
}

fn cfnum(v: i32) -> CFNumberRef {
    unsafe {
        CFNumberCreate(
            ptr::null(),
            K_CF_NUMBER_SINT32,
            &v as *const i32 as *const c_void,
        )
    }
}

/// What the decode callback leaves behind.
///
/// A queue and not a single frame, because the decoder hands pictures back in
/// the order it decoded them and a stream with B-frames does not decode in the
/// order it displays. The caller asks for a presentation time and takes it out
/// when it arrives.
#[derive(Default)]
struct Sink {
    /// `(presentation time, picture)`, in whatever order they came.
    ready: Vec<(i64, Picture)>,
    err: Option<String>,
    /// The session was asked for planes, not BGRA.
    planar: bool,
    /// Where the planes' buffers come from.
    pool: crate::bytes::FramePool,
}

/// One decoded picture, as the session was asked to give it.
enum Picture {
    /// Tightly packed BGRA.
    Bgra(Vec<u8>),
    /// NV12.
    Planes(PackedFrame),
}

extern "C" fn on_decoded(
    ref_con: *mut c_void,
    _source: *mut c_void,
    status: OSStatus,
    _flags: u32,
    image: CVPixelBufferRef,
    pts: CMTime,
    _dur: CMTime,
) {
    if ref_con.is_null() {
        return;
    }
    let shared = unsafe { &*(ref_con as *const Mutex<Sink>) };
    let Ok(mut sink) = shared.lock() else { return };
    if status != 0 {
        sink.err = Some(format!("decode callback status {status}"));
        return;
    }
    if image.is_null() {
        // A dropped frame, not an error — the session simply had nothing to
        // hand back for this one.
        return;
    }
    unsafe {
        if CVPixelBufferLockBaseAddress(image, 1) != 0 {
            sink.err = Some("could not lock the decoded pixel buffer".into());
            return;
        }
        let w = CVPixelBufferGetWidth(image);
        let h = CVPixelBufferGetHeight(image);
        if sink.planar {
            if let Some(frame) = planes(image, w, h, &sink.pool) {
                sink.ready.push((pts.value, Picture::Planes(frame)));
            }
            CVPixelBufferUnlockBaseAddress(image, 1);
            return;
        }
        let stride = CVPixelBufferGetBytesPerRow(image);
        let base = CVPixelBufferGetBaseAddress(image) as *const u8;
        if !base.is_null() && w > 0 && h > 0 {
            let mut frame = vec![0u8; w * h * 4];
            // Row by row: the buffer is padded to the hardware's stride, and a
            // straight copy of `h * stride` would carry the padding into the
            // picture and shear it.
            for y in 0..h {
                let src = base.add(y * stride);
                let dst = frame.as_mut_ptr().add(y * w * 4);
                ptr::copy_nonoverlapping(src, dst, w * 4);
            }
            sink.ready.push((pts.value, Picture::Bgra(frame)));
        }
        CVPixelBufferUnlockBaseAddress(image, 1);
    }
}

/// A locked NV12 buffer's two planes, row by row past the hardware's
/// padding: a copy, and nothing else.
///
/// # Safety
/// `image` must be a locked bi-planar pixel buffer.
unsafe fn planes(
    image: CVPixelBufferRef,
    w: usize,
    h: usize,
    pool: &crate::bytes::FramePool,
) -> Option<PackedFrame> {
    if w == 0 || h == 0 || unsafe { CVPixelBufferGetPlaneCount(image) } != 2 {
        return None;
    }
    let mut out: [Vec<u8>; 2] = [
        pool.take(w * h),
        pool.take(w.div_ceil(2) * 2 * h.div_ceil(2)),
    ];
    for (i, plane) in out.iter_mut().enumerate() {
        // Luma; then Cb and Cr side by side, half as many rows.
        let (row, rows) = if i == 0 {
            (w, h)
        } else {
            (w.div_ceil(2) * 2, h.div_ceil(2))
        };
        let base = unsafe { CVPixelBufferGetBaseAddressOfPlane(image, i) } as *const u8;
        let stride = unsafe { CVPixelBufferGetBytesPerRowOfPlane(image, i) };
        let samples_across = if i == 0 { w } else { w.div_ceil(2) };
        if base.is_null()
            || unsafe { CVPixelBufferGetWidthOfPlane(image, i) } < samples_across
            || unsafe { CVPixelBufferGetHeightOfPlane(image, i) } < rows
            || stride < row
        {
            return None;
        }
        plane.reserve(row * rows);
        for y in 0..rows {
            plane.extend_from_slice(unsafe {
                std::slice::from_raw_parts(base.add(y * stride), row)
            });
        }
    }
    let [y, uv] = out;
    Some(PackedFrame {
        width: w as u32,
        height: h as u32,
        bit_depth: 8,
        y,
        uv,
        // The session keeps the stream's matrix; which it is is not read
        // back here, so the usual guess: BT.709 from 720 lines up.
        color: ColorInfo::from_vui(None, false, h as u32),
    })
}

/// Split an `avcC` into its SPS and PPS, and report the NAL length prefix.
///
/// Layout is fixed: a version byte, three of profile/compatibility/level, then
/// `0xFC | (lengthSizeMinusOne)`, then `0xE0 | numSPS` and each set behind a
/// 16-bit length, then a count byte and the PPSs the same way.
fn split_avcc(cfg: &[u8]) -> Result<(Vec<(usize, usize)>, i32), String> {
    if cfg.len() < 7 {
        return Err("avcC too short".into());
    }
    let nal_len = (cfg[4] & 0x03) as i32 + 1;
    let mut sets = Vec::new();
    let mut at = 5usize;
    for round in 0..2 {
        let count = if round == 0 {
            let n = (cfg[at] & 0x1F) as usize;
            at += 1;
            n
        } else {
            if at >= cfg.len() {
                break;
            }
            let n = cfg[at] as usize;
            at += 1;
            n
        };
        for _ in 0..count {
            if at + 2 > cfg.len() {
                return Err("avcC ended inside a parameter set".into());
            }
            let len = u16::from_be_bytes([cfg[at], cfg[at + 1]]) as usize;
            at += 2;
            if at + len > cfg.len() {
                return Err("avcC parameter set runs past the box".into());
            }
            sets.push((at, len));
            at += len;
        }
    }
    if sets.is_empty() {
        return Err("avcC carried no parameter sets".into());
    }
    Ok((sets, nal_len))
}

/// Split an `hvcC` into its VPS/SPS/PPS arrays.
///
/// 22 bytes of fixed fields, then `lengthSizeMinusOne` in the low two bits of
/// byte 21, a count of arrays, and each array a type byte, a 16-bit NAL count
/// and then the NALs behind 16-bit lengths.
fn split_hvcc(cfg: &[u8]) -> Result<(Vec<(usize, usize)>, i32), String> {
    if cfg.len() < 23 {
        return Err("hvcC too short".into());
    }
    let nal_len = (cfg[21] & 0x03) as i32 + 1;
    let arrays = cfg[22] as usize;
    let mut sets = Vec::new();
    let mut at = 23usize;
    for _ in 0..arrays {
        if at + 3 > cfg.len() {
            return Err("hvcC ended inside an array header".into());
        }
        let count = u16::from_be_bytes([cfg[at + 1], cfg[at + 2]]) as usize;
        at += 3;
        for _ in 0..count {
            if at + 2 > cfg.len() {
                return Err("hvcC ended inside a parameter set".into());
            }
            let len = u16::from_be_bytes([cfg[at], cfg[at + 1]]) as usize;
            at += 2;
            if at + len > cfg.len() {
                return Err("hvcC parameter set runs past the box".into());
            }
            sets.push((at, len));
            at += len;
        }
    }
    if sets.is_empty() {
        return Err("hvcC carried no parameter sets".into());
    }
    Ok((sets, nal_len))
}

/// A format description for AV1 or VP9 from the track's configuration
/// record (`av1C`, `vpcC`) as a sample-description atom: how those codecs
/// are described to CoreMedia. Hardware AV1 is on M3 and later; VP9 comes
/// from a decoder VideoToolbox registers on request, where the Mac has one.
///
/// # Safety
/// Writes a +1 description to `out` on success.
unsafe fn atom_format(track: &VideoTrack, out: &mut CMFormatDescriptionRef) -> OSStatus {
    // `kCFStringEncodingUTF8`.
    const UTF8: u32 = 0x0800_0100;
    let (codec, atom): (u32, &[u8]) = match track.codec {
        TrackCodec::Av1 => (u32::from_be_bytes(*b"av01"), b"av1C\0"),
        _ => {
            unsafe { VTRegisterSupplementalVideoDecoderIfAvailable(u32::from_be_bytes(*b"vp09")) };
            (u32::from_be_bytes(*b"vp09"), b"vpcC\0")
        }
    };
    if track.config.is_empty() {
        // -12710, kCMFormatDescriptionError_InvalidParameter: no record to
        // describe the stream with (VP9 in Matroska carries none).
        return -12710;
    }
    let key = unsafe {
        CFStringCreateWithCString(ptr::null(), atom.as_ptr() as *const std::ffi::c_char, UTF8)
    };
    let data = unsafe {
        CFDataCreate(
            ptr::null(),
            track.config.as_ptr(),
            track.config.len() as isize,
        )
    };
    let atoms = unsafe {
        CFDictionaryCreate(
            ptr::null(),
            &key as *const CFStringRef,
            &data as *const *const c_void,
            1,
            &kCFTypeDictionaryKeyCallBacks as *const c_void,
            &kCFTypeDictionaryValueCallBacks as *const c_void,
        )
    };
    let outer_key = unsafe { kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms };
    let extensions = unsafe {
        CFDictionaryCreate(
            ptr::null(),
            &outer_key as *const CFStringRef,
            &atoms as *const CFDictionaryRef,
            1,
            &kCFTypeDictionaryKeyCallBacks as *const c_void,
            &kCFTypeDictionaryValueCallBacks as *const c_void,
        )
    };
    let st = unsafe {
        CMVideoFormatDescriptionCreate(
            ptr::null(),
            codec,
            track.width as i32,
            track.height as i32,
            extensions,
            out,
        )
    };
    unsafe { CFRelease(extensions) };
    unsafe { CFRelease(atoms) };
    unsafe { CFRelease(data) };
    unsafe { CFRelease(key) };
    st
}

/// A VideoToolbox decompression session, fed one coded frame at a time.
pub struct VideoToolboxDecoder {
    session: VTDecompressionSessionRef,
    format: CMFormatDescriptionRef,
    sink: Box<Mutex<Sink>>,
    width: u32,
    height: u32,
    /// Kept alive for as long as the session: the sample buffers point into it.
    scratch: Vec<u8>,
    /// The track's, so timestamps mean the same thing here as in the demuxer.
    timescale: u32,
}

impl VideoToolboxDecoder {
    /// Open a session for `track`'s codec and configuration, giving BGRA.
    pub fn new(track: &VideoTrack) -> Result<Self, String> {
        Self::open(track, false)
    }

    /// As [`new`](Self::new), giving NV12 for [`take_packed`](Self::take_packed)
    /// (or planes, through [`take_frame`](Self::take_frame)) instead of BGRA:
    /// for a caller that converts on the GPU. Deeper streams come back at 8
    /// bits.
    pub fn new_planar(track: &VideoTrack) -> Result<Self, String> {
        Self::open(track, true)
    }

    fn open(track: &VideoTrack, planar: bool) -> Result<Self, String> {
        let (sets, nal_len) = match track.codec {
            TrackCodec::H264 => split_avcc(&track.config)?,
            TrackCodec::Hevc => split_hvcc(&track.config)?,
            TrackCodec::Vp9 | TrackCodec::Av1 => (Vec::new(), 0),
        };
        let pointers: Vec<*const u8> = sets
            .iter()
            .map(|(o, _)| track.config[*o..].as_ptr())
            .collect();
        let sizes: Vec<usize> = sets.iter().map(|(_, l)| *l).collect();

        let mut format: CMFormatDescriptionRef = ptr::null();
        let st = unsafe {
            match track.codec {
                TrackCodec::H264 => CMVideoFormatDescriptionCreateFromH264ParameterSets(
                    ptr::null(),
                    pointers.len(),
                    pointers.as_ptr(),
                    sizes.as_ptr(),
                    nal_len,
                    &mut format,
                ),
                TrackCodec::Vp9 | TrackCodec::Av1 => atom_format(track, &mut format),
                TrackCodec::Hevc => CMVideoFormatDescriptionCreateFromHEVCParameterSets(
                    ptr::null(),
                    pointers.len(),
                    pointers.as_ptr(),
                    sizes.as_ptr(),
                    nal_len,
                    ptr::null(),
                    &mut format,
                ),
            }
        };
        if st != 0 || format.is_null() {
            return Err(format!("could not build a format description: status {st}"));
        }

        // Ask for BGRA out. The hardware does the YUV conversion on the way
        // past for nothing; not asking means writing one here. Or planes, for
        // a caller that converts on the GPU.
        let sink = Box::new(Mutex::new(Sink {
            planar,
            pool: Default::default(),
            ..Sink::default()
        }));
        let mut session: VTDecompressionSessionRef = ptr::null_mut();
        let st = unsafe {
            let key = kCVPixelBufferPixelFormatTypeKey;
            let val = cfnum(if planar {
                PIXEL_FORMAT_NV12
            } else {
                PIXEL_FORMAT_BGRA
            });
            let attrs = CFDictionaryCreate(
                ptr::null(),
                &key as *const CFStringRef,
                &val as *const CFNumberRef,
                1,
                &kCFTypeDictionaryKeyCallBacks as *const c_void,
                &kCFTypeDictionaryValueCallBacks as *const c_void,
            );
            let record = VTDecompressionOutputCallbackRecord {
                callback: Some(on_decoded),
                ref_con: &*sink as *const Mutex<Sink> as *mut c_void,
            };
            let st = VTDecompressionSessionCreate(
                ptr::null(),
                format,
                ptr::null(),
                attrs,
                &record,
                &mut session,
            );
            CFRelease(val);
            CFRelease(attrs);
            st
        };
        if st != 0 || session.is_null() {
            unsafe { CFRelease(format) };
            return Err(format!("VTDecompressionSessionCreate failed: status {st}"));
        }

        Ok(Self {
            session,
            format,
            sink,
            width: track.width,
            height: track.height,
            scratch: Vec::new(),
            timescale: track.timescale,
        })
    }

    /// Size of the frames this session returns.
    pub fn size(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Hand one coded frame to the decoder, in **decode order**.
    ///
    /// `sample` is the bytes the demuxer pointed at — length-prefixed NAL
    /// units, exactly as they sit in the file. The timestamps come from the
    /// demuxer too and are not optional: without them the decoder cannot say
    /// which picture it just produced, and a stream with B-frames comes back
    /// shuffled.
    ///
    /// Pictures go into an internal queue; take them with [`take`](Self::take).
    pub fn push(&mut self, sample: &[u8], pts: i64, dts: i64, duration: i64) -> Result<(), String> {
        // The block buffer borrows this rather than copying, so it has to
        // outlive the decode call — hence a field and not a local.
        self.scratch.clear();
        self.scratch.extend_from_slice(sample);
        {
            let mut s = self.sink.lock().map_err(|_| "decoder sink poisoned")?;
            s.err = None;
        }

        let mut block: CMBlockBufferRef = ptr::null_mut();
        let st = unsafe {
            CMBlockBufferCreateWithMemoryBlock(
                ptr::null(),
                self.scratch.as_mut_ptr() as *mut c_void,
                self.scratch.len(),
                // `kCFAllocatorNull`, and it has to be spelled out. The
                // parameter is the allocator CoreMedia will *deallocate* the
                // block with, and passing null there means the default one —
                // which then tries to free a Rust `Vec`'s buffer and aborts
                // the process. The null *allocator* is the way to say "this
                // memory is borrowed"; `scratch` outlives the call.
                kCFAllocatorNull,
                ptr::null(),
                0,
                self.scratch.len(),
                0,
                &mut block,
            )
        };
        if st != 0 || block.is_null() {
            return Err(format!("CMBlockBufferCreateWithMemoryBlock: status {st}"));
        }

        let timing = CMSampleTimingInfo {
            duration: CMTime::new(duration, self.timescale),
            presentation: CMTime::new(pts, self.timescale),
            decode: CMTime::new(dts, self.timescale),
        };
        let mut sbuf: CMSampleBufferRef = ptr::null_mut();
        let sizes = [self.scratch.len()];
        let st = unsafe {
            CMSampleBufferCreateReady(
                ptr::null(),
                block,
                self.format,
                1,
                1,
                &timing,
                1,
                sizes.as_ptr(),
                &mut sbuf,
            )
        };
        unsafe { CFRelease(block as *const c_void) };
        if st != 0 || sbuf.is_null() {
            return Err(format!("CMSampleBufferCreateReady: status {st}"));
        }

        let st = unsafe {
            let mut info = 0u32;
            // Temporal processing, so the decoder is allowed to hold a frame
            // back until the ones it depends on have arrived.
            let st = VTDecompressionSessionDecodeFrame(
                self.session,
                sbuf,
                DECODE_ENABLE_TEMPORAL,
                ptr::null_mut(),
                &mut info,
            );
            if st == 0 {
                VTDecompressionSessionWaitForAsynchronousFrames(self.session);
            }
            CFRelease(sbuf as *const c_void);
            st
        };
        if st != 0 {
            return Err(format!("VTDecompressionSessionDecodeFrame: status {st}"));
        }
        let s = self.sink.lock().map_err(|_| "decoder sink poisoned")?;
        if let Some(e) = &s.err {
            return Err(e.clone());
        }
        Ok(())
    }

    /// Take the picture for presentation time `pts`, if the decoder has
    /// produced it yet. Tightly packed BGRA, `width * height * 4`.
    ///
    /// Frames before `pts` are dropped on the way past: they have been shown.
    /// On a [planar](Self::new_planar) session, converted here.
    pub fn take(&mut self, pts: i64) -> Option<Vec<u8>> {
        match self.take_picture(pts)? {
            Picture::Bgra(bgra) => Some(bgra),
            Picture::Planes(frame) => Some(frame.to_decoded().to_bgra()),
        }
    }

    /// Take the picture for presentation time `pts` as planes, from a session
    /// made with [`new_planar`](Self::new_planar); `None` from a BGRA one.
    pub fn take_frame(&mut self, pts: i64) -> Option<DecodedFrame> {
        self.take_packed(pts).map(|f| f.to_decoded())
    }

    /// Copy pictures into buffers from `pool` (see
    /// [`FramePool`](crate::bytes::FramePool)), to be given back there.
    pub fn set_pool(&mut self, pool: crate::bytes::FramePool) {
        if let Ok(mut sink) = self.sink.lock() {
            sink.pool = pool;
        }
    }

    /// Take the picture for presentation time `pts` as the decoder left it,
    /// NV12, from a session made with [`new_planar`](Self::new_planar).
    pub fn take_packed(&mut self, pts: i64) -> Option<PackedFrame> {
        match self.take_picture(pts)? {
            Picture::Planes(frame) => Some(frame),
            Picture::Bgra(_) => None,
        }
    }

    fn take_picture(&mut self, pts: i64) -> Option<Picture> {
        let mut sink = self.sink.lock().ok()?;
        let hit = sink.ready.iter().position(|(p, _)| *p == pts)?;
        let (_, frame) = sink.ready.remove(hit);
        sink.ready.retain(|(p, _)| *p > pts);
        Some(frame)
    }

    /// How many decoded pictures are waiting to be taken.
    pub fn queued(&self) -> usize {
        self.sink.lock().map(|s| s.ready.len()).unwrap_or(0)
    }
}

impl Drop for VideoToolboxDecoder {
    fn drop(&mut self) {
        unsafe {
            if !self.session.is_null() {
                VTDecompressionSessionInvalidate(self.session);
                CFRelease(self.session as *const c_void);
            }
            if !self.format.is_null() {
                CFRelease(self.format);
            }
        }
    }
}

// The session is only touched through `&mut self`, and the sink behind a mutex.
unsafe impl Send for VideoToolboxDecoder {}