Mint Serena 64 bit using the Mate desktop environment. Most of the following scripts will run on this machine, although some have only been tested with the Gnome desktop. Extra software requirements can be met by the Ubuntu and safe PPA repositories. Scripts may be re-written or added to from time to time, the date serves as the version number. Syntax highlighting on these pages is provided by GVim's "Convert to HTML" option.
Showing posts with label media. Show all posts
Showing posts with label media. Show all posts

Clean Scrape


#!/bin/bash
# Filename: clean-scrape.sh
# Version.: 05082018
# Author..: robz
# Clean list of magnet links from "showRSS.info" page source scrape.
# Add to your file browser scripts directory for right click usage.
# Usage: In the web browser, right click - "View Page Source" - "Select All" 
# left click - drag to desktop - right click - run script

cd '/home/robz/Desktop'
[ -e 'dropped text.txt' ] || exit
sed '/1080p\|720p/d;/href="magnet/!d;s/.*href="//;s/" .*//' 'dropped text.txt' \
| sort -t= -k3 -o 'dropped text.txt'
mv 'dropped text.txt' 'add-magnet.txt'
exit

Fix Subtitle Offset


#!/bin/bash
# Filename: srt-fix-offset.sh
# Version.: 20052018
# Author..: not robz
# A script to modify subtitle offset beyond the Kodi maximum of 60 seconds.
# Put original titles in a file called "srt.txt" in your home directory and
# run the script.
# In all honesty this is pretty much a copy paste job from Linux Questions.
# For more detailed information goto:
# www.linuxquestions.org/questions/linux-newbie-8/editing-srt-files-4175436550/
#
# Modify and comment the offset variable as appropriate.
# Advance subtitles.
offset="75 seconds"
# Retard subtiles.
#offset="5 seconds ago"

while read start s end; do
    if [[ $start =~ ^..:..:..,... ]]; then
        start=$(date -d "$start $offset" +%H:%M:%S,%N)
        end=$(date -d "$end $offset" +%H:%M:%S,%N)
        echo ${start:0:12} $s ${end:0:12}
    else
        echo $start $s $end
    fi
done < srt.txt >> new-subtitles.srt

DAB Radio


#!/bin/bash
# Filename: dab-radio.sh
# Version.: 07022018
# Author..: robz
# Basic DAB radio via a cheap DVB-T dongle using a "zenity" gui and the command
# line version of "vlc player", see man vlc. The utility "wmctrl" places the gui
# top left of the screen. The initial scanning for radio stations I used the
# "w_scan" utility to create a playlist text file.

text="Make a selection"
optn=":dvb-frequency=522000000 :dvb-bandwidth=8 :dvb-ts-id=4168 \
:dvb-code-rate-hp=2/3 :dvb-modulation=64QAM :dvb-transmission=8 \
:dvb-guard=1/32 :program="

get_mplex () {
prog=$(zenity --list --radiolist --height=400 --width=200 --hide-header \
--title='robz DAB Radio' --text="$text" --column '' --column '' --column '' \
--hide-column=3 --print-column=ALL --ok-label='Play' \
FALSE 'BBC Radio 1' '6720' \
FALSE 'BBC Radio 1 Extra' '5888' \
FALSE 'BBC Radio 2' '6784' \
FALSE 'BBC Radio 3' '6848' \
FALSE 'BBC Radio 4' '6912' \
FALSE 'BBC Radio 4 Extra' '5824' \
FALSE 'BBC World Service' '6016' \
FALSE 'BBC Radio 5 Live' '5632' \
FALSE 'BBC Radio 5 Sport' '5696' \
FALSE 'BBC Radio 6 Music' '5760' \
FALSE 'BBC Manchester' '6152' \
FALSE 'BBC Lancashire' '6216'
)
}

while true; do
    (sleep .5 && wmctrl -r "robz DAB Radio" -e 1,0,0,200,400) &
    get_mplex
    text="<b>Playing: $(cut -d'|' -f1 <<< $prog)</b>"
    prog="$(cut -d'|' -f2 <<< $prog)"
    pkill -9 vlc
    if [ "$prog" = '' ]; then exit; fi
    (cvlc dvb-t:// $optn$prog > /dev/null 2>&1) &
done


Own Media


#!/bin/bash
# Filename: own-media
# Version: 090813
# Author: robz
# The purpose of this script is to automate the transfer of TV media files
# from another user account to my standard working account.
# Source and destination directories will need changing to suit.
# You can use this as a Nautilus script or via a launcher. You will need the
# excellent "tvnamer" utility available from the Ubuntu Software Centre.

# Ask for password to obtain administrator privileges.
if [ "$UID" != "0" ]; then
    sudo -k; exec gksudo --message "$(echo\
    'Enter your password please, you need root';\
    echo 'privilages to access another user account.')"\
    "$0"
fi

USE="robz1"                              # This scripts destination user name.
BAK="$IFS"                               # Backup internal field separator.
IFS="\n"                                 # Set internal field separator.
DES="/home/robz1/Torrents/Complete/"     # Save directory minus one level.
ARC="/media/Backup/TV"                   # Backup achive location.

trap 'IFS="$BAK"; exit' INT TERM EXIT    # Restore IFS on exit.

# Select files to be copied.
FIL=$(zenity --file-selection --multiple --separator=$'\n'\
    --filename="/home/transmission/Downloads/Torrents/Complete/"\
    --title="Own-Media - >>SELECT FILE OR FILES<<")
if [ "$?" = 1 ]; then exit $?; fi        # Kill script on cancel.

# File destination, this appends to the "$DES" initial destination variable.
STO=$(zenity --title="Own-Media" --text="Select Destination" --height=170\
    --list --radiolist --column "Select" --column "Send Files To..."\
    TRUE "NewTV" FALSE "Somewhere else") # Change "NewTV" to whatever you want.
if [ "$?" = 1 ]; then exit $?; fi

SAV="$DES""$STO""/"                      # Set initial destination.

# Select alternative file destination, ignore "$DES" and go somewhere else.
if [ "$STO" = "Somewhere else" ]; then
    SAV=$(zenity --file-selection --directory --filename="/home/robz1/"\
    --title="Own-Media - >>SELECT DESTINATION<<")
    if [ "$?" = 1 ]; then exit $?; fi
    SAV="$SAV""/"                        # Reset destination, maybe.
fi

# Copy files to destination.
while read N; do cp -u "$N" "$SAV"; done <<< "$FIL"

# Take possession of files as destination user, change owner.
while read N; do chown "$USE":"$USE" "$SAV""$(basename "$N")"; done <<< "$FIL"

sudo -k                                  # Drop superuser privileges.

# Rename to standard format i.e. [ Show Name - [01x01] - Episode Name ].
zenity --question --title= --text="Do you wish to rename &amp; achive."
if [ "$?" = 1 ]; then exit $?
else
    while read N; do tvnamer --batch "$SAV""$(basename "$N")"; done <<< "$FIL"
fi

cp -aur "$SAV""." "$ARC"                 # Copy new files to a backup achive.



File Transfer


#!/bin/bash
# Filename: ssh-transfer
# Version: 140713
# Author: robz
#
# This little script automates the transfer of media files from my PC to my XBMC
# media centre, which runs on the embedded Openelec operating system installed
# on a Raspberry Pi credit-card computer.
# First install the rsync utility on your XBMC media centre via "ADD-ONS".
# Use this excellent link to setup an ssh key for rsync to login automagicly.  
# http://www.thegeekstuff.com/2011/07/rsync-over-ssh-without-password/
# Put this script in your "nautilus-scripts" directory select file/s to
# transfer then right click and select this script from the Scripts menu.
# Don't forget "chmod u+x /home/<user>/.gnome2/nautilus-scripts/ssh-transfer"
# to make it executable.

# Path to the "rsync" utility on Openelec.
RSYNC="/storage/.xbmc/addons/network.backup.rsync/bin/rsync"
IPADD="192.168.1.67"                    # IP address of your Openelec box.
OELEC="/media/USBMEDIA/"                # Destination directory on XBMC.

# Create newline delimited selected files list, handling spaces in file names.
FILES=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" |\
    awk 'BEGIN { FS = "\n" } { printf "\"%s\" ", $1 }' | sed -e s#\"\"##)

# Select destination for file transfer.
LOCTN=$(zenity\
    --title "SSH File Transfer"\
    --height=230\
    --text "Transfer Files To XBMC Media Centre."\
    --list --radiolist\
    --column "Select" --column "Send Files To..."\
    TRUE New FALSE TV FALSE Movies FALSE Music FALSE Concerts)
if [ "$?" = 1 ]; then exit $?; fi       # Cancel/close? then exit script.

# File count, how many files.
IFS=$(echo -en "\n\b")                  # Loop handles names with spaces now.
for N in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do ((NOFLS+=1)); done

# Open a terminal to run rsync and view file transfer progress.
gnome-terminal --geometry 70x30+48+0 --title="SSH File Transfer" -x bash -c\
    "echo 'Sending $NOFLS files to $OELEC$LOCTN'; echo; tput civis;\
    rsync -avP --rsync-path=$RSYNC -e ssh $FILES root@$IPADD:$OELEC$LOCTN;\
    tput bold; tput setaf 3; echo;\
    echo -e 'Done, hit a key to exit this shell, auto exit in 30s...';\
    read -n1 -t30"

# Update XBMC ibrary.
ssh -l root $IPADD 'xbmc-send --action="XBMC.updatelibrary(video)"' && \
ssh -l root $IPADD 'xbmc-send --action="XBMC.updatelibrary(music)"'


DVD Audio Rip


#!/bin/bash
# Filename: dvd-audio-rip.sh
# Version: 160612
# Author: robz
# This script will rip the audio tracks off of a "concert dvd" to multiple mp3
# files named Track 01, Track 02, etc. You then have options listen to them on
# yer iPod, in your car or burn them to a cd. Quality of the rip depends on the
# option switch "--lame_preset", see "man transcode" for other presets.
# You may need to alter the "DRIVE" variable to suit, you'll also need packages
# "transcode" and "lsdvd" to be installed.
# Usage: Double click the script and select "Run in Terminal", Ctrl+c to stop.

trap "killall transcode; exit" INT TERM EXIT      # Terminate this script.
mkdir -p new-audio; cd new-audio                  # Make a dir. for the mp3s.

DRIVE="/dev/sr0"                                  # Path to your dvd drive.
TITLE=$(lsdvd -a "$DRIVE" | awk '/Longest track/ {print$3}')
CHPTR=$(lsdvd -a -t"$TITLE" "$DRIVE" | awk '/Chapters/ {print $6}')
ASTRM="0"                                         # Audio stream (0=pcm 1=ac3).

for TRACK in $(eval echo "{1..${CHPTR%,*}}")      # Loop through the chapters.
do
    transcode\
    -i /dev/sr0\
    -x null,dvd\
    -T "$TITLE","$TRACK",1\
    -a "$ASTRM"\
    -y null,tcaud\
    --lame_preset extreme\
    -m "Track "$(printf "%02d" "$TRACK").mp3
done                                              # Files are on the desktop.
 


Rip YouTube.

~/.scripts/Media_processing/Media_scripts/rip-youtube.html #!/bin/bash
# Filename: rip-youtube
# Version: 100112
# Author: robz
# This is intended to be used with the Mozilla Firefox browser and run as a
# right-click nautilus script. It recovers "deleted" YouTube video/music files
# from the /proc/ directory.
# Wait until the file download has completed then run the script, copies of the
# media will be placed in the $DEST directory.
# You will need to run the script before closing the tabs or the browser.

DEST="$HOME/Videos"
find /proc/*/fd/ -lname "/tmp/Flash*" 2>/dev/null
| xargs -i{} cp {} "$DEST"

# Bare bones but effective.

# Err was effective, looking for a cure!

Basic PVR

#!/bin/bash
# Filename: mypvr.sh
# Version: 081211
# Author: robz
# This script uses http://ezrss.it to check for the lastest episodes of your
# favorite tv shows, which you'll have listed in the "followed-shows" file.
# Run mypvr.sh from your chosen directory. First, the above list file will be
# set up, once this is done the script can be controlled via a crontab or on
# PC startup, or both. Here's a crontab to check for new shows every 2 hours.
# 25 */2 * * * export DISPLAY=:0 && /$HOME/PVR/mypvr.sh >/dev/null 2>&1
# Selected .torrent trackers will be sent to your "Downloads" directory ready
# to be picked up by "Transmission" gui/daemon or any other client that can be
# set to auto-load from a monitored directory.

SHOW_NAME_EXACT=""                  # Allow some search leeway.
QUALITY="hdtv"                      # HDTV standard quality.
QUALITY_EXACT="true"                # Only hdtv not 720p - no huge files.
DWNLDS="$HOME/Downloads"            # Default Downloads, change if you like.
green="<span color=\"#008000\">"    # Green ok! :p

func_form_url ()                                    # Create web search url.
{
WEBSITE="http://ezrss.it/search/index.php?show_name="$SHOW_NAME"&\
show_name_exact=$SHOW_NAME_EXACT&date=&quality=$QUALITY&\
quality_exact=$QUALITY_EXACT&release_group=&mode=simple"
}

cd
"$(dirname "$0")"                                # Do cd to "mypvr.sh" dir.

trap "rm -f "newlist" "urllist"; exit" \
INT TERM EXIT                                       # Clean up cruft on close.

if [ ! -e "donelist" ]; then touch donelist; fi     # Check donelist exists.
if [ ! -e "followed-shows" ]; then                  # Check shows list exists.
cat > followed-shows << EOF
# Type the names of tv shows to be followed into this list.
# Hash commented, like this line, and blank lines will be ignored.
# To stop a show search, comment "#" the line or delete it :)

Spooks
#Terra Nova < examples, delete and replace with yours.
Dexter

# End of list - a blank line is required above this line.
EOF
gedit followed-shows                                # Edit new shows list.
exit; fi

while read SHOW_NAME; do                            # Read followed-shows list.
    if [[ "${SHOW_NAME:0:1}" != "#" && -n "$SHOW_NAME" ]]; then
        SHOW_NAME=$(echo "$SHOW_NAME" | sed -e 's/ \+/+/g')
        func_form_url                               # Create custom url.
        # Get web pages for shows, take episode at top of page - newest.
        wget -q --random-wait -O - $WEBSITE |\
        egrep -om1 "http:.*.torrent" >> urllist
    fi
done < followed-shows                               # Feed followed-shows.

sort -u urllist > newlist                           # De-dupe, make copy.

# Whittle away the URL bumf for a naked "newlist".
sed -i 's#http:/[^",]*/##' newlist
sed -i 's/\([Ee][0-9][0-9]\)\+.*/\1/' newlist       # S01E02 - s01e02.
sed -i 's/\([Xx][0-9][0-9]\)\+.*/\1/' newlist       # 1X02 - 1x02 - 01X02.
#sed -i 's/\([0-9][0-9][0-9]\)\+.*/\1/' newlist     # 102 ? (V2009)?! aah!
sed -i '/torrent/d' newlist                         # Remove strays.

sort newlist -o newlist                             # Sort stripped list.

NEW=$(comm --check-order -23 newlist donelist)      # Compare new/existing.
if [ -z "$NEW" ]; then exit; fi                     # $tring null? then exit.

for LINE in $NEW; do SEL+=" TRUE $LINE"; done       # Prepend entries "TRUE".

# Option for 10 mins to choose/cancel or it auto-downloads all new trackers.
CHOOSE=$(zenity --title "PVR" --timeout 600 --width 300 --height 225 \
--list --text "$green""There are new TV episodes available</span>" \
--checklist --column " #" --column "Download torrent trackers for:" $SEL)
EXITCODE="$?"

if [ "$EXITCCODE" = 1 ] || [[ "$EXITCODE" = 0 && -z "$CHOOSE" ]]; then
    exit                                            # Null entry or cancel.
elif [ -z "$CHOOSE" ]; then                         # $CHOOSE empty, use $NEW.
    CHOOSE=$(echo $NEW | sed 's/  */|/g')           # Add "|" egrep delimiters.
    zenity --notification --text "Auto download of latest TV trackers"\
    & disown
fi

timeout 60 \
wget --quiet --no-clobber --random-wait --directory-prefix=$DWNLDS \
--input-file=$(egrep $(echo $CHOOSE) urllist)       # Go "wget" the trackers.

CHOOSE=$(echo "$CHOOSE" | sed 's/|/ /g')            # Strip delimiters.

# If tracker has downloaded correctly, make entry to "donelist".
for LINE in $CHOOSE; do
    if [ $(ls "$DWNLDS" | grep $LINE) ]; then echo "$LINE" >> donelist
    elif [ -z $PID ]; then zenity --notification\
        --text="`echo -e "One or more trackers has failed to download.\
        \nNext try is scheduled for $(date --date='+2 hours' +%H:25) hours."`"\
        & disown
        PID=$!                                      # Just one notification.
    fi
done

sort donelist -o donelist                           # Sort new "donelist".

notify-send -i '/usr/share/icons/hicolor/scalable/apps/transmission.svg' \
"Tracker files downloaded" "$(ls "$DWNLDS" | grep "\.torrent")" &


Quick n' Dirty MPG>ISO>DISK

#!/bin/bash
# Filename: qd-dvd
# Version: 061111
# Author: robz
# Quick n' dirty single "movie.mpg" to "dvd.iso" to dvdrw/dvdr disk.
# The "movie.mpg" will need to be a dvd compatible file, eg with ffmpeg the
# "-target" switch will be required with pal-dvd or ntsc-dvd or film-dvd set.
# Script will overwrite rw disks without asking so make sure you have the
# right disk in your drive, in my case that drive is /dev/sr0 yours may be
# different.
# Make the script executable and chuck it in the "nautilus-scripts" directory.
# Usage: Insert a disk, right-click file to burn > Scripts > qd-dvd.

trap "killall -q dvdauthor genisoimage growisofs; rm -rf 'tmp-files'; \
exit" INT TERM EXIT                                     # Clean on exit/error.

author_it ()
{
echo -e "\033[1m\E[37mWorking on - $MOVIE"              # Colour the headings.
echo -e "\033[1m\E[36mCreating the DVD file structure\033[0m\E[37m"
nice -n 19 dvdauthor -o tmp-files -t $MOVIE && \
echo -e "\033[1m\E[34mSuccessfully created file structure"
echo -e "\033[1m\E[36m\nFinalize the structure\033[0m\E[37m"
VIDEO_FORMAT=PAL nice -n 19 dvdauthor -o tmp-files -T && \
echo -e "\033[1m\E[34mFile Structure finalized"
}

iso_it ()
{
MOVIE=${MOVIE%.mpg}.iso                                 # Change extension.
echo -e "\033[1m\E[36m\nCreating $MOVIE\033[0m\E[37m\
\nThis may take a while, please wait...."
nice -n 19 genisoimage -quiet -V "DVD" -o "$MOVIE" -dvd-video tmp-files && \
tput cuu1; tput el; \
echo -e "\033[1m\E[34mISO created successfully\n\033[0m\E[37m"
}

burn_it ()
{
if ! udisks --show-info /dev/sr0 | grep "media: *optical_dvd_plus_r"; then
    echo -e "\033[1m\E[33mOOPS\033[1m\E[37m"
    echo -e "No writeable disk! Burn created .iso later eh. \033[1m\E[34m"
    read -p "Hit a key to exit" -n1; exit
else
    tput cuu1; tput el; tput cuu1
    echo -e "\033[1m\E[36m\nBurning $MOVIE\033[0m\E[37m"
    echo "This may take a while, please wait....       "
    nice -n 19 growisofs -quiet -dvd-compat -Z /dev/sr0="$MOVIE"\
    -use-the-force-luke=notray -use-the-force-luke=tty  # My drive sr0, yours?
    if [ "$?" = "0" ]; then                             # Did it burn OK?
        echo -e "\033[1m\E[32m$MOVIE burned - job done - Bye! \n\033[1m\E[36m"
        rm "$MOVIE"                                     # Clean up iso file.
    else echo -e "\033[1m\E[31mERROR\033[1m\E[37m burn failed"
    fi
fi
sleep 2
eject -r sr0; read -t10 -p "Remove disk and hit a key to exit";
}

export -f author_it; export -f iso_it; export -f burn_it; export MOVIE="$1"

gnome-terminal --title="Quick n' Dirty MPG>ISO>DISK" \
--geometry=85x55+0+25 -x bash -c "tput civis; author_it; iso_it; burn_it"

FFmpeg with progress bar (re-work)

#!/bin/bash
# File name: ZAVI2MPG - saved in the "nautilus-scripts" directory.
# Author: robz
# Version: 130511
# This is a re-re-work of a previous script for converting .avi television
# files to a "burnable to DVD" format. This time though conversion statistics
# visual output is supplied by the Zenity dialogue. Stats logfile also added.
# File locations in some variables are specific to my PC check "# Vars" first.
# The script is called by right clicking on the ".avi file" then clicking
# the appropriate choice in the nautilus-scripts menu.
# You'll need "FFmpeg" an FFmpeg notify-send icon and a ding-dong.wav sound.

# Vars.
ICON=$HOME/Pictures/user_graphics/Icons/ffmpeg-logo-small.png
LOG=$HOME/Torrents/re-coding.log

display () # Calculate/collect progress bar info. & pipe to Zenity.
{
START=$(date +%s); FR_CNT=0; ETA=0; ELAPSED=0
while [ -e /proc/$PID ]; do                         # Is FFmpeg running?
    sleep 2
    VSTATS=$(awk '{gsub(/frame=/, "")}/./{line=$1-1} END{print line}' \
    "$RM"/vstats*)                                  # Parse vstats file.
    if [ $VSTATS -gt $FR_CNT ]; then                # Parsed sane or no?
        FR_CNT=$VSTATS
        PERCENTAGE=$(( 100 * FR_CNT / TOT_FR ))     # Progbar calc.
        ELAPSED=$(( $(date +%s) - START )); echo $ELAPSED > /tmp/elapsed.value
        ETA=$(date -d @$(awk 'BEGIN{print int(('$ELAPSED' / '$FR_CNT') *\
        ('$TOT_FR' - '$FR_CNT'))}') -u +%H:%M:%S)   # ETA calc.
    fi
    echo "# Working on file: $COUNT of $OF - Length: $DUR - Frames: $TOT_FR\
    \nFilename: ${NFILE%.*}\nSaved to: $SAVEAS\
    \nTelevision standard is set to: $TFORM2\
    \nRe-coding with FFmpeg, method: $QUAL\
    \nFrame: $FR_CNT of $TOT_FR   Elapsed: $(date -d @$ELAPSED -u\
    +%H:%M:%S)   ET to finish: $ETA"                # Text for stats. output.
    echo $PERCENTAGE                                # Feed the progbar.
done | zenity\
    --progress\
    --window-icon $ICON\
    --title="AVI-2-MPG ${QUAL:10:13}"\
    --text="Initializing please wait..."\
    --percentage=0\
    --auto-close\
    --auto-kill
}

SEL=$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS            # Right clicked selection.
RM=$(pwd)
trap "killall ffmpeg ZAVI2MPG; rm -f "$RM/ffmpeg2pass*" "$RM/vstats*"; exit" \
INT TERM EXIT                                       # Kill & clean if stopped.

# Select re-coded file destination.
SAVEAS=$(zenity --file-selection --directory\
    --window-icon $ICON --title ">>SELECT DESTINATION FOR RE-CODED FILE<<")
if [ "$?" = 1 ]; then
    exit $?
fi

# Select quality of re-code.
QUAL=$(zenity --window-icon $ICON --title "AVI-2-MPG"\
    --width 340 --height 170 --list --text "Recode Mode"\
    --radiolist --column "Select " --column "FFmpeg re-code option"\
    FALSE 'One Pass, same Q big file, fast.'\
    TRUE 'Two Pass, same Q smaller file, slow.');
if [ $? = 1 ]; then
    exit $?
elif [ "${QUAL:0:8}" = "One Pass" ]; then
    QUAL="One Pass - Re-coding..."
fi

SAVEIFS=$IFS                                        # Make "for loops" handle
IFS=$(echo -en "\n\b")                              # filenames with spaces.

for FILE in $SEL; do ((OF+=1)); done                    # Count right click
echo -e $(date +%c)" - Files processed: $OF\n" >> $LOG  # selected files, log.

# Loop through counted file selection and process in turn.
for FILE in $SEL; do ((COUNT+=1))
    NFILE=$(basename "$FILE")
    # Get duration and PAL/NTSC fps then calculate total frames.
    FPS=$(ffprobe "$FILE" 2>&1 | sed -n "s/.*, \(.*\) tbr.*/\1/p")
    DUR=$(ffprobe "$FILE" 2>&1 | sed -n "s/.* Duration: \([^,]*\), .*/\1/p")
    HRS=$(echo $DUR | cut -d":" -f1)
    MIN=$(echo $DUR | cut -d":" -f2)
    SEC=$(echo $DUR | cut -d":" -f3)
    TOT_FR=$(echo "($HRS*3600+$MIN*60+$SEC)*$FPS" | bc | cut -d"." -f1)
    if [ ! "$TOT_FR" -gt "0" ]; then zenity --error; exit; fi

    # TV format to FFmpeg friendly.
    TFORM=$(echo "$FPS" |\
        sed "s/25/pal-dvd/g; s/30/pal-dvd/g; s/29.98/ntsc-dvd/g;\
        s/29.97/ntsc-dvd/g; s/23.98/ntsc-dvd/g;")
    TFORM2=$(echo "$FPS" |\
        sed "s/25/PAL @ 25fps/g; s/30/PAL @ 30fps/g;\
        s/29.98/NTSC @ 29.98fps/g; s/29.97/NTSC @ 29.97fps/g;\
        s/23.98/NTSC-Film @ 23.98fps/g;")

    # Re-code with it.
    if [ "$QUAL" = "One Pass - Re-coding..." ]; then    # Same Q big file.
        nice -n 15 ffmpeg -i "$FILE"\
        -target $TFORM\
        -sameq\
        -r $FPS\
        -vstats\
        -y\
        $SAVEAS/${NFILE%.*}.mpg &                       # Background FFmpeg.
        PID=$! && display                               # GUI stats. func.
        rm -f "$RM"/vstats*                             # Clean up tmp files.
    else
        QUAL="Two Pass - Analysing..."                  # Analyse video only.
        nice -n 15 ffmpeg -i "$FILE"\
        -pass 1\
        -target $TFORM\
        -r $FPS\
        -vstats\
        -b 2800k\
        -an\
        -y\
        /dev/null &                                     # Background FFmpeg.
        PID=$! && display                               # GUI stats. func.
        rm -f "$RM"/vstats*                             # Clean up.
        AN_TM=$(cat /tmp/elapsed.value)                 # Get analyse time.
        ((BATCH+=$AN_TM))                               # Batch time totaling.
        QUAL="Two Pass - Re-coding..."                  # Do smaller re-code.
        nice -n 15 ffmpeg -i "$FILE"\
        -pass 2\
        -target $TFORM\
        -r $FPS\
        -vstats\
        -b 2800k\
        -acodec ac3\
        -ar 48000\
        -ab 128k\
        -y\
        $SAVEAS/${NFILE%.*}.mpg &                       # Background FFmpeg.
        PID=$! && display                               # GUI stats. func.
        rm -f "$RM"/ffmpeg2pass* "$RM"/vstats*          # Clean up tmp files.
    fi
    # Statistics for logfile entry.
    ((BATCH+=$(cat /tmp/elapsed.value)))                # Batch time totaling.
    ELAPSED=$(cat /tmp/elapsed.value)                   # Per file time.
    echo -e $COUNT\. ${NFILE%.*}\
    "\nDuration: $DUR - Total frames: $TOT_FR\
    \nCoded to $TFORM2 standard using \"${QUAL:0:8}\" option." >> $LOG
    # Elapsed time for 1 pass, average for 2 passes, fps average for both.
    if [ "${QUAL:0:8}" = "Two Pass" ]; then
        ((ELAPSED+=$AN_TM)); AV_RATE=$(( TOT_FR * 2 / ELAPSED ))
    else
        AV_RATE=$(( TOT_FR / ELAPSED ))
    fi
    echo -e "Re-coding time taken: $(date -d @$ELAPSED -u +%H:%M:%S)"\
    "at an average rate of $AV_RATE""fps.\n" >> $LOG
done

# Notify finished batch ding-dong gong and message, log it, all done bye ;¬)
TEXT="Total re-coding time: $(date -d @$BATCH -u +%H:%M:%S)."
echo -e "$TEXT\n\
__________________________________________________________________" >> $LOG
notify-send -i $ICON "ZAVI2MPG Re-code completed" "$TEXT"
/usr/bin/canberra-gtk-play --volume 2 -f $HOME/Audio/2tone.wav