“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Hard decoding in Android

If you have not made a player or have no experience with the screen, you will feel that hard decoding is very strange, even if you know every word, but do not know where to start with it. The purpose of this article is to give you a basic understanding of hard decoding, at least in the idea is clear.

Hard decoding and soft decoding

All videos that can be played have their own formats. If we want to play these videos, we need to decode them according to the corresponding formats. This part of the operation is called decoding.

Decoding is divided into two types: hard decoding and soft decoding.

  • Hard decoding: the use of mobile phone decoding chip decoding, fast speed, no heat, the disadvantage is that the hardware is not a unified platform, poor adaptation. Like MediaCodeC for Android phones

  • Soft decoding: the use of mobile phone CPU decoding, will heat, the advantage is very good adaptation, such as FFmpeg

This article is about hard decoding in Android, also known as MediaCodeC

MediaCodeC

MediaCodeC is essentially the key to the multimedia underlying library, which can be used to drive the underlying chip for encoding or decoding.

I’m quoting a picture from the Internet

There are many processors on the codec chip. When any part of the chip is idle, it is thrown in to encode/decode and the encoded/decoded data is returned to MediaCodeC

Basic use of MediaCodeC

MediaCodeC create

MediaCodeC objects are typically obtained in the following way


private final static String MIME_TYPE = "video/avc";

MediaCodec codec = MediaCodec.createDecoderByType(MIME_TYPE);

Copy the code

MediaCodeC configuration

Configuration methods have a separate object called MediaFormat, through which we can set keyframes, bit streams, frame rates, and so on. The code is as follows:


final MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, width, height);

format.setInteger(MediaFormat.KEY_BIT_RATE, width * height);

format.setInteger(MediaFormat.KEY_FRAME_RATE, 20);

format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);

Copy the code

MediaCodeC maps to the carrier

You have to map the data to the carrier to show it.


codec.configure(format, surface, null, 0);

Copy the code

MediaCodeC gets the width and height

Get the width and height of the media through MediaCodeC.

The program should first have the default width and height, and then dynamically modify the width and height of the display area in the code stream if the width and height change, to achieve the same proportion of the effect, and further can also be filled according to the width or according to the height.


MediaFormat currentFormat = mediaCodec.getOutputFormat();

int mediaW = currentFormat.getInteger("width");

int mediaH = currentFormat.getInteger("height");

Copy the code