Skip to content

Instantly share code, notes, and snippets.

@lightmaster
Created December 10, 2020 23:47
Show Gist options
  • Save lightmaster/582225afbbd3810b17811cf81a8acaf4 to your computer and use it in GitHub Desktop.
Save lightmaster/582225afbbd3810b17811cf81a8acaf4 to your computer and use it in GitHub Desktop.
Find all .mp4 files in the current directory and subdirectories and convert them into .mkv files without re-encoding. This does not lose any quality and the resulting files are the same size as the originals. This will also repair any .mp4 files which do not have `ctts atom`, which can cause playback issues in numerous players. It will delete it…
#!/bin/bash
if ! [ -x "$(command -v mkvmerge)" ]; then
echo 'Error: mkvmerge is not installed.' >&2
exit 1
fi
if ! [ -x "$(command -v ffmpeg)" ]; then
echo 'Error: ffmpeg is not installed.' >&2
exit 1
fi
# Save original Input File Separator
SAVEIFS=$IFS
# Set the temporary IFS for this script
IFS=$(echo -en "\n\b")
# Always restore the original IFS regardless of how the script exits
trap 'IFS=$SAVEIFS' EXIT
# Create a variable containing all .mp4 files found recursively
Files=$(find . -name "*.mp4" -type f)
for f in $Files
do
# Print out name of the file we're working on
echo $f
newFileName="${f%.mp4}"
# Create temp file containing all videos from original .mp4
mkvmerge -A -S -o temp.video.mkv "${newFileName}".mp4
# Create temp file containing all audio and subtitles from original
mkvmerge -D -o temp.audio.mkv "${newFileName}".mp4
# Recombine them into a new .mp4 file
ffmpeg -loglevel 0 -hide_banner -stats -y -i temp.video.mkv -i temp.audio.mkv -c copy -c:s srt -map 0 -map 1 "${newFileName}".mkv
# Delete temp files used
rm temp.video.mkv temp.audio.mkv
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment