Reduce FFmpeg CPU Usage with cpulimit and PHP - php

I run FFmpeg on my server using PHP exec().
It currently uses 100% of the cpu thread while encoding.
I followed this gude that uses a program called cpulimit to reduce it to 30%.
PHP
$args = "nice -19 cpulimit -l 30 -- ffmpeg -y -i intput.avi -vcodec libx264 -acodec aac -b:a 192k -threads 1 output.mp4"
exec(escapeshellcmd($args));
FFmpeg/PHP works, and it will work with nice/cpulimit through the terminal, but after adding
nice -19 cpulimit -l 30 -- to the PHP script it no longer works with exec().
Output
FFmpeg output returns blank. I'm not able to see the full output, I tried using:
$output = shell_exec($args);
echo "<p>$output</p>"
and
file_put_contents("/var/www/mysite/logs/$output.log", $line . PHP_EOL, FILE_APPEND);
But they return 1 empty line.
Solution
My thought is that www-data runs FFmpeg and nice/cpulimit may need root?
How can I get PHP exec() to work with FFmpeg args and cpulimit?
Or is there an alternative way to limit the usage %?

If safemode is enabled then, the execution of programes are limited. Check this documentation here, http://php.net/manual/en/function.exec.php

I found the answer on this forum post using google translate.
https://murobbs.muropaketti.com/threads/nice-komento-ja-php-n-exec-funktio-ratkaistu.551174/
Define the path to FFmpeg if using nice or cpulimit
nice -19 cpulimit -l 30 /usr/local/bin/ffmpeg -i ...
Now it works through PHP exec().

Related

FFMpeg working in command line but not in PHP script

I am using FFMpeg to convert videos and it is working fine from the command line. I am using the following command:
ffmpeg -i input.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv output.flv
However, when I run the command using PHP script, the output video is not encoded.
exec("ffmpeg -i input.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv output.flv",$output, $returnvalue);
$returnvalue = 127;
FFMPEG installed path :
[root#localhost ~]# which ffmpeg
/root/bin/ffmpeg
My Script Path :
www.domainname.com/core/foldername/ffmpeg.php
Please provide me solution for the same ASAP.
Thank you.
The natural way to run ffmpeg from PHP scripts is something like:
<?php
echo "Starting ffmpeg...\n\n";
echo shell_exec("ffmpeg -i input.avi output.avi &");
echo "Done.\n";
?>
There are several issues that need to be pointed out here. The first one is that, although we specified we want ffmpeg to be executed in the background (using the ampersand operator "&"), PHP script will not continue it's execution until ffmpeg has finished its execution. This is due to the fact, mentioned in one of the notes for the ​PHP's exec() function that says:
If a program is started with this function, in order for it to
continue running in the background, the output of the program must be
redirected to a file or another output stream. Failing to do so will
cause PHP to hang until the execution of the program ends.
Don't be confused about the example showing ​shell_exec() call instead of ​exec(). All of the ​PHP's Program execution functions share the similar code base and limitations.
So, to work around this issue, we need to do something like this:
<?php
echo "Starting ffmpeg...\n\n";
echo shell_exec("ffmpeg -i input.avi output.avi >/dev/null 2>/dev/null &");
echo "Done.\n";
?>
The part that says ">/dev/null" will redirect the standard OUTPUT (stdout) of the ffmpeg instance to /dev/null (effectively ignoring the output) and "2>/dev/null" will redirect the standard ERROR (stderr) to /dev/null (effectively ignoring any error log messages). These two can be combined into a shorter representation: ">/dev/null 2>&1". If you like, you can ​read more about I/O Redirection.
An important note should be mentioned here. The ffmpeg command-line tool uses stderr for output of error log messages and stdout is reserved for possible use of pipes (to redirect the output media stream generated from ffmpeg to some other command line tool). That being said, if you run your ffmpeg in the background, you'll most probably want to redirect the stderr to a log file, to be able to check it later.
One more thing to take care about is the standard INPUT (stdin). Command-line ffmpeg tool is designed as an interactive utility that accepts user's input (usually from keyboard) and reports the error log on the user's current screen/terminal. When we run ffmpeg in the background, we want to tell ffmpeg that no input should be accepted (nor waited for) from the stdin. We can tell this to ffmpeg, using I/O redirection again ** "ffmpeg command-line tool in the background would be similar to this:
<?php
echo "Starting ffmpeg...\n\n";
echo shell_exec("ffmpeg -y -i input.avi output.avi </dev/null >/dev/null 2>/var/log/ffmpeg.log &");
echo "Done.\n";
?>
The ​"-y" option is used to auto-overwrite the output file (output.avi) without asking for yes/no confirmation. If you need the opposite scenario, to auto-cancel the entire process if the output file already exists, then use "-n" option instead.
Wrapper Libraries
Some PHP libraries allow wrapping ffmpeg calls into PHP objects, and give you a nice syntax to work with if you don't like to use the command line. One of these is the actively maintained ​PHP-FFMpeg. It only requires you to ​download a recent ffmpeg and ffprobe build apart from installing the PHP components. Then you can run PHP code like this:
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video
->filters()
->resize(new FFMpeg\Coordinate\Dimension(320, 240))
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
Of course you need to take care of running such a task in the background. Libraries such as ​GearmanClient facilitate this.
Note: ​ffmpeg-php is an extension that is not developed since 2007 (and requires "ffmpeg-0.4.9_pre1 or higher"), which means that you are restricted to use a very old version of ffmpeg, without possibility to update it to the latest version. Since a lot of changes/improvements are being made, inside ffmpeg's code, every day, it makes ffmpeg-php incompatible with the latest ffmpeg.
Read the official documentation for more info.
I covered the solution that helps most people that I spoke to about this in another thread.
https://stackoverflow.com/a/38626752/2074077
Essentially, your user needs access to the public directories.
<?php
exec('whoami'); // Gives you the running user; often it's www-data
?>
Then change your public ownership to the whoami user.
sudo chown -R www-data:root /var/www
This happened to me, I found this on another forum; the trick inside of PHP is to give the absolute path to FFMPEG. Try running it like this..
exec("/root/bin/ffmpeg -i input.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv output.flv",$output, $returnvalue);
Something about the fact that php is a different user than you are when typing straight into the command line. I guess it doesn't have the same shortcut list or whatever it is.
Not sure exactly why but it worked for me!
Good luck.

Problems with executing FFMPEG through PHP

Have been trying to execute FFMPEG using a script I have uploaded to my domain
<?php
$output = array();
$result = -1;
exec('../../../../../../usr/bin/ffmpeg -ab 320k -i source.wav dest320.mp3', $output, $result);
var_dump($output, $result);
?>
The example code says the program should not be returning -1 unless there is an error but I have pointed to the exact path that FFMPEG is stored in.....
When I call 'ffmpeg -ab 320k -i source.wav dest320.mp3' from CentOS it works...
Am lost and have spent hte last few hours trying to work it out.
Thanks
CP
Any time you have an exec that doesn't work in php, you should switch to passthru for debugging.
passthru('../../../../../../usr/bin/ffmpeg -ab 320k -i source.wav dest320.mp3 1 2>&1');
Appending 1 2>&1 to the end, pipes your stderr to stout, and returns any errors you have while running your exec.
It is probably safer to use passthru('/usr/bin/env ffmpeg -ab 320k -i source.wav dest320.mp3 1 2>&1'); which will get the correct path for ffmpeg without the need to specify and absolute/relative path.
Also worth noting that if you are using Ubuntu since 12.04, the ffmpeg command has been renamed to avconv.

using ffmpeg exe in php

and am wanting to use ffmpeg as command line direct on windows 7 x64, I tried adding the extension, but unfortunately it did not work for some unknown reason, but the executable worked perfectly, I'm using the exec command, the only problem is that does not work with direct lines, I have to create a file. bat to run the program. this is my doubt.
$a = exec('\b.bat');
if ($a)
{
echo "Success"."\n";
print $a;
}else {
echo "No good"."\n";
print $a;
}
b.bat
ffmpeg -i video.flv -an -ss 00:00:16 -an -r 1 -vframes 1 -y %a.jpg
already tried several alternatives but the only one that worked was with the. bat
$a = exec('\windows/system32/ffmpeg.exe ffmpeg -i video.flv -an -ss 00:00:16 -an -r 1 -vframes 1 -y %a.jpg');
Make sure you include the full path to your .bat file and also make sure to include the full path to ffmpeg.exe in your .bat file.
Well, I am also working on this ffmpeg file to convert my movies and stuff my idea is for people to watch movies for free anyway here is what I use to convert my movies, have a note that when the ffmpeg.exe is not in the same folder than the movies then you will need to give a full path or use of ../ to go up a folder and / to a folder for example:
$input_path= $_FILES["file"]["tmp_name"];
$output_result= "movies/" . basename($_FILES["file"]["name"]).".flv";
exec("FFMPEG.EXE -i '$input_path' -s 900x400 -r 29.97 -b 1024k -ar 22050 -ab 50k -ac 1 '$output_result'");
there I am using scale and rateframe as well as bitrate and sound quality so my input and output I gave them in a variable basically that command you can use as is just give a value to those variables $input and $output. Please note that I am barely working out the idea too so far this is what I have come out with please do not expect excellent results since we are using microsoft windows the results may vary from version to version and you may have to use the command in administrator mode I hope this helps you my email is support#web2021.com if anything let me know man.

FFMpeg working in command line but not in PHP using exec();

I am using FFMpeg to covert videos and it is working fine from the command line. I am using the following command:
ffmpeg -i input.mpg -vcodec libx264 -b 819200 -s 100x100 -g 15 -bf 3 -b_strategy 1 -coder 1 -qmin 10 -qmax 51 -sc_threshold 40 -flags +loop -cmp +chroma -me_range 16 -me_method hex -subq 5 -i_qfactor 0.71 -qcomp 0.6 -qdiff 4 -directpred 1 -flags2 +fastpskip -dts_delta_threshold 1 -acodec libfaac -ab 48000 output.m4v
However, when I run the command using PHP exec(), the output video is not encoded correctly and is distorted and cropped. I am using the following in PHP:
$output = exec($cmd . ' 2>&1', $output, $return);
The $output returns a '0' successful code.
Does any one have any suggestions?
Thank you.
This is unusual. It is possible that you have more than one ffmpeg binary installed, and the one that is being called by the PHP/Apache user is not the same as the one you call as your user from the command line.
Try specifying the full path to your ffmpeg binary (/usr/bin/ffmpeg or whatever) inside your exec().
It sounds like some command line options are getting lost/altered. I would try to split this into a 2 part process:
write a shell script on-the-fly (from PHP) that has all the proper command arguments (make it executable)
execute the shell script (from PHP)
I would probably try:
1) change ' 2>&1' to ' 2>&1 &'
Also, transcoding can take a while. Are you certain you are waiting long enough for the transcode to complete?

how to convert video from one format to another using php

hi i want to include the vedio download option in my webpage. I am using ffmpeg, but it seems to work very slow. Is there is any other way to do this or how to spead up the ffmpeg.
i am using this code to get the frames from the vedio.
to convert the vedio
$call="ffmpeg -i ".$_SESSION['video_to_convert']." -vcodec libvpx -r 30 -b ".$quality." -acodec libvorbis -ab 128000 -ar ".$audio." -ac 2 -s ".$size." ".$converted_vids.$name.".".$type." -y 2> log/".$name.".txt";
$convert = (popen("start /b ".$call, "r"));
pclose($convert);
to get the frame from the vedio
exec("ffmpeg -vframes 1 -ss ".$time_in_seconds." -i $converted_vids video_images.jpg -y 2>);
but this code does not generate any error its loading continously.
Cache or pre-generate the output format.
Use the ffmpeg-php library. Should boost up some processes rather then manually calling the ffmpeg command line tool using exec.
I'd first of all take PHP out of the equasion and time how long it takes to do what you're after via the command line.
Once you're happy that works the way you'd like it to, make sure you've tweaked your script's execution time (see http://php.net/manual/en/function.set-time-limit.php) to accomodate what's likely to take a while.
Consider an async approach if it's getting in the way of UX.
Ta

Categories