Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ffmpeg fix video orientation

A video can contain a meta info about the camera orientation. For example iPhone and other phones set this flag if you turn the device. Problem is while some player read this info and rotate the video accordingly, other players do not.

To fix this the video has to be rotated and the meta info needs to be set correctly.

Does ffmpeg provide a fix for this or do I have to go the hard way (Read rotation, rotate, set meta data)

like image 908
PiTheNumber Avatar asked Mar 17 '14 09:03

PiTheNumber


People also ask

Can FFmpeg rotate video?

We can use it to rotate the sample video either clockwise or anti-clockwise. It also allows us to flip videos vertically or horizontally. The transpose filter accepts the values from 0-3.


1 Answers

I did go the hard way:

$ffmpeg == "path/to/ffmpeg";
$output_file_full = "file/after/normal/conversion";

// get rotation of the video
ob_start();
passthru($ffmpeg . " -i " . $output_file_full . " 2>&1");
$duration_output = ob_get_contents();
ob_end_clean();

// rotate?
if (preg_match('/rotate *: (.*?)\n/', $duration_output, $matches))
{
    $rotation = $matches[1];
    if ($rotation == "90")
    {
        echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=1" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";
        echo shell_exec("mv $output_file_full.rot.mp4 $output_file_full") . "\n";
    }
    else if ($rotation == "180")
    {
        echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=1,transpose=1" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";
        echo shell_exec("mv $output_file_full.rot.mp4 $output_file_full") . "\n";
    }
    else if ($rotation == "270")
    {
        echo shell_exec($ffmpeg . ' -i ' . $output_file_full . ' -metadata:s:v:0 rotate=0 -vf "transpose=2" ' . $output_file_full . ".rot.mp4 2>&1") . "\n";
        echo shell_exec("mv $output_file_full.rot.mp4 $output_file_full") . "\n";
    }
}

I used some ugly temp files. Sorry about that.

like image 196
PiTheNumber Avatar answered Oct 13 '22 01:10

PiTheNumber