Skip to content

🎥 Make videos programmatically with React

Fixes #3588

Jonny Burgera565f4478b02
diff --git a/packages/renderer/src/stringify-ffmpeg-filter.ts b/packages/renderer/src/stringify-ffmpeg-filter.ts
index e1cadedb75..fbd0051de2 100644
--- a/packages/renderer/src/stringify-ffmpeg-filter.ts
+++ b/packages/renderer/src/stringify-ffmpeg-filter.ts
@@ -13,6 +13,18 @@ export type ProcessedTrack = {
pad_end: string | null;
};
+const stringifyTrim = (trim: number) => {
+ const value = trim * 1_000_000;
+ const asString = `${value}us`;
+
+ // Handle very small values such as `"6e-7us"`, those are essentially rounding errors to 0
+ if (asString.includes('e-')) {
+ return '0us';
+ }
+
+ return asString;
+};
+
const trimAndSetTempo = ({
playbackRate,
trimLeft,
@@ -34,6 +46,10 @@ const trimAndSetTempo = ({
? Math.min(trimRight, assetDuration)
: trimRight;
+ // If we need seamless AAC stitching, we need to apply the tempo filter first
+ // because the atempo filter is not frame-perfect. It creates a small offset
+ // and the offset needs to be the same for all audio tracks, before processing it further.
+ // This also affects the trimLeft and trimRight values, as they need to be adjusted.
if (forSeamlessAacConcatenation) {
const actualTrimLeft = trimLeft / playbackRate;
const actualTrimRight = trimRightOrAssetDuration / playbackRate;
@@ -41,21 +57,23 @@ const trimAndSetTempo = ({
return {
filter: [
calculateATempo(playbackRate),
- `atrim=${actualTrimLeft * 1_000_000}us:${
- actualTrimRight * 1_000_000
- }us`,
+ `atrim=${stringifyTrim(actualTrimLeft)}us:${stringifyTrim(
+ actualTrimRight,
+ )}us`,
],
actualTrimLeft,
audibleDuration: actualTrimRight - actualTrimLeft,
};
}
+ // Otherwise, we first trim and then apply playback rate, as then the atempo
+ // filter needs to do less work.
if (!forSeamlessAacConcatenation) {
return {
filter: [
- `atrim=${trimLeft * 1_000_000}us:${
- trimRightOrAssetDuration * 1_000_000
- }us`,
+ `atrim=${stringifyTrim(trimLeft)}us:${stringifyTrim(
+ trimRightOrAssetDuration,
+ )}us`,
calculateATempo(playbackRate),
],
actualTrimLeft: trimLeft,
@@ -134,8 +152,6 @@ export const stringifyFfmpegFilter = ({
`aformat=sample_fmts=s32:sample_rates=${DEFAULT_SAMPLE_RATE}`,
// The order matters here! For speed and correctness, we first trim the audio
...trimAndTempoFilter,
- // then set the tempo
- // set the volume if needed
// The timings for volume must include whatever is in atrim, unless the volume
// filter gets applied before atrim
volumeFilter.value === '1'