Check for broken MP4 file in PHP on Linux

mp4box

I’m working on a project where MP4 files are FTPd over to a different server. This server’s job is to add a front and end bumper to the video clips automatically and host for user pickup. I needed to find a way to ensure that the source video had finished transferring and was complete before starting the process. I’ve found that MP4Box is up to the task.

For this I’m using a server with Ubuntu 14.04.2 LTS and PHP 5.5.

There’s a lot of hints out there that mplayer or ffmpeg could be used to detect the MP4 file integrity but I found that this didn’t integrate very well with PHP. After some digging I found a utility called MP4Box. First off we’ll need to install that.

This part of my post is information that I gained from sudosu.in.

Install subversion so that we can download it from the repo.

# apt-get install subversion

Download the latest version of gpac from the repo.

# svn co https://svn.code.sf.net/p/gpac/code/trunk/gpac gpac

Configure the source package.

# cd gpac
# chmod +x configure
# ./configure --disable-opengl --use-js=no --use-ft=no --use-jpeg=no --use-png=no --use-faad=no --use-mad=no --use-xvid=no --use-ffmpeg=no --use-ogg=no --use-vorbis=no --use-theora=no --use-openjpeg=no

Install the gpack package.

# make
# make install
# cp bin/gcc/libgpac.so /usr/lib

Verify the installation.

# which MP4Box

Now for the PHP part.

Passing a file in to MP4Box’s -info function will give you a result really quickly and provide an error if the file is truncated.

Here’s an example response from MP4Box with an incomplete MP4 file…

user@Stagbeetle:~/mp4/incoming$ MP4Box -info 'broken.mp4'
[iso file] Incomplete box mdat
Truncated file - missing 9795055 bytes
Error opening file broken.mp4: IsoMedia File is truncated

MP4Box tells us that the file is truncated meaning that the transfer is either still in progress or has failed. We can now capture this error in PHP and only continue with a process if the file is fully there.

<?php
//Look for MP4 files within the incoming directory
$files = glob('/home/user/mp4/incoming/*.mp4');
  //Loop through these files
  foreach($files as $file) {
    //Run MP4Box's -info function on the file
    //You must include the '2>&1' here to see the output in PHP
    $output = shell_exec( "/usr/local/bin/MP4Box -info '$file' 2>&1" );
    //If the output contains 'truncated' then the file is broken
    if( strpos( $output, 'truncated' ) == false ) echo "The file is complete. Do something here.";
  }
?>

Leave a Reply

Your email address will not be published. Required fields are marked *