Конвертация видео для Android-планшетов на базе WonderMedia

Сейчас бросовыми планшетами на базе Android не торгует только ленивый. В китайских магазинах “это” стоит примерно от 80 USD, на рынках эРэФии можно отовариться тысяч за 5, в зависимости от наглости продавца и дурости покупателя.

Вобщем все здорово, только видео-кодеки “из коробки” весьма ограничены, а ставить плееры сторонние – идея откровенно плохая, ибо родной плеер оптимизирован под железку, привнесенные работать не будут или эффекта нужного не дадут.

В любом случае, ниже cкрипт на языке Perl, который при установленном в системе ffmpeg перекодирует заданные видео-файлы в “подходящие”.

Алгоритм простой – читаем “инфу” о кодеках в файле, если видео НЕ mpeg4 или его битрейт больше заданного – конвертируем, если кодек mpeg4, битрейт “пролазит”, то копируем видеопоток без изменений. Со звуком еще проще – всегда приводится к mp3@128k@44100, воизбежание, да еще и gain выставляется, чтобы увеличить громкость на “как-бы динамиках”. gain можно отключить в опциях или поменять в тексте скрипта.


#!/usr/bin/perl

use Getopt::Long;
use IPC::Open3;
use File::Basename;

#actual settings — play around here

my $ffmpeg=”/usr/bin/ffmpeg”; #path to your ffmpg
my $mp3codec=”libmp3lame”; #actual audio codec
my $volume_gain=”1024″; #volume gain, see ffmpeg doc for details
my $video_limit = 985; #just an experimental value, calcualated from some movie “totalbitrate-audiobitrate”. try to increase, but avoid performance flaws
my $target_ext = “mkv”; #extension for target files – try to change to “mp4″ and maybe it will work for your iPad :-)
my $mp3encoder = “libmp3lame”; #actual codec – on some setups must be changed to “mp3″, tested on ubuntu

#actual settings — end

&GetOptions(\%opt,
“help!”,
“outdir=s”,
“donotgain”,
);

if ($#ARGV == -1 or $opt{help}) {
print <<END;
Script converts video files to WonderMedia Android tablet compatible format using ffmpeg codec.
Usage: $0 [options] [ ...]
Available options
–help : Display this message
–outdir : Output directory
–donotgain : Disable audio gain
END

exit;
}

#parsing source file, try to get bitrate video

foreach $org (@ARGV){

$body = $org;
$body =~ s/^(.+)\.\w+?$/$1/;
$targetfile = “$body.$targext”;

local(*HIS_IN, *HIS_OUT, *HIS_ERR);

open3( *HIS_IN, *HIS_OUT, *HIS_ERR, “$ffmpeg -i $org” ) or die “can’t run $ffmpeg\n”;

my @res = <HIS_ERR>;
close(HIS_IN);
close(HIS_OUT);
close (HIS_ERR);

print “FFMPEG output:\n”;

my $duration = join (”,grep(/Duration:/, @res));
my $video = join (”,grep(/Video:/,@res));
my $audio = join (”,grep(/Audio:/,@res));

my $total_bitrate=0;
my $audio_bitrate=0;
my $video_codec=0;

if ($duration =~ m/bitrate: (\d*) kb\/s/) {
$total_bitrate = $1;
}

if ($video =~ m/Video: (.*?)\,/) {
$video_codec = $1;
}

if ($audio =~ m/.*,\s(\d*)\skb\/s/) {
$audio_bitrate = $1;
}

print “overall bitrate: $total_bitrate\n”;
print “video codec: $video_codec\n”;
print “audio bitrate: $audio_bitrate\n”;

my $video_bitrate = $total_bitrate – $audio_bitrate;

my $vcodec = “copy”;

# if codec is not “mpeg4″ or video bitrate bigger than bitrate limit – form the string.
# else – use copy

if (($video_codec ne “mpeg4″) || ($video_bitrate > $video_limit))
{
my $target_bitrate = $video_limit;

if($video_limit > $video_bitrate) #quite possible, we do have lower bitrate, so let’s leave it as it was, to prevent unnescessary size increase
{
$target_bitrate = $video_bitrate;
}
$vcodec = “mpeg4 -b $target_bitrate”.”kb -mbd 2 -cmp 2 -subcmp 2″;

}

#stolen from some other’s perl code, sorry

$body = $org;
$body =~ s/^(.+)\.\w+?$/$1/;
$targetfile = “$body”.”_tablet.$target_ext”;

#if out dir set – we can use it for output

if ($opt{outdir}){
$targetfile = basename($targetfile);
$targetfile = $opt{outdir}.”/”.$targetfile;
}

my $ffmpeg_command = qq($ffmpeg -y -i “$org” -acodec $mp3encoder -ar 44100 -ac 2 -ab 128kb -vol 1024 -vcodec $vcodec “$targetfile”);

#remove volume gain if asked

if ($opt{donotgain}){
$ffmpeg_command =~ s/\-vol\s1024//;
}

#print actual ffmpeg command, then run

print “$ffmpeg_command\n”;
`$ffmpeg_command`;

}

P.S. Надеюсь, ничего не “побилось” при вставке.
Приятного просмотра.

Добавить комментарий

Please log in using one of these methods to post your comment:

Логотип WordPress.com

You are commenting using your WordPress.com account. Log Out / Изменить )

Фотография Twitter

You are commenting using your Twitter account. Log Out / Изменить )

Фотография Facebook

You are commenting using your Facebook account. Log Out / Изменить )

Connecting to %s

Follow

Get every new post delivered to your Inbox.