Skip to content

Instantly share code, notes, and snippets.

@tom-huntington
Created August 29, 2023 10:04
Show Gist options
  • Save tom-huntington/1323af4b991ca34ef4a46b3e44532ada to your computer and use it in GitHub Desktop.
Save tom-huntington/1323af4b991ca34ef4a46b3e44532ada to your computer and use it in GitHub Desktop.
files by chapter concatenated to chapterized file
import subprocess
import os
import re
def make_chapters_metadata(list_mp4: list):
print(f"Making metadata source file")
chapters = {}
for single_mp4 in list_mp4:
number = single_mp4.removesuffix(".m4a")
cmd = f"ffprobe -v quiet -of csv=p=0 -show_entries format=duration '{folder}/{single_mp4}'"
print(f"{cmd=}")
duration_in_microseconds_ = subprocess.run(cmd, shell=True, capture_output=True)
duration_in_microseconds__ = duration_in_microseconds_.stdout.decode().strip().replace(".", "")
print(f"{duration_in_microseconds_=}")
duration_in_microseconds = int(duration_in_microseconds__)
chapters[number] = {"duration": duration_in_microseconds}
print(f"{chapters=}")
chapters[list_mp4[0].removesuffix(".m4a")]["start"] = 0
for n in range(1, len(chapters)):
chapter = list_mp4[n-1].removesuffix(".m4a")
next_chapter = list_mp4[n].removesuffix(".m4a")
chapters[chapter]["end"] = chapters[chapter]["start"] + chapters[chapter]["duration"]
chapters[next_chapter]["start"] = chapters[chapter]["end"] + 1
last_chapter = list_mp4[len(chapters)-1].removesuffix(".m4a")
chapters[last_chapter]["end"] = chapters[last_chapter]["start"] + chapters[last_chapter]["duration"]
metadatafile = f"{folder}/combined.metadata.txt"
with open(metadatafile, "w+") as m:
m.writelines(";FFMETADATA1\n")
for chapter in chapters:
ch_meta = """
[CHAPTER]
TIMEBASE=1/1000000
START={}
END={}
title={}
""".format(chapters[chapter]["start"], chapters[chapter]["end"], chapter)
m.writelines(ch_meta)
def concatenate_all_to_one_with_chapters():
print(f"Concatenating list of mp4 to combined.mp4")
metadatafile = f"{folder}/combined.metadata.txt"
subprocess.run(["ffmpeg", "-hide_banner", "-y", "-safe", "0", "-f", "concat", "-i", "list_mp4.txt", "-c", "copy", "-i", f"{metadatafile}", "-map_metadata", "1", "combined.m4a"])
if __name__ == '__main__':
folder = "." # Specify folder where the files 0001.mp4... are
# concatenate_all_to_one_with_chapters()
# exit(0)
list_mp4 = [f for f in os.listdir(folder) if f.endswith('.m4a')]
list_mp4.sort()
print(f"{list_mp4=}")
# Make the list of mp4 in ffmpeg format
if os.path.isfile("list_mp4.txt"):
os.remove("list_mp4.txt")
for filename_mp4 in list_mp4:
with open("list_mp4.txt", "a") as f:
line = f"file '{filename_mp4}'\n"
f.write(line)
make_chapters_metadata(list_mp4)
concatenate_all_to_one_with_chapters()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment