// WavCodecHeaderTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @_spi(LyrebirdExtensions) import LyrebirdSynth // Headers no writer of ours emits, but real files carry: a `fmt ` chunk too // short for the fields the reader loads at fixed offsets, and // WAVE_FORMAT_EXTENSIBLE, which is what most 24-bit and multichannel writers // actually produce. @Suite("Portable WAV codec — header edge cases") struct WavCodecHeaderTests { private func tempURL() -> URL { FileManager.default.temporaryDirectory .appendingPathComponent("lyrebird-wavhdr-\(UUID().uuidString).wav") } /// Builds a WAV whose `fmt ` chunk is written verbatim, so a test can hand /// the reader a header no writer of ours would produce. private func writeWav(fmtChunk: [UInt8], dataBytes: [UInt8], to url: URL) throws { var file: [UInt8] = [] func appendLE32(_ value: UInt32) { file.append(contentsOf: [ UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8), UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 24), ]) } file.append(contentsOf: Array("RIFF".utf8)) appendLE32(UInt32(4 + 8 + fmtChunk.count + 8 + dataBytes.count)) file.append(contentsOf: Array("WAVE".utf8)) file.append(contentsOf: Array("fmt ".utf8)) appendLE32(UInt32(fmtChunk.count)) file.append(contentsOf: fmtChunk) file.append(contentsOf: Array("data".utf8)) appendLE32(UInt32(dataBytes.count)) file.append(contentsOf: dataBytes) try Data(file).write(to: url) } private func le16(_ value: UInt16) -> [UInt8] { [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)] } private func le32(_ value: UInt32) -> [UInt8] { [ UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8), UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 24), ] } /// 16-byte PCM `fmt ` body. private func pcmFmt(tag: UInt16, channels: UInt16, rate: UInt32, bits: UInt16) -> [UInt8] { let blockAlign: UInt16 = channels * (bits / 8) var out: [UInt8] = [] out += le16(tag) out += le16(channels) out += le32(rate) out += le32(rate * UInt32(blockAlign)) out += le16(blockAlign) out += le16(bits) return out } @Test("a fmt chunk too short to hold its fields throws instead of trapping") func shortFmtChunkThrows() throws { // 14 bytes: everything except bitsPerSample, which the reader loads at // offset 14. Before the length check this indexed past the chunk. let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } let truncatedFmt: [UInt8] = Array(pcmFmt(tag: 1, channels: 1, rate: 44100, bits: 16).prefix(14)) try writeWav(fmtChunk: truncatedFmt, dataBytes: [0, 0, 0, 0], to: url) #expect(throws: WavFileError.truncated) { _ = try WavFileReader(url: url) } } @Test("WAVE_FORMAT_EXTENSIBLE is read via its SubFormat GUID") func extensibleFormatIsAccepted() throws { // What most 24-bit and multichannel writers actually emit. The header // is a PCM header with tag 0xFFFE plus a 22-byte extension whose GUID // opens with the real format tag (1 = PCM). let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } var fmt: [UInt8] = pcmFmt(tag: 0xFFFE, channels: 2, rate: 48000, bits: 24) fmt += le16(22) // cbSize fmt += le16(24) // validBitsPerSample fmt += le32(3) // channel mask: front left + right fmt += le16(1) // SubFormat GUID: leading tag = PCM fmt += [UInt8](repeating: 0, count: 14) // rest of the GUID // Two frames of stereo 24-bit silence. let data: [UInt8] = [UInt8](repeating: 0, count: 2 * 2 * 3) try writeWav(fmtChunk: fmt, dataBytes: data, to: url) let reader: WavFileReader = try WavFileReader(url: url) defer { reader.close() } #expect(reader.encoding == .int24) #expect(reader.channels == 2) #expect(reader.sampleRate == 48000) #expect(reader.frameCount == 2) } @Test("an unreadable extensible SubFormat is still reported, not guessed") func extensibleWithUnsupportedSubFormatThrows() throws { let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } var fmt: [UInt8] = pcmFmt(tag: 0xFFFE, channels: 1, rate: 44100, bits: 16) fmt += le16(22) fmt += le16(16) fmt += le32(4) fmt += le16(0x0011) // ADPCM — not something we decode fmt += [UInt8](repeating: 0, count: 14) try writeWav(fmtChunk: fmt, dataBytes: [0, 0], to: url) #expect(throws: WavFileError.unsupportedFormat(formatTag: 0x0011, bitsPerSample: 16)) { _ = try WavFileReader(url: url) } } @Test("a float32 file declares cbSize and carries a fact chunk") func float32HeaderIsSpecCompliant() throws { // RIFF requires non-PCM tags to declare `cbSize` — an 18-byte `fmt ` // body — and to carry a `fact` chunk holding the sample count. Writers // that emit the plain 16-byte PCM header for float data are rejected by // strict readers. let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } let channels: Int = 2 let frames: Int = 10 let writer: WavFileWriter = try WavFileWriter( url: url, channels: channels, sampleRate: 48000, encoding: .float32 ) try writer.write( interleaved: [Float](repeating: 0.25, count: frames * channels), frames: frames ) try writer.finalize() let bytes: [UInt8] = [UInt8](try Data(contentsOf: url)) func le16(at offset: Int) -> UInt16 { UInt16(bytes[offset]) | (UInt16(bytes[offset + 1]) << 8) } func le32(at offset: Int) -> UInt32 { UInt32(bytes[offset]) | (UInt32(bytes[offset + 1]) << 8) | (UInt32(bytes[offset + 2]) << 16) | (UInt32(bytes[offset + 3]) << 24) } #expect(String(decoding: bytes[12..<16], as: UTF8.self) == "fmt ") #expect(le32(at: 16) == 18, "fmt body must be 18 bytes for a non-PCM tag") #expect(le16(at: 20) == 3, "format tag 3 = IEEE float") #expect(le16(at: 36) == 0, "cbSize: no format extension") #expect(String(decoding: bytes[38..<42], as: UTF8.self) == "fact") #expect(le32(at: 42) == 4, "fact body is one UInt32") #expect(le32(at: 46) == UInt32(frames), "fact holds the per-channel sample count") #expect(String(decoding: bytes[50..<54], as: UTF8.self) == "data") #expect(le32(at: 54) == UInt32(frames * channels * 4)) // RIFF size counts everything after the first eight bytes. #expect(le32(at: 4) == UInt32(bytes.count - 8)) } @Test("an integer file keeps the canonical 44-byte header") func int16HeaderStaysCanonical() throws { let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } let writer: WavFileWriter = try WavFileWriter( url: url, channels: 1, sampleRate: 44100, encoding: .int16 ) try writer.write(interleaved: [Float](repeating: 0, count: 4), frames: 4) try writer.finalize() let bytes: [UInt8] = [UInt8](try Data(contentsOf: url)) func le32(at offset: Int) -> UInt32 { UInt32(bytes[offset]) | (UInt32(bytes[offset + 1]) << 8) | (UInt32(bytes[offset + 2]) << 16) | (UInt32(bytes[offset + 3]) << 24) } #expect(le32(at: 16) == 16, "PCM fmt body stays 16 bytes") #expect(String(decoding: bytes[36..<40], as: UTF8.self) == "data") #expect(le32(at: 40) == UInt32(4 * 2)) #expect(bytes.count == 44 + 4 * 2) } @Test("the 4 GB RIFF boundary throws instead of trapping") func riffSizeOverflowThrows() throws { // The conversion this guards used to be a plain `UInt32(...)`, which // traps — and a trap an hour into an offline render is the worst // possible outcome. Tested through the size computation so the boundary // can be crossed without writing four gigabytes. let header: Int = 44 let justUnder: Int = Int(UInt32.max) - header + 8 #expect(try WavFileWriter.riffChunkSize(headerBytes: header, dataBytes: justUnder) == UInt32.max) #expect(throws: WavFileError.fileTooLarge(bytes: Int(UInt32.max) + 1)) { _ = try WavFileWriter.riffChunkSize(headerBytes: header, dataBytes: justUnder + 1) } } @Test("an odd data payload is padded to a word boundary") func oddDataPayloadIsPadded() throws { // int24 mono with an odd frame count produces an odd `data` chunk. RIFF // requires the next chunk to start on a word boundary, so a pad byte // follows the payload — counted in the RIFF size, not the data size. let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } let frames: Int = 3 // 3 frames x 1 channel x 3 bytes = 9, odd let writer: WavFileWriter = try WavFileWriter( url: url, channels: 1, sampleRate: 44100, encoding: .int24 ) try writer.write(interleaved: [Float](repeating: 0.5, count: frames), frames: frames) try writer.finalize() let bytes: [UInt8] = [UInt8](try Data(contentsOf: url)) func le32(at offset: Int) -> UInt32 { UInt32(bytes[offset]) | (UInt32(bytes[offset + 1]) << 8) | (UInt32(bytes[offset + 2]) << 16) | (UInt32(bytes[offset + 3]) << 24) } #expect(le32(at: 40) == UInt32(frames * 3), "data size counts payload only") #expect(bytes.count == 44 + frames * 3 + 1, "a pad byte follows the payload") #expect(le32(at: 4) == UInt32(bytes.count - 8), "RIFF size includes the pad") #expect(bytes[bytes.count - 1] == 0) } @Test("a data size larger than the file is clamped to what is there") func oversizedDataChunkIsClamped() throws { // Streaming writers leave a placeholder `data` size they never patch. // Believing it produces a nonsense frame count and a mid-render throw // rather than a clean end of file. let url: URL = tempURL() defer { try? FileManager.default.removeItem(at: url) } let realFrames: Int = 4 let channels: Int = 2 var file: [UInt8] = [] file += Array("RIFF".utf8) file += le32(0xFFFF_FFFF) file += Array("WAVE".utf8) file += Array("fmt ".utf8) file += le32(16) file += pcmFmt(tag: 1, channels: UInt16(channels), rate: 44100, bits: 16) file += Array("data".utf8) file += le32(0xFFFF_FFFF) // lying placeholder file += [UInt8](repeating: 0, count: realFrames * channels * 2) try Data(file).write(to: url) let reader: WavFileReader = try WavFileReader(url: url) defer { reader.close() } #expect(reader.frameCount == realFrames) let all: [Float] = try reader.read(frames: realFrames * 4) #expect(all.count == realFrames * channels) } }