Skip to content

Instantly share code, notes, and snippets.

@i5heu
Created April 28, 2024 19:54
Show Gist options
  • Save i5heu/f2f4b63930ed039941b93b8783c54e70 to your computer and use it in GitHub Desktop.
Save i5heu/f2f4b63930ed039941b93b8783c54e70 to your computer and use it in GitHub Desktop.
FFmpeg Bash to turn a 5.1 mkv into a 2.1 mkv. It extracts the original 5.1 audio, creates a stereo downmix, and adds a compressed & enhanced 2.1 track for improved dialogue clarity. Ideal for enhancing audio intelligibility in media files. Will also give the new mkv the name of the folder the original mkv is in.
#!/bin/bash
# Check if the input file is provided
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <input.mkv>"
exit 1
fi
input="$1"
# Ensure the input path is absolute to avoid errors in path handling
input=$(realpath "$input")
dirname=$(basename "$(dirname "$input")")
output="$(dirname "$input")/${dirname}_add-2.1.mkv"
# Extract the original 5.1 DTS track
ffmpeg -i "$input" -map 0:a -c copy "original_5.1_track.dts"
# Create the stereo DTS track from the 5.1 DTS track
ffmpeg -i "original_5.1_track.dts" -c:a dca -strict -2 -af "volume=1.660156, pan=stereo|c0=0.5*c2+0.707*c0+0.707*c4+0.5*c3|c1=0.5*c2+0.707*c1+0.707*c5+0.5*c3" "derived_stereo.dts"
# Create compressed and normalized 2.1 track
ffmpeg -i "derived_stereo.dts" -c:a dca -strict -2 -af "acompressor=ratio=4.0:threshold=-30dB:attack=5:release=50, loudnorm" "enhanced_stereo.dts"
# Merge the original 5.1, new stereo, and compressed stereo tracks into an MKV
ffmpeg -i "$input" -i "original_5.1_track.dts" -i "derived_stereo.dts" -i "enhanced_stereo.dts" \
-map 0:v \
-map 1:a \
-map 2:a \
-map 3:a \
-c:v copy \
-c:a copy \
-metadata:s:a:0 title="5.1 Original Audio Track" \
-metadata:s:a:1 title="2.1 Downmixed Stereo Track" \
-metadata:s:a:2 title="2.1 Compressed & Enhanced Stereo Track" \
"$output"
# Clean up the temporary tracks
rm "original_5.1_track.dts" "derived_stereo.dts" "enhanced_stereo.dts"
echo "Processing completed. Output file: $output"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment