Skip to content

Instantly share code, notes, and snippets.

@NonLogicalDev
Last active February 8, 2025 02:00
Show Gist options
  • Save NonLogicalDev/86452b0e9ad8b7b41ab262f3eadbc259 to your computer and use it in GitHub Desktop.
Save NonLogicalDev/86452b0e9ad8b7b41ab262f3eadbc259 to your computer and use it in GitHub Desktop.
FFMPEG: Convert to GIF.sh
#!/bin/bash
cnv_to_gif() {
local usage="Usage: $0 [--fps <fps>] [--wsize <width>] [--hsize <height>] [--start <timestamp>] [--end <timestamp>] <input> [<output>]"
local in_f="" out_f="" fps=15 wsize="500" hsize="-1" start="00:00:00" end="00:00:00"
while [[ $# -gt 0 ]]; do
case "$1" in
--fps) fps="$2"; shift 2;;
--wsize) wsize="$2"; shift 2;;
--hsize) hsize="$2"; shift 2;;
--start) start="$2"; shift 2;;
--end) end="$2"; shift 2;;
-h|--help)
echo "$usage"; exit 0
;;
*)
if [[ -z "$in_f" ]]; then
in_f="$1"
elif [[ -z "$out_f" ]]; then
out_f="$1"
fi
shift
;;
esac
done
if [[ -z $out_f ]]; then
out_f="${in_f}.gif"
fi
echo "| IN |: $in_f"
echo "| OUT |: $out_f"
echo "| PARAMS |: --fps=$fps / --wsize=$wsize / --hize=$hsize / --start=$start / --end=$end"
read -p "Proceed with conversion? [y/N] " cnf
if [[ "$cnf" != "y" && "$cnf" != "Y" ]]; then echo "Aborted"; exit 1; fi
local trim_args=()
if [[ "$start" != "00:00:00" ]]; then trim_args+=("-ss" "$start"); fi
if [[ "$end" != "00:00:00" ]]; then trim_args+=("-to" "$end"); fi;
# FILTER: pre-process, set fps, scale and split into 2 streams for pallette generation
# FILTER: generate pallette for gif output (consumes s0)
# FILTER: apply pallette to video stream (consumes s1 and pallette from p)
ffmpeg -hide_banner "${trim_args[@]}" -i "${in_f}" -filter_complex "
[in] $trim_filter fps=${fps}, scale=${wsize}:${hsize}:flags=lanczos [preproc];
[preproc] split [s0][s1];
[s0] palettegen= max_colors=256 : stats_mode=diff [p];
[s1][p] paletteuse= dither=bayer : bayer_scale=5 : diff_mode=rectangle [out];
[out]null
" "${out_f}"
}
cnv_to_gif "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment