Skip to content

ABCTimestamps

Bases: ABC

Timestamps object contains informations about the timestamps of an video. Constant Frame Rate (CFR) and Variable Frame Rate (VFR) videos are supported.

Depending of the software you use to create the video, the PTS (Presentation Time Stamp) may be rounded of floored.

In general, the PTS are floored, so you should use RoundingMethod.FLOOR.

But, Matroska (.mkv) file are an exception because they are rounded. If you want to be compatible with mkv, use RoundingMethod.ROUND. By default, they only have a precision to milliseconds instead of nanoseconds like most format.

For more detail see
  1. mkvmerge timestamp scale documentation
  2. Matroska timestamp scale rounding notes
Source code in video_timestamps/abc_timestamps.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
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
295
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
322
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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
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
464
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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
class ABCTimestamps(ABC):
    """Timestamps object contains informations about the timestamps of an video.
    Constant Frame Rate (CFR) and Variable Frame Rate (VFR) videos are supported.

    Depending of the software you use to create the video, the PTS (Presentation Time Stamp)
    may be rounded of floored.

    In general, the PTS are floored, so you should use [`RoundingMethod.FLOOR`][video_timestamps.rounding_method.RoundingMethod.FLOOR].

    But, Matroska (.mkv) file are an exception because they are rounded.
    If you want to be compatible with mkv, use [`RoundingMethod.ROUND`][video_timestamps.rounding_method.RoundingMethod.ROUND].
    By default, they only have a precision to milliseconds instead of nanoseconds like most format.

    For more detail see:
        1. [mkvmerge timestamp scale documentation](https://mkvtoolnix.download/doc/mkvmerge.html#mkvmerge.description.timestamp_scale)
        2. [Matroska timestamp scale rounding notes](https://www.matroska.org/technical/notes.html#timestampscale-rounding)
    """

    @property
    @abstractmethod
    def fps(self) -> Fraction:
        """
        Returns:
            The framerate of the video.
        """
        pass

    @property
    @abstractmethod
    def time_scale(self) -> Fraction:
        """
        Returns:
            Unit of time (in seconds) in terms of which frame PTS are represented.

                **Important**: Don't confuse time_scale with the time_base. As a reminder, time_base = 1 / time_scale.
        """
        pass

    @property
    @abstractmethod
    def first_timestamps(self) -> Fraction:
        """
        Returns:
            Time (in seconds) of the first frame of the video.

                **Warning**: Depending on the subclass, the first_timestamps may not be rounded, so it won't really be first_timestamps.
        """
        pass

    @abstractmethod
    def _time_to_frame(
        self,
        time: Fraction,
        time_type: TimeType,
    ) -> int:
        pass

    def time_to_frame(
        self,
        time: int | Fraction,
        time_type: TimeType,
        input_unit: int | None = None
    ) -> int:
        """Converts a given time value into the corresponding frame number based on the specified time type.

        Parameters:
            time: The time value to convert.

                - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

                - If `time` is a Fraction, the value is expected to be in seconds.
            time_type: The type of timing to use for conversion.
            input_unit: The unit of the `time` parameter when it is an int.
                Must be a non-negative integer if specified.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds

                If None, the `time` will be a Fraction representing seconds.

        Returns:
            The corresponding frame number for the given time.

        Examples:
            >>> timestamps.time_to_frame(50, TimeType.START, 3)
            2
            >>> timestamps.time_to_frame(Fraction(50/1000), TimeType.START)
            2
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        if input_unit is None:
            if not isinstance(time, Fraction):
                raise ValueError("If input_unit is none, the time needs to be a Fraction.")
            time_in_second = time
        else:
            if not isinstance(time, int):
                raise ValueError("If you specify a input_unit, the time needs to be a int.")

            if input_unit < 0:
                raise ValueError("The input_unit needs to be above or equal to 0.")

            time_in_second = time * Fraction(1, 10 ** input_unit)

        first_timestamps = self.frame_to_time(0, TimeType.EXACT)

        if time_in_second < first_timestamps and time_type == TimeType.EXACT:
            raise ValueError(f"You cannot specify a time under the first timestamps {first_timestamps} with the TimeType.EXACT.")
        if time_in_second <= first_timestamps:
            if time_type == TimeType.START:
                return 0
            elif time_type == TimeType.END:
                raise ValueError(f"You cannot specify a time under or equals the first timestamps {first_timestamps} with the TimeType.END.")

        frame = self._time_to_frame(time_in_second, time_type)
        return frame


    @abstractmethod
    def _frame_to_time(
        self,
        frame: int,
    ) -> Fraction:
        pass

    @overload
    def frame_to_time(
        self,
        frame: int,
        time_type: TimeType,
        output_unit: None = None,
        center_time: bool = False,
    ) -> Fraction:
        ...

    @overload
    def frame_to_time(
        self,
        frame: int,
        time_type: TimeType,
        output_unit: int,
        center_time: bool = False,
    ) -> int:
        ...

    def frame_to_time(
        self,
        frame: int,
        time_type: TimeType,
        output_unit: int | None = None,
        center_time: bool = False,
    ) -> int | Fraction:
        """Converts a given frame number into the corresponding time value based on the specified time type.

        Parameters:
            frame: The frame number to convert.
            time_type: The type of timing to use for conversion.
            output_unit: The unit of the output time value.
                Must be a non-negative integer if specified.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds

                If None, the output will be a Fraction representing seconds.
            center_time: If True, the output time will represent the time at the center of two frames.
                This option is only applicable when `time_type` is either [`TimeType.START`][video_timestamps.time_type.TimeType.START] or [`TimeType.END`][video_timestamps.time_type.TimeType.END].

        Returns:
            The corresponding time for the given frame number.

        Examples:
            >>> timestamps.frame_to_time(2, TimeType.START, 3)
            83
            >>> timestamps.frame_to_time(2, TimeType.START)
            7507/90000
            >>> timestamps.frame_to_time(2, TimeType.START, 3, True)
            63
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        if output_unit is not None and output_unit < 0:
            raise ValueError("The output_unit needs to be above or equal to 0.")

        if frame < 0:
            raise ValueError("You cannot specify a frame under 0.")

        if time_type == TimeType.EXACT and center_time:
            raise ValueError("It doesn't make sense to use the time in the center of two frame for TimeType.EXACT.")

        if time_type == TimeType.START:
            upper_bound = self._frame_to_time(frame)

            if center_time and frame > 0:
                lower_bound = self._frame_to_time(frame - 1)
                time = (lower_bound + upper_bound) / 2
            else:
                time = upper_bound
        elif time_type == TimeType.END:
            upper_bound = self._frame_to_time(frame + 1)

            if center_time:
                lower_bound = self._frame_to_time(frame)
                time = (lower_bound + upper_bound) / 2
            else:
                time = upper_bound
        elif time_type == TimeType.EXACT:
            time = self._frame_to_time(frame)
        else:
            raise ValueError(f'The TimeType "{time_type}" isn\'t supported.')

        if output_unit is None:
            return time

        if time_type == TimeType.EXACT:
            time_output = ceil(time * Fraction(10) ** output_unit)
        elif center_time and not (time_type == TimeType.START and frame == 0):
            time_output = RoundingMethod.ROUND(time * 10 ** output_unit)
        else:
            time_output = floor(time * Fraction(10) ** output_unit)

        result_frame = self.time_to_frame(time_output, time_type, output_unit)

        if frame != result_frame:
            raise ValueError(
                f"The frame {frame} cannot be represented exactly at output_unit={output_unit}. "
                f"The conversion gave the time {time_output} which correspond to the frame {result_frame} which is different then {frame}. "
                f"Try using a finer output_unit then {time_output}."
            )

        return time_output


    def pts_to_frame(
        self,
        pts: int,
        time_type: TimeType,
        time_scale: Fraction | None = None
    ) -> int:
        """Converts a given PTS into the corresponding frame number based on the specified time type.

        Parameters:
            pts: The Presentation Time Stamp value to convert.
            time_type: The type of timing to use for conversion.
            time_scale: The time scale to interpret the `pts` parameter.
                If None, it is assumed that the `pts` parameter uses the same time scale as the Timestamps object.

        Returns:
            The corresponding frame number for the given PTS.

        Examples:
            >>> timestamps.pts_to_frame(7507, TimeType.START, Fraction(90000))
            2
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        if time_scale is None:
            time = pts / self.time_scale
        else:
            time = pts / time_scale

        frame = self.time_to_frame(time, time_type)
        return frame


    def frame_to_pts(
        self,
        frame: int,
        time_type: TimeType,
        time_scale: Fraction | None = None
    ) -> int:
        """Converts a given frame number into the corresponding PTS based on the specified time type.

        Parameters:
            frame: The frame number to convert.
            time_type: The type of timing to use for conversion.
            time_scale: The time scale to interpret the `pts` parameter.
                If None, it is assumed that the `pts` parameter uses the same time scale as the Timestamps object.

        Returns:
            The corresponding PTS for the given frame number.

        Examples:
            >>> timestamps.frame_to_pts(2, TimeType.START, Fraction(90000))
            7507
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        time = self.frame_to_time(frame, time_type)

        round_pts_method: Callable[[Fraction], int]
        if time_type == TimeType.EXACT:
            round_pts_method = ceil
        else:
            round_pts_method = floor

        if time_scale is None:
            pts = time * self.time_scale
            if pts != round_pts_method(pts):
                raise ValueError(f"An unexpected error occured. The generated pts {pts} isn't an integer. The requested frame is {frame} and the requested time_type is {time_type}. The object is {repr(self)}. Please, open an issue on GitHub.")
        else:
            pts = time * time_scale

        return round_pts_method(pts)


    @overload
    def move_time_to_frame(
        self,
        time: int | Fraction,
        time_type: TimeType,
        output_unit: None,
        input_unit: int | None = None,
        center_time: bool = False
    ) -> Fraction:
        ...

    @overload
    def move_time_to_frame(
        self,
        time: int | Fraction,
        time_type: TimeType,
        output_unit: int,
        input_unit: int | None = None,
        center_time: bool = False
    ) -> int:
        ...

    def move_time_to_frame(
        self,
        time: int | Fraction,
        time_type: TimeType,
        output_unit: int | None = None,
        input_unit: int | None = None,
        center_time: bool = False
    ) -> int | Fraction:
        """
        Moves the time to the corresponding frame time.
        It is something close to using "CTRL + 3" and "CTRL + 4" on Aegisub.

        Parameters:
            time: The time value to convert.

                - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

                - If `time` is a Fraction, the value is expected to be in seconds.
            time_type: The type of timing to use for conversion.
            output_unit: The unit of the output time value.
                Must be a non-negative integer if specified.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds

                If None, the output will be a Fraction representing seconds.
            input_unit: The unit of the `time` parameter when it is an int.
                Must be a non-negative integer if specified.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds

                If None, the `time` will be a Fraction representing seconds.
            center_time: If True, the output time will represent the time at the center of two frames.
                This option is only applicable when `time_type` is either [`TimeType.START`][video_timestamps.time_type.TimeType.START] or [`TimeType.END`][video_timestamps.time_type.TimeType.END].

        Returns:
            The output represents `time` moved to the frame time.

        Examples:
            >>> timestamps.move_time_to_frame(50, TimeType.START, 3, 3)
            83
            >>> timestamps.move_time_to_frame(50, TimeType.START, 9, 3)
            83411111
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        return self.frame_to_time(self.time_to_frame(time, time_type, input_unit), time_type, output_unit, center_time)


    def pts_to_time(
        self,
        pts: int,
        time_type: TimeType,
        output_unit: int,
        time_scale: Fraction | None = None
    ) -> int:
        """
        Converts a given PTS into the corresponding time, ensuring that
        the resulting value corresponds to the same frame.

        Parameters:
            pts: The Presentation Time Stamp value to convert.
            time_type: The type of timing to use for conversion.
            time_scale: The time scale to interpret the `pts` parameter.
                If None, it is assumed that the `pts` parameter uses the same time scale as the Timestamps object.

        Returns:
            The corresponding time for the given PTS.

        Examples:
            >>> timestamps.pts_to_time(7507, TimeType.START, 3, Fraction(90000))
            83
            >>> timestamps.pts_to_time(7507, TimeType.START, 9, Fraction(90000))
            83411111
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        if time_scale is None:
            time = pts / self.time_scale
        else:
            time = pts / time_scale

        return self.time_to_time(time, time_type, output_unit)


    @overload
    def time_to_pts(
        self,
        time: int,
        time_type: TimeType,
        input_unit: int,
        time_scale: Fraction | None = None,
    ) -> int:
        ...

    @overload
    def time_to_pts(
        self,
        time: Fraction,
        time_type: TimeType,
        input_unit: None = None,
        time_scale: Fraction | None = None,
    ) -> int:
        ...

    def time_to_pts(
        self,
        time: int | Fraction,
        time_type: TimeType,
        input_unit: int | None = None,
        time_scale: Fraction | None = None,
    ) -> int:
        """
        Converts a given time value into the corresponding PTS, ensuring that
        the resulting value corresponds to the same frame.

        Parameters:
            time: The time value to convert.

                - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

                - If `time` is a Fraction, the value is expected to be in seconds.
            time_type: The type of timing to use for conversion.
            input_unit: The unit of the `time` parameter when it is an int.
                Must be a non-negative integer if specified.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds

                If None, the `time` will be a `Fraction` representing seconds.
            time_scale: The time scale to interpret the `pts` that will be returned by this function.
                - If None, the `pts` that will be returned will uses the same time scale as the Timestamps object.

        Returns:
            The corresponding PTS for the given time.

        Examples:
            >>> timestamps.time_to_pts(83, TimeType.START, 3, Fraction(90000))
            7470
            >>> timestamps.time_to_pts(83411111, TimeType.START, 9, Fraction(90000))
            7507
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """

        if input_unit is None:
            time_in_second = time
        else:
            time_in_second = time * Fraction(1, 10 ** input_unit)

        if time_scale is None:
            output_time_scale = self.time_scale
        else:
            output_time_scale = time_scale

        frame = self.time_to_frame(time, time_type, input_unit)
        pts_output = time_in_second * output_time_scale

        # Try with round first because we want to get the closest result
        pts_output_round = RoundingMethod.ROUND(pts_output)
        frame_round = self.pts_to_frame(pts_output_round, time_type, output_time_scale)
        if frame_round == frame:
            return pts_output_round

        # Try with the opposite of round
        pts_output_other = floor(pts_output) if pts_output_round == ceil(pts_output) else ceil(pts_output)
        frame_other = self.pts_to_frame(pts_output_other, time_type, output_time_scale)
        if frame_other == frame:
            return pts_output_other

        raise ValueError(f"It is not possible to convert the time {time_in_second} to a PTS with a timescale of {output_time_scale} accurately.")


    @overload
    def time_to_time(
        self,
        time: int,
        time_type: TimeType,
        output_unit: int,
        input_unit: int,
    ) -> int:
        ...

    @overload
    def time_to_time(
        self,
        time: Fraction,
        time_type: TimeType,
        output_unit: int,
        input_unit: None = None,
    ) -> int:
        ...

    def time_to_time(
        self,
        time: int | Fraction,
        time_type: TimeType,
        output_unit: int,
        input_unit: int | None = None,
    ) -> int:
        """
        Converts a given time value from one unit to another, ensuring that
        the resulting value corresponds to the same frame.

        Parameters:
            time: The time value to convert.

                - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

                - If `time` is a Fraction, the value is expected to be in seconds.
            time_type: The type of timing to use for conversion.
            output_unit: The unit of the output time value.
                Must be a non-negative integer.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds
            input_unit: The unit of the `time` parameter when it is an `int`.
                - Must be a non-negative integer if specified.

                Common values:

                - 3 means milliseconds
                - 6 means microseconds
                - 9 means nanoseconds

                If None, the `time` will be a `Fraction` representing seconds.

        Returns:
            The converted time value expressed in `output_unit`.

        Examples:
            >>> timestamps.time_to_time(83411111, TimeType.START, 3, 9)
            83
            >>> timestamps.time_to_time(83411112, TimeType.START, 3, 9)
            84
            # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
        """
        if input_unit is not None and input_unit < 0:
            raise ValueError("The input_unit needs to be above or equal to 0.")

        if output_unit < 0:
            raise ValueError("The output_unit needs to be above or equal to 0.")

        if input_unit == output_unit and isinstance(time, int): # Just to make mypy happy, use isinstance so it doesn't report int | Fraction.
            return time
        elif input_unit is not None and input_unit < output_unit:
            return RoundingMethod.ROUND(time * 10 ** (output_unit - input_unit)) # Just to make mypy happy, round the result, but it is impossible to get a float from this.
        else:
            frame = self.time_to_frame(time, time_type, input_unit)
            if isinstance(time, int) and input_unit is not None: # Just to make mypy happy, verify if input_unit is not None even if it can't.
                time_output = Fraction(time, 10 ** (input_unit - output_unit))
            else:
                time_output = time * Fraction(10 ** output_unit)

            # Try with round first because we want to get the closest result
            time_output_round = RoundingMethod.ROUND(time_output)
            try:
                frame_round = self.time_to_frame(time_output_round, time_type, output_unit)
            except ValueError:
                frame_round = None
            if frame_round == frame:
                return time_output_round

            # Try with the opposite of round
            time_output_other = floor(time_output) if time_output_round == ceil(time_output) else ceil(time_output)
            try:
                frame_other = self.time_to_frame(time_output_other, time_type, output_unit)
            except ValueError:
                frame_other = None
            if frame_other == frame:
                return time_output_other

            raise ValueError(f"It is not possible to convert the time {time} from {input_unit} to {output_unit} accurately.")


    @abstractmethod
    def __eq__(self, other: object) -> bool:
        pass


    @abstractmethod
    def __hash__(self) -> int:
        pass

fps abstractmethod property

Returns:

Type Description
Fraction

The framerate of the video.

time_scale abstractmethod property

Returns:

Type Description
Fraction

Unit of time (in seconds) in terms of which frame PTS are represented.

Important: Don't confuse time_scale with the time_base. As a reminder, time_base = 1 / time_scale.

first_timestamps abstractmethod property

Returns:

Type Description
Fraction

Time (in seconds) of the first frame of the video.

Warning: Depending on the subclass, the first_timestamps may not be rounded, so it won't really be first_timestamps.

time_to_frame(time, time_type, input_unit=None)

Converts a given time value into the corresponding frame number based on the specified time type.

Parameters:

Name Type Description Default
time int | Fraction

The time value to convert.

  • If time is an int, the unit of the value is specified by input_unit parameter.

  • If time is a Fraction, the value is expected to be in seconds.

required
time_type TimeType

The type of timing to use for conversion.

required
input_unit int | None

The unit of the time parameter when it is an int. Must be a non-negative integer if specified.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds

If None, the time will be a Fraction representing seconds.

None

Returns:

Type Description
int

The corresponding frame number for the given time.

Examples:

>>> timestamps.time_to_frame(50, TimeType.START, 3)
2
>>> timestamps.time_to_frame(Fraction(50/1000), TimeType.START)
2
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def time_to_frame(
    self,
    time: int | Fraction,
    time_type: TimeType,
    input_unit: int | None = None
) -> int:
    """Converts a given time value into the corresponding frame number based on the specified time type.

    Parameters:
        time: The time value to convert.

            - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

            - If `time` is a Fraction, the value is expected to be in seconds.
        time_type: The type of timing to use for conversion.
        input_unit: The unit of the `time` parameter when it is an int.
            Must be a non-negative integer if specified.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds

            If None, the `time` will be a Fraction representing seconds.

    Returns:
        The corresponding frame number for the given time.

    Examples:
        >>> timestamps.time_to_frame(50, TimeType.START, 3)
        2
        >>> timestamps.time_to_frame(Fraction(50/1000), TimeType.START)
        2
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    if input_unit is None:
        if not isinstance(time, Fraction):
            raise ValueError("If input_unit is none, the time needs to be a Fraction.")
        time_in_second = time
    else:
        if not isinstance(time, int):
            raise ValueError("If you specify a input_unit, the time needs to be a int.")

        if input_unit < 0:
            raise ValueError("The input_unit needs to be above or equal to 0.")

        time_in_second = time * Fraction(1, 10 ** input_unit)

    first_timestamps = self.frame_to_time(0, TimeType.EXACT)

    if time_in_second < first_timestamps and time_type == TimeType.EXACT:
        raise ValueError(f"You cannot specify a time under the first timestamps {first_timestamps} with the TimeType.EXACT.")
    if time_in_second <= first_timestamps:
        if time_type == TimeType.START:
            return 0
        elif time_type == TimeType.END:
            raise ValueError(f"You cannot specify a time under or equals the first timestamps {first_timestamps} with the TimeType.END.")

    frame = self._time_to_frame(time_in_second, time_type)
    return frame

frame_to_time(frame, time_type, output_unit=None, center_time=False)

frame_to_time(
    frame: int,
    time_type: TimeType,
    output_unit: None = None,
    center_time: bool = False,
) -> Fraction
frame_to_time(
    frame: int,
    time_type: TimeType,
    output_unit: int,
    center_time: bool = False,
) -> int

Converts a given frame number into the corresponding time value based on the specified time type.

Parameters:

Name Type Description Default
frame int

The frame number to convert.

required
time_type TimeType

The type of timing to use for conversion.

required
output_unit int | None

The unit of the output time value. Must be a non-negative integer if specified.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds

If None, the output will be a Fraction representing seconds.

None
center_time bool

If True, the output time will represent the time at the center of two frames. This option is only applicable when time_type is either TimeType.START or TimeType.END.

False

Returns:

Type Description
int | Fraction

The corresponding time for the given frame number.

Examples:

>>> timestamps.frame_to_time(2, TimeType.START, 3)
83
>>> timestamps.frame_to_time(2, TimeType.START)
7507/90000
>>> timestamps.frame_to_time(2, TimeType.START, 3, True)
63
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
247
248
249
250
def frame_to_time(
    self,
    frame: int,
    time_type: TimeType,
    output_unit: int | None = None,
    center_time: bool = False,
) -> int | Fraction:
    """Converts a given frame number into the corresponding time value based on the specified time type.

    Parameters:
        frame: The frame number to convert.
        time_type: The type of timing to use for conversion.
        output_unit: The unit of the output time value.
            Must be a non-negative integer if specified.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds

            If None, the output will be a Fraction representing seconds.
        center_time: If True, the output time will represent the time at the center of two frames.
            This option is only applicable when `time_type` is either [`TimeType.START`][video_timestamps.time_type.TimeType.START] or [`TimeType.END`][video_timestamps.time_type.TimeType.END].

    Returns:
        The corresponding time for the given frame number.

    Examples:
        >>> timestamps.frame_to_time(2, TimeType.START, 3)
        83
        >>> timestamps.frame_to_time(2, TimeType.START)
        7507/90000
        >>> timestamps.frame_to_time(2, TimeType.START, 3, True)
        63
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    if output_unit is not None and output_unit < 0:
        raise ValueError("The output_unit needs to be above or equal to 0.")

    if frame < 0:
        raise ValueError("You cannot specify a frame under 0.")

    if time_type == TimeType.EXACT and center_time:
        raise ValueError("It doesn't make sense to use the time in the center of two frame for TimeType.EXACT.")

    if time_type == TimeType.START:
        upper_bound = self._frame_to_time(frame)

        if center_time and frame > 0:
            lower_bound = self._frame_to_time(frame - 1)
            time = (lower_bound + upper_bound) / 2
        else:
            time = upper_bound
    elif time_type == TimeType.END:
        upper_bound = self._frame_to_time(frame + 1)

        if center_time:
            lower_bound = self._frame_to_time(frame)
            time = (lower_bound + upper_bound) / 2
        else:
            time = upper_bound
    elif time_type == TimeType.EXACT:
        time = self._frame_to_time(frame)
    else:
        raise ValueError(f'The TimeType "{time_type}" isn\'t supported.')

    if output_unit is None:
        return time

    if time_type == TimeType.EXACT:
        time_output = ceil(time * Fraction(10) ** output_unit)
    elif center_time and not (time_type == TimeType.START and frame == 0):
        time_output = RoundingMethod.ROUND(time * 10 ** output_unit)
    else:
        time_output = floor(time * Fraction(10) ** output_unit)

    result_frame = self.time_to_frame(time_output, time_type, output_unit)

    if frame != result_frame:
        raise ValueError(
            f"The frame {frame} cannot be represented exactly at output_unit={output_unit}. "
            f"The conversion gave the time {time_output} which correspond to the frame {result_frame} which is different then {frame}. "
            f"Try using a finer output_unit then {time_output}."
        )

    return time_output

pts_to_frame(pts, time_type, time_scale=None)

Converts a given PTS into the corresponding frame number based on the specified time type.

Parameters:

Name Type Description Default
pts int

The Presentation Time Stamp value to convert.

required
time_type TimeType

The type of timing to use for conversion.

required
time_scale Fraction | None

The time scale to interpret the pts parameter. If None, it is assumed that the pts parameter uses the same time scale as the Timestamps object.

None

Returns:

Type Description
int

The corresponding frame number for the given PTS.

Examples:

>>> timestamps.pts_to_frame(7507, TimeType.START, Fraction(90000))
2
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
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
def pts_to_frame(
    self,
    pts: int,
    time_type: TimeType,
    time_scale: Fraction | None = None
) -> int:
    """Converts a given PTS into the corresponding frame number based on the specified time type.

    Parameters:
        pts: The Presentation Time Stamp value to convert.
        time_type: The type of timing to use for conversion.
        time_scale: The time scale to interpret the `pts` parameter.
            If None, it is assumed that the `pts` parameter uses the same time scale as the Timestamps object.

    Returns:
        The corresponding frame number for the given PTS.

    Examples:
        >>> timestamps.pts_to_frame(7507, TimeType.START, Fraction(90000))
        2
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    if time_scale is None:
        time = pts / self.time_scale
    else:
        time = pts / time_scale

    frame = self.time_to_frame(time, time_type)
    return frame

frame_to_pts(frame, time_type, time_scale=None)

Converts a given frame number into the corresponding PTS based on the specified time type.

Parameters:

Name Type Description Default
frame int

The frame number to convert.

required
time_type TimeType

The type of timing to use for conversion.

required
time_scale Fraction | None

The time scale to interpret the pts parameter. If None, it is assumed that the pts parameter uses the same time scale as the Timestamps object.

None

Returns:

Type Description
int

The corresponding PTS for the given frame number.

Examples:

>>> timestamps.frame_to_pts(2, TimeType.START, Fraction(90000))
7507
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
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
318
319
320
321
322
323
def frame_to_pts(
    self,
    frame: int,
    time_type: TimeType,
    time_scale: Fraction | None = None
) -> int:
    """Converts a given frame number into the corresponding PTS based on the specified time type.

    Parameters:
        frame: The frame number to convert.
        time_type: The type of timing to use for conversion.
        time_scale: The time scale to interpret the `pts` parameter.
            If None, it is assumed that the `pts` parameter uses the same time scale as the Timestamps object.

    Returns:
        The corresponding PTS for the given frame number.

    Examples:
        >>> timestamps.frame_to_pts(2, TimeType.START, Fraction(90000))
        7507
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    time = self.frame_to_time(frame, time_type)

    round_pts_method: Callable[[Fraction], int]
    if time_type == TimeType.EXACT:
        round_pts_method = ceil
    else:
        round_pts_method = floor

    if time_scale is None:
        pts = time * self.time_scale
        if pts != round_pts_method(pts):
            raise ValueError(f"An unexpected error occured. The generated pts {pts} isn't an integer. The requested frame is {frame} and the requested time_type is {time_type}. The object is {repr(self)}. Please, open an issue on GitHub.")
    else:
        pts = time * time_scale

    return round_pts_method(pts)

move_time_to_frame(time, time_type, output_unit=None, input_unit=None, center_time=False)

move_time_to_frame(
    time: int | Fraction,
    time_type: TimeType,
    output_unit: None,
    input_unit: int | None = None,
    center_time: bool = False,
) -> Fraction
move_time_to_frame(
    time: int | Fraction,
    time_type: TimeType,
    output_unit: int,
    input_unit: int | None = None,
    center_time: bool = False,
) -> int

Moves the time to the corresponding frame time. It is something close to using "CTRL + 3" and "CTRL + 4" on Aegisub.

Parameters:

Name Type Description Default
time int | Fraction

The time value to convert.

  • If time is an int, the unit of the value is specified by input_unit parameter.

  • If time is a Fraction, the value is expected to be in seconds.

required
time_type TimeType

The type of timing to use for conversion.

required
output_unit int | None

The unit of the output time value. Must be a non-negative integer if specified.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds

If None, the output will be a Fraction representing seconds.

None
input_unit int | None

The unit of the time parameter when it is an int. Must be a non-negative integer if specified.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds

If None, the time will be a Fraction representing seconds.

None
center_time bool

If True, the output time will represent the time at the center of two frames. This option is only applicable when time_type is either TimeType.START or TimeType.END.

False

Returns:

Type Description
int | Fraction

The output represents time moved to the frame time.

Examples:

>>> timestamps.move_time_to_frame(50, TimeType.START, 3, 3)
83
>>> timestamps.move_time_to_frame(50, TimeType.START, 9, 3)
83411111
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def move_time_to_frame(
    self,
    time: int | Fraction,
    time_type: TimeType,
    output_unit: int | None = None,
    input_unit: int | None = None,
    center_time: bool = False
) -> int | Fraction:
    """
    Moves the time to the corresponding frame time.
    It is something close to using "CTRL + 3" and "CTRL + 4" on Aegisub.

    Parameters:
        time: The time value to convert.

            - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

            - If `time` is a Fraction, the value is expected to be in seconds.
        time_type: The type of timing to use for conversion.
        output_unit: The unit of the output time value.
            Must be a non-negative integer if specified.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds

            If None, the output will be a Fraction representing seconds.
        input_unit: The unit of the `time` parameter when it is an int.
            Must be a non-negative integer if specified.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds

            If None, the `time` will be a Fraction representing seconds.
        center_time: If True, the output time will represent the time at the center of two frames.
            This option is only applicable when `time_type` is either [`TimeType.START`][video_timestamps.time_type.TimeType.START] or [`TimeType.END`][video_timestamps.time_type.TimeType.END].

    Returns:
        The output represents `time` moved to the frame time.

    Examples:
        >>> timestamps.move_time_to_frame(50, TimeType.START, 3, 3)
        83
        >>> timestamps.move_time_to_frame(50, TimeType.START, 9, 3)
        83411111
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    return self.frame_to_time(self.time_to_frame(time, time_type, input_unit), time_type, output_unit, center_time)

pts_to_time(pts, time_type, output_unit, time_scale=None)

Converts a given PTS into the corresponding time, ensuring that the resulting value corresponds to the same frame.

Parameters:

Name Type Description Default
pts int

The Presentation Time Stamp value to convert.

required
time_type TimeType

The type of timing to use for conversion.

required
time_scale Fraction | None

The time scale to interpret the pts parameter. If None, it is assumed that the pts parameter uses the same time scale as the Timestamps object.

None

Returns:

Type Description
int

The corresponding time for the given PTS.

Examples:

>>> timestamps.pts_to_time(7507, TimeType.START, 3, Fraction(90000))
83
>>> timestamps.pts_to_time(7507, TimeType.START, 9, Fraction(90000))
83411111
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
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
429
430
431
432
433
434
435
436
437
def pts_to_time(
    self,
    pts: int,
    time_type: TimeType,
    output_unit: int,
    time_scale: Fraction | None = None
) -> int:
    """
    Converts a given PTS into the corresponding time, ensuring that
    the resulting value corresponds to the same frame.

    Parameters:
        pts: The Presentation Time Stamp value to convert.
        time_type: The type of timing to use for conversion.
        time_scale: The time scale to interpret the `pts` parameter.
            If None, it is assumed that the `pts` parameter uses the same time scale as the Timestamps object.

    Returns:
        The corresponding time for the given PTS.

    Examples:
        >>> timestamps.pts_to_time(7507, TimeType.START, 3, Fraction(90000))
        83
        >>> timestamps.pts_to_time(7507, TimeType.START, 9, Fraction(90000))
        83411111
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    if time_scale is None:
        time = pts / self.time_scale
    else:
        time = pts / time_scale

    return self.time_to_time(time, time_type, output_unit)

time_to_pts(time, time_type, input_unit=None, time_scale=None)

time_to_pts(
    time: int,
    time_type: TimeType,
    input_unit: int,
    time_scale: Fraction | None = None,
) -> int
time_to_pts(
    time: Fraction,
    time_type: TimeType,
    input_unit: None = None,
    time_scale: Fraction | None = None,
) -> int

Converts a given time value into the corresponding PTS, ensuring that the resulting value corresponds to the same frame.

Parameters:

Name Type Description Default
time int | Fraction

The time value to convert.

  • If time is an int, the unit of the value is specified by input_unit parameter.

  • If time is a Fraction, the value is expected to be in seconds.

required
time_type TimeType

The type of timing to use for conversion.

required
input_unit int | None

The unit of the time parameter when it is an int. Must be a non-negative integer if specified.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds

If None, the time will be a Fraction representing seconds.

None
time_scale Fraction | None

The time scale to interpret the pts that will be returned by this function. - If None, the pts that will be returned will uses the same time scale as the Timestamps object.

None

Returns:

Type Description
int

The corresponding PTS for the given time.

Examples:

>>> timestamps.time_to_pts(83, TimeType.START, 3, Fraction(90000))
7470
>>> timestamps.time_to_pts(83411111, TimeType.START, 9, Fraction(90000))
7507
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
460
461
462
463
464
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
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
def time_to_pts(
    self,
    time: int | Fraction,
    time_type: TimeType,
    input_unit: int | None = None,
    time_scale: Fraction | None = None,
) -> int:
    """
    Converts a given time value into the corresponding PTS, ensuring that
    the resulting value corresponds to the same frame.

    Parameters:
        time: The time value to convert.

            - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

            - If `time` is a Fraction, the value is expected to be in seconds.
        time_type: The type of timing to use for conversion.
        input_unit: The unit of the `time` parameter when it is an int.
            Must be a non-negative integer if specified.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds

            If None, the `time` will be a `Fraction` representing seconds.
        time_scale: The time scale to interpret the `pts` that will be returned by this function.
            - If None, the `pts` that will be returned will uses the same time scale as the Timestamps object.

    Returns:
        The corresponding PTS for the given time.

    Examples:
        >>> timestamps.time_to_pts(83, TimeType.START, 3, Fraction(90000))
        7470
        >>> timestamps.time_to_pts(83411111, TimeType.START, 9, Fraction(90000))
        7507
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """

    if input_unit is None:
        time_in_second = time
    else:
        time_in_second = time * Fraction(1, 10 ** input_unit)

    if time_scale is None:
        output_time_scale = self.time_scale
    else:
        output_time_scale = time_scale

    frame = self.time_to_frame(time, time_type, input_unit)
    pts_output = time_in_second * output_time_scale

    # Try with round first because we want to get the closest result
    pts_output_round = RoundingMethod.ROUND(pts_output)
    frame_round = self.pts_to_frame(pts_output_round, time_type, output_time_scale)
    if frame_round == frame:
        return pts_output_round

    # Try with the opposite of round
    pts_output_other = floor(pts_output) if pts_output_round == ceil(pts_output) else ceil(pts_output)
    frame_other = self.pts_to_frame(pts_output_other, time_type, output_time_scale)
    if frame_other == frame:
        return pts_output_other

    raise ValueError(f"It is not possible to convert the time {time_in_second} to a PTS with a timescale of {output_time_scale} accurately.")

time_to_time(time, time_type, output_unit, input_unit=None)

time_to_time(
    time: int,
    time_type: TimeType,
    output_unit: int,
    input_unit: int,
) -> int
time_to_time(
    time: Fraction,
    time_type: TimeType,
    output_unit: int,
    input_unit: None = None,
) -> int

Converts a given time value from one unit to another, ensuring that the resulting value corresponds to the same frame.

Parameters:

Name Type Description Default
time int | Fraction

The time value to convert.

  • If time is an int, the unit of the value is specified by input_unit parameter.

  • If time is a Fraction, the value is expected to be in seconds.

required
time_type TimeType

The type of timing to use for conversion.

required
output_unit int

The unit of the output time value. Must be a non-negative integer.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds
required
input_unit int | None

The unit of the time parameter when it is an int. - Must be a non-negative integer if specified.

Common values:

  • 3 means milliseconds
  • 6 means microseconds
  • 9 means nanoseconds

If None, the time will be a Fraction representing seconds.

None

Returns:

Type Description
int

The converted time value expressed in output_unit.

Examples:

>>> timestamps.time_to_time(83411111, TimeType.START, 3, 9)
83
>>> timestamps.time_to_time(83411112, TimeType.START, 3, 9)
84
# Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
Source code in video_timestamps/abc_timestamps.py
550
551
552
553
554
555
556
557
558
559
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def time_to_time(
    self,
    time: int | Fraction,
    time_type: TimeType,
    output_unit: int,
    input_unit: int | None = None,
) -> int:
    """
    Converts a given time value from one unit to another, ensuring that
    the resulting value corresponds to the same frame.

    Parameters:
        time: The time value to convert.

            - If `time` is an int, the unit of the value is specified by `input_unit` parameter.

            - If `time` is a Fraction, the value is expected to be in seconds.
        time_type: The type of timing to use for conversion.
        output_unit: The unit of the output time value.
            Must be a non-negative integer.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds
        input_unit: The unit of the `time` parameter when it is an `int`.
            - Must be a non-negative integer if specified.

            Common values:

            - 3 means milliseconds
            - 6 means microseconds
            - 9 means nanoseconds

            If None, the `time` will be a `Fraction` representing seconds.

    Returns:
        The converted time value expressed in `output_unit`.

    Examples:
        >>> timestamps.time_to_time(83411111, TimeType.START, 3, 9)
        83
        >>> timestamps.time_to_time(83411112, TimeType.START, 3, 9)
        84
        # Example with FPS = 24000/1001, time_scale = 90000, rounding method = FLOOR.
    """
    if input_unit is not None and input_unit < 0:
        raise ValueError("The input_unit needs to be above or equal to 0.")

    if output_unit < 0:
        raise ValueError("The output_unit needs to be above or equal to 0.")

    if input_unit == output_unit and isinstance(time, int): # Just to make mypy happy, use isinstance so it doesn't report int | Fraction.
        return time
    elif input_unit is not None and input_unit < output_unit:
        return RoundingMethod.ROUND(time * 10 ** (output_unit - input_unit)) # Just to make mypy happy, round the result, but it is impossible to get a float from this.
    else:
        frame = self.time_to_frame(time, time_type, input_unit)
        if isinstance(time, int) and input_unit is not None: # Just to make mypy happy, verify if input_unit is not None even if it can't.
            time_output = Fraction(time, 10 ** (input_unit - output_unit))
        else:
            time_output = time * Fraction(10 ** output_unit)

        # Try with round first because we want to get the closest result
        time_output_round = RoundingMethod.ROUND(time_output)
        try:
            frame_round = self.time_to_frame(time_output_round, time_type, output_unit)
        except ValueError:
            frame_round = None
        if frame_round == frame:
            return time_output_round

        # Try with the opposite of round
        time_output_other = floor(time_output) if time_output_round == ceil(time_output) else ceil(time_output)
        try:
            frame_other = self.time_to_frame(time_output_other, time_type, output_unit)
        except ValueError:
            frame_other = None
        if frame_other == frame:
            return time_output_other

        raise ValueError(f"It is not possible to convert the time {time} from {input_unit} to {output_unit} accurately.")