Transcoderr/transcode.sh

96 lines
3.4 KiB
Bash

!#/bin/bash
#Author: Glahera Matebi
#Defining Variables:
log=transcode.log
redis_cli="redis-cli -h redis"
tmp_fol=/tmp
ext=mkv
target_rate=8000000
a_rate=640000
a_opts="-c:a ac3 -b:a $a_rate"
a_def_opts="-c:a copy"
v_avg_rate=$(echo "$target_rate"-"$a_rate" | bc)
v_min_rate=$(echo "$v_avg_rate"*80/100 | bc)
v_max_rate=$(echo "$v_avg_rate"*120/100 | bc)
v_buf=$(echo "$v_avg_rate"*2 | bc)
##This transcode setting also transcode from HDR to SDR, scale the resolution to 1920 width and encode as h264. Please change to your need.
v_opts="-c:V libx264 -vf scale=1920:-2 -b:V $v_avg_rate -maxrate $v_max_rate -minrate $v_min_rate -bufsize $v_buf -preset slower"
v_def_opts="-c:v copy"
#Defining Functions:
#Run:
mkdir -p /var/log/transcode
touch /var/log/transcode/$log.ffmpeg
while true; do
## Receive Job from Redis Server
declare -a args=($(echo "BLPOP sonarr radarr 0" | $redis_cli))
## Declaring Origin Program
prog=${args[0]}
echo_log "Start: ${prog^}"
## Declaring Input File
file=$(echo ${args[1]} | base64 -d)
echo_log "Input File's Path: $file"
height="$(mediainfo --Inform='Video;%Height%' "$file")"
if [[ ! -z $height ]]; then
height="[${height}p]"
echo_log "Resolution: $height"
fi
# name = filename without extension
name=$(echo ${file%.*})
# strip trailing space or hyphen
name=$(echo $name | sed -r 's/[- ]{1,}$//g')
tmp_file="/tmp/tmp_${RANDOM}.$ext"
# check for ffmpeg
ffmpeg=$(which ffmpeg)
if [[ $? != 0 ]]; then
echo_log "ERROR, ffmpeg missing"
exit 1
fi
start=$(date +%s%N)
echo_log "Transcoding with the following settings: $ffmpeg_options $a_opts $v_opts"
##Encode Pass 1
nice -n20 ffmpeg -y -i "$file" -map V $v_opts -pass 1 -f matroska -passlogfile plex /dev/null
##Encode Pass 2
nice -n20 ffmpeg -i "$file" $ffmpeg_options $a_opts $v_opts -pass 2 -f matroska -passlogfile plex "$tmp_file"
if [[ $? != 0 ]]; then
echo_log "ERROR, ffmpeg exit code $?"
rm "$tmp_file"
exit 1
fi
end=$(date +%s%N)
## Input file size
isize=$(du -b "$file" | awk '{print $1}')
isizeh=$(du -h "$file" | awk '{print $1}')
if [[ $remove_original = 1 ]]; then
echo_log "Removing Original File"
rm "$file"
if [[ $? != 0 ]]; then
echo_log "WARNING, original file missing: $file"
fi
fi
mv "$tmp_file" "$name.$ext"
if [[ $? != 0 ]]; then
echo_log "WARNING, temporary file missing: $tmp_file"
fi
# Output File Size:
osize=$(du -b "$name.$ext" | awk '{print $1}')
osizeh=$(du -h "$name.$ext" | awk '{print $1}')
# Calculations:
speed=$(echo "scale=2; ($end - $start) / 1000000000 / 60" | bc)
size=$(echo "scale=2; ($isize - $osize)/$isize * 100" | bc)
echo_log "Input Size: $isizeh"
echo_log "Output Size: $osizeh"
echo_log "Encoding Speed: $speed min"
echo_log "Size Change: $size %"
echo_log "Output Filename: `basename "$name.$ext"`"
echo_log "End: ${prog^}"
done