Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
206 changes: 172 additions & 34 deletions ios/Audio.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,30 @@ private func floatFormat(sampleRate: Double, channels: Int) -> AudioStreamBasicD
mChannelsPerFrame: UInt32(channels), mBitsPerChannel: 32, mReserved: 0)
}

// A converter between two formats, with the decoder's magic cookie if any.
private func makeConverter(
_ source: AudioStreamBasicDescription, _ destination: AudioStreamBasicDescription, _ cookie: Data?
) throws -> AudioConverterRef {
var source = source
var destination = destination
var converter: AudioConverterRef?
let status = AudioConverterNew(&source, &destination, &converter)
guard status == noErr, let converter else {
throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))")
}
if let cookie {
let status = cookie.withUnsafeBytes {
AudioConverterSetProperty(
converter, kAudioConverterDecompressionMagicCookie, UInt32($0.count), $0.baseAddress!)
}
guard status == noErr else {
AudioConverterDispose(converter)
throw WebCodecsError.notSupported("the AAC magic cookie (\(status))")
}
}
return converter
}

private func compressedFormat(codec: String, sampleRate: Double, channels: Int) throws
-> AudioStreamBasicDescription
{
Expand All @@ -47,6 +71,62 @@ private func compressedFormat(codec: String, sampleRate: Double, channels: Int)
mBitsPerChannel: 0, mReserved: 0)
}

// An AudioSpecificConfig in an ES descriptor (esds): the magic cookie
// AudioToolbox takes for AAC, laid out as FFmpeg's ffat_get_magic_cookie does.
private func esdsCookie(_ asc: Data) -> Data {
func descriptor(_ tag: UInt8, _ size: Int) -> [UInt8] {
[
tag, UInt8((size >> 21) & 0x7f) | 0x80, UInt8((size >> 14) & 0x7f) | 0x80,
UInt8((size >> 7) & 0x7f) | 0x80, UInt8(size & 0x7f),
]
}
var cookie = descriptor(0x03, 3 + 5 + 13 + 5 + asc.count)
cookie += [0, 0, 0] // ES_ID, flags
cookie += descriptor(0x04, 13 + 5 + asc.count)
// MPEG-4 audio, an audio stream, buffer size, max and average bitrate.
cookie += [0x40, 0x15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
cookie += descriptor(0x05, asc.count)
return Data(cookie) + asc
}

// The stream's format as its cookie describes it, which the config's rate and
// channels may not: the richest layer the system plays (HE-AAC v2, HE-AAC,
// then AAC-LC), so SBR and PS are decoded, at their rate and channels, with
// 2048 frames a packet.
private func aacFormat(cookie: Data) throws -> AudioStreamBasicDescription {
try cookie.withUnsafeBytes { raw -> AudioStreamBasicDescription in
var base = AudioStreamBasicDescription()
base.mFormatID = kAudioFormatMPEG4AAC
var size = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
let status = AudioFormatGetProperty(
kAudioFormatProperty_FormatInfo, UInt32(raw.count), raw.baseAddress, &size, &base)
guard status == noErr else {
throw WebCodecsError.notSupported("an AudioSpecificConfig AudioToolbox rejects (\(status))")
}
var info = AudioFormatInfo(mASBD: base, mMagicCookie: raw.baseAddress!, mMagicCookieSize: UInt32(raw.count))
let infoSize = UInt32(MemoryLayout<AudioFormatInfo>.size)
let itemSize = MemoryLayout<AudioFormatListItem>.size
var listSize = UInt32(0)
guard AudioFormatGetPropertyInfo(kAudioFormatProperty_FormatList, infoSize, &info, &listSize) == noErr,
Int(listSize) >= itemSize
else { return base }
var items = [AudioFormatListItem](repeating: AudioFormatListItem(), count: Int(listSize) / itemSize)
guard AudioFormatGetProperty(kAudioFormatProperty_FormatList, infoSize, &info, &listSize, &items) == noErr
else { return base }
let count = min(items.count, Int(listSize) / itemSize)
guard count > 0 else { return base }
var index = UInt32(0)
var indexSize = UInt32(MemoryLayout<UInt32>.size)
if AudioFormatGetProperty(
kAudioFormatProperty_FirstPlayableFormatFromList, UInt32(count * itemSize), &items, &indexSize, &index)
!= noErr || Int(index) >= count
{
index = 0
}
return items[Int(index)].mASBD
}
}

// MARK: - AudioEncoder (PCM → AAC)

final class HybridNativeAudioEncoder: HybridNativeAudioEncoderSpec {
Expand Down Expand Up @@ -79,13 +159,9 @@ final class HybridNativeAudioEncoder: HybridNativeAudioEncoderSpec {
else {
throw WebCodecsError.notSupported("AAC-LC, 1 or 2 channels, at a standard sample rate")
}
var source = floatFormat(sampleRate: sampleRate, channels: channels)
var destination = try compressedFormat(codec: "aac", sampleRate: sampleRate, channels: channels)
var converter: AudioConverterRef?
let status = AudioConverterNew(&source, &destination, &converter)
guard status == noErr, let converter else {
throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))")
}
let converter = try makeConverter(
floatFormat(sampleRate: sampleRate, channels: channels),
compressedFormat(codec: "aac", sampleRate: sampleRate, channels: channels), nil)
self.converter = converter
if let bitrate = config.bitrate, bitrate > 0 {
var rate = UInt32(bitrate)
Expand Down Expand Up @@ -223,24 +299,51 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
private var start: Double?
private var framesOut: Int64 = 0
private var failed = false
// flush(): the input procedure ends the stream when it has nothing more.
private var endOfStream = false
// What flush() makes a new converter from.
private let sourceFormat: AudioStreamBasicDescription
private let destinationFormat: AudioStreamBasicDescription
private let cookie: Data?

init(
config: NativeAudioDecoderConfig,
output: @escaping (NativeDecodedAudio) -> Void,
error: @escaping (String) -> Void
) throws {
channels = Int(config.numberOfChannels)
sampleRate = config.sampleRate
self.output = output
self.error = error
var source = try compressedFormat(codec: config.codec, sampleRate: sampleRate, channels: channels)
framesPerPacket = Int(source.mFramesPerPacket)
var destination = floatFormat(sampleRate: sampleRate, channels: channels)
var converter: AudioConverterRef?
let status = AudioConverterNew(&source, &destination, &converter)
guard status == noErr, let converter else {
throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))")
// The AudioSpecificConfig is authoritative (WebCodecs AAC registration):
// the format and cookie come from it, the config's values only without one.
var source: AudioStreamBasicDescription
var cookie: Data?
if config.codec == "aac", let description = config.description, description.size > 0 {
let esds = esdsCookie(description.toData(copyIfNeeded: true))
source = try aacFormat(cookie: esds)
cookie = esds
} else {
source = try compressedFormat(
codec: config.codec, sampleRate: config.sampleRate, channels: Int(config.numberOfChannels))
}
if source.mSampleRate <= 0 { source.mSampleRate = config.sampleRate }
if source.mChannelsPerFrame == 0 { source.mChannelsPerFrame = UInt32(config.numberOfChannels) }
framesPerPacket = max(Int(source.mFramesPerPacket), 1024)
let destination = floatFormat(sampleRate: source.mSampleRate, channels: Int(source.mChannelsPerFrame))
sourceFormat = source
destinationFormat = destination
self.cookie = cookie
let converter = try makeConverter(source, destination, cookie)
// What the converter outputs, which the AudioData say.
var current = destination
var currentSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
if AudioConverterGetProperty(
converter, kAudioConverterCurrentOutputStreamDescription, &currentSize, &current) != noErr
|| current.mSampleRate <= 0 || current.mChannelsPerFrame != destination.mChannelsPerFrame
{
current = destination
}
sampleRate = current.mSampleRate
channels = Int(current.mChannelsPerFrame)
self.converter = converter
super.init()
}
Expand All @@ -255,7 +358,7 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
) -> OSStatus {
guard let packet else {
packets.pointee = 0
return noMoreInputNow
return endOfStream ? noErr : noMoreInputNow
}
held = packet // valid until the next call
self.packet = nil
Expand All @@ -276,21 +379,31 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
guard converter != nil else { throw WebCodecsError.invalidState("the decoder is closed") }
let bytes = data.toData(copyIfNeeded: true)
queue.async {
guard !self.failed, let converter = self.converter else { return }
guard !self.failed, self.converter != nil else { return }
if self.start == nil { self.start = timestamp }
self.packet = bytes
let capacity = self.framesPerPacket * 2
var samples = [Float](repeating: 0, count: capacity * self.channels)
self.pull()
}
}

// Outputs what the converter has decoded, until it wants more input (or,
// at the end of the stream, has no more).
private func pull() {
guard let converter else { return }
let capacity = framesPerPacket * 2
// Scratch space for each pass, copied out before the next.
var samples = [Float](repeating: 0, count: capacity * channels)
var done = false
while !done {
var total = 0
while true {
while total < capacity {
var frames = UInt32(capacity - total)
if frames == 0 { break }
let status = samples.withUnsafeMutableBytes { raw -> OSStatus in
var list = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(self.channels), mDataByteSize: UInt32(Int(frames) * 4 * self.channels),
mData: raw.baseAddress!.advanced(by: total * 4 * self.channels)))
mNumberChannels: UInt32(channels), mDataByteSize: UInt32(Int(frames) * 4 * channels),
mData: raw.baseAddress!.advanced(by: total * 4 * channels)))
return AudioConverterFillComplexBuffer(
converter,
{ _, packets, data, descriptions, user in
Expand All @@ -300,28 +413,53 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
Unmanaged.passUnretained(self).toOpaque(), &frames, &list, nil)
}
total += Int(frames)
if status == noMoreInputNow || frames == 0 { break }
if status == noMoreInputNow || frames == 0 {
done = true
break
}
if status != noErr {
self.failed = true
self.error(errorMessage("EncodingError", "audio-failed", "AudioConverter failed (\(status))"))
failed = true
error(errorMessage("EncodingError", "audio-failed", "AudioConverter failed (\(status))"))
return
}
}
if total > 0 {
let buffer = ArrayBuffer.allocate(size: total * 4 * self.channels)
samples.withUnsafeBytes { memcpy(buffer.data, $0.baseAddress!, total * 4 * self.channels) }
let ts = (self.start ?? 0) + Double(self.framesOut) * 1_000_000 / self.sampleRate
self.framesOut += Int64(total)
self.output(NativeDecodedAudio(
data: buffer, frames: Double(total), sampleRate: self.sampleRate,
numberOfChannels: Double(self.channels), timestamp: ts.rounded()))
let buffer = ArrayBuffer.allocate(size: total * 4 * channels)
samples.withUnsafeBytes { memcpy(buffer.data, $0.baseAddress!, total * 4 * channels) }
let ts = (start ?? 0) + Double(framesOut) * 1_000_000 / sampleRate
framesOut += Int64(total)
output(NativeDecodedAudio(
data: buffer, frames: Double(total), sampleRate: sampleRate,
numberOfChannels: Double(channels), timestamp: ts.rounded()))
}
}
}

func flush() throws -> Promise<Void> {
guard converter != nil else { return Promise.rejected(withError: WebCodecsError.invalidState("the decoder is closed")) }
return Promise.parallel(queue) {
// Nothing decoded since the last flush: nothing to end.
if self.failed || self.start == nil { return }
// End the stream, for the frames the converter still holds, then start
// a new one: without a reset, the next chunk would overlap the last
// (MDCT and SBR state), as after a seek.
self.endOfStream = true
self.pull()
// A new converter, not AudioConverterReset: after the end of the
// stream, a reset converter put out nothing more on the CI Simulator.
if let old = self.converter {
do {
self.converter = try makeConverter(
self.sourceFormat, self.destinationFormat, self.cookie)
} catch {
self.failed = true
self.error(errorMessage("EncodingError", "audio-failed", "\(error)"))
return
}
AudioConverterDispose(old)
}
self.endOfStream = false
self.packet = nil
// A later decode() may jump: start timing from its timestamp again.
self.start = nil
self.framesOut = 0
Expand Down
17 changes: 17 additions & 0 deletions ios/Surface.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,18 @@ final class HybridNativeSurface: HybridNativeSurfaceSpec {
let height: Double
let format: String

// Whether `surface` holds a use count, released with it.
private var inUse = false

init(surface: IOSurfaceRef) {
self.surface = surface
width = Double(IOSurfaceGetWidth(surface))
height = Double(IOSurfaceGetHeight(surface))
format = webCodecsFormat(IOSurfaceGetPixelFormat(surface))
// A producer's CVPixelBufferPool reuses a surface once its use count is
// zero, whatever its retain count: pin it until the frame is closed.
IOSurfaceIncrementUseCount(surface)
inUse = true
super.init()
}

Expand Down Expand Up @@ -148,11 +155,21 @@ final class HybridNativeSurface: HybridNativeSurfaceSpec {
return copy
}

private func unpin() {
if inUse, let surface { IOSurfaceDecrementUseCount(surface) }
inUse = false
}

func release() throws {
unpin()
surface = nil
buffer = nil
fence = nil
}

deinit {
unpin()
}
}

final class HybridNativeSurfacePool: HybridNativeSurfacePoolSpec {
Expand Down
Loading
Loading