geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import AVFoundation
import Copus
import Foundation
enum NativeOpusError: Error {
case invalidFormat
case invalidPacket
case decode(Int32)
case emptyStream
case engineUnavailable
}
/// Confined to NativeOpusPCMSource. libopus emits interleaved samples; the
/// player node receives separate Float32 channels at the Opus 48 kHz clock.
final class NativeOpusDecoder {
private let decoder: OpaquePointer
private let channels: Int
private let gain: Float
let format: AVAudioFormat
init(channels: Int, outputGainDB: Double) throws {
guard (1...2).contains(channels), outputGainDB.isFinite,
let format = AVAudioFormat(
commonFormat: .pcmFormatFloat32, sampleRate: 48_000,
channels: 2, interleaved: false)
else { throw NativeOpusError.invalidFormat }
var error: Int32 = 0
guard let decoder = opus_decoder_create(48_000, Int32(channels), &error), error == 0 else {
throw NativeOpusError.decode(error)
}
self.decoder = decoder
self.channels = channels
self.format = format
self.gain = Float(pow(10, outputGainDB / 20))
}
deinit { opus_decoder_destroy(decoder) }
func reset() throws {
let result = opus_decoder_init(decoder, 48_000, Int32(channels))
guard result == 0 else { throw NativeOpusError.decode(result) }
}
func decode(_ data: Data) throws -> AVAudioPCMBuffer {
guard !data.isEmpty, data.count <= 65_536 else { throw NativeOpusError.invalidPacket }
return try data.withUnsafeBytes { bytes in
guard let packet = bytes.bindMemory(to: UInt8.self).baseAddress else {
throw NativeOpusError.invalidPacket
}
let frames = opus_decoder_get_nb_samples(decoder, packet, Int32(data.count))
guard frames > 0, frames <= 5_760 else { throw NativeOpusError.invalidPacket }
var interleaved = [Float](repeating: 0, count: Int(frames) * channels)
let decoded = interleaved.withUnsafeMutableBufferPointer { samples -> Int32 in
guard let output = samples.baseAddress else { return -1 }
return opus_decode_float(decoder, packet, Int32(data.count), output, frames, 0)
}
guard decoded > 0, decoded <= frames else { throw NativeOpusError.decode(decoded) }
guard
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(decoded)),
let output = buffer.floatChannelData
else { throw NativeOpusError.invalidFormat }
buffer.frameLength = AVAudioFrameCount(decoded)
// Keep a stable stereo output format across mono/stereo track boundaries.
for channel in 0..<2 {
for frame in 0..<Int(decoded) {
output[channel][frame] = interleaved[frame * channels + min(channel, channels - 1)] * gain
}
}
return buffer
}
}
}