Created
July 25, 2023 00:32
-
-
Save unkn-one/b935f7f533846024142b1cbb48851c1c to your computer and use it in GitHub Desktop.
Convert youtube timestamps to ffmpeg chapters
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
#!/usr/bin/env python3 | |
from datetime import time | |
import fileinput | |
import re | |
time_re = re.compile( | |
r'((?P<hour>\d+):)?(?P<minute>\d+):(?P<second>\d+)(.(?P<microsecond>\d+))?') | |
ini_start = '''\ | |
;FFMETADATA1 | |
encoder=Lavf58.65.100 | |
''' | |
chap = '''\ | |
[CHAPTER] | |
TIMEBASE=1/1000 | |
START={start} | |
END={end} | |
title={title}\ | |
''' | |
def main(): | |
with open('chapters.ini', 'w') as out: | |
start_l = [] | |
title_l = [] | |
for line in fileinput.input(): | |
t, s = line.split(maxsplit=1) | |
t = time(**{k:int(v) for k, v in time_re.match(t).groupdict().items() if v}) | |
t = ((t.hour * 60 + t.minute) * 60 + t.second) * 1000 + t.microsecond | |
start_l.append(t) | |
title_l.append(s) | |
out.write(ini_start) | |
# it need fake last chapter at the movie length to generate end in previous chapter | |
for start, end, title in zip(start_l, start_l[1:], title_l): | |
out.write(chap.format(start=start, end=end, title=title)) | |
print('OK\nRun: ffmpeg -i input_file -i chapters.ini -map_metadata 1 -codec copy output_file') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment