Skip to content

Commit

Permalink
Fixes rounding in timecode conversion from seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
palemieux authored Oct 31, 2024
1 parent c0f6929 commit 848aeee
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/main/python/ttconv/time_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ def parse(time_code: str) -> ClockTime:

@staticmethod
def from_seconds(seconds: Union[float, Fraction]) -> ClockTime:
"""Creates a time code from time offset in seconds"""
"""Creates a time code from time offset in seconds (rounds to the closest millisecond)"""

if seconds < 0:
raise ValueError("Seconds must not be less than zero")

seconds = float(seconds)
seconds = round(seconds, 3)

h = floor(seconds / 3600)
m = floor(seconds / 60 % 60)
Expand Down
17 changes: 17 additions & 0 deletions src/test/python/test_time_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,22 @@ def test_time_code(self):
self.assertEqual("24:00:01,500", str(time_code))
self.assertEqual(seconds, time_code.to_seconds())

def test_from_seconds_rounding_up(self):
seconds = Fraction(41039999,7500)
time_code = ClockTime.from_seconds(seconds)
self.assertEqual(time_code.get_hours(), 1)
self.assertEqual(time_code.get_minutes(), 31)
self.assertEqual(time_code.get_seconds(), 12)
self.assertEqual(time_code.get_milliseconds(), 0)


def test_from_seconds_rounding_down(self):
seconds = 5471.9994
time_code = ClockTime.from_seconds(seconds)
self.assertEqual(time_code.get_hours(), 1)
self.assertEqual(time_code.get_minutes(), 31)
self.assertEqual(time_code.get_seconds(), 11)
self.assertEqual(time_code.get_milliseconds(), 999)

if __name__ == '__main__':
unittest.main()
6 changes: 3 additions & 3 deletions src/test/python/test_vtt_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_position(self):
expected_vtt="""WEBVTT
1
00:00:03.501 --> 00:00:12.000 line:90%,end
00:00:03.500 --> 00:00:12.000 line:90%,end
Only one or two short samples are needed
to make sure the conversion basically works
Expand Down Expand Up @@ -177,7 +177,7 @@ def test_align(self):
expected_vtt="""WEBVTT
1
00:00:03.501 --> 00:00:12.000 align:center
00:00:03.500 --> 00:00:12.000 align:center
Only one or two short samples are needed
to make sure the conversion basically works
Expand Down Expand Up @@ -217,7 +217,7 @@ def test_cue_id(self):

expected_vtt="""WEBVTT
00:00:03.501 --> 00:00:12.000
00:00:03.500 --> 00:00:12.000
Only one or two short samples are needed
to make sure the conversion basically works
Expand Down

0 comments on commit 848aeee

Please sign in to comment.