Firefly Open Source Community

Title: Android hardware encoding and decoding [Print This Page]

Author: Andy    Time: 12/12/2014 11:41
Title: Android hardware encoding and decoding

Android hardware encoding mainly realized by MediaCodec.

The official documentation of Android shows as below.

  1. MediaCodec codec = MediaCodec.createDecoderByType(type);
  2. codec.configure(format, ...);
  3. codec.start();
  4. ByteBuffer[] inputBuffers = codec.getInputBuffers();
  5. ByteBuffer[] outputBuffers = codec.getOutputBuffers();
  6. for (;;) {
  7.    int inputBufferIndex = codec.dequeueInputBuffer(timeoutUs);
  8.    if (inputBufferIndex >= 0) {
  9.      // fill inputBuffers[inputBufferIndex] with valid data
  10.      ...
  11.      codec.queueInputBuffer(inputBufferIndex, ...);
  12.    }

  13.    int outputBufferIndex = codec.dequeueOutputBuffer(timeoutUs);
  14.    if (outputBufferIndex >= 0) {
  15.      // outputBuffer is ready to be processed or rendered.
  16.      ...
  17.      codec.releaseOutputBuffer(outputBufferIndex, ...);
  18.    } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
  19.      outputBuffers = codec.getOutputBuffers();
  20.    } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
  21.      // Subsequent data will conform to new format.
  22.      MediaFormat format = codec.getOutputFormat();
  23.      ...
  24.    }
  25. }
  26. codec.stop();
  27. codec.release();
  28. codec = null;
Copy the code

We made a demo using MdeiaCodec to realize the hardware encoding and decoding of camera.

This is the GUI of the demo.


The GUI is simple£¬the preview of camera located at the lower right corner.

The window on the middle is the picture after decoding.

  1. private void doCodec(byte[] data){
  2.                 int et = mEncoder.encode(data , 0 , data.length, buffer1, 0);
  3.                 Log.d("buncodec","encode et="+et);
  4.                  
  5.                 int dt = mDecoder.decode(buffer1, 0 , et , buffer2 , 0);
  6.                 Log.d("buncodec","decode dt="+dt);
  7.                  
  8.                  
  9.                 // The data of NV21 showed by YUV Image, efficient less, just a demo.
  10.         YuvImage image = new YuvImage(buffer2,
  11.                 getPreviewFormat(), getPreviewWidth(), getPreviewHeight(),
  12.                 null);
  13.         setData(image,getPreviewWidth(),getPreviewHeight());
  14.          
  15.         image = null ;
  16.         }
Copy the code

The information of logcat show as below:


From the information above, you can see the preview data length of 1280*720 pixels is 1280*720*3/2=1382400£»

Et stands for the length after encoding,it¡¯s within 50000.

Dt stands for the length after decoding,it¡¯s back to 1382400.


Author: ZZP    Time: 12/13/2014 09:26
handsome boy




Welcome Firefly Open Source Community (https://bbs.t-firefly.com/) Powered by Discuz! X3.1