video 2 mp4 converter

created a new script for movie 2 mp4 convertion

features:

*  save metadata
* save creaton date
* delete greater files if you whant

#!/bin/bash
# 
# converter for video files to mp4
# this script delete also all huger files if you want
# please take care with DELETE FILES = yes
# double check our output first if the quality is good enough for you
# this script keeps metadata and date of creaton for the file
#
# written 2016/07/17 by Daniel Gohlke to clean up my NAS
#
# you need ffmpeg and some codecs, if i forget something please update this script
# sudo apt-get install libavcodec-extra-53 libavutil-extra-51 libavformat-extra-53 libx264-146 ffmpeg
# change what ever you need

EXTENSION_NEW="mp4"
DELETE_FILES="no"
DEFAULT_CRF="22" # some kind of medium
OUTPUT_DIR="output"

read -p "Please enter CRF Quality / higher value is lower quality [51 worst .. 0 Loseless (default $DEFAULT_CRF) ]: " CRF
CRF=${CRF:-$DEFAULT_CRF}
echo "convert with CRF $CRF"


# error handling
function finish {
  if [ $FILENAME ]; then
    echo "some error occoured, cleanup file $OUTPUT_DIR/$FILENAME.mp4"
    echo "Error on line $1"
    rm -f "$OUTPUT_DIR/$FILENAME.mp4"
  else
    echo "User Break, leave $d untouched"
  fi
  rm -f $OUTPUT_DIR/filelist.txt
}

# Trap if something failed
trap 'finish $LINENO' ERR
#trap 'finish $LINENO' EXIT


function start_convert {

 mkdir -p $OUTPUT_DIR
 find . -type f \( ! -iname "filelist.txt" \) | grep -v "$OUTPUT_DIR" > $OUTPUT_DIR/filelist.txt 
   for d in $( cat $OUTPUT_DIR/filelist.txt ); do
#  for d in *; do
    echo "converting with crf $DEFAULT_CRF $d";
    FILENAME=$(basename "$d")
    EXTENSION="${FILENAME##*.}"
    FILENAME="${FILENAME%.*}"
    
    # convert
    ffmpeg -stats -i $d -c:v h264 -strict experimental -crf $CRF -map_metadata 0 $OUTPUT_DIR/$FILENAME.mp4

    # pply another file's attributes to new file
    touch -r $d $OUTPUT_DIR/$FILENAME.mp4    
    FILESIZE_OLD=$(stat -c%s "$FILENAME.$EXTENSION")
    FILESIZE_NEW=$(stat -c%s "$OUTPUT_DIR/$FILENAME.$EXTENSION_NEW")
#    echo $FILESIZE_OLD  
#    echo $FILESIZE_NEW
    
    if [ "$DELETE_FILES" == "yes" ]; then
      echo "delete greater files is turned on"
  
      if [ "$FILESIZE_OLD" -ge "$FILESIZE_NEW" ]; then
        echo "delete $FILENAME.$EXTENSION"
        rm -f $FILENAME.$EXTENSION
      else 
       echo "delete $OUTPUT_DIR/$FILENAME.$EXTENSION_NEW"
       rm -f $OUTPUT_DIR/$FILENAME.$EXTENSION_NEW
      fi
        
    else 
      echo "delete greater files is turned off"
    fi
    
  done

rm -f $OUTPUT_DIR/filelist.txt
exit 0
}

#ffmpeg -stats -i 0621232021DVB-TDasErste.m4v -c:v h264 -strict experimental -crf 20 -map_metadata 0  FILENAMEdefaultcrf20.mp4

# Start Program
read -p "Do you wish to start convert your videos? (y/n)" yn
case $yn in
  [Yy]* ) start_convert;;
  [Nn]* ) exit;;
   * ) echo "Please answer yes(y) or no(n).";;
esac

 

link to github: https://github.com/danielgohlke/scripts/blob/master/converttomp4.sh