library/media: add tests for tagging, resampling and codec pipelines
- Commit
27d8093aedbfdd2581c9eea018311b0c23c7c0d5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:15 UTC (29 days ago)
- Parents
b66d3e9
Merged INSTRUCTION coverage 50.5% -> 88.4% (2564/5076 -> 4489/5076). New unit tests (39): VorbisComments comment-list layout, cover-art picture blocks and blank-field omission; OggOpusTagger page rewriting, multi-page comments, truncation and renumbering; ByteArrayMediaDataSource and OpusTranscoder failure paths under Robolectric; resampler, PCM queue and Ogg page edge cases. New instrumented tests (6, emulator): AAC/MP4 and WebM/Opus sources are generated with the platform encoders, then transcoded and remuxed end to end, including streaming progress, cancellation and garbage input. This covers OpusPump (89.8%) and OpusRemuxer (71.4%), which have no JVM codec. Verified: testDebugUnitTest 83/83, instrumented 6/6, lint and detekt pass (detekt jar needed one --refresh-dependencies fetch). Untestable remainder: codec-refusal error branches inside OpusTranscoder (57.5%) and the no-audio-track remux path. (cherry picked from commit 7f38a7655102b407d2d8d20bd2ef2ce6c12cb3a4)
Diff
library/media/src/androidTest/java/com/vayunmathur/library/media/CodecPipelineTest.kt
diff --git a/library/media/src/androidTest/java/com/vayunmathur/library/media/CodecPipelineTest.kt b/library/media/src/androidTest/java/com/vayunmathur/library/media/CodecPipelineTest.ktnew file mode 100644index 0000000000..f616cbf7f7--- /dev/null+++ b/library/media/src/androidTest/java/com/vayunmathur/library/media/CodecPipelineTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.library.media++import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.media.MediaMuxer+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.ByteBuffer+import kotlin.math.PI+import kotlin.math.sin++/**+ * End-to-end codec pipelines on a real device: the platform decoders, resampler+ * and Opus encoder that [OpusTranscoder] drives, and the demux/mux pair that+ * [OpusRemuxer] drives, none of which exist under Robolectric.+ */+class CodecPipelineTest {++ private val context get() = InstrumentationRegistry.getInstrumentation().targetContext++ // ------------------------------------------------------------------+ // Source generation: encode a sine tone with the platform encoders.+ // ------------------------------------------------------------------++ private fun pcmSine(sampleRate: Int, channels: Int, seconds: Double = 0.5): ByteArray {+ val frames = (sampleRate * seconds).toInt()+ val out = ByteArray(frames * channels * 2)+ var at = 0+ for (frame in 0 until frames) {+ val value = (sin(2.0 * PI * 440.0 * frame / sampleRate) * 12_000).toInt()+ repeat(channels) {+ out[at++] = value.toByte()+ out[at++] = (value shr 8).toByte()+ }+ }+ return out+ }++ /** Encodes PCM into a muxed file (MP4/AAC or WebM/Opus) and returns its bytes. */+ private fun encodeToFile(mime: String, muxerFormat: Int, suffix: String): ByteArray {+ val sampleRate = 44_100+ val channels = 2+ val pcm = pcmSine(sampleRate, channels)+ val file = File.createTempFile("codec-src", suffix, context.cacheDir)+ file.delete()+ val codec = MediaCodec.createEncoderByType(mime)+ val muxer = MediaMuxer(file.absolutePath, muxerFormat)+ try {+ val format = MediaFormat.createAudioFormat(mime, sampleRate, channels).apply {+ setInteger(MediaFormat.KEY_BIT_RATE, 128_000)+ setInteger(MediaFormat.KEY_PCM_ENCODING, android.media.AudioFormat.ENCODING_PCM_16BIT)+ if (mime == MediaFormat.MIMETYPE_AUDIO_AAC) {+ setInteger(+ MediaFormat.KEY_AAC_PROFILE,+ MediaCodecInfo.CodecProfileLevel.AACObjectLC,+ )+ }+ }+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ codec.start()+ var track = -1+ var muxerStarted = false+ var inputDone = false+ var outputDone = false+ var pcmOffset = 0+ var framesQueued = 0L+ val info = MediaCodec.BufferInfo()+ while (!outputDone) {+ if (!inputDone) {+ val index = codec.dequeueInputBuffer(10_000)+ if (index >= 0) {+ val buffer = codec.getInputBuffer(index)!!+ buffer.clear()+ if (pcmOffset >= pcm.size) {+ codec.queueInputBuffer(+ index, 0, 0,+ framesQueued * 1_000_000L / sampleRate,+ MediaCodec.BUFFER_FLAG_END_OF_STREAM,+ )+ inputDone = true+ } else {+ val chunk = minOf(buffer.remaining(), pcm.size - pcmOffset)+ val frames = chunk / (channels * 2) * (channels * 2)+ buffer.put(pcm, pcmOffset, frames)+ codec.queueInputBuffer(+ index, 0, frames,+ framesQueued * 1_000_000L / sampleRate, 0,+ )+ framesQueued += frames / (channels * 2)+ pcmOffset += frames+ }+ }+ }+ val outIndex = codec.dequeueOutputBuffer(info, 10_000)+ when {+ outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {+ track = muxer.addTrack(codec.outputFormat)+ muxer.start()+ muxerStarted = true+ }+ outIndex >= 0 -> {+ val buffer = codec.getOutputBuffer(outIndex)!!+ if (info.size > 0 && muxerStarted &&+ info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0+ ) {+ buffer.position(info.offset)+ buffer.limit(info.offset + info.size)+ muxer.writeSampleData(track, buffer, info)+ }+ codec.releaseOutputBuffer(outIndex, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {+ outputDone = true+ }+ }+ }+ }+ assertTrue("muxer must have started for $mime", muxerStarted)+ // Stop the muxer before reading: an MP4 without its moov atom (or an+ // unfinalised WebM) has no readable tracks, so reading first would+ // hand the transcoders a file with nothing in it.+ runCatching { codec.stop() }+ runCatching { muxer.stop() }+ val bytes = file.readBytes()+ assertTrue("encoded $mime source must not be empty", bytes.size > 500)+ return bytes+ } finally {+ runCatching { codec.stop() }+ runCatching { codec.release() }+ runCatching { muxer.stop() }+ runCatching { muxer.release() }+ file.delete()+ }+ }++ private fun aacMp4(): ByteArray =+ encodeToFile(MediaFormat.MIMETYPE_AUDIO_AAC, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, ".m4a")++ private fun opusWebM(): ByteArray =+ encodeToFile(MediaFormat.MIMETYPE_AUDIO_OPUS, MediaMuxer.OutputFormat.MUXER_OUTPUT_WEBM, ".webm")++ private fun assertOggOpus(bytes: ByteArray, minSize: Int = 200) {+ assertTrue("expected an Ogg stream, got ${bytes.size} bytes", bytes.size > minSize)+ assertEquals("OggS", String(bytes, 0, 4, Charsets.ISO_8859_1))+ assertTrue("stream must carry OpusHead", containsSubarray(bytes, "OpusHead".toByteArray()))+ assertTrue("stream must carry OpusTags", containsSubarray(bytes, "OpusTags".toByteArray()))+ }++ private fun containsSubarray(haystack: ByteArray, needle: ByteArray): Boolean {+ outer@ for (i in 0..haystack.size - needle.size) {+ for (j in needle.indices) if (haystack[i + j] != needle[j]) continue@outer+ return true+ }+ return false+ }++ // ------------------------------------------------------------------+ // OpusTranscoder+ // ------------------------------------------------------------------++ @Test+ fun transcode_convertsAacMp4ToOggOpus() {+ val result = OpusTranscoder.transcode(aacMp4())+ assertNotNull("AAC MP4 must transcode on device", result)+ assertOggOpus(result!!)+ // The result must be retaggable, which is the path every download takes.+ val tagged = OggOpusTagger.tag(result, VorbisTags(title = "Tone"))+ assertNotNull(tagged)+ assertTrue(String(tagged!!, Charsets.UTF_8).contains("TITLE=Tone"))+ }++ @Test+ fun transcodeTo_streamsAndReportsProgress() {+ val sink = ByteArrayOutputStream()+ val progress = ArrayList<Float>()+ val count = OpusTranscoder.transcodeTo(aacMp4(), sink) { progress.add(it) }+ assertNotNull(count)+ assertEquals(sink.size().toLong(), count)+ assertOggOpus(sink.toByteArray())+ assertTrue("progress must be reported", progress.isNotEmpty())+ assertTrue(progress.all { it in 0f..1f })+ }++ @Test+ fun transcode_cancelledReturnsNull() {+ val sink = ByteArrayOutputStream()+ val count = OpusTranscoder.transcodeTo(aacMp4(), sink, isStopped = { true })+ assertNull(count)+ assertNull(OpusTranscoder.transcode(aacMp4(), isStopped = { true }))+ }++ @Test+ fun transcode_reencodesWebmOpus() {+ val result = OpusTranscoder.transcode(opusWebM())+ assertNotNull(result)+ assertOggOpus(result!!)+ }++ // ------------------------------------------------------------------+ // OpusRemuxer+ // ------------------------------------------------------------------++ @Test+ fun remux_convertsWebmOpusToOggOpus() {+ val result = OpusRemuxer.remux(context, opusWebM())+ assertNotNull("WebM/Opus must remux on device", result)+ assertOggOpus(result!!)+ }++ @Test+ fun remux_rejectsGarbage() {+ assertNull(OpusRemuxer.remux(context, ByteArray(512) { 0x33 }))+ assertNull(OpusRemuxer.remux(context, ByteArray(0)))+ }+}
library/media/src/test/java/com/vayunmathur/library/media/ByteArrayMediaDataSourceTest.kt
diff --git a/library/media/src/test/java/com/vayunmathur/library/media/ByteArrayMediaDataSourceTest.kt b/library/media/src/test/java/com/vayunmathur/library/media/ByteArrayMediaDataSourceTest.ktnew file mode 100644index 0000000000..2994a335d6--- /dev/null+++ b/library/media/src/test/java/com/vayunmathur/library/media/ByteArrayMediaDataSourceTest.kt@@ -0,0 +1,40 @@+package com.vayunmathur.library.media++import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ByteArrayMediaDataSourceTest {++ private val bytes = ByteArray(64) { (it * 3).toByte() }++ @Test+ fun `reads through the media data source contract`() {+ val source = ByteArrayMediaDataSource(bytes)+ assertEquals(bytes.size.toLong(), source.size)+ val destination = ByteArray(16)+ assertEquals(8, source.readAt(4, destination, 3, 8))+ assertTrue(bytes.copyOfRange(4, 12).contentEquals(destination.copyOfRange(3, 11)))+ }++ @Test+ fun `truncates at the end and reports eos as minus one`() {+ val source = ByteArrayMediaDataSource(bytes)+ val destination = ByteArray(16)+ assertEquals(4, source.readAt(60, destination, 0, 16))+ assertEquals(-1, source.readAt(64, destination, 0, 4))+ assertEquals(-1, source.readAt(-5, destination, 0, 4))+ assertEquals(0, source.readAt(10, destination, 0, 0))+ }++ @Test+ fun `close is a no op`() {+ val source = ByteArrayMediaDataSource(bytes)+ source.close()+ assertEquals(bytes.size.toLong(), source.size)+ assertEquals(2, source.readAt(0, ByteArray(4), 0, 2))+ }+}
library/media/src/test/java/com/vayunmathur/library/media/MediaEdgeCasesTest.kt
diff --git a/library/media/src/test/java/com/vayunmathur/library/media/MediaEdgeCasesTest.kt b/library/media/src/test/java/com/vayunmathur/library/media/MediaEdgeCasesTest.ktnew file mode 100644index 0000000000..050e5fc62f--- /dev/null+++ b/library/media/src/test/java/com/vayunmathur/library/media/MediaEdgeCasesTest.kt@@ -0,0 +1,231 @@+package com.vayunmathur.library.media++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Edge cases for the already-covered pure classes: error branches and boundaries. */+class MediaEdgeCasesTest {++ // PolyphaseResampler validation and helper branches++ @Test+ fun `resampler rejects non positive rates and bad channel counts`() {+ assertFailsWith<IllegalArgumentException> { PolyphaseResampler(0, 48_000, 1) }+ assertFailsWith<IllegalArgumentException> { PolyphaseResampler(44_100, 0, 1) }+ assertFailsWith<IllegalArgumentException> { PolyphaseResampler(-44_100, 48_000, 1) }+ assertFailsWith<IllegalArgumentException> { PolyphaseResampler(44_100, 48_000, 0) }+ assertFailsWith<IllegalArgumentException> { PolyphaseResampler(44_100, 48_000, 3) }+ }++ @Test+ fun `resampler handles zero and negative frame counts`() {+ val resampler = PolyphaseResampler(44_100, 48_000, 1)+ assertEquals(0, resampler.process(FloatArray(0), 0).size)+ assertEquals(0, resampler.process(FloatArray(4), -3).size)+ val passthrough = PolyphaseResampler(48_000, 48_000, 2)+ assertEquals(0, passthrough.process(FloatArray(0), 0).size)+ assertEquals(0, passthrough.flush().size, "passthrough flush has nothing to drain")+ }++ @Test+ fun `resampler flush without input is empty and mono downsample works`() {+ assertEquals(0, PolyphaseResampler(96_000, 48_000, 1).flush().size)+ val resampler = PolyphaseResampler(192_000, 48_000, 1)+ assertEquals(1, resampler.interpolation)+ assertEquals(4, resampler.decimation)+ val out = resampler.process(FloatArray(19_200) { 0.25f }, 19_200) + resampler.flush()+ assertTrue(kotlin.math.abs(out.size - 4_800) <= 1, "got ${out.size}")+ val settled = out.copyOfRange(500, out.size - 500)+ assertTrue(settled.all { kotlin.math.abs(it - 0.25f) < 0.01f }, "DC must survive decimation")+ }++ @Test+ fun `taps per phase stays within bounds for every rate pair`() {+ for (rate in listOf(8_000, 16_000, 22_050, 44_100, 96_000, 192_000)) {+ val resampler = PolyphaseResampler(rate, 48_000, 1)+ assertTrue(+ resampler.tapsPerPhase in 16..192 && resampler.tapsPerPhase % 2 == 0,+ "$rate Hz taps=${resampler.tapsPerPhase}",+ )+ }+ // Passthrough needs no filter at all.+ assertEquals(0, PolyphaseResampler(48_000, 48_000, 1).tapsPerPhase)+ }++ @Test+ fun `stereo resampling keeps both channels at unity dc`() {+ val resampler = PolyphaseResampler(44_100, 48_000, 2)+ val frames = 20_000+ val input = FloatArray(frames * 2) { if (it % 2 == 0) 0.4f else -0.2f }+ val out = resampler.process(input, frames) + resampler.flush()+ val settledFrames = (2_000 until (out.size / 2 - 2_000))+ for (frame in settledFrames) {+ assertTrue(kotlin.math.abs(out[frame * 2] - 0.4f) < 2e-3f, "left at frame $frame")+ assertTrue(kotlin.math.abs(out[frame * 2 + 1] + 0.2f) < 2e-3f, "right at frame $frame")+ }+ }++ // PcmBuffers / PcmQueue edges++ @Test+ fun `fold to stereo rejects stereo and mono`() {+ assertFailsWith<IllegalArgumentException> { PcmBuffers.foldToStereo(FloatArray(8), 4, 2) }+ assertFailsWith<IllegalArgumentException> { PcmBuffers.foldToStereo(FloatArray(8), 4, 1) }+ assertEquals(0, PcmBuffers.foldToStereo(FloatArray(0), 0, 4))+ }++ @Test+ fun `pcm reads and writes of nothing`() {+ val out = FloatArray(2)+ assertEquals(0, PcmBuffers.readS16(ByteBuffer.allocate(0), out))+ assertEquals(0, PcmBuffers.readFloat(ByteBuffer.allocate(0), out))+ assertEquals(0, PcmBuffers.writeS16(floatArrayOf(0.5f), 0, ByteArray(2)))+ // Partial conversion: only the requested sample count is written.+ val bytes = ByteArray(6) { 0x7f }+ assertEquals(2, PcmBuffers.writeS16(floatArrayOf(0f, 1f, 1f), 1, bytes))+ assertEquals(0x7f, bytes[2])+ }++ @Test+ fun `pcm queue ignores empty writes and refuses sub frame drains`() {+ val queue = PcmQueue(initialCapacity = 8)+ queue.write(ByteArray(4), 0)+ queue.write(ByteArray(4), -1)+ assertEquals(0, queue.size)+ assertEquals(0, queue.drainTo(ByteBuffer.allocate(8), 8, 4))+ queue.write(byteArrayOf(1, 2, 3), 3)+ assertEquals(0, queue.drainTo(ByteBuffer.allocate(8), 8, 4), "3 bytes is not a stereo frame")+ assertEquals(3, queue.size)+ queue.write(byteArrayOf(4), 1)+ val destination = ByteBuffer.allocate(8)+ assertEquals(4, queue.drainTo(destination, 8, 4))+ assertTrue(byteArrayOf(1, 2, 3, 4).contentEquals(destination.array().copyOf(4)))+ assertEquals(0, queue.drainTo(ByteBuffer.allocate(8), 8, 4), "drained queue stays drained")+ }++ @Test+ fun `pcm queue default capacity holds a frame`() {+ val queue = PcmQueue()+ queue.write(ByteArray(16) { it.toByte() }, 16)+ assertEquals(16, queue.size)+ }++ // OggPages helpers++ @Test+ fun `ogg long and int writers round trip`() {+ val buffer = ByteArray(16)+ OggPages.writeLongLe(buffer, 4, 0x0102030405060708L)+ assertTrue(+ byteArrayOf(8, 7, 6, 5, 4, 3, 2, 1).contentEquals(buffer.copyOfRange(4, 12)),+ )+ assertTrue(byteArrayOf(8, 7, 6, 5, 4, 3, 2, 1).contentEquals(OggPages.longLe(0x0102030405060708L)))+ OggPages.writeIntLe(buffer, 0, -1)+ assertTrue(byteArrayOf(-1, -1, -1, -1).contentEquals(buffer.copyOfRange(0, 4)))+ OggPages.writeIntLe(buffer, 0, Int.MIN_VALUE)+ assertEquals(0x80.toByte(), buffer[3])+ }++ @Test+ fun `ogg crc is zero for empty input and changes with content`() {+ assertEquals(0, OggPages.crc(ByteArray(0)))+ val a = OggPages.crc(byteArrayOf(1, 2, 3))+ val b = OggPages.crc(byteArrayOf(1, 2, 4))+ assertTrue(a != b)+ assertEquals(a, OggPages.crc(byteArrayOf(1, 2, 3)), "crc must be deterministic")+ }++ @Test+ fun `forPacket splits exactly at the segment limit`() {+ // 255*255 = 65025 payload bytes fills one page of segments exactly (plus terminator).+ val packet = ByteArray(65_025) { (it % 251).toByte() }+ val pages = OggPages.forPacket(packet, 7, 0, 42L, OggPages.FLAG_BEGIN_OF_STREAM)+ val rejoined = pages.fold(ByteArray(0)) { acc, page ->+ val segmentCount = page[26].toInt() and 0xff+ acc + page.copyOfRange(27 + segmentCount, page.size)+ }+ assertTrue(packet.contentEquals(rejoined))+ // An empty packet is a single zero lacing value on one page.+ val empty = OggPages.forPacket(ByteArray(0), 7, 0, 0L, 0)+ assertEquals(1, empty.size)+ assertEquals(0, empty[0][27].toInt(), "empty packet lacing terminator")+ }++ @Test+ fun `writer finish with no audio still emits an end of stream page`() {+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(99, sink)+ writer.writeHeaderPacket(OpusHead.build(1, 312, 48_000))+ writer.finish(1234L)+ val bytes = sink.toByteArray()+ assertTrue(bytes.isNotEmpty())+ // Last page carries EOS flag; parse via tagger-independent check of flag byte.+ assertEquals("OggS", String(bytes, 0, 4, Charsets.ISO_8859_1))+ }++ @Test+ fun `writer flushes by packet count as well as by segments`() {+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(5, sink)+ writer.writeHeaderPacket(OpusHead.build(2, 312, 48_000))+ var granule = 0L+ // 51 tiny packets: the 51st forces a flush of the first 50 onto their own page.+ repeat(51) {+ granule += 960+ writer.writeAudioPacket(ByteArray(4) { 0xFC.toByte() }, granule)+ }+ val sizeBeforeFinish = sink.size()+ writer.finish(granule)+ assertTrue(sink.size() > sizeBeforeFinish, "finish writes the trailing page")+ assertTrue(sizeBeforeFinish > 0, "packet-count flush must emit before finish")+ }++ // OpusHead edges++ @Test+ fun `opus head rejects truncated marker chunks`() {+ assertNull(OpusHead.fromCodecConfig("AOPUSHDR".toByteArray(Charsets.ISO_8859_1)))+ assertNull(+ OpusHead.fromCodecConfig(+ "AOPUSHDR".toByteArray(Charsets.ISO_8859_1) + ByteArray(4),+ ),+ )+ // Length below the header size.+ val head = OpusHead.build(2, 312, 48_000)+ val tooShort = "AOPUSHDR".toByteArray(Charsets.ISO_8859_1) ++ ByteArray(8) { (10L ushr (8 * it)).toByte() } + head+ assertNull(OpusHead.fromCodecConfig(tooShort))+ // A bare header shorter than 19 bytes.+ assertNull(OpusHead.fromCodecConfig(head.copyOf(10)))+ }++ @Test+ fun `opus head build encodes mono and max preskip`() {+ val head = OpusHead.build(1, 65_535, 8_000)+ assertEquals(1, head[9].toInt())+ assertEquals(65_535, OpusHead.preSkipOf(head))+ assertEquals(OpusHead.SIZE, head.size)+ }++ @Test+ fun `packet samples covers silk hybrid and celt configs`() {+ fun packet(config: Int, code: Int, count: Byte = 1) =+ byteArrayOf(((config shl 3) or code).toByte(), count)+ // SILK wideband configs 4..11 share the 10/20/40/60 table by low bits.+ assertEquals(480, OpusHead.packetSamples(packet(4, 0), 2))+ assertEquals(2_880, OpusHead.packetSamples(packet(11, 0), 2))+ // Hybrid configs 14/15: 10/20 ms by low bit.+ assertEquals(480, OpusHead.packetSamples(packet(14, 0), 2))+ assertEquals(960, OpusHead.packetSamples(packet(15, 0), 2))+ // CELT configs use the 2.5/5/10/20 table.+ assertEquals(240, OpusHead.packetSamples(packet(17, 0), 2))+ assertEquals(480, OpusHead.packetSamples(packet(18, 0), 2))+ // Code 3 with a zero frame count byte is degenerate but must not crash.+ assertEquals(0, OpusHead.packetSamples(packet(31, 3, 0), 2))+ }+}
library/media/src/test/java/com/vayunmathur/library/media/OggOpusTaggerTest.kt
diff --git a/library/media/src/test/java/com/vayunmathur/library/media/OggOpusTaggerTest.kt b/library/media/src/test/java/com/vayunmathur/library/media/OggOpusTaggerTest.ktnew file mode 100644index 0000000000..c63eaf1650--- /dev/null+++ b/library/media/src/test/java/com/vayunmathur/library/media/OggOpusTaggerTest.kt@@ -0,0 +1,235 @@+package com.vayunmathur.library.media++import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class OggOpusTaggerTest {++ private val serial = 0x0BADCAFE++ private class Page(+ val headerType: Int,+ val granule: Long,+ val serial: Int,+ val sequence: Int,+ val lacing: List<Int>,+ val payload: ByteArray,+ val crcValid: Boolean,+ val raw: ByteArray,+ )++ private fun parse(stream: ByteArray): List<Page> {+ val pages = ArrayList<Page>()+ var offset = 0+ while (offset + 27 <= stream.size) {+ assertEquals("OggS", String(stream, offset, 4, Charsets.ISO_8859_1))+ 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 end = payloadStart + lacing.sum()+ val whole = stream.copyOfRange(offset, end)+ val stated = readIntLe(whole, 22)+ for (i in 22..25) whole[i] = 0+ pages.add(+ Page(+ headerType = stream[offset + 5].toInt() and 0xff,+ granule = readLongLe(stream, offset + 6),+ serial = readIntLe(stream, offset + 14),+ sequence = readIntLe(stream, offset + 18),+ lacing = lacing,+ payload = stream.copyOfRange(payloadStart, end),+ crcValid = OggPages.crc(whole) == stated,+ raw = stream.copyOfRange(offset, end),+ ),+ )+ offset = end+ }+ assertEquals(stream.size, offset, "parser must consume the whole stream")+ 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+ }++ private fun packetsOf(page: Page): List<ByteArray> {+ val out = ArrayList<ByteArray>()+ var at = 0; var start = 0+ for (value in page.lacing) {+ at += value+ if (value < 255) { out.add(page.payload.copyOfRange(start, at)); start = at }+ }+ return out+ }++ /** Builds head + comment + one audio page with the given packets. */+ private fun oggFile(+ commentPacket: ByteArray,+ audioPacket: ByteArray = ByteArray(100) { 0xFC.toByte() },+ audioGranule: Long = 960L,+ ): ByteArray {+ val out = ByteArrayOutputStream()+ var sequence = 0+ val head = OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000)+ for (page in OggPages.forPacket(head, serial, sequence, 0L, OggPages.FLAG_BEGIN_OF_STREAM)) {+ out.write(page); sequence+++ }+ val commentStart = sequence+ for (page in OggPages.forPacket(commentPacket, serial, sequence, 0L, 0)) {+ out.write(page); sequence+++ }+ check(sequence > commentStart)+ out.write(+ OggPages.build(+ OggPages.FLAG_END_OF_STREAM, audioGranule, serial, sequence,+ OggPages.lacingFor(audioPacket.size), audioPacket, 0, audioPacket.size,+ ),+ )+ return out.toByteArray()+ }++ private fun streamWithAudio(packets: Int): ByteArray {+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(serial, sink)+ writer.writeHeaderPacket(OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000))+ writer.writeHeaderPacket(OggOpusTagger.buildOpusTagsPacket(VorbisTags()))+ var samples = 0L+ repeat(packets) {+ samples += 960+ writer.writeAudioPacket(ByteArray(200) { 0xFC.toByte() }, samples)+ }+ writer.finish(samples)+ return sink.toByteArray()+ }++ @Test+ fun `rejects empty and non ogg input`() {+ assertNull(OggOpusTagger.tag(ByteArray(0), VorbisTags(title = "x")))+ assertNull(OggOpusTagger.tag(ByteArray(200) { 0x11 }, VorbisTags(title = "x")))+ assertNull(OggOpusTagger.tag("OggS".toByteArray(Charsets.ISO_8859_1), VorbisTags(title = "x")))+ }++ @Test+ fun `rejects a stream with only a head page`() {+ val sink = ByteArrayOutputStream()+ val writer = OggStreamWriter(serial, sink)+ writer.writeHeaderPacket(OpusHead.build(2, OpusHead.DEFAULT_PRE_SKIP, 48_000))+ writer.finish(0L)+ // finish adds an (empty) EOS page; tagging a 2-page stream whose second page+ // has no segments must also fail rather than crash.+ assertNull(OggOpusTagger.tag(sink.toByteArray(), VorbisTags(title = "x")))+ }++ @Test+ fun `rejects a truncated stream`() {+ val full = streamWithAudio(10)+ assertNull(OggOpusTagger.tag(full.copyOf(full.size - 10), VorbisTags(title = "x")))+ assertNull(OggOpusTagger.tag(full.copyOf(30), VorbisTags(title = "x")))+ }++ @Test+ fun `rejects a comment packet that never terminates`() {+ val bigComment = "OpusTags".toByteArray(Charsets.ISO_8859_1) + ByteArray(70_000) { 0x55 }+ val full = oggFile(bigComment)+ val pages = parse(full)+ // Keep only head + first comment page (all its lacing values are 255).+ val firstCommentEnd = pages[0].raw.size + pages[1].raw.size+ assertNull(OggOpusTagger.tag(full.copyOf(firstCommentEnd), VorbisTags(title = "x")))+ }++ @Test+ fun `replaces the comment packet and renumbers audio pages`() {+ val source = streamWithAudio(10)+ val before = parse(source)+ val tagged = assertNotNull(+ OggOpusTagger.tag(source, VorbisTags(title = "New Title", artist = "New Artist")),+ )+ val after = parse(tagged)+ // Head untouched byte for byte.+ assertTrue(before[0].raw.contentEquals(after[0].raw))+ after.forEachIndexed { index, page ->+ assertEquals(index, page.sequence, "page $index sequence")+ assertEquals(serial, page.serial)+ assertTrue(page.crcValid, "page $index crc")+ }+ val commentText = String(after[1].payload, Charsets.UTF_8)+ assertTrue(commentText.contains("TITLE=New Title"), commentText)+ assertTrue(commentText.contains("ARTIST=New Artist"))+ assertEquals(before.last().granule, after.last().granule)+ assertEquals(+ before.drop(2).flatMap { packetsOf(it) }.map { it.toList() },+ after.drop(2).flatMap { packetsOf(it) }.map { it.toList() },+ "audio packets must survive retagging byte for byte",+ )+ }++ @Test+ fun `shrinks a multi page comment and renumbers the audio after it`() {+ val bigComment = "OpusTags".toByteArray(Charsets.ISO_8859_1) ++ VorbisComments.buildCommentList(VorbisTags(lyrics = "x".repeat(70_000)))+ val source = oggFile(bigComment)+ val beforeCount = parse(source).size+ assertTrue(beforeCount > 3, "comment should span pages, got $beforeCount pages")+ val tagged = assertNotNull(OggOpusTagger.tag(source, VorbisTags(title = "Small")))+ val after = parse(tagged)+ assertEquals(3, after.size, "head + one comment page + one audio page")+ after.forEachIndexed { index, page ->+ assertEquals(index, page.sequence)+ assertTrue(page.crcValid, "page $index crc")+ }+ assertTrue(String(after[1].payload, Charsets.UTF_8).contains("TITLE=Small"))+ assertEquals(960L, after[2].granule)+ }++ @Test+ fun `grows the comment past one page when cover art is embedded`() {+ val source = streamWithAudio(5)+ val art = ByteArray(80_000) { (it % 253).toByte() }+ val tagged = assertNotNull(+ OggOpusTagger.tag(source, VorbisTags(title = "Art", coverArt = art, coverIsPng = true)),+ )+ val pages = parse(tagged)+ pages.forEachIndexed { index, page ->+ assertEquals(index, page.sequence)+ assertTrue(page.crcValid, "page $index crc")+ }+ assertTrue(pages.size > 3, "cover art comment must span pages")+ }++ @Test+ fun `buildOpusTagsPacket starts with the magic and the vendor`() {+ val packet = OggOpusTagger.buildOpusTagsPacket(VorbisTags(title = "Hi"))+ assertEquals("OpusTags", String(packet, 0, 8, Charsets.ISO_8859_1))+ assertTrue(String(packet, Charsets.UTF_8).contains("TITLE=Hi"))+ assertTrue(String(packet, Charsets.UTF_8).contains(VorbisComments.VENDOR))+ }++ @Test+ fun `vorbis tags default to absent fields`() {+ val tags = VorbisTags()+ assertEquals(null, tags.title)+ assertEquals(null, tags.trackNumber)+ assertEquals(null, tags.coverArt)+ assertEquals(false, tags.coverIsPng)+ val full = VorbisTags(+ title = "t", artist = "a", album = "al", albumArtist = "aa", date = "d",+ trackNumber = 1, trackTotal = 2, discNumber = 1, lyrics = "l",+ recordingId = "r", releaseId = "rel", coverArt = byteArrayOf(1), coverIsPng = true,+ )+ assertEquals("t", full.title)+ assertEquals(1, full.trackNumber)+ assertTrue(full.coverIsPng)+ }+}
library/media/src/test/java/com/vayunmathur/library/media/OpusTranscoderRobolectricTest.kt
diff --git a/library/media/src/test/java/com/vayunmathur/library/media/OpusTranscoderRobolectricTest.kt b/library/media/src/test/java/com/vayunmathur/library/media/OpusTranscoderRobolectricTest.ktnew file mode 100644index 0000000000..2e904b21e5--- /dev/null+++ b/library/media/src/test/java/com/vayunmathur/library/media/OpusTranscoderRobolectricTest.kt@@ -0,0 +1,37 @@+package com.vayunmathur.library.media++import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The failure paths of the transcoder that do not need a real codec: under+ * Robolectric the extractor finds no tracks, which is exactly the "no+ * decodable audio" case a caller has to handle. The happy path runs on a+ * device in CodecPipelineTest.+ */+@RunWith(RobolectricTestRunner::class)+class OpusTranscoderRobolectricTest {++ @Test+ fun `transcode of undecodable bytes returns null`() {+ assertNull(OpusTranscoder.transcode(ByteArray(256) { 0x42 }))+ assertNull(OpusTranscoder.transcode(ByteArray(0)))+ }++ @Test+ fun `transcodeTo of undecodable bytes writes nothing and returns null`() {+ val sink = ByteArrayOutputStream()+ assertNull(OpusTranscoder.transcodeTo(ByteArray(256) { 0x42 }, sink))+ assertEquals(0, sink.size())+ }++ @Test+ fun `transcode constants are the documented stream values`() {+ assertEquals(1_000_000L, OpusTranscoder.US_PER_SECOND)+ assertEquals("OpusTranscoder", OpusTranscoder.TAG)+ }+}
library/media/src/test/java/com/vayunmathur/library/media/VorbisCommentsTest.kt
diff --git a/library/media/src/test/java/com/vayunmathur/library/media/VorbisCommentsTest.kt b/library/media/src/test/java/com/vayunmathur/library/media/VorbisCommentsTest.ktnew file mode 100644index 0000000000..26211b2830--- /dev/null+++ b/library/media/src/test/java/com/vayunmathur/library/media/VorbisCommentsTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.library.media++import java.util.Base64+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class VorbisCommentsTest {++ 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 readIntBe(buf: ByteArray, offset: Int): Int =+ ((buf[offset].toInt() and 0xff) shl 24) or+ ((buf[offset + 1].toInt() and 0xff) shl 16) or+ ((buf[offset + 2].toInt() and 0xff) shl 8) or+ (buf[offset + 3].toInt() and 0xff)++ /** Parses buildCommentList output into (vendor, comments). */+ private fun parse(bytes: ByteArray): Pair<String, List<String>> {+ var offset = 0+ val vendorLen = readIntLe(bytes, offset); offset += 4+ val vendor = String(bytes, offset, vendorLen, Charsets.UTF_8); offset += vendorLen+ val count = readIntLe(bytes, offset); offset += 4+ val comments = ArrayList<String>()+ repeat(count) {+ val len = readIntLe(bytes, offset); offset += 4+ comments.add(String(bytes, offset, len, Charsets.UTF_8)); offset += len+ }+ assertEquals(bytes.size, offset, "comment list must consume exactly its bytes")+ return vendor to comments+ }++ @Test+ fun `empty tags produce only the vendor and a zero count`() {+ val (vendor, comments) = parse(VorbisComments.buildCommentList(VorbisTags()))+ assertEquals(VorbisComments.VENDOR, vendor)+ assertEquals("ModernApps", vendor)+ assertTrue(comments.isEmpty())+ }++ @Test+ fun `writes every text tag in identifying-first order`() {+ val tags = VorbisTags(+ title = "Song", artist = "Artist", album = "Album", albumArtist = "Album Artist",+ date = "2024-01-02", trackNumber = 3, trackTotal = 12, discNumber = 2,+ lyrics = "la la", recordingId = "rec-1", releaseId = "rel-1",+ )+ val (_, comments) = parse(VorbisComments.buildCommentList(tags))+ assertEquals(+ listOf(+ "TITLE=Song", "ARTIST=Artist", "ALBUM=Album", "ALBUMARTIST=Album Artist",+ "DATE=2024-01-02", "TRACKNUMBER=3", "TRACKTOTAL=12", "DISCNUMBER=2",+ "MUSICBRAINZ_TRACKID=rec-1", "MUSICBRAINZ_ALBUMID=rel-1", "LYRICS=la la",+ ),+ comments,+ )+ }++ @Test+ fun `omits null and blank fields but keeps zero numbers`() {+ val tags = VorbisTags(title = " ", artist = "", album = null, trackNumber = 0, trackTotal = null)+ val (_, comments) = parse(VorbisComments.buildCommentList(tags))+ assertEquals(listOf("TRACKNUMBER=0"), comments)+ }++ @Test+ fun `keeps unicode values as utf8`() {+ val (_, comments) = parse(+ VorbisComments.buildCommentList(VorbisTags(title = "Björk — Homogenic")),+ )+ assertEquals(listOf("TITLE=Björk — Homogenic"), comments)+ }++ @Test+ fun `embeds cover art as a base64 flac picture block after the text tags`() {+ val image = byteArrayOf(1, 2, 3, 4, 5)+ val tags = VorbisTags(title = "T", coverArt = image, coverIsPng = true)+ val (_, comments) = parse(VorbisComments.buildCommentList(tags))+ assertEquals(2, comments.size)+ assertEquals("TITLE=T", comments[0])+ assertTrue(comments[1].startsWith("METADATA_BLOCK_PICTURE="))+ val block = Base64.getDecoder().decode(comments[1].removePrefix("METADATA_BLOCK_PICTURE="))+ var offset = 0+ assertEquals(3, readIntBe(block, offset), "front cover picture type"); offset += 4+ val mimeLen = readIntBe(block, offset); offset += 4+ assertEquals("image/png", String(block, offset, mimeLen, Charsets.ISO_8859_1)); offset += mimeLen+ assertEquals(0, readIntBe(block, offset), "description length"); offset += 4+ repeat(4) { assertEquals(0, readIntBe(block, offset)); offset += 4 }+ val imageLen = readIntBe(block, offset); offset += 4+ assertEquals(image.size, imageLen)+ assertTrue(image.contentEquals(block.copyOfRange(offset, offset + imageLen)))+ assertEquals(block.size, offset + imageLen)+ }++ @Test+ fun `labels jpeg cover art and ignores empty art`() {+ val (_, jpeg) = parse(+ VorbisComments.buildCommentList(VorbisTags(coverArt = byteArrayOf(9), coverIsPng = false)),+ )+ val block = Base64.getDecoder().decode(jpeg.single().removePrefix("METADATA_BLOCK_PICTURE="))+ val mimeLen = readIntBe(block, 4)+ assertEquals("image/jpeg", String(block, 8, mimeLen, Charsets.ISO_8859_1))++ val (_, empty) = parse(+ VorbisComments.buildCommentList(VorbisTags(coverArt = ByteArray(0))),+ )+ assertTrue(empty.isEmpty(), "empty cover art must not emit a picture comment")+ }++ @Test+ fun `intLe writes little endian bytes`() {+ assertTrue(byteArrayOf(0, 0, 0, 0).contentEquals(VorbisComments.intLe(0)))+ assertTrue(byteArrayOf(1, 0, 0, 0).contentEquals(VorbisComments.intLe(1)))+ assertTrue(+ byteArrayOf(0x4D, 0x3C, 0x2B, 0x1A).contentEquals(VorbisComments.intLe(0x1A2B3C4D)),+ )+ assertTrue(+ byteArrayOf(-1, -1, -1, -1).contentEquals(VorbisComments.intLe(-1)),+ )+ assertFalse(VorbisComments.intLe(256).contentEquals(VorbisComments.intLe(1)))+ }+}