Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@47ronin
Last active April 7, 2024 06:28
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 47ronin/2df2a78a1c088dc702368bf4fb01a2a4 to your computer and use it in GitHub Desktop.
Save 47ronin/2df2a78a1c088dc702368bf4fb01a2a4 to your computer and use it in GitHub Desktop.
Use yt-dlp to merge best video and best audio formats together into an MPEG-4 container, check for AV1/VP9, and transcode to H.264 if necessary. Usage: ./yt-dlp.sh <video_url>
#!/bin/bash
youtube_url="$1"
echo "Downloading video..."
video_info=$(yt-dlp -e -o "%(title)s" -- "$youtube_url")
sanitized_title=$(echo "$video_info" | sed 's/[^a-zA-Z0-9_.-]/_/g')
output_file="${sanitized_title}.mp4"
yt-dlp -o "temp.mp4" -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' -- "$youtube_url"
detected_codec=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 "temp.mp4")
echo "Detected video codec: $detected_codec"
if [ "$detected_codec" != "h264" ]; then
echo "Transcoding to H.264 format"
ffmpeg -i "temp.mp4" -c:v libx264 -preset medium -crf 23 -c:a aac -b:a 128k "$output_file"
else
echo "No transcoding needed, already in H.264 format"
cp "temp.mp4" "$output_file"
fi
# Clean up temporary file
rm "temp.mp4"
echo "Video saved as: $output_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment