Scripts

Ʌ: ffmpeg

Split a file into N-minute chunks

This simple script splits a file into roughly 20 minute chunks - e.g. when a video is 21 minutes long, it does not get split into a 20 minute and a 1 minute chunk. This behaviour can be modified through the TOLERANCE variable.

It depends only on ffmpeg-python = "^0.2.0".

import ffmpeg
import os
import sys
from pprint import pprint
from datetime import timedelta

SPLIT_LENGTH = timedelta(minutes=20).total_seconds()
TOLERANCE = 1.33

probe = ffmpeg.probe(sys.argv[1])total_duration = float(probe['format']['duration'])

if total_duration < SPLIT_LENGTH * TOLERANCE:
    sys.exit(1)

print(f"Total length: {timedelta(seconds=total_duration)}")

duration_left = total_duration
cnt = 0

while duration_left > 0:
    start = SPLIT_LENGTH * cnt
    length = SPLIT_LENGTH \
        if (duration_left > SPLIT_LENGTH * TOLERANCE) else duration_left

    path, ext = os.path.splitext(sys.argv[1])
    out_filename = f"{path}_{cnt+1}{ext}"

    print(f"CUT: {timedelta(seconds=start)} -- " +
          f"{timedelta(seconds=start + length)} --> {out_filename}")

    (
        ffmpeg
        .input(sys.argv[1], ss=start, t=length)
        # .trim(start=start, duration=length)
        .output(out_filename, vcodec='copy', acodec='copy')
        .run()
    )

    cnt += 1
    duration_left -= length