Skip to content

Instantly share code, notes, and snippets.

@ddelange
Last active December 19, 2022 07:09
Show Gist options
  • Save ddelange/b78de1c0d046f61ab550f54df61f9bba to your computer and use it in GitHub Desktop.
Save ddelange/b78de1c0d046f61ab550f54df61f9bba to your computer and use it in GitHub Desktop.
Mux multiple subtitle files into an mp4 file
# pip install sh pycountry
import re
from pathlib import Path
import pycountry
from sh import ffmpeg
def mux_mp4_subs(inp, outp, *subs, _cwd=None, **subs_map):
"""Mux multiple subtitle files into an mp4 file.
Example:
>>> mux_mp4_subs(
... "original.mp4",
... "original.subs.mp4",
... "2_English.srt",
... czech="Subs/4_Czech.srt",
... )
"""
sub_files, sub_commands = [], []
subs_map = {**{Path(sub).stem: sub for sub in subs}, **subs_map}
for i, (lang, path) in enumerate(subs_map.items()):
sub_files += ["-i", path]
lang = "".join(re.findall("[a-z]+", lang.lower()))
try:
# https://en.wikibooks.org/wiki/FFMPEG_An_Intermediate_Guide/subtitle_options#Set_Subtitle_Language
try:
lang = pycountry.languages.lookup(lang).alpha_3
except LookupError:
lang = pycountry.countries.search_fuzzy(lang)[0].alpha_3.lower()
except LookupError:
pass
sub_commands += ["-map", str(i + 1), f"-metadata:s:s:{i}", f"language={lang}"]
try:
# https://stackoverflow.com/questions/46521858/adding-multiple-srt-subtitle-streams-to-mp4-with-ffmpeg#comment129177458_65587372
return ffmpeg(
"-i",
inp,
*sub_files,
*sub_commands,
*"-map 0:v -map 0:a -c:v copy -c:a copy -c:s mov_text -movflags use_metadata_tags -map_metadata 0".split(),
outp,
_cwd=_cwd,
)
except Exception as exc:
raise Exception(exc.stderr.decode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment