| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | use std::io::Read; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | |
| 24 | use ec_core::registry::SeekMode; |
| 25 | use ec_core::timebase::{Rounding, TimeBase, Timestamp}; |
| 26 | use ec_core::{CodecId, CodecParameters, MediaParameters, MediaType, Packet}; |
| 27 | |
| 28 | |
| 29 | pub(crate) fn is_ext_codec(codec: CodecId) -> bool { |
| 30 | matches!( |
| 31 | codec, |
| 32 | CodecId::Dts |
| 33 | | CodecId::ImaAdpcmWav |
| 34 | | CodecId::MsAdpcm |
| 35 | | CodecId::ImaAdpcmQt |
| 36 | | CodecId::PcmAlaw |
| 37 | | CodecId::PcmMulaw |
| 38 | | CodecId::AmrNb |
| 39 | | CodecId::AmrWb |
| 40 | |
| 41 | | CodecId::Mp1 |
| 42 | | CodecId::Mp2 |
| 43 | | CodecId::Mp3 |
| 44 | ) |
| 45 | } |
| 46 | |
| 47 | |
| 48 | pub(crate) fn is_mkv_dts(id: &str) -> bool { |
| 49 | id == "A_DTS" || id.starts_with("A_DTS/") |
| 50 | } |
| 51 | |
| 52 | |
| 53 | |
| 54 | pub(crate) fn is_mkv_mpeg_layer(id: &str) -> bool { |
| 55 | matches!(id, "A_MPEG/L1" | "A_MPEG/L2") |
| 56 | } |
| 57 | |
| 58 | enum Inner { |
| 59 | Dts(Box<ec_dts::DtsDecoder>), |
| 60 | Probe(Box<ec_probe::AudioDecoder>), |
| 61 | } |
| 62 | |
| 63 | |
| 64 | pub(crate) struct ExtDecoder { |
| 65 | inner: Inner, |
| 66 | scratch: Vec<f32>, |
| 67 | } |
| 68 | |
| 69 | impl ExtDecoder { |
| 70 | pub(crate) fn new(params: &CodecParameters) -> crate::Result<Self> { |
| 71 | let inner = match params.codec { |
| 72 | CodecId::Dts => Inner::Dts(Box::new(ec_dts::DtsDecoder::with_options(ec_dts::Options { |
| 73 | |
| 74 | |
| 75 | refuse_xll: true, |
| 76 | }))), |
| 77 | codec if is_ext_codec(codec) => Inner::Probe(Box::new( |
| 78 | ec_probe::AudioDecoder::new(params).map_err(|e| format!("{}: {e}", codec.name()))?, |
| 79 | )), |
| 80 | codec => return Err(format!("{}: no decoder in the extended audio seat", codec.name()).into()), |
| 81 | }; |
| 82 | Ok(Self { |
| 83 | inner, |
| 84 | scratch: Vec::new(), |
| 85 | }) |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | pub(crate) fn decode(&mut self, data: &[u8]) -> crate::Result<Option<(Vec<f32>, usize)>> { |
| 91 | match &mut self.inner { |
| 92 | Inner::Dts(d) => match d.decode_frame(data) { |
| 93 | Ok(frame) => { |
| 94 | let channels = frame.layout.channel_count().max(1); |
| 95 | let mut samples: Vec<f32> = frame |
| 96 | .data |
| 97 | .first() |
| 98 | .into_iter() |
| 99 | .flat_map(|plane| plane.as_chunks::<4>().0.iter()) |
| 100 | .map(|s| f32::from_le_bytes(*s)) |
| 101 | .collect(); |
| 102 | if channels == 7 { |
| 103 | |
| 104 | for f in samples.as_chunks_mut::<7>().0 { |
| 105 | f[4..].rotate_right(1); |
| 106 | } |
| 107 | } |
| 108 | Ok((!samples.is_empty()).then_some((samples, channels))) |
| 109 | } |
| 110 | Err(ec_core::Error::NeedMore) => Ok(None), |
| 111 | Err(e) => Err(format!("DTS: {e}").into()), |
| 112 | }, |
| 113 | Inner::Probe(d) => { |
| 114 | let packet = Packet::new(0, TimeBase::new(1, 1000), data.to_vec()); |
| 115 | match d.decode(&packet, &mut self.scratch) { |
| 116 | Ok(()) => {} |
| 117 | Err(ec_core::Error::NeedMore) => return Ok(None), |
| 118 | Err(e) => return Err(format!("{}: {e}", d.codec().name()).into()), |
| 119 | } |
| 120 | let channels = d.channels().max(1); |
| 121 | Ok((!self.scratch.is_empty()).then(|| (std::mem::take(&mut self.scratch), channels))) |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | |
| 128 | #[derive(Clone, Copy)] |
| 129 | pub(crate) enum Pick { |
| 130 | |
| 131 | Nth(usize), |
| 132 | |
| 133 | Native(u64), |
| 134 | } |
| 135 | |
| 136 | |
| 137 | pub(crate) struct ExtFileTrack { |
| 138 | path: PathBuf, |
| 139 | reader: ec_probe::Reader, |
| 140 | stream: u32, |
| 141 | pick: Pick, |
| 142 | params: CodecParameters, |
| 143 | time_base: TimeBase, |
| 144 | |
| 145 | pub(crate) sample_rate: u32, |
| 146 | pub(crate) src_channels: usize, |
| 147 | pub(crate) total_samples: Option<u64>, |
| 148 | |
| 149 | |
| 150 | pub(crate) priming: u64, |
| 151 | |
| 152 | pub(crate) pre_roll_secs: f64, |
| 153 | } |
| 154 | |
| 155 | |
| 156 | |
| 157 | fn sniffs_as_ext(path: &Path) -> bool { |
| 158 | let mut head = vec![0u8; 64 << 10]; |
| 159 | let Ok(mut file) = std::fs::File::open(path) else { |
| 160 | return false; |
| 161 | }; |
| 162 | let mut n = 0; |
| 163 | while n < head.len() { |
| 164 | match file.read(&mut head[n..]) { |
| 165 | Ok(0) | Err(_) => break, |
| 166 | Ok(m) => n += m, |
| 167 | } |
| 168 | } |
| 169 | matches!( |
| 170 | ec_probe::sniff(&head[..n]), |
| 171 | Some( |
| 172 | ec_probe::Format::Wav |
| 173 | | ec_probe::Format::Dts |
| 174 | | ec_probe::Format::Amr |
| 175 | | ec_probe::Format::Mp4 |
| 176 | | ec_probe::Format::Matroska |
| 177 | ) |
| 178 | ) |
| 179 | } |
| 180 | |
| 181 | impl ExtFileTrack { |
| 182 | |
| 183 | |
| 184 | pub(crate) fn open(path: &Path, index: usize) -> crate::Result<Option<Self>> { |
| 185 | if !sniffs_as_ext(path) { |
| 186 | return Ok(None); |
| 187 | } |
| 188 | Self::open_pick(path, Pick::Nth(index)) |
| 189 | } |
| 190 | |
| 191 | |
| 192 | pub(crate) fn open_native(path: &Path, number: u64) -> crate::Result<Option<Self>> { |
| 193 | Self::open_pick(path, Pick::Native(number)) |
| 194 | } |
| 195 | |
| 196 | fn open_pick(path: &Path, pick: Pick) -> crate::Result<Option<Self>> { |
| 197 | let reader = match ec_probe::Reader::open(path) { |
| 198 | Ok(reader) => reader, |
| 199 | Err(_) => return Ok(None), |
| 200 | }; |
| 201 | let audio: Vec<_> = reader |
| 202 | .streams() |
| 203 | .iter() |
| 204 | .filter(|s| s.params.codec.media_type() == MediaType::Audio) |
| 205 | .collect(); |
| 206 | let info = match pick { |
| 207 | Pick::Nth(n) => audio.get(n).copied(), |
| 208 | Pick::Native(id) => reader |
| 209 | .stream_of_native(id) |
| 210 | .and_then(|i| audio.iter().find(|s| s.index == i).copied()), |
| 211 | }; |
| 212 | let Some(info) = info else { |
| 213 | return Ok(None); |
| 214 | }; |
| 215 | if !is_ext_codec(info.params.codec) { |
| 216 | return Ok(None); |
| 217 | } |
| 218 | let reader_is_mp4 = reader.format() == ec_probe::Format::Mp4; |
| 219 | let (stream, params, time_base) = (info.index, info.params.clone(), info.time_base); |
| 220 | let duration = info.duration; |
| 221 | let codec = info.params.codec; |
| 222 | let padding = u64::from(info.initial_padding); |
| 223 | let (mut rate, mut channels) = match ¶ms.media { |
| 224 | MediaParameters::Audio(a) => (a.sample_rate, a.layout.channel_count()), |
| 225 | _ => (0, 0), |
| 226 | }; |
| 227 | let mut track = Self { |
| 228 | path: path.to_path_buf(), |
| 229 | reader, |
| 230 | stream, |
| 231 | pick, |
| 232 | params, |
| 233 | time_base, |
| 234 | sample_rate: rate, |
| 235 | src_channels: channels.max(1), |
| 236 | total_samples: None, |
| 237 | priming: padding, |
| 238 | pre_roll_secs: match codec { |
| 239 | CodecId::Dts => 0.2, |
| 240 | CodecId::AmrNb | CodecId::AmrWb => 0.5, |
| 241 | _ => 0.0, |
| 242 | }, |
| 243 | }; |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | if reader_is_mp4 |
| 250 | && let Pick::Nth(n) = pick |
| 251 | && let Ok(mp4) = crate::mp4track::open(path) |
| 252 | && let Some(&(track_id, Some(stream))) = crate::mp4track::audio_tracks(&mp4).get(n) |
| 253 | && let Some(t) = crate::mp4track::media_time(&mp4, track_id) |
| 254 | { |
| 255 | let scale = u64::from(crate::mp4track::timescale(&mp4, stream).max(1)); |
| 256 | track.priming = t * u64::from(track.sample_rate.max(1)) / scale; |
| 257 | } |
| 258 | let mut decoder = track.decoder()?; |
| 259 | for _ in 0..64 { |
| 260 | let Some((_, bytes)) = track.next_packet()? else { |
| 261 | break; |
| 262 | }; |
| 263 | if let Some((_, c)) = decoder.decode(&bytes)? { |
| 264 | channels = c; |
| 265 | break; |
| 266 | } |
| 267 | } |
| 268 | if let Inner::Dts(d) = &decoder.inner |
| 269 | && let Some(info) = d.frame_info() |
| 270 | { |
| 271 | rate = info.sample_rate; |
| 272 | } |
| 273 | track.reopen()?; |
| 274 | if rate == 0 { |
| 275 | return Err(format!("{}: the audio track states no sample rate", path.display()).into()); |
| 276 | } |
| 277 | track.sample_rate = rate; |
| 278 | track.priming = track.priming.min(u64::MAX / 2); |
| 279 | track.src_channels = channels.max(1); |
| 280 | track.total_samples = duration |
| 281 | .filter(|&d| d > 0) |
| 282 | .map(|d| (time_base.rescale(d, TimeBase::from_rate(rate), Rounding::Down).max(0) as u64).saturating_sub(track.priming)); |
| 283 | Ok(Some(track)) |
| 284 | } |
| 285 | |
| 286 | |
| 287 | pub(crate) fn channels(&self) -> u16 { |
| 288 | if self.src_channels == 1 { 1 } else { 2 } |
| 289 | } |
| 290 | |
| 291 | pub(crate) fn codec_name(&self) -> &'static str { |
| 292 | self.params.codec.name() |
| 293 | } |
| 294 | |
| 295 | pub(crate) fn decoder(&self) -> crate::Result<ExtDecoder> { |
| 296 | ExtDecoder::new(&self.params) |
| 297 | } |
| 298 | |
| 299 | fn reopen(&mut self) -> crate::Result<()> { |
| 300 | let reader = ec_probe::Reader::open(&self.path).map_err(|e| format!("{}: {e}", self.path.display()))?; |
| 301 | self.stream = match self.pick { |
| 302 | Pick::Nth(n) => reader |
| 303 | .streams() |
| 304 | .iter() |
| 305 | .filter(|s| s.params.codec.media_type() == MediaType::Audio) |
| 306 | .nth(n) |
| 307 | .map(|s| s.index), |
| 308 | Pick::Native(id) => reader.stream_of_native(id), |
| 309 | } |
| 310 | .ok_or("the audio stream vanished on reopen")?; |
| 311 | self.reader = reader; |
| 312 | Ok(()) |
| 313 | } |
| 314 | |
| 315 | |
| 316 | pub(crate) fn seek(&mut self, secs: f64) -> crate::Result<()> { |
| 317 | let secs = secs - self.pre_roll_secs; |
| 318 | if secs <= 0.05 { |
| 319 | return self.reopen(); |
| 320 | } |
| 321 | let ticks = (secs * self.time_base.den() as f64 / self.time_base.num().max(1) as f64) as i64; |
| 322 | match self |
| 323 | .reader |
| 324 | .seek(self.stream, Timestamp::new(ticks, self.time_base), SeekMode::Exact) |
| 325 | { |
| 326 | Ok(_) => Ok(()), |
| 327 | Err(_) => self.reopen(), |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | |
| 332 | |
| 333 | pub(crate) fn next_packet(&mut self) -> crate::Result<Option<(Option<u64>, Vec<u8>)>> { |
| 334 | loop { |
| 335 | match self.reader.next_packet() { |
| 336 | Ok(p) if p.stream == self.stream => { |
| 337 | let pos = p |
| 338 | .pts |
| 339 | .or(p.dts) |
| 340 | .map(|t| p.time_base.rescale(t, TimeBase::from_rate(self.sample_rate), Rounding::Nearest).max(0) as u64); |
| 341 | return Ok(Some((pos, p.data.as_ref().to_vec()))); |
| 342 | } |
| 343 | Ok(_) => {} |
| 344 | Err(ec_core::Error::Eof) => return Ok(None), |
| 345 | Err(e) => return Err(format!("{}: {e}", self.path.display()).into()), |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | } |