Mitya
Mitya

Reputation: 34556

Run script after FFMPEG background task completes (via PHP)

I have a PHP script which triggers an FFMPEG file conversion via shell_exec().

shell_exec('ffmpeg -i file.webm -c:v libx264 -c:a aac -strict -2 file.mp4 >/dev/null 2>/dev/null &');

This happens in the background (hence &), i.e. the script completes before conversion has finished.

Is there a way to call and execute a PHP script (to update a DB flag) once the conversion is complete?

I've done plenty of Googling but my knowledge of server commands just isn't up to understanding what I'm reading (e.g. this answer). The best I could manage was to redirect stdout to a file via

shell_exec('ffmpeg -i file.webm -c:v libx264 -c:a aac -strict -2 file.mp4 > MYFILE.txt 2>/dev/null &');

...but obviously that just creates and writes to a file, it doesn't call and execute it via PHP.

Upvotes: 1

Views: 963

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

I am not that great at server commands either, so I can't really help you there. But I do have this knack for figuring things out.

So I see a few ways you could do this, essentially you need PHP to do something when the command line call finishes. The obvious answer is to remove the & off the end of the command and make it blocking so PHP sticks around tell the job is done. But in doing so you can't return to the end user until that is done.

Option 1 So one way around this is to make a sort of Bootstrap PHP script that you call non-blocking. In this script do your now blocking conversion command and after that returns have PHP do something else.

 //bootstrap.php
 shell_exec('ffmpeg -i file.webm -c:v libx264 -c:a aac -strict -2 file.mp4 > MYFILE.txt 2>/dev/null'); //blocking
 //Update the DB

Then from your Controller or what have you call the bootstrap non-blocking

shell_exec('php {pathto}/bootstrap.php 2>/dev/null &');

This way the call to the bootstrap returns immediately but the conversion call is blocking, which gives you the chance to update the DB afterwords.

Option 2

Because the conversion is outputting a file, you could start a separate background job, that monitors the modified time of the output file. Then if the modified time is like a minute in the past you could assume it's done converting and update the DB. The modified time should continue to update as long as data is being added to the file.

Hope that helps.

PS. I have some code you may fine useful on GitHub

Runs Background processes in both windows & linux

https://github.com/ArtisticPhoenix/MISC/blob/master/BgProcess.php

PHP process locking ( Mutex simulation using files)

https://github.com/ArtisticPhoenix/MISC/blob/master/ProcLock.php

Command line argument mapping for PHP programs:

https://github.com/ArtisticPhoenix/Cli

Your welcome to use them if it helps you out.

Upvotes: 1

Related Questions