mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-24 23:25:19 +00:00
* 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>
101 lines
3.6 KiB
Swift
101 lines
3.6 KiB
Swift
//
|
|
// PTTAudioTests.swift
|
|
// bitchatTests
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import Testing
|
|
import AVFoundation
|
|
import Foundation
|
|
@testable import bitchat
|
|
|
|
struct PTTAudioTests {
|
|
// MARK: - ADTS framing
|
|
|
|
@Test func adtsHeaderEncodesFrameLengthAndFormat() {
|
|
let payload = Data(repeating: 0xAB, count: 100)
|
|
let framed = ADTSFramer.frame(payload)
|
|
#expect(framed.count == 107)
|
|
|
|
// Syncword + MPEG-4 + layer 00 + no CRC.
|
|
#expect(framed[0] == 0xFF)
|
|
#expect(framed[1] == 0xF1)
|
|
// AAC-LC (01), sampling index 8 (16 kHz), channel config 1.
|
|
#expect(framed[2] == 0x60)
|
|
#expect(framed[3] == 0x40 | UInt8((107 >> 11) & 0x3))
|
|
#expect(framed[4] == UInt8((107 >> 3) & 0xFF))
|
|
#expect(framed[5] == UInt8((107 & 0x7) << 5) | 0x1F)
|
|
#expect(framed[6] == 0xFC)
|
|
#expect(Data(framed.dropFirst(7)) == payload)
|
|
}
|
|
|
|
@Test func adtsStreamIsReadableByCoreAudio() throws {
|
|
// A receiver persists bursts as ADTS .aac; the file must be openable
|
|
// by the same machinery the voice-note UI uses (AVAudioFile).
|
|
let frames = try encodeSineFrames(seconds: 0.5)
|
|
#expect(frames.count >= 4)
|
|
|
|
let url = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("ptt-test-\(UUID().uuidString).aac")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
var stream = Data()
|
|
for frame in frames {
|
|
stream.append(ADTSFramer.frame(frame))
|
|
}
|
|
try stream.write(to: url)
|
|
|
|
let file = try AVAudioFile(forReading: url)
|
|
#expect(file.length > 0)
|
|
}
|
|
|
|
// MARK: - Codec round trip
|
|
|
|
@Test func encoderProducesRealtimeSizedFrames() throws {
|
|
let frames = try encodeSineFrames(seconds: 1.0)
|
|
// 1 s of 64 ms frames ≈ 15 (allow encoder priming slack).
|
|
#expect(frames.count >= 10)
|
|
// ~16 kbps -> ~130 bytes/frame; all frames must fit the wire budget.
|
|
for frame in frames {
|
|
#expect(frame.count > 0)
|
|
#expect(frame.count < TransportConfig.pttMaxBurstContentBytes)
|
|
}
|
|
}
|
|
|
|
@Test func decoderRoundTripsEncodedAudio() throws {
|
|
let frames = try encodeSineFrames(seconds: 0.5)
|
|
let decoder = try #require(PTTFrameDecoder())
|
|
|
|
var decodedSamples = 0
|
|
var energy: Float = 0
|
|
for frame in frames {
|
|
guard let pcm = decoder.decode(frame) else { continue } // priming
|
|
decodedSamples += Int(pcm.frameLength)
|
|
if let channel = pcm.floatChannelData?[0] {
|
|
for i in 0..<Int(pcm.frameLength) {
|
|
energy += abs(channel[i])
|
|
}
|
|
}
|
|
}
|
|
// Most of the audio must decode, and it must not be silence.
|
|
#expect(decodedSamples >= 4 * Int(PTTAudioFormat.samplesPerFrame))
|
|
#expect(energy > 1)
|
|
}
|
|
|
|
// MARK: - Helpers
|
|
|
|
private func encodeSineFrames(seconds: Double) throws -> [Data] {
|
|
let encoder = try #require(PTTFrameEncoder())
|
|
let format = try #require(PTTAudioFormat.pcmFormat)
|
|
let totalFrames = AVAudioFrameCount(seconds * PTTAudioFormat.sampleRate)
|
|
let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: totalFrames))
|
|
buffer.frameLength = totalFrames
|
|
let channel = try #require(buffer.floatChannelData?[0])
|
|
for i in 0..<Int(totalFrames) {
|
|
channel[i] = sinf(2 * .pi * 440 * Float(i) / Float(PTTAudioFormat.sampleRate)) * 0.5
|
|
}
|
|
return encoder.encode(buffer)
|
|
}
|
|
}
|