Sometimes you have a video that has DTS-HD MA as the audio codec, and you have a device that misbehaves. You could transcode it, but, well, here’s a better way. It copies it through (so no loss) and adds an AAC version (in same number of channels).
#!/usr/bin/env python3
# Add an aac track alongside dts
import os, sys, json, re
input_file = sys.argv[1]
output_file = re.sub(".mkv", "-transcoded.mkv", input_file)
if (input_file == output_file):
print("Error: input == output file", file=sys.stderr)
sys.exit(1)
with os.popen('ffprobe -v quiet -print_format json -show_streams "%s"' % sys.argv[1]) as f:
data = json.load(f)
try:
data
except:
print("Error: file <%s> does not exist or is not an mkv" % input_file)
sys.exit(1)
idx_to_transcode = -1
max_idx = -1
max_audio_idx = -1
for stream in data['streams']:
max_idx = max(max_idx, stream['index'])
if stream['codec_type'] == 'audio':
max_audio_idx = max(max_audio_idx, stream['index'])
if stream['codec_name'] == 'dca' and stream['profile'] == 'DTS-HD MA' and ('language' not in stream or stream['language'] == 'eng'):
idx_to_transcode = stream['index']
new_idx = max_idx + 1
# The DTS-HD MA English stream is copied, and a new AAC transcoded one if it is made
# at new_idx. All other streams are copied as-is. The new stream is made default
cmd = ("ffmpeg -y "
"-i '%s' "
"-map 0:v? "
"-map 0:a? "
"-map 0:s? "
"-c:a copy "
"-c:v copy "
"-c:s copy "
"-map 0:%u -strict -2 -c:%u aac "
"-metadata:s:%u language=eng "
"-disposition:%u default "
"-disposition:%u none "
"'%s'") % ( input_file, idx_to_transcode, new_idx, new_idx, new_idx, idx_to_transcode, output_file)
print(cmd)
r = os.system(cmd)
if r == 0:
print("All was good!")
r = os.rename(output_file, input_file)
sys.exit(r)
else:
print("Error: input == output file", file=sys.stderr)
sys.exit(1)
Leave a Reply