rusty_esp_video_core/
encoder.rs1use rusty_esp_core::error::{Error, Result};
9use rusty_esp_core::frame::{Frame, Geometry, PixelFormat};
10
11use crate::packet::{Codec, MediaPacket};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct EncoderConfig {
16 pub bitrate_kbps: u32,
18 pub fps: u8,
20 pub gop: u16,
22 pub quality: u8,
24}
25
26impl Default for EncoderConfig {
27 fn default() -> Self {
28 EncoderConfig {
29 bitrate_kbps: 0,
30 fps: 15,
31 gop: 15,
32 quality: 80,
33 }
34 }
35}
36
37pub trait VideoEncoder {
39 fn codec(&self) -> Codec;
41
42 fn configure(&mut self, geometry: Geometry, config: &EncoderConfig) -> Result<()>;
44
45 fn encode<'b>(&mut self, frame: &Frame<'b>, out: &'b mut [u8]) -> Result<MediaPacket<'b>>;
48
49 fn request_keyframe(&mut self);
51}
52
53#[derive(Debug, Default, Clone)]
55pub struct Passthrough {
56 geometry: Option<Geometry>,
57}
58
59impl VideoEncoder for Passthrough {
60 fn codec(&self) -> Codec {
61 Codec::Jpeg
62 }
63
64 fn configure(&mut self, geometry: Geometry, _config: &EncoderConfig) -> Result<()> {
65 if geometry.format != PixelFormat::Jpeg {
66 return Err(Error::Unsupported);
67 }
68 self.geometry = Some(geometry);
69 Ok(())
70 }
71
72 fn encode<'b>(&mut self, frame: &Frame<'b>, _out: &'b mut [u8]) -> Result<MediaPacket<'b>> {
73 let data = frame.coded().ok_or(Error::Unsupported)?;
74 Ok(MediaPacket::new(Codec::Jpeg, true, frame.timestamp, data))
75 }
76
77 fn request_keyframe(&mut self) {}
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83 use rusty_esp_core::time::Micros;
84
85 #[test]
86 fn passthrough_is_zero_copy_and_jpeg_only() {
87 let g = Geometry::new(320, 240, PixelFormat::Jpeg).unwrap();
88 let mut enc = Passthrough::default();
89 enc.configure(g, &EncoderConfig::default()).unwrap();
90 let jpeg = [0xFF, 0xD8, 0x00, 0x11, 0xFF, 0xD9];
91 let frame = Frame::packed(g, Micros::from_millis(5), 3, &jpeg).unwrap();
92 let mut scratch = [0u8; 0];
93 let pkt = enc.encode(&frame, &mut scratch).unwrap();
94 assert_eq!(pkt.codec, Codec::Jpeg);
95 assert!(pkt.key);
96 assert_eq!(pkt.timestamp.as_millis(), 5);
97 assert!(core::ptr::eq(pkt.data.as_ptr(), jpeg.as_ptr()), "no copy");
98
99 let raw = Geometry::new(2, 2, PixelFormat::Gray8).unwrap();
100 assert_eq!(
101 enc.configure(raw, &EncoderConfig::default()),
102 Err(Error::Unsupported)
103 );
104 let f = Frame::packed(raw, Micros::ZERO, 0, &[0u8; 4]).unwrap();
105 assert_eq!(enc.encode(&f, &mut scratch).err(), Some(Error::Unsupported));
106 }
107}