Live push-to-talk voice for DMs (streams while you talk, voice note as fallback) (#1403)

* Live push-to-talk voice for DMs: stream while you talk, voice note as fallback

Holding the mic in a DM now streams AAC frames live over the Noise session
(walkie-talkie style, ~0.5s mouth-to-ear at one hop) while recording the same
audio as a normal voice note. On release the note ships through the existing
fileTransfer pipeline; receivers that heard the live stream absorb it silently
into the same bubble (matched by the burst ID embedded in the file name), so
reliability comes for free and nobody sees duplicates.

Protocol:
- NoisePayloadType.voiceFrame = 0x08 carrying VoiceBurstPacket
  (burstID + seq + START/data/END/CANCELED, length-prefixed AAC frames)
- 210-byte burst-content budget keeps each Noise packet inside the 256-byte
  padding bucket: one BLE frame, never the fragment scheduler
- fire-and-forget: frames are dropped (never queued) without an established
  session; live is only offered when the peer is mesh-reachable

Receive:
- ChatLiveVoiceCoordinator assembles bursts (jitter-ordered, 0.5s gap skip,
  3s idle end, flood/size caps), persists progressively as ADTS .aac so even
  a partial burst is a replayable bubble
- live autoplay only when the conversation is on screen, app active, and the
  new app-info "live voice messages" toggle is on (also gates live sending)
- one-playback-at-a-time via a shared ExclusivePlayback slot

Capture:
- PTTCaptureEngine taps AVAudioEngine, dual-encodes: live AAC frames + the
  finalized .m4a (same 16kHz/mono/16kbps settings as VoiceRecorder)
- VoiceRecordingViewModel now drives a pluggable VoiceCaptureSession; the
  composer HUD shows a pulsing LIVE treatment when streaming

Includes the push-to-talk design doc, 6 new localization keys across all 29
locales, and unit tests for framing, packetizer budget, ADTS output, codec
round-trip, and the assembly/absorb lifecycle. Public-mesh PTT (MessageType
0x29) lands separately on top of this.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* PTT follow-ups from review + field test: peer-ID normalization, toggle gates inbound, drop-path diagnostics

Codex review fixes (#1403):
- makeVoiceCaptureSession normalizes the selected peer with toShort() before
  the reachability/session checks and binds the send target to that same
  routing ID — a conversation selected under the stable 64-hex Noise key no
  longer silently falls back to a classic note while the short-ID session is
  established
- the live-voice toggle now gates inbound bursts too: off means
  classic-notes-only in both directions (no live bubble, partial file, or
  early notification; the finalized note still arrives), with a test

Field-test diagnostics (first device run: DM frames decrypted but no bubble
appeared, with no log evidence of which guard dropped them):
- coordinator logs undecodable frames (size + hex prefix) and blocked drops
- makeAssembly logs directory/file-handle failures instead of returning nil
  silently
- PTTLiveVoiceSession logs capture start and finish (packet/frame/duration
  counts); PTTCaptureEngine logs engine start success/failure with the input
  format; BLEService.sendVoiceFrame logs no-session drops

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix iPhone live-capture failure: dead input unit (AURemoteIO -10851, 0 Hz)

Field testing showed the phone's live capture failing at mic enable with
AURemoteIO -10851 and an input format of 0 Hz / 2 ch — an input unit bound
to an earlier (playback-only or settling) audio session. The Mac, which has
no session lifecycle, captured fine, which is why public bursts from the Mac
worked while phone-side sends degraded from working (first hold) to sporadic
to dead across holds.

Three layers of defense:
- PTTCaptureEngine recreates its AVAudioEngine on every start(), after the
  session is configured, so the input unit binds to the session that is
  active now; a dead input (0 Hz or 0 channels) is now a distinct, logged
  error instead of a silent setup failure
- PTTLiveVoiceSession retries the capture start once after a 150 ms
  route-settle pause
- VoiceRecordingViewModel falls back to the classic VoiceRecorder within the
  same hold if the live engine still cannot start — a route glitch now costs
  the live stream, never the voice note

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
jack
2026-07-08 09:20:58 +02:00
committed by GitHub
co-authored by jack Claude Fable 5
parent 6886035632
commit eacd8f0750
31 changed files with 3488 additions and 29 deletions
@@ -55,6 +55,14 @@ final class VoiceRecordingViewModel: ObservableObject {
}
@Published private(set) var state = State.idle
/// True while the active session streams audio live (push-to-talk); the
/// composer switches its recording HUD to the LIVE treatment.
@Published private(set) var isLiveStreaming = false
/// Supplies the capture backend per press. `ChatViewModel` swaps in a
/// live push-to-talk session when the current DM peer can hear it now.
var sessionProvider: () -> VoiceCaptureSession = { VoiceNoteCaptureSession() }
private var activeSession: VoiceCaptureSession?
func formattedDuration(for date: Date) -> String {
let clamped = max(0, state.duration(for: date))
@@ -67,26 +75,54 @@ final class VoiceRecordingViewModel: ObservableObject {
func start(shouldShow: Bool) {
guard shouldShow, state == .idle else { return }
let session = sessionProvider()
activeSession = session
state = .requestingPermission
Task {
let granted = await VoiceRecorder.shared.requestPermission()
guard state == .requestingPermission else { return }
let granted = await session.requestPermission()
guard state == .requestingPermission, activeSession === session else { return }
guard granted else {
state = .permissionDenied
activeSession = nil
return
}
state = .preparing
do {
try await VoiceRecorder.shared.startRecording()
guard state == .preparing else {
cancel()
try await session.start()
guard state == .preparing, activeSession === session else {
await session.cancel()
return
}
state = .recording(startDate: Date())
isLiveStreaming = session.isLive
} catch {
SecureLogger.error("Voice recording failed to start: \(error)", category: .session)
await VoiceRecorder.shared.cancelRecording()
guard state == .preparing else { return }
await session.cancel()
guard state == .preparing, activeSession === session else { return }
// The live engine and the classic recorder are separate
// capture stacks: when the live one hits an audio-route
// glitch, fall back within the same hold so the user still
// gets a voice note instead of an error.
if session.isLive {
let fallback = VoiceNoteCaptureSession()
activeSession = fallback
do {
try await fallback.start()
guard state == .preparing, activeSession === fallback else {
await fallback.cancel()
return
}
SecureLogger.warning("PTT: live capture failed — fell back to classic voice note", category: .session)
state = .recording(startDate: Date())
isLiveStreaming = false
return
} catch {
SecureLogger.error("Voice recording fallback failed to start: \(error)", category: .session)
await fallback.cancel()
guard state == .preparing else { return }
}
}
activeSession = nil
state = .error(message: "Could not start recording.")
}
}
@@ -103,15 +139,18 @@ final class VoiceRecordingViewModel: ObservableObject {
}
state = .idle
isLiveStreaming = false
let session = activeSession
activeSession = nil
guard case .recording(let startDate) = previousState, let completion else {
Task { await VoiceRecorder.shared.cancelRecording() }
guard case .recording(let startDate) = previousState, let completion, let session else {
Task { await session?.cancel() }
return
}
Task {
let finalDuration = Date().timeIntervalSince(startDate)
if let url = await VoiceRecorder.shared.stopRecording(),
if let url = await session.finish(),
isValidRecording(at: url, duration: finalDuration) {
completion(url)
} else {