Batch conversion using CLI via Perl or Shell script??

Discussion of the HandBrake command line interface (CLI)
Forum rules
An Activity Log is required for support requests. Please read How-to get an activity log? for details on how and why this should be provided.
jjwatmyself
Posts: 14
Joined: Thu Dec 18, 2008 5:27 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by jjwatmyself »

I have be doing this in Vista with scripting and most of this will easily translate to a shell script. There are 2 scripts... a parent and a sub-script. This process will convert to a .m2ts with 1250 bitrate H.264 and AC3 pass-through. It isn't perfected but I am using it on a large quantity of rips with success. The translation to UNIX is very simple, so I don't think you need my help on that. I think the advantage to this is that you are able to control the movies individually. Global options are stored in convertmovies.cmd and movie specific options are specified by the variable %extra%. This is useful when the endode will vary from one movie to another, ex: which title. I have lots of UNIX scripting experience, so let me know if anyone needs help UNIXifying it.

masterscript.cmd

Code: Select all

@echo off
cd /d E:\Videos\H.264

set extra=-t 1
set indir="F:\Movies\MEMORY"
set movie=Memory - DVD
call convertmovies.cmd > "Memory.log" 2>&1

set extra=-L
set indir="F:\Movies\HarryPotter"
set movie=Harry Potter 4 - And The Goblet Of Fire - DVD
call convertmovies.cmd > "Harry Potter 4 - And The Goblet Of Fire.log" 2>&1
convertmovies.cmd

Code: Select all

set basename=E:\Videos\H.264\%movie%
set outfile="%basename%.mkv"
set chapfile="%basename%.csv"
set metafile="%basename%.meta"
set outfile2="%basename%.m2ts"

echo indir=%indir%
echo outfile=%outfile%
echo chapfile=%chapfile%
echo metafile=%metafile%
echo outfile2=%outfile2%
echo extra=%extra%
echo **********************************

echo Using %indir% to create %outfile%

"C:\Program Files\HandBrake\HandBrakeCLI.exe" -i %indir% -o %outfile% --crop 0:0:0:0 -e x264 --decomb -E ac3 -p -b 1250 -2 -T -x level=41:me=umh -U -F -v %extra%
echo **********************************

echo Creating %metafile%
echo MUXOPT --no-pcr-on-video-pid --new-audio-pes --vbr  --vbv-len=500 > %metafile%
echo V_MPEG4/ISO/AVC, %outfile%, insertSEI, contSPS, track=1, lang=eng >> %metafile%
echo A_AC3, %outfile%, track=2, lang=eng >> %metafile%
echo **********************************
echo Creating %outfile2%
"C:\Program Files\tsMuxeR\tsMuxeR.exe" %metafile% %outfile2%
echo **********************************
del /q %outfile%
del /q %metafile%
SnorreSelmer
Posts: 31
Joined: Thu Aug 14, 2008 7:02 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by SnorreSelmer »

New version of my script is out!

New in this version:
- Universal is now the preset of choice.
- Video-encoding is no longer deinterlaced, it's decombed and IVTC'ed for better image quality.
- Added new command-line option: -a
Uses the audio-track given as a parameter to -a (if -a is not given, the script defaults to track 1 as is default for the Universal preset).
Usage: hb.sh -i ~/Stargate_SG-1/ -a 2 will encode the two audio-tracks (2-ch AAC and multi-channel AC-3) from audio-track 2.

Code: Select all

#!/bin/sh

###############################################################################
# Shellscript : hb.sh - Batch-encoder script for HandBrakeCLI
# Author      : Snorre Selmer <snorre.selmer@gmail.you-know-the-rest>
# Date        : 2008-12-24
# Requires    : HandBrakeCLI, awk, sed
###############################################################################
# Description:
# This script does recursive scanning of a given folder and encodes all titles
# that are within an optionally given minimum and maximum length, and outputs
# the resulting files into an optionally given folder.
###############################################################################
# Cudos:
# - First of all, big thanks to the HandBrake team for making the most awesome
#   MP4-encoder I've ever used.
# - Second thanks goes to the HandBrake CLI-forum (http://forum.handbrake.fr)
#   and especially ronnor for making the script I used as a base for this one.
#   I learned a lot from "disassembling" your script.
# - The SED and AWK tutorials at http://www.grymoire.com/Unix/index.html were
#   a great help in understanding ronnor's script.
# - Finally, http://www.shelldorado.com/goodcoding/cmdargs.html is where I
#   got the code for the commandline arguments. Excellent shell-script site!
###############################################################################
# Disclaimer:
# I give no guarantees that this script will work on your system. It works on
# mine (GNU/Linux Ubuntu 8.10 x86_64 with HandBrakeCLI 0.9.3 and Apple OSX
# 10.5.6) and that's the only place I've been able to test it so far. If you
# find a bug, let me know on the HandBrake forum at
# http://forum.handbrake.fr/viewtopic.php?f=10&t=5070
# and we can look at it.
# DO NOT E-MAIL ME BUGS! Bugs are best squashed when many can look at them,
# so use the forum!
###############################################################################
# Todo:
# - Find and eliminate the cause of the "Segmentation fault" errors
# - Sort out a command-line argument to enable deinterlacing
# - Sort out a command-line argument to select presets
# - Space for sale, user-input required
###############################################################################

#basic program-info stuff
name=`basename "$0"`
version='0.4.1'

#path to the HandBrakeCLI binary
CLIpath=~/HandBrakeCLI

#default minimum title-time (in minutes) to encode
longerthan=0

#default maximum title-time (in minutes) to encode (default = 24 hours)
shorterthan=1440

#the folder you want to scan for DVDs to encode
input=

#the folder you want to store the encoded files in (default is the folder you're in when you run the script)
output=.

#title-duration check-flag
check="n"

#audio-track to be processed
audio=1

#function that prints usage-instructions if the user input something wrong
Usage () {
   echo >&2 "$name - HandBrakeCLI batch-script, v$version
usage: $name -i PathToDVDs [-o PathToSaveFolder] [-l MinimumTitleTimeToEncode] [-s MaximumTitleTimeToEncode]
    -i:  path to scan for VIDEO_TS folders.
    -o:  path to where you want to store the finished encodes.
           Default: the current folder (./)
    -l:  only encode titles that are longer than this (in minutes).
           Ex: \"-i 30\" will only encode titles longer than 30 minutes.
           Can be used in conjunction with -s.
    -s:  only encode titles that are shorter than this (in minutes).
           Ex: \"-s 30\" will only encode titles shorter than 30 minutes.
           Can be used in conjunction with -l.
    -a:  audio-track to be used.
           Default: 1
    -c:  scans the input-path, checks and prints out the length of the titles (in minutes).
           Can be used with -l and -s, but -o has no meaning.

Example:
$name -l 30 -s 60 -i Scrubs -o /home/username/mp4

This will scan the subfolder Scrubs and encode all titles that are longer than
30 minutes and shorter than 60 minutes, and store them in /home/username/mp4.

Input- and output-paths can be either relative or absolute (ie. Scrubs, ../Scrubs or /path/to/Scrubs).
"
   exit 0
}

BadArg() {
   echo >&2 "Invalid argument.
Try \"$0 -h\" for more information"
   exit 0
}

#command-line argument parser
while [ $# -gt 0 ]
do
   case "$1" in
   -i)   input="$2"; shift;;
   -o)   output="$2"; shift;;
   -l)   longerthan="$2"; shift;;
   -s)   shorterthan="$2"; shift;;
   -a)   audio="$2"; shift;;
   -h)   Usage;;
   -c)   check="y";;
   -*)   BadArg;;
   esac
   shift
done

#test to make sure the user gave an input-path (the minimum required to successfully run the script)
if [ "${input}" = "" ]
   then echo "This script requires that you atleast give it an input-path.
Try \"$0 -h\" for more information"
   exit 0
fi

export longerthan
export shorterthan

#scans the input-path for VIDEO_TS folders
for i in $(find $input -type d -iname video_ts) ; do

#this names the filename after it's parent folder
   filename=$(echo $i | sed 's/[/]/ /g' | awk '{print $(NF-1)}')

   if [ $check = "y" ]
      then

#scans all the titles in the DVD $i, scrapes out the length in seconds and prints title duration (in minutes)
      echo "$filename"
      $CLIpath -t 0 -i $i -L 2>&1 | grep "has length" | sed 's/sec//' | sed 's/[()]//g' | awk '$8 >= (60 * ENVIRON["longerthan"]) && $8 <= (60 * ENVIRON["shorterthan"]) {print " " $2 " " $5 " is " $8/60 " minutes long"}'
   fi

   if [ $check = "n" ]
      then
#scans all the titles in the DVD $i, scrapes out the length in seconds and compares them to $longerthan and $shorterthan
      for title in $($CLIpath -t 0 -i $i -L 2>&1 | grep "has length" | sed 's/sec//' | sed 's/[()]//g' | awk '$8 >= (60 * ENVIRON["longerthan"]) && $8 <= (60 * (ENVIRON["shorterthan"])) { print $3 "-" $5 }   ') ; do

#this names the title for the output file
      titlenum=$(echo $title | cut -f 2 -d '-')

#this executes the HandBrakeCLI
#you can change the preset or any other variables here
      $CLIpath -i $i -o ${output}/${filename}-title${titlenum}.m4v -t ${titlenum} -Z "Universal" --detelecine --decomb -a $audio,$audio
      done
   fi
done
ccjensen
Posts: 48
Joined: Tue Jun 03, 2008 11:09 am

Re: Batch conversion using CLI via Perl or Shell script??

Post by ccjensen »

Hi Snorre,

One directory with spaces, one where the spaces have been replaced by dots ('.'):

Code: Select all

drwx------  5 ccj  staff  170 17 Sep 19:13 The Lord of the Rings; The Return of the King (2003)
drwx------  5 ccj  staff  170 28 Mar  2008 The.Lord.of.the.Rings;The.Fellowship.of.the.Ring.(2001)
Tried using your script, but it seems to not like spaces in the directories of the films:

Code: Select all

mbp-ccj:~ ccj$ hb ~/Movies -o ~/Movies -c
Movies
Lord
of
the
Rings;
The
Return
of
the
King
(2003)
The.Lord.of.the.Rings;The.Fellowship.of.the.Ring.(2001)
I ctrl+c'd the script at this step, as it seemed to be accepting the fellowship of the ring, and started transcoding it.

A bit annoying that it does not allow spaces, or am I just being a moron and missing something obvious?
Also, I don't quite get what the -c flag is supposed to do :)

Thanks
SnorreSelmer
Posts: 31
Joined: Thu Aug 14, 2008 7:02 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by SnorreSelmer »

Yes, the script can't handle spaces in folder-names atm.. I'm not really sure how to handle it in the script, but it's on the list of things I'd like to fix eventually.

The -c option shows you the length of all the titles on the disc(s) so that you can tweak the -l and -s options (most useful with TV-series).
No Toque
Posts: 1
Joined: Tue Mar 10, 2009 4:06 am

Re: Batch conversion using CLI via Perl or Shell script??

Post by No Toque »

I wrote a handy PowerShell script for any Windows people out there.

I use it for doing batch conversions of Tivo recordings. Just change the variables at the top to suit your input and output folders and replace the $Preset variable with whatever command line settings you use. Be aware that PowerShell uses the backtick (same as ~ key) as the escape character to work around the quote marks.

I use VideoReDo to edit out the commercials and to change the .tivo file name to a .mpg. Then I dump all the edited files into the "Ad-Scanned" folder and run the script by opening a PowerShell prompt, changing to the directory where the HandBrake.ps1 file is stored and execute it by typing ".\Handbrake.ps1"

It basically just does a DIR on any .mpg files in the source folder, then runs the CLI repeatedly on every file name found in the folder.

Code: Select all

#HandBrake.ps1
# Grab all .mpg files in the "Ad-Scanned" folder and have HandBrake
# convert them to PS3 compatible .mp4 files in the "_PS3" folder.


$HandBrake = "HandBrakeCLI.exe"
$PathIn = "`"E:\Video\Ad-Scanned\"
$PathOut = "`"E:\Video\_PS3\"
$Preset = "--preset=`"PS3`""
$List = Get-ChildItem E:\Video\Ad-Scanned -filter "*.mpg" -name
$NumberOfFiles = (Get-ChildItem E:\Video\Ad-Scanned -filter "*.mpg").Count

foreach ($Item in $List)
{
    $FileIn = $Item
    $FileOut = $FileIn.Replace('.mpg', '.mp4')
    #write-host $HandBrake "-i" $PathIn$FileIn`" "-o" $PathOut$FileOut`" $Preset
    & $HandBrake "-i" $PathIn$FileIn`" "-o" $PathOut$FileOut`" $Preset
}
xJ5x
Posts: 2
Joined: Mon May 04, 2009 2:37 am

Re: Batch conversion using CLI via Perl or Shell script??

Post by xJ5x »

I have had success with dealing with spaces in filenames using this as the loop command and to set the filename variable:

Code: Select all

#scans the input-path for VIDEO_TS folders
find $input -type d -iname video_ts | while read i ; do

#this names the filename after it's parent folder
   filename=$(echo "$i" | awk -F '/' '{print $(NF-1)}')
However, when I run the script with -c to check all the titles, I get a bus error after some number (it varies) of the folders have been read. I am not sure if this is related to the changes I have made or some other problem.
SnorreSelmer
Posts: 31
Joined: Thu Aug 14, 2008 7:02 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by SnorreSelmer »

Might be your modifications. I have used the -c option on the entire X-Files (nine seasons of 5-6 discs) without problems before.
Just to be sure I'm not talking BS, at what range do you get problems? 10+ discs? 20+?
xJ5x
Posts: 2
Joined: Mon May 04, 2009 2:37 am

Re: Batch conversion using CLI via Perl or Shell script??

Post by xJ5x »

Not very many... after just a few discs it errors out. It may be something peculiar to my install. Did you try the changes I posted to see how they work for you?
fred_be9300
Posts: 13
Joined: Thu May 07, 2009 10:04 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by fred_be9300 »

on the issue of handling spaces in names: something like this should work:

Code: Select all

IFS_SAVED="$IFS"
IFS=$'\n'
for i in `find ...........`
do  
   echo "[$i]";
   #remember to always use "$i", never $i unquoted
done
IFS="$IFS_SAVED"
jfnewell
Posts: 4
Joined: Fri Aug 28, 2009 6:19 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by jfnewell »

Hi all--

this is a really simple script that I use to check if a file has been converted or not and then convert it based on a search for .iso files...

1. Searches for all .iso files in the source path. Then,
2. one by one it runs the handbrake command line on it, if a log file doesnt exist.
3. once it converts it creates a .txt log file that contains the progress info. Probably could pipe debug info into it as well...

This works marvels for me. I just start it and let it run for days churning on my files to be converted.

The only complain "request" I have is that if you want multiple audio streams you have to specify and can't just say grab all of them...unless someone knows otherwise? If you specify multiple and there are fewer than specified then CLI fails and moves on. In that case you have to go in and remove the .txt file to have it convert next time you start the script....

PATH=%PATH%;"c:\program files (x86)\handbrake2\"
SET SOURCE=z:\movies\
SET DEST=z:\transport\
SET LOCAL=c:\movies\
mkdir %dest%
echo on
For /r %source% %%1 in (*.iso) do if NOT exist "%source%%%~n1\%%~n1.txt" HandBrakeCLI.exe -i "%%1" -t 1 -o "%dest%%%~n1.mkv" -f mkv -m -p -P -5 -d -a 1 -E ac3 -9 -e x264 -q 0.65 -6 dpl2 -D 1.5 -2 -T -x ref=2:bframes=2:me=umh >> "%source%%%~n1\%%~n1.txt"
knation
Posts: 1
Joined: Thu Sep 24, 2009 4:44 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by knation »

Hi All,

I've been working on a Perl wrapper to encode all of my raw DVDs and have a project on Google Code for it: http://code.google.com/p/handbrakecli-massencode/

Currently, it only works with raw DVD files. I've been using it for the past few months in the following manner: copy raw DVDs to hard disk using DVDFab then have a Windows scheduler task run each night to iterate through all DVDs and encode them, deleting the raw files. The obvious next step is to make it work on any media type, not just DVDs.

Any feedback is appreciated!
cmonkey
Posts: 1
Joined: Tue Nov 10, 2009 3:03 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by cmonkey »

Here's a quick perl script that batch rips files.

I've been ripping my DVD library into .mkv's for Plex.

The general setup is this, I have a big HD full of VIDEO_TS folders that uses the following structure:

>Hard Drive
>>Movie Name
>>>VIDEO_TS
>>Movie Name
>>>VIDEO_TS
>>Movie Name
>>>VIDEO_TS
etc...

I give the script a fileIn and then define a fileOut. The script goes through the target directory, lists all the contents and then batch converts. The script is NOT recursive so it does not go deeper then the root level of the fileIn directory. Wouldn't recommend keeping any other stuff in that target directory 'cause I'm not sure what will happen if you do.

All of the user variables are defined at the head of the script. Fairly self explanatory. If you can't follow basic unix commands or file paths you might want to reconsider using this script.

