-
Notifications
You must be signed in to change notification settings - Fork 874
How to rotate video based on smartphone rotate meta tag
Smartphones set a meta tag rotate
that can be used by players to automatically correct the video orientation.
The behaviour and a fix form ffmpeg
are described in an article by thornelabs.
As ffmpeg does not keep the rotate
meta-tag in it's output files, we need to correct the orientation to make sure the video is displayed correctly. This is also required for players, that do not interprete the meta-tag at all.
First, setup the ffmpeg object and get the video stream via ffprobe.
<?php
$config = array(...);
$file = 'video.mp4';
// create the ffmpeg object
$ffmpeg = FFMpeg\FFMpeg::create($config, null);
// open video file
$video = $ffmpeg->open($file);
// get the first video stream
$videostream = $ffmpeg->getFFProbe()
->streams($file)
->videos()
->first();
Now, determine whether we need to rotate. This code should go in a method, hence i'm using return.
if (! $videostream instanceof FFMpeg\FFProbe\DataMapping\Stream) {
throw new \Exception('No stream given');
}
if (!$videostream->has('tags')) {
return false;
}
$tags = $videostream->get('tags');
if (! isset($tags['rotate'])) {
return false;
}
if ($tags['rotate'] == 0) {
return false;
}
// do the rotation correction
return true;
We need to determine the correct angle for the rotation we are going to do. This is based on the rotation of the video as recorded.
switch($tags['rotate']) {
case 270:
$angle = FFMpeg\Filters\Video\RotateFilter::ROTATE_270;
break;
case 180:
$angle = FFMpeg\Filters\Video\RotateFilter::ROTATE_180;
break;
case 90:
$angle = FFMpeg\Filters\Video\RotateFilter::ROTATE_90;
break;
}
Now, add the filter to rotate the video and save it.
$video->filters()
->rotate($angle);
// $video->save(...)
That's it.