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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use crate::{
    progress_event::ProgressEventLineBuilder,
    Error,
    Event,
};
use futures::future::FutureExt;
use once_cell::sync::Lazy;
use regex::Regex;
use std::{
    ffi::OsString,
    process::Stdio,
};
use tokio::io::{
    AsyncBufReadExt,
    BufReader,
};
use tokio_stream::{
    wrappers::LinesStream,
    Stream,
    StreamExt,
};
use tracing::trace;

/// Example: "File 'test.mp4' already exists. Exiting."
static FILE_EXISTS_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new("File '.*' already exists\\. Exiting\\.")
        .expect("failed to compile FILE_EXISTS_REGEX")
});

/// A builder for an ffmpeg command
#[derive(Debug, Clone)]
pub struct Builder {
    /// The audio codec
    pub audio_codec: Option<String>,

    /// The video codec
    pub video_codec: Option<String>,

    /// The video bitrate
    pub video_bitrate: Option<String>,

    /// The input
    pub input: Option<OsString>,

    /// The output
    pub output: Option<OsString>,

    /// The input format
    pub input_format: Option<String>,

    /// The output format
    pub output_format: Option<String>,

    /// The pass # for two pass
    pub pass: Option<u8>,

    /// The # of video frames to read from the input
    pub video_frames: Option<u64>,

    /// The video profile
    pub video_profile: Option<String>,

    /// The preset
    pub preset: Option<String>,

    /// Whether to overwrite the destination
    pub overwrite: bool,
}

impl Builder {
    /// Make a new [`Builder`]
    pub fn new() -> Self {
        Self {
            audio_codec: None,
            video_codec: None,

            video_bitrate: None,

            input: None,
            output: None,

            input_format: None,
            output_format: None,

            pass: None,

            video_frames: None,

            video_profile: None,

            preset: None,

            overwrite: false,
        }
    }

    /// Set the audio codec
    pub fn audio_codec(&mut self, audio_codec: impl Into<String>) -> &mut Self {
        self.audio_codec = Some(audio_codec.into());
        self
    }

    /// Set the video codec
    pub fn video_codec(&mut self, video_codec: impl Into<String>) -> &mut Self {
        self.video_codec = Some(video_codec.into());
        self
    }

    /// Set the video bitrate
    pub fn video_bitrate(&mut self, video_bitrate: impl Into<String>) -> &mut Self {
        self.video_bitrate = Some(video_bitrate.into());
        self
    }

    /// Set the input
    pub fn input(&mut self, input: impl Into<OsString>) -> &mut Self {
        self.input = Some(input.into());
        self
    }

    /// Set the output
    pub fn output(&mut self, output: impl Into<OsString>) -> &mut Self {
        self.output = Some(output.into());
        self
    }

    /// Set the input format
    pub fn input_format(&mut self, input_format: impl Into<String>) -> &mut Self {
        self.input_format = Some(input_format.into());
        self
    }

    /// Set the output format
    pub fn output_format(&mut self, output_format: impl Into<String>) -> &mut Self {
        self.output_format = Some(output_format.into());
        self
    }

    /// The pass # for 2 pass
    pub fn pass(&mut self, pass: u8) -> &mut Self {
        self.pass = Some(pass);
        self
    }

    /// The # of video frames to accept from the input
    pub fn video_frames(&mut self, video_frames: impl Into<u64>) -> &mut Self {
        self.video_frames = Some(video_frames.into());
        self
    }

    /// The profile of the video
    pub fn video_profile(&mut self, video_profile: impl Into<String>) -> &mut Self {
        self.video_profile = Some(video_profile.into());
        self
    }

    /// The preset
    pub fn preset(&mut self, preset: impl Into<String>) -> &mut Self {
        self.preset = Some(preset.into());
        self
    }

    /// Set whether the output should be overwritten
    pub fn overwrite(&mut self, overwrite: bool) -> &mut Self {
        self.overwrite = overwrite;
        self
    }

    /// Build the command
    fn build_command(&mut self) -> Result<tokio::process::Command, Error> {
        // https://superuser.com/questions/1459810/how-can-i-get-ffmpeg-command-running-status-in-real-time
        // https://stackoverflow.com/questions/43978018/ffmpeg-get-machine-readable-output
        // https://ffmpeg.org/ffmpeg.html

        let audio_codec = self.audio_codec.take();

        let video_codec = self.video_codec.take();
        let video_bitrate = self.video_bitrate.take();

        let input = self.input.take();
        let output = self.output.take();

        let input_format = self.input_format.take();
        let output_format = self.output_format.take();

        let pass = self.pass.take();

        let video_frames = self.video_frames.take();

        let video_profile = self.video_profile.take();

        let preset = self.preset.take();

        let overwrite = std::mem::take(&mut self.overwrite);

        let mut command = tokio::process::Command::new("ffmpeg");
        command.arg("-hide_banner");
        command.arg("-nostdin");

        if let Some(input_format) = input_format.as_deref() {
            command.args(["-f", input_format]);
        }

        let input = input.ok_or(Error::MissingInput)?;
        command.args(["-i".as_ref(), input.as_os_str()]);

        if let Some(video_frames) = video_frames {
            // TODO: Consider adding itoa
            command.args(["-frames:v", &video_frames.to_string()]);
        }

        if let Some(audio_codec) = audio_codec.as_deref() {
            command.args(["-codec:a", audio_codec]);
        }

        if let Some(video_codec) = video_codec.as_deref() {
            command.args(["-codec:v", video_codec]);
        }

        if let Some(video_bitrate) = video_bitrate.as_deref() {
            command.args(["-b:v", video_bitrate]);
        }

        if let Some(video_profile) = video_profile.as_deref() {
            command.args(["-profile:v", video_profile]);
        }

        if let Some(preset) = preset.as_deref() {
            command.args(["-preset", preset]);
        }

        if let Some(pass) = pass {
            command.args(["-pass", &pass.to_string()]);
        }

        command.args(["-progress", "-"]);
        command.arg(if overwrite { "-y" } else { "-n" });

        if let Some(output_format) = output_format.as_deref() {
            command.args(["-f", output_format]);
        }

        let output = output.ok_or(Error::MissingOutput)?;
        command.arg(output.as_os_str());

        Ok(command)
    }

    /// Run the command and wait for it to finish.
    ///
    /// This will not provide progress info or stdout/stdin, but is far simpler to drive.
    pub async fn ffmpeg_status(&mut self) -> Result<std::process::ExitStatus, Error> {
        self.build_command()?.status().await.map_err(Error::Io)
    }

    /// Run the command and wait for it to finish.
    ///
    /// This will not provide progress info, but is far simpler to drive.
    pub async fn ffmpeg_output(&mut self) -> Result<std::process::Output, Error> {
        self.build_command()?.output().await.map_err(Error::Io)
    }

    /// Spawn the stream
    pub fn spawn(&mut self) -> Result<impl Stream<Item = Result<Event, Error>> + Unpin, Error> {
        let mut command = self.build_command()?;
        command
            .kill_on_drop(true)
            .stdout(Stdio::piped())
            .stdin(Stdio::null())
            .stderr(Stdio::piped());

        trace!("built ffmpeg command for spawning: {:?}", command);

        let mut child = command.spawn().map_err(Error::ProcessSpawn)?;

        // Stdout Setup
        let stdout = child.stdout.take().expect("missing stdout");
        let stdout_buf_reader = BufReader::new(stdout);
        let stdout_stream = LinesStream::new(stdout_buf_reader.lines());

        // Stderr Setup
        let stderr = child.stderr.take().expect("missing stderr");
        let stderr_buf_reader = BufReader::new(stderr);
        let stderr_stream = LinesStream::new(stderr_buf_reader.lines());

        // Make child produce exit event
        let exit_status_stream = Box::pin(async move { child.wait().await })
            .into_stream()
            .map(|maybe_exit_status| maybe_exit_status.map(Event::ExitStatus).map_err(Error::Io));

        // Process Stdout
        let mut builder = ProgressEventLineBuilder::new();
        let stdout_event_stream = stdout_stream.filter_map(move |maybe_line| {
            let maybe_event = maybe_line
                .map(|line| {
                    builder
                        .push(&line)
                        .transpose()
                        .map(|e| e.map(Event::Progress).map_err(From::from))
                })
                .transpose()?;

            Some(maybe_event.unwrap_or_else(|e| Err(Error::Io(e))))
        });

        // Process Stderr
        let stderr_event_stream = stderr_stream.map(|maybe_line| {
            let line = maybe_line.map_err(Error::Io)?;

            if FILE_EXISTS_REGEX.is_match(&line) {
                Err(Error::OutputAlreadyExists)
            } else {
                Ok(Event::Unknown(line))
            }
        });

        Ok(stdout_event_stream
            .merge(stderr_event_stream)
            .chain(exit_status_stream))
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}