Skip to content

timecodes

Classes:

  • Keyframes

    Class representing keyframes, or scenechanges.

  • Timecodes

    A list of frame durations, together representing a (possibly variable) frame rate.

FrameDur dataclass

FrameDur(frame: int, numerator: int, denominator: int)

A fraction representing the duration of a specific frame.

Methods:

  • to_fraction

    Convert the FrameDur to a Fraction that represents the frame duration.

Attributes:

denominator instance-attribute

denominator: int

The frame duration's denominator.

frame instance-attribute

frame: int

The frame number.

numerator instance-attribute

numerator: int

The frame duration's numerator.

to_fraction

to_fraction() -> Fraction

Convert the FrameDur to a Fraction that represents the frame duration.

Source code in vstools/functions/timecodes.py
52
53
54
55
56
57
def to_fraction(self) -> Fraction:
    """
    Convert the FrameDur to a Fraction that represents the frame duration.
    """

    return Fraction(self.numerator, self.denominator)

Keyframes

Keyframes(iterable: Iterable[int] = [])

Bases: list[int]

Class representing keyframes, or scenechanges.

They follow the convention of signaling the start of the new scene.

Methods:

Attributes:

Source code in vstools/functions/timecodes.py
379
380
381
def __init__(self, iterable: Iterable[int] = []) -> None:
    super().__init__(sorted(iterable))
    self.scenes = self.__class__._Scenes(self)

scenes instance-attribute

scenes = _Scenes(self)

from_clip classmethod

from_clip(
    clip: VideoNode, prop_key: str | Iterable[str] | None = None, **kwargs: Any
) -> Self

Create a Keyframes object from a clip by checking frame props.

Assumes that the clip has already been processed by scxvid.Scxvid or similar.

Parameters:

  • clip

    (VideoNode) –

    Clip to get keyframes from.

  • prop_key

    (str | Iterable[str] | None, default: None ) –

    Additional props key(s) to use for detecting scene changes.

  • **kwargs

    (Any, default: {} ) –

    Additional keyword arguments to pass to clip_async_render.

Returns:

  • Self

    Keyframes from the clip.

Source code in vstools/functions/timecodes.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
@classmethod
def from_clip(cls, clip: vs.VideoNode, prop_key: str | Iterable[str] | None = None, **kwargs: Any) -> Self:
    """
    Create a Keyframes object from a clip by checking frame props.

    Assumes that the clip has already been processed by scxvid.Scxvid or similar.

    Args:
        clip: Clip to get keyframes from.
        prop_key: Additional props key(s) to use for detecting scene changes.
        **kwargs: Additional keyword arguments to pass to clip_async_render.

    Returns:
        Keyframes from the clip.
    """
    props_key = to_arr(prop_key) if prop_key else []

    def check_props(n: int, f: vs.VideoFrame) -> int:
        if f.props.get("_SceneChangePrev"):
            return n

        if f.props.get("_SceneChangeNext"):
            return n + 1

        for key in props_key:
            if f.props.get(key):
                return n
        return -1

    frames = clip_async_render(clip, None, "Detecting scene changes...", check_props, **kwargs)
    return cls(f for f in frames if f >= 0)

from_file classmethod

from_file(file: str | PathLike[str], **kwargs: Any) -> Self
Source code in vstools/functions/timecodes.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@classmethod
def from_file(cls, file: str | os.PathLike[str], **kwargs: Any) -> Self:
    file = SPath(file).resolve()

    if not file.exists():
        raise FileNotFoundError

    lines = [line.strip() for line in file.read_lines("utf-8") if line and not line.startswith("#")]

    if not lines:
        raise ValueError("No keyframe could be found!")

    match lines[0].lower():
        # XVID
        case line if line.startswith("fps"):
            split_lines = [line.split(" ") for line in lines]
            return cls(int(n) for n, t, *_ in split_lines if t.lower() == "i")
        # V1
        case line if line.startswith(("i", "b", "p", "n")):
            return cls(i for i, line in enumerate(lines) if line.startswith("i"))
        case _:
            raise ValueError("Could not determine keyframe file type!")

from_param classmethod

from_param(clip: VideoNode, param: Self | str) -> Self
Source code in vstools/functions/timecodes.py
485
486
487
488
489
490
491
492
493
@classmethod
def from_param(cls, clip: vs.VideoNode, param: Self | str) -> Self:
    if isinstance(param, str):
        return cls.unique(clip, param)

    if isinstance(param, cls):
        return param

    return cls(param)

to_file

to_file(
    out: str | PathLike[str],
    fmt: Literal["v1", "xvid"] = "v1",
    func: FuncExcept | None = None,
    header: bool = True,
    force: bool = False,
) -> None
Source code in vstools/functions/timecodes.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def to_file(
    self,
    out: str | os.PathLike[str],
    fmt: Literal["v1", "xvid"] = "v1",
    func: FuncExcept | None = None,
    header: bool = True,
    force: bool = False,
) -> None:
    func = func or self.to_file

    out_path = Path(out).resolve()

    if out_path.exists():
        if not force and out_path.stat().st_size > 0:
            return

        out_path.unlink()

    out_path.parent.mkdir(parents=True, exist_ok=True)

    check_perms(out_path, "w+", func=func)

    match fmt:
        case "v1":
            out_text = list[str]()
            if header:
                out_text.extend(["# keyframe format v1", "fps 0", ""])
            out_text.extend(f"{n} I -1" for n in self)
            out_text.append("")
        case "xvid":
            lut_self = set(self)
            out_text = list[str]()

            if header:
                out_text.extend(["# XviD 2pass stat file", ""])

            for i in range(max(self)):
                if i in lut_self:
                    out_text.append("i")
                    lut_self.remove(i)
                else:
                    out_text.append("b")

    out_path.unlink(True)
    out_path.touch()
    out_path.write_text("\n".join(out_text))

unique classmethod

unique(
    clip: VideoNode, key: str, prop_key: str = "_SceneChangePrev", **kwargs: Any
) -> Self

Get the keyframes from a clip and write them to a file.

Assumes that the clip has already been processed by scxvid.Scxvid or similar.

This method tries to generate a unique filename based on the clip's properties and the key prefix. If a file with that name exists and is not empty, the keyframes are loaded from the file. Otherwise, they are detected from the clip and then written to the file.

Example

When working on a TV series, the episode number can be a convenient key (e.g. "01" for episode 1, "02" for episode 2, etc.):

keyframes = Keyframes.unique(clip, "01")

Parameters:

Returns:

Source code in vstools/functions/timecodes.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
@classmethod
def unique(cls, clip: vs.VideoNode, key: str, prop_key: str = "_SceneChangePrev", **kwargs: Any) -> Self:
    """
    Get the keyframes from a clip and write them to a file.

    Assumes that the clip has already been processed by scxvid.Scxvid or similar.

    This method tries to generate a unique filename based on the clip's
    properties and the `key` prefix. If a file with that name exists and is
    not empty, the keyframes are loaded from the file. Otherwise, they are
    detected from the clip and then written to the file.

    Example:
        When working on a TV series, the episode number can be a convenient key
        (e.g. `"01"` for episode 1, `"02"` for episode 2, etc.):
        ```py
        keyframes = Keyframes.unique(clip, "01")
        ```

    Args:
        clip: The clip to get keyframes from.
        key: A prefix for the filename.
        prop_key: Property key to use for detecting scene changes.
        **kwargs: Additional keyword arguments passed to
            [vstools.Keyframes.from_file][] or [vstools.Keyframes.from_clip][].

    Returns:
        An instance of [vstools.Keyframes][] containing the keyframes.
    """
    file = cls._get_unique_path(clip, key)

    if file.exists():
        if file.stat().st_size > 0:
            return cls.from_file(file, **kwargs)

        file.unlink()

    keyframes = cls.from_clip(clip, prop_key, **kwargs)
    keyframes.to_file(file, force=True)

    return keyframes

SceneAverageStats

SceneAverageStats(
    clip: VideoNode,
    keyframes: Keyframes | str,
    prop: str = "SceneStats",
    plane: int = 0,
    cache_size: int = 5,
)

Bases: SceneBasedDynamicCache

Methods:

Attributes:

Source code in vstools/functions/timecodes.py
587
588
589
590
591
592
593
594
595
596
597
598
def __init__(
    self,
    clip: vs.VideoNode,
    keyframes: Keyframes | str,
    prop: str = "SceneStats",
    plane: int = 0,
    cache_size: int = 5,
) -> None:
    super().__init__(clip, keyframes, cache_size)

    self.prop_keys = tuple(f"{prop}{x}" for x in self._props_keys)
    self.scene_avgs = self._Cache(self.clip, self.keyframes, plane)

cache_size instance-attribute

cache_size = cache_size

clip instance-attribute

clip = clip

keyframes instance-attribute

keyframes = from_param(clip, keyframes)

prop_keys instance-attribute

prop_keys = tuple(f'{prop}{x}' for x in (_props_keys))

scene_avgs instance-attribute

scene_avgs = _Cache(clip, keyframes, plane)

from_clip classmethod

from_clip(
    clip: VideoNode, keyframes: Keyframes | str, *args: Any, **kwargs: Any
) -> VideoNode
Source code in vstools/functions/timecodes.py
557
558
559
@classmethod
def from_clip(cls, clip: vs.VideoNode, keyframes: Keyframes | str, *args: Any, **kwargs: Any) -> vs.VideoNode:
    return cls(clip, keyframes, *args, **kwargs).get_eval()

get_clip

get_clip(key: int) -> VideoNode
Source code in vstools/functions/timecodes.py
600
601
def get_clip(self, key: int) -> vs.VideoNode:
    return self.clip.std.SetFrameProps(**dict(zip(self.prop_keys, self.scene_avgs[key])))

get_eval

get_eval() -> VideoNode
Source code in vstools/functions/timecodes.py
554
555
def get_eval(self) -> vs.VideoNode:
    return self.clip.std.FrameEval(lambda n: self[self.keyframes.scenes.indices[n]])

SceneBasedDynamicCache

SceneBasedDynamicCache(
    clip: VideoNode, keyframes: Keyframes | str, cache_size: int = 5
)

Bases: DynamicClipsCache[int]

Methods:

Attributes:

Source code in vstools/functions/timecodes.py
545
546
547
548
549
def __init__(self, clip: vs.VideoNode, keyframes: Keyframes | str, cache_size: int = 5) -> None:
    super().__init__(cache_size)

    self.clip = clip
    self.keyframes = Keyframes.from_param(clip, keyframes)

cache_size instance-attribute

cache_size = cache_size

clip instance-attribute

clip = clip

keyframes instance-attribute

keyframes = from_param(clip, keyframes)

from_clip classmethod

from_clip(
    clip: VideoNode, keyframes: Keyframes | str, *args: Any, **kwargs: Any
) -> VideoNode
Source code in vstools/functions/timecodes.py
557
558
559
@classmethod
def from_clip(cls, clip: vs.VideoNode, keyframes: Keyframes | str, *args: Any, **kwargs: Any) -> vs.VideoNode:
    return cls(clip, keyframes, *args, **kwargs).get_eval()

get_clip abstractmethod

get_clip(key: int) -> VideoNode
Source code in vstools/functions/timecodes.py
551
552
@abstractmethod
def get_clip(self, key: int) -> vs.VideoNode: ...

get_eval

get_eval() -> VideoNode
Source code in vstools/functions/timecodes.py
554
555
def get_eval(self) -> vs.VideoNode:
    return self.clip.std.FrameEval(lambda n: self[self.keyframes.scenes.indices[n]])

Timecodes

Bases: list[FrameDur]

A list of frame durations, together representing a (possibly variable) frame rate.

Methods:

Attributes:

  • V1

    V1 timecode format, containing a list of frame ranges with associated frame rates. For example:

  • V2

    V2 timecode format, containing a timestamp for each frame, including possibly a final timestamp after the last frame

V1 class-attribute instance-attribute

V1 = 1

V1 timecode format, containing a list of frame ranges with associated frame rates. For example:

# timecodes format v1
Assume 23.976023976024
544,548,29.97002997003
721,725,29.97002997003
770,772,17.982017982018

V2 class-attribute instance-attribute

V2 = 2

V2 timecode format, containing a timestamp for each frame, including possibly a final timestamp after the last frame to specify the final frame's duration. For example:

# timecode format v2
0.000000
41.708333
83.416667
125.125000
166.833333

accumulate_norm_timecodes classmethod

accumulate_norm_timecodes(
    timecodes: Timecodes | dict[tuple[int, int], Fraction],
) -> tuple[Fraction, dict[Fraction, list[tuple[int, int]]]]
Source code in vstools/functions/timecodes.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@classmethod
def accumulate_norm_timecodes(
    cls, timecodes: Timecodes | dict[tuple[int, int], Fraction]
) -> tuple[Fraction, dict[Fraction, list[tuple[int, int]]]]:
    if isinstance(timecodes, Timecodes):
        timecodes = timecodes.to_normalized_ranges()

    major_time, minor_fps = cls.separate_norm_timecodes(timecodes)

    acc_ranges = dict[Fraction, list[tuple[int, int]]]()

    for k, v in minor_fps.items():
        if v not in acc_ranges:
            acc_ranges[v] = []

        acc_ranges[v].append(k)

    return major_time, acc_ranges

assume_vfr

assume_vfr(clip: VideoNode, func: FuncExcept | None = None) -> VideoNode

Force the given clip to be assumed to be vfr by other applications.

Parameters:

  • clip

    (VideoNode) –

    Clip to process.

  • func

    (FuncExcept | None, default: None ) –

    Function returned for custom error handling. This should only be set by VS package developers.

Returns:

  • VideoNode

    Clip that should always be assumed to be vfr by other applications.

Source code in vstools/functions/timecodes.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def assume_vfr(self, clip: vs.VideoNode, func: FuncExcept | None = None) -> vs.VideoNode:
    """
    Force the given clip to be assumed to be vfr by other applications.

    Args:
        clip: Clip to process.
        func: Function returned for custom error handling. This should only be set by VS package developers.

    Returns:
        Clip that should always be assumed to be vfr by other applications.
    """
    func = func or self.assume_vfr

    major_time, minor_fps = self.accumulate_norm_timecodes(self)

    assumed_clip = vs.core.std.AssumeFPS(clip, None, major_time.numerator, major_time.denominator)

    for other_fps, fps_ranges in minor_fps.items():
        assumed_clip = replace_ranges(
            assumed_clip,
            vs.core.std.AssumeFPS(clip, None, other_fps.numerator, other_fps.denominator),
            fps_ranges,
            mismatch=True,
        )

    return assumed_clip

from_clip classmethod

from_clip(clip: VideoNode, **kwargs: Any) -> Self

Get the timecodes from a given clip.

Parameters:

  • clip

    (VideoNode) –

    Clip to gather metrics from.

  • **kwargs

    (Any, default: {} ) –

    Keyword arguments to pass on to clip_async_render.

Source code in vstools/functions/timecodes.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@classmethod
def from_clip(cls, clip: vs.VideoNode, **kwargs: Any) -> Self:
    """
    Get the timecodes from a given clip.

    Args:
        clip: Clip to gather metrics from.
        **kwargs: Keyword arguments to pass on to `clip_async_render`.
    """
    from ..utils import get_prop

    def _get_timecode(n: int, f: vs.VideoFrame) -> FrameDur:
        return FrameDur(n, get_prop(f, "_DurationNum", int), get_prop(f, "_DurationDen", int))

    return cls(clip_async_render(clip, None, "Fetching timecodes...", _get_timecode, **kwargs))

from_file classmethod

from_file(
    file: FilePathType, ref: VideoNode, /, *, func: FuncExcept | None = None
) -> Self
from_file(
    file: FilePathType,
    length: int,
    den: int | None = None,
    /,
    func: FuncExcept | None = None,
) -> Self
from_file(
    file: FilePathType,
    ref_or_length: int | VideoNode,
    den: int | None = None,
    /,
    func: FuncExcept | None = None,
) -> Self
Source code in vstools/functions/timecodes.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
@classmethod
def from_file(
    cls,
    file: FilePathType,
    ref_or_length: int | vs.VideoNode,
    den: int | None = None,
    /,
    func: FuncExcept | None = None,
) -> Self:
    func = func or cls.from_file

    file = Path(str(file)).resolve()

    length = ref_or_length if isinstance(ref_or_length, int) else ref_or_length.num_frames

    fb_den = (
        (None if ref_or_length.fps_den in {0, 1} else ref_or_length.fps_den)
        if isinstance(ref_or_length, vs.VideoNode)
        else None
    )

    denominator = den or fb_den or 1001

    version, *timecodes = file.read_text().splitlines()

    if "v1" in version:

        def _norm(xd: str) -> Fraction:
            return Fraction(round(denominator / float(xd)), denominator)

        assume = None

        timecodes_d = dict[tuple[int | None, int | None], Fraction]()

        for line in timecodes:
            if line.startswith("#"):
                continue

            if line.startswith("Assume"):
                assume = _norm(timecodes[0][7:])
                continue

            starts, ends, fps = line.split(",")
            timecodes_d[int(starts), int(ends) + 1] = _norm(fps)

        norm_timecodes = cls.normalize_range_timecodes(timecodes_d, length, assume)
    elif "v2" in version:
        timecodes_l = [float(t) for t in timecodes if not t.startswith("#")]
        norm_timecodes = [
            Fraction(denominator, int(denominator / float(f"{round((x - y) * 100, 4) / 100000:.08f}"[:-1])))
            for x, y in zip(timecodes_l[1:], timecodes_l[:-1])
        ]
    else:
        raise CustomValueError("timecodes file not supported!", func, file)

    if len(norm_timecodes) != length:
        raise FramesLengthError(
            func,
            "",
            "timecodes file length mismatch with specified length!",
            reason={"timecodes": len(norm_timecodes), "clip": length},
        )

    return cls(FrameDur(i, f.numerator, f.denominator) for i, f in enumerate(norm_timecodes))

normalize_range_timecodes classmethod

normalize_range_timecodes(
    timecodes: dict[tuple[int | None, int | None], Fraction],
    length: int,
    assume: Fraction | None = None,
) -> list[Fraction]

Convert from normalized ranges to a list of frame duration.

Source code in vstools/functions/timecodes.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@classmethod
def normalize_range_timecodes(
    cls, timecodes: dict[tuple[int | None, int | None], Fraction], length: int, assume: Fraction | None = None
) -> list[Fraction]:
    """
    Convert from normalized ranges to a list of frame duration.
    """
    norm_timecodes = [assume] * length if assume else list[Fraction]()

    for (startn, endn), fps in timecodes.items():
        start = max(fallback(startn, 0), 0)
        end = fallback(endn, length - 1)

        if end + 1 > len(norm_timecodes):
            norm_timecodes += [1 / fps] * (end + 1 - len(norm_timecodes))

        norm_timecodes[start : end + 1] = [1 / fps] * (end + 1 - start)

    return norm_timecodes

separate_norm_timecodes classmethod

separate_norm_timecodes(
    timecodes: Timecodes | dict[tuple[int, int], Fraction],
) -> tuple[Fraction, dict[tuple[int, int], Fraction]]
Source code in vstools/functions/timecodes.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
@classmethod
def separate_norm_timecodes(
    cls, timecodes: Timecodes | dict[tuple[int, int], Fraction]
) -> tuple[Fraction, dict[tuple[int, int], Fraction]]:
    if isinstance(timecodes, Timecodes):
        timecodes = timecodes.to_normalized_ranges()

    times_count = dict.fromkeys(timecodes.values(), 0)

    for v in timecodes.values():
        times_count[v] += 1

    major_count = max(times_count.values())
    major_time = next(t for t, c in times_count.items() if c == major_count)
    minor_fps = {r: v for r, v in timecodes.items() if v != major_time}

    return major_time, minor_fps

to_file

to_file(
    out: FilePathType, format: int = V2, func: FuncExcept | None = None
) -> None

Write timecodes to a file.

This file should always be muxed into the video container when working with Variable Frame Rate video.

Parameters:

  • out

    (FilePathType) –

    Path to write the file to.

  • format

    (int, default: V2 ) –

    Format to write the file to.

Source code in vstools/functions/timecodes.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def to_file(self, out: FilePathType, format: int = V2, func: FuncExcept | None = None) -> None:
    """
    Write timecodes to a file.

    This file should always be muxed into the video container when working with Variable Frame Rate video.

    Args:
        out: Path to write the file to.
        format: Format to write the file to.
    """
    func = func or self.to_file

    out_path = Path(str(out)).resolve()

    check_perms(out_path, "w+", func=func)

    UnsupportedTimecodeVersionError.check(self.to_file, format)

    out_text = [f"# timecode format v{format}"]

    if format == Timecodes.V1:
        major_time, minor_fps = self.separate_norm_timecodes(self)

        out_text.append(f"Assume {round(float(major_time), 12)}")

        out_text.extend([",".join(map(str, [*frange, round(float(fps), 12)])) for frange, fps in minor_fps.items()])
    elif format == Timecodes.V2:
        acc = Fraction()  # in milliseconds

        for time in [*self, Fraction()]:
            ns = round(acc * 10**6)
            ms, dec = divmod(ns, 10**6)
            out_text.append(f"{ms}.{dec:06}")
            acc += Fraction(time.numerator * 1000, time.denominator)

    out_path.unlink(True)
    out_path.touch()
    out_path.write_text("\n".join([*out_text, ""]))

to_fractions

to_fractions() -> list[Fraction]

Convert to a list of frame lengths, representing the individual framerates.

Source code in vstools/functions/timecodes.py
103
104
105
106
107
108
def to_fractions(self) -> list[Fraction]:
    """
    Convert to a list of frame lengths, representing the individual framerates.
    """

    return [t.to_fraction() for t in self]

to_normalized_ranges

to_normalized_ranges() -> dict[tuple[int, int], Fraction]

Convert to a list of normalized frame ranges and their assigned framerate.

Source code in vstools/functions/timecodes.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def to_normalized_ranges(self) -> dict[tuple[int, int], Fraction]:
    """
    Convert to a list of normalized frame ranges and their assigned framerate.
    """

    timecodes_ranges = dict[tuple[int, int], Fraction]()

    last_i = len(self) - 1
    last_tcode: tuple[int, FrameDur] = (0, self[0])

    for tcode in self[1:]:
        start, ltcode = last_tcode

        if tcode != ltcode:
            timecodes_ranges[start, tcode.frame - 1] = 1 / ltcode.to_fraction()
            last_tcode = (tcode.frame, tcode)
        elif tcode.frame == last_i:
            timecodes_ranges[start, tcode.frame] = 1 / tcode.to_fraction()

    return timecodes_ranges