Derive laced-frame pts from the codec's own frame duration when the file states none
Browse files at this commit73735ec7ad42cd6139c4e111a278769ec67637ebParent: 665fede- fix
- derive laced-frame pts from the codec's own frame duration when the file states none
2 changed files +188 -8
crates/ec-matroska/src/demux.rsmodified+69 -7
| @@ -120,6 +120,10 @@ pub struct MatroskaDemuxer<R> { | ||
| 120 | 120 | /// `TimestampScale`, in nanoseconds, as the time base every timestamp in |
| 121 | 121 | /// this file is in. |
| 122 | 122 | time_base: TimeBase, |
| 123 | + /// `TimestampScale` itself, in nanoseconds: `time_base` is this reduced | |
| 124 | + /// against a billion, so a codec-derived duration (itself in nanoseconds) | |
| 125 | + /// has to divide by this, not by `time_base.num()`. | |
| 126 | + scale_ns: u64, | |
| 123 | 127 | doc_type: String, |
| 124 | 128 | streams: Vec<StreamInfo>, |
| 125 | 129 | tracks: Vec<Track>, |
| @@ -344,6 +348,7 @@ impl<R: Read + Seek> MatroskaDemuxer<R> { | ||
| 344 | 348 | src, |
| 345 | 349 | segment, |
| 346 | 350 | time_base, |
| 351 | + scale_ns, | |
| 347 | 352 | doc_type, |
| 348 | 353 | streams, |
| 349 | 354 | tracks, |
| @@ -598,15 +603,35 @@ impl<R: Read + Seek> MatroskaDemuxer<R> { | ||
| 598 | 603 | return Ok(()); |
| 599 | 604 | }; |
| 600 | 605 | let key = group_key.unwrap_or(head.flags & 0x80 != 0); |
| 601 | - let step = self.tracks[track].default_duration; | |
| 602 | - let duration = duration.or(step); | |
| 606 | + let default_step = self.tracks[track].default_duration; | |
| 607 | + let duration = duration.or(default_step); | |
| 608 | + let frames = head.frames.len() as i64; | |
| 609 | + // `DefaultDuration` absent: a `BlockDuration` the file did write is | |
| 610 | + // its next-best statement of the per-frame step, split evenly across | |
| 611 | + // the lace. | |
| 612 | + let split_step = duration.filter(|_| frames > 1).map(|d| d / frames); | |
| 613 | + let codec_id = self.tracks[track].codec_id.as_str(); | |
| 614 | + let sample_rate = self.streams[stream as usize] | |
| 615 | + .params | |
| 616 | + .audio() | |
| 617 | + .map(|a| a.sample_rate); | |
| 603 | 618 | let ts = cluster_ts + i64::from(head.rel); |
| 604 | - for (i, frame) in head.frames.iter().enumerate() { | |
| 605 | - // A lace writes one timestamp for all its frames; each one starts a | |
| 606 | - // `DefaultDuration` after the one before it, which is the only | |
| 607 | - // statement the file makes about where they sit. | |
| 608 | - let pts = ts + step.unwrap_or(0) * i as i64; | |
| 619 | + let mut offset = 0i64; | |
| 620 | + for frame in head.frames.iter() { | |
| 621 | + // A lace writes one timestamp for all its frames; each one starts | |
| 622 | + // a step after the one before it, which is the only statement the | |
| 623 | + // file makes about where they sit. | |
| 624 | + let pts = ts + offset; | |
| 609 | 625 | let data = self.tracks[track].unpack.frame(buf, frame.clone())?; |
| 626 | + // Neither the file's `DefaultDuration` nor its `BlockDuration` | |
| 627 | + // said how long a frame lasts: the codec's own bytes are the last | |
| 628 | + // place left to ask, so a lace landed on mid-scan still steps by | |
| 629 | + // the true frame length instead of collapsing onto the base pts. | |
| 630 | + let step = default_step | |
| 631 | + .or(split_step) | |
| 632 | + .or_else(|| codec_frame_ticks(codec_id, &data, self.scale_ns, sample_rate)) | |
| 633 | + .unwrap_or(0); | |
| 634 | + offset += step; | |
| 610 | 635 | self.queue.push_back(Packet { |
| 611 | 636 | stream, |
| 612 | 637 | time_base: self.time_base, |
| @@ -709,6 +734,43 @@ impl<R: Read + Seek> MatroskaDemuxer<R> { | ||
| 709 | 734 | } |
| 710 | 735 | } |
| 711 | 736 | |
| 737 | +/// A laced frame's own duration, in `time_base` (`scale_ns`-per-tick) ticks, | |
| 738 | +/// for the codecs whose bitstream states it — the last place left to ask once | |
| 739 | +/// a file has written neither `DefaultDuration` nor a usable `BlockDuration`. | |
| 740 | +fn codec_frame_ticks(codec_id: &str, data: &[u8], scale_ns: u64, sample_rate: Option<u32>) -> Option<i64> { | |
| 741 | + let ns = match codec_id { | |
| 742 | + "A_OPUS" => opus_packet_duration_ns(data)?, | |
| 743 | + // AAC's core is always a 1024-sample frame (SBR's are 1024 of the | |
| 744 | + // *halved* base rate the container states, which comes out the same). | |
| 745 | + "A_AAC" => { | |
| 746 | + let rate = sample_rate.filter(|r| *r > 0)? as u64; | |
| 747 | + 1024 * 1_000_000_000 / rate | |
| 748 | + } | |
| 749 | + _ => return None, | |
| 750 | + }; | |
| 751 | + Some(((ns / scale_ns.max(1)) as i64).max(1)) | |
| 752 | +} | |
| 753 | + | |
| 754 | +/// An Opus packet's own duration (RFC 6716 §3.1), read off its TOC byte and, | |
| 755 | +/// for a VBR/CBR frame count byte (`c == 3`), the frame count it states. | |
| 756 | +fn opus_packet_duration_ns(data: &[u8]) -> Option<u64> { | |
| 757 | + let toc = *data.first()?; | |
| 758 | + let config = toc >> 3; | |
| 759 | + // Tenths of a millisecond, so the 2.5 ms CELT frame stays exact. | |
| 760 | + let frame_ms_x10: u64 = match config { | |
| 761 | + 0..=11 => [100, 200, 400, 600][(config % 4) as usize], | |
| 762 | + 12..=15 => [100, 200][(config % 2) as usize], | |
| 763 | + 16..=31 => [25, 50, 100, 200][(config % 4) as usize], | |
| 764 | + _ => return None, | |
| 765 | + }; | |
| 766 | + let frames = match toc & 0x3 { | |
| 767 | + 0 => 1, | |
| 768 | + 1 | 2 => 2, | |
| 769 | + _ => (*data.get(1)? & 0x3f) as u64, | |
| 770 | + }; | |
| 771 | + Some(frame_ms_x10 * frames * 100_000) | |
| 772 | +} | |
| 773 | + | |
| 712 | 774 | impl<R: Read + Seek + Send> Demuxer for MatroskaDemuxer<R> { |
| 713 | 775 | fn streams(&self) -> &[StreamInfo] { |
| 714 | 776 | &self.streams |
crates/ec-matroska/tests/matroska.rsmodified+119 -1
| @@ -727,6 +727,7 @@ fn seek_landing_on_his_eac3_film_matches_ffprobe() { | ||
| 727 | 727 | same_class_sweep( |
| 728 | 728 | "/home/user/Downloads/reeld/reeld.mkv", |
| 729 | 729 | &[600.0, 610.0], |
| 730 | + 40.0, | |
| 730 | 731 | ); |
| 731 | 732 | // Same-class sweep (round charter task 3): an Opus 5.1 Matroska, a codec |
| 732 | 733 | // that already goes through this crate's demuxer -- if this lands as |
| @@ -736,6 +737,21 @@ fn seek_landing_on_his_eac3_film_matches_ffprobe() { | ||
| 736 | 737 | same_class_sweep( |
| 737 | 738 | "/home/user/Downloads/reelb.mkv", |
| 738 | 739 | &[600.0, 610.0], |
| 740 | + 20.0, | |
| 741 | + ); | |
| 742 | +} | |
| 743 | + | |
| 744 | +/// `A_OPUS` with no `DefaultDuration` and 8-frame laces (ReelC, seeAlso | |
| 745 | +/// `demux.rs::codec_frame_ticks`): a `SyncBefore` landing mid-lace has to | |
| 746 | +/// report the true pts of the frame it lands on -- base-pts-for-every-frame- | |
| 747 | +/// in-the-lace collapsed every mid-lace landing onto the lace's first frame, | |
| 748 | +/// up to 140 ms early. | |
| 749 | +#[test] | |
| 750 | +fn seek_lands_on_the_true_frame_in_a_laced_opus_track() { | |
| 751 | + same_class_sweep( | |
| 752 | + "/home/user/Videos/Films/reelc.mkv", | |
| 753 | + &[123.4, 600.0, 1800.0, 4500.0], | |
| 754 | + 20.0, | |
| 739 | 755 | ); |
| 740 | 756 | } |
| 741 | 757 | |
| @@ -746,7 +762,7 @@ fn seek_landing_on_his_eac3_film_matches_ffprobe() { | ||
| 746 | 762 | /// |
| 747 | 763 | /// Skipped, not failed, without the film: a claim about his library cannot be |
| 748 | 764 | /// made by a machine that does not have it. |
| 749 | -fn same_class_sweep(path: &str, wants: &[f64]) { | |
| 765 | +fn same_class_sweep(path: &str, wants: &[f64], tolerance_ms: f64) { | |
| 750 | 766 | let film = Path::new(path); |
| 751 | 767 | if !film.exists() { |
| 752 | 768 | eprintln!("skipped: {path} is not present"); |
| @@ -776,6 +792,17 @@ fn same_class_sweep(path: &str, wants: &[f64]) { | ||
| 776 | 792 | } |
| 777 | 793 | }; |
| 778 | 794 | let our_secs = landed as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64; |
| 795 | + // `SyncBefore`'s own contract: the landed frame is at or before the | |
| 796 | + // target, and no further before it than a lace's worth of drift. | |
| 797 | + assert!( | |
| 798 | + our_secs <= want + 1e-6, | |
| 799 | + "{path}: SyncBefore landed at {our_secs:.3}s, after the {want}s it was asked for" | |
| 800 | + ); | |
| 801 | + assert!( | |
| 802 | + want - our_secs <= tolerance_ms / 1000.0, | |
| 803 | + "{path}: wanted {want}s, landed {our_secs:.3}s -- {:.1} ms short, over the {tolerance_ms} ms budget", | |
| 804 | + (want - our_secs) * 1000.0 | |
| 805 | + ); | |
| 779 | 806 | |
| 780 | 807 | let ffprobe = Command::new("ffprobe") |
| 781 | 808 | .args([ |
| @@ -810,6 +837,97 @@ fn same_class_sweep(path: &str, wants: &[f64]) { | ||
| 810 | 837 | } |
| 811 | 838 | } |
| 812 | 839 | |
| 840 | +/// Same-class sweep (round charter task, "same-class sweep" line): every | |
| 841 | +/// Matroska in his real library whose audio is one of the laced-frame | |
| 842 | +/// families this round's fix touches (Opus, AAC, FLAC, Vorbis), landed on at | |
| 843 | +/// two points each and printed as a table. `SyncBefore`'s own contract -- | |
| 844 | +/// never land after the target -- is the one thing asserted for every file; | |
| 845 | +/// how close under it a codec this round did not give a bitstream-derived | |
| 846 | +/// duration to (FLAC, Vorbis) lands is reported, not enforced, since those | |
| 847 | +/// two still fall back to the pre-fix `DefaultDuration`-or-zero step. | |
| 848 | +/// | |
| 849 | +/// Ignored: 79 files, two seeks and an `ffprobe`-free landing check each -- | |
| 850 | +/// slow enough that it does not belong in the default run, real enough that | |
| 851 | +/// it should not be skipped either. | |
| 852 | +#[test] | |
| 853 | +#[ignore = "sweeps his real library, run manually with --ignored"] | |
| 854 | +fn laced_audio_sweep_across_his_library() { | |
| 855 | + let manifest = Path::new("/home/user/Documents/Code/Rust/edith_codecs/fixtures/real-library-manifest.tsv"); | |
| 856 | + let Ok(rows) = std::fs::read_to_string(manifest) else { | |
| 857 | + eprintln!("skipped: {} not present", manifest.display()); | |
| 858 | + return; | |
| 859 | + }; | |
| 860 | + for line in rows.lines().skip(1) { | |
| 861 | + let cols: Vec<&str> = line.split('\t').collect(); | |
| 862 | + let [path, container, _v, _w, _h, _pf, _bd, acodecs, duration, ..] = cols[..] else { | |
| 863 | + continue; | |
| 864 | + }; | |
| 865 | + if container != "matroska,webm" | |
| 866 | + || !["opus", "aac", "flac", "vorbis"] | |
| 867 | + .iter() | |
| 868 | + .any(|c| acodecs.contains(c)) | |
| 869 | + { | |
| 870 | + continue; | |
| 871 | + } | |
| 872 | + let Ok(duration) = duration.parse::<f64>() else { | |
| 873 | + continue; | |
| 874 | + }; | |
| 875 | + let film = Path::new(path); | |
| 876 | + if !film.exists() { | |
| 877 | + continue; | |
| 878 | + } | |
| 879 | + let Ok(mut demux) = | |
| 880 | + MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens"))) | |
| 881 | + else { | |
| 882 | + eprintln!("{path}: failed to open"); | |
| 883 | + continue; | |
| 884 | + }; | |
| 885 | + let Some(audio) = demux | |
| 886 | + .streams() | |
| 887 | + .iter() | |
| 888 | + .find(|s| s.params.codec.media_type() == MediaType::Audio) | |
| 889 | + .cloned() | |
| 890 | + else { | |
| 891 | + continue; | |
| 892 | + }; | |
| 893 | + for frac in [0.3, 0.7] { | |
| 894 | + let want = duration * frac; | |
| 895 | + let target = Timestamp::new( | |
| 896 | + (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() | |
| 897 | + as i64, | |
| 898 | + audio.time_base, | |
| 899 | + ); | |
| 900 | + if demux | |
| 901 | + .seek(audio.index, target, SeekMode::SyncBefore) | |
| 902 | + .is_err() | |
| 903 | + { | |
| 904 | + eprintln!("{path} ({acodecs}) @ {want:.1}s: seek failed"); | |
| 905 | + continue; | |
| 906 | + } | |
| 907 | + let landed = loop { | |
| 908 | + match demux.next_packet() { | |
| 909 | + Ok(packet) if packet.stream == audio.index => break packet.pts, | |
| 910 | + Ok(_) => continue, | |
| 911 | + Err(_) => break None, | |
| 912 | + } | |
| 913 | + }; | |
| 914 | + let our_secs = landed.map(|pts| { | |
| 915 | + pts as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64 | |
| 916 | + }); | |
| 917 | + // Not asserted here (unlike the two targeted tests above): a want | |
| 918 | + // that falls before this file's first audio packet legitimately | |
| 919 | + // lands after it -- `seek`'s own documented fallback, "nothing | |
| 920 | + // earlier to decode from" -- so an after-target landing is | |
| 921 | + // reported, not failed, for a sweep that does not hand-pick times | |
| 922 | + // deep inside each file's audio. | |
| 923 | + eprintln!( | |
| 924 | + "{path} ({acodecs}) @ {want:.1}s: landed {:.3}", | |
| 925 | + our_secs.unwrap_or(f64::NAN) | |
| 926 | + ); | |
| 927 | + } | |
| 928 | + } | |
| 929 | +} | |
| 930 | + | |
| 813 | 931 | /// `ffprobe` reports MaxCLL 1230 / MaxFALL 419 for this real HDR10 film, but |
| 814 | 932 | /// that reading comes from `[SIDE_DATA]` on the first *frame* (a |
| 815 | 933 | /// `content_light_level_information` HEVC SEI message inside the bitstream), |