Skip to main content

moq_ext_sources/source/
rpicam.rs

1//! Raspberry Pi camera capture through `rpicam-vid`.
2//!
3//! On Raspberry Pi OS the CSI camera is only reachable through libcamera.
4//! `/dev/video0` returns raw Bayer data from the Unicam sensor, which is
5//! unusable without the ISP. This module runs `rpicam-vid` as a subprocess and
6//! reads its stdout, which carries one of two [`Output`]s:
7//!
8//! - [`Output::H264`] is Annex-B from the Pi's hardware encoder, returned by
9//!   [`rpicam_h264`](crate::rpicam_h264). It avoids both the raw pipe (about
10//!   10 MB/s at 640x360) and a second encode.
11//! - [`Output::I420`] is raw pictures, which become a
12//!   [`VideoSource`](crate::VideoSource) of [`Surface::I420`]. It costs the
13//!   pipe and an encode. It is the only path for anything that needs pixels,
14//!   such as a preview, a QR scanner or a rendition ladder.
15
16use std::{
17    collections::VecDeque,
18    process::Stdio,
19    sync::{Arc, Mutex},
20    time::Duration,
21};
22
23use bytes::{Bytes, BytesMut};
24use n0_future::{
25    StreamExt,
26    boxed::BoxStream,
27    task::{AbortOnDropHandle, spawn},
28};
29use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
30use tokio_util::sync::CancellationToken;
31use tracing::{debug, info, warn};
32
33use super::VideoFormat;
34use crate::{
35    Error,
36    frames::FrameSlot,
37    local_task::{self, LocalTask},
38    video::{Frame, FrameRate, I420, Size, Surface},
39};
40
41/// The camera app this module runs.
42const RPICAM_VID: &str = "rpicam-vid";
43
44/// How much stdout to take per read.
45///
46/// One H.264 access unit at 500 kbps and 30 fps is about 2 KB, so one read
47/// takes several frames. A raw picture takes several reads.
48const READ_CHUNK: usize = 32 * 1024;
49
50/// How many lines of the subprocess's stderr to keep for the exit report.
51///
52/// `rpicam-vid` gives its reason in the last line or two, after a libcamera
53/// banner.
54const STDERR_TAIL_LINES: usize = 10;
55
56/// How long to wait for the exit status once the subprocess closes stdout.
57///
58/// It only matters for an app that stops writing but does not exit.
59const EXIT_TIMEOUT: Duration = Duration::from_secs(2);
60
61/// The pixel alignment libcamera gives each row of a raw picture.
62///
63/// The raw stream carries no strides, so pictures can only be split off it if
64/// the rows are tightly packed. libcamera rounds the luma row up to a multiple
65/// of this and the chroma rows to half of it, and the padding goes down the
66/// pipe.
67///
68/// Measured on a Pi 4 (rpicam-apps 2024-06-17, libcamera v0.3.0, IMX708) with
69/// 1500 ms captures: 320x240, 640x360 and 1280x720 divide exactly into
70/// `width * height * 3 / 2` byte pictures. Widths 642, 656, 672, 688 and 700
71/// give the same byte count as 704, 800 the same as 832, and 96 the same as
72/// 128. Heights are not padded: 358 and 362 come out exact.
73const RAW_WIDTH_ALIGN: u32 = 64;
74
75/// Target bitrate for [`Output::H264`] when the caller names none.
76///
77/// 500 kbps keeps 640x360 from the Pi's encoder clean. On these machines the
78/// uplink is the limit long before the encoder.
79const DEFAULT_BITRATE: u32 = 500_000;
80
81/// What `rpicam-vid` writes to its stdout.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83enum Output {
84    /// Annex-B H.264 from the Pi's hardware encoder.
85    H264 {
86        /// Target bitrate in bits per second.
87        bitrate: u32,
88        /// Keyframe interval, in frames.
89        keyframe_interval: u32,
90    },
91    /// Raw planar I420 pictures, tightly packed.
92    I420,
93}
94
95/// Returns the raw capture size nearest above `size` that libcamera does not pad.
96///
97/// The width rounds up to [`RAW_WIDTH_ALIGN`] and the height to even, so
98/// [`frames`] splits pictures by size alone with no per-row copy. The encoder
99/// scales to the renditions, so the rounding does not change what is published.
100fn aligned(size: Size) -> Size {
101    let capture = Size::new(
102        size.width.max(1).div_ceil(RAW_WIDTH_ALIGN) * RAW_WIDTH_ALIGN,
103        size.height.max(1).next_multiple_of(2),
104    );
105    if capture != size {
106        info!(
107            requested = %size,
108            capturing = %capture,
109            align = RAW_WIDTH_ALIGN,
110            "rounding the raw capture up to a geometry libcamera does not pad",
111        );
112    }
113    capture
114}
115
116/// Returns the `rpicam-vid` command line for `output` at `size` and `framerate`.
117fn args(size: Size, framerate: u32, output: Output) -> Vec<String> {
118    let mut args = vec![
119        "--nopreview".to_string(),
120        // Run until killed. The process dies with the source.
121        "--timeout".to_string(),
122        "0".to_string(),
123        "--width".to_string(),
124        size.width.to_string(),
125        "--height".to_string(),
126        size.height.to_string(),
127        "--framerate".to_string(),
128        framerate.to_string(),
129        "--output".to_string(),
130        "-".to_string(),
131    ];
132    match output {
133        Output::H264 {
134            bitrate,
135            keyframe_interval,
136        } => args.extend([
137            "--codec".to_string(),
138            "h264".to_string(),
139            // Repeat the parameter sets before every keyframe, so a
140            // subscriber that joined late can start decoding.
141            "--inline".to_string(),
142            "--bitrate".to_string(),
143            bitrate.to_string(),
144            "--intra".to_string(),
145            keyframe_interval.to_string(),
146        ]),
147        Output::I420 => args.extend(["--codec".to_string(), "yuv420".to_string()]),
148    }
149    args
150}
151
152/// How to run the Raspberry Pi camera.
153#[derive(Debug, Clone)]
154#[non_exhaustive]
155pub struct RpicamConfig {
156    /// The capture size.
157    ///
158    /// The raw path rounds the width up to a multiple of 64, so libcamera does
159    /// not pad the rows.
160    pub size: Size,
161    /// Frames per second.
162    pub framerate: u32,
163    /// The hardware encoder's target bitrate, for the encoded path.
164    pub bitrate: moq_net::bandwidth::Rate,
165    /// The keyframe interval in frames, for the encoded path.
166    ///
167    /// A subscriber cannot start decoding before the next keyframe, so this
168    /// sets join latency more than bitrate.
169    pub keyframe_interval: u32,
170}
171
172impl RpicamConfig {
173    /// Creates a config for `size` at `framerate`.
174    ///
175    /// The encoded path defaults to 500 kbit/s with a keyframe every second.
176    #[must_use]
177    pub fn new(size: Size, framerate: u32) -> Self {
178        Self {
179            size,
180            framerate,
181            bitrate: moq_net::bandwidth::Rate::from_bps(u64::from(DEFAULT_BITRATE)),
182            keyframe_interval: framerate.max(1),
183        }
184    }
185
186    /// Returns this config with `bitrate` as the hardware encoder's target.
187    #[must_use]
188    pub fn with_bitrate(mut self, bitrate: moq_net::bandwidth::Rate) -> Self {
189        self.bitrate = bitrate;
190        self
191    }
192
193    /// Returns this config with a keyframe every `frames` frames.
194    #[must_use]
195    pub fn with_keyframe_interval(mut self, frames: u32) -> Self {
196        self.keyframe_interval = frames;
197        self
198    }
199}
200
201/// Starts `rpicam-vid` for the H.264 its hardware encoder writes.
202pub(super) fn open_encoded(config: RpicamConfig) -> Result<BoxStream<Bytes>, Error> {
203    let bitrate = u32::try_from(config.bitrate.as_bps()).map_err(|_| {
204        Error::invalid(format!(
205            "rpicam-vid takes at most {} bits per second, not {}",
206            u32::MAX,
207            config.bitrate.as_bps()
208        ))
209    })?;
210    let output = Output::H264 {
211        bitrate,
212        keyframe_interval: config.keyframe_interval,
213    };
214    annexb(config.size, config.framerate, output)
215}
216
217/// Starts `rpicam-vid` for raw pictures and waits for the first one.
218///
219/// Pictures are read into `slot` on a thread of their own.
220pub(super) async fn open_raw(
221    config: RpicamConfig,
222    slot: FrameSlot,
223    stop: CancellationToken,
224) -> Result<(VideoFormat, LocalTask), Error> {
225    let size = aligned(config.size);
226    let rate = FrameRate::new(config.framerate.max(1), 1)
227        .map_err(|err| Error::invalid(err.to_string()))?;
228    let format = VideoFormat { size, rate };
229    let mut pictures = frames(size, config.framerate, moq_mux::Clock::new())?;
230    let (first_tx, first) = tokio::sync::oneshot::channel();
231    let task = local_task::spawn("rpicam", stop, move |stop| async move {
232        let mut first_tx = Some(first_tx);
233        loop {
234            let frame = tokio::select! {
235                frame = pictures.next() => frame,
236                () = stop.cancelled() => break,
237            };
238            let Some(frame) = frame else {
239                slot.fail(Arc::new(Error::device_msg(format!(
240                    "{RPICAM_VID} stopped writing pictures"
241                ))));
242                break;
243            };
244            slot.send(Arc::new(frame));
245            if let Some(tx) = first_tx.take() {
246                let _ = tx.send(());
247            }
248        }
249    })?;
250    match tokio::time::timeout(super::FIRST_FRAME_PATIENCE, first).await {
251        Ok(Ok(())) => Ok((format, task)),
252        _ => Err(Error::device_msg(format!(
253            "{RPICAM_VID} produced no picture, check that the camera is connected"
254        ))),
255    }
256}
257
258/// Starts `rpicam-vid` and returns its raw pictures, stamped on `clock`.
259///
260/// The broadcast restamps what it reads, so `clock` only has to be monotonic.
261/// Fails if `rpicam-vid` does not start, or if `size` is odd or zero in either
262/// dimension.
263fn frames(size: Size, framerate: u32, clock: moq_mux::Clock) -> Result<BoxStream<Frame>, Error> {
264    let pictures = Pictures::new(size)?;
265    let process = Process::spawn(size, framerate, Output::I420)?;
266
267    let state = Raw {
268        process,
269        pictures,
270        clock,
271    };
272    Ok(Box::pin(n0_future::stream::unfold(
273        state,
274        |mut state| async move {
275            loop {
276                if let Some(picture) = state.pictures.take() {
277                    let frame = Frame::new(state.clock.now(), Surface::I420(picture));
278                    return Some((frame, state));
279                }
280                match state
281                    .process
282                    .stdout
283                    .read_buf(state.pictures.buffer_mut())
284                    .await
285                {
286                    Ok(0) => {
287                        debug!(command = RPICAM_VID, "the camera command closed its output");
288                        // A stream that ended mid-picture means the rows were
289                        // not the length we split at, and every picture was
290                        // sheared. The exit status does not show that.
291                        let trailing = state.pictures.leftover();
292                        if trailing > 0 {
293                            warn!(
294                                trailing,
295                                frame = state.pictures.frame,
296                                size = %state.pictures.size,
297                                "the raw camera stream ended part way through a picture, \
298                                 so its rows are not the length this size implies",
299                            );
300                        }
301                        state.process.report_exit().await;
302                        return None;
303                    }
304                    Ok(_) => continue,
305                    Err(err) => {
306                        warn!(command = RPICAM_VID, error = %err, "could not read the camera command's output");
307                        state.process.report_exit().await;
308                        return None;
309                    }
310                }
311            }
312        },
313    )))
314}
315
316/// Starts `rpicam-vid` and returns the Annex-B bytes it writes.
317fn annexb(size: Size, framerate: u32, output: Output) -> Result<BoxStream<Bytes>, Error> {
318    let process = Process::spawn(size, framerate, output)?;
319    let state = AnnexB {
320        process,
321        buffer: BytesMut::with_capacity(READ_CHUNK),
322    };
323    Ok(Box::pin(n0_future::stream::unfold(
324        state,
325        |mut state| async move {
326            // `split` below empties the buffer, so each read starts from zero
327            // length.
328            match state.process.stdout.read_buf(&mut state.buffer).await {
329                Ok(0) => {
330                    debug!(command = RPICAM_VID, "the camera command closed its output");
331                    state.process.report_exit().await;
332                    None
333                }
334                Ok(_) => {
335                    let chunk = state.buffer.split().freeze();
336                    Some((chunk, state))
337                }
338                Err(err) => {
339                    warn!(command = RPICAM_VID, error = %err, "could not read the camera command's output");
340                    state.process.report_exit().await;
341                    None
342                }
343            }
344        },
345    )))
346}
347
348/// The state of the Annex-B stream.
349struct AnnexB {
350    process: Process,
351    buffer: BytesMut,
352}
353
354/// The state of the raw stream.
355struct Raw {
356    process: Process,
357    pictures: Pictures,
358    clock: moq_mux::Clock,
359}
360
361/// A splitter of `rpicam-vid`'s raw output into tightly-packed I420 pictures.
362///
363/// Nothing frames the pictures, so only the geometry says where one ends, and
364/// a wrong geometry goes unnoticed while reading. Leftover bytes at the end,
365/// counted by [`leftover`](Self::leftover), are the one sign of it.
366struct Pictures {
367    size: Size,
368    /// Bytes of one picture: Y, then U, then V, with no row padding.
369    frame: usize,
370    buffer: BytesMut,
371}
372
373impl Pictures {
374    /// Creates a split for pictures of `size`.
375    ///
376    /// Fails if either dimension is odd or zero, which 4:2:0 cannot describe.
377    fn new(size: Size) -> Result<Self, Error> {
378        let frame = I420::len(size).map_err(|err| Error::invalid(err.to_string()))?;
379        Ok(Self {
380            size,
381            frame,
382            buffer: BytesMut::with_capacity(frame),
383        })
384    }
385
386    /// Returns the buffer to read into, with room for at least one more chunk.
387    fn buffer_mut(&mut self) -> &mut BytesMut {
388        self.buffer.reserve(READ_CHUNK);
389        &mut self.buffer
390    }
391
392    /// Takes the next whole picture, if the buffer holds one.
393    fn take(&mut self) -> Option<I420> {
394        if self.buffer.len() < self.frame {
395            return None;
396        }
397        let data: Vec<u8> = self.buffer.split_to(self.frame).into();
398        let picture =
399            I420::new(self.size, data).expect("the size and the length were both checked");
400        Some(picture)
401    }
402
403    /// Returns the bytes that do not make a whole picture.
404    fn leftover(&self) -> usize {
405        self.buffer.len()
406    }
407}
408
409/// A running `rpicam-vid` with its stdout and the tail of its stderr.
410struct Process {
411    /// Killed on drop, which stops the camera.
412    child: tokio::process::Child,
413    stdout: tokio::process::ChildStdout,
414    stderr_tail: Arc<Mutex<VecDeque<String>>>,
415    /// The task that collects stderr, stopped with the stream.
416    stderr_reader: Option<AbortOnDropHandle<()>>,
417}
418
419impl Process {
420    /// Starts `rpicam-vid` writing `output` at `size` and `framerate`.
421    ///
422    /// Fails if the subprocess cannot be started, usually because it is not
423    /// installed, or has no stdout pipe.
424    fn spawn(size: Size, framerate: u32, output: Output) -> Result<Self, Error> {
425        info!(command = RPICAM_VID, %size, framerate, ?output, "starting the camera command");
426
427        let mut child = tokio::process::Command::new(RPICAM_VID)
428            .args(args(size, framerate, output))
429            .stdout(Stdio::piped())
430            .stderr(Stdio::piped())
431            .kill_on_drop(true)
432            .spawn()
433            .map_err(|err| Error::device_msg(format!("failed to start {RPICAM_VID}: {err}")))?;
434
435        let stdout = child
436            .stdout
437            .take()
438            .ok_or_else(|| Error::device_msg(format!("{RPICAM_VID} produced no output pipe")))?;
439
440        // The camera app reports every problem on stderr only. An unseated
441        // ribbon cable reads as "no cameras available" there, and as an empty
442        // stdout here.
443        let stderr_tail = Arc::new(Mutex::new(VecDeque::with_capacity(STDERR_TAIL_LINES)));
444        let stderr_reader = child.stderr.take().map(|stderr| {
445            let tail = Arc::clone(&stderr_tail);
446            AbortOnDropHandle::new(spawn(async move {
447                let mut lines = BufReader::new(stderr).lines();
448                while let Ok(Some(line)) = lines.next_line().await {
449                    debug!(command = RPICAM_VID, line = %line, "the camera command wrote to stderr");
450                    let mut tail = tail.lock().expect("poisoned");
451                    if tail.len() == STDERR_TAIL_LINES {
452                        tail.pop_front();
453                    }
454                    tail.push_back(line);
455                }
456            }))
457        });
458
459        Ok(Self {
460            child,
461            stdout,
462            stderr_tail,
463            stderr_reader,
464        })
465    }
466
467    /// Reports how `rpicam-vid` exited, once it has closed its output.
468    ///
469    /// A failed camera app leaves a publisher that looks healthy. The broadcast
470    /// is announced, but no SPS arrives, so the catalog is never written. A
471    /// non-zero exit is therefore logged at `warn` with the reason from stderr.
472    async fn report_exit(&mut self) {
473        let status = match tokio::time::timeout(EXIT_TIMEOUT, self.child.wait()).await {
474            Ok(Ok(status)) => status,
475            Ok(Err(err)) => {
476                warn!(command = RPICAM_VID, error = %err, "could not collect the camera command's exit status");
477                return;
478            }
479            Err(_) => {
480                warn!(
481                    command = RPICAM_VID,
482                    timeout = ?EXIT_TIMEOUT,
483                    "the camera command closed its output but is still running",
484                );
485                return;
486            }
487        };
488        if status.success() {
489            debug!(command = RPICAM_VID, %status, "the camera command exited");
490            return;
491        }
492        // Wait for the stderr task before reading the tail. An app that fails
493        // on startup exits a millisecond after writing its reason, and reading
494        // first would report an empty reason.
495        if let Some(task) = self.stderr_reader.take()
496            && tokio::time::timeout(EXIT_TIMEOUT, task).await.is_err()
497        {
498            debug!(
499                command = RPICAM_VID,
500                "the camera command's stderr did not end with it"
501            );
502        }
503        let reason = self
504            .stderr_tail
505            .lock()
506            .expect("poisoned")
507            .iter()
508            .cloned()
509            .collect::<Vec<_>>()
510            .join("; ");
511        warn!(command = RPICAM_VID, %status, reason = %reason, "the camera command failed");
512    }
513}
514
515impl Drop for Process {
516    fn drop(&mut self) {
517        debug!(command = RPICAM_VID, "stopping the camera command");
518        // `kill_on_drop` already sends the signal. This impl exists for the
519        // log line, since a camera that stays on is the failure people notice.
520        let _ = self.child.start_kill();
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    /// A geometry the Pi 4 was measured to leave tightly packed.
529    const WIDTH: u32 = 640;
530    const HEIGHT: u32 = 360;
531
532    /// Bytes one 640x360 I420 picture takes: 345,600.
533    const FRAME: usize = (WIDTH * HEIGHT) as usize * 3 / 2;
534
535    const SIZE: Size = Size {
536        width: WIDTH,
537        height: HEIGHT,
538    };
539
540    /// Feeds `bytes` to a split in chunks, the way reads from a pipe arrive.
541    fn split(pictures: &mut Pictures, bytes: &[u8], chunk: usize) -> Vec<I420> {
542        let mut taken = Vec::new();
543        for part in bytes.chunks(chunk) {
544            pictures.buffer_mut().extend_from_slice(part);
545            while let Some(picture) = pictures.take() {
546                taken.push(picture);
547            }
548        }
549        taken
550    }
551
552    #[test]
553    fn a_whole_number_of_pictures_splits_into_that_many() {
554        let mut pictures = Pictures::new(SIZE).expect("640x360 is even");
555        assert_eq!(pictures.frame, FRAME);
556
557        let stream = vec![0u8; FRAME * 3];
558        let taken = split(&mut pictures, &stream, READ_CHUNK);
559
560        assert_eq!(taken.len(), 3);
561        for picture in &taken {
562            assert_eq!(picture.width(), WIDTH);
563            assert_eq!(picture.height(), HEIGHT);
564            // Y is `width * height`, U and V a quarter of that each.
565            assert_eq!(picture.data().len(), FRAME);
566        }
567        assert_eq!(pictures.leftover(), 0);
568    }
569
570    /// Each picture comes out whole and in order, whatever the read boundaries.
571    #[test]
572    fn a_picture_is_not_sheared_by_the_reads_that_carried_it() {
573        let mut pictures = Pictures::new(SIZE).expect("640x360 is even");
574        let mut stream = Vec::with_capacity(FRAME * 4);
575        for index in 0..4u8 {
576            stream.extend(std::iter::repeat_n(index, FRAME));
577        }
578
579        // A chunk size that is coprime with the picture size, so no read ends
580        // where a picture does.
581        let taken = split(&mut pictures, &stream, 7_777);
582
583        assert_eq!(taken.len(), 4);
584        for (index, picture) in taken.iter().enumerate() {
585            let expected = u8::try_from(index).expect("four pictures");
586            assert!(
587                picture.data().iter().all(|byte| *byte == expected),
588                "picture {index} carries bytes from another",
589            );
590        }
591    }
592
593    /// A padded row stride shows as leftover bytes.
594    #[test]
595    fn a_stream_that_does_not_divide_is_reported() {
596        let mut pictures = Pictures::new(SIZE).expect("640x360 is even");
597
598        // Two pictures with a 704-byte row stride at a 640 pixel width.
599        let padded = (704 * HEIGHT) as usize * 3 / 2;
600        let stream = vec![0u8; padded * 2];
601        let taken = split(&mut pictures, &stream, READ_CHUNK);
602
603        assert_eq!(taken.len(), stream.len() / FRAME);
604        assert_eq!(pictures.leftover(), stream.len() % FRAME);
605    }
606
607    #[test]
608    fn an_odd_geometry_is_refused() {
609        assert!(Pictures::new(Size::new(641, 360)).is_err());
610        assert!(Pictures::new(Size::new(640, 361)).is_err());
611        assert!(Pictures::new(Size::new(0, 360)).is_err());
612    }
613
614    /// Returns the command line of a 640x360 capture at 30 fps writing H.264.
615    fn h264(bitrate: u32, keyframe_interval: u32) -> String {
616        let output = Output::H264 {
617            bitrate,
618            keyframe_interval,
619        };
620        args(SIZE, 30, output).join(" ")
621    }
622
623    /// The raw width rounds up to a multiple of 64 and the height to even.
624    #[test]
625    fn raw_capture_rounds_up_to_an_unpadded_geometry() {
626        let width = |width, height| aligned(Size::new(width, height)).width;
627        assert_eq!(width(640, 360), 640);
628        assert_eq!(width(1280, 720), 1280);
629        assert_eq!(width(854, 480), 896);
630        assert_eq!(width(700, 360), 704);
631        assert_eq!(width(96, 64), 128);
632        assert_eq!(aligned(Size::new(640, 361)).height, 362);
633        assert_eq!(width(0, 0), RAW_WIDTH_ALIGN);
634    }
635
636    #[test]
637    fn the_output_picks_the_codec_flag() {
638        let h264 = h264(DEFAULT_BITRATE, 30);
639        assert!(h264.contains("--codec h264"), "{h264}");
640        assert!(h264.contains("--bitrate 500000"), "{h264}");
641        assert!(h264.contains("--intra 30"), "{h264}");
642
643        let raw = args(SIZE, 30, Output::I420).join(" ");
644        assert!(raw.contains("--codec yuv420"), "{raw}");
645        assert!(!raw.contains("--bitrate"), "{raw}");
646        assert!(!raw.contains("--intra"), "{raw}");
647    }
648
649    /// The bitrate and keyframe interval reach the command line.
650    #[test]
651    fn the_encoder_settings_reach_the_command_line() {
652        let args = h264(2_000_000, 60);
653        assert!(args.contains("--bitrate 2000000"), "{args}");
654        assert!(args.contains("--intra 60"), "{args}");
655    }
656}