Search code examples
javaandroidconcurrencyandroid-mediacodec

MediaCodec multi-threaded reference


There are two threads to access the same MediaCodec object, and they may need to run simultaneously. Now I have a problem: when the two threads are running at the same time, the code is following:

try {
   mediaCodec.releaseOutputBuffer(encoderStatus, false);
} catch (IllegalStateException e) {
    e.printStackTrace();
}

How to deal with this code?

Because the two threads reference to the same mediaCodec object, one thread executes this code will affect the other thread's reference to the mediaCodec, and the other thread cannot run normally. How to solve it?


Solution

  • I am not sure if it is wise access MediaCodec from multiple thread, you will need to be careful with the synchronization, and a lot of synchronization may stall your (encoding/decoding) process.

    If you want to push it to the PC while saving a MP4 file, I think what you should do is do your MediaCodec stuff in one thread, put the output result in a thread safe queue and process the result in other thread asynchronously ( can be done by using Handler, Executor etc)