h264/h264

123 lines
2.4 KiB
Plaintext
Raw Normal View History

2023-02-28 21:46:21 -07:00
#! /bin/sh
set -e
usage () { cat <<EOD 1>&2; }
Usage: $0 [OPTIONS...] SRC [SRC...]
2023-02-28 22:12:41 -07:00
Re-encodes to h.264, preserving audio and subtitles.
2023-02-28 21:46:21 -07:00
Output will be written to \$SRC.h264.mp4
-height H Rescale to no taller than H
-1080p Rescale to no bigger than 1080p
-720p Rescale to no bigger than 720p
-480p Rescale to no bigger than 480p
2023-03-01 09:40:20 -07:00
-bitrate B Set average bitrate to B, overriding rescale setting
2023-02-28 21:46:21 -07:00
-swenc Software encode instead of hardware
EOD
height=ih
codec=h264_v4l2m2m
bitrate="-b:v 2048k"
while true; do
case "$1" in
-height|--height)
2023-03-01 09:40:20 -07:00
height=$2
shift 2
2023-02-28 21:46:21 -07:00
;;
-1080p|--1080p)
height=1080
bitrate="-b:v 2048k"
shift
;;
-720p|--720p)
height=720
2023-03-01 09:40:20 -07:00
bitrate="-b:v 1200k"
2023-02-28 21:46:21 -07:00
shift
;;
-480p|--480p)
height=480
bitrate="-b:v 512k"
shift
;;
2023-03-01 09:40:20 -07:00
-bitrate|--bitrate)
bitrateManual="-b:v $2"
shift 2
;;
2023-02-28 21:46:21 -07:00
-swenc|--swenc)
codec=h264
shift
;;
-*)
usage
exit
;;
*)
break
;;
esac
done
if [ "$codec" = "h264" ]; then
bitrate="-crf 28"
fi
2023-03-01 09:40:20 -07:00
bitrate=${bitrateManual:-$bitrate}
2023-02-28 21:46:21 -07:00
log () {
echo "=== $*"
}
cmd () {
nice "$@"
}
# This got a height of 719 (n%2 must = 0)
#-vf "scale='min($width,iw)':'min($height,ih)':force_original_aspect_ratio=decrease,format=yuv420p" \
for fn in "$@"; do
base=${fn%.*}
filename=$(basename "$fn")
intermediate="$base.nut"
out="$base.h264.mkv"
[ -f "$out" ] && continue
case "$fn" in *.h264.mp4) continue ;; esac
# ffmpeg has some bizarro thing where the h264_v4l2m2m codec won't write to a mkv file,
# In addition, some subtitles interfere with it too.
# Solution: transcode video + audio into an intermediate file,
# then add back any subtitles.
log "$filename - Scale/Transcode"
cmd ffmpeg \
-hide_banner \
-loglevel warning \
-stats \
-i "$fn" \
-map 0:v \
-vf "scale=-2:'min($height,ih)':force_original_aspect_ratio=decrease,format=yuv420p" \
-c:v $codec \
$bitrate \
-map 0:a \
-c:a copy \
-num_capture_buffers 16 \
-num_output_buffers 32 \
-y \
"$intermediate"
log "$filename - Add subtitles"
cmd ffmpeg \
-hide_banner \
-loglevel warning \
-stats \
-i "$intermediate" \
-i "$fn" \
-map 0:v \
-map 0:a \
-map 1:s? \
2023-02-28 22:00:45 -07:00
-c copy \
2023-02-28 21:46:21 -07:00
-y \
"$out"
2023-02-28 22:06:06 -07:00
rm "$intermediate"
2023-02-28 21:46:21 -07:00
done