2020 */
2121
2222import { spawn } from "node:child_process" ;
23- import { rmSync } from "node:fs" ;
23+ import { mkdtempSync , renameSync , rmSync } from "node:fs" ;
24+ import { dirname , join } from "node:path" ;
2425import {
2526 extractAudioMetadata ,
2627 formatFfmpegError ,
@@ -39,6 +40,10 @@ import { redactKnownPaths, redactTelemetryString } from "@hyperframes/core";
3940 */
4041const AUDIO_DURATION_TOLERANCE_SECONDS = 0.001 ;
4142
43+ /** Delivery headroom applied after every AAC encode in this stage. */
44+ export const AAC_DELIVERY_TRUE_PEAK_DBFS = - 1 ;
45+ const MAX_TRUE_PEAK_CORRECTION_PASSES = 3 ;
46+
4247export interface ProbeVideoFrameInfo {
4348 /** Number of video frames in the stream. */
4449 frameCount : number ;
@@ -73,6 +78,7 @@ export interface PadTrimAudioInput {
7378 */
7479 probeVideoFrameInfo ?: ( videoPath : string ) => Promise < ProbeVideoFrameInfo > ;
7580 probeAudioInfo ?: ( audioPath : string , signal ?: AbortSignal ) => Promise < AudioProbeInfo > ;
81+ probeAudioTruePeakDbfs ?: ( audioPath : string , signal ?: AbortSignal ) => Promise < number > ;
7682 runFfmpeg ?: ( args : string [ ] ) => Promise < {
7783 success : boolean ;
7884 error ?: string ;
@@ -110,6 +116,31 @@ export interface PadTrimAudioPlan {
110116 cleanupPaths : string [ ] ;
111117}
112118
119+ function buildAacTruePeakCorrectionArgs (
120+ inputPath : string ,
121+ outputPath : string ,
122+ targetDurationSeconds : number ,
123+ attenuationDb : number ,
124+ ) : string [ ] {
125+ return [
126+ "-i" ,
127+ inputPath ,
128+ "-map" ,
129+ "0:a:0" ,
130+ "-vn" ,
131+ "-af" ,
132+ `volume=${ attenuationDb . toFixed ( 3 ) } dB` ,
133+ "-t" ,
134+ formatSeconds ( targetDurationSeconds ) ,
135+ "-c:a" ,
136+ "aac" ,
137+ "-b:a" ,
138+ "192k" ,
139+ "-y" ,
140+ outputPath ,
141+ ] ;
142+ }
143+
113144/**
114145 * Pure helper: decide the pad/trim operation and build the ffmpeg argv
115146 * sequence that materializes it. Exported separately so unit tests can pin
@@ -258,6 +289,11 @@ export async function padOrTrimAudioToVideoFrameCount(
258289 ( ( videoPath : string ) => defaultProbeVideoFrameInfo ( videoPath , input . signal ) ) ;
259290 const probeAudio = input . probeAudioInfo ?? defaultProbeAudioInfo ;
260291 const runner = input . runFfmpeg ?? ( ( args : string [ ] ) => defaultRunFfmpeg ( args , input . signal ) ) ;
292+ // Injected runners usually do not materialize media. Tests that exercise
293+ // peak correction opt in with a matching probe; production always uses the
294+ // real post-codec measurement.
295+ const probeTruePeak =
296+ input . probeAudioTruePeakDbfs ?? ( input . runFfmpeg ? undefined : defaultProbeAudioTruePeakDbfs ) ;
261297
262298 // Probe video and audio in parallel — the two ffprobe invocations are
263299 // independent and account for most of this function's wall-clock time.
@@ -346,6 +382,27 @@ export async function padOrTrimAudioToVideoFrameCount(
346382 } finally {
347383 for ( const path of plan . cleanupPaths ) rmSync ( path , { force : true } ) ;
348384 }
385+
386+ if ( probeTruePeak ) {
387+ const correction = await enforceAacTruePeak ( {
388+ audioPath : input . outputPath ,
389+ targetDurationSeconds,
390+ signal : input . signal ,
391+ probeTruePeak,
392+ runner,
393+ } ) ;
394+ if ( ! correction . success ) {
395+ return {
396+ success : false ,
397+ outputPath : input . outputPath ,
398+ targetDurationSeconds,
399+ sourceDurationSeconds : audioInfo . durationSeconds ,
400+ operation : plan . operation ,
401+ error : correction . error ,
402+ failureReason : correction . failureReason ,
403+ } ;
404+ }
405+ }
349406 return {
350407 success : true ,
351408 outputPath : input . outputPath ,
@@ -355,6 +412,76 @@ export async function padOrTrimAudioToVideoFrameCount(
355412 } ;
356413}
357414
415+ interface EnforceAacTruePeakInput {
416+ audioPath : string ;
417+ targetDurationSeconds : number ;
418+ signal ?: AbortSignal ;
419+ probeTruePeak : ( audioPath : string , signal ?: AbortSignal ) => Promise < number > ;
420+ runner : ( args : string [ ] ) => Promise < {
421+ success : boolean ;
422+ error ?: string ;
423+ failureReason ?: "external_interruption" ;
424+ } > ;
425+ }
426+
427+ async function enforceAacTruePeak (
428+ input : EnforceAacTruePeakInput ,
429+ ) : Promise < { success : boolean ; error ?: string ; failureReason ?: "external_interruption" } > {
430+ let scratchDir : string | undefined ;
431+ try {
432+ scratchDir = mkdtempSync ( join ( dirname ( input . audioPath ) , ".true-peak-" ) ) ;
433+ const correctedPath = join ( scratchDir , "audio.m4a" ) ;
434+ let attenuationDb = 0 ;
435+ let measuredPath = input . audioPath ;
436+ for ( let pass = 0 ; pass <= MAX_TRUE_PEAK_CORRECTION_PASSES ; pass += 1 ) {
437+ const truePeakDbfs = await input . probeTruePeak ( measuredPath , input . signal ) ;
438+ if ( Number . isNaN ( truePeakDbfs ) || truePeakDbfs === Number . POSITIVE_INFINITY ) {
439+ return { success : false , error : "audioPadTrim: FFmpeg reported an invalid true peak" } ;
440+ }
441+ if ( truePeakDbfs <= AAC_DELIVERY_TRUE_PEAK_DBFS ) {
442+ if ( measuredPath === correctedPath ) renameSync ( correctedPath , input . audioPath ) ;
443+ return { success : true } ;
444+ }
445+ if ( pass === MAX_TRUE_PEAK_CORRECTION_PASSES ) break ;
446+
447+ attenuationDb += AAC_DELIVERY_TRUE_PEAK_DBFS - truePeakDbfs ;
448+ const result = await input . runner (
449+ buildAacTruePeakCorrectionArgs (
450+ input . audioPath ,
451+ correctedPath ,
452+ input . targetDurationSeconds ,
453+ attenuationDb ,
454+ ) ,
455+ ) ;
456+ if ( ! result . success ) {
457+ return {
458+ success : false ,
459+ error : sanitizeProbeFailure (
460+ result . error ?? "audioPadTrim: failed to constrain AAC true peak" ,
461+ [ input . audioPath , correctedPath ] ,
462+ ) ,
463+ failureReason : result . failureReason ,
464+ } ;
465+ }
466+ measuredPath = correctedPath ;
467+ }
468+ return {
469+ success : false ,
470+ error : `audioPadTrim: AAC true peak remained above ${ AAC_DELIVERY_TRUE_PEAK_DBFS } dBFS after ${ MAX_TRUE_PEAK_CORRECTION_PASSES } correction passes` ,
471+ } ;
472+ } catch ( err ) {
473+ return {
474+ success : false ,
475+ error : `audioPadTrim: failed to validate AAC true peak: ${ sanitizeProbeFailure (
476+ err ,
477+ scratchDir ? [ input . audioPath , scratchDir ] : [ input . audioPath ] ,
478+ ) } `,
479+ } ;
480+ } finally {
481+ if ( scratchDir ) rmSync ( scratchDir , { recursive : true , force : true } ) ;
482+ }
483+ }
484+
358485function failResult (
359486 outputPath : string ,
360487 target : number ,
@@ -461,6 +588,26 @@ async function defaultProbeAudioInfo(
461588 } ;
462589}
463590
591+ async function defaultProbeAudioTruePeakDbfs (
592+ audioPath : string ,
593+ signal ?: AbortSignal ,
594+ ) : Promise < number > {
595+ const result = await runFfmpeg (
596+ [ "-i" , audioPath , "-map" , "0:a:0" , "-vn" , "-af" , "ebur128=peak=true" , "-f" , "null" , "-" ] ,
597+ { signal } ,
598+ ) ;
599+ if ( ! result . success ) {
600+ throw new Error ( `[audioPadTrim] ${ formatFfmpegError ( result . exitCode , result . stderr ) } ` ) ;
601+ }
602+ const matches = [ ...result . stderr . matchAll ( / ^ \s * P e a k : \s * ( [ + - ] ? (?: [ \d . ] + | i n f ) ) d B F S $ / gim) ] ;
603+ const token = matches . at ( - 1 ) ?. [ 1 ] ?. toLowerCase ( ) ;
604+ const value = token === "-inf" ? Number . NEGATIVE_INFINITY : Number ( token ) ;
605+ if ( Number . isNaN ( value ) || value === Number . POSITIVE_INFINITY ) {
606+ throw new Error ( "[audioPadTrim] FFmpeg did not report AAC true peak" ) ;
607+ }
608+ return value ;
609+ }
610+
464611async function defaultRunFfmpeg (
465612 args : string [ ] ,
466613 signal ?: AbortSignal ,
0 commit comments