Last active
August 15, 2022 18:59
-
-
Save 0xallie/12b57ef65ba8db746c0d51d6aff0421d to your computer and use it in GitHub Desktop.
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
from __future__ import annotations | |
import argparse | |
import os | |
import subprocess | |
from pathlib import Path | |
def strip_cc(file: Path | os.PathLike[str]) -> None: | |
""" | |
Strip EIA-608 closed captions from a H.264 MP4 file | |
while preserving x264 encoding settings. | |
""" | |
file = Path(file) | |
with open(file, "rb") as fd: | |
data = fd.read(60000) | |
needs_strip = False | |
encoding_settings = None | |
if b"1GA94" in data: | |
needs_strip = True | |
if b"x264" in data: | |
i = data.index(b"x264") | |
encoding_settings = data[i : i + data[i:].index(b"\x00")] | |
if not needs_strip: | |
return | |
bitstream_filters = ["filter_units=remove_types=6"] | |
if encoding_settings: | |
bitstream_filters.append( | |
"h264_metadata=sei_user_data={magic}+{settings}".format( | |
magic="dc45e9bde6d948b7962cd820d923eeef", | |
settings=encoding_settings.replace(b":", rb"\\:").replace(b",", rb"\,").decode(), | |
) | |
) | |
fixed_file = file.with_suffix(".fixed.mp4") | |
subprocess.run( | |
[ | |
"ffmpeg", | |
"-y", | |
"-nostdin", | |
"-hide_banner", | |
"-loglevel", | |
"error", | |
"-stats", | |
"-i", | |
file, | |
"-c", | |
"copy", | |
"-bsf:v", | |
",".join(bitstream_filters), | |
fixed_file, | |
], | |
check=True, | |
) | |
file.unlink() | |
fixed_file.rename(file) | |
def main() -> None: | |
parser = argparse.ArgumentParser() | |
parser.add_argument("input", type=Path, help="input file") | |
args = parser.parse_args() | |
strip_cc(args.input) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment