研究一段时间 Android的surface系统,一直执着地认为所有在surface或者屏幕上显示的画面,必须要转换成RGB才能显示,yuv数据也要通过颜色空间转换成RGB才能显示。可最近在研究stagefright视频显示时发现,根本找不到omx解码后的yuv是怎么转换成RGB的代码,yuv数据在render之后就找不到去向了,可画面确确实实的显示出来了,这从此颠覆了yuv必须要转换成RGB才能显示的真理了。

    稍微看一下AsomePlayer的代码,不难发现,视频的每一帧是通过调用了SoftwareRenderer来渲染显示的,我也尝试用利用SoftwareRenderer来直接render yuv数据显示,竟然成功了,这是一个很大的突破,比如以后摄像头采集到的yuv,可以直接丢yuv数据到surface显示,无需耗时耗效率的yuv转RGB了。



上一篇文章主要是参照AwesomePlayer直接用SoftwareRenderer类来显示yuv,为了能用到这个类,不惜依赖了libstagefright、libstagefright_color_conversion等动态静态库,从而造成程序具有很高的耦合度,也不便于我们理解yuv数据直接显示的深层次原因。

    于是我开始研究SoftwareRenderer的具体实现,我们来提取SoftwareRenderer的核心代码,自己来实现yuv的显示。

    SoftwareRenderer就只有三个方法,一个构造函数,一个析构函数,还有一个负责显示的render方法。构造方法里有个很重要的地方native_window_set_buffers_geometry这里是配置即将申请的图形缓冲区的宽高和颜色空间,忽略了这个地方,画面将用默认的值显示,将造成显示不正确。render函数里最重要的三个地方,一个的dequeBuffer,一个是mapper,一个是queue_buffer。

[cpp]  view plain  copy  
  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显示图形必不可少的五步。

有了以上分析,我们直接上代码:(yuv数据下载地址点击打开链接,放到sdcard)

main.cpp

[cpp]  view plain  copy  
  1. #include   
  2.   
  3. #include   
  4. #include   
  5.   
  6. #include   
  7. #include   
  8. #include   
  9. #include   
  10. #include   
  11. #include   
  12. #include   
  13. #include   
  14. #include   
  15. #include   
  16. #include   
  17. //ANativeWindow 就是surface,对应surface.cpp里的code  
  18. using namespace android;  
  19.   
  20. //将x规整为y的倍数,也就是将x按y对齐  
  21. static int ALIGN(int x, int y) {  
  22.     // y must be a power of 2.  
  23.     return (x + y - 1) & ~(y - 1);  
  24. }  
  25.   
  26. void render(  
  27.         const void *data, size_t size, const sp &nativeWindow,int width,int height) {  
  28.     sp mNativeWindow = nativeWindow;  
  29.     int err;  
  30.     int mCropWidth = width;  
  31.     int mCropHeight = height;  
  32.       
  33.     int halFormat = HAL_PIXEL_FORMAT_YV12;//颜色空间  
  34.     int bufWidth = (mCropWidth + 1) & ~1;//按2对齐  
  35.     int bufHeight = (mCropHeight + 1) & ~1;  
  36.       
  37.     CHECK_EQ(0,  
  38.             native_window_set_usage(  
  39.             mNativeWindow.get(),  
  40.             GRALLOC_USAGE_SW_READ_NEVER | GRALLOC_USAGE_SW_WRITE_OFTEN  
  41.             | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP));  
  42.   
  43.     CHECK_EQ(0,  
  44.             native_window_set_scaling_mode(  
  45.             mNativeWindow.get(),  
  46.             NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW));  
  47.   
  48.     // Width must be multiple of 32???  
  49.     //很重要,配置宽高和和指定颜色空间yuv420  
  50.     //如果这里不配置好,下面deque_buffer只能去申请一个默认宽高的图形缓冲区  
  51.     CHECK_EQ(0, native_window_set_buffers_geometry(  
  52.                 mNativeWindow.get(),  
  53.                 bufWidth,  
  54.                 bufHeight,  
  55.                 halFormat));  
  56.       
  57.       
  58.     ANativeWindowBuffer *buf;//描述buffer  
  59.     //申请一块空闲的图形缓冲区  
  60.     if ((err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(),  
  61.             &buf)) != 0) {  
  62.         ALOGW("Surface::dequeueBuffer returned error %d", err);  
  63.         return;  
  64.     }  
  65.   
  66.     GraphicBufferMapper &mapper = GraphicBufferMapper::get();  
  67.   
  68.     Rect bounds(mCropWidth, mCropHeight);  
  69.   
  70.     void *dst;  
  71.     CHECK_EQ(0, mapper.lock(//用来锁定一个图形缓冲区并将缓冲区映射到用户进程  
  72.                 buf->handle, GRALLOC_USAGE_SW_WRITE_OFTEN, bounds, &dst));//dst就指向图形缓冲区首地址  
  73.   
  74.     if (true){  
  75.         size_t dst_y_size = buf->stride * buf->height;  
  76.         size_t dst_c_stride = ALIGN(buf->stride / 2, 16);//1行v/u的大小  
  77.         size_t dst_c_size = dst_c_stride * buf->height / 2;//u/v的大小  
  78.           
  79.         memcpy(dst, data, dst_y_size + dst_c_size*2);//将yuv数据copy到图形缓冲区  
  80.     }  
  81.   
  82.     CHECK_EQ(0, mapper.unlock(buf->handle));  
  83.   
  84.     if ((err = mNativeWindow->queueBuffer(mNativeWindow.get(), buf,  
  85.             -1)) != 0) {  
  86.         ALOGW("Surface::queueBuffer returned error %d", err);  
  87.     }  
  88.     buf = NULL;  
  89. }  
  90.   
  91. bool getYV12Data(const char *path,unsigned char * pYUVData,int size){  
  92.     FILE *fp = fopen(path,"rb");  
  93.     if(fp == NULL){  
  94.         printf("read %s fail !!!!!!!!!!!!!!!!!!!\n",path);  
  95.         return false;  
  96.     }  
  97.     fread(pYUVData,size,1,fp);  
  98.     fclose(fp);  
  99.     return true;  
  100. }  
  101.   
  102. int main(void){  
  103.     // set up the thread-pool  
  104.     sp proc(ProcessState::self());  
  105.     ProcessState::self()->startThreadPool();  
  106.       
  107.     // create a client to surfaceflinger  
  108.     sp client = new SurfaceComposerClient();  
  109.     sp dtoken(SurfaceComposerClient::getBuiltInDisplay(  
  110.             ISurfaceComposer::eDisplayIdMain));  
  111.     DisplayInfo dinfo;  
  112.     //获取屏幕的宽高等信息  
  113.     status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);  
  114.     printf("w=%d,h=%d,xdpi=%f,ydpi=%f,fps=%f,ds=%f\n",   
  115.         dinfo.w, dinfo.h, dinfo.xdpi, dinfo.ydpi, dinfo.fps, dinfo.density);  
  116.     if (status)  
  117.         return -1;  
  118.     //创建surface  
  119.     sp surfaceControl = client->createSurface(String8("testsurface"),  
  120.             dinfo.w, dinfo.h, PIXEL_FORMAT_RGBA_8888, 0);  
  121.               
  122. /*************************get yuv data from file;****************************************/            
  123.     printf("[%s][%d]\n",__FILE__,__LINE__);  
  124.     int width,height;  
  125.     width = 320;  
  126.     height = 240;  
  127.     int size = width * height * 3/2;  
  128.     unsigned char *data = new unsigned char[size];  
  129.     const char *path = "/mnt/sdcard/yuv_320_240.yuv";  
  130.     getYV12Data(path,data,size);//get yuv data from file;  
  131.       
  132. /*********************配置surface*******************************************************************/  
  133.     SurfaceComposerClient::openGlobalTransaction();  
  134.     surfaceControl->setLayer(100000);//设定Z坐标  
  135.     surfaceControl->setPosition(100, 100);//以左上角为(0,0)设定显示位置  
  136.     surfaceControl->setSize(width, height);//设定视频显示大小  
  137.     SurfaceComposerClient::closeGlobalTransaction();  
  138.     sp surface = surfaceControl->getSurface();  
  139.     printf("[%s][%d]\n",__FILE__,__LINE__);  
  140.       
  141. /**********************显示yuv数据******************************************************************/     
  142.     render(data,size,surface,width,height);  
  143.     printf("[%s][%d]\n",__FILE__,__LINE__);  
  144.       
  145.     IPCThreadState::self()->joinThreadPool();//可以保证画面一直显示,否则瞬间消失  
  146.     IPCThreadState::self()->stopProcess();  
  147.     return 0;  
  148. }  

Android.mk (这次依赖的库少了很多)

[cpp]  view plain  copy  
  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)  

文章结尾有引用的出处,那里有相关问题的解答

渲染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中有相关的可以参考。
   实际的效果在我的S510E上跑,效率非常高,几乎不占用主控cpu资源,很可能都交给dsp和gpu去搞了。  
  


本文用Java创建UI并联合JNI层操作surface来直接显示yuv数据(yv12),开发环境为Android 4.4,全志A23平台。

[java] view plain copy
  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());  
  38.                 nativeShowYUV(yuvArray,width,height);  
  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);  
  78.     private native void nativeShowYUV(byte[] yuvArray,int width,int height);  
  79.     static {  
  80.         System.loadLibrary("showYUV");  
  81.     }  
  82. }  
activity_main.xml
[html] view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2.     android:layout_width="fill_parent"    
  3.     android:layout_height="fill_parent"    
  4.     android:orientation="vertical" >    
  5.     
  6.     <SurfaceView    
  7.         android:id="@+id/surfaceView"    
  8.         android:layout_width="fill_parent"    
  9.         android:layout_height="360dp" />   
  10.           
  11. LinearLayout>  

JNI层,showYUV.cpp(libshowyuv.so)采用动态注册JNI函数的方法. [cpp] view plain copy
  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5. #include   
  6. #include   
  7. #include   
  8. #include   
  9. #include   
  10. #include   
  11. using namespace android;  
  12.   
  13. static sp surface;  
  14.   
  15. static int ALIGN(int x, int y) {  
  16.     // y must be a power of 2.  
  17.     return (x + y - 1) & ~(y - 1);  
  18. }  
  19.   
  20. static void render(  
  21.         const void *data, size_t size, const sp &nativeWindow,int width,int height) {  
  22.     ALOGE("[%s]%d",__FILE__,__LINE__);  
  23.     sp mNativeWindow = nativeWindow;  
  24.     int err;  
  25.     int mCropWidth = width;  
  26.     int mCropHeight = height;  
  27.       
  28.     int halFormat = HAL_PIXEL_FORMAT_YV12;//颜色空间  
  29.     int bufWidth = (mCropWidth + 1) & ~1;//按2对齐  
  30.     int bufHeight = (mCropHeight + 1) & ~1;  
  31.       
  32.     CHECK_EQ(0,  
  33.             native_window_set_usage(  
  34.             mNativeWindow.get(),  
  35.             GRALLOC_USAGE_SW_READ_NEVER | GRALLOC_USAGE_SW_WRITE_OFTEN  
  36.             | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP));  
  37.   
  38.     CHECK_EQ(0,  
  39.             native_window_set_scaling_mode(  
  40.             mNativeWindow.get(),  
  41.             NATIVE_WINDOW_SCALING_MODE_SCALE_CROP));  
  42.   
  43.     // Width must be multiple of 32???  
  44.     //很重要,配置宽高和和指定颜色空间yuv420  
  45.     //如果这里不配置好,下面deque_buffer只能去申请一个默认宽高的图形缓冲区  
  46.     CHECK_EQ(0, native_window_set_buffers_geometry(  
  47.                 mNativeWindow.get(),  
  48.                 bufWidth,  
  49.                 bufHeight,  
  50.                 halFormat));  
  51.       
  52.       
  53.     ANativeWindowBuffer *buf;//描述buffer  
  54.     //申请一块空闲的图形缓冲区  
  55.     if ((err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(),  
  56.             &buf)) != 0) {  
  57.         ALOGW("Surface::dequeueBuffer returned error %d", err);  
  58.         return;  
  59.     }  
  60.   
  61.     GraphicBufferMapper &mapper = GraphicBufferMapper::get();  
  62.   
  63.     Rect bounds(mCropWidth, mCropHeight);  
  64.   
  65.     void *dst;  
  66.     CHECK_EQ(0, mapper.lock(//用来锁定一个图形缓冲区并将缓冲区映射到用户进程  
  67.                 buf->handle, GRALLOC_USAGE_SW_WRITE_OFTEN, bounds, &dst));//dst就指向图形缓冲区首地址  
  68.   
  69.     if (true){  
  70.         size_t dst_y_size = buf->stride * buf->height;  
  71.         size_t dst_c_stride = ALIGN(buf->stride / 2, 16);//1行v/u的大小  
  72.         size_t dst_c_size = dst_c_stride * buf->height / 2;//u/v的大小  
  73.           
  74.         memcpy(dst, data, dst_y_size + dst_c_size*2);//将yuv数据copy到图形缓冲区  
  75.     }  
  76.   
  77.     CHECK_EQ(0, mapper.unlock(buf->handle));  
  78.   
  79.     if ((err = mNativeWindow->queueBuffer(mNativeWindow.get(), buf,  
  80.             -1)) != 0) {  
  81.         ALOGW("Surface::queueBuffer returned error %d", err);  
  82.     }  
  83.     buf = NULL;  
  84. }  
  85.   
  86. static void nativeTest(){  
  87.     ALOGE("[%s]%d",__FILE__,__LINE__);  
  88. }  
  89.   
  90. static jboolean  
  91. nativeSetVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface){  
  92.     ALOGE("[%s]%d",__FILE__,__LINE__);  
  93.     surface = android_view_Surface_getSurface(env, jsurface);  
  94.     if(android::Surface::isValid(surface)){  
  95.         ALOGE("surface is valid ");  
  96.     }else {  
  97.         ALOGE("surface is invalid ");  
  98.         return false;  
  99.     }  
  100.     ALOGE("[%s][%d]\n",__FILE__,__LINE__);  
  101.     return true;  
  102. }  
  103. static void  
  104. nativeShowYUV(JNIEnv *env, jobject thiz,jbyteArray yuvData,jint width,jint height){  
  105.     ALOGE("width = %d,height = %d",width,height);  
  106.     jint len = env->GetArrayLength(yuvData);  
  107.     ALOGE("len = %d",len);  
  108.     jbyte *byteBuf = env->GetByteArrayElements(yuvData, 0);  
  109.     render(byteBuf,len,surface,width,height);  
  110. }  
  111. static JNINativeMethod gMethods[] = {  
  112.     {"nativeTest",                  "()V",                              (void *)nativeTest},  
  113.     {"nativeSetVideoSurface",       "(Landroid/view/Surface;)Z",        (void *)nativeSetVideoSurface},  
  114.     {"nativeShowYUV",               "([BII)V",                          (void *)nativeShowYUV},  
  115. };  
  116.   
  117. static const charconst kClassPathName = "com/example/myyuvviewer/MainActivity";  
  118.   
  119. // This function only registers the native methods  
  120. static int register_com_example_myyuvviewer(JNIEnv *env)  
  121. {  
  122.     ALOGE("[%s]%d",__FILE__,__LINE__);  
  123.     return AndroidRuntime::registerNativeMethods(env,  
  124.                 kClassPathName, gMethods, NELEM(gMethods));  
  125. }  
  126.   
  127. jint JNI_OnLoad(JavaVM* vm, void* reserved)  
  128. {  
  129.     ALOGE("[%s]%d",__FILE__,__LINE__);  
  130.     JNIEnv* env = NULL;  
  131.     jint result = -1;  
  132.   
  133.     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {  
  134.         ALOGE("ERROR: GetEnv failed\n");  
  135.         goto bail;  
  136.     }  
  137.     assert(env != NULL);  
  138.     ALOGE("[%s]%d",__FILE__,__LINE__);  
  139.    if (register_com_example_myyuvviewer(env) < 0) {  
  140.         ALOGE("ERROR: MediaPlayer native registration failed\n");  
  141.         goto bail;  
  142.     }  
  143.   
  144.     /* success -- return valid version number */  
  145.     result = JNI_VERSION_1_4;  
  146.   
  147. bail:  
  148.     return result;  
  149. }  

