| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | use std::io::BufReader; |
| 37 | |
| 38 | use ec_core::registry::SeekMode; |
| 39 | use ec_core::timebase::{Rounding, TimeBase, Timestamp}; |
| 40 | use ec_core::{CodecId, MediaType, Packet, StreamInfo}; |
| 41 | use ec_mpegts::{StreamKind as TsKind, TrackInfo}; |
| 42 | use ec_riff::{AviDemuxer, AviTrackInfo}; |
| 43 | |
| 44 | use super::*; |
| 45 | |
| 46 | type Reader = BufReader<File>; |
| 47 | |
| 48 | |
| 49 | fn tb() -> TimeBase { |
| 50 | TimeBase::new(1, 90_000) |
| 51 | } |
| 52 | |
| 53 | pub(crate) fn avi_error(e: ec_core::Error) -> crate::Error { |
| 54 | match &e { |
| 55 | |
| 56 | ec_core::Error::Unsupported { .. } => format!( |
| 57 | "AVI: {e} — convert it with {}", |
| 58 | super::ts::convert_line(super::ts::Flavor::Avi) |
| 59 | ) |
| 60 | .into(), |
| 61 | _ => format!("AVI: {e}").into(), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | pub fn is_avi(path: &Path) -> bool { |
| 69 | if sniff_container(path).is_some() { |
| 70 | return false; |
| 71 | } |
| 72 | let mut head = [0u8; 12]; |
| 73 | let read = File::open(path).and_then(|mut f| f.read(&mut head)).unwrap_or(0); |
| 74 | if ec_riff::is_avi(&head[..read]) { |
| 75 | return true; |
| 76 | } |
| 77 | |
| 78 | |
| 79 | path.extension() |
| 80 | .and_then(|e| e.to_str()) |
| 81 | .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "avi" | "divx")) |
| 82 | && !(read >= 4 && (&head[..4] == b"RIFF" || head[0] == 0x47)) |
| 83 | } |
| 84 | |
| 85 | |
| 86 | pub(crate) struct AviSrc { |
| 87 | d: AviDemuxer<Reader>, |
| 88 | |
| 89 | streams: Vec<StreamInfo>, |
| 90 | |
| 91 | native: Vec<TimeBase>, |
| 92 | tracks: Vec<TrackInfo>, |
| 93 | } |
| 94 | |
| 95 | fn refused_name(info: &AviTrackInfo) -> String { |
| 96 | match info.media { |
| 97 | Some(MediaType::Audio) => { |
| 98 | let tag = u16::from_le_bytes([info.tag[0], info.tag[1]]); |
| 99 | match tag { |
| 100 | 0x0160 => "wmav1".into(), |
| 101 | 0x0161 => "wmav2".into(), |
| 102 | 0x0162 => "wmapro".into(), |
| 103 | 0x0002 => "adpcm_ms".into(), |
| 104 | 0x0011 => "adpcm_ima_wav".into(), |
| 105 | 0x0055 => "mp3".into(), |
| 106 | 0x2001 => "dts".into(), |
| 107 | 0x00FF => "aac".into(), |
| 108 | _ => format!("wav_{tag:04x}"), |
| 109 | } |
| 110 | } |
| 111 | _ => String::from_utf8_lossy(&info.tag).trim().to_ascii_lowercase(), |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | fn codec_config(d: &mut AviDemuxer<Reader>, stream: &StreamInfo) -> Option<Vec<u8>> { |
| 119 | let codec = stream.params.codec; |
| 120 | if !matches!(codec, CodecId::H264 | CodecId::Mpeg2Video) { |
| 121 | return None; |
| 122 | } |
| 123 | d.rewind(); |
| 124 | let (mut sps, mut pps) = (None, None); |
| 125 | |
| 126 | |
| 127 | if let Some(extra) = stream.params.extradata.as_ref().filter(|_| codec == CodecId::H264) { |
| 128 | let extra: &[u8] = extra; |
| 129 | if extra.first() == Some(&1) { |
| 130 | return Some(extra.to_vec()); |
| 131 | } |
| 132 | for nal in ec_mpegts::nal_units(extra) { |
| 133 | match nal.first().map(|b| b & 0x1f) { |
| 134 | Some(7) if sps.is_none() => sps = Some(nal.to_vec()), |
| 135 | Some(8) if pps.is_none() => pps = Some(nal.to_vec()), |
| 136 | _ => {} |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | for _ in 0..256 { |
| 141 | if sps.is_some() && pps.is_some() { |
| 142 | break; |
| 143 | } |
| 144 | let Ok(p) = d.next_packet() else { break }; |
| 145 | if p.stream != stream.index { |
| 146 | continue; |
| 147 | } |
| 148 | let data: &[u8] = &p.data; |
| 149 | if codec == CodecId::Mpeg2Video { |
| 150 | let at = data.windows(4).position(|w| w == [0, 0, 1, 0xB3])?; |
| 151 | let end = data[at + 4..].windows(4).position(|w| w == [0, 0, 1, 0x00]).map_or(data.len(), |e| at + 4 + e); |
| 152 | return Some(data[at..end].to_vec()); |
| 153 | } |
| 154 | for nal in ec_mpegts::nal_units(data) { |
| 155 | match nal.first().map(|b| b & 0x1f) { |
| 156 | Some(7) if sps.is_none() => sps = Some(nal.to_vec()), |
| 157 | Some(8) if pps.is_none() => pps = Some(nal.to_vec()), |
| 158 | _ => {} |
| 159 | } |
| 160 | } |
| 161 | if sps.is_some() && pps.is_some() { |
| 162 | break; |
| 163 | } |
| 164 | } |
| 165 | let (sps, pps) = (sps?, pps?); |
| 166 | let mut avcc = vec![1, *sps.get(1)?, *sps.get(2)?, *sps.get(3)?, 0xFF, 0xE1]; |
| 167 | avcc.extend((sps.len() as u16).to_be_bytes()); |
| 168 | avcc.extend(&sps); |
| 169 | avcc.push(1); |
| 170 | avcc.extend((pps.len() as u16).to_be_bytes()); |
| 171 | avcc.extend(&pps); |
| 172 | Some(avcc) |
| 173 | } |
| 174 | |
| 175 | |
| 176 | fn refused_video_name(why: &str, tag: &[u8; 4]) -> String { |
| 177 | if why.contains("uncompressed") { |
| 178 | "rawvideo".into() |
| 179 | } else if why.starts_with("DV video") { |
| 180 | "dvvideo".into() |
| 181 | } else if why.starts_with("MPEG-4 Part 2") || why.starts_with("MS-MPEG4") { |
| 182 | match &tag.to_ascii_lowercase()[..] { |
| 183 | b"div3" | b"div4" | b"div5" | b"div6" | b"mp43" | b"mpg4" => "msmpeg4v3".into(), |
| 184 | b"div1" | b"mp41" => "msmpeg4v1".into(), |
| 185 | b"div2" | b"mp42" => "msmpeg4v2".into(), |
| 186 | _ => "mpeg4".into(), |
| 187 | } |
| 188 | } else { |
| 189 | String::from_utf8_lossy(tag).trim().to_ascii_lowercase() |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | impl AviSrc { |
| 194 | pub(crate) fn open(path: &Path) -> crate::Result<Self> { |
| 195 | let file = File::open(path)?; |
| 196 | let reader = BufReader::with_capacity(256 << 10, file); |
| 197 | let d = AviDemuxer::new(reader).map_err(avi_error)?; |
| 198 | let mut native = Vec::new(); |
| 199 | let mut d = d; |
| 200 | let streams: Vec<StreamInfo> = d |
| 201 | .streams() |
| 202 | .iter() |
| 203 | .map(|s| { |
| 204 | native.push(s.time_base); |
| 205 | let mut s = s.clone(); |
| 206 | let to = |t: i64| Timestamp::new(t, s.time_base).rescale(tb(), Rounding::Nearest).ticks; |
| 207 | s.start_time = s.start_time.map(to); |
| 208 | s.duration = s.duration.map(to); |
| 209 | s.time_base = tb(); |
| 210 | s |
| 211 | }) |
| 212 | .collect(); |
| 213 | let mut streams = streams; |
| 214 | for stream in &mut streams { |
| 215 | if let Some(extra) = codec_config(&mut d, stream) { |
| 216 | stream.params.extradata = Some(extra.into()); |
| 217 | } |
| 218 | } |
| 219 | d.rewind(); |
| 220 | let tracks = d |
| 221 | .tracks() |
| 222 | .into_iter() |
| 223 | .map(|t| { |
| 224 | let params = t.stream.and_then(|i| streams.iter().find(|s| s.index == i)); |
| 225 | |
| 226 | |
| 227 | let supported = |c: CodecId| { |
| 228 | matches!( |
| 229 | c, |
| 230 | CodecId::H264 |
| 231 | | CodecId::Mpeg2Video |
| 232 | | CodecId::Mjpeg |
| 233 | | CodecId::ProRes |
| 234 | | CodecId::Dnxhd |
| 235 | | CodecId::DvVideo |
| 236 | | CodecId::Mpeg4Part2 |
| 237 | | CodecId::MsMpeg4V2 |
| 238 | | CodecId::MsMpeg4V3 |
| 239 | | CodecId::RawVideo |
| 240 | ) |
| 241 | }; |
| 242 | let refused_picture = params |
| 243 | .map(|p| p.params.codec) |
| 244 | .filter(|c| c.media_type() == MediaType::Video && !supported(*c)); |
| 245 | let mut refusal = t.unsupported.clone(); |
| 246 | let mut stream = t.stream; |
| 247 | let kind = match (t.media, params.map(|p| p.params.codec)) { |
| 248 | _ if refused_picture.is_some() => { |
| 249 | let c = refused_picture.unwrap_or(CodecId::H264); |
| 250 | refusal = Some(format!("{} video: no decoder in this build", c.name())); |
| 251 | stream = None; |
| 252 | TsKind::Other(format!("{}:{}", super::ts::REFUSED_VIDEO, c.name())) |
| 253 | } |
| 254 | (_, Some(CodecId::H264)) => TsKind::H264, |
| 255 | (_, Some(CodecId::Mpeg2Video)) => TsKind::Mpeg2Video, |
| 256 | (_, Some(CodecId::Mjpeg)) => TsKind::Other("mjpeg".into()), |
| 257 | (_, Some(CodecId::ProRes)) => TsKind::Other("prores".into()), |
| 258 | (_, Some(CodecId::Dnxhd)) => TsKind::Other("dnxhd".into()), |
| 259 | (_, Some(CodecId::DvVideo)) => TsKind::Other("dvvideo".into()), |
| 260 | |
| 261 | (_, Some(CodecId::Mpeg4Part2)) => { |
| 262 | TsKind::Other(format!("mpeg4:{}", String::from_utf8_lossy(&t.tag.to_ascii_uppercase()))) |
| 263 | } |
| 264 | (_, Some(CodecId::MsMpeg4V2)) => TsKind::Other("msmpeg4v2".into()), |
| 265 | (_, Some(CodecId::MsMpeg4V3)) => TsKind::Other("msmpeg4v3".into()), |
| 266 | (_, Some(CodecId::RawVideo)) => TsKind::Other("rawvideo".into()), |
| 267 | (_, Some(CodecId::Aac)) => TsKind::AacAdts, |
| 268 | (_, Some(CodecId::Ac3)) => TsKind::Ac3, |
| 269 | (_, Some(CodecId::Mp2 | CodecId::Mp3)) => TsKind::MpegAudio, |
| 270 | (_, Some(CodecId::PcmU8)) => TsKind::Other("pcm_u8".into()), |
| 271 | (_, Some(CodecId::PcmS16Le)) => TsKind::Other("pcm_s16le".into()), |
| 272 | (_, Some(CodecId::PcmS24Le)) => TsKind::Other("pcm_s24le".into()), |
| 273 | (_, Some(CodecId::PcmS32Le)) => TsKind::Other("pcm_s32le".into()), |
| 274 | (_, Some(CodecId::PcmF32Le)) => TsKind::Other("pcm_f32le".into()), |
| 275 | (_, Some(CodecId::ImaAdpcmWav)) => TsKind::Other("adpcm_ima_wav".into()), |
| 276 | (_, Some(CodecId::MsAdpcm)) => TsKind::Other("adpcm_ms".into()), |
| 277 | (_, Some(CodecId::PcmAlaw)) => TsKind::Other("pcm_alaw".into()), |
| 278 | (_, Some(CodecId::PcmMulaw)) => TsKind::Other("pcm_mulaw".into()), |
| 279 | (_, Some(CodecId::Dts)) => TsKind::Dts, |
| 280 | (_, Some(_)) => TsKind::Other("data".into()), |
| 281 | (Some(MediaType::Video), None) => TsKind::Other(format!( |
| 282 | "{}:{}", |
| 283 | super::ts::REFUSED_VIDEO, |
| 284 | refused_video_name(t.unsupported.as_deref().unwrap_or_default(), &t.tag) |
| 285 | )), |
| 286 | (Some(MediaType::Audio), None) => TsKind::Other(refused_name(&t)), |
| 287 | _ => TsKind::Other("data".into()), |
| 288 | }; |
| 289 | TrackInfo { |
| 290 | pid: t.number as u16, |
| 291 | stream_type: 0, |
| 292 | kind, |
| 293 | stream, |
| 294 | refusal, |
| 295 | language: None, |
| 296 | } |
| 297 | }) |
| 298 | .collect(); |
| 299 | let mut tracks: Vec<TrackInfo> = tracks; |
| 300 | |
| 301 | |
| 302 | for s in &streams { |
| 303 | if s.params.codec == CodecId::PcmS16Le && !tracks.iter().any(|t| t.stream == Some(s.index)) { |
| 304 | tracks.push(TrackInfo { |
| 305 | pid: 0x100 + s.index as u16, |
| 306 | stream_type: 0, |
| 307 | kind: TsKind::Other("pcm_s16le".into()), |
| 308 | stream: Some(s.index), |
| 309 | refusal: None, |
| 310 | language: None, |
| 311 | }); |
| 312 | } |
| 313 | } |
| 314 | Ok(Self { |
| 315 | d, |
| 316 | streams, |
| 317 | native, |
| 318 | tracks, |
| 319 | }) |
| 320 | } |
| 321 | |
| 322 | pub(crate) fn streams(&self) -> &[StreamInfo] { |
| 323 | &self.streams |
| 324 | } |
| 325 | |
| 326 | pub(crate) fn tracks(&self) -> Vec<TrackInfo> { |
| 327 | self.tracks.clone() |
| 328 | } |
| 329 | |
| 330 | pub(crate) fn next_packet(&mut self) -> ec_core::Result<Packet> { |
| 331 | let mut p = self.d.next_packet()?; |
| 332 | let from = self.native.get(p.stream as usize).copied().unwrap_or(p.time_base); |
| 333 | let to = |t: i64| Timestamp::new(t, from).rescale(tb(), Rounding::Nearest).ticks; |
| 334 | p.pts = p.pts.map(to); |
| 335 | p.dts = p.dts.map(to); |
| 336 | p.duration = p.duration.map(to); |
| 337 | p.time_base = tb(); |
| 338 | Ok(p) |
| 339 | } |
| 340 | |
| 341 | pub(crate) fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> ec_core::Result<()> { |
| 342 | let at = to.rescale(self.native.get(stream as usize).copied().unwrap_or(to.base), Rounding::Nearest); |
| 343 | self.d.seek_stream(stream, at, mode).map(|_| ()) |
| 344 | } |
| 345 | |
| 346 | pub(crate) fn field_order(&self, stream: u32) -> Option<ec_core::frame::Interlace> { |
| 347 | self.d.field_order(stream) |
| 348 | } |
| 349 | |
| 350 | pub(crate) fn duration_secs(&self) -> Option<f64> { |
| 351 | self.streams |
| 352 | .iter() |
| 353 | .filter_map(|s| s.duration) |
| 354 | .max() |
| 355 | .map(|t| t as f64 / 90_000.0) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | |
| 360 | pub(crate) fn is_b_picture(codec: Codec, au: &[u8]) -> bool { |
| 361 | match codec { |
| 362 | Codec::Mpeg4 => mpeg4_is_b(au), |
| 363 | Codec::Mpeg2 => mpeg2_picture_type(au) == Some(3), |
| 364 | Codec::H264 => h264_is_b(au), |
| 365 | _ => false, |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | |
| 370 | |
| 371 | fn mpeg4_is_b(au: &[u8]) -> bool { |
| 372 | au.windows(5).find(|w| w[..4] == [0, 0, 1, 0xB6]).is_some_and(|w| w[4] >> 6 == 2) |
| 373 | } |
| 374 | |
| 375 | |
| 376 | fn mpeg2_picture_type(au: &[u8]) -> Option<u8> { |
| 377 | let at = au.windows(4).position(|w| w == [0, 0, 1, 0x00])?; |
| 378 | Some(au.get(at + 5)? >> 3 & 7) |
| 379 | } |
| 380 | |
| 381 | |
| 382 | fn h264_is_b(au: &[u8]) -> bool { |
| 383 | for nal in ec_mpegts::nal_units(au) { |
| 384 | let Some(&head) = nal.first() else { continue }; |
| 385 | if !matches!(head & 0x1f, 1 | 5) { |
| 386 | continue; |
| 387 | } |
| 388 | let mut rbsp = Vec::new(); |
| 389 | unescape_rbsp(&nal[1..nal.len().min(16)], &mut rbsp); |
| 390 | let mut bits = Bits { data: &rbsp, at: 0 }; |
| 391 | let _first_mb = bits.ue(); |
| 392 | return matches!(bits.ue(), Some(1 | 6)); |
| 393 | } |
| 394 | false |
| 395 | } |
| 396 | |
| 397 | struct Bits<'a> { |
| 398 | data: &'a [u8], |
| 399 | at: usize, |
| 400 | } |
| 401 | |
| 402 | impl Bits<'_> { |
| 403 | fn bit(&mut self) -> Option<u32> { |
| 404 | let byte = *self.data.get(self.at / 8)?; |
| 405 | let b = (byte >> (7 - self.at % 8)) & 1; |
| 406 | self.at += 1; |
| 407 | Some(u32::from(b)) |
| 408 | } |
| 409 | |
| 410 | fn ue(&mut self) -> Option<u32> { |
| 411 | let mut zeros = 0; |
| 412 | while self.bit()? == 0 { |
| 413 | zeros += 1; |
| 414 | if zeros > 31 { |
| 415 | return None; |
| 416 | } |
| 417 | } |
| 418 | let mut v = 0u32; |
| 419 | for _ in 0..zeros { |
| 420 | v = v << 1 | self.bit()?; |
| 421 | } |
| 422 | Some((1u32 << zeros) - 1 + v) |
| 423 | } |
| 424 | } |