package com.cottondb.android.testmedia import android.content.Context import android.graphics.ImageFormat import android.media.Image import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaMuxer import java.io.File import java.util.UUID /** * A tiny device-generated silent AVC/MP4 fixture for Android instrumentation tests. * * The fixture has one video track and no audio track. It uses the platform encoder and muxer, * never stores an asset, and removes a partial output whenever encoding does not complete. */ class SyntheticVideoFixture private constructor( val file: File, val width: Int, val height: Int, val frameCount: Int, ) : AutoCloseable { override fun close() { check(!file.exists() || file.delete()) { "Could not remove synthetic video fixture." } } companion object { const val WIDTH = 16 const val HEIGHT = 16 const val FRAME_COUNT = 3 fun create(context: Context, frameCount: Int = FRAME_COUNT): SyntheticVideoFixture { val output = File(context.cacheDir, "synthetic-video-${UUID.randomUUID()}.mp4") return create(output, frameCount) } /** Visible for tests which need to prove a failed output path leaves no partial file. */ fun create(output: File, frameCount: Int = FRAME_COUNT): SyntheticVideoFixture { require(frameCount in 1..100) { "Fixture frame count must be bounded." } require(output.name.endsWith(".mp4")) { "Synthetic video output must be an MP4 file." } require(!output.exists()) { "Synthetic video output already exists." } try { encode(output, frameCount) check(output.isFile && output.length() > 0L) { "The encoder did not produce an MP4 file." } return SyntheticVideoFixture(output, WIDTH, HEIGHT, frameCount) } catch (failure: Throwable) { output.delete() throw failure } } private fun encode(output: File, frameCount: Int) { val codec = MediaCodec.createEncoderByType(MIME_AVC) var muxer: MediaMuxer? = null var codecStarted = false var muxerStarted = false var failure: Throwable? = null try { muxer = MediaMuxer(output.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) val format = MediaFormat.createVideoFormat(MIME_AVC, WIDTH, HEIGHT).apply { setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible) setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE) setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE) setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1) } codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) codec.start() codecStarted = true val drain = EncoderDrain(codec, requireNotNull(muxer)) { muxerStarted = true } repeat(frameCount) { frame -> val input = awaitInputBuffer(codec) val image = requireNotNull(codec.getInputImage(input)) { "The AVC encoder did not provide a writable flexible YUV image." } fillFrame(image, frame) codec.queueInputBuffer(input, 0, FRAME_BYTES, frame.toLong() * FRAME_DURATION_US, 0) drain.available() } val endInput = awaitInputBuffer(codec) codec.queueInputBuffer( endInput, 0, 0, frameCount.toLong() * FRAME_DURATION_US, MediaCodec.BUFFER_FLAG_END_OF_STREAM, ) check(drain.untilEndOfStream()) { "The AVC encoder did not finish." } // A successful fixture is finalized synchronously. Do not hide failures from // stop(): without them an MP4 may exist but have no playable index. requireNotNull(muxer).stop() muxerStarted = false codec.stop() codecStarted = false } catch (thrown: Throwable) { failure = thrown throw thrown } finally { cleanup(codec, codecStarted, muxer, muxerStarted)?.let { cleanupFailure -> val originalFailure = failure if (originalFailure != null) originalFailure.addSuppressed(cleanupFailure) else throw cleanupFailure } } } /** Releases both platform resources even when stopping or releasing either one fails. */ private fun cleanup( codec: MediaCodec, codecStarted: Boolean, muxer: MediaMuxer?, muxerStarted: Boolean, ): Throwable? { var cleanupFailure: Throwable? = null fun attempt(action: () -> Unit) { try { action() } catch (failure: Throwable) { if (cleanupFailure == null) cleanupFailure = failure else cleanupFailure!!.addSuppressed(failure) } } // The muxer owns MP4 finalization, so stop it before releasing the encoder. if (muxerStarted && muxer != null) attempt(muxer::stop) if (codecStarted) attempt(codec::stop) attempt(codec::release) if (muxer != null) attempt(muxer::release) return cleanupFailure } private fun awaitInputBuffer(codec: MediaCodec): Int { repeat(MAX_CODEC_POLLS) { val index = codec.dequeueInputBuffer(CODEC_TIMEOUT_US) if (index >= 0) return index } error("The AVC encoder did not accept an input frame.") } private fun fillFrame(image: Image, frame: Int) { check(image.format == ImageFormat.YUV_420_888) { "The AVC encoder did not expose YUV_420_888 input." } check(image.width == WIDTH && image.height == HEIGHT) { "The AVC encoder changed the fixture dimensions." } val luma = (48 + frame * 64).toByte() fillPlane(image.planes[0], WIDTH, HEIGHT, luma) fillPlane(image.planes[1], WIDTH / 2, HEIGHT / 2, 128.toByte()) fillPlane(image.planes[2], WIDTH / 2, HEIGHT / 2, 128.toByte()) } private fun fillPlane(plane: Image.Plane, width: Int, height: Int, value: Byte) { val buffer = plane.buffer val start = buffer.position() repeat(height) { row -> repeat(width) { column -> buffer.put(start + row * plane.rowStride + column * plane.pixelStride, value) } } } private const val MIME_AVC = MediaFormat.MIMETYPE_VIDEO_AVC private const val BIT_RATE = 64_000 private const val FRAME_RATE = 10 private const val FRAME_DURATION_US = 100_000L private const val FRAME_BYTES = WIDTH * HEIGHT * 3 / 2 private const val CODEC_TIMEOUT_US = 10_000L private const val MAX_CODEC_POLLS = 500 } } private class EncoderDrain( private val codec: MediaCodec, private val muxer: MediaMuxer, private val onMuxerStarted: () -> Unit, ) { private val info = MediaCodec.BufferInfo() private var track = -1 private var muxerStarted = false fun available(): Boolean { while (true) { when (val output = codec.dequeueOutputBuffer(info, CODEC_TIMEOUT_US)) { MediaCodec.INFO_TRY_AGAIN_LATER -> return false MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> { check(!muxerStarted) { "The AVC encoder changed output format twice." } track = muxer.addTrack(codec.outputFormat) muxer.start() muxerStarted = true onMuxerStarted() } else -> if (output >= 0) { val encoded = requireNotNull(codec.getOutputBuffer(output)) { "The AVC encoder returned an empty output buffer." } try { if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0 && info.size > 0) { check(muxerStarted && track >= 0) { "The AVC encoder emitted a sample before its format." } encoded.position(info.offset) encoded.limit(info.offset + info.size) muxer.writeSampleData(track, encoded, info) } } finally { codec.releaseOutputBuffer(output, false) } if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return true } } } } fun untilEndOfStream(): Boolean { repeat(MAX_CODEC_POLLS) { if (available()) return true } return false } private companion object { const val CODEC_TIMEOUT_US = 10_000L const val MAX_CODEC_POLLS = 500 } }