Skip to main content

VideoReader

Struct VideoReader 

Source
pub struct VideoReader {
    pub mov: MovVideo,
    /* private fields */
}
Available on crate feature decode only.
Expand description

A video file opened for reading as ffmpeg -i <file> -f rawvideo -pix_fmt rgb24 - would: same frames, same order, same pixels.

Fields§

§mov: MovVideo

The track’s timing as ffmpeg computes it.

Implementations§

Source§

impl VideoReader

Source

pub fn open(data: Vec<u8>) -> Result<Self, String>

Err for anything outside the supported subset (codec, rotation, fragmented files, multiple sample descriptions or edits).

Examples found in repository?
examples/media_banner.rs (line 13)
6fn main() {
7    let a: Vec<String> = std::env::args().collect();
8    if a.len() < 2 {
9        eprintln!("usage: media_banner FILE");
10        std::process::exit(2);
11    }
12    let data = std::fs::read(&a[1]).expect("read");
13    match threers_codec::ffcompat::reader::VideoReader::open(data) {
14        Ok(r) => {
15            let m = &r.mov;
16            println!(
17                "fps {} tbr {}/{} duration {:.2} start_us {} frames {}",
18                m.banner_fps,
19                m.r_frame_rate.0,
20                m.r_frame_rate.1,
21                m.banner_duration,
22                m.start_us,
23                m.pts.len()
24            );
25        }
26        Err(e) => println!("ERROR {e}"),
27    }
28}
More examples
Hide additional examples
examples/video_rgb_pipe.rs (line 16)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    if a.len() < 3 {
13        eprintln!("usage: video_rgb_pipe IN OUT.rgb");
14        std::process::exit(2);
15    }
16    let r = threers_codec::ffcompat::reader::VideoReader::open(std::fs::read(&a[1]).expect("read"))
17        .unwrap_or_else(|e| {
18            println!("ERROR {e}");
19            std::process::exit(2)
20        });
21    let frames = r.pipe(None);
22    let wanted: BTreeSet<usize> = frames.iter().copied().collect();
23    let mut got = std::collections::BTreeMap::new();
24    if let Err(e) = r.decode_rgb(&wanted, |i, rgb| {
25        got.insert(i, rgb.to_vec());
26        Ok(())
27    }) {
28        println!("ERROR {e}");
29        std::process::exit(2)
30    }
31    let out: Vec<u8> = frames.iter().flat_map(|i| got[i].clone()).collect();
32    let (w, h) = r.size();
33    if a.get(2).map(String::as_str) == Some("--compare") {
34        let reference = std::fs::read(&a[3]).expect("reference");
35        let n = out.len().min(reference.len());
36        let diff = (0..n).filter(|&i| out[i] != reference[i]).count();
37        let maxd = (0..n)
38            .map(|i| (out[i] as i32 - reference[i] as i32).abs())
39            .max()
40            .unwrap_or(0);
41        let first = (0..n).find(|&i| out[i] != reference[i]).map(|i| {
42            (
43                i / (w as usize * h as usize * 3),
44                (i / 3) % w as usize,
45                (i / 3 / w as usize) % h as usize,
46                i % 3,
47            )
48        });
49        println!("{w}x{h} frames ours {} ref {}: {diff} bytes differ (max {maxd}), first (frame, x, y, c) {first:?}", out.len() / (w as usize * h as usize * 3), reference.len() / (w as usize * h as usize * 3));
50    } else {
51        std::fs::write(&a[2], out).expect("write");
52    }
53}
Source

pub fn size(&self) -> (u32, u32)

Size of the piped pictures (after autorotation).

Examples found in repository?
examples/video_rgb_pipe.rs (line 32)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    if a.len() < 3 {
13        eprintln!("usage: video_rgb_pipe IN OUT.rgb");
14        std::process::exit(2);
15    }
16    let r = threers_codec::ffcompat::reader::VideoReader::open(std::fs::read(&a[1]).expect("read"))
17        .unwrap_or_else(|e| {
18            println!("ERROR {e}");
19            std::process::exit(2)
20        });
21    let frames = r.pipe(None);
22    let wanted: BTreeSet<usize> = frames.iter().copied().collect();
23    let mut got = std::collections::BTreeMap::new();
24    if let Err(e) = r.decode_rgb(&wanted, |i, rgb| {
25        got.insert(i, rgb.to_vec());
26        Ok(())
27    }) {
28        println!("ERROR {e}");
29        std::process::exit(2)
30    }
31    let out: Vec<u8> = frames.iter().flat_map(|i| got[i].clone()).collect();
32    let (w, h) = r.size();
33    if a.get(2).map(String::as_str) == Some("--compare") {
34        let reference = std::fs::read(&a[3]).expect("reference");
35        let n = out.len().min(reference.len());
36        let diff = (0..n).filter(|&i| out[i] != reference[i]).count();
37        let maxd = (0..n)
38            .map(|i| (out[i] as i32 - reference[i] as i32).abs())
39            .max()
40            .unwrap_or(0);
41        let first = (0..n).find(|&i| out[i] != reference[i]).map(|i| {
42            (
43                i / (w as usize * h as usize * 3),
44                (i / 3) % w as usize,
45                (i / 3 / w as usize) % h as usize,
46                i % 3,
47            )
48        });
49        println!("{w}x{h} frames ours {} ref {}: {diff} bytes differ (max {maxd}), first (frame, x, y, c) {first:?}", out.len() / (w as usize * h as usize * 3), reference.len() / (w as usize * h as usize * 3));
50    } else {
51        std::fs::write(&a[2], out).expect("write");
52    }
53}
Source

pub fn seeks_for(&self, wanted: &BTreeSet<usize>) -> bool

Indices (into MovVideo::pts) of the frames the CLI writes for -ss A -i f -ss B, (A, B) in microseconds. Where decoding can start for the samples in need (decode index -> frame): one sync sample before the last sync sample at or before the first needed one. The extra GOP covers open-GOP leading pictures (a B-frame shown before its I-frame references the previous GOP); with fewer sync samples than that, the stream start. Without this every call decodes from the start of the stream, which makes extracting a long video chunk by chunk quadratic. Whether decode_rgb of wanted starts after the stream start (diagnostics / tests).

Source

pub fn pipe(&self, seek: Option<(i64, i64)>) -> Vec<usize>

Which frames the CLI writes to its pipe, as indices into mov.pts, for input and output seeks -ss A -i f -ss B given as (A, B) in microseconds.

Examples found in repository?
examples/video_rgb_pipe.rs (line 21)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    if a.len() < 3 {
13        eprintln!("usage: video_rgb_pipe IN OUT.rgb");
14        std::process::exit(2);
15    }
16    let r = threers_codec::ffcompat::reader::VideoReader::open(std::fs::read(&a[1]).expect("read"))
17        .unwrap_or_else(|e| {
18            println!("ERROR {e}");
19            std::process::exit(2)
20        });
21    let frames = r.pipe(None);
22    let wanted: BTreeSet<usize> = frames.iter().copied().collect();
23    let mut got = std::collections::BTreeMap::new();
24    if let Err(e) = r.decode_rgb(&wanted, |i, rgb| {
25        got.insert(i, rgb.to_vec());
26        Ok(())
27    }) {
28        println!("ERROR {e}");
29        std::process::exit(2)
30    }
31    let out: Vec<u8> = frames.iter().flat_map(|i| got[i].clone()).collect();
32    let (w, h) = r.size();
33    if a.get(2).map(String::as_str) == Some("--compare") {
34        let reference = std::fs::read(&a[3]).expect("reference");
35        let n = out.len().min(reference.len());
36        let diff = (0..n).filter(|&i| out[i] != reference[i]).count();
37        let maxd = (0..n)
38            .map(|i| (out[i] as i32 - reference[i] as i32).abs())
39            .max()
40            .unwrap_or(0);
41        let first = (0..n).find(|&i| out[i] != reference[i]).map(|i| {
42            (
43                i / (w as usize * h as usize * 3),
44                (i / 3) % w as usize,
45                (i / 3 / w as usize) % h as usize,
46                i % 3,
47            )
48        });
49        println!("{w}x{h} frames ours {} ref {}: {diff} bytes differ (max {maxd}), first (frame, x, y, c) {first:?}", out.len() / (w as usize * h as usize * 3), reference.len() / (w as usize * h as usize * 3));
50    } else {
51        std::fs::write(&a[2], out).expect("write");
52    }
53}
Source

pub fn decode_rgb( &self, wanted: &BTreeSet<usize>, f: impl FnMut(usize, &[u8]) -> Result<(), String>, ) -> Result<(), String>

Decode once, calling f(index, rgb24) for each wanted frame index (presentation order, ascending).

Examples found in repository?
examples/video_rgb_pipe.rs (lines 24-27)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    if a.len() < 3 {
13        eprintln!("usage: video_rgb_pipe IN OUT.rgb");
14        std::process::exit(2);
15    }
16    let r = threers_codec::ffcompat::reader::VideoReader::open(std::fs::read(&a[1]).expect("read"))
17        .unwrap_or_else(|e| {
18            println!("ERROR {e}");
19            std::process::exit(2)
20        });
21    let frames = r.pipe(None);
22    let wanted: BTreeSet<usize> = frames.iter().copied().collect();
23    let mut got = std::collections::BTreeMap::new();
24    if let Err(e) = r.decode_rgb(&wanted, |i, rgb| {
25        got.insert(i, rgb.to_vec());
26        Ok(())
27    }) {
28        println!("ERROR {e}");
29        std::process::exit(2)
30    }
31    let out: Vec<u8> = frames.iter().flat_map(|i| got[i].clone()).collect();
32    let (w, h) = r.size();
33    if a.get(2).map(String::as_str) == Some("--compare") {
34        let reference = std::fs::read(&a[3]).expect("reference");
35        let n = out.len().min(reference.len());
36        let diff = (0..n).filter(|&i| out[i] != reference[i]).count();
37        let maxd = (0..n)
38            .map(|i| (out[i] as i32 - reference[i] as i32).abs())
39            .max()
40            .unwrap_or(0);
41        let first = (0..n).find(|&i| out[i] != reference[i]).map(|i| {
42            (
43                i / (w as usize * h as usize * 3),
44                (i / 3) % w as usize,
45                (i / 3 / w as usize) % h as usize,
46                i % 3,
47            )
48        });
49        println!("{w}x{h} frames ours {} ref {}: {diff} bytes differ (max {maxd}), first (frame, x, y, c) {first:?}", out.len() / (w as usize * h as usize * 3), reference.len() / (w as usize * h as usize * 3));
50    } else {
51        std::fs::write(&a[2], out).expect("write");
52    }
53}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.