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

Newsletter

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

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: