Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android MediaCodec: how to request a key frame when encoding

In Android4.1, a key frame is often requested in a real-time encoding application. But how to do it using MediaCodec object? The current Android4.2 SDK seems not support it.

like image 505
user1874818 Avatar asked Dec 20 '22 12:12

user1874818


1 Answers

You can produce random keyframe by specifying MediaCodec.BUFFER_FLAG_SYNC_FRAME when queuing input buffers:

MediaCodec codec = MediaCodec.createDecoderByType(type);
codec.configure(format, ...);
codec.start();
ByteBuffer[] inputBuffers = codec.getInputBuffers();
for (;;) {
  int inputBufferIndex = codec.dequeueInputBuffer(timeoutUs);
  if (inputBufferIndex >= 0) {
    // fill inputBuffers[inputBufferIndex] with valid data
    ...
    codec.queueInputBuffer(inputBufferIndex, 0, inputBuffers[inputBufferIndex].limit(), presentationTime,
        isKeyFrame ? MediaCodec.BUFFER_FLAG_SYNC_FRAME : 0);
  }

}

Stumbled upon the need to insert random keyframe when encoding video on Galaxy Nexus. On it, MediaCodec didn't automatically produce keyframe at the start of the video.

like image 107
user2394982 Avatar answered Mar 07 '23 16:03

user2394982