Detecting episode transitions in a video

A few days ago I downloaded a few large files that contain a bunch of Tom & Jerry episodes stitched together. The duration of each file is north of one hour. Since I don't watch the whole thing in a single sitting, I find myself having to perform a dance of fast forwarding to where I left off, accidentally overshoot, then go backwards before being able to properly resume the video. I was wasting precious time that should instead be exploited in doom scrolling. I decided to take matters into my own hands...

ffmpeg to the rescue

The first thing I noticed was that the screen fades to black between episodes of the same file. My first reflex was to somehow detect this, and split the large video file based on black screens. This heuristic turned out to be an actual thing, because ffmpeg already supports it with a filter called blackdetect. I didn't have to write any code for this part.

ffmpeg spits out start and end offsets for the black screens, along with a bunch of irrelevant information:


$ ffmpeg -i video.mkv -vf blackdetect -f null /dev/null -nostats
[blackdetect @ 0x578c18c0f740] black_start:0 black_end:2.252 black_duration:2.252
[blackdetect @ 0x578c18c0f740] black_start:438.271 black_end:440.774 black_duration:2.503
[blackdetect @ 0x578c18c0f740] black_start:1585.21 black_end:1589.3 black_duration:4.087
[blackdetect @ 0x578c18c0f740] black_start:2033.95 black_end:2035.99 black_duration:2.044
[blackdetect @ 0x578c18c0f740] black_start:2389.01 black_end:2392.98 black_duration:3.962
[blackdetect @ 0x578c18c0f740] black_start:3209.21 black_end:3211.46 black_duration:2.252
[blackdetect @ 0x578c18c0f740] black_start:5273.4 black_end:5277.61 black_duration:4.212
[blackdetect @ 0x578c18c0f740] black_start:5713.51 black_end:5718.26 black_duration:4.754

The next step was to parse this out, then issue commands to split the video based on the timestamps. We're only interested in the parts between black_end and the next black_start. The first one can be ignored since there's no episode before it. With the help of regex101, I wrote this regex: (?:black_start|black_end):([^ ]+) to parse out the offsets and put them in a list. The idea is to generate, from the output above, these series of commands:


ffmpeg -i video.mkv -ss 2.252 -to 438.271 'video-1.mkv'
ffmpeg -i video.mkv -ss 440.774 -to 1585.21 'video-2.mkv'
ffmpeg -i video.mkv -ss 1589.3 -to 2033.95 'video-3.mkv'
ffmpeg -i video.mkv -ss 2035.99 -to 2389.01 'video-4.mkv'
ffmpeg -i video.mkv -ss 2392.98 -to 3209.21 'video-5.mkv'
ffmpeg -i video.mkv -ss 3211.46 -to 5273.4 'video-6.mkv'
ffmpeg -i video.mkv -ss 5277.61 -to 5713.51 'video-7.mkv'
ffmpeg -i video.mkv -ss 5718.26 'video-8.mkv'

with -ss being the end of a black screen, and -to being the start of the next black screen. This way, we only keep the contents that are between transitions.

At least in this case, the last line proved to be useless. It only held the last black screen that shows up before the video ends. I still left it in there because I couldn't reliably tell if a video ended with a black screen, or if it just cut abruptly. It's possible to make that call based on the length of video-8.mkv, but it just wasn't worth the trouble for me.

The last line doesn't have a -to offset to indicate to ffmpeg that it should split from that timestamp until the end of the video. To model this in Python, I added a sentinel value of -1, which I then use in the ffmpeg generation code to decide whether or not to expect an end offset:


def parse_offsets(blackscreen_lines: list[str]) -> list[float]:
    offsets = []
    #[blackdetect @ 0x59eed34c9740] black_start:0 black_end:2.252 black_duration:2.252
    pattern = re.compile('(?:black_start|black_end):([^ ]+)')
    for i, line in enumerate(blackscreen_lines):
        if not line.startswith('[blackdetect'):
            continue
        print(line)
        blackstart, blackend = pattern.findall(line)
        offsets.append(float(blackstart))
        offsets.append(float(blackend))
    return offsets

def offsets_to_ffmpeg(path, offsets: list[float]) -> list[str]:
    commands = []
    filename, extension = os.path.splitext(path)
    offsets_with_sentinel = offsets + [-1]
    for i, (blackend, blackstart) in enumerate(batched(offsets_with_sentinel[1:], 2)):
        if blackstart == -1:
            commands.append(f"ffmpeg -i '{path}' -ss {blackend} '{filename}-{i+1}{extension}'")
        else:
            commands.append(f"ffmpeg -i '{path}' -ss {blackend} -to {blackstart} '{filename}-{i+1}{extension}'")
    return commands

Upon running the Python script, I realized that the generated parts still have some transitions that the blackdetect filter didn't catch. This can be caused by the black screen being too short to be considered a transition, or too light for the black color detection threshold, among other things. Luckily these thresholds can be tweaked with black_min_duration and pixel_black_th respectively. What would a reasonable value be though? Putting a low value in black_min_duration has yielded false positives, short scene transitions within the same episode that are treated by the script as separate episodes. On the other hand, using a high value will skip some valid black screens.

Visualization

Since the script was taking a while to finish, I asked Claude to generate an HTML page where I can upload the video and the ffmpeg blackscreen detection output, and have it display a seekbar where the black screens are highlighted. This way I can analyze the black screens before actually splitting the video, which gives me a faster feedback loop. Here's the prompt I used:

hello,

I'm trying to build a HTML page where I can visualize a video, and have, below it, a custom seek bar.

the seek bar will need to display clickable offsets for where the video has black screens. these offsets are pregenerated by ffmpeg in the following format:

[blackdetect @ 0x55faf5406100] black_start:0 black_end:2.252 black_duration:2.252

[blackdetect @ 0x55faf5406100] black_start:21.688 black_end:22.772 black_duration:1.084

the caveat is that if I click on such an element on the seek bar, the video should jump to that offset.

can you generate this for me in plain HTML and javascript? thanks

The generated code can be found here, though I did modify for some quality of life improvements, like keyboard-controlled seeking and slight visual edits, resulting in this final version.

Here's what it looks like with black_min_duration set to 1 second:

Detected black screens of at least 1 second

Notice that there are evenly spaced black screens, as evidenced by the seekbar, except for the ones right after the sixth blackscreen. They are still black screens, but they are scene transitions within the same episode, rather than episode transitions.

Here's what it looks like with black_min_duration set to 1.7 seconds:

Detected black screens of at least 1.7 seconds

The black screens are unevenly spaced, implying that certain episodes are much larger than others, which is incorrect. Some valid black screens got filtered out by the high minimum duration value.

Not only that, but in both cases, there are two black screens that are right next to each other:

Episode of five seconds

Skipping false positives

Since I wasn't able to get it to an acceptable correctness just by tweaking black_min_duration, I decided to add an intermediate layer of filtering. It goes like this: we keep a relatively short black_min_duration value, then we skip the false positive episode transitions if their length is suspiciously short. Here's an example with black_min_duration set to 1.7:


$ ffmpeg -i video.mkv -vf blackdetect=d=1.7 -f null /dev/null -nostats 2>&1
[blackdetect @ 0x5bec48f57800] black_start:0 black_end:2.252 black_duration:2.252
[blackdetect @ 0x5bec48f57800] black_start:438.271 black_end:440.774 black_duration:2.503
[blackdetect @ 0x5bec48f57800] black_start:1585.21 black_end:1589.3 black_duration:4.087
[blackdetect @ 0x5bec48f57800] black_start:2033.95 black_end:2035.99 black_duration:2.044
[blackdetect @ 0x5bec48f57800] black_start:2389.01 black_end:2392.98 black_duration:3.962
[blackdetect @ 0x5bec48f57800] black_start:2398.23 black_end:2399.94 black_duration:1.71
[blackdetect @ 0x5bec48f57800] black_start:3209.21 black_end:3211.46 black_duration:2.252
[blackdetect @ 0x5bec48f57800] black_start:3623.75 black_end:3625.5 black_duration:1.752
[blackdetect @ 0x5bec48f57800] black_start:5273.4 black_end:5277.61 black_duration:4.212
[blackdetect @ 0x5bec48f57800] black_start:5713.51 black_end:5718.26 black_duration:4.754

The suspicious lines are:

[blackdetect @ 0x5bec48f57800] black_start:2389.01 black_end:2392.98 black_duration:3.962

[blackdetect @ 0x5bec48f57800] black_start:2398.23 black_end:2399.94 black_duration:1.71

The first black_end offset is 2392.98, but the next black_start offset is 2398.23, not even a six second difference. Since there are no six second episodes, we can consider this to be a false positive. We can merge it into the actual episode by removing the false black screen, the one that spans 2389.01 to 2392.98.

Before:


[blackdetect @ 0x5bec48f57800] black_start:2033.95 black_end:2035.99 black_duration:2.044
[blackdetect @ 0x5bec48f57800] black_start:2389.01 black_end:2392.98 black_duration:3.962
[blackdetect @ 0x5bec48f57800] black_start:2398.23 black_end:2399.94 black_duration:1.71

After:


[blackdetect @ 0x5bec48f57800] black_start:2033.95 black_end:2035.99 black_duration:2.044
[blackdetect @ 0x5bec48f57800] black_start:2398.23 black_end:2399.94 black_duration:1.71

With it out of the way, we now have an episode whose length is 2398.23 - 2035.99 = 362.24 seconds, around six minutes, which is more realistic than the previous six seconds.

However, skipping just once may not be enough if there are more false episode transitions within the same episode. To reiterate, scene transitions are separated by a black screen that the script will falsly flag as an episode transition. We need to keep skipping these black screens until we reach a reasonable value between the end of the current black screen and the start of the next one, ie longer than five minutes:


# episodes tend to be 5+ minutes long
def remove_false_positives(offsets: list[float], episode_length_threshold: int = 60*5) -> list[float]:
    if len(offsets) % 2 != 0:
        raise Exception("Expected start-end pairs in offsets, but it has an odd amount of values (" + str(len(offsets)) + ")")
    result = []
    i = 0
    while i < len(offsets):
        blackstart, blackend = offsets[i], offsets[i + 1]
        if i + 2 >= len(offsets): #last pair, so no nextblackstart after blackend
            result.append(blackstart)
            result.append(blackend)
            i += 2
        else:
            nextblackstart = offsets[i + 2]
            episode_length = nextblackstart - blackend
            result.append(blackstart)
            result.append(blackend)
            if episode_length >= episode_length_threshold:
                i += 2
            else:
                # handle situation where the episode is too short
                print(f'Detected suspiciously short episode between {blackend} and {nextblackstart}, duration = {episode_length}')
                j = i + 4
                while j < len(offsets):
                    if offsets[j] - blackend < episode_length_threshold:
                        j += 2
                    else:
                        break
                i = j
    return result

With that modification in place, we now get some reasonable episode splits:

Full script here, it assumes that ffmpeg is on your path.

Commentaires

Posts les plus consultés de ce blog

Writing a fast(er) youtube downloader

Cloning an infrared remote controller on Android

Porting a Golang and Rust CLI tool to D