Skip to main content

moq_rtc/codec/
vp8.rs

1//! VP8 bridge.
2//!
3//! VP8 carries no out-of-band config record. str0m hands us complete frames
4//! and we forward them to a `.vp8` track with the matching catalog entry.
5//! Keyframes are detected from the first byte (P-frame bit, RFC 6386 §9.1).
6
7use crate::{Result, codec};
8
9/// Forwards str0m's VP8 frames to a `.vp8` track, detecting keyframes inline.
10pub struct Bridge {
11	catalog: moq_mux::catalog::Producer,
12	track: moq_mux::container::Producer<moq_mux::catalog::hang::Container>,
13	announced: bool,
14}
15
16impl Bridge {
17	/// Publish a `.vp8` track on `broadcast`; the catalog rendition is added on the first frame.
18	pub fn new(mut broadcast: moq_net::BroadcastProducer, catalog: moq_mux::catalog::Producer) -> Result<Self> {
19		let track = broadcast.unique_track(".vp8")?;
20		let producer = moq_mux::container::Producer::new(track, moq_mux::catalog::hang::Container::Legacy);
21		Ok(Self {
22			catalog,
23			track: producer,
24			announced: false,
25		})
26	}
27
28	fn announce(&mut self) {
29		if self.announced {
30			return;
31		}
32		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
33		config.container = hang::catalog::Container::Legacy;
34		self.catalog
35			.lock()
36			.video
37			.renditions
38			.insert(self.track.track().name.clone(), config);
39		self.announced = true;
40	}
41}
42
43impl codec::Bridge for Bridge {
44	fn push(&mut self, frame: codec::Frame) -> Result<()> {
45		self.announce();
46		let pts = moq_mux::container::Timestamp::from_micros(frame.timestamp_us)
47			.map_err(|err| crate::Error::Other(anyhow::anyhow!("invalid timestamp: {err}")))?;
48		// VP8: first byte bit 0 == 0 means keyframe (RFC 6386 §9.1).
49		let keyframe = frame.payload.first().map(|b| b & 0x01 == 0).unwrap_or(false);
50		self.track
51			.write(moq_mux::container::Frame {
52				timestamp: pts,
53				payload: frame.payload,
54				keyframe,
55				duration: None,
56			})
57			.map_err(|err| crate::Error::Other(anyhow::anyhow!("vp8 track write failed: {err}")))?;
58		Ok(())
59	}
60}
61
62impl Drop for Bridge {
63	fn drop(&mut self) {
64		self.catalog.lock().video.renditions.remove(&self.track.track().name);
65	}
66}