Skip to content

Instantly share code, notes, and snippets.

@kraftwerk28
Last active June 14, 2023 10:34
Show Gist options
  • Save kraftwerk28/9582e7a777e7ee51951157e7ea85f494 to your computer and use it in GitHub Desktop.
Save kraftwerk28/9582e7a777e7ee51951157e7ea85f494 to your computer and use it in GitHub Desktop.
Telegram video sticker tool
#!/bin/bash
#
# Convert a video file to suitable format for Telegram video stickers.
# See: https://core.telegram.org/stickers#video-stickers
# If the video stream has duration larger than required, it will be sped up
# to match 3 seconds.
# Script requires `ffmpeg`, `ffprobe` and `jq` to be present in $PATH.
#
set -euo pipefail
if [[ $# -lt 2 ]]; then
echo "Usage: $0 <input video> <output video> [ffmpeg options]..." >&2
exit 1
fi
export target_duration=3
target_wh=512
export target_size=2020 # TODO: which number to use?
target_fps=30
duration_mul=$(ffprobe -v quiet -show_format -of json "$1" | jq -r \
' (env.target_duration | tonumber) as $d
| .format.duration | tonumber
| if . > $d then $d / . else 1 end')
scale="w=${target_wh}:h=${target_wh}:force_original_aspect_ratio=decrease"
pts="${duration_mul}*PTS"
target_bitrate="$(jq -nr '(env.target_size | tonumber) / (env.target_duration | tonumber)')k"
vfilter="setpts=${pts},fps=${target_fps},scale=${scale}"
in_file="$1"
out_file="${2%.webm}.webm"
shift
shift
set -x
ffmpeg -hide_banner -y -i "$in_file" -c:v libvpx-vp9 -pix_fmt yuva420p -vf "$vfilter" \
-b:v "$target_bitrate" -an -pass 1 -f null "$@" /dev/null
ffmpeg -hide_banner -i "$in_file" -c:v libvpx-vp9 -pix_fmt yuva420p -vf "$vfilter" \
-b:v "$target_bitrate" -an -pass 2 "$@" "${out_file}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment