Skip to main content

vector_core/
video_poster.rs

1//! A web video's opening, enough for a webview to show its first frame, fetched as byte
2//! ranges rather than the whole file.
3//!
4//! WebM starts with its first frames. MP4 and MOV need their index (`moov`) too, which a
5//! camera often writes after the data: then it is fetched from where it sits and moved to
6//! the front, its chunk offsets shifted by its own length, as `qt-faststart` does. What
7//! comes back is a short file that plays its first frames and stops.
8
9use std::time::Duration;
10
11/// The first request: an index at the front and a first frame usually fit in it.
12const HEAD_BYTES: u64 = 512 * 1024;
13/// WebM's first cluster holds its keyframe; this covers it for anything chat-sized.
14const WEBM_BYTES: u64 = 2 * 1024 * 1024;
15/// Past this a first frame isn't worth the bytes; the video keeps its tap to play.
16const MAX_PREFIX_BYTES: u64 = 8 * 1024 * 1024;
17const MAX_MOOV_BYTES: u64 = 4 * 1024 * 1024;
18/// After the first sample: the few frames a seek to the opening decodes.
19const FRAME_MARGIN: u64 = 256 * 1024;
20/// Boxes walked past the data looking for the index.
21const MAX_BOX_HOPS: usize = 8;
22
23pub struct Poster {
24    pub bytes: Vec<u8>,
25    pub ext: &'static str,
26}
27
28/// The opening of the video at `url`, through the transport and the privacy proxy like
29/// any other media. An error means no frame is shown, never a broken one.
30pub async fn fetch(url: &str) -> Result<Poster, String> {
31    crate::net::validate_url_not_private(url).map_err(str::to_string)?;
32    poster_from(&Web(url)).await
33}
34
35/// Where the bytes come from: the web, or a file in a test.
36trait Source {
37    /// Bytes `start..end`, and the file's size when known. A source that can't seek may
38    /// answer only from the top, so `start` must be 0 then.
39    async fn range(&self, start: u64, end: u64) -> Result<Fetched, String>;
40}
41
42async fn poster_from(src: &impl Source) -> Result<Poster, String> {
43    let head = src.range(0, HEAD_BYTES).await?;
44    let total = head.total;
45    let mut bytes = head.bytes;
46    if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {
47        if (bytes.len() as u64) < WEBM_BYTES && total.is_none_or(|t| bytes.len() as u64 != t) {
48            extend(src, &mut bytes, WEBM_BYTES, total).await?;
49        }
50        return Ok(Poster { bytes, ext: "webm" });
51    }
52    if bytes.len() < 12 || &bytes[4..8] != b"ftyp" {
53        return Err("Not a video".into());
54    }
55    let ext = if &bytes[8..12] == b"qt  " { "mov" } else { "mp4" };
56    if total.is_some_and(|t| bytes.len() as u64 >= t) {
57        return Ok(Poster { bytes, ext });
58    }
59
60    let layout = top_level(&bytes);
61    let mdat_box = layout.iter().find(|b| &b.kind == b"mdat").ok_or("No video data")?;
62    let (mdat, mdat_end) = (mdat_box.offset, mdat_box.size.map(|s| mdat_box.offset + s));
63    let (moov_offset, moov) = match layout.iter().find(|b| &b.kind == b"moov") {
64        Some(b) => {
65            let size = b.size.ok_or("No video index")?;
66            if size > MAX_MOOV_BYTES {
67                return Err("Video index too large".into());
68            }
69            if b.offset + size > bytes.len() as u64 {
70                extend(src, &mut bytes, b.offset + size, total).await?;
71            }
72            (b.offset, bytes[b.offset as usize..(b.offset + size) as usize].to_vec())
73        }
74        None => find_moov(src, &layout, total).await?,
75    };
76
77    let first = first_video_sample(&moov).ok_or("No video track")?;
78    let need = first.0.checked_add(first.1).ok_or("Bad video index")?;
79    if need > MAX_PREFIX_BYTES {
80        return Err("The first frame is too far in".into());
81    }
82    let want = total.map_or(need + FRAME_MARGIN, |t| t.min(need + FRAME_MARGIN));
83    if (bytes.len() as u64) < want {
84        extend(src, &mut bytes, want, total).await?;
85    }
86    if (bytes.len() as u64) < need {
87        return Err("The first frame didn't arrive".into());
88    }
89    bytes.truncate(want.min(bytes.len() as u64) as usize);
90
91    if moov_offset < mdat {
92        return Ok(Poster { bytes, ext });
93    }
94    // The index's old place, when the prefix reaches it, goes: one index per file.
95    if let Some(end) = mdat_end {
96        bytes.truncate(end.min(bytes.len() as u64) as usize);
97    }
98    Ok(Poster { bytes: faststart(&bytes, mdat, moov)?, ext })
99}
100
101/// The index moved in front of the data, every chunk offset in it shifted by its length.
102fn faststart(prefix: &[u8], mdat: u64, mut moov: Vec<u8>) -> Result<Vec<u8>, String> {
103    let shift = moov.len() as u64;
104    shift_chunk_offsets(&mut moov, shift)?;
105    let split = mdat as usize;
106    if split > prefix.len() {
107        return Err("No video data".into());
108    }
109    let mut out = Vec::with_capacity(prefix.len() + moov.len());
110    out.extend_from_slice(&prefix[..split]);
111    out.extend_from_slice(&moov);
112    out.extend_from_slice(&prefix[split..]);
113    Ok(out)
114}
115
116struct Fetched {
117    bytes: Vec<u8>,
118    total: Option<u64>,
119}
120
121struct Web<'a>(&'a str);
122
123impl Source for Web<'_> {
124    /// A server that ignores the range is read from the top and cut off.
125    async fn range(&self, start: u64, end: u64) -> Result<Fetched, String> {
126        range(self.0, start, end).await
127    }
128}
129
130async fn range(url: &str, start: u64, end: u64) -> Result<Fetched, String> {
131    use futures_util::StreamExt;
132    let timeout = crate::transport::budget(crate::transport::Op::HttpTotal, Duration::from_secs(20));
133    let client = crate::net::build_http_client(timeout)?;
134    let resp = crate::net::proxied_request(&client, reqwest::Method::GET, url)
135        .await
136        .header(reqwest::header::RANGE, format!("bytes={start}-{}", end - 1))
137        .send()
138        .await
139        .map_err(|e| e.to_string())?;
140    let status = resp.status();
141    let ranged = status == reqwest::StatusCode::PARTIAL_CONTENT;
142    if !ranged && !(status.is_success() && start == 0) {
143        return Err(format!("The video host answered {status}"));
144    }
145    let total = if ranged {
146        resp.headers()
147            .get(reqwest::header::CONTENT_RANGE)
148            .and_then(|v| v.to_str().ok())
149            .and_then(|v| v.rsplit('/').next())
150            .and_then(|t| t.parse().ok())
151    } else {
152        resp.content_length()
153    };
154    let want = (end - start) as usize;
155    let mut bytes = Vec::with_capacity(want.min(1024 * 1024));
156    let mut body = resp.bytes_stream();
157    while let Some(chunk) = body.next().await {
158        bytes.extend_from_slice(&chunk.map_err(|e| e.to_string())?);
159        if bytes.len() >= want {
160            bytes.truncate(want);
161            break;
162        }
163    }
164    Ok(Fetched { bytes, total })
165}
166
167/// Grow `bytes` (the file from its start) to `end`, or to the file's end.
168async fn extend(src: &impl Source, bytes: &mut Vec<u8>, end: u64, total: Option<u64>) -> Result<(), String> {
169    let end = total.map_or(end, |t| t.min(end));
170    let have = bytes.len() as u64;
171    if have >= end {
172        return Ok(());
173    }
174    if end > MAX_PREFIX_BYTES + MAX_MOOV_BYTES {
175        return Err("Too far into the video".into());
176    }
177    let more = src.range(have, end).await?;
178    bytes.extend_from_slice(&more.bytes);
179    Ok(())
180}
181
182/// The index when it comes after the data: box headers read one hop at a time from the
183/// end of the last box the head showed.
184async fn find_moov(src: &impl Source, layout: &[BoxAt], total: Option<u64>) -> Result<(u64, Vec<u8>), String> {
185    let last = layout.last().ok_or("No video index")?;
186    let mut at = last.offset.checked_add(last.size.ok_or("No video index")?).ok_or("Bad video")?;
187    for _ in 0..MAX_BOX_HOPS {
188        if total.is_some_and(|t| at + 8 > t) {
189            break;
190        }
191        let head = src.range(at, at + 16).await?.bytes;
192        let b = parse_header(&head, at).ok_or("No video index")?;
193        let size = b.size.ok_or("No video index")?;
194        if &b.kind == b"moov" {
195            if size > MAX_MOOV_BYTES {
196                return Err("Video index too large".into());
197            }
198            let moov = src.range(at, at + size).await?.bytes;
199            if moov.len() as u64 != size {
200                return Err("The video index didn't arrive".into());
201            }
202            return Ok((at, moov));
203        }
204        at = at.checked_add(size).ok_or("Bad video")?;
205    }
206    Err("No video index".into())
207}
208
209struct BoxAt {
210    offset: u64,
211    header: u64,
212    /// None when the box runs to the end of the file.
213    size: Option<u64>,
214    kind: [u8; 4],
215}
216
217fn parse_header(buf: &[u8], offset: u64) -> Option<BoxAt> {
218    let size32 = u32::from_be_bytes(buf.get(0..4)?.try_into().ok()?) as u64;
219    let kind: [u8; 4] = buf.get(4..8)?.try_into().ok()?;
220    let (header, size) = match size32 {
221        0 => (8, None),
222        1 => (16, Some(u64::from_be_bytes(buf.get(8..16)?.try_into().ok()?))),
223        n => (8, Some(n)),
224    };
225    if size.is_some_and(|s| s < header) {
226        return None;
227    }
228    Some(BoxAt { offset, header, size, kind })
229}
230
231/// The top-level boxes whose headers are in `buf`, the file's start.
232fn top_level(buf: &[u8]) -> Vec<BoxAt> {
233    let mut out = Vec::new();
234    let mut at = 0u64;
235    while let Some(b) = buf.get(at as usize..).and_then(|rest| parse_header(rest, at)) {
236        let next = b.size.and_then(|s| at.checked_add(s));
237        out.push(b);
238        match next {
239            Some(n) => at = n,
240            None => break,
241        }
242        if out.len() > 64 {
243            break;
244        }
245    }
246    out
247}
248
249/// The children of the container whose payload is `buf[start..end]`, as (payload start, end, kind).
250fn children(buf: &[u8], start: usize, end: usize) -> Vec<(usize, usize, [u8; 4])> {
251    let mut out = Vec::new();
252    let mut at = start;
253    while at + 8 <= end {
254        let Some(b) = parse_header(&buf[at..end], at as u64) else { break };
255        let size = b.size.map_or(end - at, |s| s as usize);
256        if size < b.header as usize || at + size > end {
257            break;
258        }
259        out.push((at + b.header as usize, at + size, b.kind));
260        at += size;
261    }
262    out
263}
264
265fn child(buf: &[u8], start: usize, end: usize, kind: &[u8; 4]) -> Option<(usize, usize)> {
266    children(buf, start, end).into_iter().find(|c| &c.2 == kind).map(|c| (c.0, c.1))
267}
268
269fn be32(buf: &[u8], at: usize) -> Option<u64> {
270    Some(u32::from_be_bytes(buf.get(at..at + 4)?.try_into().ok()?) as u64)
271}
272
273fn be64(buf: &[u8], at: usize) -> Option<u64> {
274    Some(u64::from_be_bytes(buf.get(at..at + 8)?.try_into().ok()?))
275}
276
277/// Each track's sample table, as (payload start, end) in `moov`.
278fn sample_tables(moov: &[u8]) -> Vec<(usize, usize, bool)> {
279    let Some(root) = parse_header(moov, 0) else { return Vec::new() };
280    let mut out = Vec::new();
281    for (ts, te, kind) in children(moov, root.header as usize, moov.len()) {
282        if &kind != b"trak" {
283            continue;
284        }
285        let Some((ms, me)) = child(moov, ts, te, b"mdia") else { continue };
286        // hdlr: version and flags, pre_defined, then the handler type.
287        let video = child(moov, ms, me, b"hdlr").and_then(|(hs, _)| moov.get(hs + 8..hs + 12)) == Some(b"vide");
288        let Some((ns, ne)) = child(moov, ms, me, b"minf") else { continue };
289        let Some((ss, se)) = child(moov, ns, ne, b"stbl") else { continue };
290        out.push((ss, se, video));
291    }
292    out
293}
294
295/// Where the first video sample starts in the original file, and its size.
296fn first_video_sample(moov: &[u8]) -> Option<(u64, u64)> {
297    let (ss, se, _) = sample_tables(moov).into_iter().find(|t| t.2)?;
298    let offset = if let Some((cs, _)) = child(moov, ss, se, b"stco") {
299        (be32(moov, cs + 4)? > 0).then_some(())?;
300        be32(moov, cs + 8)?
301    } else {
302        let (cs, _) = child(moov, ss, se, b"co64")?;
303        (be32(moov, cs + 4)? > 0).then_some(())?;
304        be64(moov, cs + 8)?
305    };
306    let (zs, _) = child(moov, ss, se, b"stsz")?;
307    let uniform = be32(moov, zs + 4)?;
308    let size = if uniform > 0 { uniform } else { be32(moov, zs + 12)? };
309    Some((offset, size))
310}
311
312/// Every chunk offset in every track, moved `shift` bytes later.
313fn shift_chunk_offsets(moov: &mut [u8], shift: u64) -> Result<(), String> {
314    for (ss, se, _) in sample_tables(moov) {
315        for (cs, ce, kind) in children(moov, ss, se) {
316            let wide = match &kind {
317                b"stco" => false,
318                b"co64" => true,
319                _ => continue,
320            };
321            let count = be32(moov, cs + 4).ok_or("Bad video index")? as usize;
322            let width = if wide { 8 } else { 4 };
323            if cs + 8 + count * width > ce {
324                return Err("Bad video index".into());
325            }
326            for i in 0..count {
327                let at = cs + 8 + i * width;
328                if wide {
329                    let v = be64(moov, at).unwrap() + shift;
330                    moov[at..at + 8].copy_from_slice(&v.to_be_bytes());
331                } else {
332                    let v = u32::try_from(be32(moov, at).unwrap() + shift).map_err(|_| "Video too large to move")?;
333                    moov[at..at + 4].copy_from_slice(&v.to_be_bytes());
334                }
335            }
336        }
337    }
338    Ok(())
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
346        let mut b = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
347        b.extend_from_slice(kind);
348        b.extend_from_slice(payload);
349        b
350    }
351
352    fn full(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
353        let mut p = vec![0, 0, 0, 0];
354        p.extend_from_slice(body);
355        boxed(kind, &p)
356    }
357
358    /// A moov with one track of `handler`, its chunk offsets and a uniform sample size.
359    fn moov(tracks: &[(&[u8; 4], Vec<u32>, u32)]) -> Vec<u8> {
360        let mut traks = Vec::new();
361        for (handler, offsets, size) in tracks {
362            let mut stco = (offsets.len() as u32).to_be_bytes().to_vec();
363            for o in offsets {
364                stco.extend_from_slice(&o.to_be_bytes());
365            }
366            let mut stsz = size.to_be_bytes().to_vec();
367            stsz.extend_from_slice(&1u32.to_be_bytes());
368            let stbl = boxed(b"stbl", &[full(b"stsz", &stsz), full(b"stco", &stco)].concat());
369            let mut hdlr = vec![0, 0, 0, 0];
370            hdlr.extend_from_slice(*handler);
371            hdlr.extend_from_slice(&[0; 12]);
372            let mdia = boxed(b"mdia", &[full(b"hdlr", &hdlr), boxed(b"minf", &stbl)].concat());
373            traks.extend(boxed(b"trak", &mdia));
374        }
375        boxed(b"moov", &traks)
376    }
377
378    #[test]
379    fn the_first_video_sample_is_found_past_an_audio_track() {
380        let m = moov(&[(b"soun", vec![40], 10), (b"vide", vec![100, 900], 300)]);
381        assert_eq!(first_video_sample(&m), Some((100, 300)));
382        assert_eq!(first_video_sample(&moov(&[(b"soun", vec![40], 10)])), None);
383    }
384
385    #[test]
386    fn moving_the_index_forward_shifts_every_chunk_offset_by_its_length() {
387        let ftyp = boxed(b"ftyp", b"isom\0\0\0\0");
388        let data_at = ftyp.len() as u32 + 8;
389        let mdat = boxed(b"mdat", &[7u8; 64]);
390        let m = moov(&[(b"vide", vec![data_at, data_at + 32], 16), (b"soun", vec![data_at + 16], 8)]);
391        let file = [ftyp.clone(), mdat.clone(), m.clone()].concat();
392        let out = faststart(&file[..ftyp.len() + mdat.len()], ftyp.len() as u64, m.clone()).unwrap();
393        let layout = top_level(&out);
394        let kinds: Vec<_> = layout.iter().map(|b| b.kind).collect();
395        assert_eq!(kinds, vec![*b"ftyp", *b"moov", *b"mdat"]);
396        let moved = &out[layout[1].offset as usize..layout[2].offset as usize];
397        let (offset, size) = first_video_sample(moved).unwrap();
398        assert_eq!((offset, size), (data_at as u64 + m.len() as u64, 16));
399        // The sample the moved index points at is the same bytes it pointed at before.
400        assert_eq!(&out[offset as usize..(offset + size) as usize], &file[data_at as usize..(data_at + 16) as usize]);
401    }
402
403    struct File(Vec<u8>, std::cell::Cell<u64>);
404
405    impl Source for File {
406        async fn range(&self, start: u64, end: u64) -> Result<Fetched, String> {
407            let end = end.min(self.0.len() as u64);
408            self.1.set(self.1.get() + end.saturating_sub(start));
409            Ok(Fetched { bytes: self.0.get(start as usize..end as usize).unwrap_or_default().to_vec(), total: Some(self.0.len() as u64) })
410        }
411    }
412
413    /// A real video's poster: `VIDEO_POSTER_IN=a.mp4 VIDEO_POSTER_OUT=b.mp4 cargo test … -- --ignored`.
414    #[tokio::test]
415    #[ignore]
416    async fn a_poster_from_a_local_file() {
417        let input = std::fs::read(std::env::var("VIDEO_POSTER_IN").unwrap()).unwrap();
418        let file = File(input, std::cell::Cell::new(0));
419        let poster = poster_from(&file).await.unwrap();
420        println!("read {} of {} bytes, wrote {} ({})", file.1.get(), file.0.len(), poster.bytes.len(), poster.ext);
421        std::fs::write(std::env::var("VIDEO_POSTER_OUT").unwrap(), poster.bytes).unwrap();
422    }
423
424    #[test]
425    fn a_box_that_claims_less_than_its_header_ends_the_walk() {
426        let mut buf = boxed(b"ftyp", b"isom\0\0\0\0");
427        buf.extend_from_slice(&[0, 0, 0, 4, b'm', b'd', b'a', b't']);
428        assert_eq!(top_level(&buf).len(), 1);
429        assert!(parse_header(&[0, 0, 0, 1, b'm', b'd', b'a', b't', 0, 0, 0, 0, 0, 0, 0, 9], 0).is_none());
430    }
431}