Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Last active October 9, 2022 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save akostadinov/5028a4f2d26eb79e80b6ed2b11ab88ff to your computer and use it in GitHub Desktop.
Save akostadinov/5028a4f2d26eb79e80b6ed2b11ab88ff to your computer and use it in GitHub Desktop.
ffmpeg chapters creation
# copy of https://ikyle.me/blog/2020/add-mp4-chapters-ffmpeg
import re
chapters = list()
with open('chapters.txt', 'r') as f:
for line in f:
if not line.strip():
continue
x = re.match(r"(\d):(\d{2}):(\d{2}) (.*)", line)
hrs = int(x.group(1))
mins = int(x.group(2))
secs = int(x.group(3))
title = x.group(4)
minutes = (hrs * 60) + mins
seconds = secs + (minutes * 60)
timestamp = (seconds * 1000)
chap = {
"title": title,
"startTime": timestamp
}
chapters.append(chap)
text = ""
for i in range(len(chapters)-1):
chap = chapters[i]
title = chap['title']
start = chap['startTime']
end = chapters[i+1]['startTime']-1
text += f"""
[CHAPTER]
TIMEBASE=1/1000
START={start}
END={end}
title={title}
"""
with open("FFMETADATAFILE", "a") as myfile:
myfile.write(text)
0:01:41 Chapter 1
0:02:00 Another Chapter
0:02:11 Whatever Chapter
0:02:25 Extra Chapter
0:02:42 Credits
0:05:42 needed to avoid off by one, time should be end of video
;FFMETADATA1
major_brand=mp42
minor_version=0
compatible_brands=mp42mp41
title=Sharks Group Video Film.mp4
comment=some comment
encoder=Lavf58.76.100
[CHAPTER]
TIMEBASE=1/1000
START=101000
END=119999
title=Chapter 1
[CHAPTER]
TIMEBASE=1/1000
START=120000
END=130999
title=Another Chapter
[CHAPTER]
TIMEBASE=1/1000
START=131000
END=144999
title=Another Chapter
# Get existing video metadata
ffmpeg -i INPUT.mp4 -f ffmetadata FFMETADATAFILE
# make sure no CHAPTERS in FFMETADATAFILE
python3 chapters-ffmpeg.py
ffmpeg -i INPUT.mp4 -i FFMETADATAFILE -map 0 -map_metadata 1 -codec copy OUTPUT.mp4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment