| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::fs::File; |
| 8 | use std::io::{self, BufWriter, Seek, SeekFrom, Write}; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | |
| 11 | use anyhow::bail; |
| 12 | use symphonia::core::codecs::CodecParameters; |
| 13 | use symphonia::core::codecs::audio::well_known::CODEC_ID_OPUS; |
| 14 | use symphonia::core::formats::{FormatOptions, FormatReader}; |
| 15 | use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions}; |
| 16 | use symphonia::default::formats::MkvReader; |
| 17 | |
| 18 | |
| 19 | const CLUSTER_MS: i64 = 5_000; |
| 20 | |
| 21 | const DEFAULT_GAP_MS: i64 = 20; |
| 22 | |
| 23 | const SIZE_MARK: u64 = 1 << 56; |
| 24 | |
| 25 | const EBML: u32 = 0x1A45_DFA3; |
| 26 | const DOC_TYPE: u32 = 0x4282; |
| 27 | const DOC_TYPE_VERSION: u32 = 0x4287; |
| 28 | const DOC_TYPE_READ_VERSION: u32 = 0x4285; |
| 29 | const SEGMENT: u32 = 0x1853_8067; |
| 30 | const INFO: u32 = 0x1549_A966; |
| 31 | const TIMECODE_SCALE: u32 = 0x2AD7_B1; |
| 32 | const DURATION: u32 = 0x4489; |
| 33 | const MUXING_APP: u32 = 0x4D80; |
| 34 | const WRITING_APP: u32 = 0x5741; |
| 35 | const TRACKS: u32 = 0x1654_AE6B; |
| 36 | const TRACK_ENTRY: u32 = 0xAE; |
| 37 | const TRACK_NUMBER: u32 = 0xD7; |
| 38 | const TRACK_UID: u32 = 0x73C5; |
| 39 | const TRACK_TYPE: u32 = 0x83; |
| 40 | const CODEC_ID: u32 = 0x86; |
| 41 | const CODEC_PRIVATE: u32 = 0x63A2; |
| 42 | const AUDIO: u32 = 0xE1; |
| 43 | const SAMPLING_FREQUENCY: u32 = 0xB5; |
| 44 | const CHANNELS: u32 = 0x9F; |
| 45 | const CLUSTER: u32 = 0x1F43_B675; |
| 46 | const TIMECODE: u32 = 0xE7; |
| 47 | const SIMPLE_BLOCK: u32 = 0xA3; |
| 48 | const CUES: u32 = 0x1C53_BB6B; |
| 49 | const CUE_POINT: u32 = 0xBB; |
| 50 | const CUE_TIME: u32 = 0xB3; |
| 51 | const CUE_TRACK_POSITIONS: u32 = 0xB7; |
| 52 | const CUE_TRACK: u32 = 0xF7; |
| 53 | const CUE_CLUSTER_POSITION: u32 = 0xF1; |
| 54 | |
| 55 | |
| 56 | struct Codec { |
| 57 | head: Box<[u8]>, |
| 58 | rate: u32, |
| 59 | channels: u64, |
| 60 | } |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | pub fn join(parts: &[PathBuf], out: &Path) -> anyhow::Result<()> { |
| 67 | let mut muxer: Option<Muxer> = None; |
| 68 | |
| 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 | |
| 74 | let mut last: Option<i64> = None; |
| 75 | let mut gap = DEFAULT_GAP_MS; |
| 76 | |
| 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 | |
| 106 | fn 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 | |
| 125 | |
| 126 | struct Muxer { |
| 127 | file: BufWriter<File>, |
| 128 | |
| 129 | pos: u64, |
| 130 | |
| 131 | segment: u64, |
| 132 | |
| 133 | segment_size_at: u64, |
| 134 | |
| 135 | duration_at: u64, |
| 136 | |
| 137 | cluster: Option<(i64, Vec<u8>)>, |
| 138 | |
| 139 | cues: Vec<(i64, u64)>, |
| 140 | } |
| 141 | |
| 142 | impl Muxer { |
| 143 | |
| 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 | |
| 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 | |
| 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 | |
| 198 | |
| 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 | |
| 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 | |
| 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 | |
| 245 | fn 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 | |
| 252 | fn 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 | |
| 258 | fn 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 | |
| 266 | fn 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 | |
| 272 | fn text(id: u32, value: &str) -> Vec<u8> { |
| 273 | element(id, value.as_bytes()) |
| 274 | } |
| 275 | |
| 276 | fn float(id: u32, value: f64) -> Vec<u8> { |
| 277 | element(id, &value.to_be_bytes()) |
| 278 | } |
| 279 | |
| 280 | #[cfg(test)] |
| 281 | mod tests { |
| 282 | use std::fs; |
| 283 | |
| 284 | use super::*; |
| 285 | |
| 286 | |
| 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 | |
| 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 | |
| 300 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | } |