forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

webm.rs389 lines, 14.6 KiBHistoryRawDownload
1//! Joins the raw MediaRecorder parts of a recording take into one WebM.
2//!
3//! Each part is an EBML header, a Segment and Clusters of unknown size, and may end in a block
4//! cut off by a crash. Packets are copied, never decoded: Symphonia reads them and this module
5//! writes them back with known sizes.
6
7use std::fs::File;
8use std::io::{self, BufWriter, Seek, SeekFrom, Write};
9use std::path::{Path, PathBuf};
10
11use anyhow::bail;
12use symphonia::core::codecs::CodecParameters;
13use symphonia::core::codecs::audio::well_known::CODEC_ID_OPUS;
14use symphonia::core::formats::{FormatOptions, FormatReader};
15use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
16use symphonia::default::formats::MkvReader;
17
18/// Largest span of one Cluster, in milliseconds.
19const CLUSTER_MS: i64 = 5_000;
20/// Length of a packet when the container gives none and there is no gap to measure.
21const DEFAULT_GAP_MS: i64 = 20;
22/// Marks an 8-byte EBML size, in the high byte of the value.
23const SIZE_MARK: u64 = 1 << 56;
24
25const EBML: u32 = 0x1A45_DFA3;
26const DOC_TYPE: u32 = 0x4282;
27const DOC_TYPE_VERSION: u32 = 0x4287;
28const DOC_TYPE_READ_VERSION: u32 = 0x4285;
29const SEGMENT: u32 = 0x1853_8067;
30const INFO: u32 = 0x1549_A966;
31const TIMECODE_SCALE: u32 = 0x2AD7_B1;
32const DURATION: u32 = 0x4489;
33const MUXING_APP: u32 = 0x4D80;
34const WRITING_APP: u32 = 0x5741;
35const TRACKS: u32 = 0x1654_AE6B;
36const TRACK_ENTRY: u32 = 0xAE;
37const TRACK_NUMBER: u32 = 0xD7;
38const TRACK_UID: u32 = 0x73C5;
39const TRACK_TYPE: u32 = 0x83;
40const CODEC_ID: u32 = 0x86;
41const CODEC_PRIVATE: u32 = 0x63A2;
42const AUDIO: u32 = 0xE1;
43const SAMPLING_FREQUENCY: u32 = 0xB5;
44const CHANNELS: u32 = 0x9F;
45const CLUSTER: u32 = 0x1F43_B675;
46const TIMECODE: u32 = 0xE7;
47const SIMPLE_BLOCK: u32 = 0xA3;
48const CUES: u32 = 0x1C53_BB6B;
49const CUE_POINT: u32 = 0xBB;
50const CUE_TIME: u32 = 0xB3;
51const CUE_TRACK_POSITIONS: u32 = 0xB7;
52const CUE_TRACK: u32 = 0xF7;
53const CUE_CLUSTER_POSITION: u32 = 0xF1;
54
55/// Opus parameters of a part, written into the joined Tracks.
56struct Codec {
57 head: Box<[u8]>,
58 rate: u32,
59 channels: u64,
60}
61
62/// Joins `parts` in order into one WebM at `out`, which is written in place: a failed join
63/// leaves a partial file, so callers write to a temporary name and rename on success. Parts
64/// that cannot be opened, have no Opus track, or hold no packets are skipped. Fails when no
65/// part has any packet.
66pub fn join(parts: &[PathBuf], out: &Path) -> anyhow::Result<()> {
67 let mut muxer: Option<Muxer> = None;
68 // Where the next part starts, in milliseconds.
69 let mut shift = 0;
70 for path in parts {
71 let Some((mut reader, id, codec)) = open(path) else { continue };
72 let mut start_pts = None;
73 // Shifted timestamp of the previous packet of this part.
74 let mut last: Option<i64> = None;
75 let mut gap = DEFAULT_GAP_MS;
76 // A read error is the cut-off tail of a crashed recording: it ends the part.
77 while let Ok(Some(packet)) = reader.next_packet() {
78 if packet.track_id != id {
79 continue;
80 }
81 let first = *start_pts.get_or_insert(packet.pts.get());
82 let ts = shift + (packet.pts.get() - first).max(0);
83 gap = match (packet.dur.get(), last) {
84 (0, Some(prev)) => (ts - prev).max(0),
85 (0, None) => gap,
86 (dur, _) => dur as i64,
87 };
88 if muxer.is_none() {
89 muxer = Some(Muxer::new(out, &codec)?);
90 }
91 if let Some(muxer) = muxer.as_mut() {
92 muxer.block(ts, &packet.data)?;
93 }
94 last = Some(ts);
95 }
96 if let Some(last) = last {
97 shift = last + gap;
98 }
99 }
100 let Some(muxer) = muxer else { bail!("no Opus packets in {} parts", parts.len()) };
101 muxer.finish(shift)?;
102 Ok(())
103}
104
105/// Opens a part and finds its Opus track. `None` when it cannot be read or has no Opus track.
106fn open(path: &Path) -> Option<(Box<dyn FormatReader>, u32, Codec)> {
107 let file = File::open(path).ok()?;
108 let mss = MediaSourceStream::new(Box::new(file), MediaSourceStreamOptions::default());
109 let reader = MkvReader::try_new(mss, FormatOptions::default()).ok()?;
110 let (id, codec) = reader.tracks().iter().find_map(|track| match track.codec_params.as_ref()? {
111 CodecParameters::Audio(audio) if audio.codec == CODEC_ID_OPUS => Some((
112 track.id,
113 Codec {
114 head: audio.extra_data.clone()?,
115 rate: audio.sample_rate?,
116 channels: audio.channels.as_ref()?.count() as u64,
117 },
118 )),
119 _ => None,
120 })?;
121 Some((Box::new(reader), id, codec))
122}
123
124/// Writes the joined WebM. The Segment size and the Duration are not known until the end, so
125/// they are written as placeholders and patched in place.
126struct Muxer {
127 file: BufWriter<File>,
128 /// Bytes written so far.
129 pos: u64,
130 /// Where the Segment's data starts.
131 segment: u64,
132 /// Where the Segment's 8-byte size is.
133 segment_size_at: u64,
134 /// Where the Info's 8-byte Duration is.
135 duration_at: u64,
136 /// Start time and body of the open Cluster.
137 cluster: Option<(i64, Vec<u8>)>,
138 /// Start time and position (from the Segment's data) of each written Cluster.
139 cues: Vec<(i64, u64)>,
140}
141
142impl Muxer {
143 /// Creates `path` and writes the EBML header, the Segment start, Info and Tracks.
144 fn new(path: &Path, codec: &Codec) -> io::Result<Self> {
145 let mut muxer = Self {
146 file: BufWriter::new(File::create(path)?),
147 pos: 0,
148 segment: 0,
149 segment_size_at: 0,
150 duration_at: 0,
151 cluster: None,
152 cues: Vec::new(),
153 };
154 let header = [text(DOC_TYPE, "webm"), uint(DOC_TYPE_VERSION, 4), uint(DOC_TYPE_READ_VERSION, 2)];
155 muxer.put(&element(EBML, &header.concat()))?;
156 muxer.put(&id_bytes(SEGMENT))?;
157 muxer.segment_size_at = muxer.pos;
158 muxer.put(&[0x01, 0, 0, 0, 0, 0, 0, 0])?;
159 muxer.segment = muxer.pos;
160
161 let tail = [text(MUXING_APP, "project_note"), text(WRITING_APP, "project_note")].concat();
162 // Timestamps are in milliseconds.
163 let info = element(
164 INFO,
165 &[uint(TIMECODE_SCALE, 1_000_000), element(DURATION, &[0u8; 8]), tail.clone()].concat(),
166 );
167 muxer.duration_at = muxer.pos + (info.len() - tail.len() - 8) as u64;
168 muxer.put(&info)?;
169
170 let audio = [float(SAMPLING_FREQUENCY, f64::from(codec.rate)), uint(CHANNELS, codec.channels)];
171 let entry = [
172 uint(TRACK_NUMBER, 1),
173 uint(TRACK_UID, 1),
174 uint(TRACK_TYPE, 2),
175 text(CODEC_ID, "A_OPUS"),
176 element(CODEC_PRIVATE, &codec.head),
177 element(AUDIO, &audio.concat()),
178 ];
179 muxer.put(&element(TRACKS, &element(TRACK_ENTRY, &entry.concat())))?;
180 Ok(muxer)
181 }
182
183 fn put(&mut self, bytes: &[u8]) -> io::Result<()> {
184 self.file.write_all(bytes)?;
185 self.pos += bytes.len() as u64;
186 Ok(())
187 }
188
189 /// Overwrites bytes already written at `at`, then goes back to the end.
190 fn patch(&mut self, at: u64, bytes: &[u8]) -> io::Result<()> {
191 self.file.seek(SeekFrom::Start(at))?;
192 self.file.write_all(bytes)?;
193 self.file.seek(SeekFrom::Start(self.pos))?;
194 Ok(())
195 }
196
197 /// Adds one packet at `ts` (milliseconds), starting a new Cluster when the open one is full
198 /// or too far behind.
199 fn block(&mut self, ts: i64, data: &[u8]) -> io::Result<()> {
200 let open = matches!(&self.cluster, Some((start, _)) if (0..CLUSTER_MS).contains(&(ts - start)));
201 if !open {
202 self.flush_cluster()?;
203 self.cluster = Some((ts, uint(TIMECODE, ts as u64)));
204 }
205 if let Some((start, body)) = self.cluster.as_mut() {
206 // Track 1, relative timecode, keyframe flag, then the packet.
207 let mut block = vec![0x81];
208 block.extend(((ts - *start) as i16).to_be_bytes());
209 block.push(0x80);
210 block.extend_from_slice(data);
211 body.extend(element(SIMPLE_BLOCK, &block));
212 }
213 Ok(())
214 }
215
216 fn flush_cluster(&mut self) -> io::Result<()> {
217 if let Some((start, body)) = self.cluster.take() {
218 self.cues.push((start, self.pos - self.segment));
219 self.put(&element(CLUSTER, &body))?;
220 }
221 Ok(())
222 }
223
224 /// Closes the last Cluster, writes Cues, and patches the Segment size and the Duration (ms).
225 fn finish(mut self, duration: i64) -> io::Result<()> {
226 self.flush_cluster()?;
227 let points: Vec<Vec<u8>> = self
228 .cues
229 .iter()
230 .map(|&(time, position)| {
231 let positions = [uint(CUE_TRACK, 1), uint(CUE_CLUSTER_POSITION, position)].concat();
232 let point = [uint(CUE_TIME, time as u64), element(CUE_TRACK_POSITIONS, &positions)];
233 element(CUE_POINT, &point.concat())
234 })
235 .collect();
236 self.put(&element(CUES, &points.concat()))?;
237 let size = self.pos - self.segment;
238 self.patch(self.segment_size_at, &(SIZE_MARK | size).to_be_bytes())?;
239 self.patch(self.duration_at, &(duration as f64).to_be_bytes())?;
240 self.file.flush()
241 }
242}
243
244/// Element ID bytes, without leading zeros.
245fn id_bytes(id: u32) -> Vec<u8> {
246 let bytes = id.to_be_bytes();
247 let skip = bytes.iter().take_while(|&&byte| byte == 0).count();
248 bytes[skip..].to_vec()
249}
250
251/// Smallest EBML size field that holds `size`.
252fn size_vint(size: u64) -> Vec<u8> {
253 let len = (1..=8u32).find(|&len| size < (1u64 << (7 * len)) - 1).unwrap_or(8);
254 let value = size | (1u64 << (7 * len));
255 value.to_be_bytes()[8 - len as usize..].to_vec()
256}
257
258fn element(id: u32, body: &[u8]) -> Vec<u8> {
259 let mut out = id_bytes(id);
260 out.extend(size_vint(body.len() as u64));
261 out.extend_from_slice(body);
262 out
263}
264
265/// Unsigned integer, big-endian, without leading zeros.
266fn uint(id: u32, value: u64) -> Vec<u8> {
267 let bytes = value.to_be_bytes();
268 let skip = bytes.iter().take_while(|&&byte| byte == 0).count().min(7);
269 element(id, &bytes[skip..])
270}
271
272fn text(id: u32, value: &str) -> Vec<u8> {
273 element(id, value.as_bytes())
274}
275
276fn float(id: u32, value: f64) -> Vec<u8> {
277 element(id, &value.to_be_bytes())
278}
279
280#[cfg(test)]
281mod tests {
282 use std::fs;
283
284 use super::*;
285
286 /// OpusHead for mono 48 kHz, used as CodecPrivate.
287 const OPUS_HEAD: &[u8] = b"OpusHead\x01\x01\x38\x01\x80\xBB\x00\x00\x00\x00\x00";
288 const UNKNOWN_SIZE: [u8; 8] = [0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
289
290 /// One SimpleBlock of 20 bytes, `rel` milliseconds into its Cluster.
291 fn block(rel: i64, fill: u8) -> Vec<u8> {
292 let mut body = vec![0x81];
293 body.extend((rel as i16).to_be_bytes());
294 body.push(0x80);
295 body.extend([fill; 20]);
296 element(SIMPLE_BLOCK, &body)
297 }
298
299 /// A MediaRecorder-style WebM: unknown-size Segment and Clusters, one Opus track. Each
300 /// cluster is (start ms, [(ms, fill)]).
301 fn recorder(clusters: &[(i64, Vec<(i64, u8)>)]) -> Vec<u8> {
302 let mut out = element(EBML, &text(DOC_TYPE, "webm"));
303 out.extend(id_bytes(SEGMENT));
304 out.extend(UNKNOWN_SIZE);
305 let info = [uint(TIMECODE_SCALE, 1_000_000), text(MUXING_APP, "Chrome"), text(WRITING_APP, "Chrome")];
306 out.extend(element(INFO, &info.concat()));
307 let audio = [float(SAMPLING_FREQUENCY, 48_000.0), uint(CHANNELS, 1)].concat();
308 let entry = [
309 uint(TRACK_NUMBER, 1),
310 uint(TRACK_UID, 1),
311 uint(TRACK_TYPE, 2),
312 text(CODEC_ID, "A_OPUS"),
313 element(CODEC_PRIVATE, OPUS_HEAD),
314 element(AUDIO, &audio),
315 ];
316 out.extend(element(TRACKS, &element(TRACK_ENTRY, &entry.concat())));
317 for (start, blocks) in clusters {
318 out.extend(id_bytes(CLUSTER));
319 out.extend(UNKNOWN_SIZE);
320 out.extend(uint(TIMECODE, *start as u64));
321 for &(ts, fill) in blocks {
322 out.extend(block(ts - start, fill));
323 }
324 }
325 out
326 }
327
328 /// Opens a WebM and reads its duration in ms and every packet as (ms, data).
329 fn read(path: &Path) -> (Option<u64>, Vec<(i64, Vec<u8>)>) {
330 let mut reader = open(path).expect("output opens").0;
331 let duration = reader.media_info().duration.map(|d| d.get());
332 let mut packets = Vec::new();
333 while let Some(packet) = reader.next_packet().expect("packet reads") {
334 packets.push((packet.pts.get(), packet.data.to_vec()));
335 }
336 (duration, packets)
337 }
338
339 fn scratch(name: &str) -> PathBuf {
340 let dir = std::env::temp_dir().join(format!("webm-{name}-{}", uuid::Uuid::now_v7()));
341 fs::create_dir_all(&dir).unwrap();
342 dir
343 }
344
345 #[test]
346 fn joins_parts_with_summed_duration_and_shifted_timestamps() {
347 let dir = scratch("join");
348 let first = dir.join("0.weba");
349 let second = dir.join("1.weba");
350 fs::write(&first, recorder(&[(0, vec![(0, 1), (20, 2)]), (40, vec![(40, 3)])])).unwrap();
351 fs::write(&second, recorder(&[(0, vec![(0, 4), (20, 5)])])).unwrap();
352 let out = dir.join("joined.weba");
353 join(&[first, second], &out).unwrap();
354
355 // The first part is 60 ms (last packet at 40 ms plus a 20 ms gap), the second 40 ms.
356 let (duration, packets) = read(&out);
357 assert_eq!(duration, Some(100));
358 let expected: Vec<(i64, Vec<u8>)> = [(0, 1), (20, 2), (40, 3), (60, 4), (80, 5)]
359 .into_iter()
360 .map(|(ts, fill)| (ts, vec![fill; 20]))
361 .collect();
362 assert_eq!(packets, expected);
363 fs::remove_dir_all(&dir).unwrap();
364 }
365
366 #[test]
367 fn drops_only_a_block_cut_off_at_the_end_of_a_part() {
368 let dir = scratch("cut");
369 let first = dir.join("0.weba");
370 let second = dir.join("1.weba");
371 fs::write(&first, recorder(&[(0, vec![(0, 1), (20, 2)]), (40, vec![(40, 3)])])).unwrap();
372 let mut cut = recorder(&[(0, vec![(0, 4), (20, 5)])]);
373 // Ends inside the data of the second block.
374 cut.truncate(cut.len() - 10);
375 fs::write(&second, cut).unwrap();
376 let out = dir.join("joined.weba");
377 join(&[first, second], &out).unwrap();
378
379 // The second part keeps only its first block, so it is 20 ms long.
380 let (duration, packets) = read(&out);
381 assert_eq!(duration, Some(80));
382 let expected: Vec<(i64, Vec<u8>)> = [(0, 1), (20, 2), (40, 3), (60, 4)]
383 .into_iter()
384 .map(|(ts, fill)| (ts, vec![fill; 20]))
385 .collect();
386 assert_eq!(packets, expected);
387 fs::remove_dir_all(&dir).unwrap();
388 }
389}