forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

mp4track.rs160 lines, 5.9 KiBHistoryRawDownload
1//! Edith's access to an mp4 track's audio, over `ec-mp4`'s demuxer.
2//!
3//! The audio readers ask an mp4 the same few questions -- which tracks are
4//! audio, what each one's config says, how long its sample table is, where its
5//! edit list starts the presentation -- and this is where those answers come
6//! from. Stream numbers are `ec-mp4`'s: [`ec_mp4::TrackInfo::stream`] for a
7//! track, [`ec_mp4::Mp4Demuxer::samples`] for its table.
8
9use std::fs::File;
10use std::io::BufReader;
11use std::path::Path;
12
13use ec_core::{CodecId, Demuxer as _, MediaParameters, MediaType, Packet, StreamInfo};
14use ec_mp4::Mp4Demuxer;
15
16/// An mp4 file open for reading: its sample tables are its index, and sample
17/// bytes are read on demand.
18pub(crate) type Reader = Mp4Demuxer<BufReader<File>>;
19
20/// Opens `path` as an mp4 (or QuickTime) file and reads its movie header and
21/// sample tables.
22pub(crate) fn open(path: &Path) -> crate::Result<Reader> {
23 crate::demux::refuse_asf(path)?;
24 let file = File::open(path)?;
25 Mp4Demuxer::new(BufReader::new(file)).map_err(crate::demux::mp4_error)
26}
27
28/// The audio tracks of `reader`, in file order (the order a stream index
29/// counts in), as `(track id, stream)`. `stream` is [`None`] for a track this
30/// build has no codec for. Read from the `moov`, not a `HashMap`, so "stream 0"
31/// is the same track from one run to the next.
32pub(crate) fn audio_tracks(reader: &Reader) -> Vec<(u32, Option<u32>)> {
33 reader
34 .tracks()
35 .iter()
36 .filter(|t| t.media == Some(MediaType::Audio))
37 .map(|t| (t.track_id, t.stream))
38 .collect()
39}
40
41fn stream_info(reader: &Reader, stream: u32) -> Option<&StreamInfo> {
42 reader.streams().iter().find(|s| s.index == stream)
43}
44
45/// The codec of `stream`, [`None`] for a stream that does not exist.
46pub(crate) fn codec(reader: &Reader, stream: u32) -> Option<CodecId> {
47 stream_info(reader, stream).map(|s| s.params.codec)
48}
49
50/// The fourcc of `track_id`'s first sample entry: `mp4a`, `ac-3`, `alac`, ...
51pub(crate) fn sample_entry(reader: &Reader, track_id: u32) -> [u8; 4] {
52 reader
53 .tracks()
54 .iter()
55 .find(|t| t.track_id == track_id)
56 .map_or([0; 4], |t| t.sample_entry)
57}
58
59/// The sample rate of an audio `stream`, in Hz (for AAC, the rate the decoder
60/// produces: the SBR extension rate where the config states one).
61pub(crate) fn sample_rate(reader: &Reader, stream: u32) -> u32 {
62 match stream_info(reader, stream).map(|s| &s.params.media) {
63 Some(MediaParameters::Audio(a)) => a.sample_rate,
64 _ => 0,
65 }
66}
67
68/// The channel count of an audio `stream`, from its config.
69pub(crate) fn channels(reader: &Reader, stream: u32) -> usize {
70 match stream_info(reader, stream).map(|s| &s.params.media) {
71 Some(MediaParameters::Audio(a)) => a.layout.channel_count(),
72 _ => 0,
73 }
74}
75
76/// The codec configuration bytes of `stream` as the file states them: an AAC
77/// track's `AudioSpecificConfig` verbatim, extension frequency and all.
78pub(crate) fn extradata(reader: &Reader, stream: u32) -> Option<Box<[u8]>> {
79 stream_info(reader, stream)
80 .and_then(|s| s.params.extradata.as_deref())
81 .map(Box::from)
82}
83
84/// Ticks per second of `stream`'s time base: its media timescale.
85pub(crate) fn timescale(reader: &Reader, stream: u32) -> u32 {
86 stream_info(reader, stream).map_or(1, |s| {
87 let (num, den) = (s.time_base.num().max(1), s.time_base.den());
88 u32::try_from(den / num).unwrap_or(u32::MAX).max(1)
89 })
90}
91
92/// The `mdhd` duration of `stream`, in its timescale, [`None`] where the file
93/// states none.
94pub(crate) fn duration(reader: &Reader, stream: u32) -> Option<u64> {
95 stream_info(reader, stream)?
96 .duration
97 .and_then(|d| u64::try_from(d).ok())
98}
99
100/// The ISO 639-2 language of `track_id`, [`None`] for the `und` a muxer writes
101/// when it was never told.
102pub(crate) fn language(reader: &Reader, track_id: u32) -> Option<String> {
103 reader
104 .tracks()
105 .iter()
106 .find(|t| t.track_id == track_id)
107 .and_then(|t| t.language.clone())
108}
109
110/// `media_time` of `track_id`'s first real edit-list entry, in its timescale:
111/// where the presentation starts inside the media. [`None`] with no edit list,
112/// or only empty entries, which shift the timeline rather than trim the media.
113pub(crate) fn media_time(reader: &Reader, track_id: u32) -> Option<u64> {
114 reader
115 .tracks()
116 .iter()
117 .find(|t| t.track_id == track_id)
118 .and_then(|t| t.media_time)
119 .and_then(|t| u64::try_from(t).ok())
120}
121
122/// How many samples `stream` has.
123pub(crate) fn sample_count(reader: &Reader, stream: u32) -> u32 {
124 u32::try_from(reader.samples(stream).len()).unwrap_or(u32::MAX)
125}
126
127/// The bytes of `stream`'s samples in all: what its byte rate is measured from.
128pub(crate) fn sample_bytes(reader: &Reader, stream: u32) -> u64 {
129 reader
130 .samples(stream)
131 .iter()
132 .map(|s| u64::from(s.size))
133 .sum()
134}
135
136/// The decode durations of `stream` as `(sample count, duration)` runs, the
137/// shape of an `stts` table, for [`crate::audio::packet_at`].
138pub(crate) fn stts(reader: &Reader, stream: u32) -> Vec<(u32, u32)> {
139 let mut runs: Vec<(u32, u32)> = Vec::new();
140 for sample in reader.samples(stream) {
141 match runs.last_mut() {
142 Some((count, delta)) if *delta == sample.duration => *count += 1,
143 _ => runs.push((1, sample.duration)),
144 }
145 }
146 runs
147}
148
149/// Sample `id` of `stream`, counted from 1 as an mp4 counts them, read without
150/// moving any other cursor. [`None`] past the end of the track.
151pub(crate) fn sample(reader: &mut Reader, stream: u32, id: u32) -> crate::Result<Option<Packet>> {
152 let Some(index) = id.checked_sub(1) else {
153 return Ok(None);
154 };
155 match reader.read_sample(stream, index as usize) {
156 Ok(packet) => Ok(Some(packet)),
157 Err(ec_core::Error::Eof) => Ok(None),
158 Err(e) => Err(crate::demux::mp4_error(e)),
159 }
160}