Repository navigation
Description
Symptom. Continuous crackle/distortion on the native software-decode path (dispatch → software, SoftwarePlaybackHost + AudioDecoder + AVSampleBufferAudioRenderer) for a source that is an MPEG-2 video (so it takes the software path, not loopback-HLS/AVPlayer) carrying a 44.1 kHz AC-3 stereo track in an MKV (1 ms container timebase). Video is perfect. The same content at 48 kHz AC-3 is clean. The bitstream itself is valid and decodes cleanly through AudioToolbox and ffmpeg, so it is not the data or the decode — it is the buffer timing.
Root cause. AudioDecoder.emitPending() stamps each CMSampleBuffer's presentationTimeStamp with the frame's container PTS, quantized to the container timebase (1 ms). The buffer duration is correctly per-sample (1/sampleRate), so the buffer's true length is nb_samples/sampleRate. When that length is not an integer number of container ticks, consecutive buffers no longer abut:
- AC-3 frame = 1536 samples. At 48 kHz = 32.000 ms (integer ms, buffers abut, clean).
- At 44.1 kHz = 34.829 ms → container PTS step in integer ms (34, 35, 35, 36 …), so every boundary is off by -0.83 / +0.17 / +1.17 ms, and
AVSampleBufferAudioRendererreconciles a discontinuity at every frame (~29 Hz) → a continuous crackle.
Measured boundary deltas on a real 44.1 kHz file (gap = pts[n] - (pts[n-1] + 1536/44100)): -0.83, +0.17, +0.17, +0.17, -0.83 … ms — a click at every AC-3 frame. The same rounding is silent for 48 kHz AC-3 but bites any rate whose frame duration is not integer-ms; 48 kHz AAC/FLAC (1024/4096-sample frames = 21.33/85.33 ms) are affected on this path too.
Fix. Derive each buffer's PTS from a running sample count anchored to the first frame so buffers abut to the sample. Reset on flush(); re-anchor on a real >100 ms PTS discontinuity (seek/edit). Confirmed on-device: 44.1 kHz AC-3 in an MPEG-2 MKV — crackle gone, audio clean and in sync after seeking; 48 kHz unaffected.
Patch:
diff --git a/Sources/AetherEngine/Audio/AudioDecoder.swift b/Sources/AetherEngine/Audio/AudioDecoder.swift
index 3f0f63d..bacf1f9 100644
--- a/Sources/AetherEngine/Audio/AudioDecoder.swift
+++ b/Sources/AetherEngine/Audio/AudioDecoder.swift
@@ -33,6 +33,20 @@ final class AudioDecoder: @unchecked Sendable {
private var pendingStartPTS: CMTime = .invalid
private var pendingSampleCount: Int = 0
+ /// Sample-clock anchor for gapless output. Container per-packet PTS are quantized
+ /// to the container timebase (1 ms for MKV). When the decoded frame duration is
+ /// not an integer number of those ticks — e.g. a 1536-sample AC-3 frame at
+ /// 44.1 kHz is 34.83 ms, not an integer ms — stamping every CMSampleBuffer with
+ /// its own quantized PTS leaves a ±0.5 ms gap/overlap between consecutive buffers,
+ /// and AVSampleBufferAudioRenderer reconciles a discontinuity at each boundary
+ /// (~29 audible clicks/sec — a continuous crackle). 48 kHz (1536 samples =
+ /// exactly 32 ms) is integer-ms so it never showed. Anchor to the first frame's
+ /// PTS, then advance by emitted sample count so consecutive buffers abut to the
+ /// sample. Reset on flush; re-anchored on a real source PTS discontinuity
+ /// (seek/edit) so genuine gaps aren't papered over.
+ private var clockAnchorPTS: CMTime = .invalid
+ private var emittedSamplesSinceAnchor: Int64 = 0
+
#if DEBUG
private var _loggedZeroConvert = false
#endif
@@ -170,6 +184,9 @@ final class AudioDecoder: @unchecked Sendable {
avcodec_flush_buffers(ctx)
// Drop the coalesced samples; after a seek they'd be at the wrong PTS anyway.
resetPending()
+ // Re-anchor the sample clock to the post-seek PTS on the next emitted buffer.
+ clockAnchorPTS = .invalid
+ emittedSamplesSinceAnchor = 0
#if DEBUG
_loggedZeroConvert = false
#endif
@@ -356,12 +373,34 @@ final class AudioDecoder: @unchecked Sendable {
return nil
}
+ // Sample-accurate, gapless PTS (see clockAnchorPTS): derive this buffer's
+ // start from the running sample count so consecutive buffers abut exactly,
+ // instead of from each buffer's container PTS (quantized to the container's
+ // ms tick → ±0.5 ms gaps/overlaps and per-frame clicks for non-integer-ms
+ // frame durations such as 1536-sample AC-3 @ 44.1 kHz).
+ let totalSamples64 = Int64(totalSamples)
+ let outPTS: CMTime
+ let willReanchor: Bool
+ if clockAnchorPTS.isValid, startPTS.isValid {
+ let predicted = CMTimeAdd(
+ clockAnchorPTS,
+ CMTime(value: emittedSamplesSinceAnchor, timescale: sampleRate)
+ )
+ if abs(CMTimeGetSeconds(CMTimeSubtract(startPTS, predicted))) > 0.10 {
+ outPTS = startPTS; willReanchor = true // real discontinuity (seek/edit)
+ } else {
+ outPTS = predicted; willReanchor = false
+ }
+ } else {
+ outPTS = startPTS; willReanchor = true // first buffer after open/flush
+ }
+
// Single timing entry: CoreMedia treats `duration` as per-SAMPLE, so LPCM must be 1/sampleRate. Stamping
// the buffer total made GetDuration report totalSamples^2/sampleRate (~22s for 1024 samples), wedging
// AudioPlaybackHost's buffer-ahead gate after one packet.
var timing = CMSampleTimingInfo(
duration: CMTime(value: 1, timescale: sampleRate),
- presentationTimeStamp: startPTS,
+ presentationTimeStamp: outPTS,
decodeTimeStamp: .invalid
)
@@ -382,6 +421,12 @@ final class AudioDecoder: @unchecked Sendable {
)
resetPending()
guard status == noErr, let sample = sampleBuffer else { return nil }
+ if willReanchor {
+ clockAnchorPTS = outPTS
+ emittedSamplesSinceAnchor = totalSamples64
+ } else {
+ emittedSamplesSinceAnchor += totalSamples64
+ }
return sample
}
Activity
superuser404notfound commentedon Jun 30, 2026
Fixed on
main(55bb619).Shipped the diagnosed fix, with the gapless-clock logic extracted into a small pure value type rather than inlined into
emitPending(), so it carries unit tests.AudioClockAnchormirrors the existingOutputTimestampSanitizershape: a focusedmutating structthat's driven directly in tests, no FFmpeg fixture needed.Behaviour is exactly as described:
CMSampleBufferis stamped from a running sample count anchored to the first frame, so consecutive buffers abut to the sample instead of inheriting the container-quantized PTS.flush()drops the anchor.resolveis pure,commitruns afterCMSampleBufferCreatesucceeds), so a dropped buffer never injects phantom samples into the running count.Test coverage (7 cases, all green; full suite XCTest 208 / Swift Testing 265, no regressions):
testConsecutiveBuffersAbutToTheSample_441kHzAC3reproduces the crackle: it asserts every boundary delta equals the true 34.83 ms frame length, which the old container-quantized path fails at (it steps 34/35/35/36 ms).testSmallContainerJitterIsAbsorbed(sub-threshold rounding stays gapless),testRealDiscontinuityReanchors(60 s seek honoured),testResetReanchorsNextBuffer(flush),test48kHzAC3StaysGapless(the previously-clean case stays clean),testDroppedBufferDoesNotAdvanceClock.Files:
Sources/AetherEngine/Audio/AudioClockAnchor.swift,AudioDecoder.swift,Tests/AetherEngineTests/AudioClockAnchorTests.swift,docs/architecture.md. Sodalite pin bumped to 55bb619.Thanks for the precise root-cause writeup and the measured boundary deltas, that made this a direct fix.
chore(release): prep 4.8.0 - #87/#89/#90/#91/#92 fixes, unified playb…
fix(audio): stamp SW-decode buffers from a gapless sample clock (supe…
superuser404notfound commentedon Jul 23, 2026
Fixed on main in 55bb619. The sample-clock anchored output removes the container-timebase quantization gaps, and the reported 44.1 kHz AC-3 case was already confirmed clean on device. Closing as completed.
fix(audio): decoded audio placed by its own source time; the sample c…
fix(audio): decoded audio placed by its own source time; the sample c…
fix(audio): the FFmpeg bridge and the software decoder place audio on…