Skip to content

Instantly share code, notes, and snippets.

@fstanis
Last active July 5, 2021 12:05
Show Gist options
  • Save fstanis/696beb77717719f5cd0943e3c754f9bf to your computer and use it in GitHub Desktop.
Save fstanis/696beb77717719f5cd0943e3c754f9bf to your computer and use it in GitHub Desktop.
Simple shell script for creating HQ gifs from videos using ffmpeg
#!/bin/bash
# Based on: https://medium.com/@colten_jackson/doing-the-gif-thing-on-debian-82b9760a8483
# Command line arguments:
# -i <input file> (required)
# -o <output file> (required)
# -s <start time>
# -t <duration in seconds>
# -f <output FPS>
# -w <output width>
# -p <presentation timestamp, for speeding up or down>
# -c <crop string, e.g. 1080:540:500:100>
# -d <pad string, e.g. 640:480:0:40:violet>
# -y (overwrite output files without asking)
# -n (deinterlace)
set -e
flag_ss=()
flag_t=()
while getopts 's:t:i:f:o:w:p:c:d:yn' flag; do
case "${flag}" in
s) flag_ss=("-ss" "${OPTARG}") ;;
t) flag_t=("-t" "${OPTARG}") ;;
i) flag_i="${OPTARG}" ;;
o) flag_output="${OPTARG}" ;;
f) flag_fps="${OPTARG}" ;;
w) flag_width="${OPTARG}" ;;
p) flag_pts="${OPTARG}" ;;
c) flag_crop="${OPTARG}" ;;
d) flag_pad="${OPTARG}" ;;
y) flag_y="-y" ;;
n) flag_interlace="yadif," ;;
*) exit 1 ;;
esac
done
if [ -z "$flag_i" ] || [ -z "$flag_output" ]; then
echo "Missing input or output"
exit 1
fi
filter_str="$flag_interlace"
if [ ! -z "$flag_fps" ]; then
filter_str="fps=$flag_fps,"
fi
if [ ! -z "$flag_crop" ]; then
filter_str="${filter_str}crop=$flag_crop,"
fi
if [ ! -z "$flag_pad" ]; then
filter_str="${filter_str}pad=$flag_pad,"
fi
if [ ! -z "$flag_width" ]; then
filter_str="${filter_str}scale=$flag_width:-1:flags=lanczos,"
fi
if [ ! -z "$flag_pts" ]; then
filter_str="${filter_str}setpts=${flag_pts}*PTS,"
fi
palette_file=$(mktemp -u --suffix=".png")
ffmpeg "${flag_ss[@]}" "${flag_t[@]}" -i "$flag_i" -vf "${filter_str}palettegen" "$palette_file"
if [ ! -z $filter_str ]; then
filter_str="${filter_str%?}[x];[x][1:v]"
fi
ffmpeg $flag_y "${flag_ss[@]}" "${flag_t[@]}" -i "$flag_i" -i "$palette_file" -filter_complex "${filter_str}paletteuse" "$flag_output"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment