Skip to main content

kessel_frame_ring/
lib.rs

1//! # kessel-frame-ring
2//!
3//! A single-producer, single-consumer ring of NV12 video frames in a
4//! shared-memory file, for handing frames from one process to another on
5//! the same machine. It was made for an iPhone's screen share: the broadcast
6//! upload extension (the producer, its own process with a 50 MB cap) copies
7//! each screen frame in, and the app (the consumer) reads it out and
8//! encodes it.
9//!
10//! - **The consumer creates the ring** ([`Consumer::create`]) in a file both
11//!   processes can open (an App Group container on iOS), with a fixed
12//!   [`Layout`]: the largest frame (either way round), the slot count and the
13//!   highest rate. The producer maps it read-write ([`Producer::attach`]).
14//! - **The producer never blocks and never waits for the consumer.** It
15//!   scales each frame down to fit the layout's box, writes it into the slot
16//!   after the newest one, and publishes it. When the consumer doesn't want
17//!   frames, is gone, or hasn't looked for two seconds (the app suspended),
18//!   pushes return at once without copying anything.
19//! - **Each frame carries its own size, rotation, colour and timestamp**, so
20//!   a turn or a new size needs no re-layout. Only the capacity is fixed.
21//! - **Torn frames are never read.** Each slot has a sequence word (a
22//!   seqlock): odd while being written, even when whole. A producer killed
23//!   mid-write leaves its slot odd and unpublished; the next producer
24//!   rewrites it. A consumer suspended mid-read finds the sequence moved and
25//!   drops the copy.
26//! - **The control words** carry the producer's state (waiting, running,
27//!   ended and why) and the consumer's wishes (wants frames, please stop,
28//!   gone, highest rate). A producer holds an advisory lock on the file
29//!   while attached, so the consumer can tell a killed producer
30//!   ([`ProducerState::Gone`]) from one that is merely quiet.
31//! - **Memory stays bounded:** the file is the header and the slots, sized
32//!   once; nothing is allocated per frame on the producer's side.
33//! - **The consumer trusts nothing in the file.** The producer is another
34//!   process, so a frame's slot, size, rotation, colour and length are
35//!   checked against the consumer's own layout before a byte is copied
36//!   (see [`FrameInfo`]), and the file's length before each use of the
37//!   mapping. The README's "Trust boundary" says what that covers and
38//!   what it can't.
39//! - **The producer trusts nothing in the file either.** The consumer is
40//!   another process too: the producer checks the layout once, at attach,
41//!   writes by its own copy, keeps its own count of each slot's sequence
42//!   word and of the newest slot (a word in the file is never added to),
43//!   holds the rate to a layout's range, and checks the file's length
44//!   before each use of the mapping.
45//!
46//! The producer's whole surface is also a small `extern "C"` API ([`ffi`]),
47//! for an app extension written in Swift that links this crate as a static
48//! library. Unix only (macOS, iOS, Linux, Android).
49//!
50//! ```
51//! # #[cfg(unix)] {
52//! use kessel_frame_ring::{Consumer, Layout, Nv12Frame, Producer, Pushed};
53//!
54//! let path = std::env::temp_dir().join(format!("doc-ring-{}", std::process::id()));
55//! let mut consumer = Consumer::create(&path, Layout::new(64, 48))?;
56//! let mut producer = Producer::attach(&path)?;
57//! producer.start();
58//! let (y, uv) = (vec![100u8; 64 * 48], vec![128u8; 64 * 24]);
59//! let frame = Nv12Frame::new(&y, 64, &uv, 64, 64, 48);
60//! assert!(matches!(producer.push(&frame)?, Pushed::Written { .. }));
61//! let mut buf = Vec::new();
62//! let info = consumer.try_read(&mut buf).expect("a frame");
63//! assert_eq!((info.width, info.height, buf.len()), (64, 48, 64 * 48 * 3 / 2));
64//! # }
65//! # Ok::<(), kessel_frame_ring::RingError>(())
66//! ```
67
68// Off Unix only the types build; the layout's words go unused.
69#![cfg_attr(not(unix), allow(dead_code))]
70
71#[cfg(unix)]
72mod consumer;
73#[cfg(unix)]
74pub mod ffi;
75#[cfg(unix)]
76mod producer;
77#[cfg(unix)]
78mod scale;
79#[cfg(unix)]
80mod shm;
81#[cfg(all(test, unix))]
82mod hostile_tests;
83#[cfg(all(test, unix))]
84mod tests;
85
86#[cfg(unix)]
87pub use consumer::Consumer;
88#[cfg(unix)]
89pub use producer::{Producer, Pushed};
90#[cfg(unix)]
91pub use shm::monotonic_ns;
92
93/// The format version in the header. A file of another version is refused.
94pub const VERSION: u32 = 1;
95/// The most slots a ring may have.
96pub const MAX_SLOTS: u32 = 8;
97/// The largest side of the layout's box.
98pub const MAX_SIDE: u32 = 4096;
99/// The largest side of a frame handed to [`Producer::push`] (it is scaled
100/// down to the box).
101pub const MAX_INPUT_SIDE: u32 = 16_384;
102/// The consumer counts as away when it hasn't looked for this long (ns).
103pub const CONSUMER_STALE_NS: u64 = 2_000_000_000;
104
105/// The ring's fixed shape, set by the consumer.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107#[non_exhaustive]
108pub struct Layout {
109    /// The widest frame, landscape (even, 16 to [`MAX_SIDE`]). The box is
110    /// orientation-free: a 1280 x 720 layout also takes 720 x 1280.
111    pub max_width: u32,
112    /// The tallest frame, landscape (even, 16 to [`MAX_SIDE`]).
113    pub max_height: u32,
114    /// Slots (2 to [`MAX_SLOTS`]): the newest frame, one being written, and
115    /// one spare for a slow reader. Default 3.
116    pub slots: u32,
117    /// The producer drops frames that come faster than this (0: no limit).
118    /// The consumer can change it while running. Default 15.
119    pub max_fps: u32,
120}
121
122impl Layout {
123    /// A `max_width` x `max_height` box, 3 slots, at most 15 fps.
124    pub fn new(max_width: u32, max_height: u32) -> Layout {
125        Layout {
126            max_width,
127            max_height,
128            slots: 3,
129            max_fps: 15,
130        }
131    }
132
133    /// 1280 x 720 (either way round), 3 slots, 15 fps: about 4 MB.
134    pub fn hd720() -> Layout {
135        Layout::new(1280, 720)
136    }
137
138    /// Check the fields.
139    pub fn validate(&self) -> Result<(), RingError> {
140        for (what, v) in [("width", self.max_width), ("height", self.max_height)] {
141            if !(16..=MAX_SIDE).contains(&v) || !v.is_multiple_of(2) {
142                return Err(RingError::Invalid(format!("a max {what} of {v}")));
143            }
144        }
145        if !(2..=MAX_SLOTS).contains(&self.slots) {
146            return Err(RingError::Invalid(format!("{} slots", self.slots)));
147        }
148        if self.max_fps > layout::MAX_FPS {
149            return Err(RingError::Invalid(format!("{} fps", self.max_fps)));
150        }
151        Ok(())
152    }
153
154    /// The bytes one slot holds: an NV12 frame of the box.
155    pub fn slot_bytes(&self) -> usize {
156        nv12_len(self.max_width, self.max_height)
157    }
158
159    /// The whole file's length (`usize::MAX` for a layout too large to
160    /// exist, which [`Layout::validate`] refuses).
161    pub fn file_len(&self) -> usize {
162        (self.slots as usize)
163            .saturating_mul(self.slot_stride())
164            .saturating_add(layout::HEADER)
165    }
166
167    pub(crate) fn slot_stride(&self) -> usize {
168        layout::SLOT_HEADER
169            .saturating_add(self.slot_bytes())
170            .div_ceil(64)
171            .saturating_mul(64)
172    }
173
174    /// Does a `width` x `height` frame fit the box, either way round?
175    pub(crate) fn fits(&self, width: u32, height: u32) -> bool {
176        let (bw, bh) = (self.max_width, self.max_height);
177        (width <= bw && height <= bh) || (width <= bh && height <= bw)
178    }
179}
180
181/// The bytes of a tight NV12 frame: the Y plane, then interleaved U and V
182/// at half size (rounded up). `usize::MAX` when that doesn't fit a `usize`
183/// (no real frame is that large), so it never overflows.
184pub fn nv12_len(width: u32, height: u32) -> usize {
185    let (w, h) = (u64::from(width), u64::from(height));
186    // Each term fits a u64 (under 2^64 and 2^63); only the sum may not.
187    let len = (w * h).saturating_add(2 * w.div_ceil(2) * h.div_ceil(2));
188    usize::try_from(len).unwrap_or(usize::MAX)
189}
190
191/// The colour description of a frame's YUV.
192#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
193#[repr(u32)]
194#[non_exhaustive]
195pub enum Color {
196    /// BT.601, limited range (16-235).
197    #[default]
198    Bt601Limited = 0,
199    /// BT.709, limited range (`420v` pixel buffers).
200    Bt709Limited = 1,
201    /// BT.709, full range (`420f` pixel buffers).
202    Bt709Full = 2,
203}
204
205impl Color {
206    /// From its number (0, 1 or 2).
207    pub fn from_u32(v: u32) -> Option<Color> {
208        match v {
209            0 => Some(Color::Bt601Limited),
210            1 => Some(Color::Bt709Limited),
211            2 => Some(Color::Bt709Full),
212            _ => None,
213        }
214    }
215}
216
217/// Why the producer stopped.
218#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219#[repr(u32)]
220#[non_exhaustive]
221pub enum EndReason {
222    /// The person stopped it (an iOS broadcast's `broadcastFinished`).
223    UserStopped = 1,
224    /// The producer went away for another reason, or was dropped without
225    /// saying why.
226    SourceClosed = 2,
227    /// The producer failed.
228    Failed = 3,
229}
230
231impl EndReason {
232    /// From its number (1, 2 or 3).
233    pub fn from_u32(v: u32) -> Option<EndReason> {
234        match v {
235            1 => Some(EndReason::UserStopped),
236            2 => Some(EndReason::SourceClosed),
237            3 => Some(EndReason::Failed),
238            _ => None,
239        }
240    }
241}
242
243/// What the consumer knows of the producer.
244#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
245#[non_exhaustive]
246pub enum ProducerState {
247    /// None attached yet, or attached and not started.
248    Waiting,
249    /// Started and alive.
250    Running,
251    /// Stopped, and said why.
252    Ended(EndReason),
253    /// Started, then died without a word (killed, or crashed): its lock on
254    /// the file is gone.
255    Gone,
256}
257
258/// One frame for [`Producer::push`]: NV12 planes with any row strides
259/// (bytes per row of each plane), as a `CVPixelBuffer` hands them out.
260#[derive(Clone, Copy, Debug)]
261#[non_exhaustive]
262pub struct Nv12Frame<'a> {
263    /// The Y plane: `height` rows of `y_stride` bytes (the last row may
264    /// stop at `width`).
265    pub y: &'a [u8],
266    /// Bytes per Y row (at least `width`).
267    pub y_stride: usize,
268    /// The interleaved U and V plane: half the rows (rounded up).
269    pub uv: &'a [u8],
270    /// Bytes per UV row (at least `width` rounded up to even).
271    pub uv_stride: usize,
272    /// Width in pixels.
273    pub width: u32,
274    /// Height in pixels.
275    pub height: u32,
276    /// How far the frame must turn clockwise to stand upright: 0, 90, 180
277    /// or 270. It travels with the frame; the consumer turns it.
278    pub rotation: u32,
279    /// The colour description.
280    pub color: Color,
281    /// When it was captured, in ns on [`monotonic_ns`]'s clock (the same
282    /// in every process: mach absolute time on Apple, `CLOCK_MONOTONIC`
283    /// elsewhere). 0: stamp it now.
284    pub timestamp_ns: u64,
285}
286
287impl<'a> Nv12Frame<'a> {
288    /// Upright, BT.601 limited range, stamped when pushed.
289    pub fn new(
290        y: &'a [u8],
291        y_stride: usize,
292        uv: &'a [u8],
293        uv_stride: usize,
294        width: u32,
295        height: u32,
296    ) -> Nv12Frame<'a> {
297        Nv12Frame {
298            y,
299            y_stride,
300            uv,
301            uv_stride,
302            width,
303            height,
304            rotation: 0,
305            color: Color::Bt601Limited,
306            timestamp_ns: 0,
307        }
308    }
309
310    pub(crate) fn validate(&self) -> Result<(), RingError> {
311        let bad = |why: String| Err(RingError::Invalid(why));
312        let (w, h) = (self.width as usize, self.height as usize);
313        if !(1..=MAX_INPUT_SIDE).contains(&self.width)
314            || !(1..=MAX_INPUT_SIDE).contains(&self.height)
315        {
316            return bad(format!("a {w}x{h} frame"));
317        }
318        if !matches!(self.rotation, 0 | 90 | 180 | 270) {
319            return bad(format!("a rotation of {}", self.rotation));
320        }
321        // A plane of `rows` rows `stride` apart, the last `row` bytes long,
322        // needs this many bytes; None when that overflows (a stride no real
323        // plane has).
324        let need =
325            |stride: usize, rows: usize, row: usize| stride.checked_mul(rows - 1)?.checked_add(row);
326        if self.y_stride < w {
327            return bad(format!("a Y stride of {} for {w} pixels", self.y_stride));
328        }
329        if need(self.y_stride, h, w).is_none_or(|n| self.y.len() < n) {
330            return bad(format!(
331                "a {}-byte Y plane for {w}x{h}, stride {}",
332                self.y.len(),
333                self.y_stride
334            ));
335        }
336        let (cw2, ch) = (2 * w.div_ceil(2), h.div_ceil(2));
337        if self.uv_stride < cw2 {
338            return bad(format!("a UV stride of {} for {w} pixels", self.uv_stride));
339        }
340        if need(self.uv_stride, ch, cw2).is_none_or(|n| self.uv.len() < n) {
341            return bad(format!(
342                "a {}-byte UV plane for {w}x{h}, stride {}",
343                self.uv.len(),
344                self.uv_stride
345            ));
346        }
347        Ok(())
348    }
349}
350
351/// One frame read by [`Consumer::try_read`]: what it is, and where its
352/// planes sit in the bytes read out (tight NV12).
353///
354/// The producer is another process, so the consumer checks what it wrote
355/// before handing a frame out: the width and height are at least 1 and fit
356/// the ring's box (either way round), the rotation is 0, 90, 180 or 270,
357/// the colour is one this version knows, and the bytes read out are exactly
358/// [`FrameInfo::len`]. A slot that fails a check is skipped
359/// ([`RingStats::rejected`]). The timestamp and the frame number are only
360/// numbers: use them with saturating or checked maths.
361#[derive(Clone, Copy, Debug, PartialEq, Eq)]
362#[non_exhaustive]
363pub struct FrameInfo {
364    /// Counts up from 1 across producers (to 2^56 - 1, then from 1 again);
365    /// a gap means frames were skipped.
366    pub frame_no: u64,
367    /// Width in pixels (after the producer's scaling).
368    pub width: u32,
369    /// Height in pixels.
370    pub height: u32,
371    /// How far to turn it clockwise to stand upright: 0, 90, 180 or 270.
372    pub rotation: u32,
373    /// The colour description.
374    pub color: Color,
375    /// Capture time, ns on [`monotonic_ns`]'s clock, as the producer
376    /// stamped it.
377    pub timestamp_ns: u64,
378}
379
380impl FrameInfo {
381    /// Bytes per Y row (the width).
382    pub fn y_stride(&self) -> usize {
383        self.width as usize
384    }
385
386    /// Where the UV plane starts.
387    pub fn uv_offset(&self) -> usize {
388        (self.width as usize).saturating_mul(self.height as usize)
389    }
390
391    /// Bytes per UV row (the width rounded up to even).
392    pub fn uv_stride(&self) -> usize {
393        2 * (self.width as usize).div_ceil(2)
394    }
395
396    /// The whole frame's bytes.
397    pub fn len(&self) -> usize {
398        nv12_len(self.width, self.height)
399    }
400
401    /// Never: a frame has at least one pixel.
402    pub fn is_empty(&self) -> bool {
403        self.len() == 0
404    }
405}
406
407/// The consumer's counters.
408#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
409#[non_exhaustive]
410pub struct RingStats {
411    /// Frames the producers wrote.
412    pub written: u64,
413    /// Frames the producers dropped (not wanted, or over the rate).
414    pub dropped: u64,
415    /// Frames written but never read (the consumer read a newer one).
416    pub missed: u64,
417    /// Reads given up because the producer kept rewriting the slot.
418    pub torn: u64,
419    /// Frames skipped because their slot didn't describe a valid frame (a
420    /// corrupt ring, or a producer that misbehaves). Counted once per
421    /// frame.
422    pub rejected: u64,
423    /// Producers that attached.
424    pub attaches: u64,
425}
426
427/// What went wrong.
428#[derive(Debug)]
429#[non_exhaustive]
430pub enum RingError {
431    /// No ring at that path: the consumer hasn't made one (on iOS, the app
432    /// isn't in a call).
433    NotFound,
434    /// Another producer is attached.
435    Busy,
436    /// The file isn't a ring of this version, or its length doesn't match
437    /// its layout.
438    Mismatch(String),
439    /// A bad argument: a layout, a frame's size, strides or rotation.
440    Invalid(String),
441    /// The OS failed.
442    Io(std::io::Error),
443}
444
445impl RingError {
446    /// The `extern "C"` code: -1 invalid, -2 not found, -3 busy, -4
447    /// mismatch, -5 I/O.
448    pub fn code(&self) -> i32 {
449        match self {
450            RingError::Invalid(_) => -1,
451            RingError::NotFound => -2,
452            RingError::Busy => -3,
453            RingError::Mismatch(_) => -4,
454            RingError::Io(_) => -5,
455        }
456    }
457}
458
459impl std::fmt::Display for RingError {
460    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
461        match self {
462            RingError::NotFound => f.write_str("no frame ring there"),
463            RingError::Busy => f.write_str("another producer is attached"),
464            RingError::Mismatch(why) => write!(f, "not a matching frame ring: {why}"),
465            RingError::Invalid(why) => write!(f, "invalid: {why}"),
466            RingError::Io(e) => write!(f, "I/O: {e}"),
467        }
468    }
469}
470
471impl std::error::Error for RingError {
472    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
473        match self {
474            RingError::Io(e) => Some(e),
475            _ => None,
476        }
477    }
478}
479
480impl From<std::io::Error> for RingError {
481    fn from(e: std::io::Error) -> RingError {
482        if e.kind() == std::io::ErrorKind::NotFound {
483            RingError::NotFound
484        } else {
485            RingError::Io(e)
486        }
487    }
488}
489
490/// The file's layout: a 256-byte header, then the slots, each a 64-byte
491/// header and an NV12 frame of the box, rounded up to 64 bytes. Every
492/// number is in the machine's byte order (both sides run on one machine).
493pub(crate) mod layout {
494    /// "KFRAMRNG" read as a little-endian u64.
495    pub(crate) const MAGIC: u64 = u64::from_le_bytes(*b"KFRAMRNG");
496    pub(crate) const HEADER: usize = 256;
497    pub(crate) const SLOT_HEADER: usize = 64;
498
499    // Header words. Fixed at create: magic to slot bytes.
500    pub(crate) const H_MAGIC: usize = 0; // u64
501    pub(crate) const H_VERSION: usize = 8; // u32
502    pub(crate) const H_HEADER_SIZE: usize = 12; // u32
503    pub(crate) const H_SLOT_HEADER: usize = 16; // u32
504    pub(crate) const H_SLOTS: usize = 20; // u32
505    pub(crate) const H_MAX_WIDTH: usize = 24; // u32
506    pub(crate) const H_MAX_HEIGHT: usize = 28; // u32
507    pub(crate) const H_SLOT_BYTES: usize = 32; // u64
508                                               // The consumer's words.
509    pub(crate) const H_MAX_FPS: usize = 40; // u32
510    pub(crate) const H_FLAGS: usize = 44; // u32, F_*
511    pub(crate) const H_BEAT: usize = 48; // u64, ns: when the consumer last looked
512                                         // The producer's words.
513    pub(crate) const H_STATE: usize = 56; // u32, S_*
514    pub(crate) const H_END_REASON: usize = 60; // u32, EndReason
515    pub(crate) const H_LATEST: usize = 64; // u64: frame_no << 8 | slot; 0 = none
516    /// The largest frame number (56 bits, beside the slot in `H_LATEST`).
517    /// After it the producer starts again at 1.
518    pub(crate) const MAX_FRAME_NO: u64 = (1 << 56) - 1;
519    /// The highest rate a layout may ask for.
520    pub(crate) const MAX_FPS: u32 = 240;
521    /// The largest sequence word a producer writes counts from: it starts
522    /// again at 0 after (2^61 frames, never reached). A larger word in the
523    /// file is corruption, and the producer never adds to it.
524    pub(crate) const MAX_SEQ: u64 = 1 << 62;
525    pub(crate) const H_WRITTEN: usize = 72; // u64
526    pub(crate) const H_DROPPED: usize = 80; // u64
527    pub(crate) const H_ATTACHES: usize = 88; // u64
528
529    /// The consumer wants frames.
530    pub(crate) const F_WANTS: u32 = 1;
531    /// The consumer asks the producer to stop.
532    pub(crate) const F_STOP: u32 = 2;
533    /// The consumer is gone.
534    pub(crate) const F_GONE: u32 = 4;
535
536    pub(crate) const S_WAITING: u32 = 0;
537    pub(crate) const S_RUNNING: u32 = 1;
538    pub(crate) const S_ENDED: u32 = 2;
539
540    // Slot header words. Written by the producer under the slot's seqlock.
541    pub(crate) const SL_SEQ: usize = 0; // u64: odd while writing
542    pub(crate) const SL_FRAME_NO: usize = 8; // u64
543    pub(crate) const SL_WIDTH: usize = 16; // u32
544    pub(crate) const SL_HEIGHT: usize = 20; // u32
545    pub(crate) const SL_ROTATION: usize = 24; // u32
546    pub(crate) const SL_COLOR: usize = 28; // u32
547    pub(crate) const SL_TIMESTAMP: usize = 32; // u64
548    pub(crate) const SL_LEN: usize = 40; // u64
549}