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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use std::num::ParseIntError;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::{error, ImageBuf, Rgb};

#[derive(Debug)]
pub enum Error {
    FileDoesNotExist,
    InvalidImageShape,
    InvalidFrameCount,
}

pub struct Ffmpeg {
    path: PathBuf,
    width: usize,
    height: usize,
    args: Vec<String>,
    pub(crate) frames: usize,
    pub(crate) index: usize,
}

impl Ffmpeg {
    fn get_shape(path: &PathBuf) -> Result<(usize, usize), error::Error> {
        let ffprobe_size = Command::new("ffprobe")
            .args(&[
                "-v",
                "error",
                "-select_streams",
                "v:0",
                "-show_entries",
                "stream=width,height",
                "-of",
                "csv=s=x:p=0",
            ])
            .arg(path)
            .output()?;

        let shape = match String::from_utf8(ffprobe_size.stdout) {
            Ok(shape) => shape,
            Err(_) => return Err(error::Error::FFmpeg(Error::InvalidImageShape)),
        };

        let t = shape
            .split('x')
            .map(|a| a.trim().parse::<usize>())
            .collect::<Vec<Result<usize, ParseIntError>>>();

        if t.len() < 2 {
            return Err(error::Error::FFmpeg(Error::InvalidImageShape));
        }

        let x = match (&t[0], &t[1]) {
            (Ok(w), Ok(h)) => (w.clone(), h.clone()),
            (_, _) => return Err(error::Error::FFmpeg(Error::InvalidImageShape)),
        };

        Ok(x)
    }

    fn get_frames(path: &PathBuf) -> Result<usize, error::Error> {
        let ffprobe_num_frames = Command::new("ffprobe")
            .args(&[
                "-v",
                "error",
                "-hide_banner",
                "-count_frames",
                "-select_streams",
                "v:0",
                "-show_entries",
                "stream=nb_frames",
                "-of",
                "default=nokey=1:noprint_wrappers=1",
            ])
            .arg(&path)
            .output()?;

        let frames = match String::from_utf8(ffprobe_num_frames.stdout) {
            Ok(f) => f,
            Err(_) => return Err(error::Error::FFmpeg(Error::InvalidFrameCount)),
        };

        let frames = match frames.trim().parse::<usize>() {
            Ok(n) => n,
            Err(_) => return Err(error::Error::FFmpeg(Error::InvalidFrameCount)),
        };

        Ok(frames)
    }

    pub fn open<P: AsRef<Path>>(path: P) -> Result<Ffmpeg, error::Error> {
        let path = path.as_ref().to_path_buf();
        if !path.exists() {
            return Err(error::Error::FFmpeg(Error::FileDoesNotExist));
        }

        let (width, height) = Self::get_shape(&path)?;
        let frames = Self::get_frames(&path)?;
        let args = Vec::new();

        Ok(Ffmpeg {
            path,
            width,
            height,
            frames,
            index: 0,
            args,
        })
    }

    pub fn arg<S: AsRef<str>>(&mut self, arg: S) {
        self.args.push(String::from(arg.as_ref()))
    }

    pub fn reset(&mut self) {
        self.index = 0;
    }

    pub fn skip(&mut self, n: usize) {
        self.index += n;
    }

    pub fn rewind(&mut self, n: usize) {
        if n < self.index {
            self.index = 0;
        } else {
            self.index -= 1;
        }
    }

    pub fn next(&mut self) -> Option<ImageBuf<u8, Rgb>> {
        if self.index >= self.frames {
            return None;
        }

        let cmd = Command::new("ffmpeg")
            .args(&["-v", "error", "-hide_banner", "-i"])
            .arg(&self.path)
            .arg("-vf")
            .arg(format!("select=gte(n\\,{})", self.index))
            .args(&[
                "-vframes", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "-an", "-",
            ])
            .args(&self.args)
            .output();

        let cmd = match cmd {
            Ok(x) => x,
            _ => return None,
        };

        self.index += 1;

        Some(ImageBuf::new_from(self.width, self.height, cmd.stdout))
    }

    pub fn next_n(&mut self, n: usize) -> Vec<ImageBuf<u8, Rgb>> {
        let mut v = Vec::new();

        for _ in 0..n {
            match self.next() {
                Some(x) => v.push(x),
                None => break,
            }
        }

        v
    }
}