Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

feat(macos): decode H.264 frames with VideoToolbox (#57)

alexfoxtm744564f183c6
diff --git a/desktop/app/src/mac/h264.rs b/desktop/app/src/mac/h264.rs
index f5c49de..96819e8 100644
--- a/desktop/app/src/mac/h264.rs
+++ b/desktop/app/src/mac/h264.rs
@@ -1,60 +1,274 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-//! macOS H.264 video decoding stubs.
+//! H.264 decoding with macOS's own VideoToolbox (Apple's hardware decoder
+//! where the Mac has one): each Annex B access unit in, its picture out
+//! right away, as NV12. HEVC and AV1 aren't decoded on macOS yet.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
-pub struct Colors {
- pub bt601: bool,
- pub full_range: bool,
-}
+mod annexb;
+mod vt;
+/// A decoded picture: NV12, `stride` bytes per row, the chroma plane after
+/// `plane_rows` rows of luma.
#[derive(Debug)]
-#[allow(dead_code)]
pub struct Picture {
pub width: u32,
pub height: u32,
pub stride: usize,
pub plane_rows: usize,
pub nv12: Vec<u8>,
+ /// How its colors turn into RGB, as the stream says.
pub colors: Colors,
}
-#[derive(Debug, Default)]
+/// The YUV-to-RGB formula a stream uses (its VUI, as the decoder reports
+/// it). Phones are asked for BT.709 limited range, but not all comply.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Colors {
+ pub bt601: bool,
+ pub full_range: bool,
+}
+
+impl Colors {
+ /// Fixed-point (×256) coefficients: luma scale, then V→R, U→G, V→G, U→B.
+ fn coefficients(self) -> (i32, i32, i32, i32, i32) {
+ let luma = if self.full_range { 256 } else { 298 };
+ let chroma = match (self.bt601, self.full_range) {
+ (false, false) => (459, 55, 136, 541),
+ (false, true) => (403, 48, 120, 475),
+ (true, false) => (409, 100, 208, 516),
+ (true, true) => (359, 88, 183, 454),
+ };
+ (luma, chroma.0, chroma.1, chroma.2, chroma.3)
+ }
+}
+
pub struct Decoder {
codec: String,
+ /// Whether to ask for Apple's hardware decoder first.
+ prefer_gpu: bool,
+ sets: annexb::ParameterSets,
+ /// The format of the latest SPS and PPS.
+ format: Option<vt::Format>,
+ /// Started at the first slice, as it needs the stream's format.
+ session: Option<vt::Session>,
+ /// Last presentation timestamp submitted, in microseconds. Kept across
+ /// flush: a new session must not repeat one CoreMedia already accepted.
+ last_pts: Option<i64>,
+}
+
+impl std::fmt::Debug for Decoder {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Decoder")
+ .field("codec", &self.codec)
+ .field("on_gpu", &self.on_gpu())
+ .finish_non_exhaustive()
+ }
}
impl Decoder {
+ /// A low-latency decoder for `"h264"`; VideoToolbox picks its decoder.
pub fn new_for_codec(codec: &str) -> Result<Decoder, String> {
- Err(format!("video decoding ({codec}) is not yet supported on macOS"))
+ Self::create(codec, false)
}
+ /// As [`Decoder::new_for_codec`], asking for Apple's hardware decoder
+ /// first and falling back to whichever VideoToolbox has.
pub fn new_gpu(codec: &str) -> Result<Decoder, String> {
- Self::new_for_codec(codec)
+ let mut decoder = Self::new_for_codec(codec)?;
+ decoder.prefer_gpu = true;
+ Ok(decoder)
+ }
+
+ fn create(codec: &str, prefer_gpu: bool) -> Result<Decoder, String> {
+ if codec != "h264" {
+ return Err(format!("{} video can't be decoded on macOS yet, only H.264", codec.to_uppercase()));
+ }
+ Ok(Decoder {
+ codec: codec.to_owned(),
+ prefer_gpu,
+ sets: annexb::ParameterSets::default(),
+ format: None,
+ session: None,
+ last_pts: None,
+ })
}
+ /// Whether the hardware decoder runs the current session, as
+ /// VideoToolbox reports it; false until the first picture's session starts.
pub fn on_gpu(&self) -> bool {
- false
+ self.session.as_ref().is_some_and(vt::Session::on_gpu)
}
pub fn codec(&self) -> &str {
&self.codec
}
- pub fn decode(&mut self, _data: &[u8], _time_us: u64) -> Result<Vec<Picture>, String> {
- Err("video decoding is not supported on macOS".into())
+ /// Decodes one access unit (Annex B); returns the pictures it completed.
+ /// After an error the session is dropped: the caller starts over from the
+ /// next keyframe, which gets a fresh one.
+ pub fn decode(&mut self, data: &[u8], time_us: u64) -> Result<Vec<Picture>, String> {
+ let unit = annexb::access_unit(data, &mut self.sets)?;
+ if self.sets.take_changed() {
+ self.reformat()?;
+ }
+ if !unit.has_slice {
+ return Ok(Vec::new());
+ }
+ let format = self.format.as_ref().ok_or("an H.264 slice before its SPS and PPS")?;
+ // Reserve the timestamp before borrowing the session. A failed open
+ // still keeps it, so a retry cannot submit the same value twice.
+ let pts = monotonic_presentation_us(&mut self.last_pts, time_us)?;
+ let session = match &mut self.session {
+ Some(session) => session,
+ none => none.insert(open(format, &mut self.prefer_gpu)?),
+ };
+ let result = session.decode(format, &unit.avcc, pts);
+ if result.is_err() {
+ self.session = None;
+ }
+ result
+ }
+
+ /// Starts over (after lost packets): the next keyframe decodes cleanly
+ /// in a new session, with the parameter sets seen so far. The presentation
+ /// clock stays, so that session cannot repeat a timestamp.
+ pub fn flush(&mut self) {
+ self.session = None;
}
- pub fn flush(&mut self) {}
+ /// Takes in new parameter sets, keeping the session if it can go on.
+ fn reformat(&mut self) -> Result<(), String> {
+ let Some((sps, pps)) = self.sets.sets() else {
+ // A changed SPS clears every PPS. The previous format still
+ // describes that old pair, so a later slice must not use it.
+ self.format = None;
+ self.session = None;
+ return Ok(());
+ };
+ match vt::Format::h264(sps, &pps) {
+ Ok(format) => {
+ if self.session.as_ref().is_some_and(|session| !session.can_accept(&format)) {
+ self.session = None;
+ }
+ self.format = Some(format);
+ Ok(())
+ }
+ Err(e) => {
+ self.format = None;
+ self.session = None;
+ self.sets = annexb::ParameterSets::default();
+ Err(e)
+ }
+ }
+ }
+}
+
+/// A session for `format`. Hardware is required when preferred. Only a
+/// decoder-unavailable status falls back, and then not again for this decoder.
+fn open(format: &vt::Format, prefer_gpu: &mut bool) -> Result<vt::Session, String> {
+ if *prefer_gpu {
+ match vt::Session::new(format, true) {
+ Ok(session) => return Ok(session),
+ Err(error) if error.hardware_unavailable() => {
+ tracing::info!(
+ status = error.status_code(),
+ error = %error,
+ "hardware H.264 decoder unavailable; VideoToolbox picks a decoder"
+ );
+ *prefer_gpu = false;
+ }
+ Err(error) => return Err(error.into_message()),
+ }
+ }
+ vt::Session::new(format, false).map_err(vt::StartError::into_message)
+}
+
+/// Presentation time in microseconds, strictly after `last` once one is set.
+/// CoreMedia leaves equal timestamps in one stream undefined, and the protocol
+/// only needs differences, so a repeat or a step backward becomes last + 1.
+/// `u64` values that do not fit in `i64` saturate; the clock then stops with
+/// an error instead of repeating `i64::MAX`.
+fn monotonic_presentation_us(last: &mut Option<i64>, time_us: u64) -> Result<i64, String> {
+ let requested = i64::try_from(time_us).unwrap_or(i64::MAX);
+ let pts = match *last {
+ Some(prev) if requested <= prev => {
+ prev.checked_add(1).ok_or("H.264 presentation timestamps ran out of range")?
+ }
+ _ => requested,
+ };
+ *last = Some(pts);
+ Ok(pts)
}
+/// Pixels from which a frame is converted on several cores: 4K takes about
+/// 24 ms on one core, most of a 30 fps frame's 33 ms, while 720p is quick
+/// enough on the calling thread.
+const PARALLEL_FROM_PIXELS: usize = 1920 * 1080;
+
+/// NV12 (in the picture's own colors) to 32-bit BGRX, the visible
+/// `width` x `height`. Large frames are split into bands of rows, one per
+/// core (scoped threads cost microseconds, against milliseconds of work).
pub fn to_bgrx(picture: &Picture, width: u32, height: u32) -> Vec<u8> {
let (w, h) = (width.min(picture.width) as usize, height.min(picture.height) as usize);
- vec![0; w * h * 4]
+ let mut out = vec![0u8; w * h * 4];
+ if w == 0 || h == 0 {
+ return out;
+ }
+ if !holds(picture, w, h) {
+ tracing::warn!(
+ width = picture.width,
+ height = picture.height,
+ stride = picture.stride,
+ len = picture.nv12.len(),
+ "an NV12 picture smaller than it says; not converted"
+ );
+ return out;
+ }
+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get()).min(8);
+ if w * h < PARALLEL_FROM_PIXELS || cores < 2 {
+ convert_rows(picture, w, 0, &mut out);
+ return out;
+ }
+ // Bands of an even number of rows, so each starts on a chroma row.
+ let band = h.div_ceil(cores).next_multiple_of(2);
+ std::thread::scope(|scope| {
+ for (i, rows) in out.chunks_mut(band * w * 4).enumerate() {
+ scope.spawn(move || convert_rows(picture, w, i * band, rows));
+ }
+ });
+ out
}
-#[allow(dead_code)]
-pub fn ensure_mf_started() -> Result<(), String> {
- Ok(())
+/// Whether `p` has the luma and chroma rows `convert_rows` reads for `w` x `h`.
+fn holds(p: &Picture, w: usize, h: usize) -> bool {
+ let needed = p
+ .stride
+ .checked_mul(p.plane_rows)
+ .and_then(|luma| luma.checked_add(p.stride.checked_mul(h.div_ceil(2))?));
+ p.stride >= w.next_multiple_of(2) && p.plane_rows >= h && needed.is_some_and(|n| p.nv12.len() >= n)
+}
+
+fn convert_rows(p: &Picture, w: usize, first: usize, out: &mut [u8]) {
+ let uv_plane = p.stride * p.plane_rows;
+ let (luma, vr, ug, vg, ub) = p.colors.coefficients();
+ let black = if p.colors.full_range { 0 } else { 16 };
+ for (i, row) in out.chunks_exact_mut(w * 4).enumerate() {
+ let y_row = first + i;
+ let y_line = &p.nv12[y_row * p.stride..][..w];
+ let uv_line = &p.nv12[uv_plane + (y_row / 2) * p.stride..][..w.next_multiple_of(2)];
+ for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ let c = (i32::from(y_line[x]) - black) * luma;
+ let d = i32::from(uv_line[x & !1]) - 128;
+ let e = i32::from(uv_line[(x & !1) + 1]) - 128;
+ px[0] = clamp((c + ub * d + 128) >> 8);
+ px[1] = clamp((c - ug * d - vg * e + 128) >> 8);
+ px[2] = clamp((c + vr * e + 128) >> 8);
+ px[3] = 255;
+ }
+ }
+}
+
+fn clamp(v: i32) -> u8 {
+ v.clamp(0, 255) as u8
}
#[cfg(test)]
@@ -62,14 +276,93 @@ mod tests {
use super::*;
#[test]
- fn h264_decoder_reports_unsupported_on_creation() {
- assert!(Decoder::new_for_codec("h264").is_err());
- assert!(Decoder::new_gpu("h264").is_err());
+ fn h264_keyframe_decodes_to_nv12_and_converts_in_its_range() {
+ // The hardening's success path, without VideoToolbox: a later timestamp
+ // is kept, a required-hardware create with no property answer stays
+ // hardware, and a 64-byte aligned row has a checked offset.
+ let mut clock = None;
+ assert_eq!(monotonic_presentation_us(&mut clock, 0).unwrap(), 0);
+ assert_eq!(monotonic_presentation_us(&mut clock, 33_333).unwrap(), 33_333);
+ assert!(vt::hardware_in_use(true, None));
+ assert!(vt::hardware_in_use(false, Some(true)));
+ assert_eq!(vt::plane_row_offset(1, 64, 32).unwrap(), 64);
+
+ // Synthetic solid red 32x32 baseline IDR (AUD, SPS, PPS, slice),
+ // tagged BT.709 limited range.
+ let mut decoder = Decoder::new_for_codec("h264").unwrap();
+ let pictures = decoder.decode(include_bytes!("testdata/red-32x32.annexb"), 0).unwrap();
+ assert_eq!(pictures.len(), 1);
+ let picture = &pictures[0];
+ assert_eq!((picture.width, picture.height), (32, 32));
+ assert!(!picture.colors.bt601);
+ let bgrx = to_bgrx(picture, 32, 32);
+ assert_eq!(bgrx.len(), 32 * 32 * 4);
+ // Read as full range, this red would come out near (15, 15, 239).
+ for px in bgrx.as_chunks::<4>().0 {
+ assert!(px[0] <= 10 && px[1] <= 10 && px[2] >= 244 && px[3] == 255, "{px:?}");
+ }
+
+ // The fixture's SPS with one profile bit flipped, and no PPS. The
+ // open format must be dropped; the following slice must not reach
+ // VideoToolbox on the parameters from the picture above.
+ let mut sets = annexb::ParameterSets::default();
+ annexb::access_unit(include_bytes!("testdata/red-32x32.annexb"), &mut sets).unwrap();
+ let mut changed_sps = sets.sets().unwrap().0.to_vec();
+ changed_sps[1] ^= 1;
+ let mut sps_only = vec![0, 0, 0, 1];
+ sps_only.extend_from_slice(&changed_sps);
+ assert!(decoder.decode(&sps_only, 1).unwrap().is_empty());
+ let error = decoder.decode(&[0, 0, 0, 1, 0x65, 0x88, 0x84], 2).unwrap_err();
+ assert_eq!(error, "an H.264 slice before its SPS and PPS");
+ assert!(!decoder.on_gpu());
}
#[test]
- fn h264_decode_reports_unsupported() {
- let mut decoder = Decoder::default();
- assert!(decoder.decode(&[0, 0, 0, 1], 0).is_err());
+ fn decoder_refuses_other_codecs_and_malformed_h264() {
+ assert!(Decoder::new_gpu("h265").is_err());
+ assert!(Decoder::new_for_codec("av1").is_err());
+ let mut decoder = Decoder::new_gpu("h264").unwrap();
+ assert!(decoder.decode(&[0x65, 0x88, 0x84], 0).is_err(), "no start code");
+ assert!(decoder.decode(&[0, 0, 0, 1, 0x65, 0x88, 0x84], 0).is_err(), "a slice before SPS and PPS");
+ assert!(decoder.decode(&vec![0; annexb::MAX_ACCESS_UNIT + 1], 0).is_err(), "over the packet limit");
+ assert!(!decoder.on_gpu());
+
+ // Parameter and bad-data failures are not "no hardware". Only the
+ // three decoder-unavailable statuses are. Unknown hardware stays false.
+ assert!(!vt::hardware_decoder_unavailable(-12902));
+ assert!(!vt::hardware_decoder_unavailable(-12904));
+ assert!(!vt::hardware_decoder_unavailable(-12909));
+ assert!(vt::hardware_decoder_unavailable(-12906));
+ assert!(vt::hardware_decoder_unavailable(-12907));
+ assert!(vt::hardware_decoder_unavailable(-12913));
+ assert!(!vt::hardware_in_use(false, None));
+ assert!(!vt::hardware_in_use(true, Some(false)));
+
+ let mut clock = None;
+ assert_eq!(monotonic_presentation_us(&mut clock, 10).unwrap(), 10);
+ assert_eq!(monotonic_presentation_us(&mut clock, 10).unwrap(), 11);
+ assert_eq!(monotonic_presentation_us(&mut clock, 9).unwrap(), 12);
+ clock = Some(i64::MAX);
+ assert!(monotonic_presentation_us(&mut clock, u64::MAX).is_err());
+ assert_eq!(clock, Some(i64::MAX));
+
+ assert!(vt::plane_row_offset(0, 31, 32).is_err(), "stride shorter than the row");
+ assert!(vt::plane_row_offset(1, usize::MAX / 2, 32).is_err(), "stride past the cap");
+ let wide = vt::max_plane_pitch(32);
+ assert!(vt::plane_row_offset(1, wide, 32).is_ok());
+ assert!(vt::plane_row_offset(1, wide + 1, 32).is_err());
+
+ // Rotation must not combine a new SPS with an old encoder's PPS.
+ let mut sets = annexb::ParameterSets::default();
+ let fixture = include_bytes!("testdata/red-32x32.annexb");
+ annexb::access_unit(fixture, &mut sets).unwrap();
+ let mut changed_sps = sets.sets().unwrap().0.to_vec();
+ changed_sps[1] ^= 1;
+ let mut packet = vec![0, 0, 0, 1];
+ packet.extend(changed_sps);
+ annexb::access_unit(&packet, &mut sets).unwrap();
+ assert!(sets.sets().is_none(), "a changed SPS invalidates previous PPS ids");
+ annexb::access_unit(fixture, &mut sets).unwrap();
+ assert!(sets.sets().is_some(), "the next complete keyframe restores both parameter sets");
}
}
diff --git a/desktop/app/src/mac/h264/annexb.rs b/desktop/app/src/mac/h264/annexb.rs
new file mode 100644
index 0000000..709ee92
--- /dev/null
+++ b/desktop/app/src/mac/h264/annexb.rs
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! H.264 Annex B access units (docs/protocol/mirror.md §3) turned into what
+//! VideoToolbox takes: the stream's SPS and PPS kept aside for its format
+//! description, the rest as 4-byte length-prefixed NAL units (AVCC).
+
+/// The protocol's packet limit; anything longer is refused unread.
+pub(super) const MAX_ACCESS_UNIT: usize = 8 << 20;
+/// NAL units in one access unit, at most (phones send a handful).
+const MAX_NAL_UNITS: usize = 512;
+/// A parameter set larger than this is refused (real ones are tens of bytes).
+const MAX_PARAMETER_SET: usize = 4096;
+/// Distinct PPS ids kept, at most.
+const MAX_PPS: usize = 32;
+
+const SLICE: u8 = 1;
+const SLICE_IDR: u8 = 5;
+const SEI: u8 = 6;
+const SPS: u8 = 7;
+const PPS: u8 = 8;
+
+/// The parameter sets seen so far: the latest SPS and each PPS by id.
+#[derive(Debug, Default)]
+pub(super) struct ParameterSets {
+ sps: Option<Vec<u8>>,
+ pps: Vec<(u32, Vec<u8>)>,
+ changed: bool,
+}
+
+impl ParameterSets {
+ /// The SPS and every PPS, when there are both.
+ pub(super) fn sets(&self) -> Option<(&[u8], Vec<&[u8]>)> {
+ let sps = self.sps.as_deref()?;
+ (!self.pps.is_empty()).then(|| (sps, self.pps.iter().map(|(_, pps)| pps.as_slice()).collect()))
+ }
+
+ /// Whether a set changed since the last call.
+ pub(super) fn take_changed(&mut self) -> bool {
+ std::mem::take(&mut self.changed)
+ }
+
+ fn set_sps(&mut self, nal: &[u8]) -> Result<(), String> {
+ check_parameter_set("SPS", nal)?;
+ if self.sps.as_deref() != Some(nal) {
+ self.sps = Some(nal.to_vec());
+ self.pps.clear();
+ self.changed = true;
+ }
+ Ok(())
+ }
+
+ fn set_pps(&mut self, nal: &[u8]) -> Result<(), String> {
+ check_parameter_set("PPS", nal)?;
+ let id = first_ue(&nal[1..]).ok_or("a PPS without a readable id")?;
+ let at_limit = self.pps.len() >= MAX_PPS;
+ match self.pps.iter_mut().find(|(known, _)| *known == id) {
+ Some((_, pps)) if pps.as_slice() == nal => return Ok(()),
+ Some((_, pps)) => *pps = nal.to_vec(),
+ None if at_limit => return Err(format!("more than {MAX_PPS} PPS ids")),
+ None => self.pps.push((id, nal.to_vec())),
+ }
+ self.changed = true;
+ Ok(())
+ }
+}
+
+fn check_parameter_set(kind: &str, nal: &[u8]) -> Result<(), String> {
+ if nal.len() < 2 || nal.len() > MAX_PARAMETER_SET {
+ return Err(format!("a {kind} of {} bytes", nal.len()));
+ }
+ Ok(())
+}
+
+/// One access unit, ready for VideoToolbox.
+#[derive(Debug)]
+pub(super) struct AccessUnit {
+ /// The coded slices and SEI, each after its length (big-endian u32).
+ pub(super) avcc: Vec<u8>,
+ /// Whether it holds a picture to decode (it may be parameter sets only).
+ pub(super) has_slice: bool,
+}
+
+/// Splits an Annex B access unit, keeping its parameter sets in `sets`.
+pub(super) fn access_unit(data: &[u8], sets: &mut ParameterSets) -> Result<AccessUnit, String> {
+ if data.len() > MAX_ACCESS_UNIT {
+ return Err(format!("an access unit of {} bytes", data.len()));
+ }
+ let mut avcc = Vec::with_capacity(data.len() + 16);
+ let mut has_slice = false;
+ for nal in nal_units(data)? {
+ match nal[0] & 0x1f {
+ SPS => sets.set_sps(nal)?,
+ PPS => sets.set_pps(nal)?,
+ kind @ (SLICE | SLICE_IDR | SEI) => {
+ has_slice |= kind != SEI;
+ // At most MAX_ACCESS_UNIT bytes, so it fits.
+ avcc.extend_from_slice(&(nal.len() as u32).to_be_bytes());
+ avcc.extend_from_slice(nal);
+ }
+ // Data-partitioned slices (Extended profile): VideoToolbox can't.
+ 2..=4 => return Err("data-partitioned H.264 slices aren't supported".into()),
+ // Delimiters, end of sequence or stream, filler, SVC/MVC layers
+ // over the base one, reserved types: nothing to decode here.
+ _ => {}
+ }
+ }
+ Ok(AccessUnit { avcc, has_slice })
+}
+
+/// The NAL units of an Annex B buffer, without start codes or trailing zeros.
+fn nal_units(data: &[u8]) -> Result<Vec<&[u8]>, String> {
+ let first = start_code(data, 0).ok_or("not Annex B: no start code")?;
+ if data[..first].iter().any(|&b| b != 0) {
+ return Err("not Annex B: bytes before the first start code".into());
+ }
+ let mut units = Vec::new();
+ let mut pos = first + 3;
+ loop {
+ let next = start_code(data, pos);
+ let mut nal = &data[pos..next.unwrap_or(data.len())];
+ // A 4-byte start code's leading zero, or trailing_zero_8bits.
+ while let [rest @ .., 0] = nal {
+ nal = rest;
+ }
+ if let Some(&header) = nal.first() {
+ if header & 0x80 != 0 {
+ return Err("a NAL unit with its forbidden bit set".into());
+ }
+ if units.len() == MAX_NAL_UNITS {
+ return Err(format!("more than {MAX_NAL_UNITS} NAL units in an access unit"));
+ }
+ units.push(nal);
+ }
+ match next {
+ Some(at) => pos = at + 3,
+ None => return Ok(units),
+ }
+ }
+}
+
+/// Where the next `00 00 01` at or after `from` starts.
+fn start_code(data: &[u8], from: usize) -> Option<usize> {
+ let mut i = from;
+ while i + 2 < data.len() {
+ match data[i + 2] {
+ 1 if data[i] == 0 && data[i + 1] == 0 => return Some(i),
+ 0 => i += 1,
+ _ => i += 3,
+ }
+ }
+ None
+}
+
+/// The first Exp-Golomb `ue(v)` of an escaped RBSP (a PPS's id).
+fn first_ue(escaped: &[u8]) -> Option<u32> {
+ let mut bits = escaped
+ .iter()
+ .enumerate()
+ // Emulation prevention: a 3 after two zeros isn't data.
+ .filter(|&(i, &b)| !(b == 3 && i >= 2 && escaped[i - 2] == 0 && escaped[i - 1] == 0))
+ .flat_map(|(_, &b)| (0..8).rev().map(move |bit| (b >> bit) & 1 == 1));
+ let mut zeros = 0u32;
+ while !bits.next()? {
+ zeros += 1;
+ if zeros > 31 {
+ return None;
+ }
+ }
+ let mut suffix = 0u64;
+ for _ in 0..zeros {
+ suffix = (suffix << 1) | u64::from(bits.next()?);
+ }
+ u32::try_from((1u64 << zeros) - 1 + suffix).ok()
+}
diff --git a/desktop/app/src/mac/h264/vt.rs b/desktop/app/src/mac/h264/vt.rs
new file mode 100644
index 0000000..b8ca170
--- /dev/null
+++ b/desktop/app/src/mac/h264/vt.rs
@@ -0,0 +1,781 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! VideoToolbox decompression sessions for H.264, with each decoded NV12
+//! pixel buffer copied out as a [`Picture`]. The declarations follow the
+//! macOS SDK headers (VTDecompressionSession.h, VTSession.h, VTErrors.h,
+//! CMFormatDescription.h, CMBlockBuffer.h, CMSampleBuffer.h, CMTime.h,
+//! CVPixelBuffer.h, CVBuffer.h, CVImageBuffer.h, CFBase.h, CFDictionary.h,
+//! CFArray.h, CFNumber.h).
+
+#![allow(unsafe_code)]
+
+use std::{
+ ffi::{c_int, c_void},
+ panic::{AssertUnwindSafe, catch_unwind},
+ ptr::{self, NonNull},
+ slice,
+ sync::Mutex,
+};
+
+use super::{Colors, Picture};
+
+type OSStatus = i32;
+type Boolean = u8;
+type CFIndex = isize;
+type CFTypeID = usize;
+type CFTypeRef = *const c_void;
+type CFStringRef = *const c_void;
+type CMFormatDescriptionRef = *const c_void;
+type CMBlockBufferRef = *mut c_void;
+type CMSampleBufferRef = *mut c_void;
+type VTDecompressionSessionRef = *mut c_void;
+type CVImageBufferRef = *mut c_void;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct CMTime {
+ value: i64,
+ timescale: i32,
+ flags: u32,
+ epoch: i64,
+}
+
+#[repr(C)]
+struct CMSampleTimingInfo {
+ duration: CMTime,
+ presentation_time_stamp: CMTime,
+ decode_time_stamp: CMTime,
+}
+
+#[repr(C)]
+struct CMVideoDimensions {
+ width: i32,
+ height: i32,
+}
+
+type OutputCallback = unsafe extern "C" fn(
+ decompression_output_ref_con: *mut c_void,
+ source_frame_ref_con: *mut c_void,
+ status: OSStatus,
+ info_flags: u32,
+ image_buffer: CVImageBufferRef,
+ presentation_time_stamp: CMTime,
+ presentation_duration: CMTime,
+);
+
+#[repr(C)]
+struct OutputCallbackRecord {
+ decompression_output_callback: Option<OutputCallback>,
+ decompression_output_ref_con: *mut c_void,
+}
+
+#[link(name = "CoreFoundation", kind = "framework")]
+unsafe extern "C" {
+ // Callback tables, only ever passed by address.
+ static kCFTypeDictionaryKeyCallBacks: u8;
+ static kCFTypeDictionaryValueCallBacks: u8;
+ static kCFTypeArrayCallBacks: u8;
+ static kCFBooleanTrue: CFTypeRef;
+
+ fn CFRelease(cf: CFTypeRef);
+ fn CFEqual(cf1: CFTypeRef, cf2: CFTypeRef) -> Boolean;
+ fn CFGetTypeID(cf: CFTypeRef) -> CFTypeID;
+ fn CFBooleanGetTypeID() -> CFTypeID;
+ fn CFBooleanGetValue(boolean: CFTypeRef) -> Boolean;
+ fn CFNumberCreate(allocator: CFTypeRef, the_type: CFIndex, value_ptr: *const c_void) -> CFTypeRef;
+ fn CFArrayCreate(
+ allocator: CFTypeRef,
+ values: *const CFTypeRef,
+ num_values: CFIndex,
+ call_backs: *const c_void,
+ ) -> CFTypeRef;
+ fn CFDictionaryCreate(
+ allocator: CFTypeRef,
+ keys: *const CFTypeRef,
+ values: *const CFTypeRef,
+ num_values: CFIndex,
+ key_call_backs: *const c_void,
+ value_call_backs: *const c_void,
+ ) -> CFTypeRef;
+}
+
+#[link(name = "CoreMedia", kind = "framework")]
+unsafe extern "C" {
+ fn CMVideoFormatDescriptionCreateFromH264ParameterSets(
+ allocator: CFTypeRef,
+ parameter_set_count: usize,
+ parameter_set_pointers: *const *const u8,
+ parameter_set_sizes: *const usize,
+ nal_unit_header_length: c_int,
+ format_description_out: *mut CMFormatDescriptionRef,
+ ) -> OSStatus;
+ fn CMVideoFormatDescriptionGetDimensions(video_desc: CMFormatDescriptionRef) -> CMVideoDimensions;
+ fn CMBlockBufferCreateWithMemoryBlock(
+ structure_allocator: CFTypeRef,
+ memory_block: *mut c_void,
+ block_length: usize,
+ block_allocator: CFTypeRef,
+ custom_block_source: *const c_void,
+ offset_to_data: usize,
+ data_length: usize,
+ flags: u32,
+ block_buffer_out: *mut CMBlockBufferRef,
+ ) -> OSStatus;
+ fn CMBlockBufferReplaceDataBytes(
+ source_bytes: *const c_void,
+ destination_buffer: CMBlockBufferRef,
+ offset_into_destination: usize,
+ data_length: usize,
+ ) -> OSStatus;
+ fn CMSampleBufferCreateReady(
+ allocator: CFTypeRef,
+ data_buffer: CMBlockBufferRef,
+ format_description: CMFormatDescriptionRef,
+ num_samples: CFIndex,
+ num_sample_timing_entries: CFIndex,
+ sample_timing_array: *const CMSampleTimingInfo,
+ num_sample_size_entries: CFIndex,
+ sample_size_array: *const usize,
+ sample_buffer_out: *mut CMSampleBufferRef,
+ ) -> OSStatus;
+}
+
+#[link(name = "CoreVideo", kind = "framework")]
+unsafe extern "C" {
+ static kCVPixelBufferPixelFormatTypeKey: CFStringRef;
+ static kCVImageBufferYCbCrMatrixKey: CFStringRef;
+ static kCVImageBufferYCbCrMatrix_ITU_R_601_4: CFStringRef;
+
+ fn CVPixelBufferGetTypeID() -> CFTypeID;
+ fn CVPixelBufferLockBaseAddress(pixel_buffer: CVImageBufferRef, lock_flags: u64) -> i32;
+ fn CVPixelBufferUnlockBaseAddress(pixel_buffer: CVImageBufferRef, unlock_flags: u64) -> i32;
+ fn CVPixelBufferGetWidth(pixel_buffer: CVImageBufferRef) -> usize;
+ fn CVPixelBufferGetHeight(pixel_buffer: CVImageBufferRef) -> usize;
+ fn CVPixelBufferGetPixelFormatType(pixel_buffer: CVImageBufferRef) -> u32;
+ fn CVPixelBufferIsPlanar(pixel_buffer: CVImageBufferRef) -> Boolean;
+ fn CVPixelBufferGetPlaneCount(pixel_buffer: CVImageBufferRef) -> usize;
+ fn CVPixelBufferGetHeightOfPlane(pixel_buffer: CVImageBufferRef, plane_index: usize) -> usize;
+ fn CVPixelBufferGetBytesPerRowOfPlane(pixel_buffer: CVImageBufferRef, plane_index: usize) -> usize;
+ fn CVPixelBufferGetBaseAddressOfPlane(pixel_buffer: CVImageBufferRef, plane_index: usize) -> *mut c_void;
+ fn CVBufferCopyAttachment(
+ buffer: CVImageBufferRef,
+ key: CFStringRef,
+ attachment_mode: *mut u32,
+ ) -> CFTypeRef;
+}
+
+#[link(name = "VideoToolbox", kind = "framework")]
+unsafe extern "C" {
+ static kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder: CFStringRef;
+ static kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder: CFStringRef;
+
+ fn VTDecompressionSessionCreate(
+ allocator: CFTypeRef,
+ video_format_description: CMFormatDescriptionRef,
+ video_decoder_specification: CFTypeRef,
+ destination_image_buffer_attributes: CFTypeRef,
+ output_callback: *const OutputCallbackRecord,
+ decompression_session_out: *mut VTDecompressionSessionRef,
+ ) -> OSStatus;
+ fn VTDecompressionSessionDecodeFrame(
+ session: VTDecompressionSessionRef,
+ sample_buffer: CMSampleBufferRef,
+ decode_flags: u32,
+ source_frame_ref_con: *mut c_void,
+ info_flags_out: *mut u32,
+ ) -> OSStatus;
+ fn VTDecompressionSessionCanAcceptFormatDescription(
+ session: VTDecompressionSessionRef,
+ new_format_desc: CMFormatDescriptionRef,
+ ) -> Boolean;
+ fn VTDecompressionSessionWaitForAsynchronousFrames(session: VTDecompressionSessionRef) -> OSStatus;
+ fn VTDecompressionSessionInvalidate(session: VTDecompressionSessionRef);
+ fn VTSessionCopyProperty(
+ session: CFTypeRef,
+ property_key: CFStringRef,
+ allocator: CFTypeRef,
+ property_value_out: *mut c_void,
+ ) -> OSStatus;
+}
+
+const CF_NUMBER_SINT32: CFIndex = 3;
+const CM_TIME_VALID: u32 = 1;
+const CM_TIME_INVALID: CMTime = CMTime { value: 0, timescale: 0, flags: 0, epoch: 0 };
+const CM_BLOCK_BUFFER_ASSURE_MEMORY_NOW: u32 = 1;
+const CV_LOCK_READ_ONLY: u64 = 1;
+const NV12_VIDEO_RANGE: u32 = u32::from_be_bytes(*b"420v");
+const NV12_FULL_RANGE: u32 = u32::from_be_bytes(*b"420f");
+const DECODE_INFO_FRAME_DROPPED: u32 = 1 << 1;
+const DECODE_INFO_FRAME_INTERRUPTED: u32 = 1 << 4;
+
+/// Largest width or height decoded (8K); larger streams are refused.
+const MAX_DIMENSION: usize = 8192;
+/// Pictures one decode call keeps, at most (one sample normally gives one).
+const MAX_PENDING: usize = 4;
+/// `kVTCouldNotFindVideoDecoderErr` (VTErrors.h).
+const VT_COULD_NOT_FIND_VIDEO_DECODER: i32 = -12906;
+/// `kVTCouldNotCreateInstanceErr`.
+const VT_COULD_NOT_CREATE_INSTANCE: i32 = -12907;
+/// `kVTVideoDecoderNotAvailableNowErr`.
+const VT_VIDEO_DECODER_NOT_AVAILABLE_NOW: i32 = -12913;
+
+/// Whether `status` is one of the three VideoToolbox codes that mean a
+/// hardware decoder cannot be opened. Other failures (bad parameters, bad
+/// data, allocation) must surface instead of being treated as "no hardware".
+pub(super) fn hardware_decoder_unavailable(status: i32) -> bool {
+ matches!(
+ status,
+ VT_COULD_NOT_FIND_VIDEO_DECODER | VT_COULD_NOT_CREATE_INSTANCE | VT_VIDEO_DECODER_NOT_AVAILABLE_NOW
+ )
+}
+
+/// Hardware in use for a session that was just created.
+/// An explicit VideoToolbox answer wins. When the property cannot be read,
+/// a create that required hardware is hardware; otherwise unknown stays false.
+pub(super) fn hardware_in_use(require_hardware: bool, reported: Option<bool>) -> bool {
+ reported.unwrap_or(require_hardware)
+}
+
+/// A failure from [`Session::new`], with the OSStatus when VideoToolbox returned one.
+pub(super) struct StartError {
+ status: Option<i32>,
+ message: String,
+}
+
+impl StartError {
+ fn from_status(status: i32, doing: &str) -> StartError {
+ StartError { status: Some(status), message: describe(status, doing) }
+ }
+
+ pub(super) fn hardware_unavailable(&self) -> bool {
+ self.status.is_some_and(hardware_decoder_unavailable)
+ }
+
+ pub(super) fn status_code(&self) -> i32 {
+ self.status.unwrap_or(0)
+ }
+
+ pub(super) fn into_message(self) -> String {
+ self.message
+ }
+}
+
+impl From<String> for StartError {
+ fn from(message: String) -> StartError {
+ StartError { status: None, message }
+ }
+}
+
+impl From<&str> for StartError {
+ fn from(message: &str) -> StartError {
+ StartError { status: None, message: message.to_owned() }
+ }
+}
+
+impl std::fmt::Display for StartError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.message)
+ }
+}
+
+/// One reference to a Core Foundation object, released on drop.
+#[derive(Debug)]
+struct Owned(NonNull<c_void>);
+
+impl Owned {
+ /// Takes over the reference a Create or Copy call returned.
+ fn new(object: *const c_void) -> Option<Owned> {
+ NonNull::new(object.cast_mut()).map(Owned)
+ }
+
+ fn get(&self) -> *mut c_void {
+ self.0.as_ptr()
+ }
+}
+
+impl Drop for Owned {
+ fn drop(&mut self) {
+ // SAFETY: this holds exactly one reference.
+ unsafe { CFRelease(self.0.as_ptr()) }
+ }
+}
+
+/// A stream's format, from its SPS and PPS.
+#[derive(Debug)]
+pub(super) struct Format(Owned);
+
+impl Format {
+ pub(super) fn h264(sps: &[u8], pps: &[&[u8]]) -> Result<Format, String> {
+ let sets: Vec<&[u8]> = std::iter::once(sps).chain(pps.iter().copied()).collect();
+ let pointers: Vec<*const u8> = sets.iter().map(|set| set.as_ptr()).collect();
+ let sizes: Vec<usize> = sets.iter().map(|set| set.len()).collect();
+ let mut out = ptr::null();
+ // SAFETY: `pointers` and `sizes` describe `sets.len()` live slices;
+ // the description comes back with one reference, ours.
+ let status = unsafe {
+ CMVideoFormatDescriptionCreateFromH264ParameterSets(
+ ptr::null(),
+ sets.len(),
+ pointers.as_ptr(),
+ sizes.as_ptr(),
+ 4,
+ &mut out,
+ )
+ };
+ let format = Owned::new(out);
+ check(status, "reading the SPS and PPS")?;
+ let format = Format(format.ok_or("no H.264 format description")?);
+ // SAFETY: a live video format description.
+ let CMVideoDimensions { width, height } =
+ unsafe { CMVideoFormatDescriptionGetDimensions(format.0.get()) };
+ let valid = |side: i32| usize::try_from(side).is_ok_and(|side| (1..=MAX_DIMENSION).contains(&side));
+ if !valid(width) || !valid(height) {
+ return Err(format!("an H.264 stream of {width}x{height}"));
+ }
+ Ok(format)
+ }
+}
+
+/// Where the output callback leaves what it decoded.
+#[derive(Debug, Default)]
+struct Sink {
+ frames: Mutex<Frames>,
+}
+
+#[derive(Debug, Default)]
+struct Frames {
+ pictures: Vec<Picture>,
+ error: Option<String>,
+}
+
+/// A VideoToolbox decompression session decoding synchronously: each frame's
+/// picture is out before [`Session::decode`] returns.
+#[derive(Debug)]
+pub(super) struct Session {
+ session: Owned,
+ /// Owned here (a leaked `Box`) and freed only after the session is
+ /// invalidated, as the callback writes to it until then.
+ sink: NonNull<Sink>,
+ hardware: bool,
+}
+
+impl Session {
+ /// A session for `format`; with `require_hardware`, only on Apple's
+ /// hardware decoder (else VideoToolbox picks, hardware first).
+ pub(super) fn new(format: &Format, require_hardware: bool) -> Result<Session, StartError> {
+ // SAFETY: the dictionaries retain their keys and values; constants
+ // are the frameworks' own.
+ let (specification, attributes) = unsafe {
+ let specification = if require_hardware {
+ Some(dictionary(&[(
+ kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder,
+ kCFBooleanTrue,
+ )])?)
+ } else {
+ None
+ };
+ // NV12 in whichever range the stream has; the format type says which.
+ let number = |value: i32| {
+ Owned::new(CFNumberCreate(ptr::null(), CF_NUMBER_SINT32, (&raw const value).cast()))
+ };
+ let (Some(video), Some(full)) = (number(NV12_VIDEO_RANGE as i32), number(NV12_FULL_RANGE as i32))
+ else {
+ return Err("CFNumberCreate failed".into());
+ };
+ let values = [video.get().cast_const(), full.get().cast_const()];
+ let array = Owned::new(CFArrayCreate(
+ ptr::null(),
+ values.as_ptr(),
+ values.len() as CFIndex,
+ (&raw const kCFTypeArrayCallBacks).cast(),
+ ))
+ .ok_or("CFArrayCreate failed")?;
+ (specification, dictionary(&[(kCVPixelBufferPixelFormatTypeKey, array.get().cast_const())])?)
+ };
+ let sink = NonNull::from(Box::leak(Box::<Sink>::default()));
+ let record = OutputCallbackRecord {
+ decompression_output_callback: Some(on_output),
+ decompression_output_ref_con: sink.as_ptr().cast(),
+ };
+ let mut out = ptr::null_mut();
+ // SAFETY: all arguments are live; the session copies `record` and
+ // comes back with one reference, ours.
+ let status = unsafe {
+ VTDecompressionSessionCreate(
+ ptr::null(),
+ format.0.get(),
+ specification.as_ref().map_or(ptr::null(), |s| s.get().cast_const()),
+ attributes.get(),
+ &record,
+ &mut out,
+ )
+ };
+ let Some(session) = Owned::new(out).filter(|_| status == 0) else {
+ // SAFETY: no session refers to the sink.
+ drop(unsafe { Box::from_raw(sink.as_ptr()) });
+ return Err(StartError::from_status(status, "starting the H.264 decoder"));
+ };
+ // SAFETY: a live session and the framework's key. A missing answer
+ // after a required-hardware create is still hardware (VTDecompressionProperties.h).
+ let reported = unsafe {
+ bool_property(session.get(), kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder)
+ };
+ let hardware = hardware_in_use(require_hardware, reported);
+ Ok(Session { session, sink, hardware })
+ }
+
+ /// Whether Apple's hardware decoder runs this session, as VideoToolbox says.
+ pub(super) fn on_gpu(&self) -> bool {
+ self.hardware
+ }
+
+ /// Whether this session can go on with a new format (new SPS or PPS).
+ pub(super) fn can_accept(&self, format: &Format) -> bool {
+ // SAFETY: both are live.
+ unsafe { VTDecompressionSessionCanAcceptFormatDescription(self.session.get(), format.0.get()) != 0 }
+ }
+
+ /// Decodes one access unit (`avcc`, in `format`) into its pictures.
+ pub(super) fn decode(
+ &mut self,
+ format: &Format,
+ avcc: &[u8],
+ presentation_us: i64,
+ ) -> Result<Vec<Picture>, String> {
+ let sample = sample(format, avcc, presentation_us)?;
+ let mut info = 0;
+ // SAFETY: both are live. With no flags, the callback has run by the
+ // time this returns (VTDecompressionSession.h).
+ let status = unsafe {
+ VTDecompressionSessionDecodeFrame(self.session.get(), sample.get(), 0, ptr::null_mut(), &mut info)
+ };
+ let frames = std::mem::take(&mut *self.sink().frames.lock().unwrap_or_else(|e| e.into_inner()));
+ check(status, "decoding H.264")?;
+ match frames.error {
+ Some(error) => Err(error),
+ None => Ok(frames.pictures),
+ }
+ }
+
+ fn sink(&self) -> &Sink {
+ // SAFETY: freed only in `drop`.
+ unsafe { self.sink.as_ref() }
+ }
+}
+
+impl Drop for Session {
+ fn drop(&mut self) {
+ // SAFETY: once invalidated the session calls back no more, so the
+ // sink can go; the session's reference is released after this.
+ unsafe {
+ VTDecompressionSessionWaitForAsynchronousFrames(self.session.get());
+ VTDecompressionSessionInvalidate(self.session.get());
+ drop(Box::from_raw(self.sink.as_ptr()));
+ }
+ }
+}
+
+/// A sample buffer holding `avcc`, a copy CoreMedia allocates.
+fn sample(format: &Format, avcc: &[u8], presentation_us: i64) -> Result<Owned, String> {
+ if avcc.is_empty() {
+ return Err("an empty access unit".into());
+ }
+ let len = avcc.len();
+ let mut block = ptr::null_mut();
+ // SAFETY: CoreMedia allocates `len` bytes now, with the default allocator.
+ let status = unsafe {
+ CMBlockBufferCreateWithMemoryBlock(
+ ptr::null(),
+ ptr::null_mut(),
+ len,
+ ptr::null(),
+ ptr::null(),
+ 0,
+ len,
+ CM_BLOCK_BUFFER_ASSURE_MEMORY_NOW,
+ &mut block,
+ )
+ };
+ let block = Owned::new(block);
+ check(status, "allocating a sample")?;
+ let block = block.ok_or("no block buffer")?;
+ // SAFETY: `avcc` is `len` bytes, as is the block.
+ let status = unsafe { CMBlockBufferReplaceDataBytes(avcc.as_ptr().cast(), block.get(), 0, len) };
+ check(status, "copying a sample")?;
+ let timing = CMSampleTimingInfo {
+ duration: CM_TIME_INVALID,
+ presentation_time_stamp: CMTime {
+ value: presentation_us,
+ timescale: 1_000_000,
+ flags: CM_TIME_VALID,
+ epoch: 0,
+ },
+ decode_time_stamp: CM_TIME_INVALID,
+ };
+ let mut sample = ptr::null_mut();
+ // SAFETY: one sample of `len` bytes with one timing entry, all live;
+ // the sample comes back with one reference, ours.
+ let status = unsafe {
+ CMSampleBufferCreateReady(
+ ptr::null(),
+ block.get(),
+ format.0.get(),
+ 1,
+ 1,
+ &timing,
+ 1,
+ &len,
+ &mut sample,
+ )
+ };
+ let sample = Owned::new(sample);
+ check(status, "making a sample")?;
+ sample.ok_or_else(|| "no sample buffer".into())
+}
+
+/// The session's output callback: copies the picture out, or notes the error.
+unsafe extern "C" fn on_output(
+ sink: *mut c_void,
+ _frame: *mut c_void,
+ status: OSStatus,
+ info: u32,
+ image: CVImageBufferRef,
+ _presentation: CMTime,
+ _duration: CMTime,
+) {
+ // A panic must not unwind into VideoToolbox.
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ // SAFETY: the session's sink, alive until the session is invalidated.
+ let sink = unsafe { &*sink.cast::<Sink>() };
+ let result = if status != 0 {
+ Err(describe(status, "decoding H.264"))
+ } else if info & (DECODE_INFO_FRAME_DROPPED | DECODE_INFO_FRAME_INTERRUPTED) != 0 {
+ // Dropped, or decoded but not handed over (maybe black): nothing to show.
+ return;
+ } else if image.is_null() {
+ Err("VideoToolbox decoded no picture".into())
+ } else {
+ // SAFETY: VideoToolbox keeps `image` alive during the callback.
+ unsafe { copy_picture(image) }
+ };
+ let mut frames = sink.frames.lock().unwrap_or_else(|e| e.into_inner());
+ match result {
+ Ok(picture) => {
+ if frames.pictures.len() == MAX_PENDING {
+ frames.pictures.remove(0);
+ }
+ frames.pictures.push(picture);
+ }
+ Err(error) => {
+ frames.error.get_or_insert(error);
+ }
+ }
+ }));
+}
+
+/// Copies an NV12 pixel buffer into a tightly packed [`Picture`].
+///
+/// # Safety
+/// `image` is a live CoreVideo image buffer.
+unsafe fn copy_picture(image: CVImageBufferRef) -> Result<Picture, String> {
+ // SAFETY: CoreVideo queries on a live buffer; planes are read only while
+ // locked, and only at a checked offset inside the capped stride.
+ unsafe {
+ if CFGetTypeID(image) != CVPixelBufferGetTypeID() {
+ return Err("VideoToolbox decoded into something other than a pixel buffer".into());
+ }
+ let full_range = match CVPixelBufferGetPixelFormatType(image) {
+ NV12_VIDEO_RANGE => false,
+ NV12_FULL_RANGE => true,
+ other => {
+ let code = String::from_utf8_lossy(&other.to_be_bytes()).into_owned();
+ return Err(format!("VideoToolbox decoded into '{code}', not NV12"));
+ }
+ };
+ if CVPixelBufferIsPlanar(image) == 0 || CVPixelBufferGetPlaneCount(image) != 2 {
+ return Err("an NV12 picture without two planes".into());
+ }
+ let (width, height) = (CVPixelBufferGetWidth(image), CVPixelBufferGetHeight(image));
+ if !(1..=MAX_DIMENSION).contains(&width) || !(1..=MAX_DIMENSION).contains(&height) {
+ return Err(format!("a decoded picture of {width}x{height}"));
+ }
+ // Chroma rows hold `width` rounded up to even bytes (Cb, Cr pairs).
+ let stride = width.next_multiple_of(2);
+ let chroma_rows = height.div_ceil(2);
+ let _lock = Lock::new(image)?;
+ let (luma, luma_pitch) = plane(image, 0, width, height)?;
+ let (chroma, chroma_pitch) = plane(image, 1, stride, chroma_rows)?;
+ let mut nv12 = vec![0; stride * (height + chroma_rows)];
+ let (luma_out, chroma_out) = nv12.split_at_mut(stride * height);
+ for (row, out) in luma_out.chunks_exact_mut(stride).enumerate() {
+ let offset = plane_row_offset(row, luma_pitch, width)?;
+ // `offset` is `row * pitch` and does not wrap; the row holds `width` bytes.
+ out[..width].copy_from_slice(slice::from_raw_parts(luma.add(offset), width));
+ }
+ for (row, out) in chroma_out.chunks_exact_mut(stride).enumerate() {
+ let offset = plane_row_offset(row, chroma_pitch, stride)?;
+ out.copy_from_slice(slice::from_raw_parts(chroma.add(offset), stride));
+ }
+ Ok(Picture {
+ width: width as u32,
+ height: height as u32,
+ stride,
+ plane_rows: height,
+ nv12,
+ colors: Colors { bt601: matrix_is_bt601(image), full_range },
+ })
+ }
+}
+
+/// A plane's start and bytes per row, if it holds `rows` rows of `row_bytes`.
+///
+/// # Safety
+/// `image` is a live pixel buffer, locked.
+unsafe fn plane(
+ image: CVImageBufferRef,
+ index: usize,
+ row_bytes: usize,
+ rows: usize,
+) -> Result<(*const u8, usize), String> {
+ // SAFETY: as the caller promises.
+ let (base, pitch, plane_rows) = unsafe {
+ (
+ CVPixelBufferGetBaseAddressOfPlane(image, index).cast::<u8>().cast_const(),
+ CVPixelBufferGetBytesPerRowOfPlane(image, index),
+ CVPixelBufferGetHeightOfPlane(image, index),
+ )
+ };
+ if base.is_null() || rows == 0 || plane_rows < rows {
+ return Err(format!(
+ "NV12 plane {index} is {pitch} bytes x {plane_rows} rows, short of {row_bytes} x {rows}"
+ ));
+ }
+ // The last row's offset must fit. A later row in the copy uses the same check.
+ plane_row_offset(rows - 1, pitch, row_bytes).map_err(|error| format!("NV12 plane {index}: {error}"))?;
+ Ok((base, pitch))
+}
+
+/// Largest bytes-per-row accepted for a row of `row_bytes` pixels: sixteen
+/// times the row, and at least 4 KiB of padding, so alignment is allowed and
+/// a corrupt stride cannot be indexed.
+pub(super) fn max_plane_pitch(row_bytes: usize) -> usize {
+ row_bytes.saturating_mul(16).max(row_bytes.saturating_add(4096))
+}
+
+/// Byte offset of `row` when each row is `pitch` bytes and `row_bytes` are read.
+/// `pitch` must sit between `row_bytes` and [`max_plane_pitch`], and the
+/// multiply must not wrap.
+pub(super) fn plane_row_offset(row: usize, pitch: usize, row_bytes: usize) -> Result<usize, String> {
+ let cap = max_plane_pitch(row_bytes);
+ if row_bytes == 0 || pitch < row_bytes || pitch > cap {
+ return Err(format!("an NV12 stride of {pitch} bytes for a row of {row_bytes}"));
+ }
+ let offset = row.checked_mul(pitch).ok_or("an NV12 plane stride overflows")?;
+ offset.checked_add(row_bytes).ok_or("an NV12 plane stride overflows")?;
+ Ok(offset)
+}
+
+/// Whether the picture is tagged BT.601 (the stream's VUI, as VideoToolbox
+/// passes it on); untagged pictures are taken as BT.709, as phones are asked.
+///
+/// # Safety
+/// `image` is a live CoreVideo buffer.
+unsafe fn matrix_is_bt601(image: CVImageBufferRef) -> bool {
+ // SAFETY: the attachment comes back with one reference, ours.
+ unsafe {
+ Owned::new(CVBufferCopyAttachment(image, kCVImageBufferYCbCrMatrixKey, ptr::null_mut()))
+ .is_some_and(|matrix| CFEqual(matrix.get(), kCVImageBufferYCbCrMatrix_ITU_R_601_4) != 0)
+ }
+}
+
+/// A pixel buffer's base address locked for reading, unlocked on drop.
+struct Lock(CVImageBufferRef);
+
+impl Lock {
+ /// # Safety
+ /// `image` is a live pixel buffer that outlives the lock.
+ unsafe fn new(image: CVImageBufferRef) -> Result<Lock, String> {
+ // SAFETY: as the caller promises.
+ let status = unsafe { CVPixelBufferLockBaseAddress(image, CV_LOCK_READ_ONLY) };
+ if status != 0 {
+ return Err(format!("CVPixelBufferLockBaseAddress failed ({status})"));
+ }
+ Ok(Lock(image))
+ }
+}
+
+impl Drop for Lock {
+ fn drop(&mut self) {
+ // SAFETY: locked in `new` with the same flags.
+ unsafe { CVPixelBufferUnlockBaseAddress(self.0, CV_LOCK_READ_ONLY) };
+ }
+}
+
+/// A CFDictionary of `pairs`, which it retains.
+///
+/// # Safety
+/// Every key and value is a live CF object.
+unsafe fn dictionary(pairs: &[(CFTypeRef, CFTypeRef)]) -> Result<Owned, String> {
+ let keys: Vec<CFTypeRef> = pairs.iter().map(|&(key, _)| key).collect();
+ let values: Vec<CFTypeRef> = pairs.iter().map(|&(_, value)| value).collect();
+ // SAFETY: `keys` and `values` hold `pairs.len()` live objects; the
+ // callback tables are CoreFoundation's own.
+ unsafe {
+ Owned::new(CFDictionaryCreate(
+ ptr::null(),
+ keys.as_ptr(),
+ values.as_ptr(),
+ pairs.len() as CFIndex,
+ (&raw const kCFTypeDictionaryKeyCallBacks).cast(),
+ (&raw const kCFTypeDictionaryValueCallBacks).cast(),
+ ))
+ }
+ .ok_or_else(|| "CFDictionaryCreate failed".into())
+}
+
+/// A session's boolean property, if it has one.
+///
+/// # Safety
+/// `session` is a live VideoToolbox session; `key` a CFString.
+unsafe fn bool_property(session: VTDecompressionSessionRef, key: CFStringRef) -> Option<bool> {
+ let mut value: CFTypeRef = ptr::null();
+ // SAFETY: the value comes back with one reference, ours; its type is
+ // checked before it's read as a boolean.
+ unsafe {
+ let status = VTSessionCopyProperty(session, key, ptr::null(), (&raw mut value).cast());
+ let value = Owned::new(value);
+ if status != 0 {
+ return None;
+ }
+ let value = value?;
+ (CFGetTypeID(value.get()) == CFBooleanGetTypeID()).then(|| CFBooleanGetValue(value.get()) != 0)
+ }
+}
+
+fn check(status: OSStatus, doing: &str) -> Result<(), String> {
+ if status == 0 { Ok(()) } else { Err(describe(status, doing)) }
+}
+
+/// An OSStatus from VideoToolbox or CoreMedia, named where VTErrors.h names it.
+fn describe(status: OSStatus, doing: &str) -> String {
+ let name = match status {
+ -12902 => "kVTParameterErr",
+ -12903 => "kVTInvalidSessionErr",
+ -12904 => "kVTAllocationFailedErr",
+ VT_COULD_NOT_FIND_VIDEO_DECODER => "kVTCouldNotFindVideoDecoderErr",
+ VT_COULD_NOT_CREATE_INSTANCE => "kVTCouldNotCreateInstanceErr",
+ -12909 => "kVTVideoDecoderBadDataErr",
+ -12910 => "kVTVideoDecoderUnsupportedDataFormatErr",
+ -12911 => "kVTVideoDecoderMalfunctionErr",
+ VT_VIDEO_DECODER_NOT_AVAILABLE_NOW => "kVTVideoDecoderNotAvailableNowErr",
+ -12916 => "kVTFormatDescriptionChangeNotSupportedErr",
+ -17690 => "kVTVideoDecoderRemovedErr",
+ -17691 => "kVTSessionMalfunctionErr",
+ -17694 => "kVTVideoDecoderReferenceMissingErr",
+ _ => "",
+ };
+ if name.is_empty() {
+ format!("{doing} failed ({status})")
+ } else {
+ format!("{doing} failed: {name} ({status})")
+ }
+}
diff --git a/desktop/app/src/mac/testdata/README.md b/desktop/app/src/mac/testdata/README.md
new file mode 100644
index 0000000..b9716da
--- /dev/null
+++ b/desktop/app/src/mac/testdata/README.md
@@ -0,0 +1,23 @@
+# Synthetic H.264 fixture
+
+`red-32x32.annexb` is an original, one-frame solid-red 32x32 test pattern,
+created locally without camera, microphone, screen capture or personal data.
+SHA-256: 8013c4ec0b809193701da4f9fca1d701601508f06776adf8f70bbe35cc823b45.
+
+Generated with FFmpeg/libx264 baseline, yuv420p, no B frames, repeated headers,
+AUD, BT.709 limited-range metadata; filter_units removes the SEI NAL. The encoder
+is a development tool and is not bundled with NectarLink. Offline reference decode
+produced one 4096-byte BGRA frame with first pixel [0, 0, 252, 255].
+
+Generation command:
+
+```sh
+ffmpeg -hide_banner -loglevel error -f lavfi -i color=c=red:size=32x32:rate=1 \
+ -frames:v 1 -pix_fmt yuv420p -c:v libx264 -profile:v baseline \
+ -preset ultrafast -tune zerolatency \
+ -x264-params keyint=1:bframes=0:repeat-headers=1:aud=1 \
+ -color_range tv -colorspace bt709 -color_primaries bt709 -color_trc bt709 \
+ -bsf:v filter_units=remove_types=6 -f h264 red-32x32.annexb
+```
+
+This test data is dedicated to the public domain under CC0-1.0.
diff --git a/desktop/app/src/mac/testdata/red-32x32.annexb b/desktop/app/src/mac/testdata/red-32x32.annexb
new file mode 100644
index 0000000..ad7b211
Binary files /dev/null and b/desktop/app/src/mac/testdata/red-32x32.annexb differ