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 BlueSky

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Word is Doomed, Flawed LLM benchmarks, hard sorting and CSS mistakes Spot LLM benchmark flaws, learn why sorting is hard, how to run Doom in Word and how to say "no" like a manager.
30 years of JS, Browser AI, how attackers use GenAI, whistling code Learn how to use AI in your browser and not on the cloud, why AI makes different mistakes than humans and go and whistle up some code!
197: Dunning-Kruger steroids, state of cloud security, puppies>beer
196: AI killed devops, what now? LLM Political bias & AI security Learn how AI killed DevOps, create long tasks in JS, why 1 in 5 security breaches are AI generated code & play "The Scope Creep"
195: End of likes, JS Zoo and Tim Berners-Lee doesn't see AI vs Web Meta kills like buttons, Tim-Berners-Lee thinks AI won't kill the web, GitHub is ending toasts and the worst selling Microsoft product.

My other work: