SSH Executing via PHP interrupted - php

I've got something like Video uploader written in PHP. When application puts video into FTP server, application is executing ffmpeg to convert that video to .mp4 format:
if(ftp_put($connection, $file_name, $file, FTP_BINARY) == true) {
ftp_close($connection);
if($extension == 'mp4') {
return redirect('/');
} else {
$ssh = new SSH2($server->ip);
if (!$ssh->login($server->ssh_user, $server->ssh_pass)) {
exit('Login Failed');
} else {
$ssh->exec('cd /var/www/videos/' . $video->id . ' && ffmpeg -i ' . $file_name . ' -c:v libx264 ' . $file_name_we . '.mp4');
}
}
}
The problem is: video converting is being interuptted. How to make that ffmpeg is going to successfully convert a video to mp4 via PHP?

Related

How to use system command in php?

I am working on a PHP code as shown below in which conversion of mp4 into mp3 is happening at Line B.
I have added if block after system command to print Conversion Completed on the webpage once the conversion is complete but it doesn't seem to work.
Php code:
if (isset($_POST['id']))
{
for($i=0; $i <count($mp4_files); $i++) {
if($i == $_POST['id']) {
$f = $mp4_files[$i];
$parts = pathinfo($f);
switch ($parts['extension'])
{
case 'mp4' :
$filePath = $src_dir . DS . $f;
print_r($f); // Line A
system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result); // Line B
if($result)
{
echo "Conversion Completed";
}
}
}
}
}
Problem Statement:
I am wondering what changes I should make in the PHP code above so that once the conversion is complete; on the webpage, it should print Conversion Completed.
You can use shell_exec to get a return value and then put that in an if statement like this
$output = shell_exec('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3');
if ($output) {
echo "Conversion Completed!";
// or redirect here
}
Also, make sure to sanitize your inputs as they are exposed to a CLI interface.

Returning shell_exec as string PHP detecting BPM with soundtouch/soundstrech

I am working on a php function used to upload a .wav to server (along with converting to mp3 and creating waveform image png) , and within the function I would like it to use soundtouch / soundstrech to detect the B.P.M. (Beats Per Minute). I know it will not be the most accurate but for my purposes it will be all I need.
I was able to get the B.P.M. of a .wav file using soundtouch / soundstrech along with ffmpeg within a test.php file using deven's php-bpm-detect wrapper But When I try to integrate it within my PHP function it returns the B.P.M. as zero.
I am wondering if there is a simpler way to get the bpm as a string from the following shell exec without having to use a separate php library?
I would like to perform this and have it return as a string:
$song_bpm = shell_exec('soundstretch ' . $file_path . ' -bpm');
test.php (This works and returns the proper bpm:)
<?php
require "class.bpm.php";
$wavfile = "38a2819c20.wav";
$bpm_detect = new bpm_detect($wavfile);
$test = $bpm_detect->detectBPM();
echo ' bpm of ' . $wavfile . ' is: ' . $test . ' ';
?>
PHP Function: (returns bpm as zero)
function upload_a_sound($user_id, $file_temp, $file_extn, $name, $uploader, $keywords) {
$timecode = substr(md5(time()), 0, 10);
$mp3name = 'beats/' . $timecode . '.mp3';
$file_path = 'beats/' . $timecode . '.wav';
move_uploaded_file($file_temp, $file_path);
shell_exec('ffmpeg -i ' . $file_path . ' -vn -ar 44100 -ac 2 -ab 192k -f mp3 ' . $mp3name . '');
require ('classAudioFile.php'); // This creates a spectogram .png file of .wav
$AF = new AudioFile;
$AF->loadFile($file_path);
$AF->visual_width=200;
$AF->visual_height=200;
$AF->visual_graph_color="#c491db";
$AF->visual_background_color="#000000";
$AF->visual_grid=false;
$AF->visual_border=false;
$AF->visual_graph_mode=0;
$AF->getVisualization ('images/song/' . $timecode . '.png');
$imageloc = 'images/song/' . $timecode . '.png';
require ('class.bpm.php'); //Deseven's class to get bpm,
$bpm_detect = new bpm_detect($file_path);
$song_bpm = $bpm_detect->detectBPM(); //when used here this returns 0
mysql_query("INSERT INTO `content` VALUES ('', '', '$name', '$uploader', '$keywords', '$file_path', '$imageloc', '$mp3name', '$song_bpm')"); // I will update this to mysqli soon, for now it works
}
I also found this which works, but not when I integrate it into my function:
// create new files, because we don't want to override the old files
$wavFile = $filename . ".wav";
$bpmFile = $filename . ".bpm";
//convert to wav file with ffmpeg
$exec = "ffmpeg -loglevel quiet -i \"" . $filename . "\" -ar 32000 -ac 1 \"" . $wavFile . "\"";
$output = shell_exec($exec);
// now execute soundstretch with the newly generated wav file, write the result into a file
$exec = "soundstretch \"" . $wavFile . "\" -bpm 2> " . $bpmFile;
shell_exec($exec);
// read and parse the file
$output = file_get_contents($bpmFile);
preg_match_all("!(?:^|(?<=\s))[0-9]*\.?[0-9](?=\s|$)!is", $output, $match);
// don't forget to delete the new generated files
unlink($wavFile);
unlink($bpmFile);
// here we have the bpm
echo $match[0][2];
I've updated my class so it's supporting absolute and relative paths now.
And the straightforward solution:
exec('soundstretch "test.wav" -bpm 2>&1',$average_bpm);
foreach ($average_bpm as $line) {
if (strpos($line,"Detected BPM rate") !== false) {
$line = explode(" ",$line);
$average_bpm = round($line[3]);
break;
}
}
echo $average_bpm;
Just keep in mind that $average_bpm will contain the error if anything goes wrong.

Make PHP wait for Matlab script to finish executing [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php exec command (or similar) to not wait for result
exec() waiting for a response in PHP
I have a php script that calls and runs a Matlab script. The result of the Matlab script is a .png image, which I would then like to load in php and send to a webpage. The php code I have is:
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
passthru($command);
$im = file_get_contents('C:\\habitat.png');
header('Content-type:image/png');
echo $im;
However, it appears that after sending the 'passthru' command, php does not wait for the Matlab script to finish running. Thus, if the image file does not exist before running the php code, then I get an error message.
Is there a way to make it so that the php code waits for the Matlab script to finish running before it attempts to load the image file?
passthru is not the main issue here .. but i guess as soon you have a response from your command the image is not written instantly but by a 3rd process
file_get_contents might also fail in this instance because .. The image might not be written once or in the process of writing which can result to file lock .. in any case you need to be sure you have a valid image before output is sent;
set_time_limit(0);
$timeout = 30; // sec
$output = 'C:\\habitat.png';
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
try {
if (! #unlink($output) && is_file($output))
throw new Exception("Unable to remove old file");
passthru($command);
$start = time();
while ( true ) {
// Check if file is readable
if (is_file($output) && is_readable($output)) {
$img = #imagecreatefrompng($output);
// Check if Math Lab is has finished writing to image
if ($img !== false) {
header('Content-type:image/png');
imagepng($img);
break;
}
}
// Check Timeout
if ((time() - $start) > $timeout) {
throw new Exception("Timeout Reached");
break;
}
}
} catch ( Exception $e ) {
echo $e->getMessage();
}
I believe if you change passthru to exec it will work as intended. You can also try this:
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
passthru($command);
// once a second, check for the file, up to 10 seconds
for ($i = 0; $i < 10; $i++) {
sleep(1);
if (false !== ($im = #file_get_contents('C:\\habitat.png'))) {
header('Content-type:image/png');
echo $im;
break;
}
}

Live streaming doesn't work

I'm using FFmpeg to capture my screen:
ffmpeg -f dshow -i video="UScreenCapture" -r 5 -s 640x480 -acodec libmp3lame -ac 1 -vcodec mpeg 4 -vtag divx -q 10 -f mpegts tcp://127.0.0.1:1234
so let it stream to somewhere. The accepter script:
error_reporting(E_ALL); /* Allow the script to hang around waiting for connections. */
set_time_limit(30); /* Turn on implicit output flushing so we see what we're getting as it comes in. */
ob_implicit_flush();
$address = '127.0.0.1';
$port = 1234;
$outfile = dirname(__FILE__)."/output.flv";
$ofp = fopen($outfile, 'wb');
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; sleep (5); die; }
if (socket_bind($sock, $address, $port) === false) { echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; sleep (5); die; }
if (socket_listen($sock, 5) === false) { echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; sleep (5); die; }
if (($msgsock = socket_accept($sock)) === false) { echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; sleep (5); break; }
do {
$a = '';
socket_recv ($msgsock, $a, 65536, MSG_WAITALL);
fwrite ($ofp, $a);
//echo strlen($a)."\r\n";
} while (true);
it seems to save the stuff to the disk OK. Now here comes the html:
I dont really know how to do this, but based on an example:
<video src="/output.flv"></video>
but it doesn't do anything. And if I want to stream the live incoming stuff, then what's the matter?
HTML 5 Video will not support the Flv format HTML5 will be support the following format video only
.mp4 = H.264 + AAC
.ogg/.ogv = Theora + Vorbis
.webm = VP8 + Vorbis
study the HTML5 video basics in the following site
HTML5 video basics
if you want to play the flv you have to use the flash or Flex program or some flv players like flowplayer

Echo "success" after using ftp_put()

I have a php script that sends large files via FTP. After the file is sent I'm trying to write to the browser "success". I'm also trying to send a query to the database to record that the file was sent. However, any code that I have that comes after the ftp_put does not get executed.
if (ftp_put($conn_id, $upload_filename, $filename, FTP_BINARY))
{
echo "File Sent";
echo $upload_filename." - ".date("d/m/Y H:i:s")." - ".filesize($filename)." bytes<br>" ;
}
else
{
echo "Problem while Uploading $filename\n <br/>". $upload_filename ;
}
If ftp_put is false the echo works. But, if the ftp_put is a success any code I put there will not run.
The file size I am sending is 7,305kb
It is likely that the problem here is that your script is timing out while the file is uploading. Try adding this line before the code above:
set_time_limit(0);
The thing is that ftp_put() blocks any further action until the upload is finished. Try ftp_nb_put() (no blocking) like so:
$upload = ftp_nb_put($conn_id, $upload_filename, $filename, FTP_BINARY);
if($upload == FTP_MOREDATA)
{
echo 'Uploading ' . $upload_filename . ' - ' . date("d/m/Y H:i:s") . ' - ' . filesize($filename) . ' bytes<br />';
while($upload == FTP_MOREDATA)
{
echo '.'; //Output a . to page or do whatever
$upload = ftp_nb_continue($conn_id);
}
}
//Note: While in the while above, it will either end in FTP_FINISHED or FTP_FAILED
if($upload == FTP_FAILED)
{
echo "Problem while Uploading $filename\n <br />". $upload_filename;
}

Categories