Christian Heilmann

Quick and dirty: Batch conversion of lots of video files on the command line with PHP and ffmpeg

Thursday, September 3rd, 2020 at 5:33 pm

I just found some old DVDs with lots of small videos I collected on the web of a long ago. They are in most dubious formats and some of them play not very well on my Mac because of it (even in VLC, we’re talking .asf, .3gp and lots of .mpeg here). So I wondered what I can do to batch convert them all.

Turns out, ffmpeg has an OK quality command for that and with a bit of PHP, I can let the machine churn through all of them and put them in an mp4 folder.

I am not too proud of this, but it works an may help you, too:

<?php
// Get all files in folder
$files = scandir('.');
// Create MP4 folder
exec('mkdir mp4');
 
// Filter out files starting with .,mp4, php files
// and folders
function thingstoskip($f) {
  if(is_dir($f)) {
    return false;
  } else {
    return !preg_match("/^\.|\.$|\.mp4$|.php$/",$f);
  }
}
$urls = array_filter($files, thingstoskip);
 
// Get number of all files and loop over them
$all = sizeof($urls);
foreach ($urls as $u) {
  echo $all.": ".$u."\n";
  // convert with ffmpeg, rename to mp4 and save in the mp4 folder
  exec(
    'ffmpeg -loglevel error -i "'. $u .
    '" -c:v libx264 -c:a libvo_aacenc -crf 20 -preset:v medium "./mp4/'.
    preg_replace("/\.[^\.]*$/",'.mp4',$u).'"'
  );
  $all = $all - 1;
}
?>

Share on Mastodon (needs instance)

Share on Twitter

My other work: