simple-ffmpeg-edits 0.1.0

Simple ffmpeg wrapper for trimming, cropping, merging videos and photos
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
* TODO:
    - turn picture into a video (append prepend logo)
        - force aspect ratio, fit within
    - merge two videos together (append prepend logo)
    - trim video from either start end
    - convert images
*/

mod probe;
#[cfg(test)]
mod test;

use std::{
    io::{BufRead, BufReader},
    os::unix::{fs::MetadataExt, process::CommandExt},
    path::PathBuf,
    process::{Command, Stdio},
    str::Utf8Error,
};
use tracing::{debug, error, trace};

use crate::probe::{AspectRatio, Resolution};

pub struct PhotoOutputFormat {
    pub codec: PhotoCodec,
    pub quality: u8,
    pub default_video_duration: u32,
}

pub struct VideoOutputFormat {
    pub video_codec: VideoCodec,
    pub audio_codec: AudioCodec,
    pub video_kbitrate: u16,
    pub audio_kbitrate: u8,
}

#[derive(Default)]
pub enum VideoCodec {
    #[default]
    AV1,
}

#[derive(Default)]
pub enum AudioCodec {
    #[default]
    OPUS,
}

#[derive(Default)]
pub enum PhotoCodec {
    #[default]
    WEBP,
}

impl std::fmt::Display for AudioCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "libopus")
    }
}

impl std::fmt::Display for VideoCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "libsvtav1")
    }
}

impl PhotoCodec {
    pub fn to_container_str(&self) -> &str {
        match &self {
            Self::WEBP => "webp",
        }
    }
}

impl VideoCodec {
    pub fn to_container_str(&self) -> &str {
        match &self {
            Self::AV1 => "mp4",
        }
    }
}

#[derive(Default)]
pub struct Encoder {
    pub video_format: VideoOutputFormat,
    pub photo_format: PhotoOutputFormat,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("File not supported or does not exist, {0}")]
    WrongPath(String),
    #[error("Spawning ffmpeg and listening to stdin returned error, is ffmpeg installed? {0}")]
    Sys(String),
    #[error("Listening to process lines threw error, wha..? {0}")]
    IO(#[from] std::io::Error),
    #[error("Something went wrong during conversion of file, {0}")]
    Ffmpeg(String),
    #[error("Something went wrong during probing metadata of file, {0}")]
    Ffprobe(String),
    #[error("String conversion error, {0}")]
    Utf8(#[from] Utf8Error),
}

pub struct EncoderCommandBuffer {
    pub input_file_path: PathBuf,
    pub output_file_path: PathBuf,
    pub pass1_logfile: PathBuf,
    pub vcodec_str: String,
    pub acodec_str: String,
    pub vcodec_rate_str: String,
    pub acodec_rate_str: String,
    pub commands: Vec<Command>,
}

impl Encoder {
    pub fn new(
        video_format: Option<VideoOutputFormat>,
        photo_format: Option<PhotoOutputFormat>,
    ) -> Self {
        Self {
            video_format: video_format.unwrap_or(VideoOutputFormat::default()),
            photo_format: photo_format.unwrap_or(PhotoOutputFormat::default()),
        }
    }

    fn create_common_command_args<'a>(
        &self,
        com_buffer: &'a mut EncoderCommandBuffer,
        mut prepend_args: Option<Vec<String>>,
        mut append_args: Option<Vec<String>>,
    ) -> Result<Vec<String>, Error> {
        let mut common_args: Vec<String> =
            vec!["-progress", "-", "-nostats", "-stats_period", "50ms", "-y"]
                .into_iter()
                .map(|s| s.to_owned())
                .collect();

        if let Some(prepend) = prepend_args.as_mut() {
            common_args.append(prepend)
        }

        common_args.append(
            &mut vec![
                "-i",
                com_buffer.input_file_path.to_str().ok_or(Error::WrongPath(
                    "filepath to string returned none, UNICODE shenanigans?".to_owned(),
                ))?,
                "-vcodec",
                &com_buffer.vcodec_str,
                "-acodec",
                &com_buffer.acodec_str,
                "-cpu-used",
                "0",
                "-threads",
                "16",
                "-b:v",
                &com_buffer.vcodec_rate_str,
                "-b:a",
                &com_buffer.acodec_rate_str,
                "-passlogfile",
                &com_buffer
                    .pass1_logfile
                    .as_os_str()
                    .to_str()
                    .ok_or(Error::WrongPath(
                        "filepath to string returned none, UNICODE shenanigans?".to_owned(),
                    ))?,
            ]
            .into_iter()
            .map(|s| s.to_owned())
            .collect(),
        );

        common_args.append(&mut match self.video_format.video_codec {
            VideoCodec::AV1 => vec!["-preset", "8", "-svtav1-params", "rc=1:scd=1"]
                .into_iter()
                .map(|s| s.to_owned())
                .collect(),
        });

        if let Some(append) = append_args.as_mut() {
            common_args.append(append)
        }

        Ok(common_args)
    }

    fn create_base_command_buffers<'a>(
        &self,
        input_file_path: PathBuf,
        prepend_args: Option<Vec<&'a str>>,
        append_args: Option<Vec<&'a str>>,
    ) -> Result<EncoderCommandBuffer, Error> {
        match input_file_path.try_exists() {
            Ok(exists) => {
                if !exists {
                    return Err(Error::WrongPath(
                        "File doesn't exist according to PathBuf.try_exists(), aiaiai".to_string(),
                    ));
                }
            }
            Err(e) => return Err(e.into()),
        }

        let mut output_file_path = input_file_path.clone();

        let mut pass1 = Command::new("ffmpeg");
        let mut pass2 = Command::new("ffmpeg");

        let mut pass1_logfile = input_file_path.clone();

        pass1_logfile.set_extension("");

        output_file_path.set_extension(self.video_format.video_codec.to_container_str());

        output_file_path.set_file_name(
            "encoded_".to_owned() + output_file_path.file_name().unwrap().to_str().unwrap(),
        );

        let mut args_pass1 = vec![];
        let mut args_pass2 = vec![];

        let vcodec_str = self.video_format.video_codec.to_string();
        let acodec_str = self.video_format.audio_codec.to_string();
        let vcodec_rate_str = format!("{}k", self.video_format.video_kbitrate);
        let acodec_rate_str = format!("{}k", self.video_format.audio_kbitrate);

        let mut com_buf = EncoderCommandBuffer {
            input_file_path,
            output_file_path,
            pass1_logfile,
            vcodec_str,
            acodec_str,
            vcodec_rate_str,
            acodec_rate_str,
            commands: vec![],
        };

        let prepend_args = prepend_args.map(|v| v.into_iter().map(|s| s.to_owned()).collect());
        let append_args = append_args.map(|v| v.into_iter().map(|s| s.to_owned()).collect());
        let mut common_args =
            self.create_common_command_args(&mut com_buf, prepend_args, append_args)?;

        args_pass1.append(common_args.clone().as_mut());
        args_pass2.append(&mut common_args);

        args_pass1.append(
            &mut vec![
                "-pass",
                "1",
                "-f",
                self.video_format.video_codec.to_container_str(),
            ]
            .into_iter()
            .map(|s| s.to_owned())
            .collect(),
        );

        if cfg!(windows) {
            args_pass1.push("NUL".to_owned());
        } else {
            args_pass1.push("/dev/null".to_owned());
        }

        args_pass2.append(
            &mut vec![
                "-pass",
                "2",
                com_buf
                    .output_file_path
                    .as_os_str()
                    .to_str()
                    .ok_or(Error::WrongPath(
                        "filepath to string returned none, UNICODE shenanigans?".to_owned(),
                    ))?,
            ]
            .into_iter()
            .map(|s| s.to_owned())
            .collect(),
        );

        debug!(
            "ffmpeg {} \n&& ffmpeg {}",
            args_pass1
                .clone()
                .iter()
                .fold("".to_owned(), |a, b| format!("{} \\\n{}", a, b)),
            args_pass2
                .clone()
                .iter()
                .fold("".to_owned(), |a, b| format!("{} \\\n{}", a, b))
        );

        pass1.args(args_pass1);
        pass2.args(args_pass2);

        com_buf.commands = vec![pass1, pass2];
        Ok(com_buf)
    }

    fn run_command_buffer(&self, command: &mut Command) -> Result<(), Error> {
        command.stdout(Stdio::piped());
        command.stderr(Stdio::piped());
        command.stdin(Stdio::null());

        let mut command_handle = command.spawn();

        let buff_reader = BufReader::new(command_handle.as_mut().unwrap().stdout.take().ok_or(
            Error::Sys("encoder stdout missing - exited early or unavailable".to_owned()),
        )?);

        for maybe_line in buff_reader.lines() {
            match maybe_line {
                Ok(line) => {
                    trace!(line);
                    if line.contains("end") {
                        trace!("LINE CONTAINED END!");
                        break;
                    }
                }
                Err(e) => return Err(e.into()),
            }
        }
        Ok(())
    }

    fn is_run_sucessful(&self, output_file_path: &mut PathBuf) -> Result<(), Error> {
        match output_file_path.try_exists() {
            Ok(exists) => {
                if !exists {
                    return Err(Error::WrongPath(
                        "File doesn't exist according to PathBuf.try_exists(), aiaiai".to_string(),
                    ));
                }
                if output_file_path.metadata()?.size() < 1_000 {
                    return Err(Error::Ffmpeg(
                        "File is smaller than 1kb, prolly invalid encode?".to_owned(),
                    ));
                }
            }
            Err(e) => return Err(e.into()),
        }
        Ok(())
    }

    pub fn reencode(&self, file_path: PathBuf) -> Result<PathBuf, Error> {
        let mut com_buffers = self.create_base_command_buffers(file_path, None, None)?;
        for com_buffer in com_buffers.commands.iter_mut() {
            self.run_command_buffer(com_buffer)?;
        }

        self.is_run_sucessful(&mut com_buffers.output_file_path)?;
        Ok(com_buffers.output_file_path)
    }

    pub fn picture_to_video(
        &self,
        file_path: PathBuf,
        duration: Option<u32>,
        force_resolution: Option<Resolution>,
    ) -> Result<PathBuf, Error> {
        let duration = duration
            .unwrap_or(self.photo_format.default_video_duration)
            .to_string();

        let mut append_args = vec![];
        let mut prepend_args = vec![];
        let aspect_filter = force_resolution.map(|a| {
            format!(
                "scale={}:{}:force_original_aspect_ratio=decrease,pad={}:{}:(ow-iw)/2:(oh-ih)/2",
                a.0, a.1, a.0, a.1
            )
        });

        if let Some(aspect) = aspect_filter.as_ref() {
            append_args.append(&mut vec!["-vf", &aspect])
        }
        prepend_args.append(&mut vec!["-t", &duration]);

        let mut com_buffers =
            self.create_base_command_buffers(file_path, Some(prepend_args), Some(append_args))?;
        for com_buffer in com_buffers.commands.iter_mut() {
            self.run_command_buffer(com_buffer)?;
        }

        self.is_run_sucessful(&mut com_buffers.output_file_path)?;
        Ok(com_buffers.output_file_path)
    }

    pub fn trim_video(
        &self,
        file_path: PathBuf,
        start_time: Option<u32>,
        end_time: Option<u32>,
        duration: Option<f32>,
    ) -> Result<PathBuf, Error> {
        unimplemented!();
        /*
                let mut append_args = vec![];
                if let Some(ms) = start_time {
                    let ts = ms_to_tsm(ms);
                    let from_time = time_format::strftime_ms_local("%H:%M:%S.{ms}", ts)?;
                    append_args.append(&mut vec!["-ss".to_owned(), from_time])
                }
                if let Some(ms) = end_time
                    && let Some(duration) = duration
                {
                    let ts = ms_to_tsm(duration as u32 - ms);
                    let to_time = time_format::strftime_ms_local("%H:%M:%S.{ms}", ts)?;
                    append_args.append(&mut vec!["-to".to_owned(), to_time])
                }
                // let mut append_args = start_time.map(|e|);

                let append_args_b = append_args.iter().map(|s| s.as_str()).collect::<Vec<_>>();

                let mut com_buffers =
                    self.create_base_command_buffers(file_path, None, Some(append_args_b))?;
                for com_buffer in com_buffers.commands.iter_mut() {
                    self.run_command_buffer(com_buffer)?;
                }

                self.is_run_sucessful(&mut com_buffers.output_file_path)?;
                Ok(com_buffers.output_file_path)
        */
    }

    pub fn surround_video(
        &self,
        file_path: PathBuf,
        append_file_path: PathBuf,
        prepend_file_path: PathBuf,
    ) -> Result<PathBuf, Error> {
        unimplemented!();
    }
}

impl Default for VideoOutputFormat {
    fn default() -> Self {
        Self {
            video_kbitrate: 1000,
            audio_kbitrate: 128,
            video_codec: VideoCodec::default(),
            audio_codec: AudioCodec::default(),
        }
    }
}

impl Default for PhotoOutputFormat {
    fn default() -> Self {
        Self {
            quality: 80,
            codec: PhotoCodec::default(),
            default_video_duration: 5,
        }
    }
}

fn ms_to_str(ms: u32) -> String {
    let mut s = ms / 1000;
    let mut ms = ms - s * 1000;
    let mut m = s / 60;

    // let ts = TimeStampMs::new(s as i64, m as u16);
    // debug!("sec:{}, ms:{}", ts.seconds, ts.milliseconds);
    unimplemented!()
}