Skip to content

Instantly share code, notes, and snippets.

@htpc-helper
Last active July 19, 2024 08:58
Show Gist options
  • Save htpc-helper/878994aa82e2cfb9cdde6e6ce4b17b12 to your computer and use it in GitHub Desktop.
Save htpc-helper/878994aa82e2cfb9cdde6e6ce4b17b12 to your computer and use it in GitHub Desktop.
Bash script for converting mkv to mp4 without transcoding video
#!/bin/bash
# Configure inputs
INPUT_FOLDER='/media'
DELETE_ORIGINALS=false #set to true to delete original files
# Set $IFS variable to handle files whitespace in name
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
# Generate list of files to be processed
FILES=`find "$INPUT_FOLDER" -name "*.mkv" | sort`
# Iterate over files in list
for FILE in $FILES
do
# Generate output file name
OUTPUT_FILE=`echo $FILE | rev | cut -d. -f2- | rev`".mp4"
# Analyse file params with ffprobe
AUDIO_CH=`ffprobe "${FILE}" -show_streams -select_streams a:0 -loglevel quiet | sed -n '/channels=/s/channels=//p'`
AUDIO_CODEC=`ffprobe "${FILE}" -show_streams -select_streams a:0 -loglevel quiet | sed -n '/codec_name=/s/codec_name=//p'`
# Process with ffmpeg
if [[ $AUDIO_CH == "6" ]]; then
# Downmix 6ch audio to 2ch aac
ffmpeg -i "${FILE}" -c:v copy -af aresample=matrix_encoding=dplii -ac 2 -c:a aac -strict -2 -b:a 128k "${OUTPUT_FILE}"
elif [[ $AUDIO_CODEC == "ac3" ]]; then
# Convert ac3 audio to aac for better compatibility
ffmpeg -i "${FILE}" -c:v copy -c:a aac -strict -2 -b:a 128k "${OUTPUT_FILE}"
elif [[ $AUDIO_CODEC == "dca" ]]; then
# Convert dts audio to aac for better compatibility
ffmpeg -i "${FILE}" -c:v copy -c:a aac -strict -2 -b:a 128k "${OUTPUT_FILE}"
else
# Simple container change for files that do not hit conditions above
ffmpeg -i "${FILE}" -codec copy "${OUTPUT_FILE}"
fi
# Delete original file if configured to do so
if $DELETE_ORIGINALS; then
rm "${FILE}"
fi
done
@htpc-helper
Copy link
Author

htpc-helper commented Jun 19, 2017

Updated to handle files with white space in filename

Further work:

  • option to transcode or skip for video codecs such as h265
  • publish as Docker container using Alpine Linux
  • Docker run command to set environmental variable that determines whether original files are deleted

@htpc-helper
Copy link
Author

Updated to fix problem where only first file was being processed when multiple files in input folder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment