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
63 changes: 27 additions & 36 deletions ios/Audio.swift
Original file line number Diff line number Diff line change
Expand Up @@ -294,17 +294,19 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
private let error: (String) -> Void
private let queue = DispatchQueue(label: "webcodecs.audio-decoder")
private var packet: Data?
private var packetDescription = AudioStreamPacketDescription()
private var held: Data?
// The packet the converter reads, and its description: AudioToolbox keeps
// both pointers until the next input call, so they must not move. (A
// pointer from Data.withUnsafeBytes is only valid inside the closure: for
// a packet of 14 bytes or less, such as silent AAC, it points at a
// temporary copy.)
private var held: UnsafeMutableRawPointer?
private let packetDescription = UnsafeMutablePointer<AudioStreamPacketDescription>.allocate(
capacity: 1)
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,
Expand All @@ -329,9 +331,6 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
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
Expand All @@ -349,6 +348,8 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
}

deinit {
held?.deallocate()
packetDescription.deallocate()
if let converter { AudioConverterDispose(converter) }
}

Expand All @@ -360,17 +361,18 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
packets.pointee = 0
return endOfStream ? noErr : noMoreInputNow
}
held = packet // valid until the next call
held?.deallocate()
let bytes = UnsafeMutableRawPointer.allocate(byteCount: max(packet.count, 1), alignment: 16)
packet.copyBytes(to: bytes.assumingMemoryBound(to: UInt8.self), count: packet.count)
held = bytes // valid until the next call
self.packet = nil
packetDescription = AudioStreamPacketDescription(
packetDescription.pointee = AudioStreamPacketDescription(
mStartOffset: 0, mVariableFramesInPacket: 0, mDataByteSize: UInt32(packet.count))
held!.withUnsafeMutableBytes { raw in
data.pointee.mNumberBuffers = 1
data.pointee.mBuffers.mData = raw.baseAddress
data.pointee.mBuffers.mDataByteSize = UInt32(raw.count)
data.pointee.mBuffers.mNumberChannels = UInt32(channels)
}
withUnsafeMutablePointer(to: &packetDescription) { descriptions?.pointee = $0 }
data.pointee.mNumberBuffers = 1
data.pointee.mBuffers.mData = bytes
data.pointee.mBuffers.mDataByteSize = UInt32(packet.count)
data.pointee.mBuffers.mNumberChannels = UInt32(channels)
descriptions?.pointee = packetDescription
packets.pointee = 1
return noErr
}
Expand Down Expand Up @@ -413,15 +415,16 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
Unmanaged.passUnretained(self).toOpaque(), &frames, &list, nil)
}
total += Int(frames)
if status == noMoreInputNow || frames == 0 {
done = true
break
}
if status != noErr {
// An error first: with 0 frames it would otherwise pass for the end.
if status != noErr && status != noMoreInputNow {
failed = true
error(errorMessage("EncodingError", "audio-failed", "AudioConverter failed (\(status))"))
return
}
if status == noMoreInputNow || frames == 0 {
done = true
break
}
}
if total > 0 {
let buffer = ArrayBuffer.allocate(size: total * 4 * channels)
Expand All @@ -445,19 +448,7 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec {
// (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)
}
if let converter = self.converter { AudioConverterReset(converter) }
self.endOfStream = false
self.packet = nil
// A later decode() may jump: start timing from its timestamp again.
Expand Down
84 changes: 84 additions & 0 deletions src/__tests__/WebCodecs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2311,6 +2311,90 @@ describe("react-native-webcodecs + Mediabunny", () => {
expect(result.after).toBeLessThan(0.001);
}, 180000);

it("decodes AAC packets of a few bytes", async () => {
if (!probes()) {
return;
}
// Digital silence: the encoder makes each packet 4 bytes.
const file = await soundClip("tone-then-silence.m4a", [
"-f",
"lavfi",
"-i",
"sine=frequency=440:sample_rate=48000:duration=4",
"-af",
"volume=volume=0:enable='gte(t,2)'",
"-c:a",
"aac",
"-b:a",
"128k",
]);
const result = await runOnDevice<any>(
({ mediabunny: mb, webcodecs: wc, ctx }) => {
const input = new mb.Input({
source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)),
formats: mb.ALL_FORMATS,
});
return input.getPrimaryAudioTrack().then((track: any) =>
track.getDecoderConfig().then((config: any) => {
const packets: any[] = [];
const sink = new mb.EncodedPacketSink(track).packets();
const read = (): Promise<void> =>
sink.next().then((r: any) => {
if (r.done) {
return undefined;
}
if (r.value.timestamp >= 3 && r.value.timestamp < 3.5) {
packets.push(r.value);
}
return read();
});
const errors: string[] = [];
let frames = 0;
let peak = 0;
const decoder = new wc.AudioDecoder({
output: (data: any) => {
const n = data.numberOfFrames * data.numberOfChannels;
const buffer = new Float32Array(n);
data.copyTo(buffer, { planeIndex: 0, format: "f32" });
for (let i = 0; i < n; i++) {
peak = Math.max(peak, Math.abs(buffer[i]));
}
frames += data.numberOfFrames;
data.close();
},
error: (e: any) => errors.push(String(e)),
});
decoder.configure(config);
return read()
.then(() => {
packets.forEach((p: any) =>
decoder.decode(p.toEncodedAudioChunk()),
);
return decoder.flush();
})
.then(() => {
decoder.close();
input.dispose();
return {
errors,
frames,
peak,
sizes: packets.map((p: any) => p.byteLength),
};
});
}),
);
},
{ file },
120000,
);
expect(result.errors).toEqual([]);
expect(result.sizes.length).toBeGreaterThan(10);
expect(Math.max(...result.sizes)).toBeLessThanOrEqual(14);
expect(result.frames).toBeGreaterThan(0);
expect(result.peak).toBeLessThan(0.001);
}, 180000);

it("flushes a VideoEncoder given two frames with one timestamp", async () => {
if (!supported()) {
return;
Expand Down
Loading