Posts Tagged ‘keep’

Serverside video resizing script for ffmpeg or Mencoder

Monday, October 1st, 2007

Some days ago, while working on a project that involves the re-encoding of a lot of videos coming from several sources, aspect ratios, resolutions, etc, i found myself in the situation where i needed to “standarize” somehow all the videos to a prefixed size in order to place them on a fixed space in a web page.
While most linux tools like ffmpeg or mencoder include native functions to scale or resize the video, they don’t care about the aspect ratios or about the fact that most video encoders expect mod16 values for the height and width values.
So my situation was like this:

I needed to make all the videos 480 pixels high, and scale the width proportionally.

That being said, i came up with this PHP script that i call from inside a bash script:

#!/usr/bin/php
<?php
$cmdWidth = 'midentify '.$argv[1];
$finalHeight = $argv[2];
exec($cmdWidth, $output);

foreach ($output as $value) {
    if (strstr($value, "ID_VIDEO_WIDTH")) {
		
		$width = parseResult($value);
    }
    if (strstr($value, "ID_VIDEO_HEIGHT")) {
    	$height = parseResult($value);
    }
}
$frameSize = $width / $height;
$finalWidth = $finalHeight * $frameSize;
echo getMod16(round($finalWidth)) . "x" . getMod16(round($finalHeight)) . "\n";
function parseResult($line) {
	$v1 = explode("=",$line);
	$v20 = $v1[1];
	
	//var_dump($v2);
	return $v20;
}
function getMod16($number){
	while (fmod($number, 16) != 0) {
		$number ++;
	}
	return $number;
}
?>

This script assumes that you have the “midentify” utility (wich comes with mplayer) installed in your path, and expects 2 arguments, being argument 1 the movie you want to resize and argument 2 the actual height you want to reach.
That being said, suppose you have a movie that is 848 pixels width and 480 pixels high and you want to re-scale it so it fits inside a 400 pixels high space, you would call the script like this:

./resizer mymovie.avi 400

The script will output this:

720x400

You can use later this value as an input parameter for ffmpeg for example.

Before somebody asks, the reason because i used PHP instead of BASH, is simply because bash does not supports floats.