musicbrainz: count granule positions from the decodable sample total
- Commit
67a25891a0503847b5a5e0572a474abe0530f158- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-20 17:52 UTC (3 months ago)
- Parents
7a95e3c
Diff
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.ktindex 692b9c47c8..398407de76 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriter.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriter.kt@@ -188,8 +188,9 @@ internal class OggStreamWriter(private val serialNumber: Int) { } /**- * 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.+ * Queues an audio packet. [granulePosition] is the total number of samples a decoder gets+ * out of the stream through the end of this 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
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusTranscoder.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusTranscoder.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusTranscoder.ktindex 0fa7fd031c..2aaa36f019 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusTranscoder.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/OpusTranscoder.kt@@ -129,7 +129,10 @@ private class OpusPump( var encoder: MediaCodec? = null private set - private val info = MediaCodec.BufferInfo()+ // One per codec: sharing a BufferInfo would work only because the loop happens to read+ // each one before the other overwrites it, which is not a property worth relying on.+ private val decoderInfo = MediaCodec.BufferInfo()+ private val encoderInfo = MediaCodec.BufferInfo() private val queue = PcmQueue() private val writer = OggStreamWriter(Random.nextInt()) @@ -194,7 +197,14 @@ private class OpusPump( private fun feedDecoder(): Boolean { val index = decoder.dequeueInputBuffer(TIMEOUT_US) if (index < 0) return false- val buffer = decoder.getInputBuffer(index) ?: return false+ val buffer = decoder.getInputBuffer(index)+ if (buffer == null) {+ // Hand the index straight back rather than dropping it: a buffer taken from the+ // codec and never returned is gone for the rest of the run, and enough of them+ // would leave the pump with nothing to queue into and no way to reach the end.+ decoder.queueInputBuffer(index, 0, 0, 0, 0)+ return false+ } val size = extractor.readSampleData(buffer, 0) if (size < 0) { decoder.queueInputBuffer(index, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)@@ -207,7 +217,7 @@ private class OpusPump( /** Drains one decoded buffer into the encoder's queue. Returns true at end of stream. */ private fun drainDecoder(): Boolean {- val index = decoder.dequeueOutputBuffer(info, TIMEOUT_US)+ val index = decoder.dequeueOutputBuffer(decoderInfo, TIMEOUT_US) if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { configure(decoder.outputFormat) return false@@ -215,17 +225,17 @@ private class OpusPump( if (index < 0) return false val buffer = decoder.getOutputBuffer(index)- if (buffer != null && info.size > 0) {+ if (buffer != null && decoderInfo.size > 0) { // Some codecs deliver their first buffer before the format-changed event, so the // resampler is built on first use as well as on that event. if (resampler == null) configure(decoder.outputFormat)- buffer.position(info.offset)- buffer.limit(info.offset + info.size)+ buffer.position(decoderInfo.offset)+ buffer.limit(decoderInfo.offset + decoderInfo.size) resample(buffer) } decoder.releaseOutputBuffer(index, false) - if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {+ if (decoderInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { resampler?.flush()?.let { queuePcm(it, it.size) } return true }@@ -299,7 +309,11 @@ private class OpusPump( if (queue.size < frameBytes) return val index = encoder.dequeueInputBuffer(TIMEOUT_US) if (index < 0) return- val buffer = encoder.getInputBuffer(index) ?: return+ val buffer = encoder.getInputBuffer(index)+ if (buffer == null) {+ encoder.queueInputBuffer(index, 0, 0, presentationTimeUs(), 0)+ return+ } buffer.clear() // Only whole frames: half a frame queued would swap the channels of everything after // it, and the remainder is carried forward instead.@@ -333,7 +347,7 @@ private class OpusPump( /** Returns true once the encoder has reported end of stream. */ private fun drainEncoder(encoder: MediaCodec): Boolean {- val index = encoder.dequeueOutputBuffer(info, TIMEOUT_US)+ val index = encoder.dequeueOutputBuffer(encoderInfo, TIMEOUT_US) if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // Only if the format actually carries the header. Writing the fallback here // would lock it in before the codec-config buffer arrives with the real one.@@ -343,21 +357,24 @@ private class OpusPump( if (index < 0) return false val buffer = encoder.getOutputBuffer(index)- if (buffer != null && info.size > 0) {- buffer.position(info.offset)- buffer.limit(info.offset + info.size)- val bytes = ByteArray(info.size)+ if (buffer != null && encoderInfo.size > 0) {+ buffer.position(encoderInfo.offset)+ buffer.limit(encoderInfo.offset + encoderInfo.size)+ val bytes = ByteArray(encoderInfo.size) buffer.get(bytes)- if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {+ if (encoderInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) { OpusHead.fromCodecConfig(bytes)?.let { writeHeaders(it) } } else { writeHeaders(null)+ // The granule position is the total samples a decoder gets out of the stream+ // so far, which already counts the pre-skip: those are the first samples it+ // decodes and then throws away, not extra ones on top. encoded += OpusHead.packetSamples(bytes, bytes.size)- writer.writeAudioPacket(bytes, preSkip + encoded)+ writer.writeAudioPacket(bytes, encoded) } } encoder.releaseOutputBuffer(index, false)- return info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0+ return encoderInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0 } /**
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.ktindex 7509755759..07855dbacb 100644--- a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriterTest.kt+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggStreamWriterTest.kt@@ -95,18 +95,22 @@ class OggStreamWriterTest { 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. */+ /**+ * Builds a stream of [packets] 20 ms packets, as the transcoder does.+ *+ * A granule position counts every sample a decoder produces, pre-skip included, because+ * the pre-skip samples are the first ones it decodes and then discards.+ */ 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(OpusHead.build(channels, OpusHead.DEFAULT_PRE_SKIP, 48_000)) writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags())) var samples = 0L repeat(packets) { samples += 960- writer.writeAudioPacket(opusPacket(packetSize), preSkip + samples)+ writer.writeAudioPacket(opusPacket(packetSize), samples) }- return writer.finish(preSkip + samples)+ return writer.finish(samples) } // ------------------------------------------------------------------@@ -162,13 +166,19 @@ class OggStreamWriterTest { val audio = pages.drop(2) var seen = 0+ var previous = 0L for (page in audio) { seen += page.packets.size assertEquals(- OpusHead.DEFAULT_PRE_SKIP + seen * 960L,+ seen * 960L, page.granulePosition, "granule position decides the duration a player reports", )+ assertTrue(+ page.granulePosition > previous,+ "a granule position that goes backwards reads as a corrupt stream",+ )+ previous = page.granulePosition } assertEquals(packets, seen, "every packet must reach a page") }@@ -214,6 +224,25 @@ class OggStreamWriterTest { assertTrue(rejoined.contentEquals(big), "the packet did not survive being split") } + @Test+ fun `lets the final position trim the encoder's padding`() {+ // The encoder pads its last frame out to a whole 20 ms, so the last page reports the+ // real length instead of the padded one and a decoder drops the difference. Reporting+ // the padded length is how a track ends with a fraction of a second of silence.+ val writer = OggStreamWriter(serial)+ writer.writeHeaderPacket(OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000))+ writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags()))+ repeat(3) { writer.writeAudioPacket(opusPacket(640), (it + 1) * 960L) }+ val trimmed = 2_400L+ val pages = parse(writer.finish(trimmed))++ assertEquals(trimmed, pages.last().granulePosition)+ assertTrue(+ pages.last().granulePosition < 3 * 960L,+ "the reported length should be under what the packets decode to",+ )+ }+ @Test fun `writes a stream the tagger can retag and the library can read`() { val tagged = assertNotNull(@@ -243,7 +272,7 @@ class OggStreamWriterTest { assertTrue(page.checksumValid, "page $index has a bad CRC after retagging") } assertEquals(- 50 * 960L + OpusHead.DEFAULT_PRE_SKIP,+ 50 * 960L, pages.last().granulePosition, "retagging must not change the stream's length", )