|
14 | 14 | * "audio cuts off early" or "video shows a frozen final frame" bugs. |
15 | 15 | * |
16 | 16 | * The fix: post-pad/trim audio to *exactly* `frameCount / fps` seconds at |
17 | | - * assemble time. Pad by concat-copying a generated silence tail, trim with |
18 | | - * `-t`, and avoid re-encoding the already mixed source AAC in either case. |
| 17 | + * assemble time. Pad by concat-copying a generated silence tail. For trim, |
| 18 | + * decode and filter to the exact target before re-encoding into an M4A |
| 19 | + * container; packet-copying AAC can only cut on packet boundaries. |
19 | 20 | */ |
20 | 21 |
|
21 | 22 | import { spawn } from "node:child_process"; |
@@ -121,8 +122,8 @@ export interface PadTrimAudioPlan { |
121 | 122 | * tail, then concat-copy the source AAC plus that tail. This avoids |
122 | 123 | * re-encoding the already mixed `audio.aac`; the pad branch remains the |
123 | 124 | * inverse of trim instead of becoming a second full-source AAC encode. |
124 | | - * - `sourceDuration > targetDuration` → trim with `-t target`. `-c:a copy` |
125 | | - * is preserved when the input is already AAC. |
| 125 | + * - `sourceDuration > targetDuration` → filter to the exact target and |
| 126 | + * re-encode AAC so packet padding cannot outlast the video. |
126 | 127 | * - `|Δ| < AUDIO_DURATION_TOLERANCE_SECONDS` → no-op `copy`, but we still |
127 | 128 | * run ffmpeg with `-c:a copy` to materialize the output path. |
128 | 129 | */ |
@@ -187,13 +188,27 @@ export function buildPadTrimAudioPlan( |
187 | 188 | cleanupPaths: [silencePath, concatListPath], |
188 | 189 | }; |
189 | 190 | } |
190 | | - // Trim. `-t` truncates AAC without re-encoding because AAC frames are |
191 | | - // independently decodable; ffmpeg snaps the cut point to the nearest |
192 | | - // packet boundary, fine for the ±1ms tolerance we care about here. |
| 191 | + // Packet-copy trimming snaps to AAC frame boundaries (typically 1024 |
| 192 | + // samples), which can leave ~20ms beyond the target. Decode/filter/re-encode |
| 193 | + // into M4A so ffmpeg records the exact presentation duration. |
193 | 194 | return { |
194 | 195 | operation: "trim", |
195 | 196 | steps: [ |
196 | | - { kind: "trim", args: ["-i", audioPath, "-t", targetSec, "-c:a", "copy", "-y", outputPath] }, |
| 197 | + { |
| 198 | + kind: "trim", |
| 199 | + args: [ |
| 200 | + "-i", |
| 201 | + audioPath, |
| 202 | + "-af", |
| 203 | + `atrim=duration=${targetSec},asetpts=PTS-STARTPTS`, |
| 204 | + "-c:a", |
| 205 | + "aac", |
| 206 | + "-b:a", |
| 207 | + "192k", |
| 208 | + "-y", |
| 209 | + outputPath, |
| 210 | + ], |
| 211 | + }, |
197 | 212 | ], |
198 | 213 | cleanupPaths: [], |
199 | 214 | }; |
|
0 commit comments