5

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)

Community
  • 1
  • 1
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180

1 Answers1

8

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.

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
  • 1
    eeeeshhhh this sure is hacky. Consider the following instead to get the meta data as json: ffprobe -of json -show_streams your_video.file 2>/dev/null – deweydb Mar 01 '16 at 01:20
  • 1
    I know I'm coming very late, but instead of rotating it twice, you might as well "transpose=2,transpose=2" – ZioCain Jul 21 '20 at 16:38
  • 1
    @ZioCain Do you mean $rotation == "180"? Maybe like this: `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";` ? – PiTheNumber Jul 22 '20 at 14:53
  • @PiTheNumber yeah, that's what I actually meant! thank you for providing again the full working code! – ZioCain Jul 22 '20 at 16:48
  • 1
    @PiTheNumber The `ffmpeg` output is not meant to be machine parsed. Use [`ffprobe` instead to get the rotation](https://stackoverflow.com/a/41306388/) (and it will simplify your code). – llogan Jul 22 '20 at 17:26