Skip to content

Feature request: opt-in decoded PCM audio tap for host-side speech/audio features #95

Closed

Description

@dlev02

Title: Feature request: opt-in decoded PCM audio tap for host-side speech/audio features

What

An opt-in way for a host to observe the decoded playback audio as PCM
(AVAudioPCMBuffer + source-PTS timestamps, post-track-selection, pre-output),
published off the render path similar to how subtitleCues work.

Why

Looking to add two specific features:

  • AI subtitles: live on-device transcription of the active audio track
    (SpeechAnalyzer/SpeechTranscriber on OS 26), with optional translation —
    great for content with no subtitle tracks.
  • Soundtrack recognition: user-initiated "what song is this?" via
    ShazamKit's SHSignatureGenerator from playback audio.

With AetherEngine there is currently no host-side path to playback PCM:

Sketch

The CEA-608 ClosedCaptionTap (#77) feels like the precedent: a read-only
observer riding the producer's existing source connection. An audio version
would need a decode stage on the native path (libavcodec is already linked),
ideally:

  • Opt-in per load (nothing decoded when no consumer), e.g.
    engine.installAudioTap(handler:) / removeAudioTap(), or an
    AsyncStream<(AVAudioPCMBuffer, sourceTime: Double)>.
  • Follows the active audio track selection.
  • Downmix to mono/stereo float PCM would be fine for both use cases (speech
    and Shazam signatures don't need surround); a fixed, documented output
    format keeps it cheap.
  • Timestamps on the same source axis as clock.sourceTime so cues line up.
  • Best-effort/lossy under pressure is fine — recognition consumers tolerate
    gaps; it should never be allowed to stall playback.

FrameExtractor's "fully isolated from playback" design would also work
(an AudioExtractor decoding a time range out-of-band), and would even let a
host transcribe ahead of the playhead, but a live tap on the producer's
connection avoids a second network stream for remote sources.

Happy to test builds against real content on iPhone/Apple TV and report back.

Activity

  1. superuser404notfound commented on Jul 3, 2026

    @superuser404notfound
    Owner

    Implemented on main (5f8ce9b), ready for you to test.

    API (as sketched in your request, with an AsyncStream shape):

    let stream = engine.installAudioTap()   // AsyncStream<AudioTapBuffer>
    for await buf in stream {
        // buf.buffer: AVAudioPCMBuffer, mono Float32 48 kHz (AetherEngine.audioTapFormat)
        // buf.sourceTime: source-PTS seconds, same axis as engine.sourceTime / subtitleCues
        // buf.discontinuity: true after any gap (seek, track switch, drops under pressure)
    }
    engine.removeAudioTap()                 // or let load()/stop() finish it

    One tap per engine, opt-in per load, nothing is decoded when no consumer is installed. Delivery is lossy under pressure (bufferingNewest(64)) and can never stall playback.

    One deviation from your sketch, deliberately: the tap does not ride the producer's source connection. The producer runs 30-60 s ahead of the playhead, parks when the forward buffer is full, and has already reached EOF on fully cached VOD, so a tap installed mid-session (user enables AI subtitles at minute 50, or presses "what song is this?") would see future audio or nothing at all. Instead the tap reads the engine's own muxed fMP4 segments from the segment cache near the playhead and decodes their audio track out-of-band. That gives playhead-aligned PCM, mid-session install, zero extra network (everything is local), and it follows the active audio track for free since the mux contains exactly the selected track, post-bridge. On the software path (AV1/VP9) the existing PCM decode is mirrored through an AVAudioConverter into the same stream, so the API behaves identically on both backends. EAC3+JOC decodes as the EAC3 core, which is what speech and Shazam want anyway. Live sources work through the same mechanism but are declared best-effort for now.

    Verified with the new aetherctl audiotap command (writes the tap to a WAV and prints continuity stats) across AAC stream-copy, EAC3 stream-copy, and the FLAC-bridge path; unit tests cover pacing, PTS mapping, and discontinuity marking.

    Pin main and it is all there. Happy to hear how SpeechAnalyzer and SHSignatureGenerator behave against real content on your devices, especially mid-session installs and seeks during an active tap.

  2. added a commit that references this issue on Jul 5, 2026
  3. dlev02 commented on Jul 6, 2026

    @dlev02
    ContributorAuthor

    Shipping this now — AI subtitles (SpeechAnalyzer/SpeechTranscriber) and soundtrack recognition (ShazamKit) are both live on the #95 tap on iOS/macOS. Two pieces of field feedback from real content: one minor heads-up, one that's an actual gap.

    1. SpeechAnalyzer needs a strictly monotonic, non-overlapping input timeline — the tap can emit overlapping PTS (handled host-side, flagging for you)

    On a native-loopback HEVC + E-AC3 stream (audio tap installed … live=true), the analyzer kept failing with:

    SpeechAnalyzer: Input loop ending with error:
      SFSpeechErrorDomain Code=17 "Audio input timestamp overlaps or precedes prior audio input"
    

    Consecutive AudioTapBuffers occasionally overlap on sourceTime — at segment boundaries (E-AC3 decoder priming) and right after a reanchor, a buffer starts slightly before the previous one's end. SpeechAnalyzer.start(inputSequence:) terminates its input loop on the first overlap, so before I caught it the analyzer was dying and getting rebuilt ~20×/min → zero transcription (just a flashing "Preparing…").

    Fixed entirely on my side by gating buffers to a monotonic, non-overlapping timeline (feed forward / drop sub-threshold overlaps / restart only on a real backward seek), so no change required from you. Flagging it because (a) any SpeechAnalyzer consumer will hit it, so it may be worth a doc note next to discontinuity, and (b) if it's cheap, having the tap coalesce/trim sub-discontinuity PTS overlaps at segment seams would make it plug-and-play. Totally optional — this is exactly the "seeks during an active tap" case you flagged.

    2. The tap has no delivery source on the loadRemoteHLS (AVPlayer-direct) path — this blocks AI subtitles/soundtrack on remote & live HLS

    installAudioTap() → makeNativeTapReader requires nativeVideoSession + session.cache + session.provider + audioPipelineDescription. The loopback native path (loadNative, with the segment producer/cache) and the software path both provide that, and the tap works great there. But loadRemoteHLS sets playbackBackend = .native and plays through a bare NativeAVPlayerHost with no loopback producer / segment cache ("none of which exists on this bypass"), so makeNativeTapReader returns nil and the stream finishes immediately (live=false).

    That's the same AVPlayer / MTAudioProcessingTap limitation from the original request — solved for the loopback path by reading the mux, but the remote-HLS bypass has no mux to read. Net effect: AI subtitles and "what song is this?" silently can't work on remote/live HLS (Jellyfin HLS transcode, live streams).

    Whichever is feasible:

    • a side-decode/loopback tap for the loadRemoteHLS path (or route those sources through the loopback producer when a tap is installed), or
    • at minimum, a host-visible signal that the tap has no delivery source (expose hasDeliverySource, or a terminal reason on the finished stream) so the host can fail loudly ("not available for this stream") instead of hanging.

    Honesty note: I've runtime-confirmed the tap works on the native-loopback path; the loadRemoteHLS gap is from reading the loading code (my test stream happened to be a direct file), so I haven't captured a live=false trace on a remote-HLS source yet — but the code path is unambiguous. Happy to grab that trace if it helps.

    No rush on either — I've shipped a host-side workaround for #1 and a "not available for this stream" fallback for #2. Thanks again for the tap; it's exactly what these features needed.

  4. superuser404notfound commented on Jul 6, 2026

    @superuser404notfound
    Owner

    Both items are handled on main (bfef533).

    1. Overlapping PTS at segment seams. The tap now guarantees a strictly monotonic, non-overlapping timeline for consecutive non-discontinuity buffers, so SpeechAnalyzer is plug-and-play with no host-side gating. A shared AudioTapMonotonicFilter (all backends) trims sub-threshold seam overlaps (E-AC3 priming) and restamps to the previous buffer's end; a larger unflagged backward jump is passed through as a discontinuity instead. discontinuity is documented with this invariant.

    2. No delivery source on the loadRemoteHLS path. There is now an out-of-band AudioTapHLSReader for that path: it reads the same remote HLS source independently of AVPlayer, follows the playhead (VOD by cumulative-EXTINF index, live by playlist tracking near the edge), decodes the audio out of band, and feeds the same tap stream. It prefers a separate audio rendition, else the lowest variant, to cap extra bandwidth. TS and fMP4 both work. Live remains best-effort.

    Also added audioTapHasDeliverySource (read it right after installAudioTap()) so a stream with no source is observable instead of just finishing empty.

    Verified end to end against a public HLS VOD (monotonic timeline, single startup discontinuity). Would be glad to hear how SpeechAnalyzer and SHSignatureGenerator behave on real remote/live HLS on your devices, especially mid-session install and seeks during an active tap.

  5. dlev02 commented on Jul 7, 2026

    @dlev02
    ContributorAuthor

    That was fast — thank you! Pinned main (7ea6d3e) and adopted all three pieces today:

    • Monotonic filter: confirmed via the doc note + AudioTapMonotonicFilter; I'm keeping my host-side gate as a belt-and-braces layer (it's inert when your filter holds the invariant), but SpeechAnalyzer consumers being plug-and-play out of the box is the right call.
    • audioTapHasDeliverySource: reading it right after installAudioTap() and now failing loudly immediately ("AI Subtitles aren't available for this stream" / same for song recognition) instead of waiting out an 8-second silence watchdog. The watchdog stays as a fallback. Exactly the signal I asked for.
    • Remote-HLS reader: builds and passes my suite against the new pin. I don't have a Jellyfin transcode session in front of me right now, but I'll report back with real-device SpeechAnalyzer/ShazamKit results on remote HLS (including mid-session install + seeks) once I've put it through its paces.

    The audio-rendition-first/lowest-variant bandwidth cap is a nice touch. As far as I'm concerned both items from my last comment are fully resolved — closing the loop here, and thanks again for turning this around so quickly.

  6. superuser404notfound commented on Jul 7, 2026

    @superuser404notfound
    Owner

    Glad it slotted in cleanly, and thanks for the detailed adoption notes.

    Keeping the host-side gate as an inert belt-and-braces layer is the right instinct: it costs nothing while the engine holds the monotonic invariant, and it is exactly the safety net you want if some future backend ever emits an unflagged overlap.

    Closing this as resolved, since all three pieces are shipped and adopted. If the real-device remote/live HLS pass turns up anything (SpeechAnalyzer or SHSignatureGenerator on a Jellyfin transcode or the live edge, mid-session install, or seeks during an active tap), reopen here or drop a trace and I will jump on it. Thanks again for the thorough back and forth and for driving these features onto the tap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions