Skip to content

The swiss army knife of lossless video/audio editing

Fix frame timecode at whole seconds for rational fps like 24000/1001

Claudece153fa9b798
diff --git a/src/renderer/src/util/duration.test.ts b/src/renderer/src/util/duration.test.ts
index 3395a46b..88eee6fa 100644
--- a/src/renderer/src/util/duration.test.ts
+++ b/src/renderer/src/util/duration.test.ts
@@ -97,3 +97,14 @@ it('should round up properly', () => {
expect(formatDuration({ seconds: 3599.9999 })).toBe('01:00:00.000');
expect(formatDuration({ seconds: (3600 - halfFrame) + 0.001, fps })).toBe('01:00:00.00');
});
+
+// 20 minutes covers e.g. 00:16:41 at 24000/1001, where floating point rounding used to show the wrong frame
+it.each([24, 25, 30, 60, 24000 / 1001, 30000 / 1001, 48000 / 1001, 60000 / 1001])('should round-trip every frame timecode at %d fps', (fps) => {
+ const mismatches: string[] = [];
+ for (let frame = 0; frame < fps * 60 * 20; frame += 1) {
+ const formatted = formatDuration({ seconds: frame / fps, fps });
+ const roundTripped = formatDuration({ seconds: parseDuration(formatted, fps), fps });
+ if (roundTripped !== formatted) mismatches.push(`${formatted} -> ${roundTripped}`);
+ }
+ expect(mismatches).toEqual([]);
+});
diff --git a/src/renderer/src/util/duration.ts b/src/renderer/src/util/duration.ts
index 6fc5aa09..4ee4b5a5 100644
--- a/src/renderer/src/util/duration.ts
+++ b/src/renderer/src/util/duration.ts
@@ -18,14 +18,15 @@ export function formatDuration({ seconds: totalSecondsIn, fileNameFriendly, show
// round to integer for our current unit
const totalUnits = Math.round(totalSecondsAbs * unitsPerSec);
- const seconds = Math.floor(totalUnits / unitsPerSec);
+ // epsilon: with fractional fps like 24000/1001, e.g. 24000 / fps = 1000.9999999999999
+ const seconds = Math.floor(totalUnits / unitsPerSec + 1e-9);
const secondsPadded = padStart(String(seconds % 60), 2, '0');
- const minutes = Math.floor(totalUnits / unitsPerSec / 60) % 60;
- const hours = Math.floor(totalUnits / unitsPerSec / 60 / 60);
+ const minutes = Math.floor(seconds / 60) % 60;
+ const hours = Math.floor(seconds / 60 / 60);
const minutesPadded = shorten && hours === 0 ? `${minutes}` : padStart(String(minutes), 2, '0');
- const remainder = totalUnits % unitsPerSec;
+ const remainder = Math.max(0, totalUnits - seconds * unitsPerSec);
// Be nice to filenames and use .
const delim = fileNameFriendly ? '.' : ':';
@@ -39,7 +40,7 @@ export function formatDuration({ seconds: totalSecondsIn, fileNameFriendly, show
let fraction = '';
if (showFraction && !(shorten && remainder === 0)) {
const numDigits = fps != null ? 2 : 3;
- fraction = `.${padStart(String(Math.floor(remainder)), numDigits, '0')}`;
+ fraction = `.${padStart(String(Math.floor(remainder + 1e-6)), numDigits, '0')}`;
}
return `${sign}${hoursPart}${minutesPadded}${delim}${secondsPadded}${fraction}`;