Last active
June 14, 2021 12:51
-
-
Save u1735067/98b1b8f6fce2d3365bfd14e44ff90580 to your computer and use it in GitHub Desktop.
Tool to extract one or many tracks from one or many mkv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
''' BSD 3-Clause License — but if it was useful to you, you may tell me :) | |
Copyright (c) 2016-2017, Alexandre Levavasseur | |
All rights reserved. | |
Redistribution and use in source and binary forms, with or without | |
modification, are permitted provided that the following conditions are met: | |
* Redistributions of source code must retain the above copyright | |
notice, this list of conditions and the following disclaimer. | |
* Redistributions in binary form must reproduce the above copyright | |
notice, this list of conditions and the following disclaimer in the | |
documentation and/or other materials provided with the distribution. | |
* Neither the name of the copyright holder nor the names of its | |
contributors may be used to endorse or promote products | |
derived from this software without specific prior written permission. | |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY | |
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
''' | |
# To set | |
extract_types = { # Types as in reported by mkvmerge | |
'video': None, | |
'audio': ['fre'], | |
'subtitles': [], # empty = all, None = none | |
'button': None # ? | |
} | |
mkvtoolnix_basepath = r'C:\path\to\mkvtoolnix' | |
mkvmerge = mkvtoolnix_basepath+'\mkvmerge.exe' | |
mkvextract = mkvtoolnix_basepath+'\mkvextract.exe' | |
### | |
import sys, os, glob, subprocess, json | |
from collections import OrderedDict | |
# https://mkvtoolnix.download/doc/mkvextract.html#mkvextract.output_file_formats | |
# https://github.com/mbunkus/mkvtoolnix/blob/release-15.0.0/src/extract/xtr_base.cpp#L139 | |
# https://github.com/mbunkus/mkvtoolnix/blob/release-15.0.0/src/common/codec.h#L27 | |
# https://github.com/mbunkus/mkvtoolnix/blob/release-15.0.0/src/common/codec.cpp#L26 | |
# https://github.com/mbunkus/mkvtoolnix/blob/release-15.0.0/src/common/file_types.cpp#L25 | |
codec_to_extension = { | |
'A_AC3': 'ac3', | |
'A_EAC3': 'eac3', | |
'A_MPEG/L2': 'mp2', | |
'A_MPEG/L3': 'mp3', | |
'A_DTS': 'dts', | |
'A_PCM/INT/': 'wav', | |
'A_FLAC': 'flac', | |
'A_ALAC': 'caf', | |
'A_VORBIS': 'oga', | |
'A_OPUS': 'opus', | |
'A_AAC': 'aac', | |
'A_REAL/': 'ra', | |
'A_MLP': 'mlp', | |
'A_TRUEHD': 'thd', | |
'A_TTA1': 'tta', | |
'A_WAVPACK4': 'wv', | |
'V_MS/VFW/FOURCC': 'avi', | |
'V_MPEG4/ISO/AVC': 'h264', | |
'V_MPEGH/ISO/HEVC': 'h265', | |
'V_REAL/': 'rv', | |
'V_MPEG1': 'm1v', | |
'V_MPEG2': 'm2v', | |
'V_THEORA': 'ogv', | |
'V_VP8': 'ivf', | |
'V_VP9': 'ivf', | |
'S_TEXT/UTF8': 'srt', | |
'S_TEXT/ASCII': 'srt', | |
'S_TEXT/SSA': 'ssa', | |
'S_TEXT/ASS': 'ass', | |
'S_SSA': 'ssa', | |
'S_ASS': 'ass', | |
'S_VOBSUB': 'sub', # Will be overwrited to .sub and .idx | |
'S_TEXT/USF': 'usf', | |
'S_KATE': 'ogx', | |
'S_HDMV/PGS': 'sup', | |
'S_HDMV/TEXTST': 'textst', | |
'S_TEXT/WEBVTT': 'vtt', | |
} | |
def extension_lookup(codec_id): | |
for codec, extension in codec_to_extension.items(): | |
if codec_id.lower().startswith(codec.lower()): | |
return extension | |
#return 'unk' | |
return codec_id[2:].lower().replace('/', '-') | |
files = glob.glob(sys.argv[1]) | |
for fileno, file in enumerate(files): | |
log_prefix = '[{}/{}] File {}'.format(fileno+1, len(files), os.path.basename(file)) | |
try: | |
# https://docs.python.org/3/library/subprocess.html | |
json_infos = subprocess.check_output((mkvmerge, '-i', '-F', 'json', file)) | |
infos = json.loads(json_infos.decode()) | |
except Exception as e: | |
print(log_prefix+', error while retrieiving informations: {}'.format(e), file=sys.stderr) | |
continue | |
to_extract = OrderedDict() # Keep tracks in order .. | |
for track in infos['tracks']: | |
if track['type'] in extract_types.keys() and extract_types[track['type']] is not None: | |
try: | |
lang = track['properties']['language'] if 'language' in track['properties'] else 'eng' # Or '---' ? | |
if (not len(extract_types[track['type']])) or (lang in extract_types[track['type']]): | |
to_extract[track['id']] = '.'.join(( | |
os.path.splitext(file)[0], | |
track['type'], | |
str(track['id']), | |
lang, | |
extension_lookup(track['properties']['codec_id']) | |
)) | |
except Exception as e: | |
print(log_prefix+', track {}, error while creating output list: {}'.format(track['id'], e), file=sys.stderr) | |
if not len(to_extract): | |
print(log_prefix+': no track marked for extraction', file=sys.stderr) | |
continue | |
try: | |
args = [mkvextract, 'tracks', file] | |
for track_id, outfile in to_extract.items(): | |
args.append(str(track_id)+':'+outfile) | |
print(log_prefix+': executing '+' '.join(('"'+arg+'"' if " " in arg else arg for arg in args))) | |
subprocess.check_call(args) | |
except Exception as e: | |
print(log_prefix+', error executing extraction command: {}'.format(e), file=sys.stderr) | |
''' | |
> py .\extract_subs.py *.mkv | |
[1/1] MyFile.mkv: executing C:\path\to\mkvtoolnix\mkvextract.exe tracks MyFile.mkv 2:MyFile.audio.2.fre.ac3 3:MyFile.subtitles.3.eng.sub 4:MyFile.subtitles.4.fre.sub 5:MyFile.subtitles.5.ger.sub 6:MyFile.subtitles.6.fre.sub | |
Extracting track 2 with the CodecID 'A_AC3' to the file 'MyFile.audio.2.fre.ac3'. Container format: Dolby Digital (AC-3) | |
Extracting track 3 with the CodecID 'S_VOBSUB' to the file 'MyFile.subtitles.3.eng.sub'. Container format: VobSubs | |
Extracting track 4 with the CodecID 'S_VOBSUB' to the file 'MyFile.subtitles.4.fre.sub'. Container format: VobSubs | |
Extracting track 5 with the CodecID 'S_VOBSUB' to the file 'MyFile.subtitles.5.ger.sub'. Container format: VobSubs | |
Extracting track 6 with the CodecID 'S_VOBSUB' to the file 'MyFile.subtitles.6.fre.sub'. Container format: VobSubs | |
Writing the VobSub index file 'MyFile.subtitles.3.eng.idx'. | |
Writing the VobSub index file 'MyFile.subtitles.4.fre.idx'. | |
Writing the VobSub index file 'MyFile.subtitles.5.ger.idx'. | |
Writing the VobSub index file 'MyFile.subtitles.6.fre.idx'. | |
Progress: 100% | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment