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


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

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

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

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

  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顯示圖形必不可少的五步。

#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;

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;
}

GraphicBufferMapper &mapper = GraphicBufferMapper::get();

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中有相關的可以參考。

 

參考資料

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

2、android源碼里的/frameworks/av/media/libstagefright/AwesomePlayer.cpp 

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

3、MediaCodec的api接口

 

 

遇到的坑:

1、貼圖到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顯示效果差,不清晰

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

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

    視頻顯示需要native_window_set_buffers_geometry native_window_set_scaling_mode不應該放到nativeShowYUV函數里去執行,因為這兩個函數在同一個視頻流里,只要設置一次就行了,如果放到nativeShowYUV里,每一幀數據都要執行一次這兩個函數,效率會很低。造成顯示速度跟不上,如果解碼使用的是MediaCodec,解碼也會堵塞。所以需要把這連個函數放到nativeSetVideoSurface里,在一開始設置一次就行了,這個相當於初始化。這樣能使速度明顯提升。

 

3、使用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源碼,可以當做啟發,自己參照源碼實現一遍,會了解得比較透徹。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM