#!/usr/local/bin/zsh set -eu recode=false for f ; do recode=false nvid=${#${(f)"$(ffprobe -hide_banner -v error -select_streams v -show_entries stream=index -of csv=p=0 ${f})"}} if [ $nvid -eq 0 ]; then continue fi naudio=${#${(f)"$(ffprobe -hide_banner -v error -select_streams a -show_entries stream=index -of csv=p=0 ${f})"}} if [ $naudio -eq 0 ]; then continue fi vtags=() print -n "$f: [" for i in {0..$nvid}; do if [ $i -eq $nvid ]; then break fi if [ $i -gt 0 ]; then print -n ", " fi eval $(ffprobe -hide_banner -v error -select_streams v:$i -show_entries stream=codec_name,width,height -of default=noprint_wrappers=1 ${f}) case "$codec_name" in hevc) if [ $height -gt 1080 ]; then vtags+=(-c:v:$i libx265 -tag:v:$i hvc1 -filter:v:$i scale=1920:-2 -x265-params no-open-gop=1:gop-lookahead=12:bframes=6:weightb=1:hme=1:strong-intra-smoothing=0:rect=0:aq-mode=4) recode=true else vtags+=(-c:v:$i copy) fi ;; mjpeg) vtags+=(-c:v:$i copy) ;; *) recode=true vtags+=(-c:v:$i libx265 -tag:v:$i hvc1 -x265-params no-open-gop=1:gop-lookahead=12:bframes=6:weightb=1:hme=1:strong-intra-smoothing=0:rect=0:aq-mode=4) if [ $height -gt 1080 ]; then vtags+=(-filter:v:$i scale=1920:-2) fi ;; esac print -n "v:$i: $codec_name" done # audio atags=() for i in {0..${naudio}} ; do if [ $i -eq ${naudio} ]; then break fi if [ $i -gt 0 ]; then print -n ", " else print -n " | " fi eval $(ffprobe -hide_banner -v error -select_streams a:$i -show_entries stream=codec_name,channels:stream_tags=language -of flat=sep_char=_ ${f}) codec_name=${streams_stream_0_codec_name} lang=${streams_stream_0_tags_language-und} channels=${streams_stream_0_channels} case "$codec_name" in aac|opus) atags+=(-c:a:$i copy) ;; *) atags+=(-c:a:$i libopus -b:a:$i 128k -ac:a:$i $channels) recode=true ;; esac print -n "a:$i: { $codec_name, $channels, $lang }" done # subtitles nst=${#${(f)"$(ffprobe -hide_banner -v error -select_streams s -show_entries stream=index -of csv=p=0 ${f})"}} stags=() for i in {0..${nst}} ; do if [ $i -eq ${nst} ]; then break fi if [ $i -gt 0 ]; then print -n ", " else print -n " | " fi eval $(ffprobe -hide_banner -v error -select_streams s:$i -show_entries stream=codec_name:stream_tags=language -of flat=sep_char=_ ${f}) codec_name=${streams_stream_0_codec_name} lang=${streams_stream_0_tags_language-und} case "$codec_name" in ass) stags+=(-c:s:$i srt) recode=true ;; *) stags+=(-c:s:$i copy) ;; esac print -n "s:$i: { $codec_name, ${lang} } " done print ']' $recode || continue echo ffmpeg -i "$f" -map 0 $vtags -crf 23 $atags $stags "${f:r}-new.mkv" #exit 0 if ffmpeg -i "$f" -map 0 $vtags -crf 23 $atags $stags "${f:r}-new.mkv" ; then mv "${f:r}-new.mkv" "${f:r}.mkv" if [ ${f:e} != "mkv" ]; then rm -f "$f" fi else [ -f "${f:r}-new.mkv" ] && rm -f "${f:r}-new.mkv" fi done