musicbrainz: write Ogg/Opus containers without the platform muxer
- Commit
57cd4d857339fac0ea841b445e8f603b487291bd- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-20 17:29 UTC (3 months ago)
- Parents
0f3300c
Diff
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/ByteArrayMediaDataSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/ByteArrayMediaDataSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/ByteArrayMediaDataSource.ktnew file mode 100644index 0000000000..27f204b2c1--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/ByteArrayMediaDataSource.kt@@ -0,0 +1,40 @@+package com.vayunmathur.musicbrainz.data.download++import android.media.MediaDataSource++/**+ * Lets [android.media.MediaExtractor] read the downloaded bytes straight out of RAM.+ *+ * The download is already buffered in memory so it can be tagged before it is filed away,+ * and writing it back out to a temp file first would double the peak storage a hi-res track+ * needs - well over 200 MB for a long 24/192 recording - and add a cleanup path that has to+ * survive every failure.+ */+internal class ByteArrayMediaDataSource(private val bytes: ByteArray) : MediaDataSource() {++ override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int =+ ByteArrayReads.readAt(bytes, position, buffer, offset, size)++ override fun getSize(): Long = bytes.size.toLong()++ override fun close() = Unit+}++/**+ * The read logic on its own, so it can be tested without the framework class.+ *+ * The contract has sharp edges - end of stream is -1 rather than 0, and a read that starts+ * inside the buffer but runs past the end has to be truncated rather than refused - and+ * getting either wrong makes the extractor report a corrupt file.+ */+internal object ByteArrayReads {++ /** Returns the number of bytes copied, or -1 once [position] is at or past the end. */+ fun readAt(source: ByteArray, position: Long, destination: ByteArray, offset: Int, size: Int): Int {+ if (position < 0 || position >= source.size) return -1+ if (size <= 0) return 0+ val available = (source.size - position).coerceAtMost(size.toLong()).toInt()+ System.arraycopy(source, position.toInt(), destination, offset, available)+ return available+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.ktindex 7a926a141d..0c10c7c272 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggOpusTagger.kt@@ -38,8 +38,6 @@ data class VorbisTags( */ object OggOpusTagger { - private const val MAX_SEGMENTS_PER_PAGE = 255- /** * Returns the retagged bytes, or null when the input is not an Ogg/Opus file this can * rewrite. Callers fall back to the original bytes: an untagged file is still worth@@ -68,7 +66,13 @@ object OggOpusTagger { val serial = readIntLe(source, head.start + 14) val packet = buildOpusTagsPacket(tags)- val commentPages = buildPages(packet, serial, startSequence = 1)+ val commentPages = OggPages.forPacket(+ packet = packet,+ serialNumber = serial,+ startSequence = 1,+ granulePosition = 0L,+ firstHeaderType = 0,+ ) val out = ByteArrayOutputStream(source.size + packet.size) out.write(source, head.start, head.end - head.start)@@ -79,8 +83,8 @@ object OggOpusTagger { var sequence = 1 + commentPages.size for (i in commentEnd + 1 until pages.size) { val page = source.copyOfRange(pages[i].start, pages[i].end)- writeIntLe(page, 18, sequence)- setChecksum(page)+ OggPages.writeIntLe(page, 18, sequence)+ OggPages.setChecksum(page) out.write(page) sequence++ }@@ -105,10 +109,10 @@ object OggOpusTagger { private fun parsePages(buf: ByteArray): List<Page>? { val pages = ArrayList<Page>() var offset = 0- while (offset + 27 <= buf.size) {+ while (offset + OggPages.HEADER_SIZE <= buf.size) { if (String(buf, offset, 4, Charsets.ISO_8859_1) != "OggS") break val segmentCount = buf[offset + 26].toInt() and 0xff- val tableStart = offset + 27+ val tableStart = offset + OggPages.HEADER_SIZE if (tableStart + segmentCount > buf.size) return null var payload = 0 for (i in 0 until segmentCount) payload += buf[tableStart + i].toInt() and 0xff@@ -120,115 +124,7 @@ object OggOpusTagger { return pages.takeIf { it.isNotEmpty() } } - /** Splits a single packet into as many pages as its length needs, up to 255 segments each. */- private fun buildPages(packet: ByteArray, serial: Int, startSequence: Int): List<ByteArray> {- val lacing = ArrayList<Int>()- var remaining = packet.size- while (remaining >= 255) {- lacing.add(255)- remaining -= 255- }- lacing.add(remaining) // final segment is always < 255, marking the packet's end.-- val pages = ArrayList<ByteArray>()- var lacingIndex = 0- var payloadOffset = 0- var sequence = startSequence- var first = true- while (lacingIndex < lacing.size) {- val segmentCount = minOf(MAX_SEGMENTS_PER_PAGE, lacing.size - lacingIndex)- val segments = lacing.subList(lacingIndex, lacingIndex + segmentCount)- val payloadSize = segments.sum()- pages.add(- buildPage(- headerType = if (first) 0x00 else 0x01, // 0x01 marks a continued packet- serial = serial,- sequence = sequence,- segments = segments,- payload = packet,- payloadOffset = payloadOffset,- payloadSize = payloadSize,- ),- )- lacingIndex += segmentCount- payloadOffset += payloadSize- sequence++- first = false- }- return pages- }-- private fun buildPage(- headerType: Int,- serial: Int,- sequence: Int,- segments: List<Int>,- payload: ByteArray,- payloadOffset: Int,- payloadSize: Int,- ): ByteArray {- val out = ByteArrayOutputStream(27 + segments.size + payloadSize)- out.write("OggS".toByteArray(Charsets.ISO_8859_1))- out.write(0) // stream structure version- out.write(headerType)- out.write(ByteArray(8)) // granule position: 0 for a header page- out.write(VorbisComments.intLe(serial))- out.write(VorbisComments.intLe(sequence))- out.write(ByteArray(4)) // CRC placeholder, filled in below- out.write(segments.size)- segments.forEach { out.write(it) }- out.write(payload, payloadOffset, payloadSize)- val bytes = out.toByteArray()- setChecksum(bytes)- return bytes- }-- /** Zeroes the checksum field, computes the Ogg CRC over the whole page, and writes it back. */- private fun setChecksum(page: ByteArray) {- page[22] = 0- page[23] = 0- page[24] = 0- page[25] = 0- writeIntLe(page, 22, oggCrc(page))- }-- // ------------------------------------------------------------------- // Ogg CRC-32 (poly 0x04C11DB7, no reflection, no final xor)- // -------------------------------------------------------------------- private val crcTable = IntArray(256).also { table ->- for (i in 0 until 256) {- var crc = i shl 24- repeat(8) {- crc = if (crc and 0x80000000.toInt() != 0) {- (crc shl 1) xor 0x04c11db7- } else {- crc shl 1- }- }- table[i] = crc- }- }-- private fun oggCrc(data: ByteArray): Int {- var crc = 0- for (b in data) {- val index = ((crc ushr 24) xor (b.toInt() and 0xff)) and 0xff- crc = (crc shl 8) xor crcTable[index]- }- return crc- }-- // ------------------------------------------------------------------- private fun readIntLe(buf: ByteArray, offset: Int): Int = ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).int-- private fun writeIntLe(buf: ByteArray, offset: Int, value: Int) {- buf[offset] = value.toByte()- buf[offset + 1] = (value ushr 8).toByte()- buf[offset + 2] = (value ushr 16).toByte()- buf[offset + 3] = (value ushr 24).toByte()- } }
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriter.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriter.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriter.ktnew file mode 100644index 0000000000..692b9c47c8--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriter.kt@@ -0,0 +1,256 @@+package com.vayunmathur.musicbrainz.data.download++import java.io.ByteArrayOutputStream++/**+ * Ogg page construction: lacing tables, the Ogg CRC-32, and splitting a packet across pages.+ *+ * Shared by [OggOpusTagger], which rewrites the pages of a file the platform muxer produced,+ * and by [OggStreamWriter], which builds a file from encoder packets with no muxer involved.+ */+internal object OggPages {++ const val HEADER_SIZE = 27+ const val MAX_SEGMENTS = 255++ const val FLAG_CONTINUED = 0x01+ const val FLAG_BEGIN_OF_STREAM = 0x02+ const val FLAG_END_OF_STREAM = 0x04++ /**+ * The lacing values for one packet: 255 for every full segment, then a final value under+ * 255 that marks the packet's end. A packet whose length is a multiple of 255 therefore+ * ends with a zero-length segment, which is what tells a reader the packet is complete.+ */+ fun lacingFor(packetSize: Int): List<Int> {+ val lacing = ArrayList<Int>(packetSize / MAX_SEGMENTS + 1)+ var remaining = packetSize+ while (remaining >= MAX_SEGMENTS) {+ lacing.add(MAX_SEGMENTS)+ remaining -= MAX_SEGMENTS+ }+ lacing.add(remaining)+ return lacing+ }++ fun build(+ headerType: Int,+ granulePosition: Long,+ serialNumber: Int,+ sequence: Int,+ segments: List<Int>,+ payload: ByteArray,+ payloadOffset: Int,+ payloadSize: Int,+ ): ByteArray {+ val out = ByteArrayOutputStream(HEADER_SIZE + segments.size + payloadSize)+ out.write("OggS".toByteArray(Charsets.ISO_8859_1))+ out.write(0) // stream structure version+ out.write(headerType)+ out.write(longLe(granulePosition))+ out.write(VorbisComments.intLe(serialNumber))+ out.write(VorbisComments.intLe(sequence))+ out.write(ByteArray(4)) // CRC placeholder, filled in below+ out.write(segments.size)+ segments.forEach { out.write(it) }+ out.write(payload, payloadOffset, payloadSize)+ val bytes = out.toByteArray()+ setChecksum(bytes)+ return bytes+ }++ /**+ * Splits a single packet into as many pages as its length needs.+ *+ * Only a header packet with embedded cover art gets anywhere near this; audio packets+ * always fit on one page.+ */+ fun forPacket(+ packet: ByteArray,+ serialNumber: Int,+ startSequence: Int,+ granulePosition: Long,+ firstHeaderType: Int,+ ): List<ByteArray> {+ val lacing = lacingFor(packet.size)+ val pages = ArrayList<ByteArray>()+ var lacingIndex = 0+ var payloadOffset = 0+ var sequence = startSequence+ while (lacingIndex < lacing.size) {+ val segmentCount = minOf(MAX_SEGMENTS, lacing.size - lacingIndex)+ val segments = lacing.subList(lacingIndex, lacingIndex + segmentCount)+ val payloadSize = segments.sum()+ pages.add(+ build(+ headerType = if (lacingIndex == 0) firstHeaderType else FLAG_CONTINUED,+ granulePosition = granulePosition,+ serialNumber = serialNumber,+ sequence = sequence,+ segments = segments,+ payload = packet,+ payloadOffset = payloadOffset,+ payloadSize = payloadSize,+ ),+ )+ lacingIndex += segmentCount+ payloadOffset += payloadSize+ sequence+++ }+ return pages+ }++ /** Zeroes the checksum field, computes the Ogg CRC over the whole page, and writes it back. */+ fun setChecksum(page: ByteArray) {+ for (i in 22..25) page[i] = 0+ writeIntLe(page, 22, crc(page))+ }++ fun writeIntLe(buffer: ByteArray, offset: Int, value: Int) {+ buffer[offset] = value.toByte()+ buffer[offset + 1] = (value ushr 8).toByte()+ buffer[offset + 2] = (value ushr 16).toByte()+ buffer[offset + 3] = (value ushr 24).toByte()+ }++ fun writeLongLe(buffer: ByteArray, offset: Int, value: Long) {+ for (i in 0 until 8) buffer[offset + i] = (value ushr (8 * i)).toByte()+ }++ fun longLe(value: Long): ByteArray = ByteArray(8).also { writeLongLe(it, 0, value) }++ // ------------------------------------------------------------------+ // Ogg CRC-32 (poly 0x04C11DB7, no reflection, no initial or final xor)+ // ------------------------------------------------------------------++ private val crcTable = IntArray(256).also { table ->+ for (i in 0 until 256) {+ var crc = i shl 24+ repeat(8) {+ crc = if (crc and 0x80000000.toInt() != 0) {+ (crc shl 1) xor 0x04c11db7+ } else {+ crc shl 1+ }+ }+ table[i] = crc+ }+ }++ fun crc(data: ByteArray): Int {+ var crc = 0+ for (b in data) {+ val index = ((crc ushr 24) xor (b.toInt() and 0xff)) and 0xff+ crc = (crc shl 8) xor crcTable[index]+ }+ return crc+ }+}++/**+ * Writes an Ogg stream from packets, in one pass, with no platform muxer.+ *+ * [MediaMuxer][android.media.MediaMuxer]'s `MUXER_OUTPUT_OGG` can only be handed a track+ * format, and the platform Opus encoder describes itself through Android's own+ * `AOPUSHDR` marker-chunk codec config rather than the split `csd-0`/`csd-1`/`csd-2` an+ * extractor produces - so whether the muxer would accept it is not something the app can+ * rely on, and it would also need a temp file, since the muxer cannot write to memory. All+ * of the Ogg framing the app needs already existed in [OggOpusTagger] for retagging, so+ * this writes the container directly instead: no temp file, no framework dependency, and+ * the byte-level behaviour is unit-testable.+ *+ * Header packets each get their own page, as the Opus mapping requires. Audio packets are+ * grouped so a page holds up to about a second of audio, which is the usual trade between+ * page overhead and how much a reader loses to a corrupt page.+ */+internal class OggStreamWriter(private val serialNumber: Int) {++ private val out = ByteArrayOutputStream(INITIAL_CAPACITY)+ private var sequence = 0+ private var headerWritten = false++ private val pendingPackets = ArrayList<ByteArray>()+ private var pendingSegments = 0+ private var pendingGranule = 0L++ /** Writes a header packet on a page of its own, with a granule position of zero. */+ fun writeHeaderPacket(packet: ByteArray) {+ val pages = OggPages.forPacket(+ packet = packet,+ serialNumber = serialNumber,+ startSequence = sequence,+ granulePosition = 0L,+ firstHeaderType = if (headerWritten) 0 else OggPages.FLAG_BEGIN_OF_STREAM,+ )+ pages.forEach { out.write(it) }+ sequence += pages.size+ headerWritten = true+ }++ /**+ * Queues an audio packet. [granulePosition] is the stream position at the *end* of the+ * packet, which is what Ogg records for the last packet finishing on a page.+ */+ fun writeAudioPacket(packet: ByteArray, granulePosition: Long) {+ val segments = OggPages.lacingFor(packet.size).size+ if (pendingPackets.isNotEmpty() &&+ (pendingSegments + segments > OggPages.MAX_SEGMENTS ||+ pendingPackets.size >= MAX_PACKETS_PER_PAGE)+ ) {+ flushPage(endOfStream = false, granulePosition = pendingGranule)+ }+ pendingPackets.add(packet)+ pendingSegments += segments+ pendingGranule = granulePosition+ }++ /**+ * Closes the stream and returns the bytes.+ *+ * [finalGranulePosition] overrides the last page's granule position so it reports the+ * stream's true length: the encoder pads its final packet out to a whole frame, and a+ * decoder trims that padding by comparing what it decoded against this number.+ */+ fun finish(finalGranulePosition: Long): ByteArray {+ flushPage(endOfStream = true, granulePosition = finalGranulePosition)+ return out.toByteArray()+ }++ private fun flushPage(endOfStream: Boolean, granulePosition: Long) {+ if (pendingPackets.isEmpty() && !endOfStream) return+ val segments = ArrayList<Int>(pendingSegments)+ var payloadSize = 0+ for (packet in pendingPackets) {+ segments.addAll(OggPages.lacingFor(packet.size))+ payloadSize += packet.size+ }+ val payload = ByteArray(payloadSize)+ var at = 0+ for (packet in pendingPackets) {+ packet.copyInto(payload, at)+ at += packet.size+ }+ out.write(+ OggPages.build(+ headerType = if (endOfStream) OggPages.FLAG_END_OF_STREAM else 0,+ granulePosition = granulePosition,+ serialNumber = serialNumber,+ sequence = sequence,+ segments = segments,+ payload = payload,+ payloadOffset = 0,+ payloadSize = payloadSize,+ ),+ )+ sequence+++ pendingPackets.clear()+ pendingSegments = 0+ }++ private companion object {+ const val INITIAL_CAPACITY = 1 * 1024 * 1024++ /** Fifty 20 ms Opus packets, so a page carries about one second. */+ const val MAX_PACKETS_PER_PAGE = 50+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusHead.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusHead.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusHead.ktnew file mode 100644index 0000000000..24a1fd5140--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusHead.kt@@ -0,0 +1,108 @@+package com.vayunmathur.musicbrainz.data.download++/**+ * The Opus identification header, and the packet arithmetic the Ogg writer needs.+ *+ * An Ogg/Opus file opens with a 19-byte `OpusHead` describing the channel count, the+ * pre-skip and the source rate. When the platform Opus encoder is driving, that has to come+ * from the encoder rather than being invented, because only the encoder knows how much+ * lookahead it introduced - get the pre-skip wrong and every player reports a duration a+ * few milliseconds out and starts playback slightly early.+ *+ * Android does not hand it over in the split `csd-0`/`csd-1`/`csd-2` form an extractor+ * produces. The platform encoder packs the header, the codec delay and the seek pre-roll+ * into one codec-config buffer as three `AOPUS...` marker chunks, so [fromCodecConfig]+ * accepts either shape, and [build] covers a codec that supplies neither.+ */+internal object OpusHead {++ const val SIZE = 19+ const val SAMPLE_RATE = 48_000++ private const val MAGIC = "OpusHead"+ private const val HEADER_MARKER = "AOPUSHDR"+ private const val MARKER_SIZE = 8+ private const val CHUNK_LENGTH_SIZE = 8++ /**+ * The Opus encoder's lookahead at 48 kHz, used only when a codec reports no header at+ * all. `libopus` returns 6.5 ms for every configuration the encoder is used in here.+ */+ const val DEFAULT_PRE_SKIP = 312++ fun build(channels: Int, preSkip: Int, inputSampleRate: Int): ByteArray {+ val head = ByteArray(SIZE)+ MAGIC.toByteArray(Charsets.ISO_8859_1).copyInto(head)+ head[8] = 1 // version+ head[9] = channels.toByte()+ head[10] = preSkip.toByte()+ head[11] = (preSkip ushr 8).toByte()+ OggPages.writeIntLe(head, 12, inputSampleRate)+ // Output gain 0 dB at 16..17, channel mapping family 0 at 18, both already zero.+ return head+ }++ /**+ * Pulls the identification header out of a codec-config buffer, or returns null when+ * there is nothing recognisable in it.+ */+ fun fromCodecConfig(config: ByteArray): ByteArray? {+ if (startsWith(config, 0, MAGIC)) {+ return config.takeIf { it.size >= SIZE }?.copyOfRange(0, SIZE)+ }+ if (startsWith(config, 0, HEADER_MARKER)) {+ val lengthAt = MARKER_SIZE+ val payloadAt = lengthAt + CHUNK_LENGTH_SIZE+ if (config.size < payloadAt) return null+ val length = readLongLe(config, lengthAt)+ if (length < SIZE || payloadAt + length > config.size) return null+ val head = config.copyOfRange(payloadAt, payloadAt + length.toInt())+ return head.takeIf { startsWith(it, 0, MAGIC) }+ }+ return null+ }++ fun preSkipOf(head: ByteArray): Int =+ (head[10].toInt() and 0xff) or ((head[11].toInt() and 0xff) shl 8)++ /**+ * How many 48 kHz samples one Opus packet decodes to, from its table-of-contents byte.+ *+ * Read rather than assumed, because the granule positions in the Ogg pages are what+ * decide the file's reported duration and how it seeks, and an encoder is free to pick+ * its own frame size.+ */+ fun packetSamples(packet: ByteArray, size: Int): Int {+ if (size < 1) return 0+ val toc = packet[0].toInt() and 0xff+ val config = toc ushr 3+ val frameSamples = when {+ // SILK and hybrid modes: 10, 20, 40 or 60 ms, chosen by the low two bits.+ config < 12 -> intArrayOf(480, 960, 1920, 2880)[config and 3]+ config < 16 -> intArrayOf(480, 960)[config and 1]+ // CELT: 2.5, 5, 10 or 20 ms.+ else -> intArrayOf(120, 240, 480, 960)[config and 3]+ }+ val frames = when (toc and 3) {+ 0 -> 1+ 1, 2 -> 2+ // An arbitrary-frame packet carries the count in the low six bits of byte one.+ else -> if (size < 2) return 0 else packet[1].toInt() and 0x3f+ }+ return frameSamples * frames+ }++ private fun startsWith(buffer: ByteArray, offset: Int, text: String): Boolean {+ if (buffer.size < offset + text.length) return false+ for (i in text.indices) {+ if (buffer[offset + i] != text[i].code.toByte()) return false+ }+ return true+ }++ private fun readLongLe(buffer: ByteArray, offset: Int): Long {+ var value = 0L+ for (i in 0 until 8) value = value or ((buffer[offset + i].toLong() and 0xff) shl (8 * i))+ return value+ }+}
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriterTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriterTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriterTest.ktnew file mode 100644index 0000000000..7509755759--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriterTest.kt@@ -0,0 +1,268 @@+package com.vayunmathur.musicbrainz.data.download++import java.io.ByteArrayInputStream+import com.vayunmathur.musicbrainz.data.library.TagReader+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Tests for the Ogg container the transcoder writes from scratch.+ *+ * Nothing here can be checked on a device from a unit test, and a malformed page is the kind+ * of mistake a player rejects silently, so the framing is pinned down byte by byte: the+ * magic, the flags, contiguous page sequence numbers, the granule positions that decide the+ * reported duration, and a CRC that a reader will actually verify. The strongest check is the+ * last one - a stream built here, retagged by [OggOpusTagger] and read back by [TagReader] -+ * because that is exactly the path a download takes.+ */+class OggStreamWriterTest {++ private val serial = 0x1A2B3C4D++ private class ParsedPage(+ val headerType: Int,+ val granulePosition: Long,+ val serial: Int,+ val sequence: Int,+ val lacing: List<Int>,+ val payload: ByteArray,+ val checksumValid: Boolean,+ ) {+ /** Splits the payload back into packets using the lacing table. */+ val packets: List<ByteArray>+ get() {+ val out = ArrayList<ByteArray>()+ var at = 0+ var start = 0+ for (value in lacing) {+ at += value+ if (value < 255) {+ out.add(payload.copyOfRange(start, at))+ start = at+ }+ }+ return out+ }+ }++ private fun parse(stream: ByteArray): List<ParsedPage> {+ val pages = ArrayList<ParsedPage>()+ var offset = 0+ while (offset + 27 <= stream.size) {+ assertEquals("OggS", String(stream, offset, 4, Charsets.ISO_8859_1), "page at $offset")+ val segmentCount = stream[offset + 26].toInt() and 0xff+ val lacing = (0 until segmentCount).map { stream[offset + 27 + it].toInt() and 0xff }+ val payloadStart = offset + 27 + segmentCount+ val payloadSize = lacing.sum()+ val end = payloadStart + payloadSize++ val whole = stream.copyOfRange(offset, end)+ val stated = readIntLe(whole, 22)+ for (i in 22..25) whole[i] = 0++ pages.add(+ ParsedPage(+ headerType = stream[offset + 5].toInt() and 0xff,+ granulePosition = readLongLe(stream, offset + 6),+ serial = readIntLe(stream, offset + 14),+ sequence = readIntLe(stream, offset + 18),+ lacing = lacing,+ payload = stream.copyOfRange(payloadStart, end),+ checksumValid = OggPages.crc(whole) == stated,+ ),+ )+ offset = end+ }+ return pages+ }++ private fun readIntLe(buf: ByteArray, offset: Int): Int =+ (buf[offset].toInt() and 0xff) or+ ((buf[offset + 1].toInt() and 0xff) shl 8) or+ ((buf[offset + 2].toInt() and 0xff) shl 16) or+ ((buf[offset + 3].toInt() and 0xff) shl 24)++ private fun readLongLe(buf: ByteArray, offset: Int): Long {+ var value = 0L+ for (i in 0 until 8) value = value or ((buf[offset + i].toLong() and 0xff) shl (8 * i))+ return value+ }++ /** A 20 ms stereo CELT packet of [size] bytes, which is the shape the encoder emits. */+ private fun opusPacket(size: Int, fill: Int = 0x5A): ByteArray =+ ByteArray(size) { if (it == 0) 0xFC.toByte() else (fill + it).toByte() }++ /** Builds a stream of [packets] 20 ms packets, as the transcoder does. */+ private fun stream(packets: Int, packetSize: Int = 640, channels: Int = 2): ByteArray {+ val writer = OggStreamWriter(serial)+ val preSkip = OpusHead.DEFAULT_PRE_SKIP+ writer.writeHeaderPacket(OpusHead.build(channels, preSkip, 48_000))+ writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags()))+ var samples = 0L+ repeat(packets) {+ samples += 960+ writer.writeAudioPacket(opusPacket(packetSize), preSkip + samples)+ }+ return writer.finish(preSkip + samples)+ }++ // ------------------------------------------------------------------++ @Test+ fun `opens with the two header packets on pages of their own`() {+ val pages = parse(stream(packets = 3))+ assertTrue(pages.size >= 3, "head, tags and audio need at least three pages")++ assertEquals(OggPages.FLAG_BEGIN_OF_STREAM, pages[0].headerType)+ assertEquals(1, pages[0].packets.size, "the head packet must not share its page")+ assertEquals("OpusHead", String(pages[0].payload, 0, 8, Charsets.ISO_8859_1))+ assertEquals(0L, pages[0].granulePosition, "a header page has no granule position")++ assertEquals(0, pages[1].headerType)+ assertEquals("OpusTags", String(pages[1].payload, 0, 8, Charsets.ISO_8859_1))+ assertEquals(0L, pages[1].granulePosition)+ }++ @Test+ fun `numbers pages contiguously and stamps them all with one serial`() {+ val pages = parse(stream(packets = 300))+ pages.forEachIndexed { index, page ->+ assertEquals(index, page.sequence, "page $index is out of sequence")+ assertEquals(serial, page.serial, "page $index belongs to another stream")+ }+ }++ @Test+ fun `checksums every page it writes`() {+ parse(stream(packets = 120)).forEachIndexed { index, page ->+ assertTrue(page.checksumValid, "page $index has a bad CRC and would be dropped")+ }+ }++ @Test+ fun `flags only the last page end of stream`() {+ val pages = parse(stream(packets = 200))+ pages.dropLast(1).forEachIndexed { index, page ->+ assertEquals(0, page.headerType and OggPages.FLAG_END_OF_STREAM, "page $index")+ }+ assertEquals(+ OggPages.FLAG_END_OF_STREAM,+ pages.last().headerType and OggPages.FLAG_END_OF_STREAM,+ "without an end-of-stream flag a reader treats the file as truncated",+ )+ }++ @Test+ fun `records the granule position of the last packet to finish on each page`() {+ val packets = 200+ val pages = parse(stream(packets = packets))+ val audio = pages.drop(2)++ var seen = 0+ for (page in audio) {+ seen += page.packets.size+ assertEquals(+ OpusHead.DEFAULT_PRE_SKIP + seen * 960L,+ page.granulePosition,+ "granule position decides the duration a player reports",+ )+ }+ assertEquals(packets, seen, "every packet must reach a page")+ }++ @Test+ fun `groups audio packets rather than paging each one`() {+ val audio = parse(stream(packets = 200)).drop(2)+ assertTrue(+ audio.all { it.packets.size > 1 },+ "one packet per page would treble the container overhead",+ )+ assertTrue(+ audio.all { it.lacing.size <= OggPages.MAX_SEGMENTS },+ "a page cannot carry more than 255 segments",+ )+ }++ @Test+ fun `keeps the packets byte for byte`() {+ val expected = opusPacket(640)+ val recovered = parse(stream(packets = 40)).drop(2).flatMap { it.packets }+ assertEquals(40, recovered.size)+ assertTrue(recovered.all { it.contentEquals(expected) }, "a packet was altered in paging")+ }++ @Test+ fun `pages a packet that will not fit in one page`() {+ // 255 segments hold 65025 bytes at most, so this has to be continued onto a second+ // page - the case embedded cover art hits in the comment header.+ val writer = OggStreamWriter(serial)+ val big = ByteArray(70_000) { (it % 251).toByte() }+ writer.writeHeaderPacket(big)+ val pages = parse(writer.finish(0L))++ assertTrue(pages.size > 1, "an oversized packet must span pages")+ assertEquals(OggPages.FLAG_BEGIN_OF_STREAM, pages[0].headerType)+ assertEquals(+ OggPages.FLAG_CONTINUED,+ pages[1].headerType and OggPages.FLAG_CONTINUED,+ "a page that starts mid-packet must say so",+ )+ val rejoined = pages.dropLast(1).fold(ByteArray(0)) { acc, page -> acc + page.payload }+ assertTrue(rejoined.contentEquals(big), "the packet did not survive being split")+ }++ @Test+ fun `writes a stream the tagger can retag and the library can read`() {+ val tagged = assertNotNull(+ OggOpusTagger.tag(+ stream(packets = 50),+ VorbisTags(+ title = "Weightless",+ artist = "Marconi Union",+ album = "Ambient Transmissions",+ recordingId = "12345678-1234-1234-1234-123456789abc",+ ),+ ),+ "the tagger should recognise a stream this writer produced",+ )++ val tags = TagReader.readOgg(ByteArrayInputStream(tagged))+ assertEquals("Weightless", tags.title)+ assertEquals("Marconi Union", tags.artist)+ assertEquals("Ambient Transmissions", tags.album)+ assertEquals("12345678-1234-1234-1234-123456789abc", tags.recordingId)++ // Retagging must leave the audio pages valid, or the file plays the tags and nothing+ // else. Page numbering and CRCs are recomputed, so both are checked again.+ val pages = parse(tagged)+ pages.forEachIndexed { index, page ->+ assertEquals(index, page.sequence, "page $index is out of sequence after retagging")+ assertTrue(page.checksumValid, "page $index has a bad CRC after retagging")+ }+ assertEquals(+ 50 * 960L + OpusHead.DEFAULT_PRE_SKIP,+ pages.last().granulePosition,+ "retagging must not change the stream's length",+ )+ }++ @Test+ fun `builds the lacing table so a reader can find the packet boundary`() {+ assertEquals(listOf(0), OggPages.lacingFor(0))+ assertEquals(listOf(1), OggPages.lacingFor(1))+ assertEquals(listOf(254), OggPages.lacingFor(254))+ // A length that is an exact multiple of 255 needs a trailing zero-length segment,+ // otherwise the packet reads as continuing onto the next page.+ assertEquals(listOf(255, 0), OggPages.lacingFor(255))+ assertEquals(listOf(255, 255, 0), OggPages.lacingFor(510))+ assertEquals(listOf(255, 130), OggPages.lacingFor(385))+ }++ @Test+ fun `refuses to retag something that is not an ogg stream`() {+ assertNull(OggOpusTagger.tag(ByteArray(100), VorbisTags(title = "x")))+ }+}
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OpusHeadTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OpusHeadTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OpusHeadTest.ktnew file mode 100644index 0000000000..4b2e6fd5bf--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OpusHeadTest.kt@@ -0,0 +1,171 @@+package com.vayunmathur.musicbrainz.data.download++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Tests for the Opus identification header and the packet arithmetic around it.+ *+ * The pre-skip and the packet duration are what the Ogg writer turns into granule positions,+ * so a mistake in either shows up as a file whose reported duration is wrong and which seeks+ * to the wrong place - never as a crash. The marker-chunk parsing matters because that is the+ * shape the platform encoder actually produces, and a stray `AOPUSHDR` copied into the file+ * as if it were a header would make the whole stream unreadable.+ */+class OpusHeadTest {++ private fun longLe(value: Long) = ByteArray(8) { (value ushr (8 * it)).toByte() }++ @Test+ fun `builds a header a reader can parse`() {+ val head = OpusHead.build(channels = 2, preSkip = 312, inputSampleRate = 44_100)+ assertEquals(OpusHead.SIZE, head.size)+ assertEquals("OpusHead", String(head, 0, 8, Charsets.ISO_8859_1))+ assertEquals(1, head[8].toInt(), "version")+ assertEquals(2, head[9].toInt(), "channel count")+ assertEquals(312, OpusHead.preSkipOf(head))+ assertEquals(44_100, readIntLe(head, 12), "original sample rate is informational")+ assertEquals(0, head[16].toInt() or head[17].toInt(), "output gain should be 0 dB")+ assertEquals(0, head[18].toInt(), "channel mapping family 0 covers mono and stereo")+ }++ @Test+ fun `round trips a pre-skip that needs both bytes`() {+ val head = OpusHead.build(channels = 1, preSkip = 3_840, inputSampleRate = 48_000)+ assertEquals(3_840, OpusHead.preSkipOf(head))+ }++ @Test+ fun `reads a plain header straight out of a codec config`() {+ val head = OpusHead.build(channels = 2, preSkip = 120, inputSampleRate = 48_000)+ // Extractors hand over exactly 19 bytes; a decoder may append its own padding.+ val parsed = assertNotNull(OpusHead.fromCodecConfig(head + ByteArray(5)))+ assertEquals(120, OpusHead.preSkipOf(parsed))+ assertEquals(OpusHead.SIZE, parsed.size)+ }++ @Test+ fun `unwraps the marker chunks the platform encoder produces`() {+ val head = OpusHead.build(channels = 2, preSkip = 312, inputSampleRate = 48_000)+ val config = "AOPUSHDR".toByteArray(Charsets.ISO_8859_1) ++ longLe(head.size.toLong()) ++ head ++ "AOPUSDLY".toByteArray(Charsets.ISO_8859_1) + longLe(8) + longLe(6_500_000) ++ "AOPUSPRL".toByteArray(Charsets.ISO_8859_1) + longLe(8) + longLe(80_000_000)++ val parsed = assertNotNull(+ OpusHead.fromCodecConfig(config),+ "the marker-chunk form is what the platform encoder actually emits",+ )+ assertEquals("OpusHead", String(parsed, 0, 8, Charsets.ISO_8859_1))+ assertEquals(312, OpusHead.preSkipOf(parsed))+ assertTrue(parsed.size >= OpusHead.SIZE)+ }++ @Test+ fun `rejects a codec config it cannot make sense of`() {+ assertNull(OpusHead.fromCodecConfig(ByteArray(0)))+ assertNull(OpusHead.fromCodecConfig(ByteArray(40)))+ assertNull(OpusHead.fromCodecConfig("OpusHead".toByteArray(Charsets.ISO_8859_1)))+ // A marker chunk claiming more than the buffer holds must not be trusted.+ assertNull(+ OpusHead.fromCodecConfig(+ "AOPUSHDR".toByteArray(Charsets.ISO_8859_1) + longLe(9_000) + ByteArray(19),+ ),+ )+ // A marker chunk whose payload is not a header either.+ assertNull(+ OpusHead.fromCodecConfig(+ "AOPUSHDR".toByteArray(Charsets.ISO_8859_1) + longLe(19) + ByteArray(19),+ ),+ )+ }++ // ------------------------------------------------------------------+ // Packet durations+ // ------------------------------------------------------------------++ /** A packet whose TOC declares [config] and frame-count code [code]. */+ private fun packet(config: Int, code: Int, frameCount: Int = 0): ByteArray =+ byteArrayOf(((config shl 3) or code).toByte(), frameCount.toByte())++ @Test+ fun `reads the frame length out of the table of contents byte`() {+ // SILK narrowband: 10, 20, 40, 60 ms.+ assertEquals(480, OpusHead.packetSamples(packet(0, 0), 2))+ assertEquals(960, OpusHead.packetSamples(packet(1, 0), 2))+ assertEquals(1_920, OpusHead.packetSamples(packet(2, 0), 2))+ assertEquals(2_880, OpusHead.packetSamples(packet(3, 0), 2))+ // Hybrid: 10 or 20 ms only.+ assertEquals(480, OpusHead.packetSamples(packet(12, 0), 2))+ assertEquals(960, OpusHead.packetSamples(packet(13, 0), 2))+ // CELT fullband, which is what a 256 kbps music encode uses: 2.5, 5, 10, 20 ms.+ assertEquals(120, OpusHead.packetSamples(packet(28, 0), 2))+ assertEquals(960, OpusHead.packetSamples(packet(31, 0), 2))+ }++ @Test+ fun `counts the frames a packet carries`() {+ assertEquals(960, OpusHead.packetSamples(packet(31, 0), 2), "one frame")+ assertEquals(1_920, OpusHead.packetSamples(packet(31, 1), 2), "two equal frames")+ assertEquals(1_920, OpusHead.packetSamples(packet(31, 2), 2), "two unequal frames")+ assertEquals(+ 2_880,+ OpusHead.packetSamples(packet(31, 3, frameCount = 3), 2),+ "an arbitrary-frame packet counts them in the second byte",+ )+ }++ @Test+ fun `returns nothing for a packet too short to describe itself`() {+ assertEquals(0, OpusHead.packetSamples(ByteArray(0), 0))+ assertEquals(0, OpusHead.packetSamples(packet(31, 3), 1))+ }++ private fun readIntLe(buf: ByteArray, offset: Int): Int =+ (buf[offset].toInt() and 0xff) or+ ((buf[offset + 1].toInt() and 0xff) shl 8) or+ ((buf[offset + 2].toInt() and 0xff) shl 16) or+ ((buf[offset + 3].toInt() and 0xff) shl 24)+}++/**+ * Tests for reading the downloaded bytes as a media source.+ *+ * The contract has two sharp edges - end of stream is -1, not 0, and a read that overruns+ * the end must be truncated rather than refused - and getting either wrong makes the+ * extractor report a perfectly good download as corrupt.+ */+class ByteArrayReadsTest {++ private val source = ByteArray(100) { it.toByte() }++ @Test+ fun `copies from the requested position`() {+ val destination = ByteArray(10)+ assertEquals(4, ByteArrayReads.readAt(source, 20, destination, 2, 4))+ assertEquals(listOf<Byte>(0, 0, 20, 21, 22, 23, 0, 0, 0, 0), destination.toList())+ }++ @Test+ fun `truncates a read that runs past the end`() {+ val destination = ByteArray(20)+ assertEquals(5, ByteArrayReads.readAt(source, 95, destination, 0, 20))+ assertEquals(listOf<Byte>(95, 96, 97, 98, 99), destination.take(5))+ }++ @Test+ fun `reports end of stream as minus one`() {+ assertEquals(-1, ByteArrayReads.readAt(source, 100, ByteArray(4), 0, 4))+ assertEquals(-1, ByteArrayReads.readAt(source, 500, ByteArray(4), 0, 4))+ assertEquals(-1, ByteArrayReads.readAt(source, -1, ByteArray(4), 0, 4))+ }++ @Test+ fun `treats a zero-length read as nothing to do`() {+ assertEquals(0, ByteArrayReads.readAt(source, 10, ByteArray(4), 0, 0))+ }+}