forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

avi.rs424 lines, 17.6 KiBHistoryRawDownload
1//! AVI -- `.avi`, `.divx` -- over the family's own [`ec_riff::AviDemuxer`], read by the very
2//! readers a transport stream is ([`super::ts`]): [`ts::TsDemuxer`](super::ts::TsDemuxer) for
3//! the picture, [`ts::TsAudio`](super::ts::TsAudio) for each sound track.
4//!
5//! [`AviSrc`] is the adapter: it presents the AVI as the 90 kHz packet stream the readers
6//! expect (every stream's `dwScale/dwRate` time base rescaled to ticks, a seek rescaled
7//! back), and its tracks as the [`ec_mpegts::TrackInfo`] list `ts::describe_open` walks.
8//! Source time 0 is frame 0 (an AVI stream starts at 0).
9//!
10//! **Picture.** MJPEG, H.264 (Annex B), MPEG-2, ProRes, DNxHD, DV (type-2, where the sound is its
11//! own stream, and type-1 `iavs`, where `ec-riff` splits the sound out of the frames), MPEG-4
12//! Part 2 (XviD, DivX 4-6, FMP4...), MS-MPEG4 version 2 and 3 (`MP42`, `DIV3`...) and raw video
13//! (`BI_RGB` 24 and 32 bit, YUY2, UYVY, I420, YV12). Refused by name with the ffmpeg line that
14//! converts the file: MS-MPEG4 version 1 (`MPG4`, `DIV1`), other raw layouts (8, 15 and 16 bit
15//! DIB, palettised, NV12, V210, YVYU...) and any other FourCC. A file whose picture is refused
16//! but whose sound is usable still opens as sound (the audio door ignores the refused picture stream and names
17//! nothing); asking for its picture fails with the refusal.
18//!
19//! **Sound.** PCM (8/16/24/32 bit integer, 32 bit float), MPEG layer II/III, AC-3 and AAC
20//! (raw, with its `AudioSpecificConfig`). Any other `wFormatTag` is refused by name.
21//!
22//! **B-frames.** An AVI carries no timestamps: the packets are in decode order and the
23//! demuxer's pts is the decode slot. The decoders release pictures in display order by
24//! themselves, so a sequential decode is right; what a slot cannot say is the display index
25//! of a keyframe that has pictures displayed before it *after* it in the file (an open-GOP
26//! `I` followed by its leading `B`s). [`is_b_picture`] recognises those in the bitstream
27//! (the run of B pictures right behind the keyframe), and the picture reader adds them to
28//! the slot. Limit: a keyframe flagged by the index that is not the start of a GOP in this
29//! sense and has no B pictures behind it is taken at its slot; and a dropped frame (a
30//! zero-size video chunk) keeps its slot but yields no picture, so a file with those drifts
31//! by that many frames after them.
32//!
33//! **Time.** 90 kHz ticks rounded from the stream's own rate: a sample count of a 96 kHz or
34//! faster PCM stream may come back one sample off (a tick is 1.07 samples there).
35
36use std::io::BufReader;
37
38use ec_core::registry::SeekMode;
39use ec_core::timebase::{Rounding, TimeBase, Timestamp};
40use ec_core::{CodecId, MediaType, Packet, StreamInfo};
41use ec_mpegts::{StreamKind as TsKind, TrackInfo};
42use ec_riff::{AviDemuxer, AviTrackInfo};
43
44use super::*;
45
46type Reader = BufReader<File>;
47
48/// The ticks a second is cut into, as [`super::ts`] counts.
49fn tb() -> TimeBase {
50 TimeBase::new(1, 90_000)
51}
52
53pub(crate) fn avi_error(e: ec_core::Error) -> crate::Error {
54 match &e {
55 // A refusal is a named gap with a way out; a damaged file is not.
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/// Whether `path` is an AVI file: its first twelve bytes, or -- for a name that says so and
66/// bytes that say nothing else -- its extension (`.avi`, `.divx`). A container whose magic
67/// is Matroska's or an mp4's is never one.
68pub 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 // A name that says AVI over a file that is plainly something else (a transport stream, a
78 // WAV) is not one; over bytes that say nothing, the open reports what is wrong.
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/// An AVI as the packet stream [`super::ts::Src`] speaks.
86pub(crate) struct AviSrc {
87 d: AviDemuxer<Reader>,
88 /// The streams in 90 kHz ticks.
89 streams: Vec<StreamInfo>,
90 /// Each stream's own time base, by stream index.
91 native: Vec<TimeBase>,
92 tracks: Vec<TrackInfo>,
93}
94
95fn 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/// What an AVI does not state, read off the first pictures: for H.264 the `avcC` record of its
116/// first SPS and PPS, for MPEG-2 the sequence header with its extension. `None` where the
117/// stream is neither or shows nothing in its first packets.
118fn 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 // The strf tail, where a muxer that keeps the sets out of band (ffmpeg, from an mp4)
126 // puts them: Annex B, or an `avcC` record already.
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/// ffprobe's name for a picture stream the demuxer refused, from its reason and FourCC.
176fn 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
193impl 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 // A picture codec this build has no decode seat for (ec-riff reads more than the
226 // engine routes) is refused by name here.
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 // The FourCC rides in the kind: it picks the decoder's encoder workarounds.
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 // The sound a type-1 DV stream carries inside its frames: streams the file never
301 // declared as tracks of their own, which `ec-riff` splits out of each frame chunk.
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/// Whether a packet of `codec` holds a B picture.
360pub(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/// Whether the first VOP of an MPEG-4 Part 2 packet is a B-VOP (`vop_coding_type` 2). A packed
370/// packet (a P-VOP with its B-VOP behind it) reads as the P it leads with.
371fn 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/// `picture_coding_type` of the first picture header in an MPEG-1/2 packet.
376fn 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/// Whether the first slice of an Annex-B H.264 packet is a B slice (`slice_type` 1 or 6).
382fn 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
397struct Bits<'a> {
398 data: &'a [u8],
399 at: usize,
400}
401
402impl 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}