MediaCodec解碼,yuv貼圖播放的實現

最近在研究stagefright視頻顯示時發現,yuv數據是在render裏直接在surface上顯示的,不須要yuv轉換成RGB。參考AsomePlayer的代碼,視頻的每一幀是經過調用了SoftwareRenderer來渲染顯示的,我參考SoftwareRenderer來直接render yuv數據顯示。html

  這樣的方式能夠實現一些經常使用的功能,好比之後攝像頭採集到的yuv,能夠直接丟yuv數據到surface顯示,無需耗時耗效率的yuv轉RGB了。也可使用MediaCode解碼媒體文件,解碼後的yuv數據直接貼圖在surface上顯示(android的播放器就是如此實現)。可是本身控制實現yuv貼圖,能夠實現yuv格式的轉化,拉伸,旋轉等操做。java

     本文介紹從SoftwareRenderer提取核心部分代碼,本身來實現yuv的顯示。android

  SoftwareRenderer就只有三個方法,一個構造函數,一個析構函數,還有一個負責顯示的render方法。構造方法裏有個很重要的地方native_window_set_buffers_geometry這裏是配置即將申請的圖形緩衝區的寬高和顏色空間,忽略了這個地方,畫面將用默認的值顯示,將形成顯示不正確。render函數裏最重要的三個地方,一個的dequeBuffer,一個是mapper,一個是queue_buffer。api

  1. native_window_set_buffers_geometry;//設置寬高以及顏色空間yuv420  
  2. native_window_dequeue_buffer_and_wait;//根據以上配置申請圖形緩衝區  
  3. mapper.lock(buf->handle, GRALLOC_USAGE_SW_WRITE_OFTEN, bounds, &dst));//將申請到的圖形緩衝區跨進程映射到用戶空間  
  4. memcpy(dst, data, dst_y_size + dst_c_size*2);//填充yuv數據到圖形緩衝區  
  5. mNativeWindow->queueBuffer;//顯示  

以上五步是surface顯示圖形必不可少的五步。app

#include <jni.h>
#include <android_runtime/AndroidRuntime.h>
#include <android_runtime/android_view_Surface.h>
#include <gui/Surface.h>
#include <assert.h>
#include <utils/Log.h>
#include <JNIHelp.h>
#include <media/stagefright/foundation/ADebug.h>
#include <ui/GraphicBufferMapper.h>
#include <cutils/properties.h>
using namespace android;ide

static uint64_t g_ulPts = 0;
static int hWidth = 0;
static int hHeight = 0;
static int halFormat = HAL_PIXEL_FORMAT_YV12;//顏色空間
static sp<Surface> surface;函數

static int ALIGN(int x, int y) {
// y must be a power of 2.
return (x + y - 1) & ~(y - 1);
}測試

static void render(
const void *data, size_t size, const sp<ANativeWindow> &nativeWindow){//,int width,int height) {
ALOGE("[%s]%d",__FILE__,__LINE__);
sp<ANativeWindow> mNativeWindow = nativeWindow;
int err;
int mCropWidth = hWidth;
int mCropHeight = hHeight;


int bufWidth = (mCropWidth + 1) & ~1;//按2對齊
int bufHeight = (mCropHeight + 1) & ~1;


ANativeWindowBuffer *buf;//描述buffer
//申請一塊空閒的圖形緩衝區
if ((err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(),
&buf)) != 0) {
ALOGW("Surface::dequeueBuffer returned error %d", err);
return;
}ui

GraphicBufferMapper &mapper = GraphicBufferMapper::get();spa

Rect bounds(mCropWidth, mCropHeight);

void *dst;
CHECK_EQ(0, mapper.lock(//用來鎖定一個圖形緩衝區並將緩衝區映射到用戶進程
buf->handle, GRALLOC_USAGE_SW_WRITE_OFTEN, bounds, &dst));//dst就指向圖形緩衝區首地址

if (true){
const uint8_t *src_y = (const uint8_t *)data;
const uint8_t *src_u = (const uint8_t *)data + hWidth * hHeight;
const uint8_t *src_v = src_u + (hWidth / 2 * hHeight / 2);

uint8_t *dst_y = (uint8_t *)dst;
size_t dst_y_size = buf->stride * buf->height;
size_t dst_c_stride = ALIGN(buf->stride / 2, 16);
size_t dst_c_size = dst_c_stride * buf->height / 2;
uint8_t *dst_v = dst_y + dst_y_size;
uint8_t *dst_u = dst_v + dst_c_size;

for (int y = 0; y < mCropHeight; ++y) {
memcpy(dst_y, src_y, mCropWidth);

src_y += hWidth;
dst_y += buf->stride;
}

for (int y = 0; y < (mCropHeight + 1) / 2; ++y) {
memcpy(dst_u, src_u, (mCropWidth + 1) / 2);
memcpy(dst_v, src_v, (mCropWidth + 1) / 2);

src_u += hWidth / 2;
src_v += hWidth / 2;
dst_u += dst_c_stride;
dst_v += dst_c_stride;
}
}

CHECK_EQ(0, mapper.unlock(buf->handle));
native_window_set_buffers_timestamp(mNativeWindow.get(), g_ulPts);
ALOGW("Surface::queueBuffer returned");
if ((err = mNativeWindow->queueBuffer(mNativeWindow.get(), buf,
-1)) != 0) {
ALOGW("Surface::queueBuffer returned error %d", err);
}
buf = NULL;
}

static void nativeTest(){
ALOGE("[%s]%d",__FILE__,__LINE__);
}

static jboolean
nativeSetVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface,jint width,jint height){
ALOGE("[%s]%d",__FILE__,__LINE__);
surface = android_view_Surface_getSurface(env, jsurface);
hWidth = width;
hHeight = height;
if(android::Surface::isValid(surface)){
ALOGE("surface is valid ");
}else {
ALOGE("surface is invalid ");
return false;
}
ALOGE("[%s][%d]\n",__FILE__,__LINE__);
sp<ANativeWindow> mNativeWindow = surface;
// Width must be multiple of 32???
//很重要,配置寬高和和指定顏色空間yuv420
//若是這裏不配置好,下面deque_buffer只能去申請一個默認寬高的圖形緩衝區
CHECK_EQ(0, native_window_set_buffers_geometry(
mNativeWindow.get(),
hWidth,
hHeight,
halFormat));
/*CHECK_EQ(0,
native_window_set_usage(
mNativeWindow.get(),
GRALLOC_USAGE_SW_READ_NEVER | GRALLOC_USAGE_SW_WRITE_OFTEN
| GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP));*/

CHECK_EQ(0,
native_window_set_scaling_mode(
mNativeWindow.get(),
NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW));//使用surfaceView能正常顯示,顯示效果也很好
// NATIVE_WINDOW_SCALING_MODE_SCALE_CROP));//使用這個模式surfaceView會花屏,textureView不會,textureView顯示效果差,不清晰
g_ulPts = 0;
return true;
}
static void
nativeShowYUV(JNIEnv *env, jobject thiz,jbyteArray yuvData){//,jint width,jint height){
//ALOGE("width = %d,height = %d",width,height);
jint len = env->GetArrayLength(yuvData);
ALOGE("len = %d",len);
jbyte *byteBuf = env->GetByteArrayElements(yuvData, 0);
render(byteBuf,len,surface);
g_ulPts += 16000;
env->ReleaseByteArrayElements(yuvData, byteBuf, 0);
}
static JNINativeMethod gMethods[] = {
{"nativeTest", "()V", (void *)nativeTest},
{"nativeSetVideoSurface", "(Landroid/view/Surface;II)Z", (void *)nativeSetVideoSurface},
{"nativeShowYUV", "([B)V", (void *)nativeShowYUV},
};

static const char* const kClassPathName = "com/hpplay/happyplay/mainServer";

// This function only registers the native methods
static int register_com_example_myyuvviewer(JNIEnv *env)
{
ALOGE("[%s]%d",__FILE__,__LINE__);
return AndroidRuntime::registerNativeMethods(env,
kClassPathName, gMethods, NELEM(gMethods));
}

jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
ALOGE("[%s]%d",__FILE__,__LINE__);
JNIEnv* env = NULL;
jint result = -1;

if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
ALOGE("ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
ALOGE("[%s]%d",__FILE__,__LINE__);
if (register_com_example_myyuvviewer(env) < 0) {
ALOGE("ERROR: MediaPlayer native registration failed\n");
goto bail;
}

/* success -- return valid version number */
result = JNI_VERSION_1_4;

bail:
return result;
}

 

Android.mk (依賴的庫比較少)

  1. LOCAL_PATH:= $(call my-dir)  
  2. include $(CLEAR_VARS)  
  3.   
  4. LOCAL_SRC_FILES:= \  
  5.     main.cpp  
  6.       
  7. LOCAL_SHARED_LIBRARIES := \  
  8.     libcutils \  
  9.     libutils \  
  10.     libbinder \  
  11.     libui \  
  12.     libgui \  
  13.     libstagefright_foundation  
  14.       
  15. LOCAL_MODULE:= MyShowYUV  
  16.   
  17. LOCAL_MODULE_TAGS := tests  
  18.   
  19. include $(BUILD_EXECUTABLE)  

 

 

本例子,使用Java建立UI並聯合JNI層操做surface來直接顯示yuv數據(yv12),開發環境爲Android 4.4,全志A23平臺。

  1. package com.example.myyuvviewer;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.os.Environment;  
  8. import android.util.Log;  
  9. import android.view.Surface;  
  10. import android.view.SurfaceHolder;  
  11. import android.view.SurfaceHolder.Callback;  
  12. import android.view.SurfaceView;  
  13.   
  14. public class MainActivity extends Activity {  
  15.   
  16.     final private String TAG = "MyYUVViewer";  
  17.     final private String FILE_NAME = "yuv_320_240.yuv";  
  18.     private int width = 320;  
  19.     private int height = 240;  
  20.     private int size = width * height * 3/2;  
  21.       
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.activity_main);  
  26.         nativeTest();  
  27.         SurfaceView surfaceview = (SurfaceView) findViewById(R.id.surfaceView);  
  28.         SurfaceHolder holder = surfaceview.getHolder();  
  29.         holder.addCallback(new Callback(){  
  30.   
  31.             @Override  
  32.             public void surfaceCreated(SurfaceHolder holder) {  
  33.                 // TODO Auto-generated method stub  
  34.                 Log.d(TAG,"surfaceCreated");  
  35.                 byte[]yuvArray = new byte[size];  
  36.                 readYUVFile(yuvArray, FILE_NAME);  
  37.                 nativeSetVideoSurface(holder.getSurface(),width,height);  
  38.                 nativeShowYUV(yuvArray);  
  39.             }  
  40.   
  41.             @Override  
  42.             public void surfaceChanged(SurfaceHolder holder, int format,  
  43.                     int width, int height) {  
  44.                 // TODO Auto-generated method stub  
  45.                   
  46.             }  
  47.   
  48.             @Override  
  49.             public void surfaceDestroyed(SurfaceHolder holder) {  
  50.                 // TODO Auto-generated method stub  
  51.                   
  52.             }});  
  53.     }  
  54.       
  55.     private boolean readYUVFile(byte[] yuvArray,String filename){  
  56.         try {  
  57.             // 若是手機插入了SD卡,並且應用程序具備訪問SD的權限  
  58.             if (Environment.getExternalStorageState().equals(  
  59.                     Environment.MEDIA_MOUNTED)) {  
  60.                 // 獲取SD卡對應的存儲目錄  
  61.                 File sdCardDir = Environment.getExternalStorageDirectory();  
  62.                 // 獲取指定文件對應的輸入流  
  63.                 FileInputStream fis = new FileInputStream(  
  64.                         sdCardDir.getCanonicalPath() +"/" + filename);  
  65.                 fis.read(yuvArray, 0, size);  
  66.                 fis.close();  
  67.                 return true;  
  68.             } else {  
  69.                 return false;  
  70.             }  
  71.         }catch (Exception e) {  
  72.             e.printStackTrace();  
  73.             return false;  
  74.         }  
  75.     }  
  76.     private native void nativeTest();  
  77.     private native boolean nativeSetVideoSurface(Surface surface,int width,int height);  
  78.     private native void nativeShowYUV(byte[] yuvArray);  
  79.     static {  
  80.         System.loadLibrary("showYUV");  
  81.     }  
  82. }  

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    

 android:layout_width="fill_parent"    

android:layout_height="fill_parent"    

android:orientation="vertical" >    

<SurfaceView    

android:id="@+id/surfaceView"    

android:layout_width="fill_parent"    

android:layout_height="360dp" />   

</LinearLayout>  

生成的so文件複製到Java項目裏 與src並列的libs/armeabi目錄下,沒有就手動建立目錄,

這樣Eclipse會自動把so庫打包進apk。

上述例子我沒有測試過。

我是使用了Mediacodec來解碼視頻,解碼後的yuv直接調用jni來貼圖實現。JNI部分的實現是同樣的,測試結果視頻能正常顯示。

MediaCodec的用法請參考api文檔使用,這裏給出MediaCodec解碼後的步驟

outputBufferIndex = mPlaybackService.mMC.dequeueOutputBuffer(bufferInfo,33000);
if ( outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED)
{
outputBuffers = mPlaybackService.mMC.getOutputBuffers();
MiniLog.i(TAG,"MediaCodec outputBuffers Changed " + outputBufferIndex);
}
else if ( outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED)
{
outputBuffers = mPlaybackService.mMC.getOutputBuffers();
MiniLog.i(TAG,"MediaCodec outputformat Changed " + mPlaybackService.mMC.getOutputFormat());
MediaFormat mf = mPlaybackService.mMC.getOutputFormat();
mf.setInteger("width", mPlaybackService.mWidth);
mf.setInteger("height", mPlaybackService.mHeight);
yuvwidth = mPlaybackService.mWidth;
yuvheight = mPlaybackService.mHeight;
nativeSetVideoSurface(mPlaybackService.mS,yuvwidth,yuvheight);
}
else if (outputBufferIndex >= 0)
{
ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
byte[] outData = new byte[bufferInfo.size];
outputBuffer.get(outData, 0, bufferInfo.size);

nativeShowYUV(outData);//,yuvwidth,yuvheight);
outputBuffer.clear();
mPlaybackService.mMC.releaseOutputBuffer(outputBufferIndex, true);

}

 

渲染yuv數據的兩種思考方法

思路1:在Java中將Surface指針傳遞到jni層,lock以後就能夠得到SurfaceInfo,進而取得要顯示的surface格式、高度、寬度,在2.2/2.3版本,surface的Format通常都是RGB565格式,只用作一個顏色空間的轉換,scaler就能夠將yuv數據顯示出來。
顏色空間轉換和Scaler算是比較耗時的操做了。如何提升效率,scaler最好能交給Android的底層函數去作,若是有gpu的,底層函數直接會利用gpu,效率很是高,又不佔用cpu資源。

思路2:
   參考framework中的AwesomePlayer,裏面利用AwesomeLocalRenderer/AwesomeRemoteRenderer來實現解碼出來的數據顯示,這個效率應該很是高,可是平臺的關聯性會增長不少。
   調用接口比較簡單,
   首先建立一個render,
               mVideoRenderer = new AwesomeRemoteRenderer(
                mClient.interface()->createRenderer(
                        mISurface, component,
                        (OMX_COLOR_FORMATTYPE)format,
                        decodedWidth, decodedHeight,
                        mVideoWidth, mVideoHeight,
                        rotationDegrees));

  直接調用render函數就能夠顯示了。
    virtual void render(MediaBuffer *buffer) {
        void *id;
        if (buffer->meta_data()->findPointer(kKeyBufferID, &id)) {
            mTarget->render((IOMX::buffer_id)id);
        }
    }
   其它的參數都很容易得到,關鍵是buffer_id 怎麼得到?OMXCodec.cpp中有相關的能夠參考。

 

參考資料

一、博客(出處:http://blog.csdn.net/tung214/article/details/37762487

二、android源碼裏的/frameworks/av/media/libstagefright/AwesomePlayer.cpp 

                          /frameworks/av/media/libstagefright/colorconversion/SoftwareRenderer.cpp

三、MediaCodec的api接口

 

 

遇到的坑:

一、貼圖到surfaceView的surface,橫屏的分辨率能正常顯示,但顏色值不對,豎屏分辨率的圖顯示花屏

     緣由應該是yuv格式有不少,須要轉換。顯示的時候也跟分辯率相關。如下參數的修改就可能能解決問題。

  CHECK_EQ(0,
  native_window_set_scaling_mode(
  mNativeWindow.get(),
  NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW));//使用surfaceView能正常顯示,顯示效果也很好
  // NATIVE_WINDOW_SCALING_MODE_SCALE_CROP));//使用這個模式surfaceView會花屏,textureView不會,textureView顯示效果差,不清晰

二、使用surfaceView能正常顯示yuv,可是若是連續貼圖,surfaceView顯示渲染速度跟不上,會很卡頓。

     這個跟函數調用流程有關,surface設置函數nativeSetVideoSurface,只在視頻的第一幀顯示時設置,後續就視頻幀來就直接調用nativeShowYUV

    視頻顯示須要native_window_set_buffers_geometry native_window_set_scaling_mode不該該放到nativeShowYUV函數裏去執行,由於這兩個函數在同一個視頻流裏,只要設置一次就好了,若是放到nativeShowYUV裏,每一幀數據都要執行一次這兩個函數,效率會很低。形成顯示速度跟不上,若是解碼使用的是MediaCodec,解碼也會堵塞。因此須要把這連個函數放到nativeSetVideoSurface裏,在一開始設置一次就好了,這個至關於初始化。這樣能使速度明顯提高。

 

三、使用SerfaceView及TextureView的差別

  a、使用TextrueView顯示不清晰

    b、使用TextrueView的渲染速度快,在(坑2)的狀況下,比surfaceView快多了。

      c、使用TextrueView狀況下,NATIVE_WINDOW_SCALING_MODE_SCALE_CROP NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW都同樣。

 

我是參考了android的系統源碼,至關於直接扣出來的,遇到的問題其實不算多。不少都是參數的設置,調用流程的控制不對引發的。並且這種作法跟平臺的差別相關,我使用的平臺surfaceView跟textureView的效果差別挺大。網上有不少大神,用ffmpeg解碼,也是yuv貼圖,甚至yuv轉rgb後顯示,或者yuv格式的轉換,旋轉等操做,這些實現起來遇到的問題應該會比較多。

 

另外,建議遇到問題時候,多請教,跟身邊的人討論下,有時候遇到問題卡主了,應該多換換思路,換個方向。同時網上的參考,你們也應該根據實際狀況使用,有時候別人的方案,能正常使用,可是應用到本身的程序,遇到問題,有多是應用場景不同,好比我參考http://blog.csdn.net/tung214/article/details/37762487裏的實現沒錯,能正常顯示,可是該例子有可能只是爲了實現單圖顯示。而個人應用須要連續顯示播放,因此徹底照搬,就會遇到卡頓的問題了。若是有源碼參考的狀況下,你們仍是要多看看源碼,http://blog.csdn.net/tung214/article/details/37762487裏的實現是參照android源碼,能夠當作啓發,本身參照源碼實現一遍,會了解得比較透徹。

相關文章
相關標籤/搜索