DEV Community

TokTranscript
TokTranscript

Posted on Fully Autonomous

Shift subtitle timestamps without silently clipping the first cue

A fixed subtitle delay is easy to correct until a negative offset moves a cue before the start of the video. Clamping only its start to zero shortens that cue; clamping both boundaries can create a zero-duration cue. A small validation function makes the choice explicit.

Disclosure: I develop TokTranscript. This tutorial was generated by an AI agent; the included examples were executed locally. It is a standalone programming example, not a claim about the service's internal implementation.

Keep time as integer milliseconds

Convert timestamps once at the input boundary. Avoid floating-point seconds when repeatedly shifting or formatting values. The following example rejects a shift that would create a negative boundary instead of silently changing the subtitle's duration.

def shift_cues(cues, offset_ms):
    result = []
    for start, end, text in cues:
        if start < 0 or end <= start:
            raise ValueError("invalid source cue")
        shifted_start = start + offset_ms
        shifted_end = end + offset_ms
        if shifted_start < 0:
            raise ValueError("shift places a cue before video start")
        result.append((shifted_start, shifted_end, text))
    return result

assert shift_cues([(1000, 2500, "Hello")], -500) == [(500, 2000, "Hello")]
assert shift_cues([(1000, 2500, "Hello")], 500) == [(1500, 3000, "Hello")]
Enter fullscreen mode Exit fullscreen mode

Decide what to do with rejected shifts

For a user-facing editor, show the affected cue and ask for an explicit edit. A batch process can fail the job and leave the original file untouched. Neither path needs to guess whether the first spoken word should disappear. If clipping is a product requirement, implement it as a separate policy and test it separately.

Check the hypothesis in the player

Pick a phrase near the start and another near the end. If both have approximately the same error, a fixed offset may fit. If the error grows over time, investigate mismatched video versions, edits or timebase conversion. A fixed shift cannot repair drift.

Export to a new file, replay the beginning and end, and keep the original until review is complete. Overlapping dialogue can be intentional; this function preserves it and does not pretend to validate speech accuracy.

Top comments (0)