Files
Vorleser-Kit/docs/AUDIO_PIPELINE.md
T

97 lines
4.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Audio pipeline
Module: `VorleserAudio`. It depends only on AVFoundation. It knows nothing about Ollama or text.
## Interface
```swift
public struct AudioChunk: Sendable {
public let epoch: UInt64
public let segmentID: Int
public let samples: [Float] // mono, 24 kHz, already converted from Int16
public let isLastOfSegment: Bool
}
public enum AudioEvent: Sendable {
case segmentStarted(epoch: UInt64, segmentID: Int)
case segmentFinished(epoch: UInt64, segmentID: Int)
case starved(epoch: UInt64) // nothing left scheduled, not finished
case routeChanged // engine reconfigured; session should re-seek
case failed(String)
}
public protocol AudioPlaying: AnyObject, Sendable {
var events: AsyncStream<AudioEvent> { get }
func schedule(_ chunk: AudioChunk)
func play() throws
func pause()
func stopAndFlush() // drops everything scheduled
func setRate(_ rate: Float) // 0.5 ... 2.0
func elapsedInCurrentSegment() -> TimeInterval?
}
```
A `FakeAudioPlayer` that records calls and emits events on demand must exist in the test target from M3 onwards. `ReadingSession` tests run against it.
## Graph
```
AVAudioPlayerNode ──▶ AVAudioUnitTimePitch ──▶ engine.mainMixerNode ──▶ outputNode
format: Float32, 24_000 Hz, 1 ch, non-interleaved
```
- Connect player → timePitch with the 24 kHz mono format. The mixer handles sample-rate conversion to the device rate.
- `timePitch.rate = playbackRate` (0.5–2.0). `timePitch.pitch = 0`. Rate changes apply live without rescheduling.
- `timePitch.overlap` default (8). If the speech sounds phasey at 1.5–2.0×, increase it and evaluate.
## PCM conversion
```swift
// data: PCM16LE bytes, even length guaranteed by the client
let count = data.count / 2
var floats = [Float](repeating: 0, count: count)
data.withUnsafeBytes { raw in
let src = raw.bindMemory(to: Int16.self)
for i in 0..<count { floats[i] = Float(Int16(littleEndian: src[i])) / 32768.0 }
}
```
Use `vDSP.convertElements` + `vDSP.multiply` (Accelerate) once the scalar version is covered by tests.
## Scheduling
- Wrap each chunk in an `AVAudioPCMBuffer` (`frameCapacity = samples.count`).
- `player.scheduleBuffer(buf, completionCallbackType: .dataPlayedBack) { _ in … }`.
- Keep a counter `scheduledFramesAhead` (incremented on schedule, decremented in callback). When it reaches 0 and the last callback was not `isLastOfSegment` of the final segment → emit `.starved`.
- Emit `.segmentStarted` when the **first** chunk of a segment is scheduled while the player is idle, or when the preceding segment's last chunk finishes. Emit `.segmentFinished` on the `isLastOfSegment` callback.
- Ignore callbacks whose `epoch` ≠ current epoch. `stopAndFlush()` triggers callbacks for dropped buffers, and these must not be reported as finished.
## Elapsed time
Track `segmentStartSampleTime` when a segment starts:
```swift
guard let nodeTime = player.lastRenderTime,
let t = player.playerTime(forNodeTime: nodeTime) else { return nil }
return Double(t.sampleTime - segmentStartSampleTime) / t.sampleRate
```
Note: `playerTime` is in the player's own timeline and is **not** affected by timePitch rate. The value represents content time. That is the right input for the "1.5 s → restart current sentence" rule.
## Engine lifecycle
- Create the engine once. Call `engine.prepare()` at launch. Call `start()` on the first `play()`.
- Idle timer: 30 s after `stopAndFlush()` or finish → `engine.stop()`, which releases the device and lets the system sleep.
- Observe `.AVAudioEngineConfigurationChange` → rebuild connections, `engine.start()`, emit `.routeChanged`. The session responds by seeking to the current segment start (cached PCM makes this instant).
## Edge cases to test
| Case | Expected |
|---|---|
| Pause during preparing | Stays paused when first audio arrives. Audio is scheduled but not played. |
| Seek while a chunk callback is in flight | Old-epoch callback ignored, no spurious `segmentFinished` |
| Rate change while paused | Applied on resume |
| Headphones unplugged mid-sentence | `.routeChanged` → restart current segment |
| Zero-length segment audio (server returned 0 bytes) | Treat as finished immediately. Log at `.error`. |
| Very long segment (1,500 chars ≈ 90 s audio) | Streams. Memory bounded by chunk scheduling. |