Skip to content

Instantly share code, notes, and snippets.

@shawnyeager
Last active February 25, 2025 14:03
Show Gist options
  • Save shawnyeager/6b83fff4ae886079bc3ed8a896b22c94 to your computer and use it in GitHub Desktop.
Save shawnyeager/6b83fff4ae886079bc3ed8a896b22c94 to your computer and use it in GitHub Desktop.
Download YouTube video and re-encode for playback on web and iOS (requires yt-dlp and ffmpeg)
#!/usr/bin/env bash
# Usage: download-mp4.sh <YouTube_URL>
if [ -z "$1" ]; then
echo "Usage: download-mp4.sh <YouTube_URL>"
exit 1
fi
URL="$1"
# Download video using yt-dlp and store the exact filename
FILENAME=$(yt-dlp --no-simulate \
-f "bestvideo[ext=mp4][height<=720]+bestaudio[ext=m4a]/best[ext=mp4]/best" \
--merge-output-format mp4 \
-o "%(title)s.%(ext)s" \
--print filename \
"$URL")
# Verify the downloaded filename
echo "Downloaded filename: $FILENAME"
# Re-encode with FFmpeg using hardware acceleration (if available) + Progress Indicator
ffmpeg -y -i "$FILENAME" \
-c:v libx264 -preset veryfast -profile:v baseline -level 3.0 -pix_fmt yuv420p \
-c:a aac -b:a 128k \
-movflags +faststart \
-progress pipe:1 -stats \
"${FILENAME}.tmp.mp4" | awk '/out_time_ms/ { printf "\rProgress: %.2f%%", $2 / 1000000 }'
# Replace the original file with the faster-encoded version
mv "${FILENAME}.tmp.mp4" "$FILENAME"
echo -e "\nDone: $FILENAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment