Reencode videos to watch them on an Android device with ffmpeg

Here is the script I use to convert videos to watch them on a Samsung Galaxy Ace. You can probably use it for any Android device, just modify the maximum resolution.


#!/usr/bin/perl

use strict;
use Data::Dumper;
use Getopt::Long;

sub getFileResolution {
my ($file) = @_;
my $stdout = `ffmpeg -i "$file" 2>&1`;
# Stream #0.0: Video: mpeg4, yuv420p, 720x528 [PAR 1:1 DAR 15:11], 25 tbr, 25 tbn, 25 tbc
$stdout =~ /Stream.*Video:.*?([\d]+)x([\d]+)/;
my ($w, $h) = ($1, $2);
die "Failed to get original resolution of \"$file\" ($w,$h)" if ! ( $w && $h);
return ($w, $h);
}

sub getNewResolution {
my ($width, $height) = my ($newwidth, $newheight) = @_;
my $ratio = $width * 1.0 / $height;
my $maxwidth = 480;
my $maxheight = 320;
if ( $newheight > $maxheight ) {
$newheight = $maxheight;
$newwidth = $ratio * $newheight;
}
if ( $newwidth > $maxwidth ) {
$newwidth = $maxwidth;
$newheight = $newwidth / $ratio;
}
return (int($newwidth), int($newheight));
}

sub getNewName {
my ($file) = @_;
$file =~ /(.*)\./;
my $basename = $1;

my $newname = $basename . ".mp4";
return $newname if $newname ne $file;

return $basename . "-converted.mp4";
}

sub printUsage {
print STDERR "Usage: $0 --input INVIDEO [--output OUTVIDEO] [--volume N]\n";
print STDERR " Converts the input video into a MP4 video readable on mobile devices\n";
print STDERR "\n";
print STDERR " --input : the input video file\n";
print STDERR " --output : the input video file\n";
print STDERR " --volume N : increase or decrease volume ; nominal volume is N=256\n";
print STDERR "\n";
print STDERR "Example:\n";
print STDERR " $0 --input file.avi --output file.mp4 --vol 512\n";
}

my ($src, $dst, $volume);
my $gocode = GetOptions (
"input=s" => \$src,
"output=s" => \$dst,
"volume=i" => \$volume
);

if ( ! $gocode || scalar(@ARGV) ) {
printUsage();
exit(1);
}

my ($w, $h) = getNewResolution(getFileResolution($src));
$dst = getNewName($src) if ! $dst;

my @args = ("ffmpeg");
push @args, "-i", $src;
push @args, "-s", "${w}x${h}";
push @args, "-b", "600k";
push @args, "-ab", "96k";
push @args, $dst;
system(@args);

Advertisements
This entry was posted in Android, Video. Bookmark the permalink.

One Response to Reencode videos to watch them on an Android device with ffmpeg

  1. comeni says:

    tu programmes le jour de ton anniv?
    Bon anniv!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s