The perl script has some of the more basic rip variables included (the one's that I use at least) and it's a fairly simple matter at add additional ones. In addition there's an option to create a folder based on the name of the ripped file and move the rip. Also generates a log file for the entire process.

Code: Select all

#!/usr/bin/perl

###############################################################################
# perl script : HBbatch_rip.pl - Batch-encoder script for HandBrakeCLI
# Author      : Craig Lyn
# Date        : 11-10-2009
# Requires    : HandBrakeCLI
###############################################################################
# Description:
# This script scans the contents of a directory and then batch encodes each
# enclosed VIDEO_TS file into a user defined format. There is an option to move
# the output into a directory based on the name of the file. The script also
# generates a time/date stamped log to plot the progress of long rips.
###############################################################################
# Disclaimer:
# I don't have much time to support this script so it's released as is. If you
# have difficulites with tasks such as file paths or basic Unix command line
# skills I would recommend NOT using this script. For now I've only put in the
# user defined variables that I use the most.

# For the log file name OSX does not allow ":" in filenames and instead subsitutes
# "/" for H:M:S separators.
###############################################################################
# Todo:
# - add additional user defined batch variables
# - script is having issues dealing with apostrophes " ' " in file names
# - does not like simlinks for some strange reason
###############################################################################

########## timestamp ###############

$starttime = timestamp();

######### user variables ###########

# path to the directory on the hard drive where the ripped DVDs are stored
$fileIn = '/Volumes/RAID\ 1/input';     # path to VIDEO_TS files
$fileOut = '/Volumes/Raid\ 1/output';   # output directory for ripped files

$logfile = "/Volumes/RAID\ 1/output/$starttime HBbatch log.txt"; # define a path for the output log and give it a name

# Turn on Ripping; Turn on moving
$do_rip = 1;                            # on/off rip the files with HandBrakeCLI
$do_move = 1;                           # on/off create a directory for the ripped movie and then move the ripped file

# array of the names of all of the .mkv files
@targetfile = `ls $fileIn`;

# number of elements in the array
$arraysize = @targetfile;

# Handbrake Variables
$verbose = 0;				# -v turn on verbosity level from 0-2

$title = 1;				# -t select the title from the DVD to encode.

$chap_start = 1;			# chapter to start ripping
$chap_end = 1;				# chapter to end ripping
$chapters = "$chap_start-$chap_end";	# -c default is to encode all but will have to remove flag from command line

$format = "mkv";                       	# -f output format: avi mp4 m4v ogm ogg mkv
$markers = 1;                           # -m turn chapter markers on or off

$encoder = "x264";                      # -e encoders: ffmpeg xvid x264 theora
$bitrate = 2000;                        # -b ouput video bitrate
$twopass = 1;                           # -2 turn two pass encoding on/off
$turbo = 1;                             # -T turn on speedbost for first pass encoding

$audiotrack = 1;			# -a select audio track
$aencoder = "ac3";                      # -E audio encoders; faac lame vorbis ac3
$pixelratio = 1;                        # -p store pixel aspect ratio in the video stream

$decomb = 1;                            # -5 turn decomb (interlacing filter) on/off

$fsubtitle = 1;                         # -F turn on/off forced subtitling

########### create log file #############

open (MYFILE, ">$logfile");
print MYFILE "Batch conversion started: $starttime \n \n";
close (MYFILE);

########### run loop #############
print "\nThe following directories will be ripped: \n";
print "@targetfile\n";
print "Please type 'go' and hit Return to start the batch conversion: \n";

# STDIN takes the command line input
$go = <STDIN>;

# chomp removes the end carridge return and end space from the inputs
chomp $go;

    print "Batch rip launched: $timestamp \n \n";

	if ($go eq "go")        
	{
	    for ($i=0; $i<=$arraysize-1; $i++)
		{
                    if ($do_rip eq "1")
                        {    
			# write to logfile start time
			$currenttime = timestamp();
			open (MYFILE, ">>$logfile");
			$counter = $i+1;
			print MYFILE "$counter of $arraysize - $targetfile[$i]\n";
			print MYFILE "$currenttime: rip started\n";
			close (MYFILE); 
			
			print "$currenttime: rip started $targetfile[$i]\n";
								
			chomp $targetfile[$i];
				
			system("HandBrakeCLI -i $fileIn/'$targetfile[$i]' -o $fileOut/'$targetfile[$i]'.$format -f $format -v $verbose -a $audiotrack -t $title -c $chapters -e $encoder -b $bitrate -2 $twopass -T $turbo -m $markers -E $aencoder -p $pixelratio -5 $decomb -F $fsubtitle");
				
			$currenttime = timestamp();
			print "$currenttime: Rip completed $targetfile[$i]\n \n";
				
			# write to logfile end time
			open (MYFILE, ">>$logfile");
			print MYFILE "$currenttime: rip completed\n \n";
			close (MYFILE); 
                        }
                        
			
                    if ($do_move eq "1")
                            
			{
			chomp $targetfile[$i]; # remove carrige return from ls command if any

			# create directory for each $targetfile
			print "directory created for '$targetfile[$i]'\n";
			system ("mkdir $fileOut/'$targetfile[$i]'"); # the 2 single quotes ' ' treats entire string as one without whitespace
                        
			# move target file into destination directory
			system ("mv $fileOut/'$targetfile[$i].mkv' $fileOut/'$targetfile[$i]'")
			}
		}
	}
			
    open (MYFILE, ">>$logfile");
    print MYFILE "Batch rip completed: $currenttime \n \n";
    close (MYFILE);
    
    print "Batch rip complete. Thank you, come again.\n \n";
        
	
	
########## timestamp ###############

sub timestamp
    {
	@Month_name = ( "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" );
	( $sec, $min, $hour, $day, $month, $year ) = ( localtime ) [ 0, 1, 2, 3, 4, 5 ];

	return sprintf  "%02d:%02d:%02d %02d %s %04d", $hour, $min, $sec, $day, @Month_name->[$month], $year+1900 ;

	#$starttime = $timestamp
    }

airdamien
Posts: 1
Joined: Sun Jan 16, 2011 8:23 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by airdamien »

Was looking for a decent solution to this for the atv2.

Work in progress, it's currently batch converting for me, haven't tested the output on atv2, I got the settings through google.
Was about to start fixing another posted script here, when I realized that somebody else had posted one that had issues with spaces in filenames.
When I realized it's easily fixed by using -exec with find.
the outputs are .mpg.mp4 , I'll add something to fix that once this batch is done encoding.

Code: Select all

#!/bin/sh

find $1 -name '*.mpg' -exec /usr/bin/HandBrakeCLI -i {} -o {}.mp4 -e x264 -q 20.0 -r 29.97 -fr -a 1,1 -E faac,copy:ac3 -B 160,160 -6 dpl2,auto -R Auto,Auto -D 0.0,0.0 -f mp4 -4 -X 1280 --loose-anamorphic -m \;
Deleted User 11865

Re: Batch conversion using CLI via Perl or Shell script??

Post by Deleted User 11865 »

I suppose you meant --pfr rather than -fr
Dalton63841
Posts: 20
Joined: Tue Jan 11, 2011 9:54 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by Dalton63841 »

airdamien wrote:Was looking for a decent solution to this for the atv2.

Work in progress, it's currently batch converting for me, haven't tested the output on atv2, I got the settings through google.
Was about to start fixing another posted script here, when I realized that somebody else had posted one that had issues with spaces in filenames.
When I realized it's easily fixed by using -exec with find.
the outputs are .mpg.mp4 , I'll add something to fix that once this batch is done encoding.

Code: Select all

#!/bin/sh

find $1 -name '*.mpg' -exec /usr/bin/HandBrakeCLI -i {} -o {}.mp4 -e x264 -q 20.0 -r 29.97 -fr -a 1,1 -E faac,copy:ac3 -B 160,160 -6 dpl2,auto -R Auto,Auto -D 0.0,0.0 -f mp4 -4 -X 1280 --loose-anamorphic -m \;
Off the top of my head a fix for the .mpg.mp4 output would be to add another line under that command:

Code: Select all

find . -name "*.mpg.mp4" | while read i;
  do
	mv "$i" "${i%mpg.mp4}mp4";
  done
rogue23
Enlightened
Posts: 137
Joined: Thu Dec 16, 2010 7:51 pm

Re: Batch conversion using CLI via Perl or Shell script??

Post by rogue23 »

Or something like this:

Code: Select all

#!/bin/sh

find $1 -name '*.mpg' | while read filename;
do
  /usr/bin/HandBrakeCLI -i "$filename" -o "${filename/.mpg/}.mp4" -e x264 -q 20.0 -r 29.97 -fr -a 1,1 -E faac,copy:ac3 -B 160,160 -6 dpl2,auto -R auto,auto -D 0.0,0.0 -f mp4 -4 -X 1280 --loose-anamorphic -m;
done
Post Reply