1use 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
41const RPICAM_VID: &str = "rpicam-vid";
43
44const READ_CHUNK: usize = 32 * 1024;
49
50const STDERR_TAIL_LINES: usize = 10;
55
56const EXIT_TIMEOUT: Duration = Duration::from_secs(2);
60
61const RAW_WIDTH_ALIGN: u32 = 64;
74
75const DEFAULT_BITRATE: u32 = 500_000;
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83enum Output {
84 H264 {
86 bitrate: u32,
88 keyframe_interval: u32,
90 },
91 I420,
93}
94
95fn 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
116fn args(size: Size, framerate: u32, output: Output) -> Vec<String> {
118 let mut args = vec![
119 "--nopreview".to_string(),
120 "--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 "--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#[derive(Debug, Clone)]
154#[non_exhaustive]
155pub struct RpicamConfig {
156 pub size: Size,
161 pub framerate: u32,
163 pub bitrate: moq_net::bandwidth::Rate,
165 pub keyframe_interval: u32,
170}
171
172impl RpicamConfig {
173 #[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 #[must_use]
188 pub fn with_bitrate(mut self, bitrate: moq_net::bandwidth::Rate) -> Self {
189 self.bitrate = bitrate;
190 self
191 }
192
193 #[must_use]
195 pub fn with_keyframe_interval(mut self, frames: u32) -> Self {
196 self.keyframe_interval = frames;
197 self
198 }
199}
200
201pub(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
217pub(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
258fn 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 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
316fn 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 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
348struct AnnexB {
350 process: Process,
351 buffer: BytesMut,
352}
353
354struct Raw {
356 process: Process,
357 pictures: Pictures,
358 clock: moq_mux::Clock,
359}
360
361struct Pictures {
367 size: Size,
368 frame: usize,
370 buffer: BytesMut,
371}
372
373impl Pictures {
374 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 fn buffer_mut(&mut self) -> &mut BytesMut {
388 self.buffer.reserve(READ_CHUNK);
389 &mut self.buffer
390 }
391
392 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 fn leftover(&self) -> usize {
405 self.buffer.len()
406 }
407}
408
409struct Process {
411 child: tokio::process::Child,
413 stdout: tokio::process::ChildStdout,
414 stderr_tail: Arc<Mutex<VecDeque<String>>>,
415 stderr_reader: Option<AbortOnDropHandle<()>>,
417}
418
419impl Process {
420 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 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 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 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 let _ = self.child.start_kill();
521 }
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 const WIDTH: u32 = 640;
530 const HEIGHT: u32 = 360;
531
532 const FRAME: usize = (WIDTH * HEIGHT) as usize * 3 / 2;
534
535 const SIZE: Size = Size {
536 width: WIDTH,
537 height: HEIGHT,
538 };
539
540 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 assert_eq!(picture.data().len(), FRAME);
566 }
567 assert_eq!(pictures.leftover(), 0);
568 }
569
570 #[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 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 #[test]
595 fn a_stream_that_does_not_divide_is_reported() {
596 let mut pictures = Pictures::new(SIZE).expect("640x360 is even");
597
598 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 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 #[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 #[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}