Skip to content

Instantly share code, notes, and snippets.

@scastillo
Created October 30, 2024 15:55
Show Gist options
  • Save scastillo/634404a1e4f256f64ac85215e2ed36c8 to your computer and use it in GitHub Desktop.
Save scastillo/634404a1e4f256f64ac85215e2ed36c8 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Configuration
OUTPUT_DIR="optimized_videos"
FORMATS=("mp4" "webm")
MAX_WIDTH=1280
AUDIO_BITRATE="128k"
VIDEO_BITRATE="2M"
CRF=23 # Constant Rate Factor (18-28, lower = better quality)
# Create output directory
mkdir -p "$OUTPUT_DIR"
optimize_video() {
local input_file="$1"
local filename=$(basename "$input_file")
local name="${filename%.*}"
echo "Processing: $filename"
# MP4 (H.264) version
ffmpeg -i "$input_file" \
-c:v libx264 \
-preset slow \
-crf $CRF \
-c:a aac \
-b:a $AUDIO_BITRATE \
-maxrate $VIDEO_BITRATE \
-bufsize $VIDEO_BITRATE \
-vf "scale=min($MAX_WIDTH\,iw):-2" \
-movflags +faststart \
"$OUTPUT_DIR/${name}_optimized.mp4"
# WebM version
ffmpeg -i "$input_file" \
-c:v libvpx-vp9 \
-crf $CRF \
-b:v 0 \
-c:a libopus \
-b:a $AUDIO_BITRATE \
-vf "scale=min($MAX_WIDTH\,iw):-2" \
"$OUTPUT_DIR/${name}_optimized.webm"
}
# Usage instructions
show_help() {
echo "Video Optimizer for Web"
echo "Usage: $0 [options] <input_files...>"
echo ""
echo "Options:"
echo " -h, --help Show this help message"
echo " -w, --width Set maximum width (default: $MAX_WIDTH)"
echo " -q, --quality Set quality (18-28, lower is better, default: $CRF)"
echo " -b, --bitrate Set video bitrate (default: $VIDEO_BITRATE)"
echo " -a, --audio Set audio bitrate (default: $AUDIO_BITRATE)"
echo ""
echo "Example: $0 -w 720 -q 20 video1.mp4 video2.mov"
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
show_help
exit 0
;;
-w|--width)
MAX_WIDTH="$2"
shift 2
;;
-q|--quality)
CRF="$2"
shift 2
;;
-b|--bitrate)
VIDEO_BITRATE="$2"
shift 2
;;
-a|--audio)
AUDIO_BITRATE="$2"
shift 2
;;
*)
if [ -f "$1" ]; then
optimize_video "$1"
else
echo "Error: File not found - $1"
fi
shift
;;
esac
done
# Check if no input files were provided
if [ $# -eq 0 ]; then
show_help
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment