Skip to content

Instantly share code, notes, and snippets.

@pax
Created January 27, 2024 18:14
Show Gist options
  • Save pax/80d2894da3d5beb5384901193a3a3398 to your computer and use it in GitHub Desktop.
Save pax/80d2894da3d5beb5384901193a3a3398 to your computer and use it in GitHub Desktop.
Batch compress and resize videos (mov, mp3, mp4)
#!/bin/bash
# Parameters
CRF_VALUE=28 # Quality level for video compression (lower is higher quality)
FRAME_RATE=24 # Frame rate for video files
AUDIO_BITRATE=96k # Audio bitrate for MP3 files
RESIZE_PERCENT=75 # Resize percent (e.g., 75 for 75% of original size)
MIN_WIDTH=2800 # Minimum width in pixels to apply resizing
# Target directory (use current directory if not specified)
TARGET_DIR=${1:-.}
# Function to calculate new dimensions
function calculate_new_dimensions {
WIDTH=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 "$1")
HEIGHT=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$1")
# Check if resizing is needed
if [ "$WIDTH" -ge "$MIN_WIDTH" ] || [ "$HEIGHT" -ge "$MIN_WIDTH" ]; then
NEW_WIDTH=$(echo "$WIDTH * $RESIZE_PERCENT / 100" | bc)
NEW_HEIGHT=$(echo "$HEIGHT * $RESIZE_PERCENT / 100" | bc)
echo "-vf scale=$NEW_WIDTH:$NEW_HEIGHT"
else
echo ""
fi
}
# Change to target directory
cd "$TARGET_DIR"
# Compress and resize MOV and MP4 files
for f in *.mov *.mp4; do
echo "Processing video file $f"
SCALE=$(calculate_new_dimensions "$f")
ffmpeg -i "$f" -vcodec libx264 -crf "$CRF_VALUE" -r "$FRAME_RATE" $SCALE "${f%.*}-compressed.${f##*.}"
mv "${f%.*}-compressed.${f##*.}" "$f"
done
# Compress MP3 files
for f in *.mp3; do
echo "Processing audio file $f"
ffmpeg -i "$f" -ab "$AUDIO_BITRATE" "${f%.mp3}-compressed.mp3"
mv "${f%.mp3}-compressed.mp3" "$f"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment