//! Joins the raw MediaRecorder parts of a recording take into one WebM. //! //! Each part is an EBML header, a Segment and Clusters of unknown size, and may end in a block //! cut off by a crash. Packets are copied, never decoded: Symphonia reads them and this module //! writes them back with known sizes. use std::fs::File; use std::io::{self, BufWriter, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use anyhow::bail; use symphonia::core::codecs::CodecParameters; use symphonia::core::codecs::audio::well_known::CODEC_ID_OPUS; use symphonia::core::formats::{FormatOptions, FormatReader}; use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions}; use symphonia::default::formats::MkvReader; /// Largest span of one Cluster, in milliseconds. const CLUSTER_MS: i64 = 5_000; /// Length of a packet when the container gives none and there is no gap to measure. const DEFAULT_GAP_MS: i64 = 20; /// Marks an 8-byte EBML size, in the high byte of the value. const SIZE_MARK: u64 = 1 << 56; const EBML: u32 = 0x1A45_DFA3; const DOC_TYPE: u32 = 0x4282; const DOC_TYPE_VERSION: u32 = 0x4287; const DOC_TYPE_READ_VERSION: u32 = 0x4285; const SEGMENT: u32 = 0x1853_8067; const INFO: u32 = 0x1549_A966; const TIMECODE_SCALE: u32 = 0x2AD7_B1; const DURATION: u32 = 0x4489; const MUXING_APP: u32 = 0x4D80; const WRITING_APP: u32 = 0x5741; const TRACKS: u32 = 0x1654_AE6B; const TRACK_ENTRY: u32 = 0xAE; const TRACK_NUMBER: u32 = 0xD7; const TRACK_UID: u32 = 0x73C5; const TRACK_TYPE: u32 = 0x83; const CODEC_ID: u32 = 0x86; const CODEC_PRIVATE: u32 = 0x63A2; const AUDIO: u32 = 0xE1; const SAMPLING_FREQUENCY: u32 = 0xB5; const CHANNELS: u32 = 0x9F; const CLUSTER: u32 = 0x1F43_B675; const TIMECODE: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; const CUES: u32 = 0x1C53_BB6B; const CUE_POINT: u32 = 0xBB; const CUE_TIME: u32 = 0xB3; const CUE_TRACK_POSITIONS: u32 = 0xB7; const CUE_TRACK: u32 = 0xF7; const CUE_CLUSTER_POSITION: u32 = 0xF1; /// Opus parameters of a part, written into the joined Tracks. struct Codec { head: Box<[u8]>, rate: u32, channels: u64, } /// Joins `parts` in order into one WebM at `out`, which is written in place: a failed join /// leaves a partial file, so callers write to a temporary name and rename on success. Parts /// that cannot be opened, have no Opus track, or hold no packets are skipped. Fails when no /// part has any packet. pub fn join(parts: &[PathBuf], out: &Path) -> anyhow::Result<()> { let mut muxer: Option = None; // Where the next part starts, in milliseconds. let mut shift = 0; for path in parts { let Some((mut reader, id, codec)) = open(path) else { continue }; let mut start_pts = None; // Shifted timestamp of the previous packet of this part. let mut last: Option = None; let mut gap = DEFAULT_GAP_MS; // A read error is the cut-off tail of a crashed recording: it ends the part. while let Ok(Some(packet)) = reader.next_packet() { if packet.track_id != id { continue; } let first = *start_pts.get_or_insert(packet.pts.get()); let ts = shift + (packet.pts.get() - first).max(0); gap = match (packet.dur.get(), last) { (0, Some(prev)) => (ts - prev).max(0), (0, None) => gap, (dur, _) => dur as i64, }; if muxer.is_none() { muxer = Some(Muxer::new(out, &codec)?); } if let Some(muxer) = muxer.as_mut() { muxer.block(ts, &packet.data)?; } last = Some(ts); } if let Some(last) = last { shift = last + gap; } } let Some(muxer) = muxer else { bail!("no Opus packets in {} parts", parts.len()) }; muxer.finish(shift)?; Ok(()) } /// Opens a part and finds its Opus track. `None` when it cannot be read or has no Opus track. fn open(path: &Path) -> Option<(Box, u32, Codec)> { let file = File::open(path).ok()?; let mss = MediaSourceStream::new(Box::new(file), MediaSourceStreamOptions::default()); let reader = MkvReader::try_new(mss, FormatOptions::default()).ok()?; let (id, codec) = reader.tracks().iter().find_map(|track| match track.codec_params.as_ref()? { CodecParameters::Audio(audio) if audio.codec == CODEC_ID_OPUS => Some(( track.id, Codec { head: audio.extra_data.clone()?, rate: audio.sample_rate?, channels: audio.channels.as_ref()?.count() as u64, }, )), _ => None, })?; Some((Box::new(reader), id, codec)) } /// Writes the joined WebM. The Segment size and the Duration are not known until the end, so /// they are written as placeholders and patched in place. struct Muxer { file: BufWriter, /// Bytes written so far. pos: u64, /// Where the Segment's data starts. segment: u64, /// Where the Segment's 8-byte size is. segment_size_at: u64, /// Where the Info's 8-byte Duration is. duration_at: u64, /// Start time and body of the open Cluster. cluster: Option<(i64, Vec)>, /// Start time and position (from the Segment's data) of each written Cluster. cues: Vec<(i64, u64)>, } impl Muxer { /// Creates `path` and writes the EBML header, the Segment start, Info and Tracks. fn new(path: &Path, codec: &Codec) -> io::Result { let mut muxer = Self { file: BufWriter::new(File::create(path)?), pos: 0, segment: 0, segment_size_at: 0, duration_at: 0, cluster: None, cues: Vec::new(), }; let header = [text(DOC_TYPE, "webm"), uint(DOC_TYPE_VERSION, 4), uint(DOC_TYPE_READ_VERSION, 2)]; muxer.put(&element(EBML, &header.concat()))?; muxer.put(&id_bytes(SEGMENT))?; muxer.segment_size_at = muxer.pos; muxer.put(&[0x01, 0, 0, 0, 0, 0, 0, 0])?; muxer.segment = muxer.pos; let tail = [text(MUXING_APP, "project_note"), text(WRITING_APP, "project_note")].concat(); // Timestamps are in milliseconds. let info = element( INFO, &[uint(TIMECODE_SCALE, 1_000_000), element(DURATION, &[0u8; 8]), tail.clone()].concat(), ); muxer.duration_at = muxer.pos + (info.len() - tail.len() - 8) as u64; muxer.put(&info)?; let audio = [float(SAMPLING_FREQUENCY, f64::from(codec.rate)), uint(CHANNELS, codec.channels)]; let entry = [ uint(TRACK_NUMBER, 1), uint(TRACK_UID, 1), uint(TRACK_TYPE, 2), text(CODEC_ID, "A_OPUS"), element(CODEC_PRIVATE, &codec.head), element(AUDIO, &audio.concat()), ]; muxer.put(&element(TRACKS, &element(TRACK_ENTRY, &entry.concat())))?; Ok(muxer) } fn put(&mut self, bytes: &[u8]) -> io::Result<()> { self.file.write_all(bytes)?; self.pos += bytes.len() as u64; Ok(()) } /// Overwrites bytes already written at `at`, then goes back to the end. fn patch(&mut self, at: u64, bytes: &[u8]) -> io::Result<()> { self.file.seek(SeekFrom::Start(at))?; self.file.write_all(bytes)?; self.file.seek(SeekFrom::Start(self.pos))?; Ok(()) } /// Adds one packet at `ts` (milliseconds), starting a new Cluster when the open one is full /// or too far behind. fn block(&mut self, ts: i64, data: &[u8]) -> io::Result<()> { let open = matches!(&self.cluster, Some((start, _)) if (0..CLUSTER_MS).contains(&(ts - start))); if !open { self.flush_cluster()?; self.cluster = Some((ts, uint(TIMECODE, ts as u64))); } if let Some((start, body)) = self.cluster.as_mut() { // Track 1, relative timecode, keyframe flag, then the packet. let mut block = vec![0x81]; block.extend(((ts - *start) as i16).to_be_bytes()); block.push(0x80); block.extend_from_slice(data); body.extend(element(SIMPLE_BLOCK, &block)); } Ok(()) } fn flush_cluster(&mut self) -> io::Result<()> { if let Some((start, body)) = self.cluster.take() { self.cues.push((start, self.pos - self.segment)); self.put(&element(CLUSTER, &body))?; } Ok(()) } /// Closes the last Cluster, writes Cues, and patches the Segment size and the Duration (ms). fn finish(mut self, duration: i64) -> io::Result<()> { self.flush_cluster()?; let points: Vec> = self .cues .iter() .map(|&(time, position)| { let positions = [uint(CUE_TRACK, 1), uint(CUE_CLUSTER_POSITION, position)].concat(); let point = [uint(CUE_TIME, time as u64), element(CUE_TRACK_POSITIONS, &positions)]; element(CUE_POINT, &point.concat()) }) .collect(); self.put(&element(CUES, &points.concat()))?; let size = self.pos - self.segment; self.patch(self.segment_size_at, &(SIZE_MARK | size).to_be_bytes())?; self.patch(self.duration_at, &(duration as f64).to_be_bytes())?; self.file.flush() } } /// Element ID bytes, without leading zeros. fn id_bytes(id: u32) -> Vec { let bytes = id.to_be_bytes(); let skip = bytes.iter().take_while(|&&byte| byte == 0).count(); bytes[skip..].to_vec() } /// Smallest EBML size field that holds `size`. fn size_vint(size: u64) -> Vec { let len = (1..=8u32).find(|&len| size < (1u64 << (7 * len)) - 1).unwrap_or(8); let value = size | (1u64 << (7 * len)); value.to_be_bytes()[8 - len as usize..].to_vec() } fn element(id: u32, body: &[u8]) -> Vec { let mut out = id_bytes(id); out.extend(size_vint(body.len() as u64)); out.extend_from_slice(body); out } /// Unsigned integer, big-endian, without leading zeros. fn uint(id: u32, value: u64) -> Vec { let bytes = value.to_be_bytes(); let skip = bytes.iter().take_while(|&&byte| byte == 0).count().min(7); element(id, &bytes[skip..]) } fn text(id: u32, value: &str) -> Vec { element(id, value.as_bytes()) } fn float(id: u32, value: f64) -> Vec { element(id, &value.to_be_bytes()) } #[cfg(test)] mod tests { use std::fs; use super::*; /// OpusHead for mono 48 kHz, used as CodecPrivate. const OPUS_HEAD: &[u8] = b"OpusHead\x01\x01\x38\x01\x80\xBB\x00\x00\x00\x00\x00"; const UNKNOWN_SIZE: [u8; 8] = [0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; /// One SimpleBlock of 20 bytes, `rel` milliseconds into its Cluster. fn block(rel: i64, fill: u8) -> Vec { let mut body = vec![0x81]; body.extend((rel as i16).to_be_bytes()); body.push(0x80); body.extend([fill; 20]); element(SIMPLE_BLOCK, &body) } /// A MediaRecorder-style WebM: unknown-size Segment and Clusters, one Opus track. Each /// cluster is (start ms, [(ms, fill)]). fn recorder(clusters: &[(i64, Vec<(i64, u8)>)]) -> Vec { let mut out = element(EBML, &text(DOC_TYPE, "webm")); out.extend(id_bytes(SEGMENT)); out.extend(UNKNOWN_SIZE); let info = [uint(TIMECODE_SCALE, 1_000_000), text(MUXING_APP, "Chrome"), text(WRITING_APP, "Chrome")]; out.extend(element(INFO, &info.concat())); let audio = [float(SAMPLING_FREQUENCY, 48_000.0), uint(CHANNELS, 1)].concat(); let entry = [ uint(TRACK_NUMBER, 1), uint(TRACK_UID, 1), uint(TRACK_TYPE, 2), text(CODEC_ID, "A_OPUS"), element(CODEC_PRIVATE, OPUS_HEAD), element(AUDIO, &audio), ]; out.extend(element(TRACKS, &element(TRACK_ENTRY, &entry.concat()))); for (start, blocks) in clusters { out.extend(id_bytes(CLUSTER)); out.extend(UNKNOWN_SIZE); out.extend(uint(TIMECODE, *start as u64)); for &(ts, fill) in blocks { out.extend(block(ts - start, fill)); } } out } /// Opens a WebM and reads its duration in ms and every packet as (ms, data). fn read(path: &Path) -> (Option, Vec<(i64, Vec)>) { let mut reader = open(path).expect("output opens").0; let duration = reader.media_info().duration.map(|d| d.get()); let mut packets = Vec::new(); while let Some(packet) = reader.next_packet().expect("packet reads") { packets.push((packet.pts.get(), packet.data.to_vec())); } (duration, packets) } fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("webm-{name}-{}", uuid::Uuid::now_v7())); fs::create_dir_all(&dir).unwrap(); dir } #[test] fn joins_parts_with_summed_duration_and_shifted_timestamps() { let dir = scratch("join"); let first = dir.join("0.weba"); let second = dir.join("1.weba"); fs::write(&first, recorder(&[(0, vec![(0, 1), (20, 2)]), (40, vec![(40, 3)])])).unwrap(); fs::write(&second, recorder(&[(0, vec![(0, 4), (20, 5)])])).unwrap(); let out = dir.join("joined.weba"); join(&[first, second], &out).unwrap(); // The first part is 60 ms (last packet at 40 ms plus a 20 ms gap), the second 40 ms. let (duration, packets) = read(&out); assert_eq!(duration, Some(100)); let expected: Vec<(i64, Vec)> = [(0, 1), (20, 2), (40, 3), (60, 4), (80, 5)] .into_iter() .map(|(ts, fill)| (ts, vec![fill; 20])) .collect(); assert_eq!(packets, expected); fs::remove_dir_all(&dir).unwrap(); } #[test] fn drops_only_a_block_cut_off_at_the_end_of_a_part() { let dir = scratch("cut"); let first = dir.join("0.weba"); let second = dir.join("1.weba"); fs::write(&first, recorder(&[(0, vec![(0, 1), (20, 2)]), (40, vec![(40, 3)])])).unwrap(); let mut cut = recorder(&[(0, vec![(0, 4), (20, 5)])]); // Ends inside the data of the second block. cut.truncate(cut.len() - 10); fs::write(&second, cut).unwrap(); let out = dir.join("joined.weba"); join(&[first, second], &out).unwrap(); // The second part keeps only its first block, so it is 20 ms long. let (duration, packets) = read(&out); assert_eq!(duration, Some(80)); let expected: Vec<(i64, Vec)> = [(0, 1), (20, 2), (40, 3), (60, 4)] .into_iter() .map(|(ts, fill)| (ts, vec![fill; 20])) .collect(); assert_eq!(packets, expected); fs::remove_dir_all(&dir).unwrap(); } }