Skip to content

Instantly share code, notes, and snippets.

@stephen-bunn
Last active October 10, 2021 01:34
Show Gist options
  • Save stephen-bunn/60f46ba59f5be161172db5ac43867f6f to your computer and use it in GitHub Desktop.
Save stephen-bunn/60f46ba59f5be161172db5ac43867f6f to your computer and use it in GitHub Desktop.
Quick script I use for updating existing chapter names in video files
#!/usr/bin/env sh
DEPENDENCIES="ffprobe ffmpeg jq"
for dep_name in $DEPEDENCIES
do
if !(command -v "$dep_name" > /dev/null 2>&1); then
echo "$dep_name not found";
exit 1;
fi
done
# probe existing tags and chapters
probe=$(ffprobe -v quiet -print_format json -show_chapters -show_format "$1")
# format tags as key=value pairs
tags=$(echo "$probe" | jq -r '.format.tags | to_entries[] | .key + "=" + .value')
# format chapters as ini sections with TIMEBASE, START, END, and title
chapters=$(echo "$probe" | jq -r '.chapters[] | "[CHAPTER]\nTIMEBASE=" + .time_base + "\nSTART=" + (.start|tostring) + "\nEND=" + (.end|tostring) + "\ntitle=" + .tags.title + "\n"')
# create a temporary file for editing metadata
tempname="ffmpeg-meta-$(uuidgen).ini"
tempdir=$(mktemp -d)
# ensure that temporary directory is removed on script exit or failure
trap "rm -R $tempdir" 0 2 3 15
temppath="$tempdir/$tempname"
# use the user's editor to prompt for metadata updates
printf ";FFMETADATA1\n$tags\n\n$chapters" > $temppath
$EDITOR $temppath
# write out new file with updated metadata using the `.chapt` suffix extension
ext=$(echo "$1" | awk -F . '{if (NF>1) {print $NF}}')
ffmpeg -i "$1" -i "$temppath" -map_metadata 1 -map_chapters 1 -codec copy "$1.chapt.$ext"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment