vidmerger 0.4.4

A wrapper around FFmpeg which simplifies merging multiple videos and adds chapters from the file names
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
use crate::cli::Cli;
use clap::ArgMatches;
use crossterm::{
  event::{read, Event, KeyCode, KeyModifiers},
  terminal::{disable_raw_mode, enable_raw_mode},
};
use lazy_static::lazy_static;
use nanoid::nanoid;
use std::cmp::Ordering;
use std::env::temp_dir;
use std::fs::{self, canonicalize, File};
use std::io::{self, Result, Write};
use std::iter::Peekable;
use std::path::{Path, PathBuf};
use std::process;
use std::process::exit;
use std::str::Chars;

lazy_static! {
  static ref MATCHES: ArgMatches = Cli::init().get_matches();
  static ref VERBOSE: bool = MATCHES.get_flag("verbose");
}

/// Whether `--verbose` was given. Under `cargo test` it is always false: the process
/// arguments belong to the test harness, and parsing them would exit the process.
pub fn verbose() -> bool {
  if cfg!(test) {
    false
  } else {
    *VERBOSE
  }
}

/// Exits the program with status 1 and an error message if `ffmpeg` is not on the PATH.
/// Returns `()` only when `ffmpeg` is found; otherwise it does not return.
pub fn exit_when_ffmpeg_not_available() {
  if which::which("ffmpeg").is_err() {
    eprintln!("❌ ffmpeg is not available. Please install it first.");
    exit(1);
  }
}

/// Deletes `path` if it exists. Does nothing and returns `Ok` when it is missing.
/// Returns `Err` if the file exists but cannot be removed.
pub fn remove_file(path: &Path) -> Result<()> {
  if Path::new(path).exists() {
    if verbose() {
      print!(
        "🗑️  Removing old data: `{}`",
        path.file_name().unwrap().to_string_lossy()
      );
    }
    fs::remove_file(path)?;
  }
  Ok(())
}

/// Lists the paths of every entry in a folder. Returns `Err` if the folder cannot be opened or
/// if reading any of its entries fails.
pub fn read_dir(input_vids_path: &Path) -> Result<Vec<PathBuf>> {
  fs::read_dir(input_vids_path)?
    .map(|res| res.map(|e| e.path()))
    .collect::<Result<Vec<_>>>()
}

/// Returns true when the merged output file exists, so the temporary files are no longer needed.
/// Returns false when it does not, so nothing is deleted before the merge has written the output.
pub fn output_is_ready(output: &Path) -> bool {
  output.is_file()
}

/// Creates a new folder with a random name in the system temp directory and returns its path.
/// Panics if the folder cannot be created.
pub fn create_tmp_dir() -> PathBuf {
  let dir = temp_dir().join(nanoid!(8));
  fs::create_dir(&dir).unwrap();
  dir
}

/// Creates the `fps_changer` subfolder inside `base_path` and returns its path.
/// Returns `Err` if the folder cannot be created.
pub fn create_dir_for_fps_changer(base_path: &Path) -> io::Result<PathBuf> {
  let mut new_path = base_path.to_path_buf();
  new_path.push("fps_changer");
  fs::create_dir_all(&new_path)?;
  Ok(new_path)
}

/// Writes `buf` to the file at `path`, replacing any existing content. Returns `path`.
/// Panics if the file cannot be created or written.
pub fn create(path: &PathBuf, buf: String) -> &PathBuf {
  File::create(path)
    .unwrap()
    .write_all(buf.as_bytes())
    .unwrap();
  path
}

/// Compares two strings "naturally": runs of digits are compared by their
/// numeric value, so "2" sorts before "10". Other characters compare normally.
/// Ties (e.g. "01" vs "1") are broken by the plain string order.
pub fn natural_cmp(left: &str, right: &str) -> Ordering {
  let mut left_chars = left.chars().peekable();
  let mut right_chars = right.chars().peekable();

  loop {
    match (left_chars.peek(), right_chars.peek()) {
      (None, None) => return left.cmp(right),
      (None, Some(_)) => return Ordering::Less,
      (Some(_), None) => return Ordering::Greater,
      (Some(a), Some(b)) if a.is_ascii_digit() && b.is_ascii_digit() => {
        let left_digits = take_digits(&mut left_chars);
        let right_digits = take_digits(&mut right_chars);
        let left_number = left_digits.trim_start_matches('0');
        let right_number = right_digits.trim_start_matches('0');
        let by_value = left_number
          .len()
          .cmp(&right_number.len())
          .then_with(|| left_number.cmp(right_number));
        if by_value != Ordering::Equal {
          return by_value;
        }
      }
      (Some(a), Some(b)) => match a.cmp(b) {
        Ordering::Equal => {
          left_chars.next();
          right_chars.next();
        }
        other => return other,
      },
    }
  }
}

/// Consumes and returns the run of digits at the front of `chars`.
fn take_digits(chars: &mut Peekable<Chars>) -> String {
  let mut digits = String::new();
  while let Some(c) = chars.peek().filter(|c| c.is_ascii_digit()) {
    digits.push(*c);
    chars.next();
  }
  digits
}

/// Returns the canonical (absolute) paths as strings, sorted by file name in natural order.
/// Panics if a path is not valid UTF-8 or cannot be canonicalized.
pub fn path_bufs_to_sorted_strings(path_bufs: &[PathBuf]) -> Vec<String> {
  let mut sorted_path_bufs = path_bufs.to_vec();
  // FPS-adjusted clips live in a different directory, so sort by filename rather than full path.
  // Natural order keeps "2" before "10" when files are numbered without zero-padding.
  sorted_path_bufs.sort_by(|left, right| {
    natural_cmp(
      &left.file_name().unwrap_or_default().to_string_lossy(),
      &right.file_name().unwrap_or_default().to_string_lossy(),
    )
  });

  sorted_path_bufs
    .iter()
    .map(|path_buf| {
      canonicalize(path_buf.to_str().unwrap())
        .unwrap()
        .display()
        .to_string()
    })
    .collect()
}

/// Waits for ENTER to continue, ESC to exit with status 0, or Ctrl+C to exit with status 130.
/// Panics if the terminal's raw mode or key reading fails.
pub fn wait_for_enter_or_esc_key() {
  println!("❓ Press ENTER to continue or ESC to cancel...");
  enable_raw_mode().unwrap();
  loop {
    if let Event::Key(key_event) = read().unwrap() {
      match key_event.code {
        KeyCode::Enter => {
          break;
        }
        KeyCode::Esc => {
          disable_raw_mode().unwrap();
          process::exit(0);
        }
        KeyCode::Char('c' | 'C') if key_event.modifiers.contains(KeyModifiers::CONTROL) => {
          disable_raw_mode().unwrap();
          process::exit(130);
        }
        _ => {}
      }
    }
  }
  disable_raw_mode().unwrap();
}

/// The commands that shut down this OS, in the order they are tried. Like the desktop's own
/// power-off button, the first ones need no sudo. `shutdown -h now` is the last resort on Linux.
fn shutdown_commands() -> Vec<(&'static str, Vec<&'static str>)> {
  if cfg!(target_os = "windows") {
    vec![("shutdown", vec!["/s", "/t", "0"])]
  } else if cfg!(target_os = "macos") {
    vec![(
      "osascript",
      vec!["-e", "tell application \"System Events\" to shut down"],
    )]
  } else {
    vec![
      ("systemctl", vec!["poweroff"]),
      ("loginctl", vec!["poweroff"]),
      ("shutdown", vec!["-h", "now"]),
    ]
  }
}

/// Shuts down the computer, for `--shutdown`. Returns `Err` when no shutdown command worked.
pub fn shutdown() -> Result<()> {
  shutdown_with(&shutdown_commands(), |program, args| {
    process::Command::new(program)
      .args(args)
      .status()
      .is_ok_and(|status| status.success())
  })
}

/// Runs `commands` in order with `run` until one succeeds. Later commands are not run.
/// Returns `Err` when every command fails.
pub fn shutdown_with(
  commands: &[(&str, Vec<&str>)],
  run: impl Fn(&str, &[&str]) -> bool,
) -> Result<()> {
  if commands.iter().any(|(program, args)| run(program, args)) {
    Ok(())
  } else {
    Err(io::Error::other("no shutdown command worked"))
  }
}

#[cfg(test)]
mod test_shutdown_with {
  use super::*;
  use std::cell::RefCell;

  #[test]
  fn stops_at_the_first_command_that_works() {
    let tried = RefCell::new(Vec::new());
    let commands = vec![("a", vec![]), ("b", vec![]), ("c", vec![])];
    let result = shutdown_with(&commands, |program, _| {
      tried.borrow_mut().push(program.to_string());
      program == "b"
    });
    assert!(result.is_ok());
    assert_eq!(*tried.borrow(), vec!["a", "b"]);
  }

  #[test]
  fn passes_the_arguments_of_each_command() {
    let commands = vec![("shutdown", vec!["-h", "now"])];
    let result = shutdown_with(&commands, |program, args| {
      program == "shutdown" && args == ["-h", "now"]
    });
    assert!(result.is_ok());
  }

