Media Codec: Encoding and Decoding Media Files
This tutorial demonstrates how you can encode and decode media files.
Warm-up
Become familiar with the Media Codec API basics by learning about:
-
Initializing Media Codecs
Initialize the media codecs for use.
-
Managing Media Codecs
Prepare and start the codec.
-
Releasing Resources
Reset the codec and destroy the handle.
Initializing Media Codecs
Before using the Media codec:
-
To use the functions and data types of the Media Codec API (in mobile and wearable applications), include the <media_codec.h> header file in your application:
#include <media_codec.h>
- Define a handle for the media codec and pass it to the mediacodec_create() function. The handle must be passed to all other Media Codec APIs.
mediacodec_h *mediacodec; ret = mediacodec_create(&mediacodec);
- If the handle is created normally, set the codec and configuration using the mediacodec_set_codec() function.
The enumerations mediacodec_codec_type_e (in mobile and wearable applications) and mediacodec_support_type_e (in mobile and wearable applications) define the media codec type and support type.
ret = mediacodec_set_codec(mediacodec, (mediacodec_codec_type_e)codecid, flag);
- Set the video decoder using the mediacodec_set_vdec_info() or mediacodec_set_venc_info() function.
ret = mediacodec_set_vdec_info(mediacodec, width, height); // Or ret = mediacodec_set_venc_info(mediacodec, width, height, fps, target_bits);
Managing Media Codecs
The Media Codec usage follows a basic pattern:
- Create and configure the Media Codec handle.
- Loop until done:
- If an input buffer is ready, read a chunk of input and copy it into the buffer.
- If an output buffer is ready, copy the output from the buffer.
- Release the Media Codec handle.
To manage the codec process loop:
- If the prerequisites are set normally, prepare the media codec using the mediacodec_prepare() function.
ret = mediacodec_prepare(mediacodec);
- Start the media codec using the mediacodec_process_input() and mediacodec_get_output() functions.
media_packet_h in_buf = NULL; ret = mediacodec_process_input (mediacodec, in_buf, 0); media_packet_h output_buf = NULL; ret = mediacodec_get_output (mediacodec, &output_buf, 0);
Releasing Resources
To reset the codec and destroy the handle using the mediacodec_unprepare() and mediacodec_destroy() functions after you have finished work with the media codec:
ret = mediacodec_unprepare(mediacodec); ret = mediacodec_destroy(mediacodec);
Afterwards, the media codec state is changed to MEDIACODEC_STATE_NONE.