tablet-encode-2.30/0000755000175000001440000000000011275321252013343 5ustar andrewuserstablet-encode-2.30/README.txt0000644000175000001440000003017111275317554015055 0ustar andrewusers tablet-encode - Transcoding video files for Nokia Internet Tablets ~~~~~~~~~~~~~ (c) Andrew Flegg 2006-2009. v2.30 Released under the Artistic Licence. http://www.bleb.org/software/maemo/#encode INTRODUCTION As the Nokia Internet Tablets have relatively slow processors, and relatively little storage space it is a good idea to "transcode" your videos to a smaller, more suitable format for watching them. Nokia's Internet Tablet Video Converter is by far the best GUI video converter for this task, however only runs on Windows. It is also sometimes useful to be able to convert videos on the command line. It is, of course, possible to use mencoder directly to get appropriately formatted videos, but making sure the output will work, without testing it, is a laborious process and involves remembering fairly long-winded command lines. tablet-encode can help with all these problems: * It runs on Linux, Mac OS X, Unix and Windows. * It guarantees the output to be playable on a Nokia Internet Tablet using a system of "profiles". * It can rip and encode DVDs in a single step (dependent on mencoder version) * It has a simple GUI available. * It has a command-line interface so it can be easily scripted to interface to your PVR (for example, MythTV, Freevo or VDR). * Presets allow tradeoff between space/quality to be decided on a per-video basis. * Can optimise video size for the Internet Tablet's 15:9 screen. * Handles anamorphic video sources such as widescreen DVDs. * Output works with either the built-in Media Player, or mplayer. * Audio and video streams are copied if they are lower quality than the selected preset, and compatible with the Nokia Internet Tablets. DEPENDENCIES * mencoder - http://www.mplayerhq.hu/ * mplayer - http://www.mplayerhq.hu/ (optional) * Gtk2::Perl - http://gtk2-perl.sourceforge.net/ (optional) * Perl - see http://www.activestate.com/ for Windows version On a Debian or Ubuntu-based distribution, the dependencies can be met with: sudo apt-get install mencoder mplayer libgtk2-perl A good place to download mplayer and mencoder binaries for Windows is: http://oss.netfarm.it/mplayer-win32.php USAGE 1) Copy `tablet-encode' to a directory on your PATH, such as /usr/local/bin. 2) Ensure you have mencoder installed (type `mencoder' on its own). 3) Example commands: tablet-encode --help tablet-encode --preset list tablet-encode input.avi output.avi tablet-encode --list file1.avi file2.avi file3.avi tablet-encode --preset best input.avi output.avi tablet-encode --preset best dvd://1 dvd://2 dvd://3 media/ As you can see from the above, there are a number of different ways of using tablet-encode, but the simplest is to give one existing movie (or URL) and the filename of the target: tablet-encode input.avi output.avi tablet-encode http://www.example.com/somefilm.mov output.avi tablet-encode dvd://1 output.avi The last of these has shown MPlayer's support for DVDs. tablet-encode will also auto-detect directories containing VIDEO_TS folders as DVDs, and if the title on the DVD is unspecified, the longest will be used: tablet-encode dvd: output.avi tablet-encode /media/dvd/ output.avi For TV series' DVDs, the '--episodes' option can be used. This will rip all episodes on the DVD within 10% of the middle-longest track (i.e. the median): tablet-encode --episodes dvd: /media/nokia-external/Video/ A number of presets are available. If none is specified, it defaults to "average". A full list of the presets can be seen by passing `list' to the --preset option: tablet-encode --preset list If the target of the encoding is a directory, multiple input files can be specified: tablet-encode file1.avi file2.mov file3.wmv output/ There are many more options, a full listing is provided in the online help: tablet-encode --help Running tablet-encode with no parameters will start a GUI version, if possible. A GUI progress bar can be shown when specifying arguments with the `--gui' option. This requires the Gtk2-Perl bindings to be installed. CONFIGURING The file `.tablet-encode.conf' will be read from your home directory at start up. In this file you can define your own presets, change the default preset used if none is specified and a few other things. To define your own preset, say "dvd", create ~/.tablet-encode.conf in your favourite editor and add the content: $PRESET{dvd} = { abitrate => 256, vbitrate => 800, width => 400 }; This will define a preset called 'dvd' with an audio bitrate of 256kbps, a video bitrate of 800kbps and a maximum width of 400 pixels. The height is auto-calculated based on the tablet's screen and the size of the input video. To use the 'dvd' preset instead of 'average' when no preset is specified, add the following line to ~/.tablet-encode.conf: $defaultPreset = 'dvd'; Note that this is a mini-Perl script, so blank lines and lines starting `#' will be ignored. All statements MUST end in a semi-colon, `;'. For Nokia 770 users, you may wish to always use 770-compatibility mode. To achieve this, in ~/.tablet-encode.conf put: $options{770} = 1; TROUBLESHOOTING Some users have reported harsh, white-noise on the output. There are three possible solutions: 1) Reconfigure mplayer to use the MAD audio decoder in preference to libmp3. See this post for more details: http://www.internettablettalk.com/forums/showthread.php?t=10471#post90550 2) If the audio track is already MP3, use the --copy-audio option to leave the audio unprocessed (this should happen automatically, if the existing audio is compatible with the selected preset). 3) If you are using a PowerPC Mac, try using a PowerPC-specific build of MPlayer, rather than a Universal binary. Similarly, some builds of MPlayer on PowerPC Linux have also reported the same problem; however upgrading to the latest MPlayer fixes that. KNOWN BUGS * GUI is currently very basic. No support for selecting DVD tracks etc. CHANGELOG v2.30 (07-Nov-2009) * Add subtitle support (provided by Claes Holmerson) * Ensure 48kHz MP3 audio streams are not copied, but transcoded (reported by spock) * Massively improve output quality (provided by takla) * Fix two-pass encoding. * Add very high quality "N900" preset. v2.20 (07-Sep-2008) * Fix support for VDR files with spaces in name. * Fix --episodes on ripped DVDs (reported by Wouter Lagerweij). * Fix use of exec() when doing final encoding. v2.19 (09-Jun-2008) * Fix bug when auto-identifying longest DVD title. * Fix mis-calculated median which will effect --episodes with low number of episodes + extra features on a DVD. * Add vrc_minrate as half output bitrate (suggested by Navi). * Better error reporting when mencoder is not installed or doesn't support appropriate codecs. * Fix GUI fatal error when trying to launch conversion (reported by Sebastiaan Lauwers). * Improve error reporting when using GUI. v2.18 (29-Mar-2008) * Handle bitrate reduction after mplayer fails to read bitrate correctly (provided by Mike Lococo) * Re-introduce 'mplayer' preset with very high bitrate (suggested by rm_you and GeneralAntilles) * Add --episodes option. When auto-detecting a DVD title to rip (i.e. the source is "dvd:"), all titles within 10% of the *median* will be ripped. * #1900: Add --770 option to improve Nokia 770 compatibility (reported by Marius Gedminas) * Add ability to add presets and change default preset using ~/.tablet-encode.conf. * #1760: Fix GUI problem on Mandriva 2008.0 (reported by divinerites). * Add support for Freevo FXD files, including --episodes for all videos defined in a video. * Recognise direct VOB access and turn into 'dvd:' (reported by GeneralAntilles). v2.17 (09-Mar-2008) * Use /dev/null and a named log file when in two-pass mode (suggested by Dave Coutts). * When using DVD auto-detection, select language based on first key in $LANG (requested by Luca Olivetti and Brad Midgley). v2.16 (15-Dec-2007) * Make --help work again when GUI is available (reported by Marius Scurtescu and Riptorn). v2.15 (11-Dec-2007) * Add an initial basic GUI version (requires Gtk2+ Perl bindings). * Improve identification of VDR recordings (provided by Luca Olivetti). * Don't upscale videos smaller than the preset (reported by Tesiph). * When listing presets, include details on output quality (suggested by Corey Wright). v2.10 (02-Dec-2007) * --mencoder arguments weren't passed through when getting media info (reported by Stefano Z.) * Fix "argument ... is not numeric" warning when checking audio type of QuickTime videos. * Add detection of DVD directories & configure mencoder appropriately (requested by Peter Flynn). * Overhaul presets (thanks to czr). * Add support for VDR recording directories (requested by Luca Olivetti). * Remove "experimental" mencoder options. * Add sharpening filter to output. * Remove '-noidx' option and use FMP4 FOURCC to get better performance (thanks to Jeff Elkins and Frederic Crozat). * Fix superfluous prints when using --quiet. * Auto-detect longest DVD track when 'dvd:' or 'dvd://' are specified as inputs (requires mplayer). v2.00 (17-Nov-2007) * Rename to tablet-encode. * Include optional "vrcbufsize" and "vrcmaxrate" (suggested by sveinan). * Limit video bitrate to maximum of preset and equivalent bitrate of original file, when applicable (provided by Benjamin R�veill�). * Do the same for audio (suggested by mplawner). * Modify "--sample" option to allow to chose sample length (provided by Benjamin R�veill�). * Add "--index" option to force index generation (provided by Benjamin R�veill�). * Add "--list" option to allow processing multiple files (provided by Benjamin R�veill�). * Add support for command lines like `cp', so that multiple files and a directory can be specified. * Bump up quality on good/best/mplayer presets. v1.36 (22-Oct-2007) * Fix bug when only mp3lame available (reported by Ryan Abel) v1.35 (26-Sep-2006) * Allow presets to specify a height to encode for, rather than a width. * Make `mplayer' preset maximum height at 240 and increase max fps (suggested by ssvb). v1.34 (21-Sep-2006) * Win32 Perl can have weird effects, try to avoid. v1.33 (21-Aug-2006) * Add "mplayer" preset for https://garage.maemo.org/projects/mplayer/ * Fix broken support for Windows (duh) v1.32 (30-Jul-2006) * Add new maximum frame rate, and allow presets to override. * Change "best" for maximum framerate. * Add support for ActiveState's Perl. v1.31 (05-Jul-2006) * Fix bug which resulted in incorrect resolution on very wide sources (e.g. 2.35:1 films) v1.30 (26-May-2006) * Add support for anamorphic data sources (e.g. DVDs) * Add ability to pass through options to mencoder, for example: 770-encode -m-aid -m128 dvd://4 mydvd.avi v1.21 (19-May-2006) * Add volume normalisation flag (suggested by Neil Jerram) v1.20 (15-May-2006) * Fix bug with rounding when optimising wider inputs * Add two presets ("average" and "good"), with thanks to varis * Add "--sample" option (suggested by varis) v1.11 (12-May-2006) * Enhance "smallest" to better fit 770 screen * Add "small" preset * Fix cropping which just didn't work in some instances v1.10 (07-May-2006) * More intelligent cropping. * Fall back to lavc MP3 encoder if mp3lame not present * Die if lavc isn't present * Suppress "Skipping frame!" messages from mencoder v1.05 (03-May-2006) * Make handle FLV files' dodgy framerate v1.00 (08-Apr-2006) * Initial version: first 770-based media encoder aimed to: a) Guarantee playable video b) Use presets c) Provide "optimised video" COPYRIGHT (c) Andrew Flegg 2006, 2007. Released under the Artistic Licence. tablet-encode-2.30/ARTISTIC0000644000175000001440000001446310713603332014516 0ustar andrewusersThe "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a. place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b. use the modified Package only within your corporation or organization. c. rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d. make other distribution arrangements with the Copyright Holder. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a. distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b. accompany the distribution with the machine-readable source of the Package with your modifications. c. give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d. make other distribution arrangements with the Copyright Holder. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End tablet-encode-2.30/tablet-encode0000755000175000001440000006241211275321252016004 0ustar andrewusers#!/usr/bin/perl -w # # Encode a video into a format suitable for a Nokia Internet Tablet. # (c) Andrew Flegg 2006-2009. Released under the Artistic Licence. # v2.30 http://mediautils.garage.maemo.org/ use strict; use warnings; use Getopt::Long; use File::Basename; use List::Util qw(max); use POSIX; use vars qw(%PRESET @PRESET_ORDER $CONFIGURE_FILE); # -- These can be overridden in .tablet-encode.conf... # my @cropLimit = (0.15, 0.2); my $idealRatio = 800/480; # i.e. 15/9 my $maxFps = 30; my $defaultPreset = 'average'; my @defaultArgs = (); # ...and this can be added to. %PRESET = ( smallest => { abitrate => 32, vbitrate => 80, width => 240, fps => 15 }, small => { abitrate => 96, vbitrate => 150, width => 240, fps => 15 }, average => { abitrate => 128, vbitrate => 350, width => 320 }, good => { abitrate => 160, vbitrate => 600, width => 352 }, best => { abitrate => 192, vbitrate => 768, width => 400, height => 240 }, mplayer => { abitrate => 192, vbitrate => 1200, width => 400, height => 240 }, n900 => { abitrate => 192, vbitrate => 2000, width => 800, height => 480 } ); $CONFIGURE_FILE = "$ENV{HOME}/.tablet-encode.conf"; our %options = (); Getopt::Long::Configure("bundling"); GetOptions(\%options, "help|?|h", "preset|p=s", "original-aspect|o", "two-pass|2", "index|i", "770|7", "copy-audio|c", "sample|s:i", "list|l", "episodes|e", "gui|g", "hq", "mencoder|m=s@", "subtitle|t:s", "quiet|q", ); if (-f $CONFIGURE_FILE) { my $conf = ''; open(IN, "<$CONFIGURE_FILE") or die "Unable to open $CONFIGURE_FILE: $!\n"; while() { $conf .= $_; } close(IN); eval($conf) or die "Error in configuration file: $@\n"; } $options{"preset"} ||= $defaultPreset; my $syntax = < tablet-encode [options] [...] tablet-encode [options] --list [ ...] EOM @PRESET_ORDER = sort { $PRESET{$a}->{vbitrate} <=> $PRESET{$b}->{vbitrate} } keys(%PRESET); my $guiAvailable = eval{require Gtk2; require Gtk2::Helper }; my $needHelp = ($options{"help"} or (@ARGV < 2 and not $options{'list'})); $needHelp = 0 if $options{"preset"} eq 'list'; die <.srt. -e, --episodes When auto-detecting DVD track, rip all episodes. -l, --list Specify that the arguments are a list of files to encode. Output file is input suffixed with preset. Please report bugs to . Thanks. EOM if ($options{"preset"} eq 'list') { my $detail = ''; foreach my $p (@PRESET_ORDER) { my $preset = $PRESET{$p}; $detail .= ' '.$p.(' ' x (16 - length($p))).' - '. $preset->{width}.'x'. int($preset->{height} || $preset->{width} / $idealRatio).' @ '. $preset->{vbitrate}.'kbps video, '. $preset->{abitrate}.'kbps audio ('. ($preset->{fps} || $maxFps).' fps)'. "\n"; } die "Available presets:\n$detail\n"; } die "mencoder is not installed or doesn't support lavc encoder\n" unless (&mencoderSupports('oac')->{'lavc'} || &mencoderSupports('oac')->{'mp3lame'}) && &mencoderSupports('ovc')->{'lavc'}; # -- Open the GUI if appropriate... # if ($guiAvailable and ($options{'gui'} or $needHelp)) { Gtk2->init; &openGui() if $needHelp; } die "GUI option not available. Check Gtk2-Perl is installed.\n" if !$guiAvailable and $options{'gui'}; # -- Create the conversion queue... # my $preset = $PRESET{$options{"preset"}} or die "Unknown preset.\n"; my @conversions = (); if (-d $ARGV[-1]) { my $target = pop @ARGV; foreach my $f (@ARGV) { push @conversions, &movieInfo({ input => [ $f ], output => $target.'/'.(fileparse($f))[0].'.avi' }); } } elsif ($options{'list'}) { foreach my $f (@ARGV) { push @conversions, &movieInfo({ input => [ $f ], output => (fileparse($f))[0].'.'.$options{"preset"}.'.avi' }); } } elsif (@ARGV == 2) { push @conversions, &movieInfo({ input => [ $ARGV[0] ], output => $ARGV[1] }); } else { die $syntax; } # -- Run the conversion for all the appropriate files... # warn "WARNING: Preset may be too high for Nokia 770.\n\n" if $options{'770'} and $preset->{vbitrate} > 600; my $progress = $options{'gui'} ? &openProgress(1) : undef; if ($progress) { Gtk2->main; } else { foreach my $info (@conversions) { &convert($info, $preset, $info == $conversions[-1]); } } exit; # ======================================================================= # convert - transcode a file # sub convert { my ($info, $preset, $exec) = @_; # -- Various options etc... # my $twoPass = defined($options{"two-pass"}); my $maxFps = $preset->{fps} || $maxFps; my $optimise = 1 unless defined($options{"original-aspect"}); # -- Now build up the command line... # my @params = (); push @params, '-o', $info->{output}; push @params, '-srate', 44100; push @params, '-aid', $info->{audioid} if $info->{audioid}; push @params, '-passlogfile', $info->{output}.'.two-pass-log' if $twoPass; # -- Downmix to mono if low audio rate... # my $af = 'volnorm=1'; if ($preset->{abitrate} < 64) { push @params, '-channels', 1; $af .= ',channels=1'; } # -- Audio/video encoding... # if ($options{'copy-audio'} or (($info->{aformat} || '') eq '85') && (($info->{abitrate} || 0) <= $preset->{abitrate}) && (($info->{asamprate} || 999999) <= 44100)) { push @params, '-oac', 'copy'; $af = ''; } elsif (&mencoderSupports('oac')->{'mp3lame'}) { push @params, '-oac', 'mp3lame', '-lameopts', 'vbr=0:br='.$preset->{abitrate}. ($preset->{abitrate} < 64 ? ':mode=3' : ''); } else { push @params, '-oac', 'lavc', '-lavcopts', 'acodec=mp3:abitrate='.$preset->{abitrate}; } push @params, '-af', $af if $af; # -- Work out the framerate... # my $ofps = $info->{framerate} || 0; $ofps /= 2 while $ofps > $maxFps; push @params, '-ofps', $ofps if $ofps; # -- Handle anamorphic DVDs... # my $anamorphic = 1; if ($info->{aspect} == 2) { $anamorphic = 4/3; } elsif ($info->{aspect} == 3) { $anamorphic = 16/9; } elsif ($info->{aspect} == 4) { $anamorphic = 2.11; } $info->{width} *= $info->{height} * $anamorphic / $info->{width} if $anamorphic != 1; # -- Optimise for target screen... # my $aspect = $info->{width} / $info->{height}; my $scale = $preset->{width} / $info->{width}; $scale = $preset->{height} / $info->{height} if ($aspect < $idealRatio) and $preset->{height}; my ($w, $h) = (&nearest($info->{width} * $scale), &nearest($info->{height} * $scale)); my ($targetWidth, $targetHeight) = ($preset->{width}, $preset->{height} || $preset->{width} / $aspect); # Don't upscale... if ($scale > 1) { ($w, $h) = (&nearest($info->{width}), &nearest($info->{height})); print "Changing target width/height to $w x $h to prevent upscaling of $scale.\n" unless $options{"quiet"}; ($targetWidth, $targetHeight) = ($w, $h); $scale = 1; } # Work out scaling/cropping factors... if ($optimise) { my ($cropWidth, $cropHeight); my $ratio = abs($aspect - $idealRatio) / $aspect; if ($aspect > $idealRatio) { # Too wide... print "Width needs trimming by $ratio from $w x $h\n" unless $options{"quiet"}; $ratio = $cropLimit[0] if $ratio > $cropLimit[0]; my $resultRatio = $info->{width} * (1 - $ratio) / $info->{height}; my $targetHeight = &nearest( $targetWidth / $resultRatio, 16 ); my $scale = $targetHeight / $info->{height}; ($w, $h) = (&nearest($info->{width} * (1 - $ratio) * $scale, 16), $targetHeight); ($cropWidth, $cropHeight) = (int($w / $scale), int($h / $scale)); } elsif (($aspect < $idealRatio) and $preset->{height}) { # Too tall, but we've got a maximum height... print "Height needs trimming by $ratio from $w x $h to ".$preset->{height}."\n" unless $options{"quiet"}; $ratio = $cropLimit[1] if $ratio > $cropLimit[1]; my $resultRatio = $info->{width} / ($info->{height} * (1 - $ratio)); my $targetWidth = &nearest( $targetHeight * $resultRatio, 16 ); my $scale = $targetWidth / $info->{width}; ($w, $h) = ($targetWidth, &nearest($info->{height} * (1 - $ratio) * $scale, 16)); ($cropWidth, $cropHeight) = (int($w / $scale), int($h / $scale)); } elsif ($aspect < $idealRatio) { # Too tall... print "Height needs trimming by $ratio from $w x $h\n" unless $options{"quiet"}; $ratio = $cropLimit[1] if $ratio > $cropLimit[1]; ($w, $h) = (&nearest($info->{width} * $scale, 16), &nearest($info->{height} * $scale, 16)); $h = &nearest($h * (1 - $ratio), 16); ($cropWidth, $cropHeight) = (int($w / $scale), int($h / $scale)); } push @params, '-vf-add', "crop=$cropWidth:$cropHeight" if $cropWidth and $cropHeight; } push @params, '-vf-add', "scale=$w:$h"; #push @params, '-vf-add', 'unsharp=c4x4:0.3:l5x5:0.5'; # -- Work out the video bitrate... # my $ovbitrate = $preset->{vbitrate}; if ($info->{format} =~ /^(DIVX|XVID|DX50|FMP4)$/i) { my $equivbitrate = int( ($info->{vbitrate} / ($info->{framerate} * $info->{width} * $info->{height})) * ($ofps * $w * $h) * 1.1 ); print "Equivalent bitrate + margin = $equivbitrate kbps\n" unless $options{"quiet"}; if ($equivbitrate <= $preset->{vbitrate}) { if (&nearest($info->{width}, 16) == $info->{width} and &nearest($info->{height}, 16) == $info->{height} and $info->{width} <= $w and $info->{height} <= $h) { print "Copying video stream.\n" unless $options{"quiet"}; $ovbitrate = undef; } else { print "Reducing output bitrate to match.\n" unless $options{"quiet"}; $ovbitrate = $equivbitrate if $equivbitrate; } } } # -- Insert video encoding options... # if ($ovbitrate) { push @params, '-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4:vbitrate='.$ovbitrate. ":aspect=$w/$h". ':turbo'. ($options{'hq'} ? ':mbd=2:v4mv:trell' : ''); } else { push @params, '-ovc', 'copy'; } # -- Miscellaneous options... # my $subFile = push @params, @{ $info->{args} }; push @params, '-ffourcc', ($options{'770'} ? 'DIVX' : 'FMP4'); push @params, '-forceidx' if defined($options{"index"}); push @params, '-force-avi-aspect', $w/$h; push @params, '-quiet' if $options{"quiet"}; push @params, '-endpos', ($options{"sample"} || 30) if defined($options{"sample"}); if (defined($options{"subtitle"})) { my $subFile = $options{"subtitle"}; if (!$subFile) { foreach my $inFile (@{ $info->{input} }) { $subFile = "$inFile.srt"; last if -f $subFile; ($subFile) = $inFile =~ /(.*?)\.[^\.]+/; $subFile = "$subFile.srt"; last if -f $subFile; $subFile = undef; } } push @params, '-sub', $subFile if $subFile; } # -- Execute it... # push @params, @{ $info->{input} }; print '+++ '.$info->{input}->[-1]."\n" if $options{"gui"}; print "Invoking (exec = $exec) mencoder ".join(" ", @params)."...\n" unless $options{"quiet"}; close(STDERR); if ($twoPass) { my @localParams = map { /^vcodec=/ ? "$_:vpass=1" : $_ } (@params); print "---> mencoder ".join(" ", @localParams)."\n" unless $options{'quiet'}; system('mencoder', @localParams); print "Pass 1 complete.\n" unless $options{"quiet"}; @localParams = map { /^vcodec=/ ? "$_:vpass=2" : $_ } (@params); print "---> mencoder ".join(" ", @localParams)."\n" unless $options{'quiet'}; system('mencoder', @localParams); unlink($info->{output}.'.two-pass-log'); } elsif ($exec) { exec('mencoder', @params); } else { system('mencoder', @params); } } # ======================================================================= # nearest - round to the nearest multiple # sub nearest() { my ($num, $multiple) = @_; $multiple ||= 16; return int(0.5 + $num / $multiple) * $multiple; } # ======================================================================= # movieInfo - get movie info # sub movieInfo() { my %info = %{$_[0]}; $info{args} = $options{'mencoder'} || \@defaultArgs; my @result = ( \%info ); # -- Fix output filename... # $info{output} =~ s/\bdvd\:/dvd/; # -- Adapt to DVD directories and VDR/Freevo recordings... # my $file = $info{input}->[0]; $file =~ s!/+$!!; $file =~ s!/VIDEO_TS/.*$!!; if (-d "$file/VIDEO_TS") { print "$file is a DVD.\n" unless $options{"quiet"}; push @{ $info{args} }, "-dvd-device", $file; $info{input}->[0] = 'dvd:'; } elsif (-f "$file/info.vdr" or $file =~ s/(^|\/)info\.vdr$/$1/i) { print "$file is a VDR recording.\n" unless $options{"quiet"}; opendir(DIR, $file) or die "Unable to open directory '$file': $!\n"; @{ $info{input} } = sort map { "$file/$_"} grep { m!^\d{3}\.vdr$! } readdir(DIR); closedir(DIR); #use Data::Dumper; print Dumper(\%info); } elsif ($file =~ /\.fxd$/) { print "$file is Freevo meta-data.\n" unless $options{"quiet"}; my $data = \%info; my $count = 2; open(IN, "<$file") or die "Unable to read $file: $!\n"; while() { if (/<(file|url)[^>]*>(.*?)<\//) { my $type = $1; push @result, $data if $data != \%info; my $url = $2; $url = dirname($file).'/'.$url if $type eq 'file' && $url !~ /\//; $data->{input} = [ $url ]; last unless $options{episodes}; $data = { %info }; $data->{output} = $1.'-'.$count++.'.avi' if $data->{output} =~ /^(.*)\.\w+/; } } close(IN); } # -- Find DVD info... # die "No input information to process\n" unless @{$info{input}}; if ($info{input}->[0] =~ /^dvd:(\/\/)?$/) { print "Getting DVD info...\n" unless $options{"quiet"}; my $args = join " ", map { $^O eq 'MSWin32' ? "\"$_\"" : quotemeta($_) } @{ $info{args} }; my @dvd = `mplayer -identify dvd:// $args -endpos 0 -vo null -ao null 2>&1`; my %lengths = map { /^ID_DVD_TITLE_(\d+)_LENGTH=(\d+)/; $1 || '_', $2 || '0' } @dvd; my %audio = map { /^ID_AID_(\d+)_LANG=(\w+)/; ($1 || '0', $2 || '_' ) } @dvd; delete $lengths{'_'}; my @lengthsInOrder = sort { $lengths{$b} <=> $lengths{$a} } keys(%lengths); my $median = $#lengthsInOrder % 2 ? ($lengths{$lengthsInOrder[($#lengthsInOrder - 1)/2]} + $lengths{$lengthsInOrder[1+($#lengthsInOrder-1)/2]}) / 2 : $lengths{$lengthsInOrder[$#lengthsInOrder / 2]}; my ($lang) = ($ENV{LANG} || '') =~ /^([a-z]+)/; $info{audioid} = (grep { $audio{$_} eq $lang } keys(%audio))[0]; # Find tracks +-10% of median if --episodes specified, otherwise longest. if ($options{'episodes'}) { my $data = \%info; foreach my $track (@lengthsInOrder) { if (abs($lengths{$track} - $median)/$median < 0.1) { $data->{output} = $1.'-'.substr("0$track", -2).'.avi' if $data->{output} =~ /^(.*?)(-\d+)?\.\w+$/; push @result, $data if $data != \%info; print "Track $track is within 10% of $median\n" unless $options{'quiet'}; $data->{input} = [ "dvd://$track" ]; $data = { %info }; } } } else { my $longest = $lengthsInOrder[0]; print "Longest DVD track: $longest\nPreferred language: $lang\n" unless $options{"quiet"}; $info{input} = [ "dvd://$longest" ]; } } # -- Find media info... # my $args = join " ", map { $^O eq 'MSWin32' ? "\"$_\"" : quotemeta($_) } @{ $info{args} }; if ($^O eq 'MSWin32') { my $files = join " ", map { "\"$_\"" } @{ $info{input} }; $_ = `mplayer $args -endpos 0 -vo null -ao null -identify $files 2>&1` . `mencoder $args -endpos 0 -oac copy -ovc copy -o nul: $files 2>&1`; } else { my $files = join " ", map { quotemeta($_) } @{ $info{input} }; $_ = `mplayer $args -endpos 0 -vo null -ao null -identify $files 2>&1` . `mencoder $args -endpos 0 -oac copy -ovc copy -o /dev/null $files 2>&1`; } # -- Read info and populate details... # ($info{format}, $info{width}, $info{height}, $info{framerate}, $info{vbitrate}, ) = m{^VIDEO:\s* \[?(\w+)\]?.*? (\d+)x(\d+).*? ([\d\.]+)\s*fps.*? ([\d\.]+)\s*kbps }mx; $info{width} ||= $1 if /^VO:.*? => (\d+)x\d+/m; $info{height} ||= $1 if /^VO:.*? => \d+x(\d+)/m; $info{framerate} ||= $1 if /^ID_VIDEO_FPS=([\d\.]+)/m; $info{format} ||= 'unknown'; ($info{asamprate}) = m{^AUDIO:\s* (\d+)\s*Hz }mx; $info{asamprate} = $1 if /^audiocodec:.* rate=(\d+)/m; $info{abitrate} = $1 / 1000 if /^ID_AUDIO_BITRATE=(\d+)/m; $info{aformat} = $1 if /^ID_AUDIO_FORMAT=(\w+)/m; $info{asamprate} = $1 if /^ID_AUDIO_RATE=(\d+)/m; $info{aspect} = $1 if /^VIDEO:.*?\(aspect\s+(\d+)\)/m; $info{aspect} ||= 1; # If it's a Flash Video with a dodgy framerate, guess (badly)... $info{framerate} = 28 if $info{format} =~ /^FLV/ and $info{framerate} >= 1000; # -- Copy info data to the other files, if any... # foreach my $result (@result) { while(my ($k, $v) = each(%info)) { $result->{$k} ||= $v; } } #use Data::Dumper; print Dumper(\@result); die "Unable to get movie info.\n" unless $info{width} and $info{height}; return @result; } # ======================================================================= # mencodeSupports - return a hash of mencoder encoders # sub mencoderSupports { my ($type) = @_; my $list = `mencoder -\Q$type\E help 2>&1`; my %data = ($list || '') =~ /^ (\w+)\s*-\s*(.*)$/mg; return \%data; } # ======================================================================= # openGui - open a GUI interface # sub openGui { my $window = Gtk2::Window->new('toplevel'); $window->signal_connect(destroy => sub { Gtk2->main_quit; }); $window->set_title('tablet-encode'); $window->set_border_width(10); $window->set_resizable(0); $window->add(my $widgets = Gtk2::VBox->new); $widgets->add(my $options = Gtk2::Table->new(3,3)); $options->set_col_spacings(5); $options->set_row_spacings(5); $options->attach_defaults(&right(Gtk2::Label->new('Input:')), 0, 1, 0, 1); $options->attach_defaults(my $inputText = Gtk2::Entry->new, 1, 2, 0, 1); $options->attach_defaults( my $openButton = Gtk2::Button->new_from_stock('gtk-open'), 2, 3, 0, 1 ); $openButton->signal_connect(clicked => sub { my $result = &fileChooser('open'); $inputText->set_text($result) if $result; }); $options->attach_defaults(&right(Gtk2::Label->new('Destination:')), 0, 1, 1, 2); $options->attach_defaults(my $outputText = Gtk2::Entry->new, 1, 2, 1, 2); $options->attach_defaults( my $saveButton = Gtk2::Button->new_from_stock('gtk-save'), 2, 3, 1, 2 ); $saveButton->signal_connect(clicked => sub { my $result = &fileChooser('save'); $outputText->set_text($result) if $result; }); $options->attach_defaults(&right(Gtk2::Label->new('Preset:')), 0, 1, 2, 3); $options->attach_defaults(my $preset = Gtk2::ComboBox->new_text, 1, 3, 2, 3); my $count = 0; foreach my $p (@PRESET_ORDER) { $preset->append_text($p); $preset->set_active($count) if $p eq 'average'; $count++; } $widgets->add(my $buttonBar = Gtk2::HBox->new); $buttonBar->add(my $cancel = Gtk2::Button->new_from_stock('gtk-quit')); $cancel->signal_connect(clicked => sub { $window->destroy }); $buttonBar->add(my $button = Gtk2::Button->new('Convert')); $button->signal_connect(clicked => sub { eval { my $progressId = &openProgress; unless ($progressId) { print "$$ - Starting conversion...\n"; &convert(&movieInfo({ input => [ $inputText->get_text ], output => $outputText->get_text }), $PRESET{$preset->get_active_text}, 0); _exit(0); } }; if ($@) { warn "$$ - Error: $@\n"; my $dialog = Gtk2::MessageDialog->new($window, 'modal', 'error', 'cancel', "Error: $@"); my $response = $dialog->run; $dialog->destroy; _exit(1); } }); $window->show_all; Gtk2->main; exit; } # ======================================================================= # fileChooser - show a file open/save dialogue box # sub fileChooser { my ($type) = @_; my $result = undef; my $videoFilter = Gtk2::FileFilter->new; $videoFilter->set_name('Video files'); $videoFilter->add_mime_type('video/*'); my $allFiles = Gtk2::FileFilter->new; $allFiles->set_name('All files'); $allFiles->add_pattern('*'); my $file = Gtk2::FileChooserDialog->new(ucfirst($type).' file', undef, $type, 'gtk-cancel' => 'cancel', 'gtk-ok' => 'ok', 'Rip DVD' => 'help'); $file->add_filter($videoFilter); $file->add_filter($allFiles); my $action = $file->run; if ($action eq 'ok') { $result = $file->get_filename; } elsif ($action eq 'help') { # TODO Pop up title selection dialogue. $result = 'dvd:'; } $file->destroy; return $result; } # ======================================================================= # openProgress - open a progress dialogue # sub openProgress { my $quitAfter = shift; my $progress = Gtk2::Window->new('toplevel'); $progress->signal_connect(destroy => sub { print "Cancelling conversion currently unsupported.\n"; }); $progress->set_title('Converting...'); $progress->set_border_width(10); $progress->set_resizable(0); $progress->set_modal(1); $progress->{quitAfter} = $quitAfter; $progress->add($progress->{bar} = Gtk2::ProgressBar->new); $progress->{bar}->set_text(''); $progress->{bar}->set_fraction(0.0); $progress->show_all; $SIG{CHLD} = sub { &REAPER($quitAfter) }; if ($progress->{child_pid} = open my $pipe, '-|') { $progress->{tag} = Gtk2::Helper->add_watch( fileno($pipe), in => sub { if (eof($pipe)) { Gtk2::Helper->remove_watch($progress->{tag}); close($pipe); $progress->destroy; _exit(0) if $progress->{quitAfter}; } else { my $data = ''; my $length = sysread($pipe, $data, 1024); $_ = substr($data, 0, $length); print; if (/.*Pos:\s*(\d+\.?\d*)s\s*(\d+)f\s*\(\s*(\d+)\%\).*Trem:\s*(\d+\w+)\s*(\d+mb)/) { my $pos = $3 / 100; $pos = 0 if $pos < 0; $pos = 1 if $pos > 1; $progress->{bar}->set_text(($progress->{file} || '')." ETA: $4"); $progress->{bar}->set_fraction($pos); } elsif (/\+\+\+ (.*)\n/) { $progress->{file} = (fileparse($1))[0]; } } 1; }); } else { $| = 1; $progress = undef; } return $progress; } # ======================================================================= # REAPER - a reaper of dead children/zombies with exit codes to spare # sub REAPER { my $quitAfter = shift; my $stiff; while (($stiff = waitpid(-1, &WNOHANG)) > 0) { _exit(0) if $quitAfter; } $SIG{CHLD} = \&REAPER; } # ======================================================================= # right - right-align a Gtk+ widget # sub right { my $widget = shift; my $alignment = Gtk2::Alignment->new(1, 0.5, 0, 0); $alignment->add($widget); return $alignment; }