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
@@ -0,0 +1,241 @@
//
// ChatLiveVoiceCoordinatorTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Testing
import Foundation
import BitFoundation
@testable import bitchat
@MainActor
private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
var nickname = "me"
var selectedPrivateChatPeer: PeerID?
var blockedPeers: Set<PeerID> = []
private(set) var handledPrivateMessages: [BitchatMessage] = []
private(set) var upsertedMessages: [(message: BitchatMessage, peerID: PeerID)] = []
private(set) var removedMessageIDs: [String] = []
func isPeerBlocked(_ peerID: PeerID) -> Bool { blockedPeers.contains(peerID) }
func resolveNickname(for peerID: PeerID) -> String { "alice" }
func handlePrivateMessage(_ message: BitchatMessage) { handledPrivateMessages.append(message) }
func upsertPrivateMessage(_ message: BitchatMessage, in peerID: PeerID) {
upsertedMessages.append((message, peerID))
}
@discardableResult
func removePrivateMessage(withID messageID: String) -> BitchatMessage? {
removedMessageIDs.append(messageID)
return nil
}
func notifyUIChanged() {}
}
@MainActor
struct ChatLiveVoiceCoordinatorTests {
private let peer = PeerID(str: "aaaabbbbcccc0001")
private func makeBurstID(_ fill: UInt8) -> Data {
Data(repeating: fill, count: VoiceBurstPacket.burstIDSize)
}
private func send(_ packet: VoiceBurstPacket, to coordinator: ChatLiveVoiceCoordinator, from peerID: PeerID) {
coordinator.handleVoiceFramePayload(from: peerID, payload: packet.encode(), timestamp: Date())
}
private func incomingFileURL(burstID: Data) -> URL? {
guard let base = try? FileManager.default.url(
for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false
) else { return nil }
return base
.appendingPathComponent("files/voicenotes/incoming", isDirectory: true)
.appendingPathComponent("voice_live_\(burstID.hexEncodedString()).aac")
}
@Test func burstCreatesBubbleAndPersistsFramesInOrder() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
let burstID = makeBurstID(0xA1)
defer { incomingFileURL(burstID: burstID).map { try? FileManager.default.removeItem(at: $0) } }
let frame1 = Data(repeating: 0x01, count: 60)
let frame2 = Data(repeating: 0x02, count: 60)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer)
#expect(context.handledPrivateMessages.count == 1)
let bubble = try #require(context.handledPrivateMessages.first)
#expect(bubble.isPrivate)
#expect(bubble.senderPeerID == peer)
#expect(bubble.content == "[voice] voice_live_\(burstID.hexEncodedString()).aac")
#expect(coordinator.isLiveVoiceMessage(bubble))
// Deliver out of order: seq 2 buffers behind the seq-1 hole, then
// seq 1 releases both in order.
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .frames([frame2]))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([frame1]))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 3, kind: .end(totalDataPackets: 2, durationMs: 128))), to: coordinator, from: peer)
let url = try #require(incomingFileURL(burstID: burstID))
let written = try Data(contentsOf: url)
var expected = ADTSFramer.frame(frame1)
expected.append(ADTSFramer.frame(frame2))
#expect(written == expected)
// Burst ended: no longer live, bubble republished for re-render.
#expect(!coordinator.isLiveVoiceMessage(bubble))
#expect(context.upsertedMessages.contains { $0.message.id == bubble.id })
#expect(context.removedMessageIDs.isEmpty)
}
@Test func absorbsFinalizedNoteIntoLiveBubble() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
let burstID = makeBurstID(0xB2)
let hex = burstID.hexEncodedString()
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 7, count: 50)]))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .end(totalDataPackets: 1, durationMs: 64))), to: coordinator, from: peer)
let bubble = try #require(context.handledPrivateMessages.first)
let note = BitchatMessage(
sender: "alice",
content: "[voice] voice_\(hex).m4a",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "me",
senderPeerID: peer
)
#expect(coordinator.absorbFinalizedVoiceNote(note))
// The note replaced the live bubble in place: same message ID, new
// content, partial capture deleted.
let replacement = try #require(context.upsertedMessages.last)
#expect(replacement.message.id == bubble.id)
#expect(replacement.message.content == note.content)
#expect(replacement.peerID == peer)
let url = try #require(incomingFileURL(burstID: burstID))
#expect(!FileManager.default.fileExists(atPath: url.path))
// Absorption is one-shot.
#expect(!coordinator.absorbFinalizedVoiceNote(note))
}
@Test func absorbIgnoresUnrelatedVoiceNotes() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
// A classic voice note (date-stamped name) and a live-capture name
// must both pass through untouched.
let classic = BitchatMessage(
sender: "alice", content: "[voice] voice_20260708_1201.m4a", timestamp: Date(),
isRelay: false, isPrivate: true, recipientNickname: "me", senderPeerID: peer
)
#expect(!coordinator.absorbFinalizedVoiceNote(classic))
let liveCapture = BitchatMessage(
sender: "alice", content: "[voice] voice_live_aabbccdd00112233.aac", timestamp: Date(),
isRelay: false, isPrivate: true, recipientNickname: "me", senderPeerID: peer
)
#expect(!coordinator.absorbFinalizedVoiceNote(liveCapture))
// Unknown burst ID.
let unknown = BitchatMessage(
sender: "alice", content: "[voice] voice_ffffffffffffffff.m4a", timestamp: Date(),
isRelay: false, isPrivate: true, recipientNickname: "me", senderPeerID: peer
)
#expect(!coordinator.absorbFinalizedVoiceNote(unknown))
}
@Test func canceledBurstRemovesBubbleAndFile() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
let burstID = makeBurstID(0xC3)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 9, count: 40)]))), to: coordinator, from: peer)
let bubble = try #require(context.handledPrivateMessages.first)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .canceled)), to: coordinator, from: peer)
#expect(context.removedMessageIDs == [bubble.id])
let url = try #require(incomingFileURL(burstID: burstID))
#expect(!FileManager.default.fileExists(atPath: url.path))
#expect(!coordinator.isLiveVoiceMessage(bubble))
}
@Test func emptyBurstLeavesNoBubble() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
let burstID = makeBurstID(0xD4)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer)
let bubble = try #require(context.handledPrivateMessages.first)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .end(totalDataPackets: 0, durationMs: 0))), to: coordinator, from: peer)
// Nothing audible arrived: the placeholder bubble is withdrawn.
#expect(context.removedMessageIDs == [bubble.id])
}
@Test func ignoresBlockedPeersAndUnknownControlPackets() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
context.blockedPeers = [peer]
send(try #require(VoiceBurstPacket(burstID: makeBurstID(0xE5), seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer)
#expect(context.handledPrivateMessages.isEmpty)
context.blockedPeers = []
// END/CANCELED for a burst that never started must not create state.
send(try #require(VoiceBurstPacket(burstID: makeBurstID(0xE6), seq: 5, kind: .end(totalDataPackets: 4, durationMs: 256))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: makeBurstID(0xE7), seq: 5, kind: .canceled)), to: coordinator, from: peer)
#expect(context.handledPrivateMessages.isEmpty)
}
@Test func concurrentAssemblyCapDropsExtraBursts() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
var cleanup: [Data] = []
defer {
for burstID in cleanup {
incomingFileURL(burstID: burstID).map { try? FileManager.default.removeItem(at: $0) }
}
}
for i in 0..<TransportConfig.pttMaxConcurrentAssemblies {
let burstID = makeBurstID(UInt8(0x10 + i))
cleanup.append(burstID)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer)
}
#expect(context.handledPrivateMessages.count == TransportConfig.pttMaxConcurrentAssemblies)
send(try #require(VoiceBurstPacket(burstID: makeBurstID(0xFF), seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer)
#expect(context.handledPrivateMessages.count == TransportConfig.pttMaxConcurrentAssemblies)
}
@Test func liveVoiceToggleOffDropsInboundFrames() throws {
let previous = PTTSettings.liveVoiceEnabled
PTTSettings.liveVoiceEnabled = false
defer { PTTSettings.liveVoiceEnabled = previous }
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context)
let burstID = makeBurstID(0xE8)
// Off means classic-notes-only: no live bubble, no partial file.
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 5, count: 40)]))), to: coordinator, from: peer)
#expect(context.handledPrivateMessages.isEmpty)
let url = try #require(incomingFileURL(burstID: burstID))
#expect(!FileManager.default.fileExists(atPath: url.path))
}
@Test func burstIDParsingFromFileNames() {
#expect(ChatLiveVoiceCoordinator.burstID(fromVoiceFileName: "voice_00112233445566ff.m4a") == Data(hexString: "00112233445566ff"))
// Uniquified copies keep the leading hex run.
#expect(ChatLiveVoiceCoordinator.burstID(fromVoiceFileName: "voice_00112233445566ff (1).m4a") == Data(hexString: "00112233445566ff"))
#expect(ChatLiveVoiceCoordinator.burstID(fromVoiceFileName: "voice_20260708_120000.m4a") == nil)
#expect(ChatLiveVoiceCoordinator.burstID(fromVoiceFileName: "voice_live_00112233445566ff.aac") == nil)
#expect(ChatLiveVoiceCoordinator.burstID(fromVoiceFileName: "other.m4a") == nil)
}
}
@@ -174,6 +174,13 @@ private final class MockChatTransportEventContext: ChatTransportEventContext {
func handleVouchPayload(from peerID: PeerID, payload: Data) {
vouchPayloads.append((peerID, payload))
}
// Live voice payloads
private(set) var voiceFramePayloads: [(peerID: PeerID, payload: Data, timestamp: Date)] = []
func handleVoiceFramePayload(from peerID: PeerID, payload: Data, timestamp: Date) {
voiceFramePayloads.append((peerID, payload, timestamp))
}
}
// MARK: - Helpers
+100
View File
@@ -0,0 +1,100 @@
//
// 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)
}
}
+161
View File
@@ -0,0 +1,161 @@
//
// VoiceBurstPacketTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Testing
import Foundation
@testable import bitchat
struct VoiceBurstPacketTests {
private let burstID = Data((0..<8).map { UInt8($0 + 1) })
// MARK: - Round trips
@Test func startRoundTrip() throws {
let packet = try #require(VoiceBurstPacket(burstID: burstID, seq: 0, kind: .start(codec: .aacLC16kMono)))
let decoded = try #require(VoiceBurstPacket.decode(packet.encode()))
#expect(decoded == packet)
#expect(decoded.seq == 0)
}
@Test func framesRoundTrip() throws {
let frames = [Data([0xDE, 0xAD]), Data(repeating: 0x42, count: 130)]
let packet = try #require(VoiceBurstPacket(burstID: burstID, seq: 7, kind: .frames(frames)))
let decoded = try #require(VoiceBurstPacket.decode(packet.encode()))
#expect(decoded == packet)
guard case .frames(let decodedFrames) = decoded.kind else {
Issue.record("expected frames")
return
}
#expect(decodedFrames == frames)
}
@Test func endRoundTrip() throws {
let packet = try #require(VoiceBurstPacket(burstID: burstID, seq: 42, kind: .end(totalDataPackets: 41, durationMs: 2_688)))
let decoded = try #require(VoiceBurstPacket.decode(packet.encode()))
#expect(decoded == packet)
}
@Test func canceledRoundTrip() throws {
let packet = try #require(VoiceBurstPacket(burstID: burstID, seq: 3, kind: .canceled))
let decoded = try #require(VoiceBurstPacket.decode(packet.encode()))
#expect(decoded == packet)
}
@Test func decodeSurvivesReslicedData() throws {
// Simulates the payload arriving as a slice with a non-zero start index.
let packet = try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data([1, 2, 3])])))
var padded = Data([0xAA, 0xBB])
padded.append(packet.encode())
let slice = padded.dropFirst(2)
#expect(VoiceBurstPacket.decode(slice) == packet)
}
// MARK: - Validation
@Test func rejectsMalformedInput() {
#expect(VoiceBurstPacket.decode(Data()) == nil)
#expect(VoiceBurstPacket.decode(Data(repeating: 0, count: 10)) == nil)
// Unknown flags byte.
var unknownFlags = burstID
unknownFlags.append(contentsOf: [0, 1, 0xFF])
#expect(VoiceBurstPacket.decode(unknownFlags) == nil)
// Data packet with zero frames.
var empty = burstID
empty.append(contentsOf: [0, 1, 0])
#expect(VoiceBurstPacket.decode(empty) == nil)
// Truncated frame length.
var truncated = burstID
truncated.append(contentsOf: [0, 1, 0, 0x00, 0x10, 0xAB])
#expect(VoiceBurstPacket.decode(truncated) == nil)
// Unknown codec in START.
var badCodec = burstID
badCodec.append(contentsOf: [0, 0, 0x01, 0x7F])
#expect(VoiceBurstPacket.decode(badCodec) == nil)
}
@Test func rejectsInvalidConstruction() {
#expect(VoiceBurstPacket(burstID: Data([1, 2]), seq: 0, kind: .canceled) == nil)
#expect(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([])) == nil)
#expect(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data()])) == nil)
let tooMany = Array(repeating: Data([0x01]), count: VoiceBurstPacket.maxFramesPerPacket + 1)
#expect(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames(tooMany)) == nil)
}
@Test func makeBurstIDProducesUniqueEightBytes() {
let a = VoiceBurstPacket.makeBurstID()
let b = VoiceBurstPacket.makeBurstID()
#expect(a.count == VoiceBurstPacket.burstIDSize)
#expect(a != b)
}
// MARK: - Packetizer
@Test func packetizerRespectsBudgetAndCounts() throws {
var packetizer = VoiceBurstPacketizer(burstID: burstID, budget: 210)
let frame = Data(repeating: 0x55, count: 130) // realistic 16 kbps AAC frame
// First frame buffers, second forces a flush of the first.
#expect(packetizer.add(frame).isEmpty)
let flushed = packetizer.add(frame)
#expect(flushed.count == 1)
let first = try #require(VoiceBurstPacket.decode(flushed[0]))
#expect(first.seq == 1)
guard case .frames(let frames) = first.kind else {
Issue.record("expected frames")
return
}
#expect(frames == [frame])
// Remaining frame flushes on demand; counters advance.
let final = packetizer.flush()
#expect(final.count == 1)
#expect(try #require(VoiceBurstPacket.decode(final[0])).seq == 2)
#expect(packetizer.dataPacketCount == 2)
#expect(packetizer.nextSeq == 3)
#expect(packetizer.flush().isEmpty)
}
@Test func packetizerBatchesSmallFrames() throws {
var packetizer = VoiceBurstPacketizer(burstID: burstID, budget: 210)
let small = Data(repeating: 0x11, count: 40)
for _ in 0..<4 {
#expect(packetizer.add(small).isEmpty) // 4 * 42 + 11 = 179 <= 210
}
let packets = packetizer.flush()
#expect(packets.count == 1)
guard case .frames(let frames) = try #require(VoiceBurstPacket.decode(packets[0])).kind else {
Issue.record("expected frames")
return
}
#expect(frames.count == 4)
}
@Test func packetizerDropsOversizedFrame() {
var packetizer = VoiceBurstPacketizer(burstID: burstID, budget: 210)
#expect(packetizer.add(Data(repeating: 0, count: 500)).isEmpty)
#expect(packetizer.flush().isEmpty)
#expect(packetizer.dataPacketCount == 0)
}
@Test func encodedPacketStaysWithinNoisePaddingBucket() throws {
// The whole point of the budget: burst content + 1 type byte +
// 16-byte Noise tag must stay within MessagePadding's 256 bucket.
var packetizer = VoiceBurstPacketizer(burstID: burstID)
var largest = 0
for _ in 0..<3 {
for packet in packetizer.add(Data(repeating: 0xAB, count: 160)) {
largest = max(largest, packet.count)
}
}
for packet in packetizer.flush() {
largest = max(largest, packet.count)
}
#expect(largest > 0)
#expect(largest + 1 + 16 <= 256)
}
}