Skip to content

Instantly share code, notes, and snippets.

@nwithan8
Last active January 5, 2021 02:13
Show Gist options
  • Select an option

  • Save nwithan8/58f9df0de8d5787397a248b82fa314b1 to your computer and use it in GitHub Desktop.

Select an option

Save nwithan8/58f9df0de8d5787397a248b82fa314b1 to your computer and use it in GitHub Desktop.
Collect and stitch together a folder of TS files into a final TS file. Optionally remux to a different file format.
#!/usr/bin/python3
"""
Collect all TS file parts and combine them into one TS file.
Optionally remux the final TS file into a different format.
All audio channels are preserved during processing.
"""
import os
import subprocess
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('folder_name',
type=str,
help='Path of folder containing TS files')
parser.add_argument("-fp",
'--file_name_pattern',
type=str,
help="Naming scheme of each TS file part. Defaults to folder name + number")
parser.add_argument('-n',
'--starting_number',
type=int,
default=0,
help="Number the files start at. Default: 0")
parser.add_argument('-t',
'--threads',
type=int,
default=0,
help="Number of CPU threads to use during processing")
parser.add_argument('-rf',
'--remux_format',
type=str,
default=None,
help="Optionally remux the final TS file into a different format")
parser.add_argument('-c',
'--clean_up',
action="store_true",
default=False,
help="Delete temporary files when done. Source files will NOT be deleted.")
args = parser.parse_args()
if not args.file_name_pattern:
args.file_name_pattern = args.folder_name
FOLDER = args.folder_name
FILE_NAME = args.file_name_pattern
NUMBER = args.starting_number
PARTS_LIST = f"{FOLDER}.txt"
keep_going = True
while keep_going:
path = f"{FOLDER}/{FILE_NAME}{NUMBER}.ts"
if os.path.exists(path):
NUMBER += 1
else:
keep_going = False
print(f"Found {max(0, NUMBER - 1)} TS parts.")
if NUMBER <= 0:
# exit(0)
pass
with open(PARTS_LIST, "w+") as f:
for i in range(0, NUMBER):
f.write(f"file '{FOLDER}/{FILE_NAME}{i}.ts'\n")
ffmpeg_out_args = "-map 0 -threads {args.threads}"
print("Combining video files...")
subprocess.call(f'ffmpeg -f concat -safe 0 -i "{PARTS_LIST}" {ffmpeg_out_args} -c copy "{FOLDER}.ts"',
shell=True)
print("Done combining files.")
if args.remux_format:
print(f"Remuxing TS file to {args.remux}..")
subprocess.call(f'ffmpeg -i "{FOLDER}.ts" -threads {args.threads} -acodec copy -vcodec copy "{FOLDER}.{args.remux_format}"',
shell=True)
print("Done remuxing.")
if args.clean_up:
print("Cleaning up temporary files. Source files will NOT be deleted.")
os.remove(PARTS_LIST)
if args.remux_format:
os.remove(f"{FOLDER}.ts")
print("Cleanup complete.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment