Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions scenedetect/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,15 @@
# e.g. 23.976 should be detected as 24000/1001, 29.97 should be detected as 30000/1001, etc.
_NTSC_DETECTION_TOLERANCE: float = 1e-3

# Float error allowed, in units in the last place (ulps) of the scaled value, when truncating a
# time to a number of decimal places, e.g. 0.29 * 100 == 28.999999999999996 should truncate to 29,
# not 28. Converting a time to seconds and scaling it by a power of ten each add at most about one
# ulp of error, so a few ulps absorb it while staying far below the spacing of real timestamps.
Comment thread
rishi02102017 marked this conversation as resolved.
Resolved
# The limit is very long videos at high precision: at precision 9 with a 1/90000 time base, the
# tolerance passes the gap between timestamps after about 40 hours, and the last digit can come
# out one higher than it should.
_TRUNCATION_ULPS: int = 4


##
## Helpers
Expand Down Expand Up @@ -455,12 +464,24 @@ def get_timecode(
secs = self.frame_num / float(self.frame_rate)
else:
secs = self.seconds
# Negative times (e.g. from a negative PTS) are shown as zero on both paths below.
secs = max(0.0, secs)
if not use_rounding:
# Truncate in whole units of the output precision, allowing for float error (see
# _TRUNCATION_ULPS). The split into hours, minutes and seconds is done with integers so
# that no further float error can creep in.
scaled = secs * 10**precision
units = math.floor(scaled + _TRUNCATION_ULPS * math.ulp(scaled))
Comment thread
rishi02102017 marked this conversation as resolved.
Resolved
whole_secs, fraction = divmod(units, 10**precision)
hrs, whole_secs = divmod(whole_secs, int(_SECONDS_PER_HOUR))
mins, whole_secs = divmod(whole_secs, int(_SECONDS_PER_MINUTE))
msec_str = f".{fraction:0{precision}d}" if precision else ""
return f"{hrs:02d}:{mins:02d}:{whole_secs:02d}{msec_str}"
Comment thread
rishi02102017 marked this conversation as resolved.
Resolved
hrs = int(secs / _SECONDS_PER_HOUR)
secs -= hrs * _SECONDS_PER_HOUR
mins = int(secs / _SECONDS_PER_MINUTE)
secs = max(0.0, secs - (mins * _SECONDS_PER_MINUTE))
if use_rounding:
secs = round(secs, precision)
secs = round(secs, precision)
secs = min(_SECONDS_PER_MINUTE, secs)
# Guard against emitting timecodes with 60 seconds after rounding/floating point errors.
if int(secs) == _SECONDS_PER_MINUTE:
Expand Down
79 changes: 79 additions & 0 deletions tests/test_timecode.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
"""

# Third-Party Library Imports
import math
import numbers
import random
from fractions import Fraction

import pytest
Expand Down Expand Up @@ -372,6 +374,83 @@ def test_precision():
assert FrameTimecode(990, fps).get_timecode(precision=0, use_rounding=False) == "00:00:00"


def test_precision_truncation():
"""Truncating must drop the extra digits, never round up into the last digit that is kept."""
# 1.99996667s, e.g. a frame position from a 90 kHz time base.
tc = FrameTimecode(Timecode(pts=179997, time_base=Fraction(1, 90000)), Fraction(30000, 1001))
assert tc.get_timecode(precision=3, use_rounding=False) == "00:00:01.999"
assert tc.get_timecode(precision=2, use_rounding=False) == "00:00:01.99"
assert tc.get_timecode(precision=0, use_rounding=False) == "00:00:01"
assert tc.get_timecode(precision=3, use_rounding=True) == "00:00:02.000"

# Frame 911 is at 37.996s.
tc = FrameTimecode(911, Fraction(24000, 1001))
assert tc.get_timecode(precision=1, use_rounding=False) == "00:00:37.9"
assert tc.get_timecode(precision=1, use_rounding=True) == "00:00:38.0"

tc = FrameTimecode(59.99996, 24.0)
assert tc.get_timecode(use_rounding=False, nearest_frame=False) == "00:00:59.999"

# Float error must not truncate exact values down, e.g. 504 / (24000 / 1001) == 21.021.
tc = FrameTimecode(504, Fraction(24000, 1001))
assert tc.get_timecode(precision=3, use_rounding=False) == "00:00:21.021"
tc = FrameTimecode(61.29, 24.0)
assert tc.get_timecode(precision=2, use_rounding=False, nearest_frame=False) == "00:01:01.29"


def test_precision_truncation_matches_exact_arithmetic():
"""Truncation must give the exact answer at any precision, including large timestamps."""
# Float error is larger for big values at high precision: 8192.826s at 1/1000 time base.
tc = FrameTimecode(Timecode(pts=8192826, time_base=Fraction(1, 1000)), Fraction(30000, 1001))
assert tc.get_timecode(precision=3, use_rounding=False) == "02:16:32.826"
assert tc.get_timecode(precision=6, use_rounding=False) == "02:16:32.826000"

def exact(secs: Fraction, precision: int) -> str:
units = math.floor(secs * 10**precision)
secs, fraction = divmod(units, 10**precision)
hrs, secs = divmod(secs, 3600)
mins, secs = divmod(secs, 60)
return f"{hrs:02d}:{mins:02d}:{secs:02d}" + (
f".{fraction:0{precision}d}" if precision else ""
)

rng = random.Random(0)
precisions = (0, 1, 3, 6)
for time_base in (
Comment thread
rishi02102017 marked this conversation as resolved.
Resolved
Fraction(1, 1000),
Fraction(1, 90000),
Fraction(1, 24000),
Fraction(1001, 30000),
):
for _ in range(500):
pts = rng.randrange(0, 400_000_000)
tc = FrameTimecode(Timecode(pts=pts, time_base=time_base), Fraction(30000, 1001))
for precision in precisions:
assert tc.get_timecode(precision=precision, use_rounding=False) == exact(
pts * time_base, precision
), (pts, time_base, precision)

# Frame number timecodes.
for fps in (Fraction(24000, 1001), Fraction(30000, 1001), Fraction(25)):
for _ in range(500):
frame = rng.randrange(0, 10_000_000)
tc = FrameTimecode(frame, fps)
for precision in precisions:
assert tc.get_timecode(precision=precision, use_rounding=False) == exact(
Fraction(frame) / fps, precision
), (frame, fps, precision)


def test_negative_time_is_shown_as_zero():
"""A negative PTS gives a zero timecode, whether rounding or truncating."""
tc = FrameTimecode(Timecode(pts=-1, time_base=Fraction(1, 1000)), Fraction(30000, 1001))
assert tc.get_timecode(use_rounding=False) == "00:00:00.000"
assert tc.get_timecode(use_rounding=True) == "00:00:00.000"
tc = FrameTimecode(Timecode(pts=-4_000_000, time_base=Fraction(1, 1000)), Fraction(30000, 1001))
assert tc.get_timecode(use_rounding=False) == "00:00:00.000"
assert tc.get_timecode(use_rounding=True) == "00:00:00.000"


def test_rational_framerate_precision():
"""Rational framerates should round-trip frame/second conversions without drift."""
fps = Fraction(24000, 1001)
Expand Down
1 change: 1 addition & 0 deletions website/pages/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -866,3 +866,4 @@ Development
- [bugfix] `save-images` no longer takes the last image of a scene from the first frame of the next scene. `--frame-margin` is counted from the last frame of the scene again, as in v0.6 (`-m 0` now selects the last frame itself)
- [bugfix] Out of range values for `detect-adaptive --frame-window` (below 1) and `save-images` `--num-images` (below 1), `--scale`, `--height` and `--width` (negative) now give a usage error instead of a traceback, and the same values are rejected in a config file [#609](https://github.com/Breakthrough/PySceneDetect/issues/609)
- [bugfix] `detect-content` / `detect-adaptive` `--weights` set to all zeros, or with a negative or non-finite weight (also in a config file), now give an error instead of NaN frame scores and no detected scenes, and `ContentDetector` / `AdaptiveDetector` raise a `ValueError` for them [#612](https://github.com/Breakthrough/PySceneDetect/issues/612)
- [bugfix] `FrameTimecode.get_timecode()` with `use_rounding=False` now truncates instead of sometimes rounding up the last digit. Previously 0.4996 seconds with `precision=2` gave `00:00:00.50`, and 1.99997 seconds gave `00:00:01.000` instead of `00:00:01.999`. [#611](https://github.com/Breakthrough/PySceneDetect/issues/611)
Loading