Skip to content

Commit b2583f3

Browse files
Vincent Herbstclaude
andcommitted
fix(audio): count the silent-bridge gate in encoder frames, not source packets (#474)
The AE#396 detector fired during a healthy start-up on every TrueHD session and announced a failure that was not happening: [AudioBridge] ERROR: AE#396 the bridge has produced no encoded audio at all (mode=surroundCompat): fed=64 decoded=64 enqueued=2560 emitted=0. ... this session will fail its first segment cut unless output starts. The threshold was 64 SOURCE PACKETS, but the quantity that bounds the encoder arm is one ENCODER FRAME: drainFIFOIntoEncoder(requireFull:) cannot encode below frame_size, so nothing can be emitted before that many samples have been enqueued. Its derivation named its two constants, an E-AC-3 frame of 1536 and a DTS packet of 512, and the FLAC arm breaks both: a FLAC frame is 4608 samples and a TrueHD access unit is 40, so the first output needs 116 packets. The enqueued=2560 in the reporter's own line is the proof, short of 4608 and short of any output being possible. Not confined to the opt-in .lossless mode either, .surroundCompat encodes two channels or fewer to FLAC. Each arm is now counted in the unit that bounds it: the encoder's own frame_size where PCM reached the FIFO, packets only where the FIFO never moved, and the latter from the LAST accepted sample rather than from the start, so a decoder that answers for a while and then stops is the same shape as one that never answered. Four frames rather than one, because the first is when output becomes possible and the second covers an encoder that holds it. The line arrives sooner than before on the arm it was written for (128 ms of source audio on E-AC-3 against 64 packets) and now names the encoder and the frame boundary it judged. Measured on media, both arms of the same fixture family: a stereo TrueHD MKV on the default mode printed the ERROR at fed=64 before, prints nothing after, and plays 20 s clean in both. The decoder arm is pinned through the real bridge in tests (80 undecodable MP3 packets still report), because no corruption that could be built here makes libavcodec stop producing frames for a whole session. Nothing else read the threshold: both sites that classify a silent bridge are gated on an actual failure (a pump death with muxerFailed, an exhausted revive), so a healthy start-up never reached them, and $audioDelivery is derived independently and read `bridged` correctly throughout. Reported by @cmcpherson274 in #462. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q4QpZDsHPJfbz5gkxxPXF7
1 parent d6f7c7d commit b2583f3

3 files changed

Lines changed: 235 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,25 @@ the public-API contract.
2626

2727
### Fixed
2828

29+
- **The silent-bridge ERROR no longer announces a failure during a healthy start-up (AE#474).**
30+
`AudioBridge`'s AE#396 detector was counted in source packets (64) while the thing that bounds
31+
it is one encoder frame: `drainFIFOIntoEncoder(requireFull:)` cannot encode below `frame_size`,
32+
so no output is POSSIBLE until that many samples have been enqueued. Its threshold was derived
33+
from the lossy pair alone (an E-AC-3 frame of 1536 against a DTS packet of 512), and the FLAC arm
34+
breaks both constants: a FLAC frame is 4608 samples and a TrueHD access unit is 40, so the first
35+
output needs 116 packets and the line fired at 64. Every TrueHD session therefore printed
36+
`the bridge has produced no encoded audio at all ... enqueued=2560 emitted=0` and then played to
37+
the end, and not only under the opt-in `.lossless` mode: `.surroundCompat` encodes any source of
38+
two channels or fewer to FLAC, so a stereo TrueHD file reproduces it on the default setting. The
39+
gate now counts each arm in the unit that bounds it, the encoder's own `frame_size` where PCM
40+
reached the FIFO and packets only where the FIFO never moved, and the latter counts from the last
41+
accepted sample rather than from the start, so a decoder that answers for a while and then stops
42+
is caught by the same arm. The line arrives sooner than it used to on the arm it was written for
43+
(about 128 ms of source audio on E-AC-3 against 64 packets), and it now names the encoder it is
44+
talking about and the frame boundary it judged. Nothing else read the old threshold: both
45+
decision sites that classify a silent bridge are gated on an actual failure, and `$audioDelivery`
46+
is derived independently and read `bridged` correctly throughout. Reported by @cmcpherson274.
47+
2948
- **A decode-path correction reaches a custom `IOReader` session instead of being quietly dropped
3049
(AE#461 follow-up).** `LoadOptions.preferredDecodePath` was read only inside `load`, while the
3150
rebuild that keeps a retained reader picks its host from the backend the session was already on.

‎Sources/AetherEngine/Audio/AudioBridge.swift‎

Lines changed: 61 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,11 @@ final class AudioBridge: @unchecked Sendable {
478478
/// produced nothing.
479479
var framesDroppedBeforeFIFO = 0
480480
var samplesEnqueued: Int64 = 0
481+
/// Source packets fed since the FIFO last accepted a sample, reset by every accepted write.
482+
/// The decoder arm of `silenceIsStructural` is counted on this rather than on `packetsFed`,
483+
/// so a decoder that answers for a while and then stops is the same shape as one that never
484+
/// answered at all, and neither has to be told apart from a bridge that is merely young.
485+
var packetsFedSinceLastEnqueue = 0
481486
var packetsEmitted = 0
482487
/// `avcodec_receive_packet` answers that were neither a packet nor EAGAIN/EOF.
483488
var encodeErrors = 0
@@ -519,13 +524,30 @@ final class AudioBridge: @unchecked Sendable {
519524
var feedStats: FeedStats { stats }
520525

521526
/// One-shot: a bridge that stays silent for an hour costs one line, not one per packet.
522-
private var silentFeedReported = false
527+
private(set) var silentFeedReported = false
523528

524-
/// Enough source that no start-up latency explains the silence. The largest encoder frame the
525-
/// bridge builds is 1536 samples (E-AC-3) and the smallest source packet it is fed is 512 (DTS),
526-
/// so three packets is the honest worst case before the first output and 64 is two orders past it.
529+
/// AE#474: the DECODER arm's unit, and only its unit. Source went in and the FIFO got nothing
530+
/// back, so there is no sample count to bound anything with and packets are all there is.
527531
private static let silentFeedPacketThreshold = 64
528532

533+
/// AE#474: the ENCODER arm's unit. `drainFIFOIntoEncoder(requireFull: true)` cannot encode below
534+
/// `frame_size`, so nothing can be emitted until that many samples have been enqueued, and the
535+
/// figure is not a constant of the bridge: 1536 on E-AC-3, 4608 on FLAC. A source packet is not
536+
/// a constant either, 1536 samples on E-AC-3 down to 40 on a TrueHD access unit, so the ratio
537+
/// between the two spans a factor of 100 across arms this bridge already builds and no packet
538+
/// count can express one encoder frame. The old 64-packet threshold was derived from the lossy
539+
/// pair alone (1536 against 512) and fired at 2560 of FLAC's 4608 samples on TrueHD, announcing
540+
/// a failure on sessions that then played to the end. Four frames rather than one: the first is
541+
/// when output becomes POSSIBLE, the second covers an encoder that holds it, and four is still
542+
/// inside the first half second of source audio on every arm (128 ms on E-AC-3, 384 ms on FLAC
543+
/// at 48 kHz), which is sooner in wall-clock than the packet threshold it replaces.
544+
private static let silentFeedEncoderFrameMultiple: Int64 = 4
545+
546+
/// What to assume for `frame_size` before the encoder has resolved one. Shared with
547+
/// `drainFIFOIntoEncoder`, which chunks the FIFO by the same figure: a gate that used a
548+
/// different fallback than the drain it is judging would be judging a boundary nobody uses.
549+
private static let assumedEncoderFrameSize: Int32 = 4096
550+
529551
/// Snapshot of bytes live in the bridge's growable buffers, for the engine memory probe. Both fields grow on
530552
/// the FFmpeg side (FIFO reallocs upward, swr delay buffer reallocates on rate/layout shift), so a
531553
/// monotonically rising value points here vs the segment muxer or HLS server. Costs: two C calls, no allocations.
@@ -755,6 +777,7 @@ final class AudioBridge: @unchecked Sendable {
755777
}
756778

757779
stats.packetsFed += 1
780+
stats.packetsFedSinceLastEnqueue += 1
758781

759782
var results: [UnsafeMutablePointer<AVPacket>] = []
760783

@@ -839,24 +862,42 @@ final class AudioBridge: @unchecked Sendable {
839862
throw error
840863
}
841864

842-
noteSilentFeedIfNeeded()
865+
noteSilentFeedIfNeeded(encoderFrameSize: enc.pointee.frame_size)
843866
return results
844867
}
845868

846-
/// AE#396: say it once, the moment enough source has gone in for the silence to be structural
847-
/// rather than start-up latency. Without this the only downstream evidence is movenc's -22 on a
848-
/// moov it cannot build, which names the muxer and the source and never the bridge. `EngineLog`
849-
/// has no error level, so the `ERROR:` prefix carries it, as in the #165 cascade line.
850-
private func noteSilentFeedIfNeeded() {
869+
/// AE#396 / AE#474: is this silence structural, or has the bridge simply not been asked yet?
870+
/// The two ways a bridge stays quiet end at different subsystems and are bounded by different
871+
/// quantities, so each arm is counted in the unit that actually bounds it and neither is
872+
/// expressed in the other's (see `silentFeedPacketThreshold` and the frame multiple above).
873+
///
874+
/// Pure and static so the boundary can be pinned against the frame sizes this bridge really
875+
/// opens instead of against whichever one the fixtures happen to reach.
876+
static func silenceIsStructural(stats: FeedStats, encoderFrameSize: Int32) -> Bool {
877+
guard stats.isSilent else { return false }
878+
let frame = Int64(encoderFrameSize > 0 ? encoderFrameSize : assumedEncoderFrameSize)
879+
// The encoder arm: enough PCM to build several frames went in and none came back.
880+
if stats.samplesEnqueued >= frame * silentFeedEncoderFrameMultiple { return true }
881+
// The decoder arm: the FIFO has stood still for longer than any source explains.
882+
return stats.packetsFedSinceLastEnqueue >= silentFeedPacketThreshold
883+
}
884+
885+
/// AE#396: say it once, the moment the silence is structural. Without this the only downstream
886+
/// evidence is movenc's -22 on a moov it cannot build, which names the muxer and the source and
887+
/// never the bridge. `EngineLog` has no error level, so the `ERROR:` prefix carries it, as in
888+
/// the #165 cascade line.
889+
private func noteSilentFeedIfNeeded(encoderFrameSize: Int32) {
851890
guard !silentFeedReported,
852-
stats.isSilent,
853-
stats.packetsFed >= Self.silentFeedPacketThreshold else { return }
891+
Self.silenceIsStructural(stats: stats, encoderFrameSize: encoderFrameSize)
892+
else { return }
854893
silentFeedReported = true
894+
let encoder = avcodec_get_name(outputCodecID).map { String(cString: $0) } ?? "the encoder"
895+
let frame = encoderFrameSize > 0 ? encoderFrameSize : Self.assumedEncoderFrameSize
855896
EngineLog.emit(
856897
"[AudioBridge] ERROR: AE#396 the bridge has produced no encoded audio at all "
857-
+ "(mode=\(mode.rawValue)): \(stats.summary). The mp4 muxer can only build an "
858-
+ "AC-3/E-AC-3 sample entry from a packet that was written, so this session will fail "
859-
+ "its first segment cut unless output starts.",
898+
+ "(mode=\(mode.rawValue), encoder=\(encoder), frame=\(frame)): \(stats.summary). "
899+
+ "The mp4 muxer can only build a \(encoder) sample entry from a packet that was "
900+
+ "written, so this session will fail its first segment cut unless output starts.",
860901
category: .session
861902
)
862903
}
@@ -998,7 +1039,10 @@ final class AudioBridge: @unchecked Sendable {
9981039
av_audio_fifo_write(fifo, rebound, producedSamples)
9991040
}
10001041
}
1001-
if written > 0 { stats.samplesEnqueued += Int64(written) }
1042+
if written > 0 {
1043+
stats.samplesEnqueued += Int64(written)
1044+
stats.packetsFedSinceLastEnqueue = 0
1045+
}
10021046
}
10031047

10041048
/// Pull frame_size chunks from the FIFO and encode each. requireFull true stops below frame_size (streaming);
@@ -1009,7 +1053,7 @@ final class AudioBridge: @unchecked Sendable {
10091053
requireFull: Bool,
10101054
results: inout [UnsafeMutablePointer<AVPacket>]
10111055
) throws {
1012-
let frameSize = enc.pointee.frame_size > 0 ? enc.pointee.frame_size : 4096
1056+
let frameSize = enc.pointee.frame_size > 0 ? enc.pointee.frame_size : Self.assumedEncoderFrameSize
10131057
let nChannels = enc.pointee.ch_layout.nb_channels
10141058

10151059
while true {

‎Tests/AetherEngineTests/Issue396SilentAudioBridgeTests.swift‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,4 +223,159 @@ struct Issue396SilentAudioBridgeTests {
223223
"a bridge that produced audio is not the reason the moov could not be written")
224224
#expect(surfaced.snapshot?.reason == "Source audio cannot be muxed")
225225
}
226+
227+
// MARK: - AE#474: the gate's unit
228+
229+
/// Raw stereo PCM at 48 kHz. `.surroundCompat` encodes 2 channels or fewer to FLAC, so this is
230+
/// the FLAC arm on the DEFAULT mode, and raw PCM lets a packet carry any number of samples.
231+
private func makePCMCodecpar() -> UnsafeMutablePointer<AVCodecParameters> {
232+
let par = avcodec_parameters_alloc()!
233+
par.pointee.codec_type = AVMEDIA_TYPE_AUDIO
234+
par.pointee.codec_id = AV_CODEC_ID_PCM_S16LE
235+
par.pointee.sample_rate = 48_000
236+
par.pointee.format = AV_SAMPLE_FMT_S16.rawValue
237+
par.pointee.bits_per_coded_sample = 16
238+
par.pointee.block_align = 4
239+
av_channel_layout_default(&par.pointee.ch_layout, 2)
240+
return par
241+
}
242+
243+
/// One packet per TrueHD access unit: 40 samples at 48 kHz, the smallest source packet the bridge
244+
/// is fed anywhere. 64 of them are 2560 samples, which is what the reporter's device log carried.
245+
private func makeTrueHDShapedPCMPackets(count: Int, samplesPerPacket: Int = 40)
246+
-> [UnsafeMutablePointer<AVPacket>] {
247+
(0..<count).compactMap { i in
248+
guard let pkt = trackedPacketAlloc() else { return nil }
249+
let bytes = samplesPerPacket * 2 * 2
250+
guard av_new_packet(pkt, Int32(bytes)) >= 0 else { return nil }
251+
for n in 0..<samplesPerPacket {
252+
let global = i * samplesPerPacket + n
253+
let v = Int16(9000 * sin(2 * .pi * 440 * Double(global) / 48_000)).littleEndian
254+
for ch in 0..<2 {
255+
let off = (n * 2 + ch) * 2
256+
withUnsafeBytes(of: v) { raw in
257+
pkt.pointee.data!.advanced(by: off).update(from: raw.baseAddress!
258+
.assumingMemoryBound(to: UInt8.self), count: 2)
259+
}
260+
}
261+
}
262+
pkt.pointee.pts = Int64(i * samplesPerPacket)
263+
pkt.pointee.dts = pkt.pointee.pts
264+
return pkt
265+
}
266+
}
267+
268+
@Test("start-up on the FLAC arm is not silence: 64 small packets are half of one encoder frame")
269+
func flacArmStartUpIsNotReportedAsSilence() throws {
270+
let codecpar = makePCMCodecpar()
271+
defer {
272+
var p: UnsafeMutablePointer<AVCodecParameters>? = codecpar
273+
avcodec_parameters_free(&p)
274+
}
275+
let bridge = try AudioBridge(srcCodecpar: codecpar,
276+
srcTimeBase: AVRational(num: 1, den: 48_000),
277+
mode: .surroundCompat)
278+
defer { bridge.close() }
279+
#expect(bridge.outputCodecID == AV_CODEC_ID_FLAC,
280+
"precondition: the default mode encodes a stereo source to FLAC")
281+
282+
var packets = makeTrueHDShapedPCMPackets(count: 64)
283+
defer { freeAll(&packets) }
284+
var outputs: [UnsafeMutablePointer<AVPacket>] = []
285+
defer { freeAll(&outputs) }
286+
for p in packets { outputs.append(contentsOf: try bridge.feed(packet: p)) }
287+
288+
let stats = bridge.feedStats
289+
#expect(stats.packetsFed == 64)
290+
#expect(stats.samplesEnqueued == 2560, "the reporter's own counters, reproduced")
291+
#expect(stats.packetsEmitted == 0,
292+
"requireFull declines below frame_size, so no output is POSSIBLE yet")
293+
#expect(stats.isSilent, "silent in the counter's sense, which is not the same as structural")
294+
#expect(!bridge.silentFeedReported,
295+
"AE#474: 2560 samples is short of FLAC's 4608, so nothing could have been emitted")
296+
}
297+
298+
@Test("the same feed continued past the encoder's frame produces audio and still reports nothing")
299+
func flacArmProducesOnceTheFrameIsFull() throws {
300+
let codecpar = makePCMCodecpar()
301+
defer {
302+
var p: UnsafeMutablePointer<AVCodecParameters>? = codecpar
303+
avcodec_parameters_free(&p)
304+
}
305+
let bridge = try AudioBridge(srcCodecpar: codecpar,
306+
srcTimeBase: AVRational(num: 1, den: 48_000),
307+
mode: .surroundCompat)
308+
defer { bridge.close() }
309+
310+
var packets = makeTrueHDShapedPCMPackets(count: 400)
311+
defer { freeAll(&packets) }
312+
var outputs: [UnsafeMutablePointer<AVPacket>] = []
313+
defer { freeAll(&outputs) }
314+
for p in packets { outputs.append(contentsOf: try bridge.feed(packet: p)) }
315+
316+
#expect(bridge.feedStats.packetsEmitted > 0)
317+
#expect(!bridge.silentFeedReported,
318+
"a bridge that went on to produce audio must never have announced a failure")
319+
}
320+
321+
@Test("a source the decoder rejects still names itself, from the packet arm")
322+
func decoderArmStillReports() throws {
323+
let codecpar = makeMP3Codecpar()
324+
defer {
325+
var p: UnsafeMutablePointer<AVCodecParameters>? = codecpar
326+
avcodec_parameters_free(&p)
327+
}
328+
let bridge = try AudioBridge(srcCodecpar: codecpar,
329+
srcTimeBase: AVRational(num: 1, den: 1000),
330+
mode: .surroundCompat)
331+
defer { bridge.close() }
332+
333+
var packets = makeUndecodablePackets(count: 80)
334+
defer { freeAll(&packets) }
335+
for p in packets { _ = try? bridge.feed(packet: p) }
336+
337+
#expect(bridge.feedStats.samplesEnqueued == 0)
338+
#expect(bridge.silentFeedReported,
339+
"nothing ever reached the FIFO, which is the arm packets are the only unit for")
340+
}
341+
342+
// MARK: - The gate itself
343+
344+
@Test("the encoder's frame is the bound on the encoder arm, not a packet count")
345+
func structuralSilenceIsBoundedByTheEncoderFrame() {
346+
var startUp = AudioBridge.FeedStats()
347+
startUp.packetsFed = 64
348+
startUp.framesDecoded = 64
349+
startUp.samplesEnqueued = 2560
350+
startUp.packetsFedSinceLastEnqueue = 0
351+
#expect(!AudioBridge.silenceIsStructural(stats: startUp, encoderFrameSize: 4608),
352+
"AE#474: below one FLAC frame the encoder has not been asked yet")
353+
#expect(AudioBridge.silenceIsStructural(stats: startUp, encoderFrameSize: 512),
354+
"the same counters ARE structural against an encoder whose frame they cleared")
355+
356+
var fed = startUp
357+
fed.samplesEnqueued = 4608 * 4
358+
#expect(AudioBridge.silenceIsStructural(stats: fed, encoderFrameSize: 4608))
359+
360+
var healthy = fed
361+
healthy.packetsEmitted = 1
362+
#expect(!AudioBridge.silenceIsStructural(stats: healthy, encoderFrameSize: 4608),
363+
"a bridge that emitted anything is never silent")
364+
}
365+
366+
@Test("a decoder that stops answering is caught by the packet arm, from where it stopped")
367+
func decoderThatStopsAnsweringIsStillCaught() {
368+
var trickle = AudioBridge.FeedStats()
369+
trickle.packetsFed = 900
370+
trickle.framesDecoded = 3
371+
trickle.samplesEnqueued = 120
372+
trickle.packetsFedSinceLastEnqueue = 897
373+
#expect(AudioBridge.silenceIsStructural(stats: trickle, encoderFrameSize: 4608),
374+
"120 samples will never reach a FLAC frame, and the FIFO stopped moving 897 packets ago")
375+
376+
var stillFilling = trickle
377+
stillFilling.packetsFedSinceLastEnqueue = 1
378+
#expect(!AudioBridge.silenceIsStructural(stats: stillFilling, encoderFrameSize: 4608),
379+
"a FIFO that is still accepting samples is a bridge that has not been asked yet")
380+
}
226381
}

0 commit comments

Comments
 (0)