Skip to content

Instantly share code, notes, and snippets.

@cubehouse
Created July 18, 2020 20:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cubehouse/c4c15bbf090d6db7e975e81e1ffbccd8 to your computer and use it in GitHub Desktop.
Save cubehouse/c4c15bbf090d6db7e975e81e1ffbccd8 to your computer and use it in GitHub Desktop.
Bash Script to convert HDR video files into SDR format. Decent CPU can re-encode around 3-4x faster than video length.
#!/bin/bash
function convert {
filename=$(echo "$1" | cut -f 1 -d '.')
newFilename=${filename}_HD.mkv
if [ -f "$newFilename" ]; then
echo \* $newFilename already exists!
else
COLORS=$(ffprobe -show_streams -v error "$1" |egrep "^color_transfer|^color_space=|^color_primaries=" |head -3)
for C in $COLORS; do
if [[ "$C" = "color_space="* ]]; then
COLORSPACE=${C##*=}
elif [[ "$C" = "color_transfer="* ]]; then
COLORTRANSFER=${C##*=}
elif [[ "$C" = "color_primaries="* ]]; then
COLORPRIMARIES=${C##*=}
fi
done
if [ "${COLORSPACE}" = "bt2020nc" ] && [ "${COLORTRANSFER}" = "smpte2084" ] && [ "${COLORPRIMARIES}" = "bt2020" ]; then
# this file is HDR, convert a duplicate down to SDR
echo $1 contains HDR video track, creating duplicate SDR video file ${filename}...
ffmpeg -vsync 0 -hide_banner -v quiet -stats -hwaccel cuda -init_hw_device opencl=ocl -filter_hw_device ocl -extra_hw_frames 3 -threads 16 -c:v hevc_cuvid -resize 1920x1080 -i "$1" -vf "format=p010,hwupload,tonemap_opencl=tonemap=mobius:param=0.01:desat=0:r=tv:p=bt709:t=bt709:m=bt709:format=nv12,hwdownload,format=nv12" -c:a copy -c:s copy -c:v libx264 -max_muxing_queue_size 9999 "${newFilename}"
else
echo \* $1 already SDR file, no need to convert!
fi
fi
}
for f in "$@"
do
echo "Processing $f..."
convert $f
echo
done
@cubehouse
Copy link
Author

./hdr2sdr *.mkv

Will create new files with the same filename, but "_HD.mkv" on the end of the filename.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment