Skip to content

Instantly share code, notes, and snippets.

@YellowOnion
Created October 19, 2025 07:05
Show Gist options
  • Select an option

  • Save YellowOnion/d589cb015acd6befc93a6dfe04e0f65a to your computer and use it in GitHub Desktop.

Select an option

Save YellowOnion/d589cb015acd6befc93a6dfe04e0f65a to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S nix shell nixpkgs#ffmpeg-full nixpkgs#ghc --command bash
# -*- mode: sh -*-
VALID_ARGS=$(getopt -o s:d:b --long seek:,duration:,bias: -- "$@")
if [[ $? -ne 0 ]]; then
exit 1;
fi
eval set -- "$VALID_ARGS"
while [ : ]; do
case "$1" in
-s | --seek)
SEEK="-ss $2"
shift 2
;;
-d | --duration)
DUR="$2"
shift 2
;;
-b | --bias)
BIAS=$2
shift 2
;;
--)
shift 1
break
;;
esac
done
if [ -x "$1" ]; then
echo input not supplied!
exit 1
fi
INPUT="$1"
if [ -x "$2" ]; then
echo output not supplied!
exit 2
fi
OUTPUT=$2
LEN=
RET=
if [ -n "$DUR" ]; then
LEN=$(date +'%s' --utc -d "1970-01-01 0:$DUR" 2>/dev/null)
RET=$?
if [[ $RET -ne 0 ]]; then
LEN=$(date +'%s' --utc -d "1970-01-01 0:0:$DUR" 2>/dev/null)
RET=$?
fi
[[ $RET -ne 0 ]] && echo "can't parse duration: $DUR" && exit 3
fi
if [ -x "$DUR" ]; then
LEN=$(ffprobe -select_streams v:0 -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$INPUT")
fi
BITRATE=$( ghc -e "2^13 * 8 * 0.995 / $LEN - 64" )
if [ -x $BIAS ]; then
BIAS=0
fi
Y=$(ghc -e "$(cat <<EOF
let x = floor $ (1 + $BIAS/10) * ($BITRATE / 4 * 15)**0.8
in (x+40) - x \`mod\` 40
EOF
)")
X=$(ghc -e "2 * (floor $ $Y / 9 * 8)")
echo seek=$SEEK len=$LEN x=$X y=$Y bias=$BIAS $BITRATE kbps $INPUT $OUTPUT
SWS_EXTRA=force_original_aspect_ratio=decrease:force_divisible_by=2
SCALE_ARGS="-vf scale='min($X,1920)':'min($Y,1080)':$SWS_EXTRA"
PARAMS=undershoot-pct=1:overshoot-pct=0:rc=1:tune=0:passes=2
CODEC="libvpx-vp9 -row-mt 1 -threads 16"
set -x
ffmpeg ${SEEK} \
-i "${INPUT}" \
-t "${LEN}" \
-sn \
-an \
-c:v $CODEC $SCALE_ARGS -b:v "${BITRATE}k" -pass 1 \
-f null /dev/null
ffmpeg $SEEK \
-i "${INPUT}" \
-t "${LEN}" \
-sn \
-c:a libopus \
-ac 2 -b:a 64k \
-c:v $CODEC $SCALE_ARGS -b:v "${BITRATE}k" -pass 2 \
-y "${OUTPUT}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment