Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/running.rs

7.0 KiB, 1 run

created by r2953280680:79565, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! How long a sound or a film runs, read from its header: nothing is decoded.
2//!
3//! A caller that is about to hand a file to something billed by the minute, a transcriber above all,
4//! wants the length before it sends a byte. Each format states it in its own place: WAV by the
5//! `fmt ` byte rate and the `data` length, FLAC by its STREAMINFO sample count, Ogg by the granule
6//! position of its last page over the rate its first page names (Vorbis, or 48 kHz for Opus), MP3 by
7//! the frame count of a Xing, Info or VBRI frame or else by its constant bit rate, the MP4 family
8//! (MP4, M4A, MOV) by `mvhd`, and Matroska (WebM) and AVI by their own readers. A file of another
9//! format, or whose header states no length, is `None`, never a guess; a header cut short is an error.
10
11use crate::{
12 avi::Avi,
13 matroska::Matroska,
14};
15
16use oxedyne_fe2o3_core::prelude::*;
17
18
19/// The running time of a whole file, in milliseconds, where its header states it.
20pub fn millis(b: &[u8]) -> Outcome<Option<u64>> {
21 let at = |i: usize, n: usize| b.get(i..i + n);
22 match (at(0, 4), at(4, 4), at(8, 4)) {
23 (Some(b"RIFF"), _, Some(b"WAVE")) => wav(b),
24 (Some(b"RIFF"), _, Some(b"AVI ")) => Ok(res!(Avi::read(b)).millis()),
25 (Some(b"fLaC"), _, _) => flac(b),
26 (Some(b"OggS"), _, _) => ogg(b),
27 (Some([0x1A, 0x45, 0xDF, 0xA3]), _, _) => Ok(res!(Matroska::read(b)).millis()),
28 (_, Some(b"ftyp"), _) => mvhd(b, 0, b.len()),
29 _ => mp3(b),
30 }
31}
32
33fn get(b: &[u8], i: usize, n: usize) -> Outcome<&[u8]> {
34 b.get(i..i + n).ok_or_else(|| err!("The header ends before byte {} of the {} it needs.", i + n, b.len(); Invalid, Input, Missing))
35}
36fn u16le(b: &[u8], i: usize) -> Outcome<u64> { let x = res!(get(b, i, 2)); Ok(u16::from_le_bytes([x[0], x[1]]) as u64) }
37fn u32le(b: &[u8], i: usize) -> Outcome<u64> { let x = res!(get(b, i, 4)); Ok(u32::from_le_bytes([x[0], x[1], x[2], x[3]]) as u64) }
38fn u32be(b: &[u8], i: usize) -> Outcome<u64> { let x = res!(get(b, i, 4)); Ok(u32::from_be_bytes([x[0], x[1], x[2], x[3]]) as u64) }
39fn u64le(b: &[u8], i: usize) -> Outcome<u64> {
40 let x = res!(get(b, i, 8));
41 Ok(u64::from_le_bytes([x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]]))
42}
43fn u64be(b: &[u8], i: usize) -> Outcome<u64> {
44 let x = res!(get(b, i, 8));
45 Ok(u64::from_be_bytes([x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]]))
46}
47
48// `n` units at `rate` a second, in milliseconds, or none at a rate of nought.
49fn ms(n: u64, rate: u64) -> Option<u64> {
50 match rate {
51 0 => None,
52 r => Some((n as u128 * 1000 / r as u128) as u64),
53 }
54}
55
56// The chunks after `RIFF`, its length and `WAVE`, each padded to an even length. A `data` length of
57// 0xFFFFFFFF, as a recorder writes while it streams, or one past the file's end, is the bytes there are.
58fn wav(b: &[u8]) -> Outcome<Option<u64>> {
59 let (mut i, mut rate) = (12usize, None);
60 while i + 8 <= b.len() {
61 let n = res!(u32le(b, i + 4));
62 match &b[i..i + 4] {
63 b"fmt " => rate = Some(res!(u32le(b, i + 16))),
64 b"data" => return Ok(rate.and_then(|r| ms(n.min((b.len() - i - 8) as u64), r))),
65 _ => {},
66 }
67 i += 8 + n as usize + (n & 1) as usize;
68 }
69 Ok(None)
70}
71
72// STREAMINFO is the first metadata block: 20 bits of sample rate, 3 of channels, 5 of sample size
73// and 36 of total samples, from its tenth byte. A count of nought is a length the encoder did not know.
74fn flac(b: &[u8]) -> Outcome<Option<u64>> {
75 if res!(get(b, 4, 1))[0] & 0x7F != 0 {
76 return Ok(None);
77 }
78 let x = res!(u64be(b, 18));
79 Ok(match x & 0xF_FFFF_FFFF {
80 0 => None,
81 n => ms(n, x >> 44),
82 })
83}
84
85// The first page's packet names the codec and its rate; the last page's granule position is the
86// samples to its end (RFC 3533 §6, RFC 7845 §4 for Opus, less its pre-skip).
87fn ogg(b: &[u8]) -> Outcome<Option<u64>> {
88 let p = 27 + res!(get(b, 26, 1))[0] as usize;
89 let (rate, skip) = match res!(get(b, p, 8)) {
90 [1, b'v', b'o', b'r', b'b', b'i', b's', _] => (res!(u32le(b, p + 12)), 0),
91 b"OpusHead" => (48_000, res!(u16le(b, p + 10))), // fixed: Opus granules count at 48 kHz
92 _ => return Ok(None),
93 };
94 let last = b.windows(4).rposition(|w| w == b"OggS").unwrap_or(0);
95 let g = res!(u64le(b, last + 6)) as i64;
96 Ok(ms((g.max(0) as u64).saturating_sub(skip), rate))
97}
98
99// The `mvhd` within the `moov` among the boxes of [from, to): a timescale and a duration, of 32 bits
100// in version 0 and of 64 in version 1 (ISO/IEC 14496-12 §8.2.2).
101fn mvhd(b: &[u8], from: usize, to: usize) -> Outcome<Option<u64>> {
102 let mut i = from;
103 while i + 8 <= to {
104 let (n, head) = match res!(u32be(b, i)) {
105 1 => (res!(u64be(b, i + 8)) as usize, 16),
106 0 => (to - i, 8),
107 n => (n as usize, 8),
108 };
109 if n < head || i + n > to {
110 return Err(err!("The box at byte {} runs {} bytes, past its parent's end at {}.", i, n, to; Invalid, Input));
111 }
112 match &b[i + 4..i + 8] {
113 b"moov" => return mvhd(b, i + head, i + n),
114 b"mvhd" => {
115 let v = i + head;
116 return Ok(match res!(get(b, v, 1))[0] {
117 0 => ms(res!(u32be(b, v + 16)), res!(u32be(b, v + 12))),
118 _ => ms(res!(u64be(b, v + 24)), res!(u32be(b, v + 20))),
119 });
120 },
121 _ => i += n,
122 }
123 }
124 Ok(None)
125}
126
127// MPEG audio Layer III: past an ID3v2 tag, the first frame's header gives the version, the bit rate
128// and the sample rate (ISO/IEC 11172-3 §2.4.2.3); a Xing or Info frame where its side information
129// ends, or a VBRI frame 32 bytes on, counts the frames, each of 1152 samples (576 below MPEG-1).
130// Without one the rate is constant and the length is the frames' bytes over it, less an ID3v1 tag.
131fn mp3(b: &[u8]) -> Outcome<Option<u64>> {
132 const KBPS: [[u64; 15]; 2] = [ // fixed: the standard's tables, MPEG-1 then MPEG-2 and 2.5
133 [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
134 [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
135 ];
136 const HZ: [u64; 3] = [44_100, 48_000, 32_000]; // fixed: MPEG-1's, halved for MPEG-2, quartered for 2.5
137 let o = match b.get(0..3) {
138 Some(b"ID3") => {
139 let s = res!(get(b, 6, 4)).iter().fold(0usize, |a, x| (a << 7) | (*x & 0x7F) as usize);
140 10 + s + if res!(get(b, 5, 1))[0] & 0x10 != 0 { 10 } else { 0 }
141 },
142 _ => 0,
143 };
144 let h = match b.get(o..o + 4) {
145 Some(h) => h,
146 None => return Ok(None),
147 };
148 let (ver, layer, br, sr) = ((h[1] >> 3) & 3, (h[1] >> 1) & 3, (h[2] >> 4) as usize, ((h[2] >> 2) & 3) as usize);
149 if h[0] != 0xFF || h[1] & 0xE0 != 0xE0 || ver == 1 || layer != 1 || br == 0 || br == 15 || sr == 3 {
150 return Ok(None);
151 }
152 let one = ver == 3;
153 let rate = HZ[sr] >> match ver { 3 => 0, 2 => 1, _ => 2 };
154 let spf = if one { 1152 } else { 576 };
155 let side = match (one, h[3] >> 6 == 3) { (true, false) => 32, (true, true) | (false, false) => 17, (false, true) => 9 };
156 let x = o + 4 + side;
157 Ok(match (b.get(x..x + 4), b.get(o + 36..o + 40)) {
158 (Some(b"Xing"), _) | (Some(b"Info"), _) if res!(u32be(b, x + 4)) & 1 != 0 => ms(res!(u32be(b, x + 8)) * spf, rate),
159 (_, Some(b"VBRI")) => ms(res!(u32be(b, o + 50)) * spf, rate),
160 _ => {
161 let tag = if b.len() >= 128 && &b[b.len() - 128..b.len() - 125] == b"TAG" { 128 } else { 0 };
162 ms(((b.len() - o - tag) as u64) * 8, KBPS[!one as usize][br] * 1000)
163 },
164 })
165}