Android.mk [plain] view plain copy
  1. LOCAL_PATH:= $(call my-dir)  
  2. include $(CLEAR_VARS)  
  3.   
  4. LOCAL_SRC_FILES:= \  
  5.     showYUV.cpp  
  6.       
  7. LOCAL_SHARED_LIBRARIES := \  
  8.     libcutils \  
  9.     libutils \  
  10.     libbinder \  
  11.     libui \  
  12.     libgui \  
  13.     libandroid_runtime \  
  14.     libstagefright_foundation  
  15.       
  16. LOCAL_MODULE:= libshowYUV  
  17.   
  18. LOCAL_MODULE_TAGS := tests  
  19.   
  20. include $(BUILD_SHARED_LIBRARY)  

生成的so文件复制到Java项目里 与src并列的libs/armeabi目录下,没有就手动创建目录,

这样Eclipse会自动把so库打包进apk。

转载请注明出处:http://blog.csdn.net/tung214/article/details/37762487

yuvdata下载地址:点击打开链接



更多相关文章

  1. Android--设置软键盘的显示和隐藏
  2. 【转发】Android(安卓)Metro风格的Launcher开发系列第一篇
  3. 常用Android开发组件之文本类组件
  4. 【Bugly干货分享】那些年我们用过的显示性能指标
  5. android-opengles3.0开发-2-绘制图形
  6. Android用surface直接显示yuv数据(一)
  7. Android(安卓)开发解决APP在18:9,18.5:9,19:9,19:10尺寸的手机上不
  8. android 自定义坐标曲线图
  9. Android(安卓)mp3 lyric 滚动显示 Demo

随机推荐

  1. 详谈程序员到底是做什么工作的(非程序员勿
  2. Springboot+Mybatis+Thymeleaf增加数据的
  3. 收藏|2021年阿里云开源镜像站最热门镜像王
  4. Linux下的源码安装、rpm安装、yum安装三
  5. Python零基础入门-基础语法-数据结构-字
  6. Java入门自学需要注意什么?
  7. 镜像格式二十年:从 Knoppix 到 OCI-Image-
  8. JavaScript在JAVAEE项目中的作用。
  9. 莫听穿林打叶声一蓑烟雨任平生-周深光亮
  10. linux下小皮部署子域名