  #[test]
  fn fails_when_every_command_fails() {
    let commands = vec![("a", vec![]), ("b", vec![])];
    assert!(shutdown_with(&commands, |_, _| false).is_err());
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn natural_cmp_sorts_numbers_by_value() {
    assert_eq!(natural_cmp("2", "10"), Ordering::Less);
    assert_eq!(natural_cmp("10", "2"), Ordering::Greater);
    assert_eq!(natural_cmp("file2.mp4", "file10.mp4"), Ordering::Less);
  }

  #[test]
  fn natural_cmp_handles_leading_zeros() {
    assert_eq!(natural_cmp("01", "2"), Ordering::Less);
    assert_eq!(natural_cmp("007", "10"), Ordering::Less);
    assert_eq!(natural_cmp("100", "99"), Ordering::Greater);
  }

  #[test]
  fn natural_cmp_breaks_ties_by_string_order() {
    assert_eq!(natural_cmp("01", "1"), Ordering::Less);
    assert_eq!(natural_cmp("a", "a"), Ordering::Equal);
  }

  #[test]
  fn natural_cmp_compares_text_normally() {
    assert_eq!(natural_cmp("a-clip.mp4", "b-clip.mp4"), Ordering::Less);
    assert_eq!(natural_cmp("abc", "abcd"), Ordering::Less);
    assert_eq!(natural_cmp("", "a"), Ordering::Less);
  }

  #[test]
  fn sorted_names_put_2_before_10() {
    let mut names = vec!["10.mp4", "1.mp4", "3.mp4", "2.mp4", "11.mp4"];
    names.sort_by(|a, b| natural_cmp(a, b));
    assert_eq!(names, ["1.mp4", "2.mp4", "3.mp4", "10.mp4", "11.mp4"]);
  }
}

/// Integration tests: these use the real file system in a temp folder.
#[cfg(test)]
mod test_io_integration {
  use super::*;

  /// A temp folder that is removed when the test ends, even if an assert fails.
  struct TempDir(PathBuf);

  impl TempDir {
    fn new(name: &str) -> Self {
      let dir = temp_dir().join(format!("vidmerger-io-{name}-{}", process::id()));
      let _ = fs::remove_dir_all(&dir);
      fs::create_dir_all(&dir).unwrap();
      TempDir(dir)
    }
  }

  impl Drop for TempDir {
    fn drop(&mut self) {
      let _ = fs::remove_dir_all(&self.0);
    }
  }

  #[test]
  fn create_writes_the_content_to_the_file() {
    let dir = TempDir::new("create");
    let path = dir.0.join("list.txt");
    create(&path, "file 'a.mp4'\n".to_string());
    assert_eq!(fs::read_to_string(&path).unwrap(), "file 'a.mp4'\n");
  }

  #[test]
  fn remove_file_deletes_an_existing_file() {
    let dir = TempDir::new("remove");
    let path = dir.0.join("output.mp4");
    fs::write(&path, b"x").unwrap();
    remove_file(&path).unwrap();
    assert!(!path.exists());
  }

  #[test]
  fn remove_file_is_ok_when_the_file_is_missing() {
    let dir = TempDir::new("remove-missing");
    assert!(remove_file(&dir.0.join("nope.mp4")).is_ok());
  }

  #[test]
  fn read_dir_lists_every_entry_in_the_folder() {
    let dir = TempDir::new("read-dir");
    fs::write(dir.0.join("a.mp4"), b"").unwrap();
    fs::write(dir.0.join("b.mp4"), b"").unwrap();
    let mut names: Vec<String> = read_dir(&dir.0)
      .unwrap()
      .iter()
      .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
      .collect();
    names.sort();
    assert_eq!(names, ["a.mp4", "b.mp4"]);
  }

  #[test]
  fn read_dir_fails_on_a_missing_folder() {
    let dir = TempDir::new("read-dir-missing");
    assert!(read_dir(&dir.0.join("missing")).is_err());
  }

  #[test]
  fn output_is_ready_only_when_the_output_file_exists() {
    let dir = TempDir::new("output-ready");
    let output = dir.0.join("output.mp4");
    assert!(!output_is_ready(&output));
    fs::write(&output, b"x").unwrap();
    assert!(output_is_ready(&output));
  }

  #[test]
  fn create_tmp_dir_makes_a_new_folder_in_the_system_temp_dir() {
    let path = create_tmp_dir();
    assert!(path.is_dir());
    assert!(path.starts_with(temp_dir()));
    let _ = fs::remove_dir_all(&path);
  }

  #[test]
  fn create_dir_for_fps_changer_makes_the_subfolder() {
    let dir = TempDir::new("fps-dir");
    let created = create_dir_for_fps_changer(&dir.0).unwrap();
    assert_eq!(created, dir.0.join("fps_changer"));
    assert!(created.is_dir());
  }

  #[test]
  fn path_bufs_to_sorted_strings_returns_sorted_absolute_paths() {
    let dir = TempDir::new("sorted");
    fs::write(dir.0.join("b.mp4"), b"").unwrap();
    fs::write(dir.0.join("a.mp4"), b"").unwrap();
    let paths = vec![dir.0.join("b.mp4"), dir.0.join("a.mp4")];
    let strings = path_bufs_to_sorted_strings(&paths);
    assert_eq!(strings.len(), 2);
    assert!(strings[0].ends_with("a.mp4"));
    assert!(strings[1].ends_with("b.mp4"));
    assert!(Path::new(&strings[0]).is_absolute());
  }
}