vidmerger 0.4.3

A wrapper around FFmpeg which simplifies merging multiple videos and adds chapters from the file names
use super::fps_reader::get_fps;
use crate::{
  cli::Cli,
  commander,
  helper::{
    io_helper::{create_dir_for_fps_changer, path_bufs_to_sorted_strings, verbose},
    str_helper::gen_input_file_content_for_ffmpeg,
  },
};
use clap::ArgMatches;
use lazy_static::lazy_static;
use std::{
  collections::{HashMap, HashSet},
  path::{Path, PathBuf},
};

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

/// Makes every input the same frame rate before the merge. The goal is `fps_from_cli` when set
/// (not 0), otherwise the lowest fps found. Inputs at other rates are re-encoded into `tmp_dir`.
/// Returns the new input paths, their strings, and the concat list for them.
/// Panics if `tmp_dir/fps_changer` cannot be created, if FFmpeg cannot be run to read an fps,
/// or if `files_to_merge` is empty while `fps_from_cli` is 0 (there is no lowest fps to use).
pub fn change_fps(
  files_to_merge: Vec<PathBuf>,
  tmp_dir: &Path,
  fps_from_cli: f32,
) -> (Vec<PathBuf>, Vec<std::string::String>, std::string::String) {
  let mut new_files_to_merge = Vec::new();
  let mut map: HashMap<&PathBuf, f32> = HashMap::new();

  for file_to_merge in &files_to_merge {
    map.insert(file_to_merge, get_fps(file_to_merge));
  }

  let fps_goal = if fps_from_cli != 0. {
    fps_from_cli
  } else {
    *map
      .values()
      .min_by(|x, y| x.partial_cmp(y).unwrap())
      .unwrap()
  };

  let set: HashSet<String> = map.values().map(|value| value.to_string()).collect();
  let files_to_merge = if set.len() > 1 {
    let mut output_directly = Vec::new();
    for (key, value) in &map {
      if value == &fps_goal {
        output_directly.push(format!(
          "- {} ({} fps)",
          key.file_name().unwrap().to_string_lossy(),
          value
        ));
      }
    }
    output_directly.sort();

    let mut output_indirectly = Vec::new();
    for (key, value) in &map {
      if value != &fps_goal {
        output_indirectly.push(format!(
          "- {} ({} fps)",
          key.file_name().unwrap().to_string_lossy(),
          value
        ));
      }
    }
    output_indirectly.sort();

    println!(
      "🔎 FPS mismatches detected ({:?}), scaling to {} fps: {}/{}",
      set,
      fps_goal,
      output_indirectly.len(),
      set.len()
    );

    if verbose() {
      println!();
      println!("Will be merged directly: \n");
      for line in output_directly {
        println!("{line}");
      }
      println!();
      println!("Will be merged indirectly, generating new files from listed below with {fps_goal} fps and merges with listed above:");
      println!();
      for line in output_indirectly {
        println!("{line}");
      }
      println!();
    }

    // The folder is made only here, when at least one file really needs a new frame rate.
    let tmp_dir_for_fps_changer = create_dir_for_fps_changer(tmp_dir).unwrap();
    println!(
      "🎞️  FPS changer files go to: {}",
      tmp_dir_for_fps_changer.to_string_lossy()
    );
    for file_to_merge in files_to_merge {
      let fps = get_fps(&file_to_merge);

      if fps != fps_goal {
        let new_file_to_merge =
          commander::fps_adjuster::adjust_fps(file_to_merge, &fps_goal, &tmp_dir_for_fps_changer);
        new_files_to_merge.push(new_file_to_merge);
      } else {
        new_files_to_merge.push(file_to_merge);
      }
    }

    new_files_to_merge
  } else {
    files_to_merge
  };

  let files_to_merge_as_strings = path_bufs_to_sorted_strings(&files_to_merge);
  let ffmpeg_input_content = gen_input_file_content_for_ffmpeg(&files_to_merge_as_strings);

  (
    files_to_merge,
    files_to_merge_as_strings,
    ffmpeg_input_content,
  )
}