Port live video wire codec, FEC, packetizer and assembler from Android

Adds the pure-logic core of live video v1 (docs/LIVE_VIDEO_V1.md): the VideoBurstPacket wire codec, GF(2^8) Cauchy Reed-Solomon erasure code, sender packetizer, receiver assembler, congestion controller, quality presets and H.264 Annex B helpers, with tests for golden vectors, malformed input, any-k-of-k+r recovery and lossy-channel simulations.
This commit is contained in:
callebtc committed 2026-10-27 18:32:52 +01:00
1 parent 04995f68e4
commit 78f88bfcac
14 files changed
+2366

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
//
// H264NalUnits.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Minimal Annex B helpers: just enough to split access units and lift
/// SPS/PPS out of IDRs.
enum H264NalUnits {
static let typeIDR = 5
static let typeSPS = 7
static let typePPS = 8
static let typeAUD = 9
static let typeFiller = 12
private static let startCode = Data([0, 0, 0, 1])
/// NAL units (without start codes) in an Annex B buffer.
static func split(_ data: Data) -> [Data] {
let bytes = [UInt8](data)
var starts: [(offset: Int, codeLength: Int)] = []
var index = 0
while index + 3 <= bytes.count {
if bytes[index] == 0 && bytes[index + 1] == 0 {
if bytes[index + 2] == 1 {
starts.append((index + 3, 3))
index += 3
continue
}
if index + 4 <= bytes.count && bytes[index + 2] == 0 && bytes[index + 3] == 1 {
starts.append((index + 4, 4))
index += 4
continue
}
}
index += 1
}
return starts.enumerated().compactMap { position, start in
let end = position + 1 < starts.count
? starts[position + 1].offset - starts[position + 1].codeLength
: bytes.count
return end > start.offset ? Data(bytes[start.offset..<end]) : nil
}
}
/// NAL unit type (low five bits of the header byte), or -1 when empty.
static func type(_ nal: Data) -> Int {
guard let header = nal.first else { return -1 }
return Int(header & 0x1F)
}
static func join(_ nals: [Data]) -> Data {
var output = Data(capacity: nals.reduce(0) { $0 + $1.count + 4 })
for nal in nals {
output.append(startCode)
output.append(nal)
}
return output
}
static func containsType(_ data: Data, _ type: Int) -> Bool {
split(data).contains { Self.type($0) == type }
}
/// SPS and PPS NAL payloads (without start codes), as
/// `CMVideoFormatDescriptionCreateFromH264ParameterSets` takes them, or nil.
static func parameterSets(_ data: Data) -> (sps: Data, pps: Data)? {
let nals = split(data)
guard let sps = nals.first(where: { type($0) == typeSPS }),
let pps = nals.first(where: { type($0) == typePPS })
else { return nil }
return (sps, pps)
}
/// Drops filler NAL units, which some CBR encoders emit to pad the
/// bitrate; pure airtime cost.
static func withoutFiller(_ data: Data) -> Data {
let nals = split(data)
guard nals.contains(where: { type($0) == typeFiller }) else { return data }
return join(nals.filter { type($0) != typeFiller })
}
/// Access unit with SPS, PPS and AUD removed, for muxing into MP4 where
/// the format description carries them.
static func withoutParameterSets(_ data: Data) -> Data {
join(split(data).filter {
let nalType = type($0)
return nalType != typeSPS && nalType != typePPS && nalType != typeAUD
})
}
}
@@ -0,0 +1,95 @@
//
// LiveVideoCongestionController.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Sender-side congestion control for a broadcast stream with no receiver feedback.
///
/// The signal is the depth of the busiest outbound queue: on a mesh the first
/// hop is the usual bottleneck, and a growing queue is pure added latency. The
/// controller backs the encoder off multiplicatively, probes back up
/// additively once the queue stays short, and when the queue is far behind it
/// skips video until it drains, then restarts from a keyframe so the stream
/// stays live instead of drifting seconds behind.
///
/// Not thread-safe — confine to one queue. Callers supply time.
final class LiveVideoCongestionController {
struct Decision: Equatable {
let bitrate: Int
let skipVideo: Bool
let requestKeyframe: Bool
}
private static let decreaseIntervalMs: Int64 = 1_000
private static let increaseIntervalMs: Int64 = 1_000
private static let calmBeforeIncreaseMs: Int64 = 2_000
private let maxBitrate: Int
private let minBitrate: Int
private let highWater: Int
private let skipWater: Int
private let lowWater: Int
private(set) var bitrate: Int
private(set) var skipping = false
private(set) var skipEpisodes = 0
private var lastDecreaseMs = Int64.min / 2
private var lastIncreaseMs = Int64.min / 2
private var calmSinceMs: Int64?
/// `minBitrate` defaults to 30% of `maxBitrate`.
init(
maxBitrate: Int,
minBitrate: Int? = nil,
highWater: Int = 16,
skipWater: Int = 48,
lowWater: Int = 4
) {
self.maxBitrate = maxBitrate
self.minBitrate = minBitrate ?? maxBitrate * 3 / 10
self.highWater = highWater
self.skipWater = skipWater
self.lowWater = lowWater
self.bitrate = maxBitrate
}
func onBacklog(_ backlog: Int, nowMs: Int64) -> Decision {
var keyframe = false
if backlog >= skipWater {
if !skipping { skipEpisodes += 1 }
skipping = true
calmSinceMs = nil
decrease(nowMs: nowMs, factor: 0.6, force: true)
} else if backlog >= highWater {
calmSinceMs = nil
decrease(nowMs: nowMs, factor: 0.8, force: false)
} else if backlog <= lowWater {
if skipping {
skipping = false
keyframe = true
}
let since = calmSinceMs ?? nowMs
calmSinceMs = since
if nowMs - since >= Self.calmBeforeIncreaseMs
&& nowMs - lastIncreaseMs >= Self.increaseIntervalMs {
bitrate = min(maxBitrate, bitrate + maxBitrate / 12)
lastIncreaseMs = nowMs
}
} else {
calmSinceMs = nil
}
return Decision(bitrate: bitrate, skipVideo: skipping, requestKeyframe: keyframe)
}
private func decrease(nowMs: Int64, factor: Double, force: Bool) {
if !force && nowMs - lastDecreaseMs < Self.decreaseIntervalMs { return }
bitrate = max(minBitrate, Int(Double(bitrate) * factor))
lastDecreaseMs = nowMs
}
}
@@ -0,0 +1,97 @@
//
// LiveVideoQuality.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Sender presets. Dimensions are portrait and multiples of 16 so every
/// hardware H.264 encoder accepts them without cropping. Low targets multi-hop
/// Bluetooth (roughly the airtime of a live voice burst); Medium suits one or
/// two BLE hops; High assumes a Wi-Fi link.
enum LiveVideoQuality: String, CaseIterable {
case low
case medium
case high
/// Recorded clips: sized so `LiveVideoLimits.maxClipDurationMs` fits one file transfer.
case clip
var width: Int {
switch self {
case .low: return 144
case .medium, .clip: return 240
case .high: return 480
}
}
var height: Int {
switch self {
case .low: return 192
case .medium, .clip: return 320
case .high: return 640
}
}
var fps: Int {
switch self {
case .low: return 8
case .medium, .clip: return 12
case .high: return 24
}
}
/// Video bitrate in bits per second.
var videoBitrate: Int {
switch self {
case .low: return 18_000
case .medium: return 56_000
case .high: return 360_000
case .clip: return 26_000
}
}
/// Audio bitrate in bits per second.
var audioBitrate: Int {
switch self {
case .low, .clip: return 12_000
case .medium: return 16_000
case .high: return 24_000
}
}
var keyframeIntervalSeconds: Int { 2 }
var fec: LiveVideoFecPolicy {
switch self {
case .low:
return LiveVideoFecPolicy(parityRatio: 0.2, keyframeParityRatio: 0.4, blockWindowMs: 600)
case .medium:
return LiveVideoFecPolicy(parityRatio: 0.2, keyframeParityRatio: 0.35, maxSourceShards: 16)
case .high:
return LiveVideoFecPolicy(parityRatio: 0.15, keyframeParityRatio: 0.3, maxSourceShards: 32)
case .clip:
return LiveVideoFecPolicy(parityRatio: 0, keyframeParityRatio: 0)
}
}
var isLivePreset: Bool { self != .clip }
var totalBitrate: Int { videoBitrate + audioBitrate }
/// Case-insensitive lookup by name; unknown or nil falls back to `.low`.
static func fromName(_ value: String?) -> LiveVideoQuality {
guard let value else { return .low }
return LiveVideoQuality(rawValue: value.lowercased()) ?? .low
}
}
enum LiveVideoLimits {
/// Largest video file that fits one mesh file transfer: 256 fragments of
/// at most ~450 B, less the file TLVs, packet header, signature and Noise framing.
static let maxVideoFileBytes = 100 * 1_024
static let maxClipDurationMs: Int64 = 20_000
static let maxTranscodeSourceMs: Int64 = 60_000
}
@@ -0,0 +1,150 @@
//
// ReedSolomonErasure.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Systematic Reed-Solomon erasure code over GF(2^8) with a Cauchy generator.
///
/// Parity row `j` (0-based) for source symbol `i` uses coefficient
/// `1 / (i XOR (k + j))`. Every square submatrix of a Cauchy matrix is
/// invertible, so any `k` of the `k + r` symbols reconstruct the block (MDS).
/// Field polynomial: x^8 + x^4 + x^3 + x^2 + 1 (0x11D).
enum ReedSolomonErasure {
private static let fieldSize = 256
private static let tables: (exp: [Int], log: [Int]) = {
var exp = [Int](repeating: 0, count: fieldSize * 2)
var log = [Int](repeating: 0, count: fieldSize)
var value = 1
for power in 0..<(fieldSize - 1) {
exp[power] = value
log[value] = power
value <<= 1
if value & 0x100 != 0 { value ^= 0x11D }
}
for power in (fieldSize - 1)..<exp.count {
exp[power] = exp[power - (fieldSize - 1)]
}
return (exp, log)
}()
private static var exp: [Int] { tables.exp }
private static var log: [Int] { tables.log }
static func multiply(_ a: Int, _ b: Int) -> Int {
(a == 0 || b == 0) ? 0 : exp[log[a] + log[b]]
}
static func inverse(_ a: Int) -> Int {
precondition(a != 0, "zero has no inverse")
return exp[(fieldSize - 1) - log[a]]
}
static func coefficient(sourceCount: Int, parityRow: Int, sourceIndex: Int) -> Int {
inverse(sourceIndex ^ (sourceCount + parityRow))
}
/// Returns `parityCount` symbols, each as long as the (equal-length) `sources`.
static func encode(_ sources: [Data], parityCount: Int) -> [Data] {
let k = sources.count
precondition((1...128).contains(k) && (1...128).contains(parityCount) && k + parityCount <= fieldSize)
let length = sources[0].count
precondition(sources.allSatisfy { $0.count == length })
let sourceBytes = sources.map { [UInt8]($0) }
return (0..<parityCount).map { row in
var parity = [UInt8](repeating: 0, count: length)
for i in 0..<k {
addScaled(&parity, sourceBytes[i], coefficient(sourceCount: k, parityRow: row, sourceIndex: i))
}
return Data(parity)
}
}
/// Rebuilds missing source symbols.
///
/// `sources` holds the `k` source slots (nil where lost) and `parities`
/// maps a parity row to its symbol. Returns the completed source list, or
/// nil when fewer than `k` symbols are available or lengths disagree.
static func reconstruct(_ sources: [Data?], parities: [Int: Data]) -> [Data]? {
let k = sources.count
let missing = sources.indices.filter { sources[$0] == nil }
if missing.isEmpty { return sources.map { $0! } }
let firstKnown = sources.compactMap { $0 }.first ?? parities.values.first
guard parities.count >= missing.count, let length = firstKnown?.count else { return nil }
if sources.contains(where: { $0 != nil && $0!.count != length })
|| parities.values.contains(where: { $0.count != length }) {
return nil
}
let known = sources.map { $0.map { [UInt8]($0) } }
let rows = Array(parities.keys.sorted().prefix(missing.count))
// Right-hand side: parity minus the contribution of the symbols we already have.
let rhs: [[UInt8]] = rows.map { row in
var value = [UInt8](parities[row]!)
for i in 0..<k {
guard let source = known[i] else { continue }
addScaled(&value, source, coefficient(sourceCount: k, parityRow: row, sourceIndex: i))
}
return value
}
var matrix = rows.map { row in
missing.map { coefficient(sourceCount: k, parityRow: row, sourceIndex: $0) }
}
guard let solved = solve(&matrix, rhs) else { return nil }
var output = sources
for (index, sourceIndex) in missing.enumerated() {
output[sourceIndex] = Data(solved[index])
}
return output.map { $0! }
}
/// Gauss-Jordan elimination over GF(256); `rhs` rows are byte vectors.
private static func solve(_ matrix: inout [[Int]], _ rhs: [[UInt8]]) -> [[UInt8]]? {
let n = matrix.count
var values = rhs
for column in 0..<n {
guard let pivot = (column..<n).first(where: { matrix[$0][column] != 0 }) else { return nil }
if pivot != column {
matrix.swapAt(pivot, column)
values.swapAt(pivot, column)
}
let scale = inverse(matrix[column][column])
for c in 0..<n { matrix[column][c] = multiply(matrix[column][c], scale) }
scaleInPlace(&values[column], scale)
for row in 0..<n where row != column {
let factor = matrix[row][column]
if factor == 0 { continue }
for c in 0..<n { matrix[row][c] ^= multiply(factor, matrix[column][c]) }
addScaled(&values[row], values[column], factor)
}
}
return values
}
private static func addScaled(_ target: inout [UInt8], _ source: [UInt8], _ factor: Int) {
if factor == 0 { return }
let exp = self.exp
let log = self.log
let logFactor = log[factor]
for index in target.indices {
let byte = Int(source[index])
if byte != 0 {
target[index] ^= UInt8(exp[log[byte] + logFactor])
}
}
}
private static func scaleInPlace(_ target: inout [UInt8], _ factor: Int) {
let exp = self.exp
let log = self.log
let logFactor = log[factor]
for index in target.indices {
let byte = Int(target[index])
target[index] = byte == 0 ? 0 : UInt8(exp[log[byte] + logFactor])
}
}
}
@@ -0,0 +1,434 @@
//
// VideoStreamAssembler.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Output of `VideoStreamAssembler`, in decode order per track.
enum LiveVideoOutput: Equatable {
case config(LiveVideoConfig)
/// A decodable video access unit: a keyframe, or a delta frame whose
/// references all arrived.
case video(sequence: Int64, ptsMs: Int64, keyframe: Bool, data: Data)
case audio(sequence: Int64, ptsMs: Int64, data: Data)
/// Video units that were lost (or undecodable after a loss) and skipped.
case videoSkipped(Int)
case ended(durationMs: Int64)
case canceled
}
struct LiveVideoReceiveStats: Equatable {
let packets: Int
let bytes: Int64
let recoveredShards: Int
let videoUnits: Int
let audioUnits: Int
let skippedVideoUnits: Int
/// Packet loss over the most recent sequence window, 0.0...1.0.
let recentLoss: Double
}
/// Receiver state machine for one live video stream. Pure logic; the caller
/// supplies time.
///
/// Packets may arrive duplicated, reordered, or not at all. Source shards are
/// parsed the moment they arrive; parity rebuilds lost shards once any `k`
/// symbols of a block are present. Units are released per track in sequence
/// order. A gap is skipped after `gapMs`; a skipped video unit breaks the
/// reference chain, so delta frames are withheld until the next keyframe (the
/// player freezes on the last good picture instead of showing corruption).
///
/// Not thread-safe — confine to one queue.
final class VideoStreamAssembler {
private static let maxTrackedBlocks = 48
private static let maxPendingUnits = 192
private static let maxReadyUnits = 192
private static let lossWindow = 128
private final class BlockState {
var sources: [Int: Data] = [:]
var parities: [Int: Data] = [:]
var sourceCount: Int?
var parityCount: Int?
var complete = false
}
private final class PendingUnit {
let keyframe: Bool
let ptsMs: Int64
let count: Int
var fragments: [Data?]
var received = 0
var bytes = 0
init(keyframe: Bool, ptsMs: Int64, count: Int) {
self.keyframe = keyframe
self.ptsMs = ptsMs
self.count = count
self.fragments = Array(repeating: nil, count: count)
}
}
private struct ReadyUnit {
let ptsMs: Int64
let keyframe: Bool
let data: Data
}
private final class TrackState {
var pending: [Int64: PendingUnit] = [:]
/// Insertion order of `pending`, so the oldest unit is evicted first.
var pendingOrder: [Int64] = []
var ready: [Int64: ReadyUnit] = [:]
var next: Int64?
var lastReference: Int64?
var gapSinceMs: Int64?
var released = 0
func removePending(_ sequence: Int64) {
guard pending.removeValue(forKey: sequence) != nil else { return }
pendingOrder.removeAll { $0 == sequence }
}
func removePending(below target: Int64) {
pendingOrder.removeAll { $0 < target }
pending = pending.filter { $0.key >= target }
}
}
/// Longer than the widest FEC block window plus relay jitter, so parity can still land.
private let gapMs: Int64
private let maxUnitBytes: Int
private var blocks: [Int: BlockState] = [:]
private var blockOrder: [Int] = []
private let tracks: [TrackState] = LiveVideoTrack.allCases.map { _ in TrackState() }
private var lastConfig: LiveVideoConfig?
private var videoChainBroken = true
private var expectedUnits: [LiveVideoTrack: Int]?
private var endDurationMs: Int64?
private var finished = false
private var packets = 0
private var bytes: Int64 = 0
private var recoveredShards = 0
private var skippedVideo = 0
private var highestSequence: Int64?
private var recentSequences: [Int64] = []
private var recentSet = Set<Int64>()
init(gapMs: Int64 = 900, maxUnitBytes: Int = 256 * 1024) {
self.gapMs = gapMs
self.maxUnitBytes = maxUnitBytes
}
var config: LiveVideoConfig? { lastConfig }
/// The sender's END arrived; anything still missing is tail loss, not a pause.
var endReceived: Bool { expectedUnits != nil }
var isFinished: Bool { finished }
func stats() -> LiveVideoReceiveStats {
var loss = 0.0
if let high = highestSequence {
let window = min(Int64(Self.lossWindow), high + 1)
let seen = recentSet.filter { $0 > high - window }.count
loss = min(max(1.0 - Double(seen) / Double(window), 0.0), 1.0)
}
return LiveVideoReceiveStats(
packets: packets,
bytes: bytes,
recoveredShards: recoveredShards,
videoUnits: trackState(.video).released,
audioUnits: trackState(.audio).released,
skippedVideoUnits: skippedVideo,
recentLoss: loss
)
}
func onPacket(_ packet: VideoBurstPacket, sizeBytes: Int, nowMs: Int64) -> [LiveVideoOutput] {
if finished { return [] }
packets += 1
bytes += Int64(sizeBytes)
recordSequence(packet.sequence)
var output: [LiveVideoOutput] = []
switch packet.kind {
case .start(let config):
if config != lastConfig {
lastConfig = config
output.append(.config(config))
}
case .data(let block, let index, let region):
onData(block: block, index: index, region: region, nowMs: nowMs)
case .parity(let block, let parityIndex, let sourceCount, let parityCount, let symbol):
onParity(
block: block,
parityIndex: parityIndex,
sourceCount: sourceCount,
parityCount: parityCount,
symbol: symbol,
nowMs: nowMs
)
case .end(let durationMs, let videoUnits, let audioUnits, _):
expectedUnits = [.video: videoUnits, .audio: audioUnits]
endDurationMs = durationMs
case .canceled:
finished = true
return [.canceled]
}
output += release(nowMs: nowMs)
return output
}
/// Skips gaps whose deadline passed; call periodically.
func onTick(nowMs: Int64) -> [LiveVideoOutput] {
finished ? [] : release(nowMs: nowMs)
}
/// Releases everything buffered (skipping open gaps) without ending the
/// stream, so a viewer whose link went quiet keeps all it received and can
/// carry on when packets return.
func drain() -> [LiveVideoOutput] {
finished ? [] : release(nowMs: .max)
}
/// Forces every buffered unit out (skipping all gaps) and ends the stream.
func flush() -> [LiveVideoOutput] {
if finished { return [] }
var output = release(nowMs: .max)
// release() may already have ended the stream if END's totals were met.
if !finished {
finished = true
output.append(.ended(durationMs: endDurationMs ?? 0))
}
return output
}
// MARK: - Blocks
private func onData(block: Int, index: Int, region: Data, nowMs: Int64) {
let state = blockState(block)
if state.complete || state.sources[index] != nil { return }
if let limit = state.sourceCount, index >= limit { return }
state.sources[index] = region
ingestRegion(region, nowMs: nowMs)
tryRecover(state, nowMs: nowMs)
}
private func onParity(
block: Int,
parityIndex: Int,
sourceCount: Int,
parityCount: Int,
symbol: Data,
nowMs: Int64
) {
let state = blockState(block)
if state.complete { return }
if let knownK = state.sourceCount,
knownK != sourceCount || state.parityCount != parityCount {
return
}
if let existing = state.parities.values.first, existing.count != symbol.count { return }
if state.sources.keys.contains(where: { $0 >= sourceCount }) { return }
state.sourceCount = sourceCount
state.parityCount = parityCount
if state.parities[parityIndex] == nil { state.parities[parityIndex] = symbol }
tryRecover(state, nowMs: nowMs)
}
private func tryRecover(_ state: BlockState, nowMs: Int64) {
guard let k = state.sourceCount else { return }
if state.sources.count >= k {
state.complete = true
return
}
guard state.sources.count + state.parities.count >= k,
let symbolLength = state.parities.values.first?.count
else { return }
if state.sources.values.contains(where: { $0.count + 2 > symbolLength }) {
state.complete = true
return
}
let slots: [Data?] = (0..<k).map { index in
state.sources[index].map { LiveVideoSymbols.symbol($0, length: symbolLength) }
}
let rebuilt = ReedSolomonErasure.reconstruct(slots, parities: state.parities)
state.complete = true
guard let rebuilt else { return }
for index in 0..<k where state.sources[index] == nil {
guard let region = LiveVideoSymbols.region(rebuilt[index]) else { continue }
state.sources[index] = region
recoveredShards += 1
ingestRegion(region, nowMs: nowMs)
}
}
private func blockState(_ block: Int) -> BlockState {
if let state = blocks[block] { return state }
while blocks.count >= Self.maxTrackedBlocks, let oldest = blockOrder.first {
blockOrder.removeFirst()
blocks.removeValue(forKey: oldest)
}
let state = BlockState()
blocks[block] = state
blockOrder.append(block)
return state
}
// MARK: - Units
private func ingestRegion(_ region: Data, nowMs: Int64) {
guard let entries = LiveVideoEntry.decodeAll(region) else { return }
for entry in entries { ingestEntry(entry, nowMs: nowMs) }
}
private func ingestEntry(_ entry: LiveVideoEntry, nowMs: Int64) {
let track = trackState(entry.track)
let reference = track.next ?? track.lastReference ?? Int64(entry.unitSequence)
let sequence = Self.expand(entry.unitSequence, reference: reference)
if let next = track.next, sequence < next { return }
if track.ready[sequence] != nil { return }
let pending: PendingUnit
if let existing = track.pending[sequence] {
pending = existing
} else {
if track.pending.count >= Self.maxPendingUnits, let oldest = track.pendingOrder.first {
track.removePending(oldest)
}
pending = PendingUnit(keyframe: entry.keyframe, ptsMs: entry.ptsMs, count: entry.fragmentCount)
track.pending[sequence] = pending
track.pendingOrder.append(sequence)
}
if pending.count != entry.fragmentCount || pending.keyframe != entry.keyframe { return }
if pending.fragments[entry.fragmentIndex] != nil { return }
pending.bytes += entry.bytes.count
if pending.bytes > maxUnitBytes {
track.removePending(sequence)
return
}
pending.fragments[entry.fragmentIndex] = entry.bytes
pending.received += 1
if pending.received < pending.count { return }
track.removePending(sequence)
var data = Data(capacity: pending.bytes)
for fragment in pending.fragments {
data.append(fragment!)
}
if track.next == nil {
track.next = sequence
}
track.lastReference = sequence
track.ready[sequence] = ReadyUnit(ptsMs: pending.ptsMs, keyframe: pending.keyframe, data: data)
if track.ready.count > Self.maxReadyUnits, let oldest = track.ready.keys.min() {
// A runaway backlog means the head gap will never fill; skip to the oldest ready unit.
_ = skip(entry.track, track, to: oldest)
}
}
private func release(nowMs: Int64) -> [LiveVideoOutput] {
var output: [LiveVideoOutput] = []
for type in LiveVideoTrack.allCases {
let track = trackState(type)
while let next = track.next {
if let unit = track.ready.removeValue(forKey: next) {
track.gapSinceMs = nil
track.next = next + 1
track.released += 1
emit(type, sequence: next, unit: unit, into: &output)
continue
}
guard let target = track.ready.keys.min() else {
track.gapSinceMs = nil
break
}
let since = track.gapSinceMs ?? nowMs
track.gapSinceMs = since
if nowMs == .max || nowMs &- since >= gapMs {
let skipped = skip(type, track, to: target)
if type == .video && skipped > 0 { output.append(.videoSkipped(skipped)) }
track.gapSinceMs = nil
continue
}
break
}
}
if let expected = expectedUnits, !finished {
let done = expected.allSatisfy { type, total in
guard total != 0 else { return true }
guard let next = trackState(type).next else { return false }
return next >= Self.expandCount(total, reference: next)
}
if done {
finished = true
output.append(.ended(durationMs: endDurationMs ?? 0))
}
}
return output
}
private func emit(_ type: LiveVideoTrack, sequence: Int64, unit: ReadyUnit, into output: inout [LiveVideoOutput]) {
switch type {
case .audio:
output.append(.audio(sequence: sequence, ptsMs: unit.ptsMs, data: unit.data))
case .video:
if unit.keyframe { videoChainBroken = false }
if videoChainBroken {
skippedVideo += 1
output.append(.videoSkipped(1))
} else {
output.append(.video(sequence: sequence, ptsMs: unit.ptsMs, keyframe: unit.keyframe, data: unit.data))
}
}
}
private func skip(_ type: LiveVideoTrack, _ track: TrackState, to target: Int64) -> Int {
guard let next = track.next else { return 0 }
let skipped = Int(max(target - next, 0))
if skipped > 0 {
track.removePending(below: target)
if type == .video {
videoChainBroken = true
skippedVideo += skipped
}
}
track.next = target
return skipped
}
private func trackState(_ type: LiveVideoTrack) -> TrackState {
tracks[Int(type.rawValue)]
}
// MARK: - Sequence numbers
private func recordSequence(_ sequence: Int) {
let expanded = Self.expand(sequence, reference: highestSequence ?? Int64(sequence))
guard recentSet.insert(expanded).inserted else { return }
recentSequences.append(expanded)
if highestSequence.map({ expanded > $0 }) ?? true { highestSequence = expanded }
while recentSequences.count > Self.lossWindow {
recentSet.remove(recentSequences.removeFirst())
}
}
/// Maps a 16-bit wire counter to the 64-bit value closest to `reference`.
static func expand(_ value: Int, reference: Int64) -> Int64 {
let base = reference - (reference & 0xFFFF)
var candidate = base + Int64(value)
if candidate - reference > 0x8000 { candidate -= 0x10000 }
if reference - candidate > 0x8000 { candidate += 0x10000 }
return candidate
}
/// END counts units (not sequence numbers); a count of N means sequences 0..<N.
static func expandCount(_ count: Int, reference: Int64) -> Int64 {
let base = reference - (reference & 0xFFFF)
var candidate = base + Int64(count)
if candidate < reference - 0x8000 { candidate += 0x10000 }
return candidate
}
}
@@ -0,0 +1,274 @@
//
// VideoStreamPacketizer.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// One encoded access unit handed to the packetizer.
struct LiveMediaUnit {
let track: LiveVideoTrack
let ptsMs: Int64
let keyframe: Bool
let data: Data
}
/// How much Reed-Solomon parity accompanies each block of source shards.
struct LiveVideoFecPolicy: Equatable {
let parityRatio: Double
let keyframeParityRatio: Double
let maxSourceShards: Int
let shardFlushMs: Int64
let blockWindowMs: Int64
init(
parityRatio: Double,
keyframeParityRatio: Double,
maxSourceShards: Int = 12,
shardFlushMs: Int64 = 150,
blockWindowMs: Int64 = 400
) {
self.parityRatio = parityRatio
self.keyframeParityRatio = keyframeParityRatio
self.maxSourceShards = maxSourceShards
self.shardFlushMs = shardFlushMs
self.blockWindowMs = blockWindowMs
}
func parityCount(sourceCount: Int, containsKeyframe: Bool) -> Int {
let ratio = containsKeyframe ? keyframeParityRatio : parityRatio
if ratio <= 0 { return 0 }
// Two parity shards from four sources up: one lost delta frame freezes
// the picture until the next keyframe, so double losses are worth absorbing.
let floor = sourceCount >= 4 ? 2 : 1
let count = max(Int((Double(sourceCount) * ratio).rounded(.up)), floor)
return min(max(count, 1), VideoBurstPacket.maxBlockParityShards)
}
}
/// FEC symbol framing shared by sender and receiver:
/// `[regionLength: UInt16][region][zero pad]`.
enum LiveVideoSymbols {
static func symbol(_ region: Data, length: Int) -> Data {
var symbol = Data(capacity: length)
symbol.append(UInt8((region.count >> 8) & 0xFF))
symbol.append(UInt8(region.count & 0xFF))
symbol.append(region)
if symbol.count < length {
symbol.append(Data(count: length - symbol.count))
}
return symbol
}
static func region(_ symbol: Data) -> Data? {
let bytes = [UInt8](symbol)
guard bytes.count >= 2 else { return nil }
let length = (Int(bytes[0]) << 8) | Int(bytes[1])
guard length > 0, length <= bytes.count - 2,
bytes[(2 + length)...].allSatisfy({ $0 == 0 })
else { return nil }
return Data(bytes[2..<(2 + length)])
}
}
/// Turns encoded audio/video units into wire packets.
///
/// Small units are aggregated into one shard, large ones fragmented across
/// shards (in the spirit of RTP STAP-A/FU-A), so every packet is
/// independently parseable and a lost packet only damages the units it
/// carried. Consecutive source shards form a block that is closed by size, by
/// time, or before a keyframe, and then protected by Reed-Solomon parity.
/// Source shards are emitted immediately; parity only costs latency when a
/// shard is actually lost.
///
/// Not thread-safe — one sender queue owns it. Callers supply time.
final class VideoStreamPacketizer {
/// Do not open a fragment that would carry less than this many bytes.
private static let minFragmentBytes = 24
let streamID: Data
private let config: LiveVideoConfig
private let fec: LiveVideoFecPolicy
private let maxEntriesRegion: Int
private var sequence = 0
private var block = 0
private var openEntries: [LiveVideoEntry] = []
private var openSize = 0
private var openSinceMs: Int64 = 0
private var blockSymbols: [Data] = []
private var blockSinceMs: Int64 = 0
private var blockHasKeyframe = false
private var unitSequence = [Int](repeating: 0, count: LiveVideoTrack.allCases.count)
private var unitCount = [Int](repeating: 0, count: LiveVideoTrack.allCases.count)
private(set) var packetCount = 0
private(set) var droppedUnits = 0
private(set) var parityPackets = 0
init(
streamID: Data,
config: LiveVideoConfig,
fec: LiveVideoFecPolicy,
maxEntriesRegion: Int = VideoBurstPacket.maxEntriesRegion
) {
self.streamID = streamID
self.config = config
self.fec = fec
self.maxEntriesRegion = maxEntriesRegion
}
func unitsEmitted(_ track: LiveVideoTrack) -> Int {
unitCount[Int(track.rawValue)]
}
func start() -> [Data] {
packet(.start(config)).map { [$0] } ?? []
}
func add(_ unit: LiveMediaUnit, nowMs: Int64) -> [Data] {
var output: [Data] = []
if unit.data.isEmpty { return output }
let bodyBudget = maxEntriesRegion - LiveVideoEntry.headerSize
if unit.keyframe && unit.track == .video {
// Give each keyframe its own, more strongly protected block,
// announced by a repeated START so a viewer joining mid-stream can
// configure its decoder.
output += flushShard(nowMs: nowMs)
output += closeBlock()
output += start()
}
let firstCapacity = maxEntriesRegion - openSize - LiveVideoEntry.headerSize
let useOpenShard = !openEntries.isEmpty
&& firstCapacity >= min(unit.data.count, Self.minFragmentBytes)
if !openEntries.isEmpty && !useOpenShard { output += flushShard(nowMs: nowMs) }
let firstChunk = useOpenShard ? min(firstCapacity, unit.data.count) : min(bodyBudget, unit.data.count)
let remaining = unit.data.count - firstChunk
let fragmentCount = 1 + (remaining + bodyBudget - 1) / bodyBudget
if fragmentCount > 0xFF {
droppedUnits += 1
return output
}
let trackIndex = Int(unit.track.rawValue)
let seq = unitSequence[trackIndex]
unitSequence[trackIndex] = (seq + 1) & 0xFFFF
unitCount[trackIndex] = min(unitCount[trackIndex] + 1, 0xFFFF)
let pts = min(max(unit.ptsMs, 0), 0xFFFF_FFFF)
let bytes = Data(unit.data)
var offset = 0
for fragment in 0..<fragmentCount {
let chunk = fragment == 0 ? firstChunk : min(bodyBudget, bytes.count - offset)
let entry = LiveVideoEntry(
track: unit.track,
keyframe: unit.keyframe,
unitSequence: seq,
ptsMs: pts,
fragmentIndex: fragment,
fragmentCount: fragmentCount,
bytes: bytes.subdata(in: offset..<(offset + chunk))
)
offset += chunk
if openEntries.isEmpty { openSinceMs = nowMs }
openEntries.append(entry)
openSize += entry.encodedSize
if unit.keyframe { blockHasKeyframe = true }
if maxEntriesRegion - openSize < LiveVideoEntry.headerSize + Self.minFragmentBytes {
output += flushShard(nowMs: nowMs)
}
}
return output
}
/// Emits shards and parity whose latency deadlines have passed.
func tick(nowMs: Int64) -> [Data] {
var output: [Data] = []
if !openEntries.isEmpty && nowMs - openSinceMs >= fec.shardFlushMs {
output += flushShard(nowMs: nowMs)
}
if !blockSymbols.isEmpty && nowMs - blockSinceMs >= fec.blockWindowMs {
output += closeBlock()
}
return output
}
/// Flushes and emits END. END is repeated (`endCopies`) because a lost END
/// would leave viewers waiting out their reconnect window; receivers treat
/// the copies as duplicates.
func finish(durationMs: Int64, nowMs: Int64, endCopies: Int = 3) -> [Data] {
var output: [Data] = []
output += flushShard(nowMs: nowMs)
output += closeBlock()
let end = VideoBurstPacket.Kind.end(
durationMs: min(max(durationMs, 0), 0xFFFF_FFFF),
videoUnits: unitCount[Int(LiveVideoTrack.video.rawValue)],
audioUnits: unitCount[Int(LiveVideoTrack.audio.rawValue)],
packets: min(packetCount, 0xFFFF)
)
for _ in 0..<max(endCopies, 1) {
if let packet = packet(end) { output.append(packet) }
}
return output
}
func cancel() -> Data? {
packet(.canceled)
}
private func flushShard(nowMs: Int64) -> [Data] {
if openEntries.isEmpty { return [] }
let region = VideoBurstPacket.encodeEntries(openEntries)
openEntries.removeAll()
openSize = 0
if blockSymbols.isEmpty { blockSinceMs = nowMs }
let index = blockSymbols.count
blockSymbols.append(region)
var output: [Data] = []
if let packet = packet(.data(block: block, index: index, entriesRegion: region)) {
output.append(packet)
}
if blockSymbols.count >= min(fec.maxSourceShards, VideoBurstPacket.maxBlockSourceShards) {
output += closeBlock()
}
return output
}
private func closeBlock() -> [Data] {
if blockSymbols.isEmpty { return [] }
let k = blockSymbols.count
let r = fec.parityCount(sourceCount: k, containsKeyframe: blockHasKeyframe)
var output: [Data] = []
if r > 0 {
let length = 2 + (blockSymbols.map(\.count).max() ?? 0)
let symbols = blockSymbols.map { LiveVideoSymbols.symbol($0, length: length) }
for (row, parity) in ReedSolomonErasure.encode(symbols, parityCount: r).enumerated() {
let kind = VideoBurstPacket.Kind.parity(
block: block,
parityIndex: row,
sourceCount: k,
parityCount: r,
symbol: parity
)
if let packet = packet(kind) {
output.append(packet)
parityPackets += 1
}
}
}
blockSymbols.removeAll()
blockHasKeyframe = false
block = (block + 1) & 0xFFFF
return output
}
private func packet(_ kind: VideoBurstPacket.Kind) -> Data? {
guard let encoded = VideoBurstPacket(streamID: streamID, sequence: sequence, kind: kind)?.encode() else {
return nil
}
sequence = (sequence + 1) & 0xFFFF
packetCount += 1
return encoded
}
}
+350
View File
@@ -0,0 +1,350 @@
//
// VideoBurstPacket.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
import Security
/// Video codec carried by a live video START packet.
enum LiveVideoCodec: UInt8 {
/// H.264 Constrained Baseline, Annex B access units; every IDR carries
/// SPS and PPS in-band.
case h264AnnexB = 0x01
}
/// Optional audio track codec carried by a live video START packet.
enum LiveVideoAudioCodec: UInt8 {
case none = 0x00
/// Raw (ADTS-less) AAC-LC access units, 16 kHz mono; the same encoding
/// as live voice v1.
case aacLC16kMono = 0x01
}
/// Stream parameters announced at sequence 0 and repeated before every keyframe.
struct LiveVideoConfig: Equatable {
let videoCodec: LiveVideoCodec
let width: Int
let height: Int
let fps: Int
let bitrateKbps: Int
let audioCodec: LiveVideoAudioCodec
var hasAudio: Bool { audioCodec != .none }
}
/// Media track of one entry inside a data shard.
enum LiveVideoTrack: UInt8, CaseIterable {
case video = 0
case audio = 1
}
/// One fragment (or the whole) of a media unit inside a data shard.
///
/// `[flags: UInt8][unitSeq: UInt16][ptsMs: UInt32][fragIndex: UInt8][fragCount: UInt8][length: UInt16][bytes]`
struct LiveVideoEntry: Equatable {
static let headerSize = 11
private static let trackMask: UInt8 = 0x03
private static let keyframeFlag: UInt8 = 0x04
let track: LiveVideoTrack
let keyframe: Bool
let unitSequence: Int
let ptsMs: Int64
let fragmentIndex: Int
let fragmentCount: Int
let bytes: Data
var encodedSize: Int { Self.headerSize + bytes.count }
var isValid: Bool {
(0...0xFFFF).contains(unitSequence)
&& (0...0xFFFF_FFFF).contains(ptsMs)
&& (1...0xFF).contains(fragmentCount)
&& (0..<fragmentCount).contains(fragmentIndex)
&& !bytes.isEmpty && bytes.count <= 0xFFFF
&& (!keyframe || track == .video)
}
static func encodeAll(_ entries: [LiveVideoEntry], into output: inout Data) {
for entry in entries {
output.append(entry.track.rawValue | (entry.keyframe ? keyframeFlag : 0))
output.appendU16BE(entry.unitSequence)
output.appendU32BE(entry.ptsMs)
output.append(UInt8(truncatingIfNeeded: entry.fragmentIndex))
output.append(UInt8(truncatingIfNeeded: entry.fragmentCount))
output.appendU16BE(entry.bytes.count)
output.append(entry.bytes)
}
}
/// Parses an entries region; returns nil when any entry is malformed or
/// the region is empty.
static func decodeAll(_ region: Data) -> [LiveVideoEntry]? {
let data = [UInt8](region)
var entries: [LiveVideoEntry] = []
var cursor = 0
while cursor < data.count {
guard data.count - cursor >= headerSize else { return nil }
let flags = data[cursor]
guard flags & ~(trackMask | keyframeFlag) == 0,
let track = LiveVideoTrack(rawValue: flags & trackMask)
else { return nil }
let header = cursor
let length = data.u16(header + 9)
cursor += headerSize
guard length > 0, data.count - cursor >= length else { return nil }
let entry = LiveVideoEntry(
track: track,
keyframe: flags & keyframeFlag != 0,
unitSequence: data.u16(header + 1),
ptsMs: data.u32(header + 3),
fragmentIndex: Int(data[header + 7]),
fragmentCount: Int(data[header + 8]),
bytes: Data(data[cursor..<(cursor + length)])
)
guard entry.isValid else { return nil }
entries.append(entry)
cursor += length
}
return entries.isEmpty ? nil : entries
}
}
/// One live video packet (the inner payload of `NoisePayloadType.videoFrame`,
/// and — for public mesh streams — the payload of `MessageType.videoFrame`).
///
/// Wire format (see docs/LIVE_VIDEO_V1.md):
/// ```
/// [streamID: 8][seq: UInt16 BE][kind: UInt8][body…]
/// ```
/// - kind 0x01 (START): [version=1][videoCodec][width: UInt16][height: UInt16][fps][bitrateKbps: UInt16][audioCodec]
/// - kind 0x00 (DATA): [block: UInt16][index: UInt8][entries region]
/// - kind 0x03 (PARITY): [block: UInt16][parityIndex][k][r][symbolLen: UInt16][symbol]
/// - kind 0x02 (END): [durationMs: UInt32][videoUnits: UInt16][audioUnits: UInt16][packets: UInt16]
/// - kind 0x04 (CANCELED): empty body; receivers discard the stream
struct VideoBurstPacket: Equatable {
enum Kind: Equatable {
case start(LiveVideoConfig)
/// Systematic FEC source shard: `entriesRegion` is the coded symbol body.
case data(block: Int, index: Int, entriesRegion: Data)
/// Reed-Solomon parity shard over the `sourceCount` source symbols of `block`.
case parity(block: Int, parityIndex: Int, sourceCount: Int, parityCount: Int, symbol: Data)
case end(durationMs: Int64, videoUnits: Int, audioUnits: Int, packets: Int)
case canceled
}
static let version: UInt8 = 1
static let streamIDSize = 8
static let headerSize = streamIDSize + 2 + 1
static let dataHeaderSize = headerSize + 3
static let parityHeaderSize = headerSize + 7
/// Whole-packet ceiling. Keeps a Noise-wrapped, signed, source-routed (up
/// to four hops) live video packet under the 512-byte BLE fragmentation
/// threshold.
static let maxPacketBytes = 352
/// Largest entries region: a parity symbol (`[len: UInt16][region]`) must fit too.
static let maxEntriesRegion = maxPacketBytes - parityHeaderSize - 2
static let maxBlockSourceShards = 32
static let maxBlockParityShards = 16
static let maxDimension = 1_920
static let maxFPS = 60
private enum KindByte {
static let data: UInt8 = 0x00
static let start: UInt8 = 0x01
static let end: UInt8 = 0x02
static let parity: UInt8 = 0x03
static let canceled: UInt8 = 0x04
}
let streamID: Data
let sequence: Int
let kind: Kind
init?(streamID: Data, sequence: Int, kind: Kind) {
guard streamID.count == Self.streamIDSize, (0...0xFFFF).contains(sequence) else { return nil }
let valid: Bool
switch kind {
case .start(let config):
valid = (16...Self.maxDimension).contains(config.width)
&& (16...Self.maxDimension).contains(config.height)
&& config.width % 2 == 0 && config.height % 2 == 0
&& (1...Self.maxFPS).contains(config.fps)
&& (1...0xFFFF).contains(config.bitrateKbps)
case .data(let block, let index, let region):
valid = (0...0xFFFF).contains(block)
&& (0..<Self.maxBlockSourceShards).contains(index)
&& (1...Self.maxEntriesRegion).contains(region.count)
&& LiveVideoEntry.decodeAll(region) != nil
case .parity(let block, let parityIndex, let sourceCount, let parityCount, let symbol):
valid = (0...0xFFFF).contains(block)
&& (1...Self.maxBlockSourceShards).contains(sourceCount)
&& (1...Self.maxBlockParityShards).contains(parityCount)
&& (0..<parityCount).contains(parityIndex)
&& (3...(Self.maxEntriesRegion + 2)).contains(symbol.count)
case .end(let durationMs, let videoUnits, let audioUnits, let packets):
valid = (0...0xFFFF_FFFF).contains(durationMs)
&& (0...0xFFFF).contains(videoUnits)
&& (0...0xFFFF).contains(audioUnits)
&& (0...0xFFFF).contains(packets)
case .canceled:
valid = true
}
guard valid else { return nil }
self.streamID = Data(streamID)
self.sequence = sequence
self.kind = kind
}
func encode() -> Data {
var data = Data(capacity: Self.headerSize + 64)
data.append(streamID)
data.appendU16BE(sequence)
switch kind {
case .start(let config):
data.append(KindByte.start)
data.append(Self.version)
data.append(config.videoCodec.rawValue)
data.appendU16BE(config.width)
data.appendU16BE(config.height)
data.append(UInt8(truncatingIfNeeded: config.fps))
data.appendU16BE(config.bitrateKbps)
data.append(config.audioCodec.rawValue)
case .data(let block, let index, let region):
data.append(KindByte.data)
data.appendU16BE(block)
data.append(UInt8(truncatingIfNeeded: index))
data.append(region)
case .parity(let block, let parityIndex, let sourceCount, let parityCount, let symbol):
data.append(KindByte.parity)
data.appendU16BE(block)
data.append(UInt8(truncatingIfNeeded: parityIndex))
data.append(UInt8(truncatingIfNeeded: sourceCount))
data.append(UInt8(truncatingIfNeeded: parityCount))
data.appendU16BE(symbol.count)
data.append(symbol)
case .end(let durationMs, let videoUnits, let audioUnits, let packets):
data.append(KindByte.end)
data.appendU32BE(durationMs)
data.appendU16BE(videoUnits)
data.appendU16BE(audioUnits)
data.appendU16BE(packets)
case .canceled:
data.append(KindByte.canceled)
}
return data
}
static func decode(_ data: Data) -> VideoBurstPacket? {
guard data.count >= headerSize, data.count <= maxPacketBytes else { return nil }
// Work on a zero-indexed copy so subscripting is offset-safe.
let bytes = [UInt8](data)
let streamID = Data(bytes[0..<streamIDSize])
let sequence = bytes.u16(streamIDSize)
let body = headerSize
let kind: Kind
switch bytes[streamIDSize + 2] {
case KindByte.start:
guard bytes.count == body + 10, bytes[body] == version,
let codec = LiveVideoCodec(rawValue: bytes[body + 1]),
let audio = LiveVideoAudioCodec(rawValue: bytes[body + 9])
else { return nil }
kind = .start(LiveVideoConfig(
videoCodec: codec,
width: bytes.u16(body + 2),
height: bytes.u16(body + 4),
fps: Int(bytes[body + 6]),
bitrateKbps: bytes.u16(body + 7),
audioCodec: audio
))
case KindByte.data:
guard bytes.count > body + 3 else { return nil }
kind = .data(
block: bytes.u16(body),
index: Int(bytes[body + 2]),
entriesRegion: Data(bytes[(body + 3)...])
)
case KindByte.parity:
guard bytes.count >= body + 7 else { return nil }
let length = bytes.u16(body + 5)
guard bytes.count == body + 7 + length else { return nil }
kind = .parity(
block: bytes.u16(body),
parityIndex: Int(bytes[body + 2]),
sourceCount: Int(bytes[body + 3]),
parityCount: Int(bytes[body + 4]),
symbol: Data(bytes[(body + 7)...])
)
case KindByte.end:
guard bytes.count == body + 10 else { return nil }
kind = .end(
durationMs: bytes.u32(body),
videoUnits: bytes.u16(body + 4),
audioUnits: bytes.u16(body + 6),
packets: bytes.u16(body + 8)
)
case KindByte.canceled:
guard bytes.count == body else { return nil }
kind = .canceled
default:
return nil
}
return VideoBurstPacket(streamID: streamID, sequence: sequence, kind: kind)
}
static func makeStreamID() -> Data {
var bytes = Data(count: streamIDSize)
let result = bytes.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, streamIDSize, $0.baseAddress!)
}
guard result == errSecSuccess else {
return Data((0..<streamIDSize).map { _ in UInt8.random(in: .min ... .max) })
}
return bytes
}
/// The stream ID as lowercase hex, as used in `video_<streamID>.mp4` names.
static func streamIDHex(_ streamID: Data) -> String {
streamID.map { String(format: "%02x", $0) }.joined()
}
/// Encodes an entries region; the caller keeps it within `maxEntriesRegion`.
static func encodeEntries(_ entries: [LiveVideoEntry]) -> Data {
var output = Data(capacity: entries.reduce(0) { $0 + $1.encodedSize })
LiveVideoEntry.encodeAll(entries, into: &output)
return output
}
}
// MARK: - Big-endian helpers
fileprivate extension Data {
mutating func appendU16BE(_ value: Int) {
append(UInt8((value >> 8) & 0xFF))
append(UInt8(value & 0xFF))
}
mutating func appendU32BE(_ value: Int64) {
append(UInt8((value >> 24) & 0xFF))
append(UInt8((value >> 16) & 0xFF))
append(UInt8((value >> 8) & 0xFF))
append(UInt8(value & 0xFF))
}
}
fileprivate extension Array where Element == UInt8 {
func u16(_ offset: Int) -> Int {
(Int(self[offset]) << 8) | Int(self[offset + 1])
}
func u32(_ offset: Int) -> Int64 {
(Int64(self[offset]) << 24) | (Int64(self[offset + 1]) << 16)
| (Int64(self[offset + 2]) << 8) | Int64(self[offset + 3])
}
}
@@ -0,0 +1,51 @@
//
// H264NalUnitsTests.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 H264NalUnitsTests {
private let sps = Data([0x67, 0x42, 0x00, 0x1E])
private let pps = Data([0x68, 0xCE, 0x38, 0x80])
private let idr = Data([0x65, 0x11, 0x22, 0x33])
private let filler = Data([0x0C, 0xFF, 0xFF, 0x80])
@Test func splitsMixedStartCodes() {
let data = Data([0, 0, 0, 1]) + sps + Data([0, 0, 1]) + pps + Data([0, 0, 0, 1]) + idr
let nals = H264NalUnits.split(data)
#expect(nals == [sps, pps, idr])
#expect(H264NalUnits.type(nals[2]) == H264NalUnits.typeIDR)
#expect(H264NalUnits.type(Data()) == -1)
#expect(H264NalUnits.containsType(data, H264NalUnits.typeIDR))
#expect(!H264NalUnits.containsType(data, H264NalUnits.typeFiller))
}
@Test func splitsSlicesWithNonZeroStartIndex() {
let padded = Data([0xAA]) + H264NalUnits.join([sps, idr])
#expect(H264NalUnits.split(padded[1...]) == [sps, idr])
}
@Test func liftsParameterSetsAndStripsThemForMuxing() throws {
let keyframe = H264NalUnits.join([Data([0x09, 0xF0]), sps, pps, idr])
let sets = try #require(H264NalUnits.parameterSets(keyframe))
// Raw NAL payloads, as CMVideoFormatDescriptionCreateFromH264ParameterSets expects.
#expect(sets.sps == sps)
#expect(sets.pps == pps)
#expect(H264NalUnits.withoutParameterSets(keyframe) == H264NalUnits.join([idr]))
#expect(H264NalUnits.parameterSets(H264NalUnits.join([idr])) == nil)
#expect(H264NalUnits.parameterSets(H264NalUnits.join([sps, idr])) == nil)
}
@Test func dropsFillerOnly() {
let unit = H264NalUnits.join([idr, filler])
#expect(H264NalUnits.withoutFiller(unit) == H264NalUnits.join([idr]))
let clean = H264NalUnits.join([idr])
#expect(H264NalUnits.withoutFiller(clean) == clean)
}
}
@@ -0,0 +1,70 @@
//
// LiveVideoCongestionControllerTests.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 LiveVideoCongestionControllerTests {
@Test func growingQueueBacksOffThenRecoversGradually() {
let controller = LiveVideoCongestionController(maxBitrate: 60_000)
_ = controller.onBacklog(20, nowMs: 0)
#expect(controller.bitrate == 48_000)
// Rate-limited: a second high sample inside a second does not compound.
_ = controller.onBacklog(20, nowMs: 500)
#expect(controller.bitrate == 48_000)
_ = controller.onBacklog(20, nowMs: 1_000)
#expect(controller.bitrate == 38_400)
// Calm queue: nothing for two seconds, then one step per second, capped at the preset.
var now: Int64 = 2_000
_ = controller.onBacklog(0, nowMs: now)
#expect(controller.bitrate == 38_400)
for _ in 0..<20 {
now += 1_000
_ = controller.onBacklog(0, nowMs: now)
}
#expect(controller.bitrate == 60_000)
}
@Test func deepQueueSkipsVideoAndResumesWithAKeyframe() {
let controller = LiveVideoCongestionController(maxBitrate: 60_000)
let deep = controller.onBacklog(80, nowMs: 0)
#expect(deep.skipVideo)
#expect(!deep.requestKeyframe)
#expect(controller.onBacklog(30, nowMs: 250).skipVideo)
let drained = controller.onBacklog(2, nowMs: 500)
#expect(!drained.skipVideo)
#expect(drained.requestKeyframe)
#expect(!controller.onBacklog(2, nowMs: 750).requestKeyframe)
#expect(controller.skipEpisodes == 1)
#expect(!controller.skipping)
}
@Test func bitrateNeverDropsBelowTheFloor() {
let controller = LiveVideoCongestionController(maxBitrate: 20_000)
var now: Int64 = 0
for _ in 0..<30 {
_ = controller.onBacklog(100, nowMs: now)
now += 250
}
#expect(controller.bitrate == 6_000)
}
@Test func midQueueResetsTheCalmTimer() {
let controller = LiveVideoCongestionController(maxBitrate: 60_000, minBitrate: 10_000)
_ = controller.onBacklog(20, nowMs: 0)
#expect(controller.bitrate == 48_000)
_ = controller.onBacklog(0, nowMs: 1_000)
_ = controller.onBacklog(10, nowMs: 2_500) // between low and high water
_ = controller.onBacklog(0, nowMs: 3_000)
#expect(controller.bitrate == 48_000)
_ = controller.onBacklog(0, nowMs: 5_000)
#expect(controller.bitrate == 53_000)
}
}
@@ -0,0 +1,54 @@
//
// LiveVideoQualityTests.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 LiveVideoQualityTests {
@Test func presetsMatchTheSpecification() {
#expect(LiveVideoQuality.low.width == 144 && LiveVideoQuality.low.height == 192)
#expect(LiveVideoQuality.low.fps == 8 && LiveVideoQuality.low.totalBitrate == 30_000)
#expect(LiveVideoQuality.low.fec.blockWindowMs == 600)
#expect(LiveVideoQuality.medium.fec.maxSourceShards == 16)
#expect(LiveVideoQuality.high.videoBitrate == 360_000)
#expect(LiveVideoQuality.high.fec.maxSourceShards == 32)
#expect(!LiveVideoQuality.clip.isLivePreset)
#expect(LiveVideoQuality.allCases.allSatisfy { $0.width % 16 == 0 && $0.height % 16 == 0 })
#expect(LiveVideoQuality.fromName("MEDIUM") == .medium)
#expect(LiveVideoQuality.fromName("bogus") == .low)
#expect(LiveVideoQuality.fromName(nil) == .low)
#expect(LiveVideoLimits.maxVideoFileBytes == 102_400)
}
@Test func parityCountAppliesTheFloorAndCap() {
let policy = LiveVideoFecPolicy(parityRatio: 0.2, keyframeParityRatio: 0.4)
#expect(policy.parityCount(sourceCount: 1, containsKeyframe: false) == 1)
#expect(policy.parityCount(sourceCount: 3, containsKeyframe: false) == 1)
// Two parity shards from four sources up.
#expect(policy.parityCount(sourceCount: 4, containsKeyframe: false) == 2)
#expect(policy.parityCount(sourceCount: 12, containsKeyframe: false) == 3)
#expect(policy.parityCount(sourceCount: 12, containsKeyframe: true) == 5)
#expect(LiveVideoFecPolicy(parityRatio: 1, keyframeParityRatio: 1)
.parityCount(sourceCount: 32, containsKeyframe: true) == 16)
#expect(LiveVideoQuality.clip.fec.parityCount(sourceCount: 8, containsKeyframe: true) == 0)
}
@Test func clipPresetSendsNoParity() {
let packetizer = VideoStreamPacketizer(
streamID: Data(count: 8),
config: LiveVideoConfig(videoCodec: .h264AnnexB, width: 240, height: 320, fps: 12,
bitrateKbps: 26, audioCodec: .none),
fec: LiveVideoQuality.clip.fec
)
_ = packetizer.add(LiveMediaUnit(track: .video, ptsMs: 0, keyframe: true, data: Data(repeating: 1, count: 2_000)),
nowMs: 0)
_ = packetizer.finish(durationMs: 100, nowMs: 100)
#expect(packetizer.parityPackets == 0)
}
}
@@ -0,0 +1,69 @@
//
// ReedSolomonErasureTests.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 ReedSolomonErasureTests {
@Test func fieldInverseIsConsistent() {
for value in 1...255 {
#expect(ReedSolomonErasure.multiply(value, ReedSolomonErasure.inverse(value)) == 1)
}
}
@Test func fieldUsesPolynomial0x11D() {
// x^7 * x = x^8 = x^4 + x^3 + x^2 + 1 under 0x11D.
#expect(ReedSolomonErasure.multiply(0x80, 0x02) == 0x1D)
#expect(ReedSolomonErasure.multiply(0, 0x53) == 0)
#expect(ReedSolomonErasure.coefficient(sourceCount: 1, parityRow: 0, sourceIndex: 0) == 1)
}
@Test func anyKOfKPlusRSymbolsRebuildTheBlock() throws {
let random = VideoTestRandom(seed: 1234)
for k in [1, 2, 5, 12, 32] {
for r in [1, 2, 4, 16] {
let sources = (0..<k).map { _ in random.bytes(64) }
let parity = ReedSolomonErasure.encode(sources, parityCount: r)
#expect(parity.count == r)
for _ in 0..<20 {
let lostCount = random.int(0..<(min(k, r) + 1))
let lost = Set(random.shuffled(Array(0..<k)).prefix(lostCount))
var keptParity: [Int: Data] = [:]
for row in random.shuffled(Array(0..<r)).prefix(lostCount) {
keptParity[row] = parity[row]
}
let slots: [Data?] = sources.enumerated().map { lost.contains($0.offset) ? nil : $0.element }
let rebuilt = try #require(ReedSolomonErasure.reconstruct(slots, parities: keptParity))
#expect(rebuilt == sources, "k=\(k) r=\(r) lost=\(lost.sorted())")
}
}
}
}
@Test func tooFewSymbolsCannotRebuild() {
let sources = (0..<4).map { index in Data((0..<8).map { UInt8(index * 8 + $0) }) }
let parity = ReedSolomonErasure.encode(sources, parityCount: 1)
let slots: [Data?] = [nil, sources[1], nil, sources[3]]
#expect(ReedSolomonErasure.reconstruct(slots, parities: [0: parity[0]]) == nil)
}
@Test func mismatchedLengthsCannotRebuild() {
let sources = (0..<2).map { index in Data(repeating: UInt8(index + 1), count: 8) }
let parity = ReedSolomonErasure.encode(sources, parityCount: 1)
#expect(ReedSolomonErasure.reconstruct([nil, sources[1]], parities: [0: parity[0].prefix(7)]) == nil)
}
@Test func singleSourceParityIsARepetition() throws {
let source = Data([1, 2, 3, 4])
let parity = ReedSolomonErasure.encode([source], parityCount: 1)
#expect(parity[0] == source)
let rebuilt = try #require(ReedSolomonErasure.reconstruct([nil], parities: [0: parity[0]]))
#expect(rebuilt[0] == source)
}
}
@@ -0,0 +1,201 @@
//
// VideoBurstPacketTests.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 VideoBurstPacketTests {
private let streamID = Data((0..<8).map { UInt8($0 + 1) })
private let config = LiveVideoConfig(
videoCodec: .h264AnnexB,
width: 144,
height: 192,
fps: 8,
bitrateKbps: 24,
audioCodec: .aacLC16kMono
)
private func hex(_ value: String) -> Data {
let digits = Array(value.replacingOccurrences(of: " ", with: ""))
return Data(stride(from: 0, to: digits.count, by: 2).map { UInt8(String(digits[$0...$0 + 1]), radix: 16)! })
}
private func packet(_ sequence: Int, _ kind: VideoBurstPacket.Kind) throws -> VideoBurstPacket {
try #require(VideoBurstPacket(streamID: streamID, sequence: sequence, kind: kind))
}
private func mutated(_ data: Data, _ changes: [Int: UInt8]) -> Data {
var bytes = [UInt8](data)
for (index, value) in changes { bytes[index] = value }
return Data(bytes)
}
// MARK: - Round trips
@Test func everyKindRoundTrips() throws {
let entries = [
LiveVideoEntry(track: .video, keyframe: true, unitSequence: 7, ptsMs: 1_000,
fragmentIndex: 0, fragmentCount: 2, bytes: Data(repeating: 1, count: 40)),
LiveVideoEntry(track: .audio, keyframe: false, unitSequence: 9, ptsMs: 1_064,
fragmentIndex: 0, fragmentCount: 1, bytes: Data([5, 6, 7]))
]
let region = VideoBurstPacket.encodeEntries(entries)
let kinds: [VideoBurstPacket.Kind] = [
.start(config),
.data(block: 3, index: 1, entriesRegion: region),
.parity(block: 3, parityIndex: 0, sourceCount: 4, parityCount: 2,
symbol: Data((0..<60).map { UInt8($0) })),
.end(durationMs: 12_345, videoUnits: 99, audioUnits: 190, packets: 777),
.canceled
]
for (sequence, kind) in kinds.enumerated() {
let original = try packet(sequence, kind)
let decoded = try #require(VideoBurstPacket.decode(original.encode()))
#expect(decoded.streamID == streamID)
#expect(decoded.sequence == sequence)
#expect(decoded.kind == kind)
#expect(decoded == original)
}
#expect(LiveVideoEntry.decodeAll(region) == entries)
}
@Test func decodesFromNonZeroIndexedSlices() throws {
let encoded = try packet(9, .end(durationMs: 1, videoUnits: 2, audioUnits: 3, packets: 4)).encode()
let padded = Data([0xFF, 0xFF]) + encoded
let slice = padded[2...]
#expect(slice.startIndex == 2)
let decoded = try #require(VideoBurstPacket.decode(slice))
#expect(decoded.kind == .end(durationMs: 1, videoUnits: 2, audioUnits: 3, packets: 4))
}
// MARK: - Golden vectors (docs/LIVE_VIDEO_V1.md)
@Test func goldenVectorsMatchSpecification() throws {
let entry = LiveVideoEntry(track: .video, keyframe: true, unitSequence: 1, ptsMs: 64,
fragmentIndex: 0, fragmentCount: 1, bytes: hex("DEADBE"))
let vectors: [(String, VideoBurstPacket)] = [
("01 02 03 04 05 06 07 08 00 00 01 01 01 00 90 00 C0 08 00 18 01",
try packet(0, .start(config))),
("01 02 03 04 05 06 07 08 00 05 00 00 02 00 04 00 01 00 00 00 40 00 01 00 03 DE AD BE",
try packet(5, .data(block: 2, index: 0, entriesRegion: VideoBurstPacket.encodeEntries([entry])))),
("01 02 03 04 05 06 07 08 00 06 03 00 02 00 01 01 00 03 AA BB CC",
try packet(6, .parity(block: 2, parityIndex: 0, sourceCount: 1, parityCount: 1, symbol: hex("AABBCC")))),
("01 02 03 04 05 06 07 08 00 2A 02 00 00 0A 80 00 10 00 29 00 2A",
try packet(42, .end(durationMs: 2_688, videoUnits: 16, audioUnits: 41, packets: 42))),
("01 02 03 04 05 06 07 08 00 03 04",
try packet(3, .canceled))
]
for (wire, expected) in vectors {
#expect(expected.encode() == hex(wire))
#expect(VideoBurstPacket.decode(hex(wire)) == expected)
}
guard case .data(_, _, let region) = try packet(5, .data(block: 2, index: 0,
entriesRegion: VideoBurstPacket.encodeEntries([entry]))).kind
else {
Issue.record("expected data")
return
}
#expect(LiveVideoEntry.decodeAll(region) == [entry])
}
// MARK: - Validation
@Test func malformedPacketsAreRejected() throws {
let start = try packet(0, .start(config)).encode()
#expect(VideoBurstPacket.decode(start.prefix(start.count - 1)) == nil)
#expect(VideoBurstPacket.decode(start + Data([0])) == nil)
#expect(VideoBurstPacket.decode(mutated(start, [11: 0x09])) == nil) // version
#expect(VideoBurstPacket.decode(mutated(start, [12: 0x02])) == nil) // video codec
#expect(VideoBurstPacket.decode(mutated(start, [20: 0x02])) == nil) // audio codec
#expect(VideoBurstPacket.decode(mutated(start, [10: 0x07])) == nil) // kind
#expect(VideoBurstPacket.decode(Data(count: VideoBurstPacket.maxPacketBytes + 1)) == nil)
#expect(VideoBurstPacket.decode(Data(count: VideoBurstPacket.headerSize - 1)) == nil)
let entry = LiveVideoEntry(track: .audio, keyframe: false, unitSequence: 1, ptsMs: 0,
fragmentIndex: 0, fragmentCount: 1, bytes: Data([1, 2]))
let data = try packet(1, .data(block: 0, index: 0, entriesRegion: VideoBurstPacket.encodeEntries([entry]))).encode()
#expect(VideoBurstPacket.decode(data) != nil)
// Truncated entry, unknown flag bits, keyframe audio, and zero-length entries.
#expect(VideoBurstPacket.decode(data.prefix(data.count - 1)) == nil)
#expect(VideoBurstPacket.decode(mutated(data, [14: 0x08])) == nil)
#expect(VideoBurstPacket.decode(mutated(data, [14: 0x05])) == nil)
#expect(VideoBurstPacket.decode(mutated(data, [23: 0, 24: 0])) == nil)
// Fragment index beyond its count; zero fragment count.
#expect(VideoBurstPacket.decode(mutated(data, [21: 1])) == nil)
#expect(VideoBurstPacket.decode(mutated(data, [22: 0])) == nil)
// Shard index must be below 32; empty entries region.
#expect(VideoBurstPacket.decode(mutated(data, [13: 32])) == nil)
#expect(VideoBurstPacket.decode(data.prefix(VideoBurstPacket.dataHeaderSize)) == nil)
let parity = try packet(2, .parity(block: 0, parityIndex: 1, sourceCount: 4, parityCount: 2,
symbol: Data(repeating: 3, count: 10))).encode()
#expect(VideoBurstPacket.decode(parity.prefix(parity.count - 1)) == nil) // symbolLen mismatch
#expect(VideoBurstPacket.decode(mutated(parity, [14: 0])) == nil) // k = 0
#expect(VideoBurstPacket.decode(mutated(parity, [14: 33])) == nil) // k > 32
#expect(VideoBurstPacket.decode(mutated(parity, [15: 17])) == nil) // r > 16
#expect(VideoBurstPacket.decode(mutated(parity, [13: 2])) == nil) // parityIndex >= r
let end = try packet(3, .end(durationMs: 1, videoUnits: 1, audioUnits: 1, packets: 1)).encode()
#expect(VideoBurstPacket.decode(end + Data([0])) == nil)
let canceled = try packet(4, .canceled).encode()
#expect(VideoBurstPacket.decode(canceled + Data([0])) == nil)
}
@Test func invalidFieldsAreRejectedAtConstruction() {
func start(width: Int = 144, height: Int = 192, fps: Int = 8, kbps: Int = 24) -> VideoBurstPacket? {
VideoBurstPacket(streamID: streamID, sequence: 0, kind: .start(LiveVideoConfig(
videoCodec: .h264AnnexB, width: width, height: height, fps: fps,
bitrateKbps: kbps, audioCodec: .none)))
}
#expect(start() != nil)
#expect(start(width: 145) == nil)
#expect(start(width: 14) == nil)
#expect(start(height: 1_922) == nil)
#expect(start(width: 1_920, height: 1_920) != nil)
#expect(start(fps: 0) == nil)
#expect(start(fps: 61) == nil)
#expect(start(kbps: 0) == nil)
#expect(start(kbps: 0x10000) == nil)
#expect(VideoBurstPacket(streamID: Data(count: 7), sequence: 0, kind: .canceled) == nil)
#expect(VideoBurstPacket(streamID: streamID, sequence: 0x10000, kind: .canceled) == nil)
#expect(VideoBurstPacket(streamID: streamID, sequence: -1, kind: .canceled) == nil)
#expect(VideoBurstPacket(streamID: streamID, sequence: 0,
kind: .end(durationMs: 0x1_0000_0000, videoUnits: 0, audioUnits: 0, packets: 0)) == nil)
#expect(VideoBurstPacket(streamID: streamID, sequence: 0,
kind: .data(block: 0, index: 0, entriesRegion: Data([1, 2, 3]))) == nil)
}
@Test func maximalPacketsStayWithinBudget() throws {
#expect(VideoBurstPacket.maxEntriesRegion == 332)
let fullEntry = LiveVideoEntry(
track: .video, keyframe: false, unitSequence: 1, ptsMs: 0, fragmentIndex: 0, fragmentCount: 1,
bytes: Data(repeating: 7, count: VideoBurstPacket.maxEntriesRegion - LiveVideoEntry.headerSize)
)
let data = try packet(1, .data(block: 0, index: 0,
entriesRegion: VideoBurstPacket.encodeEntries([fullEntry]))).encode()
let parity = try packet(2, .parity(block: 0, parityIndex: 0, sourceCount: 1, parityCount: 1,
symbol: Data(count: VideoBurstPacket.maxEntriesRegion + 2))).encode()
#expect(data.count <= VideoBurstPacket.maxPacketBytes)
#expect(parity.count == VideoBurstPacket.maxPacketBytes)
#expect(VideoBurstPacket.decode(parity) != nil)
#expect(VideoBurstPacket(streamID: streamID, sequence: 2, kind: .parity(
block: 0, parityIndex: 0, sourceCount: 1, parityCount: 1,
symbol: Data(count: VideoBurstPacket.maxEntriesRegion + 3))) == nil)
}
// MARK: - Stream IDs
@Test func streamIDsAreRandomAndHexEncoded() {
let first = VideoBurstPacket.makeStreamID()
let second = VideoBurstPacket.makeStreamID()
#expect(first.count == VideoBurstPacket.streamIDSize)
#expect(first != second)
#expect(VideoBurstPacket.streamIDHex(Data([0x01, 0xAB, 0x00, 0xFF, 0x10, 0x20, 0x30, 0x40])) == "01ab00ff10203040")
}
}
@@ -0,0 +1,375 @@
//
// VideoStreamLossSimulationTests.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
/// Packetizer -> lossy, reordering channel -> assembler, with synthetic units and a fake clock.
struct VideoStreamLossSimulationTests {
private let config = LiveVideoConfig(
videoCodec: .h264AnnexB,
width: 144,
height: 192,
fps: 8,
bitrateKbps: 24,
audioCodec: .aacLC16kMono
)
private struct SentUnit {
let keyframe: Bool
let data: Data
}
private struct VideoOut {
let sequence: Int64
let ptsMs: Int64
let keyframe: Bool
let data: Data
}
private struct Result {
let outputs: [LiveVideoOutput]
let sentVideo: [SentUnit]
let sentAudio: [SentUnit]
let assembler: VideoStreamAssembler
let packetizer: VideoStreamPacketizer
var video: [VideoOut] { videoOutputs(outputs) }
var audio: [Data] {
outputs.compactMap { if case .audio(_, _, let data) = $0 { return data } else { return nil } }
}
var ended: Bool { outputs.contains { if case .ended = $0 { return true } else { return false } } }
}
private static func videoOutputs(_ outputs: [LiveVideoOutput]) -> [VideoOut] {
outputs.compactMap {
if case .video(let sequence, let pts, let keyframe, let data) = $0 {
return VideoOut(sequence: sequence, ptsMs: pts, keyframe: keyframe, data: data)
}
return nil
}
}
private func videoOutputs(_ outputs: [LiveVideoOutput]) -> [VideoOut] {
Self.videoOutputs(outputs)
}
private static func count(_ outputs: [LiveVideoOutput], where match: (LiveVideoOutput) -> Bool) -> Int {
outputs.filter(match).count
}
private static func isEnded(_ output: LiveVideoOutput) -> Bool {
if case .ended = output { return true }
return false
}
/// 10 s stream: 8 fps video with a 2 s GOP (keyframes ~2.4 KB, deltas
/// 120-260 B) and 64 ms audio frames (~96 B). `lose` decides per packet
/// whether the channel drops it.
private func run(
seed: UInt64,
fec: LiveVideoFecPolicy = LiveVideoFecPolicy(parityRatio: 0.25, keyframeParityRatio: 0.5),
reorderMs: Int64 = 0,
lose: @escaping (Int, Data) -> Bool
) throws -> Result {
let random = VideoTestRandom(seed: seed)
let packetizer = VideoStreamPacketizer(streamID: Data(repeating: 9, count: 8), config: config, fec: fec)
let assembler = VideoStreamAssembler()
var sentVideo: [SentUnit] = []
var sentAudio: [SentUnit] = []
var inFlight: [(due: Int64, order: Int, packet: Data)] = []
var outputs: [LiveVideoOutput] = []
var packetIndex = 0
func send(_ now: Int64, _ packets: [Data]) {
for packet in packets {
let index = packetIndex
packetIndex += 1
if !lose(index, packet) {
let delay = reorderMs > 0 ? Int64(random.int(0..<Int(reorderMs))) : 0
inFlight.append((now + delay, index, packet))
}
}
}
func deliver(_ now: Int64) throws {
let due = inFlight.filter { $0.due <= now }.sorted { ($0.due, $0.order) < ($1.due, $1.order) }
inFlight.removeAll { $0.due <= now }
for item in due {
let packet = try #require(VideoBurstPacket.decode(item.packet))
outputs += assembler.onPacket(packet, sizeBytes: item.packet.count, nowMs: now)
}
outputs += assembler.onTick(nowMs: now)
}
send(0, packetizer.start())
var nextVideo: Int64 = 0
var nextAudio: Int64 = 0
var frame = 0
for now in stride(from: Int64(0), through: 10_000, by: 4) {
if now >= nextVideo {
let key = frame % 16 == 0
let data = random.bytes(key ? 2_400 : random.int(120..<260))
sentVideo.append(SentUnit(keyframe: key, data: data))
send(now, packetizer.add(LiveMediaUnit(track: .video, ptsMs: now, keyframe: key, data: data), nowMs: now))
frame += 1
nextVideo += 125
}
if now >= nextAudio {
let data = random.bytes(random.int(80..<110))
sentAudio.append(SentUnit(keyframe: false, data: data))
send(now, packetizer.add(LiveMediaUnit(track: .audio, ptsMs: now, keyframe: false, data: data), nowMs: now))
nextAudio += 64
}
send(now, packetizer.tick(nowMs: now))
try deliver(now)
}
send(10_000, packetizer.finish(durationMs: 10_000, nowMs: 10_000))
for now in stride(from: Int64(10_000), through: 13_000, by: 10) { try deliver(now) }
if !assembler.isFinished { outputs += assembler.flush() }
return Result(outputs: outputs, sentVideo: sentVideo, sentAudio: sentAudio,
assembler: assembler, packetizer: packetizer)
}
@Test func losslessChannelDeliversEveryUnitInOrder() throws {
let result = try run(seed: 1) { _, _ in false }
#expect(result.video.count == result.sentVideo.count)
#expect(result.audio.count == result.sentAudio.count)
for (index, unit) in result.video.enumerated() {
#expect(unit.data == result.sentVideo[index].data)
#expect(unit.keyframe == result.sentVideo[index].keyframe)
#expect(unit.sequence == Int64(index))
}
for (index, data) in result.audio.enumerated() {
#expect(data == result.sentAudio[index].data)
}
#expect(result.ended)
#expect(Self.count(result.outputs, where: Self.isEnded) == 1)
#expect(result.assembler.stats().skippedVideoUnits == 0)
#expect(result.assembler.stats().recentLoss == 0)
#expect(result.assembler.endReceived)
#expect(result.assembler.config == config)
#expect(result.packetizer.unitsEmitted(.video) == result.sentVideo.count)
#expect(result.packetizer.unitsEmitted(.audio) == result.sentAudio.count)
#expect(result.packetizer.droppedUnits == 0)
}
@Test func aggregationKeepsPacketsFull() throws {
let result = try run(seed: 2) { _, _ in false }
let bytes = result.sentVideo.reduce(0) { $0 + $1.data.count } + result.sentAudio.reduce(0) { $0 + $1.data.count }
let sourcePackets = result.packetizer.packetCount - result.packetizer.parityPackets
// Far fewer packets than units: small audio/delta units share shards.
#expect(sourcePackets < (result.sentVideo.count + result.sentAudio.count) * 2 / 3)
#expect(bytes / sourcePackets > 180)
}
@Test(arguments: Array(UInt64(70)..<UInt64(78)))
func fecRepairsIndependentLossWithoutVisibleGaps(seed: UInt64) throws {
let loss = VideoTestRandom(seed: seed)
let result = try run(seed: seed, reorderMs: 120) { _, _ in loss.double() < 0.05 }
let stats = result.assembler.stats()
#expect(stats.recoveredShards > 0, "recovered \(stats.recoveredShards)")
// 5% random loss is mostly absorbed by parity; a rare unrecoverable
// block costs at most the rest of its GOP.
#expect(Double(result.video.count) >= Double(result.sentVideo.count) * 0.8,
"video \(result.video.count)/\(result.sentVideo.count)")
#expect(Double(result.audio.count) >= Double(result.sentAudio.count) * 0.95,
"audio \(result.audio.count)/\(result.sentAudio.count)")
#expect(result.ended)
}
@Test func heavyBurstLossFreezesUntilNextKeyframeAndNeverEmitsBrokenDeltas() throws {
// Drop 40 consecutive packets (an entire GOP's worth of shards plus its parity).
let result = try run(seed: 4) { index, _ in (60...99).contains(index) }
var sentByContent: [Data: SentUnit] = [:]
for unit in result.sentVideo { sentByContent[unit.data] = unit }
var chainValid = false
var previousSequence: Int64 = -1
for unit in result.video {
#expect(sentByContent[unit.data] != nil)
if unit.keyframe { chainValid = true }
#expect(chainValid, "delta emitted without an intact chain")
if !unit.keyframe { #expect(unit.sequence == previousSequence + 1) }
previousSequence = unit.sequence
}
#expect(result.assembler.stats().skippedVideoUnits > 0)
// Recovers at the next keyframe and keeps playing.
#expect(result.video.count > result.sentVideo.count / 2)
}
@Test func lateJoinerStartsAtTheFirstKeyframe() throws {
let result = try run(seed: 5) { index, _ in index < 150 }
let first = try #require(result.video.first)
#expect(first.keyframe)
#expect(result.outputs.contains { if case .config = $0 { return true } else { return false } })
}
@Test func duplicatedPacketsAreIgnored() throws {
let packetizer = VideoStreamPacketizer(
streamID: Data(count: 8), config: config,
fec: LiveVideoFecPolicy(parityRatio: 0.25, keyframeParityRatio: 0.5)
)
let assembler = VideoStreamAssembler()
let packets = packetizer.start()
+ packetizer.add(LiveMediaUnit(track: .video, ptsMs: 0, keyframe: true, data: Data(repeating: 3, count: 900)), nowMs: 0)
+ packetizer.finish(durationMs: 1_000, nowMs: 1_000)
var outputs: [LiveVideoOutput] = []
for bytes in packets + packets {
let packet = try #require(VideoBurstPacket.decode(bytes))
outputs += assembler.onPacket(packet, sizeBytes: bytes.count, nowMs: 0)
}
#expect(videoOutputs(outputs).count == 1)
#expect(Self.count(outputs, where: Self.isEnded) == 1)
#expect(outputs.last == .ended(durationMs: 1_000))
}
@Test func streamResumesAfterALongSilenceAtTheNextKeyframe() throws {
// 10 s of total silence mid-stream (a link dropout); the viewer drains
// what it has, keeps the stream open, and carries on at the first
// keyframe after the gap.
var silenceDrained = false
let packetizer = VideoStreamPacketizer(
streamID: Data(repeating: 4, count: 8), config: config,
fec: LiveVideoFecPolicy(parityRatio: 0.2, keyframeParityRatio: 0.4)
)
let assembler = VideoStreamAssembler()
var outputs: [LiveVideoOutput] = []
let random = VideoTestRandom(seed: 9)
func deliver(_ packets: [Data], _ now: Int64, silent: Bool) throws {
if silent { return }
for bytes in packets {
let packet = try #require(VideoBurstPacket.decode(bytes))
outputs += assembler.onPacket(packet, sizeBytes: bytes.count, nowMs: now)
}
}
try deliver(packetizer.start(), 0, silent: false)
var frame = 0
for now in stride(from: Int64(0), through: 30_000, by: 125) {
let silent = (10_000..<20_000).contains(now)
if silent && !silenceDrained && now >= 14_000 {
outputs += assembler.drain()
silenceDrained = true
}
let key = frame % 16 == 0
let data = random.bytes(key ? 2_000 : random.int(100..<200))
try deliver(packetizer.add(LiveMediaUnit(track: .video, ptsMs: now, keyframe: key, data: data), nowMs: now),
now, silent: silent)
try deliver(packetizer.tick(nowMs: now), now, silent: silent)
outputs += assembler.onTick(nowMs: now)
frame += 1
}
try deliver(packetizer.finish(durationMs: 30_000, nowMs: 30_000), 30_000, silent: false)
outputs += assembler.onTick(nowMs: 31_000)
let video = videoOutputs(outputs)
let before = video.filter { $0.ptsMs < 10_000 }.count
let after = video.filter { $0.ptsMs >= 20_000 }
#expect(before >= 75, "before \(before)")
#expect(after.count >= 60, "resumed \(after.count)")
#expect(after.first?.keyframe == true)
#expect(silenceDrained)
#expect(Self.count(outputs, where: Self.isEnded) == 1)
}
// MARK: - Assembler edge cases
private func dataPacket(block: Int, sequence: Int, entries: [LiveVideoEntry]) throws -> VideoBurstPacket {
try #require(VideoBurstPacket(
streamID: Data(count: 8),
sequence: sequence,
kind: .data(block: block, index: 0, entriesRegion: VideoBurstPacket.encodeEntries(entries))
))
}
private func unit(_ track: LiveVideoTrack, _ sequence: Int, keyframe: Bool = false) -> LiveVideoEntry {
LiveVideoEntry(track: track, keyframe: keyframe, unitSequence: sequence, ptsMs: Int64(sequence),
fragmentIndex: 0, fragmentCount: 1, bytes: Data([UInt8(truncatingIfNeeded: sequence)]))
}
@Test func unitSequencesExpandAcrossThe16BitWrap() throws {
let assembler = VideoStreamAssembler()
var outputs: [LiveVideoOutput] = []
for (index, sequence) in [65_534, 65_535, 0, 1].enumerated() {
let packet = try dataPacket(block: index, sequence: index,
entries: [unit(.video, sequence, keyframe: index == 0)])
outputs += assembler.onPacket(packet, sizeBytes: 0, nowMs: 0)
}
#expect(videoOutputs(outputs).map(\.sequence) == [65_534, 65_535, 65_536, 65_537])
#expect(VideoStreamAssembler.expand(2, reference: 65_535) == 65_538)
#expect(VideoStreamAssembler.expand(65_535, reference: 65_538) == 65_535)
#expect(VideoStreamAssembler.expand(65_535, reference: 0) == -1)
#expect(VideoStreamAssembler.expandCount(3, reference: 65_537) == 65_539)
#expect(VideoStreamAssembler.expandCount(0, reference: 0) == 0)
}
@Test func gapIsSkippedAfterTheDeadlineAndBreaksTheVideoChain() throws {
let assembler = VideoStreamAssembler(gapMs: 900)
var outputs: [LiveVideoOutput] = []
outputs += assembler.onPacket(try dataPacket(block: 0, sequence: 0, entries: [unit(.video, 0, keyframe: true)]),
sizeBytes: 0, nowMs: 0)
// Unit 1 lost; unit 2 (a delta) waits for it.
outputs += assembler.onPacket(try dataPacket(block: 1, sequence: 2, entries: [unit(.video, 2)]),
sizeBytes: 0, nowMs: 100)
#expect(videoOutputs(outputs).count == 1)
#expect(assembler.onTick(nowMs: 999).isEmpty)
let skipped = assembler.onTick(nowMs: 1_000)
// The gap is skipped, and the delta after it is withheld rather than decoded.
#expect(skipped == [.videoSkipped(1), .videoSkipped(1)])
#expect(assembler.stats().skippedVideoUnits == 2)
let resumed = assembler.onPacket(try dataPacket(block: 2, sequence: 3, entries: [unit(.video, 3, keyframe: true)]),
sizeBytes: 0, nowMs: 1_100)
#expect(videoOutputs(resumed).map(\.sequence) == [3])
}
@Test func readyBacklogBeyondTheCapSkipsTheHeadGap() throws {
let assembler = VideoStreamAssembler()
var outputs: [LiveVideoOutput] = []
outputs += assembler.onPacket(try dataPacket(block: 0, sequence: 0, entries: [unit(.audio, 0)]),
sizeBytes: 0, nowMs: 0)
// Unit 1 never arrives; 193 later units pile up behind it.
for sequence in 2...194 {
outputs += assembler.onPacket(try dataPacket(block: sequence, sequence: sequence, entries: [unit(.audio, sequence)]),
sizeBytes: 0, nowMs: 0)
}
let released: [Int64] = outputs.compactMap { if case .audio(let sequence, _, _) = $0 { return sequence } else { return nil } }
#expect(released == [0] + (2...194).map { Int64($0) })
#expect(assembler.stats().audioUnits == 194)
}
@Test func cancelEndsTheStreamImmediately() throws {
let assembler = VideoStreamAssembler()
let cancel = try #require(VideoBurstPacket(streamID: Data(count: 8), sequence: 1, kind: .canceled))
#expect(assembler.onPacket(cancel, sizeBytes: 11, nowMs: 0) == [.canceled])
#expect(assembler.isFinished)
#expect(assembler.onPacket(try dataPacket(block: 0, sequence: 2, entries: [unit(.audio, 0)]),
sizeBytes: 0, nowMs: 0).isEmpty)
#expect(assembler.flush().isEmpty)
}
@Test func flushEndsOnceWithoutAnEndPacket() throws {
let assembler = VideoStreamAssembler()
_ = assembler.onPacket(try dataPacket(block: 0, sequence: 0, entries: [unit(.video, 0, keyframe: true)]),
sizeBytes: 0, nowMs: 0)
#expect(assembler.flush() == [.ended(durationMs: 0)])
#expect(assembler.isFinished)
#expect(assembler.flush().isEmpty)
}
@Test func recentLossReflectsMissingSequences() throws {
let assembler = VideoStreamAssembler()
for sequence in stride(from: 0, to: 128, by: 2) {
_ = assembler.onPacket(try dataPacket(block: sequence, sequence: sequence, entries: [unit(.audio, sequence)]),
sizeBytes: 10, nowMs: 0)
}
let stats = assembler.stats()
#expect(stats.packets == 64)
#expect(stats.bytes == 640)
#expect(abs(stats.recentLoss - (1.0 - 64.0 / 127.0)) < 1e-9)
}
}
@@ -0,0 +1,51 @@
//
// VideoTestRandom.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Deterministic SplitMix64 source so the video loss simulations replay
/// identically on every run.
final class VideoTestRandom: RandomNumberGenerator {
private var state: UInt64
init(seed: UInt64) {
state = seed
}
func next() -> UInt64 {
state &+= 0x9E37_79B9_7F4A_7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
return z ^ (z >> 31)
}
/// Uniform in `range` (lower bound inclusive, upper bound exclusive).
func int(_ range: Range<Int>) -> Int {
var generator = self
return Int.random(in: range, using: &generator)
}
func double() -> Double {
var generator = self
return Double.random(in: 0..<1, using: &generator)
}
func bytes(_ count: Int) -> Data {
var data = Data(count: count)
for index in 0..<count {
data[index] = UInt8(truncatingIfNeeded: next())
}
return data
}
func shuffled<T>(_ values: [T]) -> [T] {
var generator = self
return values.shuffled(using: &generator)
}
}