Merge the mux lane into main
Browse files at this commit1 changed file +375 -46
- crates/engine/src/mux.rs +375 -46
crates/engine/src/mux.rsmodified+375 -46
| @@ -164,6 +164,99 @@ fn colr_nclx(colour: ColorDescription) -> [u8; 11] { | |||
| 164 | out | 164 | out |
| 165 | } | 165 | } |
| 166 | 166 | ||
| 167 | +/// The language an mp4 track states, from whatever a caller said the track is | ||
| 168 | +/// in. | ||
| 169 | +/// | ||
| 170 | +/// `mdhd` packs exactly three ISO 639-2 letters into its 16-bit field, and the | ||
| 171 | +/// `mp4` crate's own `language_code` (`vendor/mp4/src/mp4box/mdhd.rs:157`) | ||
| 172 | +/// masks the three UTF-16 units it is handed with `0x1F` and drops the rest -- | ||
| 173 | +/// so a two-letter `en` is written as `en` and a backtick, and a `pt-BR` tag as | ||
| 174 | +/// `ptm`, silently, with a player's subtitle menu then offering a language | ||
| 175 | +/// nobody speaks. Matroska's `Language` is raw UTF-8 beside that and may carry | ||
| 176 | +/// a BCP-47 tag, so the tag is cut to its primary subtag here, mapped through | ||
| 177 | +/// [`ISO_639_1_TO_2`] where it is two letters, and left `und` -- the code that | ||
| 178 | +/// says *undetermined* -- where nothing names it. | ||
| 179 | +/// | ||
| 180 | +/// Three lowercase letters are taken as they are: that is the code the field | ||
| 181 | +/// holds, and it is what an ISO 639-3 tag like `fil` and every language | ||
| 182 | +/// `crate::demux::mkv_language` hands over already are. | ||
| 183 | +fn mp4_language(language: &str) -> String { | ||
| 184 | + let primary = language | ||
| 185 | + .split('-') | ||
| 186 | + .next() | ||
| 187 | + .unwrap_or_default() | ||
| 188 | + .to_ascii_lowercase(); | ||
| 189 | + let code = match primary.len() { | ||
| 190 | + 2 => ISO_639_1_TO_2 | ||
| 191 | + .iter() | ||
| 192 | + .find(|(two, _)| *two == primary) | ||
| 193 | + .map(|(_, three)| *three), | ||
| 194 | + 3 if primary.bytes().all(|b| b.is_ascii_lowercase()) => Some(primary.as_str()), | ||
| 195 | + _ => None, | ||
| 196 | + }; | ||
| 197 | + code.unwrap_or("und").to_owned() | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Every ISO 639-1 code and the 639-2 (terminology) one it names the same | ||
| 201 | +/// language with -- what [`mp4_language`] maps a BCP-47 primary subtag through. | ||
| 202 | +/// | ||
| 203 | +/// corner-cut: the same standard's table `crate::demux` reads a Matroska | ||
| 204 | +/// `TrackEntry` through, carried here as well because that one is private to | ||
| 205 | +/// its module and this file owns no other file's visibility. The two must not | ||
| 206 | +/// drift, so a change belongs in both; the upgrade path is one table with | ||
| 207 | +/// `pub(crate)` on it, and a muxer that calls the demuxer's. Whole standard and | ||
| 208 | +/// not the languages a test happened to use, generated from `iso-codes`' | ||
| 209 | +/// `iso_639-2.json` like that one. | ||
| 210 | +#[rustfmt::skip] | ||
| 211 | +const ISO_639_1_TO_2: &[(&str, &str)] = &[ | ||
| 212 | + ("aa", "aar"), ("ab", "abk"), ("ae", "ave"), ("af", "afr"), | ||
| 213 | + ("ak", "aka"), ("am", "amh"), ("an", "arg"), ("ar", "ara"), | ||
| 214 | + ("as", "asm"), ("av", "ava"), ("ay", "aym"), ("az", "aze"), | ||
| 215 | + ("ba", "bak"), ("be", "bel"), ("bg", "bul"), ("bi", "bis"), | ||
| 216 | + ("bm", "bam"), ("bn", "ben"), ("bo", "bod"), ("br", "bre"), | ||
| 217 | + ("bs", "bos"), ("ca", "cat"), ("ce", "che"), ("ch", "cha"), | ||
| 218 | + ("co", "cos"), ("cr", "cre"), ("cs", "ces"), ("cu", "chu"), | ||
| 219 | + ("cv", "chv"), ("cy", "cym"), ("da", "dan"), ("de", "deu"), | ||
| 220 | + ("dv", "div"), ("dz", "dzo"), ("ee", "ewe"), ("el", "ell"), | ||
| 221 | + ("en", "eng"), ("eo", "epo"), ("es", "spa"), ("et", "est"), | ||
| 222 | + ("eu", "eus"), ("fa", "fas"), ("ff", "ful"), ("fi", "fin"), | ||
| 223 | + ("fj", "fij"), ("fo", "fao"), ("fr", "fra"), ("fy", "fry"), | ||
| 224 | + ("ga", "gle"), ("gd", "gla"), ("gl", "glg"), ("gn", "grn"), | ||
| 225 | + ("gu", "guj"), ("gv", "glv"), ("ha", "hau"), ("he", "heb"), | ||
| 226 | + ("hi", "hin"), ("ho", "hmo"), ("hr", "hrv"), ("ht", "hat"), | ||
| 227 | + ("hu", "hun"), ("hy", "hye"), ("hz", "her"), ("ia", "ina"), | ||
| 228 | + ("id", "ind"), ("ie", "ile"), ("ig", "ibo"), ("ii", "iii"), | ||
| 229 | + ("ik", "ipk"), ("io", "ido"), ("is", "isl"), ("it", "ita"), | ||
| 230 | + ("iu", "iku"), ("ja", "jpn"), ("jv", "jav"), ("ka", "kat"), | ||
| 231 | + ("kg", "kon"), ("ki", "kik"), ("kj", "kua"), ("kk", "kaz"), | ||
| 232 | + ("kl", "kal"), ("km", "khm"), ("kn", "kan"), ("ko", "kor"), | ||
| 233 | + ("kr", "kau"), ("ks", "kas"), ("ku", "kur"), ("kv", "kom"), | ||
| 234 | + ("kw", "cor"), ("ky", "kir"), ("la", "lat"), ("lb", "ltz"), | ||
| 235 | + ("lg", "lug"), ("li", "lim"), ("ln", "lin"), ("lo", "lao"), | ||
| 236 | + ("lt", "lit"), ("lu", "lub"), ("lv", "lav"), ("mg", "mlg"), | ||
| 237 | + ("mh", "mah"), ("mi", "mri"), ("mk", "mkd"), ("ml", "mal"), | ||
| 238 | + ("mn", "mon"), ("mr", "mar"), ("ms", "msa"), ("mt", "mlt"), | ||
| 239 | + ("my", "mya"), ("na", "nau"), ("nb", "nob"), ("nd", "nde"), | ||
| 240 | + ("ne", "nep"), ("ng", "ndo"), ("nl", "nld"), ("nn", "nno"), | ||
| 241 | + ("no", "nor"), ("nr", "nbl"), ("nv", "nav"), ("ny", "nya"), | ||
| 242 | + ("oc", "oci"), ("oj", "oji"), ("om", "orm"), ("or", "ori"), | ||
| 243 | + ("os", "oss"), ("pa", "pan"), ("pi", "pli"), ("pl", "pol"), | ||
| 244 | + ("ps", "pus"), ("pt", "por"), ("qu", "que"), ("rm", "roh"), | ||
| 245 | + ("rn", "run"), ("ro", "ron"), ("ru", "rus"), ("rw", "kin"), | ||
| 246 | + ("sa", "san"), ("sc", "srd"), ("sd", "snd"), ("se", "sme"), | ||
| 247 | + ("sg", "sag"), ("si", "sin"), ("sk", "slk"), ("sl", "slv"), | ||
| 248 | + ("sm", "smo"), ("sn", "sna"), ("so", "som"), ("sq", "sqi"), | ||
| 249 | + ("sr", "srp"), ("ss", "ssw"), ("st", "sot"), ("su", "sun"), | ||
| 250 | + ("sv", "swe"), ("sw", "swa"), ("ta", "tam"), ("te", "tel"), | ||
| 251 | + ("tg", "tgk"), ("th", "tha"), ("ti", "tir"), ("tk", "tuk"), | ||
| 252 | + ("tl", "tgl"), ("tn", "tsn"), ("to", "ton"), ("tr", "tur"), | ||
| 253 | + ("ts", "tso"), ("tt", "tat"), ("tw", "twi"), ("ty", "tah"), | ||
| 254 | + ("ug", "uig"), ("uk", "ukr"), ("ur", "urd"), ("uz", "uzb"), | ||
| 255 | + ("ve", "ven"), ("vi", "vie"), ("vo", "vol"), ("wa", "wln"), | ||
| 256 | + ("wo", "wol"), ("xh", "xho"), ("yi", "yid"), ("yo", "yor"), | ||
| 257 | + ("za", "zha"), ("zh", "zho"), ("zu", "zul"), | ||
| 258 | +]; | ||
| 259 | + | ||
| 167 | const VIDEO_TRACK: u32 = 1; | 260 | const VIDEO_TRACK: u32 = 1; |
| 168 | const AUDIO_TRACK: u32 = 2; | 261 | const AUDIO_TRACK: u32 = 2; |
| 169 | 262 | ||
| @@ -585,15 +678,16 @@ impl Mp4Muxer { | |||
| 585 | self.writer.add_track(&TrackConfig { | 678 | self.writer.add_track(&TrackConfig { |
| 586 | track_type: TrackType::Subtitle, | 679 | track_type: TrackType::Subtitle, |
| 587 | timescale: SUB_TIMESCALE, | 680 | timescale: SUB_TIMESCALE, |
| 588 | - // `und` and not an empty string where the source states no | 681 | + // The field's own contract, enforced here rather than trusted: |
| 589 | - // language: an mp4 packs the three letters into a 16-bit field | 682 | + // an mp4 packs exactly three ISO 639-2 letters into 16 bits, and |
| 590 | - // and has no way to leave it out, and `und` is the code that | 683 | + // the `mp4` crate's own `language_code` masks whatever it is |
| 591 | - // says *undetermined* -- while three zero bits would spell a | 684 | + // handed into that shape without a word -- a two-letter `en` |
| 592 | - // language nobody speaks. | 685 | + // comes out as `en` and a backtick, a `pt-BR` tag as `ptm` -- |
| 593 | - language: match subs.language.is_empty() { | 686 | + // while Matroska may state a BCP-47 tag for the same track. |
| 594 | - true => "und".to_string(), | 687 | + // `mp4_language` is the one place a tag becomes a code, and |
| 595 | - false => subs.language.clone(), | 688 | + // `und` (the code that means *undetermined*) is what a tag |
| 596 | - }, | 689 | + // nothing names leaves as, rather than a language nobody speaks. |
| 690 | + language: mp4_language(&subs.language), | ||
| 597 | media_conf: MediaConfig::TtxtConfig(TtxtConfig {}), | 691 | media_conf: MediaConfig::TtxtConfig(TtxtConfig {}), |
| 598 | })?; | 692 | })?; |
| 599 | for (bytes, duration) in timed_text(&subs.cues, end)? { | 693 | for (bytes, duration) in timed_text(&subs.cues, end)? { |
| @@ -623,6 +717,13 @@ impl Mp4Muxer { | |||
| 623 | // is coming for either to wait on, so this drains both fully rather | 717 | // is coming for either to wait on, so this drains both fully rather |
| 624 | // than leaving a video-only tail queued. | 718 | // than leaving a video-only tail queued. |
| 625 | self.drain_all()?; | 719 | self.drain_all()?; |
| 720 | + // Both containers refuse a file nobody put a picture in, by name and in | ||
| 721 | + // their own container's words ([`MkvMuxer::finish`] is the twin): an mp4 | ||
| 722 | + // whose picture track holds no sample is a file that opens on a blank | ||
| 723 | + // window with nothing said, which is worse than an export that fails. | ||
| 724 | + if self.frames == 0 { | ||
| 725 | + return Err("no frames were written to the mp4 file".into()); | ||
| 726 | + } | ||
| 626 | self.writer.write_end()?; | 727 | self.writer.write_end()?; |
| 627 | let Self { | 728 | let Self { |
| 628 | writer, | 729 | writer, |
| @@ -940,8 +1041,9 @@ const TIMESTAMP_SCALE_NS: u64 = 1_000_000; | |||
| 940 | /// at the first keyframe past this -- a ceiling on what the muxer holds, not a | 1041 | /// at the first keyframe past this -- a ceiling on what the muxer holds, not a |
| 941 | /// target. | 1042 | /// target. |
| 942 | const CLUSTER_BYTES: usize = 4 << 20; | 1043 | const CLUSTER_BYTES: usize = 4 << 20; |
| 943 | -/// ...and on how far a block's timestamp may sit from its cluster's: the field | 1044 | +/// ...and on how far a block's timestamp may sit from its cluster's, *either* |
| 944 | -/// is a signed 16-bit millisecond count. | 1045 | +/// way: the field is a signed 16-bit millisecond count, and a copy's backwards |
| 1046 | +/// steps over a group of pictures are the direction nothing else bounds. | ||
| 945 | const CLUSTER_MS: i64 = 30_000; | 1047 | const CLUSTER_MS: i64 = 30_000; |
| 946 | 1048 | ||
| 947 | /// The fixed four bytes of an `AV1CodecConfigurationRecord` for what both encode | 1049 | /// The fixed four bytes of an `AV1CodecConfigurationRecord` for what both encode |
| @@ -1022,6 +1124,12 @@ pub struct SubParams { | |||
| 1022 | /// where the source states none -- and *only* then, because a `TrackEntry` | 1124 | /// where the source states none -- and *only* then, because a `TrackEntry` |
| 1023 | /// without a `Language` means `eng` by spec, so a French track that leaves | 1125 | /// without a `Language` means `eng` by spec, so a French track that leaves |
| 1024 | /// this empty leaves as an English one. | 1126 | /// this empty leaves as an English one. |
| 1127 | + /// | ||
| 1128 | + /// Matroska carries whatever bytes this holds, and a file may state a | ||
| 1129 | + /// BCP-47 tag in them (`pt-BR`); an mp4 has one 16-bit field of exactly | ||
| 1130 | + /// three ISO 639-2 letters, so [`Mp4Muxer::write_subtitles`] turns a tag | ||
| 1131 | + /// into a code -- or into `und`, where nothing names it -- rather than | ||
| 1132 | + /// letting the container mangle it. | ||
| 1025 | pub language: String, | 1133 | pub language: String, |
| 1026 | /// What the track is *called*, where it has a title of its own beside its | 1134 | /// What the track is *called*, where it has a title of its own beside its |
| 1027 | /// language (`Signs`, `Forced`). Empty where it has none. | 1135 | /// language (`Signs`, `Forced`). Empty where it has none. |
| @@ -1349,7 +1457,9 @@ impl MkvMuxer { | |||
| 1349 | /// re-timing those blocks one frame apart would play the group in the order | 1457 | /// re-timing those blocks one frame apart would play the group in the order |
| 1350 | /// it was coded in. Matroska times every block in presentation and the | 1458 | /// it was coded in. Matroska times every block in presentation and the |
| 1351 | /// relative timestamp in a block header is signed, so what a copy writes | 1459 | /// relative timestamp in a block header is signed, so what a copy writes |
| 1352 | - /// here is exactly what its source said. | 1460 | + /// here is exactly what its source said -- and a step back wider than that |
| 1461 | + /// signed field reaches opens a cluster of its own rather than being | ||
| 1462 | + /// truncated into an instant nobody asked for ([`Self::cluster_holds`]). | ||
| 1353 | pub fn write_block(&mut self, payload: &[u8], key: bool, ts_ns: i64) -> crate::Result<()> { | 1463 | pub fn write_block(&mut self, payload: &[u8], key: bool, ts_ns: i64) -> crate::Result<()> { |
| 1354 | if payload.is_empty() { | 1464 | if payload.is_empty() { |
| 1355 | return Err("an empty coded block".into()); | 1465 | return Err("an empty coded block".into()); |
| @@ -1363,27 +1473,56 @@ impl MkvMuxer { | |||
| 1363 | // A new cluster at every keyframe -- a seek lands on one, so a cluster | 1473 | // A new cluster at every keyframe -- a seek lands on one, so a cluster |
| 1364 | // is a whole GOP -- and at the two limits a cluster has whatever the | 1474 | // is a whole GOP -- and at the two limits a cluster has whatever the |
| 1365 | // encoder keys: what it may weigh, and how far a 16-bit relative | 1475 | // encoder keys: what it may weigh, and how far a 16-bit relative |
| 1366 | - // timestamp reaches. | 1476 | + // timestamp reaches, either way. |
| 1367 | if self.cluster.is_empty() | 1477 | if self.cluster.is_empty() |
| 1368 | || key | 1478 | || key |
| 1369 | || self.cluster.len() >= CLUSTER_BYTES | 1479 | || self.cluster.len() >= CLUSTER_BYTES |
| 1370 | - || ts - self.cluster_ts >= CLUSTER_MS | 1480 | + || !self.cluster_holds(ts) |
| 1371 | { | 1481 | { |
| 1372 | - self.flush()?; | 1482 | + self.open_cluster(ts)?; |
| 1373 | - self.cluster_ts = ts; | ||
| 1374 | - uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 1375 | } | 1483 | } |
| 1376 | // The sound this picture plays under goes in first, into the cluster the | 1484 | // The sound this picture plays under goes in first, into the cluster the |
| 1377 | // picture opened: a player reads the two together. The cue over it with | 1485 | // picture opened: a player reads the two together. The cue over it with |
| 1378 | // them, for the same reason. | 1486 | // them, for the same reason. |
| 1379 | self.drain_audio(ts)?; | 1487 | self.drain_audio(ts)?; |
| 1380 | self.drain_subs(ts)?; | 1488 | self.drain_subs(ts)?; |
| 1381 | - self.block(1, ts, key, payload); | 1489 | + // ...unless a track lagged this picture by more than a cluster reaches |
| 1490 | + // and opened one of its own behind it, in which case the picture gets a | ||
| 1491 | + // cluster named after its own instant rather than a distance its block | ||
| 1492 | + // header cannot state. | ||
| 1493 | + if !self.cluster_holds(ts) { | ||
| 1494 | + self.open_cluster(ts)?; | ||
| 1495 | + } | ||
| 1496 | + self.block(1, ts, key, payload)?; | ||
| 1382 | self.frames += 1; | 1497 | self.frames += 1; |
| 1383 | self.last_ts = self.last_ts.max(ts); | 1498 | self.last_ts = self.last_ts.max(ts); |
| 1384 | Ok(()) | 1499 | Ok(()) |
| 1385 | } | 1500 | } |
| 1386 | 1501 | ||
| 1502 | + /// Whether the open cluster can hold a block at `ts`. A cluster is buffered | ||
| 1503 | + /// whole and its blocks are timed *relative* to it, in a signed 16-bit | ||
| 1504 | + /// millisecond field ([`CLUSTER_MS`]), so a block further from the cluster's | ||
| 1505 | + /// own timestamp than that -- in **either** direction -- needs a cluster of | ||
| 1506 | + /// its own. The backwards one is the side a copy really takes: a stream with | ||
| 1507 | + /// B-frames is stored in decode order, so its presentation times step back | ||
| 1508 | + /// over a group of pictures. | ||
| 1509 | + /// | ||
| 1510 | + /// This is what keeps every distance written inside the field, which is what | ||
| 1511 | + /// makes [`Self::relative_ms`]'s checked cast a guard of last resort rather | ||
| 1512 | + /// than the place a real block lands. | ||
| 1513 | + fn cluster_holds(&self, ts: i64) -> bool { | ||
| 1514 | + !self.cluster.is_empty() && (ts - self.cluster_ts).unsigned_abs() < CLUSTER_MS as u64 | ||
| 1515 | + } | ||
| 1516 | + | ||
| 1517 | + /// Opens a cluster stating `ts`, closing whatever was open: a cluster's size | ||
| 1518 | + /// is a header field, so it is written whole or not at all. | ||
| 1519 | + fn open_cluster(&mut self, ts: i64) -> crate::Result<()> { | ||
| 1520 | + self.flush()?; | ||
| 1521 | + self.cluster_ts = ts; | ||
| 1522 | + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 1523 | + Ok(()) | ||
| 1524 | + } | ||
| 1525 | + | ||
| 1387 | /// Every audio packet whose timestamp has been reached, into the current | 1526 | /// Every audio packet whose timestamp has been reached, into the current |
| 1388 | /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left -- | 1527 | /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left -- |
| 1389 | /// the sound of a timeline can outlast its last picture by a packet. | 1528 | /// the sound of a timeline can outlast its last picture by a packet. |
| @@ -1408,14 +1547,12 @@ impl MkvMuxer { | |||
| 1408 | let bytes = std::mem::take(&mut packet.bytes); | 1547 | let bytes = std::mem::take(&mut packet.bytes); |
| 1409 | audio.samples += u64::from(packet.samples); | 1548 | audio.samples += u64::from(packet.samples); |
| 1410 | audio.next += 1; | 1549 | audio.next += 1; |
| 1411 | - // A cluster of its own where the sound has run past what a 16-bit | 1550 | + // A cluster of its own where the sound has run further from the open |
| 1412 | - // relative timestamp reaches, which only the tail drain can do. | 1551 | + // one than a 16-bit relative timestamp reaches, either way. |
| 1413 | - if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { | 1552 | + if !self.cluster_holds(ts) { |
| 1414 | - self.flush()?; | 1553 | + self.open_cluster(ts)?; |
| 1415 | - self.cluster_ts = ts; | ||
| 1416 | - uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 1417 | } | 1554 | } |
| 1418 | - self.block(2, ts, true, &bytes); | 1555 | + self.block(2, ts, true, &bytes)?; |
| 1419 | } | 1556 | } |
| 1420 | } | 1557 | } |
| 1421 | 1558 | ||
| @@ -1444,14 +1581,13 @@ impl MkvMuxer { | |||
| 1444 | let text = std::mem::take(&mut cue.text); | 1581 | let text = std::mem::take(&mut cue.text); |
| 1445 | subs.next += 1; | 1582 | subs.next += 1; |
| 1446 | let track_no = subs.track_no; | 1583 | let track_no = subs.track_no; |
| 1447 | - // A cluster of its own where the text has run past what a 16-bit | 1584 | + // A cluster of its own where the text has run further from the |
| 1448 | - // relative timestamp reaches, exactly as the sound's drain does. | 1585 | + // open one than a 16-bit relative timestamp reaches, either way, |
| 1449 | - if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { | 1586 | + // exactly as the sound's drain does. |
| 1450 | - self.flush()?; | 1587 | + if !self.cluster_holds(ts) { |
| 1451 | - self.cluster_ts = ts; | 1588 | + self.open_cluster(ts)?; |
| 1452 | - uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 1453 | } | 1589 | } |
| 1454 | - self.block_group(track_no, ts, ms, text.as_bytes()); | 1590 | + self.block_group(track_no, ts, ms, text.as_bytes())?; |
| 1455 | } | 1591 | } |
| 1456 | } | 1592 | } |
| 1457 | Ok(()) | 1593 | Ok(()) |
| @@ -1459,23 +1595,52 @@ impl MkvMuxer { | |||
| 1459 | 1595 | ||
| 1460 | /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC | 1596 | /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC |
| 1461 | /// packet is a keyframe; a picture is one when the encoder said so. | 1597 | /// packet is a keyframe; a picture is one when the encoder said so. |
| 1462 | - fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { | 1598 | + fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) -> crate::Result<()> { |
| 1599 | + let relative = self.relative_ms(ts)?; | ||
| 1463 | let mut block = Vec::with_capacity(payload.len() + 4); | 1600 | let mut block = Vec::with_capacity(payload.len() + 4); |
| 1464 | block.push(0x80 | track); // the track number as a one-byte EBML integer | 1601 | block.push(0x80 | track); // the track number as a one-byte EBML integer |
| 1465 | - block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); | 1602 | + block.extend_from_slice(&relative); |
| 1466 | block.push(if key { 0x80 } else { 0 }); | 1603 | block.push(if key { 0x80 } else { 0 }); |
| 1467 | block.extend_from_slice(payload); | 1604 | block.extend_from_slice(payload); |
| 1468 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); | 1605 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); |
| 1606 | + Ok(()) | ||
| 1607 | + } | ||
| 1608 | + | ||
| 1609 | + /// A block's own timestamp less its cluster's, in the signed 16-bit | ||
| 1610 | + /// milliseconds the block header carries. | ||
| 1611 | + /// | ||
| 1612 | + /// Checked and not cast: a distance that does not fit is a block at an | ||
| 1613 | + /// instant nobody asked for -- `as i16` of a step back wider than the field | ||
| 1614 | + /// lands as a *positive* offset, 65.536 s past its cluster -- and the error | ||
| 1615 | + /// names the distance instead. Both callers keep the open cluster within | ||
| 1616 | + /// [`CLUSTER_MS`] of every block they write ([`Self::cluster_holds`]), so | ||
| 1617 | + /// this is the guard of last resort rather than a case a file reaches. | ||
| 1618 | + fn relative_ms(&self, ts: i64) -> crate::Result<[u8; 2]> { | ||
| 1619 | + let ms = ts - self.cluster_ts; | ||
| 1620 | + i16::try_from(ms).map(i16::to_be_bytes).map_err(|_| { | ||
| 1621 | + format!( | ||
| 1622 | + "a block {ms} ms from its cluster's timestamp does not fit the 16-bit \ | ||
| 1623 | + relative field" | ||
| 1624 | + ) | ||
| 1625 | + .into() | ||
| 1626 | + }) | ||
| 1469 | } | 1627 | } |
| 1470 | 1628 | ||
| 1471 | /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair | 1629 | /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair |
| 1472 | /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put | 1630 | /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put |
| 1473 | /// a duration, and a subtitle without one stays up until whatever a player | 1631 | /// a duration, and a subtitle without one stays up until whatever a player |
| 1474 | /// decides, which is what a subtitle must never do. | 1632 | /// decides, which is what a subtitle must never do. |
| 1475 | - fn block_group(&mut self, track: u8, ts: i64, duration_ms: u64, payload: &[u8]) { | 1633 | + fn block_group( |
| 1634 | + &mut self, | ||
| 1635 | + track: u8, | ||
| 1636 | + ts: i64, | ||
| 1637 | + duration_ms: u64, | ||
| 1638 | + payload: &[u8], | ||
| 1639 | + ) -> crate::Result<()> { | ||
| 1640 | + let relative = self.relative_ms(ts)?; | ||
| 1476 | let mut block = Vec::with_capacity(payload.len() + 4); | 1641 | let mut block = Vec::with_capacity(payload.len() + 4); |
| 1477 | block.push(0x80 | track); // the track number as a one-byte EBML integer | 1642 | block.push(0x80 | track); // the track number as a one-byte EBML integer |
| 1478 | - block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); | 1643 | + block.extend_from_slice(&relative); |
| 1479 | // No flags a text block can carry: not lacing, and "keyframe" is a | 1644 | // No flags a text block can carry: not lacing, and "keyframe" is a |
| 1480 | // `SimpleBlock` field that a plain `Block` does not have at all. | 1645 | // `SimpleBlock` field that a plain `Block` does not have at all. |
| 1481 | block.push(0); | 1646 | block.push(0); |
| @@ -1484,6 +1649,7 @@ impl MkvMuxer { | |||
| 1484 | elem(&mut group, BLOCK, &block); | 1649 | elem(&mut group, BLOCK, &block); |
| 1485 | uint(&mut group, BLOCK_DURATION, duration_ms); | 1650 | uint(&mut group, BLOCK_DURATION, duration_ms); |
| 1486 | elem(&mut self.cluster, BLOCK_GROUP, &group); | 1651 | elem(&mut self.cluster, BLOCK_GROUP, &group); |
| 1652 | + Ok(()) | ||
| 1487 | } | 1653 | } |
| 1488 | 1654 | ||
| 1489 | fn flush(&mut self) -> crate::Result<()> { | 1655 | fn flush(&mut self) -> crate::Result<()> { |
| @@ -2112,8 +2278,7 @@ mod tests { | |||
| 2112 | .is_err(), | 2278 | .is_err(), |
| 2113 | "SPS too short for avcC" | 2279 | "SPS too short for avcC" |
| 2114 | ); | 2280 | ); |
| 2115 | - assert!( | 2281 | + assert!(Mp4Muxer::create( |
| 2116 | - Mp4Muxer::create( | ||
| 2117 | &out, | 2282 | &out, |
| 2118 | &VideoParams { | 2283 | &VideoParams { |
| 2119 | frame_rate: 0.0, | 2284 | frame_rate: 0.0, |
| @@ -2121,8 +2286,7 @@ mod tests { | |||
| 2121 | }, | 2286 | }, |
| 2122 | None | 2287 | None |
| 2123 | ) | 2288 | ) |
| 2124 | - .is_err() | 2289 | + .is_err()); |
| 2125 | - ); | ||
| 2126 | assert!( | 2290 | assert!( |
| 2127 | Mp4Muxer::create(&out, &VideoParams { width: 0, ..ok }, None).is_err(), | 2291 | Mp4Muxer::create(&out, &VideoParams { width: 0, ..ok }, None).is_err(), |
| 2128 | "zero width" | 2292 | "zero width" |
| @@ -2405,7 +2569,9 @@ mod tests { | |||
| 2405 | ); | 2569 | ); |
| 2406 | let (audio, chunks) = crate::audio::AudioSession::open(&out) | 2570 | let (audio, chunks) = crate::audio::AudioSession::open(&out) |
| 2407 | .unwrap() | 2571 | .unwrap() |
| 2408 | - .unwrap_or_else(|| panic!("{name}: track decodes through the project's own reader")); | 2572 | + .unwrap_or_else(|| { |
| 2573 | + panic!("{name}: track decodes through the project's own reader") | ||
| 2574 | + }); | ||
| 2409 | assert_eq!( | 2575 | assert_eq!( |
| 2410 | (audio.sample_rate, audio.channels), | 2576 | (audio.sample_rate, audio.channels), |
| 2411 | (48_000, want), | 2577 | (48_000, want), |
| @@ -2430,7 +2596,10 @@ mod tests { | |||
| 2430 | .sum::<f32>() | 2596 | .sum::<f32>() |
| 2431 | / n as f32) | 2597 | / n as f32) |
| 2432 | .sqrt(); | 2598 | .sqrt(); |
| 2433 | - assert!(rms > 0.05, "{name}: channel {c} came back silent (rms {rms})"); | 2599 | + assert!( |
| 2600 | + rms > 0.05, | ||
| 2601 | + "{name}: channel {c} came back silent (rms {rms})" | ||
| 2602 | + ); | ||
| 2434 | } | 2603 | } |
| 2435 | std::fs::remove_file(&out).unwrap(); | 2604 | std::fs::remove_file(&out).unwrap(); |
| 2436 | } | 2605 | } |
| @@ -2555,8 +2724,7 @@ mod tests { | |||
| 2555 | 2724 | ||
| 2556 | // A track with no sequence header to declare is refused where the | 2725 | // A track with no sequence header to declare is refused where the |
| 2557 | // message still means something, rather than written unplayable. | 2726 | // message still means something, rather than written unplayable. |
| 2558 | - assert!( | 2727 | + assert!(MkvMuxer::create( |
| 2559 | - MkvMuxer::create( | ||
| 2560 | &out, | 2728 | &out, |
| 2561 | &Av1Params { | 2729 | &Av1Params { |
| 2562 | width: 640, | 2730 | width: 640, |
| @@ -2567,8 +2735,7 @@ mod tests { | |||
| 2567 | None, | 2735 | None, |
| 2568 | Vec::new(), | 2736 | Vec::new(), |
| 2569 | ) | 2737 | ) |
| 2570 | - .is_err() | 2738 | + .is_err()); |
| 2571 | - ); | ||
| 2572 | assert!(av1_sequence_header(&inter).is_none(), "no sequence header"); | 2739 | assert!(av1_sequence_header(&inter).is_none(), "no sequence header"); |
| 2573 | std::fs::remove_file(&out).unwrap(); | 2740 | std::fs::remove_file(&out).unwrap(); |
| 2574 | } | 2741 | } |
| @@ -2614,4 +2781,166 @@ mod tests { | |||
| 2614 | ); | 2781 | ); |
| 2615 | std::fs::remove_file(&out).unwrap(); | 2782 | std::fs::remove_file(&out).unwrap(); |
| 2616 | } | 2783 | } |
| 2784 | + | ||
| 2785 | + /// A block further from its cluster's own timestamp than the 16-bit | ||
| 2786 | + /// *signed* relative field reaches gets a cluster of its own, backwards as | ||
| 2787 | + /// well as forwards: a copied stream is stored in decode order, so its | ||
| 2788 | + /// presentation times step back over a group of pictures | ||
| 2789 | + /// ([`MkvMuxer::write_block`]), and `as i16` of a distance that does not | ||
| 2790 | + /// fit lands as a *positive* offset -- the third block here used to be | ||
| 2791 | + /// written 25.536 s past the cluster that holds it, a picture at 65.536 s | ||
| 2792 | + /// the source put at 0. What is asserted is what a reader sees: every block | ||
| 2793 | + /// at the instant its own source said. | ||
| 2794 | + #[test] | ||
| 2795 | + fn a_block_far_behind_its_cluster_gets_one_rather_than_wrapping() { | ||
| 2796 | + let sequence = obu(1, &[0x11, 0x22, 0x33]); | ||
| 2797 | + let mut key = sequence.clone(); | ||
| 2798 | + key.extend_from_slice(&obu(6, &[0xAA; 8])); | ||
| 2799 | + let inter = obu(6, &[0xBB; 5]); | ||
| 2800 | + let out = Scratch::file("ve_mkv_backward", "mkv"); | ||
| 2801 | + let mut muxer = MkvMuxer::create( | ||
| 2802 | + &out, | ||
| 2803 | + &Av1Params { | ||
| 2804 | + width: 640, | ||
| 2805 | + height: 360, | ||
| 2806 | + frame_rate: 30.0, | ||
| 2807 | + config: av1_sequence_header(&key).unwrap(), | ||
| 2808 | + }, | ||
| 2809 | + None, | ||
| 2810 | + Vec::new(), | ||
| 2811 | + ) | ||
| 2812 | + .unwrap(); | ||
| 2813 | + // A keyframe opens the file at 0, the next picture is 40 s later -- | ||
| 2814 | + // past the forward bound, so a cluster of its own -- and the third is a | ||
| 2815 | + // non-key block back at the start, which is the second one's reorder | ||
| 2816 | + // depth and the direction nothing checked. | ||
| 2817 | + muxer.write_block(&key, true, 0).unwrap(); | ||
| 2818 | + muxer.write_block(&inter, false, 40_000_000_000).unwrap(); | ||
| 2819 | + muxer.write_block(&inter, false, 0).unwrap(); | ||
| 2820 | + muxer.finish().unwrap(); | ||
| 2821 | + | ||
| 2822 | + let (meta, demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); | ||
| 2823 | + assert_eq!(meta.frame_count, 3); | ||
| 2824 | + let crate::demux::Demuxer::Mkv(mut demuxer) = demuxer else { | ||
| 2825 | + panic!("an mkv file"); | ||
| 2826 | + }; | ||
| 2827 | + let times: Vec<i64> = (0..3) | ||
| 2828 | + .map(|i| { | ||
| 2829 | + demuxer | ||
| 2830 | + .coded_block(i) | ||
| 2831 | + .unwrap() | ||
| 2832 | + .unwrap_or_else(|| panic!("block {i}")) | ||
| 2833 | + .ts_ns | ||
| 2834 | + }) | ||
| 2835 | + .collect(); | ||
| 2836 | + assert_eq!( | ||
| 2837 | + times, | ||
| 2838 | + [0, 40_000_000_000, 0], | ||
| 2839 | + "each block at the instant its source said, not wrapped" | ||
| 2840 | + ); | ||
| 2841 | + std::fs::remove_file(&out).unwrap(); | ||
| 2842 | + } | ||
| 2843 | + | ||
| 2844 | + /// A tag Matroska permits where an mp4 has one 16-bit field of three ISO | ||
| 2845 | + /// 639-2 letters: `mp4`'s own `language_code` masks the three UTF-16 units | ||
| 2846 | + /// it is handed with `0x1F` and drops the rest without a word | ||
| 2847 | + /// (`vendor/mp4/src/mp4box/mdhd.rs:157`), so a `pt-BR` track used to be | ||
| 2848 | + /// written as `ptm` -- a language nobody speaks, offered by a player's | ||
| 2849 | + /// subtitle menu as the language the track is not in. | ||
| 2850 | + #[test] | ||
| 2851 | + fn a_tagged_subtitle_track_states_a_language_the_field_can_hold() { | ||
| 2852 | + let out = Scratch::file("ve_mp4_language", "mp4"); | ||
| 2853 | + let mut muxer = Mp4Muxer::create( | ||
| 2854 | + &out, | ||
| 2855 | + &VideoParams { | ||
| 2856 | + width: 640, | ||
| 2857 | + height: 360, | ||
| 2858 | + frame_rate: 30.0, | ||
| 2859 | + sps: SPS, | ||
| 2860 | + pps: PPS, | ||
| 2861 | + }, | ||
| 2862 | + None, | ||
| 2863 | + ) | ||
| 2864 | + .unwrap(); | ||
| 2865 | + // A second of picture, so the text track has a film to run over. | ||
| 2866 | + for _ in 0..30 { | ||
| 2867 | + muxer | ||
| 2868 | + .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]])) | ||
| 2869 | + .unwrap(); | ||
| 2870 | + } | ||
| 2871 | + muxer | ||
| 2872 | + .write_subtitles(&[SubParams { | ||
| 2873 | + language: "pt-BR".into(), | ||
| 2874 | + name: "Signs".into(), | ||
| 2875 | + cues: vec![cue(0, 1_000, "hello")], | ||
| 2876 | + }]) | ||
| 2877 | + .unwrap(); | ||
| 2878 | + muxer.finish().unwrap(); | ||
| 2879 | + | ||
| 2880 | + let file = File::open(&out).unwrap(); | ||
| 2881 | + let size = file.metadata().unwrap().len(); | ||
| 2882 | + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); | ||
| 2883 | + let text = 2; // no audio track: the text is the track after the picture | ||
| 2884 | + assert_eq!( | ||
| 2885 | + reader.tracks()[&text].language(), | ||
| 2886 | + "por", | ||
| 2887 | + "the tag's own language, not a mangling of it" | ||
| 2888 | + ); | ||
| 2889 | + std::fs::remove_file(&out).unwrap(); | ||
| 2890 | + } | ||
| 2891 | + | ||
| 2892 | + /// The four shapes a language can arrive in, and what the container is | ||
| 2893 | + /// handed for each: the code the field already holds, a tag cut to its | ||
| 2894 | + /// primary subtag and mapped, and `und` -- never a string whose first three | ||
| 2895 | + /// UTF-16 units the `mp4` crate would mask into a language nobody speaks. | ||
| 2896 | + #[test] | ||
| 2897 | + fn a_language_is_a_code_before_it_reaches_the_mp4_field() { | ||
| 2898 | + assert_eq!(mp4_language("eng"), "eng", "three letters are the code"); | ||
| 2899 | + assert_eq!(mp4_language("tur"), "tur"); | ||
| 2900 | + assert_eq!(mp4_language("pt-BR"), "por", "the tag's primary subtag"); | ||
| 2901 | + assert_eq!(mp4_language("zh-Hans"), "zho"); | ||
| 2902 | + assert_eq!(mp4_language("en"), "eng", "two letters are mapped"); | ||
| 2903 | + assert_eq!( | ||
| 2904 | + mp4_language("JA"), | ||
| 2905 | + "jpn", | ||
| 2906 | + "a tag's case is not its language" | ||
| 2907 | + ); | ||
| 2908 | + assert_eq!(mp4_language("fil"), "fil", "639-3 is three letters too"); | ||
| 2909 | + assert_eq!(mp4_language(""), "und", "nothing stated, undetermined"); | ||
| 2910 | + assert_eq!(mp4_language("x-pig-latin"), "und", "a tag nothing maps"); | ||
| 2911 | + } | ||
| 2912 | + | ||
| 2913 | + /// A file nobody put a picture in is refused by name rather than written: | ||
| 2914 | + /// [`MkvMuxer::finish`] has always refused the same way, and an mp4 whose | ||
| 2915 | + /// picture track holds no sample comes out as a player's blank window with | ||
| 2916 | + /// nothing said. One picture is all it takes to make the same file finish. | ||
| 2917 | + #[test] | ||
| 2918 | + fn an_mp4_with_no_picture_is_refused_by_name() { | ||
| 2919 | + let params = VideoParams { | ||
| 2920 | + width: 320, | ||
| 2921 | + height: 240, | ||
| 2922 | + frame_rate: 30.0, | ||
| 2923 | + sps: SPS, | ||
| 2924 | + pps: PPS, | ||
| 2925 | + }; | ||
| 2926 | + let out = Scratch::file("ve_mp4_no_picture", "mp4"); | ||
| 2927 | + let err = Mp4Muxer::create(&out, ¶ms, None) | ||
| 2928 | + .unwrap() | ||
| 2929 | + .finish() | ||
| 2930 | + .unwrap_err(); | ||
| 2931 | + assert_eq!( | ||
| 2932 | + err.to_string(), | ||
| 2933 | + "no frames were written to the mp4 file", | ||
| 2934 | + "the Matroska muxer's refusal, in this container's own name" | ||
| 2935 | + ); | ||
| 2936 | + std::fs::remove_file(&out).unwrap(); | ||
| 2937 | + | ||
| 2938 | + let out = Scratch::file("ve_mp4_one_picture", "mp4"); | ||
| 2939 | + let mut muxer = Mp4Muxer::create(&out, ¶ms, None).unwrap(); | ||
| 2940 | + muxer | ||
| 2941 | + .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]])) | ||
| 2942 | + .unwrap(); | ||
| 2943 | + muxer.finish().unwrap(); | ||
| 2944 | + std::fs::remove_file(&out).unwrap(); | ||
| 2945 | + } | ||
| 2617 | } | 2946 | } |