I am encoding audio and video using the MediaCodec. I start a coroutine that runs the encoding using Dispatchers.IO:
CoroutineScope(Dispatchers.IO).launch {
videoEncoder.setCallback(object : MediaCodec.Callback() {
override fun onOutputBufferAvailable(mc: MediaCodec, bufferId: Int, bufferInfo: MediaCodec.BufferInfo) {
// The thread here is "main" even though a coroutine was launched using Dispatchers.IO
Log.i("encoder", "Thread name: " + Thread.currentThread().name)
}
}
}
I am using the asynchronous callback of MediaCodec to receive the encoded data. But the code inside onOutputBufferAvailable runs on the "main" thread, which is bad. Is there a way to force the encoder to run on the IO thread. Unfortunately, creating another coroutine inside onOutputBufferAvailable is not an option as creating a new coroutine each time the callback is called is way too expensive and will degrade performance.