Skip to content

timecodes

KeyframesBoundT module-attribute

KeyframesBoundT = TypeVar('KeyframesBoundT', bound=Keyframes)

TimecodeBoundT module-attribute

TimecodeBoundT = TypeVar('TimecodeBoundT', bound=Timecode)

TimecodesBoundT module-attribute

TimecodesBoundT = TypeVar('TimecodesBoundT', bound=Timecodes)

keyframes_storage module-attribute

keyframes_storage = PackageStorage(package_name='keyframes')

Keyframes

Keyframes(iterable: Iterable[int])
Keyframes(iterable: Iterable[int] = [], *, _dummy: bool = False)

Bases: list[int]

Class representing keyframes, or scenechanges.

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

Source code
351
352
353
354
355
356
def __init__(self, iterable: Iterable[int] = [], *, _dummy: bool = False) -> None:
    super().__init__(sorted(list(iterable)))

    self._dummy = _dummy

    self.scenes = self.__class__._Scenes(self)

SCXVID class-attribute instance-attribute

SCXVID: ClassVar = SCXVID

V1 class-attribute instance-attribute

V1 = 1

WWXD class-attribute instance-attribute

WWXD: ClassVar = WWXD

XVID class-attribute instance-attribute

XVID = -1

scenes instance-attribute

scenes = _Scenes(self)

from_clip classmethod

from_clip(
    clip: VideoNode,
    mode: SceneChangeMode | int = WWXD,
    height: int | None = 360,
    **kwargs: Any
) -> KeyframesBoundT
Source code
381
382
383
384
385
386
387
388
389
390
391
392
393
@classmethod
def from_clip(
    cls: type[KeyframesBoundT], clip: vs.VideoNode, mode: SceneChangeMode | int = WWXD, height: int | None = 360,
    **kwargs: Any
) -> KeyframesBoundT:

    mode = SceneChangeMode(mode)

    clip = mode.prepare_clip(clip, height)

    frames = clip_async_render(clip, None, 'Detecting scene changes...', mode.lambda_cb(), **kwargs)

    return cls(Sentinel.filter(frames))

from_file classmethod

from_file(file: FilePathType, **kwargs: Any) -> KeyframesBoundT
Source code
425
426
427
428
429
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
461
462
463
@classmethod
def from_file(cls: type[KeyframesBoundT], file: FilePathType, **kwargs: Any) -> KeyframesBoundT:
    file = SPath(str(file)).resolve()

    if not file.exists():
        raise FileNotFoundError

    if file.stat().st_size <= 0:
        raise OSError('File is empty!')

    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!')

    kf_type: int | None = None

    line = lines[0].lower()

    if line.startswith('fps'):
        kf_type = Keyframes.XVID
    elif line.startswith(('i', 'b', 'p', 'n')):
        kf_type = Keyframes.V1

    if kf_type is None:
        raise ValueError('Could not determine keyframe file type!')

    if kf_type == Keyframes.V1:
        return cls(i for i, line in enumerate(lines) if line.startswith('i'))

    if kf_type == Keyframes.XVID:
        split_lines = [line.split(' ') for line in lines]

        return cls(int(n) for n, t, *_ in split_lines if t.lower() == 'i')

    raise ValueError('Invalid keyframe file type!')

from_param classmethod

from_param(clip: VideoNode, param: KeyframesBoundT | str) -> KeyframesBoundT
Source code
504
505
506
507
508
509
510
511
512
@classmethod
def from_param(cls: type[KeyframesBoundT], clip: vs.VideoNode, param: KeyframesBoundT | str) -> KeyframesBoundT:
    if isinstance(param, str):
        return cls.unique(clip, param)

    if isinstance(param, cls):
        return param

    return cls(param)

to_clip

to_clip(
    clip: VideoNode,
    *,
    mode: SceneChangeMode | int = WWXD,
    height: int | None = 360,
    prop_key: str = next(iter(prop_keys)),
    scene_idx_prop: bool = False
) -> VideoNode
Source code
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
@inject_self.with_args(_dummy=True)
def to_clip(
    self, clip: vs.VideoNode, *, mode: SceneChangeMode | int = WWXD, height: int | None = 360,
    prop_key: str = next(iter(SceneChangeMode.SCXVID.prop_keys)), scene_idx_prop: bool = False
) -> vs.VideoNode:
    from ..utils import replace_ranges

    propset_clip = clip.std.SetFrameProp(prop_key, True)

    if self._dummy:
        mode = SceneChangeMode(mode)

        prop_clip, callback = mode.prepare_clip(clip, height), mode.check_cb()

        out = replace_ranges(clip, propset_clip, callback, prop_src=prop_clip)
    else:
        out = replace_ranges(clip, propset_clip, self)

    if not scene_idx_prop:
        return out

    def _add_scene_idx(n: int, f: vs.VideoFrame) -> vs.VideoFrame:
        f = f.copy()

        f.props._SceneIdx = self.scenes.indices[n]

        return f

    return out.std.ModifyFrame(out, _add_scene_idx)

to_file

to_file(
    out: FilePathType,
    format: int = V1,
    func: FuncExceptT | None = None,
    header: bool = True,
    force: bool = False,
) -> None
Source code
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
def to_file(
    self, out: FilePathType, format: int = V1, func: FuncExceptT | None = None,
    header: bool = True, force: bool = False
) -> None:
    from ..utils import check_perms

    func = func or self.to_file

    out_path = Path(str(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)

    if format == Keyframes.V1:
        out_text = [
            *(['# keyframe format v1', 'fps 0', ''] if header else []),
            *(f'{n} I -1' for n in self), ''
        ]
    elif format == Keyframes.XVID:
        lut_self = set(self)
        out_text = [
            *(['# XviD 2pass stat file', '',] if header else []),
            *(
                (lut_self.remove(i) or 'i') if i in lut_self else 'b'  # type: ignore
                for i in range(max(self))
            )
        ]

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

unique classmethod

unique(clip: VideoNode, key: str, **kwargs: Any) -> KeyframesBoundT
Source code
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
@classmethod
def unique(
    cls: type[KeyframesBoundT], clip: vs.VideoNode, key: str, **kwargs: Any
) -> KeyframesBoundT:
    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, **kwargs)
    keyframes.to_file(file, force=True)

    return keyframes

LWIndex dataclass

LWIndex(stream_info: StreamInfo, frame_data: list[Frame], keyframes: Keyframes)

frame_data instance-attribute

frame_data: list[Frame]

keyframes instance-attribute

keyframes: Keyframes

stream_info instance-attribute

stream_info: StreamInfo

Frame

Bases: NamedTuple

dts instance-attribute

dts: int

edi instance-attribute

edi: int

field instance-attribute

field: int

idx instance-attribute

idx: int

key instance-attribute

key: int

pic instance-attribute

pic: int

poc instance-attribute

poc: int

pos instance-attribute

pos: int

pts instance-attribute

pts: int

repeat instance-attribute

repeat: int

Regex

frame_first class-attribute instance-attribute

frame_first = compile(
    "Index=(?P<Index>-?[0-9]+),POS=(?P<POS>-?[0-9]+),PTS=(?P<PTS>-?[0-9]+),DTS=(?P<DTS>-?[0-9]+),EDI=(?P<EDI>-?[0-9]+)"
)

frame_second class-attribute instance-attribute

frame_second = compile(
    "Key=(?P<Key>-?[0-9]+),Pic=(?P<Pic>-?[0-9]+),POC=(?P<POC>-?[0-9]+),Repeat=(?P<Repeat>-?[0-9]+),Field=(?P<Field>-?[0-9]+)"
)

streaminfo class-attribute instance-attribute

streaminfo = compile(
    "Codec=(?P<Codec>[0-9]+),TimeBase=(?P<TimeBase>[0-9\\/]+),Width=(?P<Width>[0-9]+),Height=(?P<Height>[0-9]+),Format=(?P<Format>[0-9a-zA-Z]+),ColorSpace=(?P<ColorSpace>[0-9]+)"
)

StreamInfo

Bases: NamedTuple

codec instance-attribute

codec: int

colorspace instance-attribute

colorspace: Matrix

format instance-attribute

format: str

height instance-attribute

height: int

timebase instance-attribute

timebase: Fraction

width instance-attribute

width: int

from_file classmethod

from_file(
    file: FilePathType,
    ref_or_length: int | VideoNode | None = None,
    *,
    func: FuncExceptT | None = None
) -> LWIndex
Source code
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
@classmethod
def from_file(
    cls, file: FilePathType, ref_or_length: int | vs.VideoNode | None = None, *, func: FuncExceptT | None = None
) -> LWIndex:
    func = func or cls.from_file

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

    length = ref_or_length.num_frames if isinstance(ref_or_length, vs.VideoNode) else ref_or_length

    data = file.read_text('latin1').splitlines()

    indexstart, indexend = data.index("</StreamInfo>") + 1, data.index("</LibavReaderIndex>")

    if length and (idxlen := ((indexend - indexstart) // 2)) != length:
        raise FramesLengthError(
            func, '', 'index file length mismatch with specified length!',
            reason=dict(index=idxlen, clip=length)
        )

    sinfomatch = LWIndex.Regex.streaminfo.match(data[indexstart - 2])

    timebase_num, timebase_den = [
        int(i) for i in sinfomatch.group("TimeBase").split("/")  # type: ignore
    ]

    streaminfo = LWIndex.StreamInfo(
        int(sinfomatch.group("Codec")),  # type: ignore
        Fraction(timebase_num, timebase_den),
        int(sinfomatch.group("Width")),  # type: ignore
        int(sinfomatch.group("Height")),  # type: ignore
        sinfomatch.group("Format"),  # type: ignore
        Matrix(int(sinfomatch.group("ColorSpace"))),  # type: ignore
    )

    frames = sorted([
        LWIndex.Frame(*(
            int(x) for x in (
                match[0].group(key) for match in [  # type: ignore
                    (LWIndex.Regex.frame_first.match(data[i]), ['Index', 'POS', 'PTS', 'DTS', 'EDI']),
                    (LWIndex.Regex.frame_second.match(data[i + 1]), ['Key', 'Pic', 'POC', 'Repeat', 'Field'])
                ] for key in match[1]
            )
        ))
        for i in range(indexstart, indexend, 2)
    ], key=lambda x: x.pts)

    keyframes = Keyframes(i for i, f in enumerate(frames) if f.key)

    return LWIndex(streaminfo, frames, keyframes)

Timecode dataclass

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

A Timecode object representing the timecodes of a specific frame.

denominator instance-attribute

denominator: int

The framerate denominator.

frame instance-attribute

frame: int

The frame number.

numerator instance-attribute

numerator: int

The framerate numerator.

to_fraction

to_fraction() -> Fraction

Convert the Timecode to a Fraction that represents the FPS.

Source code
39
40
41
42
def to_fraction(self) -> Fraction:
    """Convert the Timecode to a Fraction that represents the FPS."""

    return Fraction(self.numerator, self.denominator)

Timecodes

Bases: list[Timecode]

A list of individual Timecode objects.

V1 class-attribute instance-attribute

V1 = 1

V2 class-attribute instance-attribute

V2 = 2

accumulate_norm_timecodes classmethod

accumulate_norm_timecodes(
    timecodes: Timecodes | dict[tuple[int, int], Fraction],
) -> tuple[Fraction, dict[Fraction, list[tuple[int, int]]]]
Source code
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@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: FuncExceptT | None = None) -> VideoNode

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

Parameters:

  • clip

    (VideoNode) –

    Clip to process.

  • func

    (FuncExceptT | 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
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
def assume_vfr(self, clip: vs.VideoNode, func: FuncExceptT | None = None) -> vs.VideoNode:
    """
    Force the given clip to be assumed to be vfr by other applications.

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

    :return:            Clip that should always be assumed to be vfr by other applications.
    """
    from ..utils import replace_ranges

    func = func or self.assume_vfr

    major_time, minor_fps = self.accumulate_norm_timecodes(self)

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

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

    return assumed_clip

from_clip classmethod

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

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
151
152
153
154
155
156
157
158
159
160
161
162
@classmethod
def from_clip(cls: type[TimecodesBoundT], clip: vs.VideoNode, **kwargs: Any) -> TimecodesBoundT:
    """
    Get the timecodes from a given clip.

    :param clip:        Clip to gather metrics from.
    :param kwargs:      Keyword arguments to pass on to `clip_async_render`.
    """
    def _get_timecode(n: int, f: vs.VideoFrame) -> Timecode:
        return Timecode(n, f.props._DurationNum, f.props._DurationDen)

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

from_file classmethod

from_file(
    file: FilePathType, ref: VideoNode, *, func: FuncExceptT | None = None
) -> TimecodesBoundT
from_file(
    file: FilePathType,
    length: int,
    den: int | None = None,
    *,
    func: FuncExceptT | None = None
) -> TimecodesBoundT
from_file(
    file: FilePathType,
    ref_or_length: int | VideoNode,
    den: int | None = None,
    *,
    func: FuncExceptT | None = None
) -> TimecodesBoundT

Read the timecodes from a given file.

Parameters:

  • file

    (FilePathType) –

    File to read.

  • ref_or_length

    (int | VideoNode) –

    Reference clip to get the total number of frames from. If int, take that as the total number of frames.

  • den

    (int | None, default: None ) –

    The denominator. If None, try to obtain it from the ref if possible, else fall back to 1001.

  • func

    (FuncExceptT | None, default: None ) –

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

Source code
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
@classmethod  # type: ignore
def from_file(
    cls: type[TimecodesBoundT], file: FilePathType, ref_or_length: int | vs.VideoNode, den: int | None = None,
    *, func: FuncExceptT | None = None
) -> TimecodesBoundT:
    """
    Read the timecodes from a given file.

    :param file:            File to read.
    :param ref_or_length:   Reference clip to get the total number of frames from.
                            If int, take that as the total number of frames.
    :param den:             The denominator. If None, try to obtain it from the ref if possible,
                            else fall back to 1001.
    :param func:            Function returned for custom error handling.
                            This should only be set by VS package developers.
    """
    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(int(denominator * float(f'{round((x - y) * 100, 4) / 100000:.08f}'[:-1])), denominator)
            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=dict(timecodes=len(norm_timecodes), clip=length)
        )

    return cls(
        Timecode(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 Fractions.

Source code
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
@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 Fractions."""

    from .funcs import fallback

    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)

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

        norm_timecodes[start:end] = [fps] * (end - 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
@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 = {k: 0 for k in timecodes.values()}

    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: FuncExceptT | 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def to_file(self, out: FilePathType, format: int = V2, func: FuncExceptT | 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.

    :param out:         Path to write the file to.
    :param format:      Format to write the file to.
    """
    from ..utils import check_perms

    func = func or self.to_file

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

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

    InvalidTimecodeVersionError.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
66
67
68
69
70
71
72
def to_fractions(self) -> list[Fraction]:
    """Convert to a list of frame lengths, representing the individual framerates."""

    return list(
        Fraction(x.numerator, x.denominator)
        for x 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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, Timecode] = (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