最近在研究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。
- native_window_set_buffers_geometry;//設置寬高以及顏色空間yuv420
- native_window_dequeue_buffer_and_wait;//根據以上配置申請圖形緩沖區
- mapper.lock(buf->handle, GRALLOC_USAGE_SW_WRITE_OFTEN, bounds, &dst));//將申請到的圖形緩沖區跨進程映射到用戶空間
- memcpy(dst, data, dst_y_size + dst_c_size*2);//填充yuv數據到圖形緩沖區
- 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 (依賴的庫比較少)
- LOCAL_PATH:= $(call my-dir)
- include $(CLEAR_VARS)
- LOCAL_SRC_FILES:= \
- main.cpp
- LOCAL_SHARED_LIBRARIES := \
- libcutils \
- libutils \
- libbinder \
- libui \
- libgui \
- libstagefright_foundation
- LOCAL_MODULE:= MyShowYUV
- LOCAL_MODULE_TAGS := tests
- include $(BUILD_EXECUTABLE)
本例子,使用Java創建UI並聯合JNI層操作surface來直接顯示yuv數據(yv12),開發環境為Android 4.4,全志A23平台。
- package com.example.myyuvviewer;
- import java.io.File;
- import java.io.FileInputStream;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- import android.view.Surface;
- import android.view.SurfaceHolder;
- import android.view.SurfaceHolder.Callback;
- import android.view.SurfaceView;
- public class MainActivity extends Activity {
- final private String TAG = "MyYUVViewer";
- final private String FILE_NAME = "yuv_320_240.yuv";
- private int width = 320;
- private int height = 240;
- private int size = width * height * 3/2;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- nativeTest();
- SurfaceView surfaceview = (SurfaceView) findViewById(R.id.surfaceView);
- SurfaceHolder holder = surfaceview.getHolder();
- holder.addCallback(new Callback(){
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- // TODO Auto-generated method stub
- Log.d(TAG,"surfaceCreated");
- byte[]yuvArray = new byte[size];
- readYUVFile(yuvArray, FILE_NAME);
- nativeSetVideoSurface(holder.getSurface(),width,height);
- nativeShowYUV(yuvArray);
- }
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format,
- int width, int height) {
- // TODO Auto-generated method stub
- }
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
- // TODO Auto-generated method stub
- }});
- }
- private boolean readYUVFile(byte[] yuvArray,String filename){
- try {
- // 如果手機插入了SD卡,而且應用程序具有訪問SD的權限
- if (Environment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED)) {
- // 獲取SD卡對應的存儲目錄
- File sdCardDir = Environment.getExternalStorageDirectory();
- // 獲取指定文件對應的輸入流
- FileInputStream fis = new FileInputStream(
- sdCardDir.getCanonicalPath() +"/" + filename);
- fis.read(yuvArray, 0, size);
- fis.close();
- return true;
- } else {
- return false;
- }
- }catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- private native void nativeTest();
- private native boolean nativeSetVideoSurface(Surface surface,int width,int height);
- private native void nativeShowYUV(byte[] yuvArray);
- static {
- System.loadLibrary("showYUV");
- }
- }
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源碼,可以當做啟發,自己參照源碼實現一遍,會了解得比較透徹。