#!/bin/bash
# v1.0 Gerald Dachs
# v1.1 Hendrik Friedel
#      Conversion of files to mkv
#      Cut-Marks transferred to mkv as Chapters
#      Check of size of converted file vs. original file
#      Combination of *.ts into one file
#      Stats as Output

RECORDING=$2
INFO=$RECORDING/info
BASEDIR=/srv/movies/uncut
SERIESDIR/srv/series/uncut
VIDEO=$RECORDING/00001.ts
TMPDIR=/srv/share/vdr/tmp
PROBLEMDIR=$TMPDIR/Problem

THRESHOLD=60000   #recordings must not be shorter by more than THRESHOLD milliseconds


LOGINFO="logger -i -s -t $0 -p user.info"
LOGERR="logger -i -s -t $0 -p user.err"
THREADCNT=4




function write_metadata(){
    echo tmpdir
    echo $TMPDIR
    meta=$TMPDIR/ffmetadata
    echo ";FFMETADATA1" > $meta
    s1=0
    ca=0
    tag=$(date -u +"%s" -d 0:00:00)
    # 0:10:03.48
    while read line
    do
        #echo $line
        line=$(echo $line|cut -d ' ' -f 1) 
        c=$(date -u +"%s" -d $line)
        cs=$(echo $line|cut -d '.' -f 2)
        ms=$(($cs*10))
        c=$(($c-$tag))
        c=$(($c*1000))
        c=$(($c+$ms))
        echo "[CHAPTER]" >> $meta
        #echo "TIMEBASE=1" >> $meta
        echo "TIMEBASE=1/1000" >> $meta
        echo "START=$ca" >> $meta
        echo "#chapter ends at $line" >> $meta
        echo "END=$(($c-1))" >> $meta
        if [ $s1 -eq 0 ]
        then
	echo "title=Werbung $line" >> $meta
	s1=1
        else
	echo "title=Film $line" >> $meta
	s1=0
        fi
        ca=$c
    done  < $RECORDING/marks
}


function duration(){
milliseconds=0
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for filename in $1/*.ts; do
DURATION=$(ffprobe  "$filename" 2>&1 | grep Duration: |  \
        cut -f2,3,4 -d: | cut -f1 -d,);


h=$(echo $DURATION | cut -f1 -d: | sed 's/^0*//')
min=$(echo $DURATION | cut -f2 -d:  | cut -f1 -d. | sed 's/^0*//')
sec=$(echo $DURATION | cut -f3 -d:  | cut -f1 -d. | sed 's/^0*//')
ms=$(echo $DURATION | cut -f2 -d. | sed 's/^0*//' )
milliseconds=$((milliseconds+(h+0)*60*60000+(min+0)*60000+(sec+0)*1000+ms))


done
echo $milliseconds
IFS=$SAVEIFS
}


function duration1(){
milliseconds=0

DURATION=$(ffprobe  "$1" 2>&1 | grep Duration: |  \
        cut -f2,3,4 -d: | cut -f1 -d,);

h=$(echo $DURATION | cut -f1 -d: | sed 's/^0*//')
min=$(echo $DURATION | cut -f2 -d:  | cut -f1 -d. | sed 's/^0*//')
sec=$(echo $DURATION | cut -f3 -d:  | cut -f1 -d. | sed 's/^0*//')
ms=$(echo $DURATION | cut -f2 -d. | sed 's/^0*//' )
milliseconds=$((milliseconds+(h+0)*60*60000+(min+0)*60000+(sec+0)*1000+ms))
echo $milliseconds
}



start=$(($(date +%s%N)/1000000))


case $1 in                                                                                                                                                    
    after) 
        $LOGINFO "processing $RECORDING"

        if [ -z "$(which vdrseriestimer)" ]; then
            $LOGERR "error: vdrseriestimer not found"
            exit 1
        fi

        if [ -z "$(which avprobe)" ]; then
            $LOGERR "error: avprobe not found"
            exit 1
        fi

        if [ ! -f $RECORDING/00001.ts ]; then
            $LOGERR "error: recording $RECORDING has no ts file"
            exit 1
        fi

#        if [ -f $RECORDING/00002.ts ]; then
#            $LOGERR "error: recording $RECORDING is broken"
#            exit 1
#        fi

        if [ ! -f $INFO ]; then
            $LOGERR "error: recording $RECORDING has no info file"
            exit 1
        fi
        SERIESPATH=""
        TITLE=$(grep "^T" $INFO | cut -d ' ' -f 2-)
        YEAR=$(grep "^D.*|Jahr: \([1-2][0-9]\{3\}\)|.*" $INFO | sed -e "s/.*|Jahr: \([1-2][0-9]\{3\}\)|.*/\1/")
        SUBTITLE=$(grep "^S" $INFO | cut -d ' ' -f 2-)
        if [ -n "$TITLE" -a -n "$SUBTITLE" ]; then
            SERIESPATH=$(vdrseriestimer --title "$TITLE" --subtitle "$SUBTITLE" -f "s%se%e - %S" -fp "%T/Season %s/")
        fi

	if [ -z "$SERIESPATH" ]; then  ##Subtitle could be part of the title behind a :
           SUBTITLE=$(echo $TITLE | cut -d ':' -f 2-)
           TITLE=$(echo $TITLE |cut -d ':' -f 1)
           SERIESPATH=$(vdrseriestimer --title "$TITLE" --subtitle "$SUBTITLE" -f "s%se%e - %S" -fp "%T/Season %s/" )
	fi

        if [ -n "$SERIESPATH" ]; then
            DESTPATH="$SERIESDIR/$SERIESPATH"
            DIRNAME=$(dirname "$DESTPATH")
            mkdir -p "$DIRNAME"
        else
            DESTPATH="$BASEDIR/$TITLE"
        fi
   
        if [ -n "$YEAR" ]; then
            DESTPATH="$DESTPATH ($YEAR)"
        fi

        DESTPATH="$DESTPATH.mkv"
        echo "................."
        echo $DESTPATH
        echo "................."
	if [ -e "$DESTPATH" ]; then
	    echo $DESTPATH exists for $RECORDING. Aborting >> /var/log/mkv_error.log
	    exit 1
	fi

        
        #to repair damaged recordings (PES packet size mismatch)
        avconv -y -f concat -i <(for f in $RECORDING/*.ts; do echo "file '$f'"; done) -vcodec copy -acodec copy $TMPDIR/$$.ts
        VIDEO=$TMPDIR/$$.ts 


        while read STREAMID STREAMTYPE CODEC; do
            echo "Stream-ID $STREAMID"
            echo "Stream-Type $STREAMTYPE"
            echo "Codec $CODEC"
            case $STREAMTYPE in 
                Video)
                    VMAP="-map $STREAMID "
                    if [ "$CODEC" != "h264" ]; then
                        VCODEC="-vcodec libx264"
                        echo "Codec is not h264 using libx264"
                    else
                        VCODEC="-vcodec copy"
                        echo "codec is h264 already. Copying Video"
                    fi
                    ;;
                Audio)
                    case $CODEC in
                        ac3)
                            AC3MAP="$AC3MAP-map $STREAMID "
                            ;;
                        mp2)
                            MP2MAP="$MP2MAP-map $STREAMID "
                            ;;
                    esac
                    ;;
                *)
                    $LOGINFO "ignoring unsupported stream type [$STREAMTYPE]"
                    ;;
            esac

        write_metadata

        done < <(avprobe $VIDEO 2>&1 | grep "Stream #[0-9]:[0-9]" | sed -e 's/.*Stream #\([0-9]:[0-9]\)\[0x[0-9a-f]*\][^: ]*: \([^: ]*\): \([^ (]*\).*/\1 \2 \3/')
         echo Running avconv -y -i $TMPDIR/ffmetadata -i $VIDEO $VMAP $VCODEC -aspect 1.7777 $AC3MAP $MP2MAP -acodec copy -threads $THREADCNT $TMPDIR/recording-$$.mkv
         (nice -n 19 avconv -y -i $TMPDIR/$$.ts $VMAP $VCODEC -aspect 1.7777 $AC3MAP $MP2MAP -acodec copy -threads $THREADCNT $TMPDIR/recording-$$.mkv
         ) 

rm $TMPDIR/$$.ts

orig=$(duration $RECORDING)
conv=$(duration1 "$TMPDIR/recording-$$.mkv")

orig_size=$( du $RECORDING | cut -f 1 )
conv_size=$( du "$TMPDIR/recording-$$.mkv" | cut -f 1)

ratio=$((100-conv_size*100/orig_size))

delta_size=$(((conv_size-orig_size)/1024))


if [ $((orig-conv)) -lt $THRESHOLD ]
then
  mv $TMPDIR/recording-$$.mkv "$DESTPATH"
  ende=$(($(date +%s%N)/1000000))
  delta=$(($ende - $start))
  time_ratio=$(($delta * 1000 /$conv))  Result is integer --> *1000 for later formating

  time_ratio=$(printf '%g\n'  $(bc <<< "scale=3; ${time_ratio}/1000"))
  echo 
  delta=$(printf '%g\n'  $(bc <<< "scale=3; ${delta}/1000"))
  echo $RECORDING converted. Compression by: $ratio %, it took $delta s, Time Ratio: $time_ratio, saved $delta_size MB  >> /var/log/mkv_success.log
else
  $LOGERR "Converted recording too small. Error! Aborting."
  echo $RECORDING >> /var/log/mkv_error.log
  mv $TMPDIR/recording-$$.mkv $PROBLEMDIR/
fi
;;
esac



