forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

reader.rs215 lines, 7.9 KiBHistoryRawDownload
1//! The reader and decoder seats: `ec_probe` behind the incumbent's traits.
2
3use symphonia_core::Result;
4use symphonia_core::codecs::audio::{AudioCodecParameters, AudioDecoder, GenericAudioBufferRef};
5use symphonia_core::codecs::from_ec_parameters;
6use symphonia_core::formats::{FormatReader, SeekMode, SeekTo, SeekedTo, Track, TrackType};
7use symphonia_core::packet::Packet;
8use symphonia_core::units::{Duration, TimeBase, Timestamp};
9
10use ec_core::registry::MediaType;
11
12/// One open file: the tracks it declares, and its packets.
13///
14/// Track ids are the *container's* own — a Matroska `TrackNumber` — so a
15/// caller that named one track by number gets that track back and not the one
16/// that happened to be at the same index.
17pub struct ProbeReader {
18 inner: ec_probe::Reader,
19 tracks: Vec<Track>,
20 /// Audio track ids still owed their terminal, empty-data packet once the
21 /// container itself has run out: `None` before that, then the queue,
22 /// draining to empty rather than back to `None` so a second real EOF read
23 /// hands out nothing more than once each.
24 eos_pending: Option<std::vec::IntoIter<u32>>,
25}
26
27impl ProbeReader {
28 /// Wrap an open [`ec_probe::Reader`].
29 pub fn new(inner: ec_probe::Reader) -> ProbeReader {
30 let tracks = inner
31 .streams()
32 .iter()
33 .map(|s| Track {
34 id: inner.native_id(s.index) as u32,
35 track_type: match s.params.codec.media_type() {
36 MediaType::Audio => TrackType::Audio,
37 MediaType::Video => TrackType::Video,
38 MediaType::Subtitle => TrackType::Subtitle,
39 },
40 time_base: Some(TimeBase::from(s.time_base)),
41 num_frames: s.duration.map(|d| d.max(0) as u64),
42 start_ts: s.start_time.unwrap_or(0).max(0) as u64,
43 delay: Some(u64::from(s.initial_padding)).filter(|d| *d > 0),
44 codec_params: Some(from_ec_parameters(&s.params)),
45 language: s.language.clone(),
46 })
47 .collect();
48 ProbeReader {
49 inner,
50 tracks,
51 eos_pending: None,
52 }
53 }
54
55 /// The stream index behind a track id.
56 fn stream_of(&self, id: u32) -> Option<u32> {
57 self.inner.stream_of_native(u64::from(id))
58 }
59
60 /// The time base of a track id.
61 fn base_of(&self, id: u32) -> ec_core::TimeBase {
62 self.stream_of(id)
63 .and_then(|s| self.inner.streams().iter().find(|i| i.index == s))
64 .map(|s| s.time_base)
65 .unwrap_or(ec_core::TimeBase::MILLIS)
66 }
67}
68
69impl FormatReader for ProbeReader {
70 fn tracks(&self) -> &[Track] {
71 &self.tracks
72 }
73
74 fn default_track(&self, kind: TrackType) -> Option<&Track> {
75 // The container's flagged track, not merely the first one of its kind:
76 // a dual-audio remux that marked its second track default opens in that
77 // language, which is what a caller asking for "the audio" means by it.
78 let media = match kind {
79 TrackType::Audio => MediaType::Audio,
80 TrackType::Video => MediaType::Video,
81 TrackType::Subtitle => MediaType::Subtitle,
82 };
83 let index = self.inner.default_stream(media)?.index;
84 self.tracks.get(index as usize)
85 }
86
87 fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result<SeekedTo> {
88 let (time, track_id) = match to {
89 SeekTo::Time { time, track_id } => (time.as_secs_f64(), track_id),
90 SeekTo::TimeStamp { ts, track_id } => {
91 let base = self.base_of(track_id);
92 (ts.value() as f64 * base.as_secs_f64(), Some(track_id))
93 }
94 };
95 let id = track_id
96 .or_else(|| self.default_track(TrackType::Audio).map(|t| t.id))
97 .unwrap_or(0);
98 let stream = self.stream_of(id).unwrap_or(0);
99 let base = self.base_of(id);
100 let ticks = (time / base.as_secs_f64()) as i64;
101 let landed = self.inner.seek(
102 stream,
103 ec_core::Timestamp::new(ticks, base),
104 match mode {
105 // Both modes land at or before the target: it is the only
106 // landing a decoder can reach the exact sample from.
107 SeekMode::Accurate | SeekMode::Coarse => ec_core::SeekMode::SyncBefore,
108 },
109 )?;
110 Ok(SeekedTo {
111 track_id: id,
112 required_ts: Timestamp::new(ticks),
113 actual_ts: Timestamp::new(landed.ticks),
114 })
115 }
116
117 fn next_packet(&mut self) -> Result<Option<Packet>> {
118 if let Some(pending) = &mut self.eos_pending {
119 // Empty data is the flush signal `EcAudioDecoder::decode` reads:
120 // a real packet is never zero bytes for any codec this family
121 // decodes.
122 return Ok(pending
123 .next()
124 .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[])));
125 }
126 match self.inner.next_packet() {
127 Ok(packet) => {
128 let id = self.inner.native_id(packet.stream) as u32;
129 let granule = ec_ogg::granule_of(&packet);
130 let mut out = Packet::new(
131 id,
132 Timestamp::new(packet.pts.unwrap_or(0)),
133 Duration::new(packet.duration.unwrap_or(0).max(0) as u64),
134 &packet.data,
135 );
136 out.granule = granule;
137 Ok(Some(out))
138 }
139 Err(e) if e.is_eof() => {
140 // The container itself is exhausted: give every audio track
141 // one last, empty packet so its decoder is told to flush the
142 // hop it has been holding back, then report real EOF.
143 let ids: Vec<u32> = self
144 .tracks
145 .iter()
146 .filter(|t| t.track_type == TrackType::Audio)
147 .map(|t| t.id)
148 .collect();
149 let mut ids = ids.into_iter();
150 let first = ids
151 .next()
152 .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[]));
153 self.eos_pending = Some(ids);
154 Ok(first)
155 }
156 Err(e) => Err(e.into()),
157 }
158 }
159}
160
161/// One decoder seat over [`ec_probe::AudioDecoder`].
162pub(crate) struct EcAudioDecoder {
163 inner: ec_probe::AudioDecoder,
164 params: AudioCodecParameters,
165 out: Vec<f32>,
166}
167
168impl EcAudioDecoder {
169 pub(crate) fn new(
170 inner: ec_probe::AudioDecoder,
171 params: AudioCodecParameters,
172 ) -> EcAudioDecoder {
173 EcAudioDecoder {
174 inner,
175 params,
176 out: Vec::new(),
177 }
178 }
179}
180
181impl AudioDecoder for EcAudioDecoder {
182 fn decode(&mut self, packet: &Packet) -> Result<GenericAudioBufferRef<'_>> {
183 if packet.data.is_empty() {
184 // `ProbeReader::next_packet`'s terminal, empty packet: the file
185 // has run out, and this is the signal to release whatever the
186 // decoder was holding back rather than decode nothing.
187 self.inner.flush(&mut self.out)?;
188 } else {
189 let rate = self.inner.sample_rate().max(1);
190 let mut ec = ec_core::Packet::new(
191 packet.track_id,
192 ec_core::TimeBase::from_rate(rate),
193 packet.data.as_ref(),
194 );
195 ec.pts = Some(packet.pts.value());
196 ec.duration = Some(packet.dur.value() as i64);
197 if let Some(granule) = packet.granule {
198 ec.side_data.push(ec_ogg::granule_side_data(granule));
199 }
200 self.inner.decode(&ec, &mut self.out)?;
201 }
202 Ok(GenericAudioBufferRef::new(
203 &self.out,
204 self.inner.channels().max(1),
205 ))
206 }
207
208 fn codec_params(&self) -> &AudioCodecParameters {
209 &self.params
210 }
211
212 fn reset(&mut self) {
213 self.inner.reset();
214 }
215}