关于音视频:Android-音视频-EGL-源码解析以及-C-实现

7次阅读

共计 10494 个字符,预计需要花费 27 分钟才能阅读完成。

OpenGL 是一个跨平台的 API, 而不同的操作系统 (Windows,Android,IOS) 各有本人的屏幕渲染实现。所以 OpenGL 定义了一个两头接口层 EGL(Embedded Graphics Library)规范,具体实现交给各个操作系统自身

EGL

简略来说 EGL 是一个两头接口层,是一个标准,因为 OpenGL 的跨平台性,所以说这个标准显得尤其重要,不论各个操作系统如何蹦跶,都不能脱离我所定义的标准。

EGL 的一些基础知识

  • EGLDisplay

EGL 定义的一个形象的零碎显示类,用于操作设施窗口。

  • EGLConfig

EGL 配置,如 rgba 位数

  • EGLSurface

渲染缓存,一块内存空间,所有要渲染到屏幕上的图像数据,都要先缓存在 EGLSurface 上。

  • EGLContext

OpenGL 上下文,用于存储 OpenGL 的绘制状态信息、数据。

初始化 EGL 的过程能够说是对下面几个信息进行配置的过程。

OpenGL ES 绘图残缺流程

咱们在应用 Java GLSurfaceView 的时候其实只是自定义了 Render, 该 Render 实现了 GLsurfaceView.Renderer 接口,而后自定义的 Render 中的 3 个办法就会失去回调,Android 零碎其实帮我省掉了其中的很多步骤。所以咱们这里来看一下 残缺流程 (1). 获取显示设施(对应于下面的 EGLDisplay)

/*
 * Get an EGL instance */
 mEgl = (EGL10) EGLContext.getEGL();
 
/*
 * Get to the default display. */
 mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

(2). 初始化 EGL

int[] version = new int[2];
// 初始化屏幕
if(!mEgl.eglInitialize(mEglDisplay, version)) {throw new RuntimeException("eglInitialize failed");
}

(3). 抉择 Config(用 EGLConfig 配置参数)

// 这段代码的作用是抉择 EGL 配置,即能够本人先设定好一个你心愿的 EGL 配置,比如说 RGB 三种色彩各占几位,你能够轻易配,而 EGL 可能不能满足你所有的要求,于是它会返回一些与你的要求最靠近的配置供你抉择。if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
 num_config)) {throw new IllegalArgumentException("eglChooseConfig#2 failed");
}

(4). 创立 EGLContext

// 从上一步 EGL 返回的配置列表中抉择一种配置,用来创立 EGL Context。egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
 mEGLContextClientVersion != 0 ? attrib_list : null);

(5). 获取 EGLSurface

// 创立一个窗口 Surface,能够看成屏幕所对应的内存
 egl.eglCreateWindowSurface(display, config, nativeWindow, null)

PS 这里的 nativeWindow 是 GLSurfaceView 的 surfaceHolder

(6). 绑定渲染环境到以后线程

/*
 * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */
 if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
    /*
    * Could not make the context current, probably because the underlying * SurfaceView surface has been destroyed. */ 
     logEglErrorAsWarning("EGLHelper", "eglMakeCurrent", mEgl.eglGetError());
     return false;
 }

循环绘制

loop:{
    // 绘制中....
    //(7). 替换缓冲区
    mEglHelper.swap();}

public int swap() {if (! mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {return mEgl.eglGetError();
    }
    return EGL10.EGL_SUCCESS;
}

Java – GLSurfaceView/GLTextureView

下面咱们介绍了 EGL 的一些基础知识,接着咱们来看在 GLSurfaceView/GLTextureView 中 EGL 的具体实现,咱们来从源码上分析 Android 零碎 EGL 及 GL 线程。

GLThread

咱们来看一下 GLThread,GLThread 也是从一般的 Thread 类继承而来,实践上就是一个一般的线程,为什么它领有 OpenGL 绘图能力?持续往下看,外面最重要的局部就是 guardedRun()办法。

static class GLThread extends Thread {
    ...
    @Override
    public void run() {
      
        try {guardedRun();
         } catch (InterruptedException e) {// fall thru and exit normally} finally {sGLThreadManager.threadExiting(this);
         }
    }
}

让咱们来看一下 guardedRun()办法里有什么货色,guardedRun()里大抵做的事件:

private void guardedRun() throws InterruptedException {while(true){
        //if ready to draw
        ...
        mEglHelper.start();// 对应于下面残缺流程中的(1)(2)(3)(4)
        
        ...
        mEglHelper.createSurface()// 对应于下面残缺流程中的(5)(6)
        
        ...
        回调 GLSurfaceView.Renderer 的 onSurfaceCreated();
        ...
        回调 GLSurfaceView.Renderer 的 onSurfaceChanged();
        ...
        回调 GLSurfaceView.Renderer 的 onDrawFrame();
        
        ...
         mEglHelper.swap();// 对应于下面残缺流程中的(5)(7)
    }
}

从下面咱们的剖析得悉 GLSurfaceView 中的 GLThread 就是一个一般的线程,只不过它依照了 OpenGL 绘图的残缺流程正确地操作了下来,因而它有 OpenGL 的绘图能力。那么,如果咱们本人创立一个线程,也按这样的操作方法,那咱们也能够在本人创立的线程里绘图吗?答案是必定的(这不正是 EGL 的接口意义),上面我会给出 EGL 在 Native C/C++ 中的实现。

Native – EGL

Android Native 环境中并不存在现成的 EGL 环境,所以咱们在进行 OpenGL 的 NDK 开发时就必须本人实现 EGL 环境,那么如何实现呢,咱们只须要参照 GLSurfaceView 中的 GLThread 的写法就能实现 Native 中的 EGL。

PS

以下的内容可能须要你对 C/C++ 以及 NDK 有肯定相熟

第 1 步实现相似于 Java GLSurfaceView 中的 GLThread 的性能

gl_render.h

class GLRender {
    private:
         const char *TAG = "GLRender";
         //OpenGL 渲染状态
         enum STATE {
             NO_SURFACE, // 没有无效的 surface
             FRESH_SURFACE, // 持有一个为初始化的新的 surface
             RENDERING, // 初始化结束,能够开始渲染
             SURFACE_DESTROY, //surface 销毁
             STOP // 进行绘制
         };
         JNIEnv *m_env = NULL;
         // 线程附丽的 jvm 环境
         JavaVM *m_jvm_for_thread = NULL;
         //Surface 援用,必须要应用援用,否则无奈在线程中操作
         jobject m_surface_ref = NULL;
         // 本地屏幕
         ANativeWindow *m_native_window = NULL;
         //EGL 显示外表
         EglSurface *m_egl_surface = NULL;
         int m_window_width = 0;
         int m_window_height = 0;
         
         // 绘制代理器
         ImageRender *pImageRender;
         
         //OpenGL 渲染状态
         STATE m_state = NO_SURFACE;
         // 初始化相干的办法
         void InitRenderThread();
         bool InitEGL();
         void InitDspWindow(JNIEnv *env);
         // 创立 / 销毁 Surface void CreateSurface();
         void DestroySurface();
         // 渲染办法
         void Render();
         void ReleaseSurface();
         void ReleaseWindow();
         // 渲染线程回调办法
         static void sRenderThread(std::shared_ptr<GLRender> that);
    public:
         GLRender(JNIEnv *env);
         ~GLRender();
         // 内部传入 Surface
         void SetSurface(jobject surface);
      
         void Stop();
         void SetBitmapRender(ImageRender *bitmapRender);
        // 开释资源相干办法
         void ReleaseRender();
         
         ImageRender *GetImageRender();};

gl_render.cpp

// 构造函数
GLRender::GLRender(JNIEnv *env) {
     this->m_env = env;
     // 获取 JVM 虚拟机,为创立线程作筹备
     env->GetJavaVM(&m_jvm_for_thread);
     InitRenderThread();}
// 析构函数
GLRender::~GLRender() {delete m_egl_surface;}

// 初始化渲染线程
void GLRender::InitRenderThread() {
    // 应用智能指针,线程完结时,主动删除本类指针
     std::shared_ptr<GLRender> that(this);
     std::thread t(sRenderThread, that);
     t.detach();}

// 线程回调函数
void GLRender::sRenderThread(std::shared_ptr<GLRender> that) {
    JNIEnv *env;
     //(1) 将线程附加到虚拟机,并获取 env
     if (that->m_jvm_for_thread->AttachCurrentThread(&env, NULL) != JNI_OK) {LOGE(that->TAG, "线程初始化异样");
            return; 
     }
     // (2) 初始化 EGL 
    if (!that->InitEGL()) {
         // 解除线程和 jvm 关联
         that->m_jvm_for_thread->DetachCurrentThread();
         return; 
     }
     
     // 进入循环
    while (true) {
            // 依据 OpenGL 渲染状态进入不同的解决
            switch (that->m_state) {// 刷新 Surface,从里面设置 Surface 后 m_state 置为该状态,阐明曾经从内部 (java 层) 取得 Surface 的对象了
                case FRESH_SURFACE:
                     LOGI(that->TAG, "Loop Render FRESH_SURFACE")
                     // (3) 初始化 Window
                     that->InitDspWindow(env);
                     // (4) 创立 EglSurface
                     that->CreateSurface();
                     // m_state 置为 RENDERING 状态进入渲染
                     that->m_state = RENDERING;
                     break; 
                 case RENDERING:
                    LOGI(that->TAG, "Loop Render RENDERING")
                    // (5) 渲染
                    that->Render();
                    break; 
               
                 case STOP:
                    LOGI(that->TAG, "Loop Render STOP")
                    //(6) 解除线程和 jvm 关联
                     that->ReleaseRender();
                     that->m_jvm_for_thread->DetachCurrentThread();
                     return; 
                case SURFACE_DESTROY:
                    LOGI(that->TAG, "Loop Render SURFACE_DESTROY")
                    //(7) 开释资源
                    that->DestroySurface();
                    that->m_state = NO_SURFACE;
                    break; 
                case NO_SURFACE:
                default:
                    break;
     }
    usleep(20000);
 }
}

咱们定义的 GLRender 各个流程代码里曾经标注了步骤,尽管代码量比拟多,然而咱们的 c++ class 剖析也是跟 java 相似,

PS 上图中的 (3)(4) 等步骤对应于代码中的步骤正文

(1)将线程附加到虚拟机,并获取 env

这一步简单明了,咱们往下看

EGL 封装筹备

咱们在上一篇就晓得了 EGL 的一些基础知识,EGLDiaplay,EGLConfig,EGLSurface,EGLContext,咱们须要把这些根底类进行封装,那么如何进行封装呢,咱们先看一下对于咱们上篇文章中自定义的 GLRender 类须要什么 gl_render.h

//Surface 援用,必须要应用援用,否则无奈在线程中操作
jobject m_surface_ref = NULL;
// 本地屏幕
ANativeWindow *m_native_window = NULL;
//EGL 显示外表 留神这里是咱们自定义的 EglSurface 包装类而不是零碎提供的 EGLSurface 哦
EglSurface *m_egl_surface = NULL;

对于 gl_render 来说 输出的是内部的 Surface 对象,咱们这里的是jobject m_surface_ref, 那么输入须要的是ANativeWindow,EglSurface

对于 ANativeWindow 能够查看官网文档 ANativeWindow

那么 EglSurface 呢,

egl_surface.h

class EglSurface {
private:
    const char *TAG = "EglSurface";
    // 本地屏幕
     ANativeWindow *m_native_window = NULL;
     // 封装了 EGLDisplay EGLConfig EGLContext 的自定义类
     EglCore *m_core;
     //EGL API 提供的 EGLSurface
     EGLSurface m_surface;
}

能够看到咱们下面的定义的思维也是 V(View)和 C(Controller)进行了拆散。

egl_core.h

class EglCore {
private:
    const char *TAG = "EglCore";
     //EGL 显示窗口
     EGLDisplay m_egl_dsp = EGL_NO_DISPLAY;
     //EGL 上下文
     EGLContext m_egl_context = EGL_NO_CONTEXT;
     //EGL 配置
     EGLConfig m_egl_config;
}

有了下面的筹备工作后,咱们就跟着流程图的步骤来一步步走。

(2)初始化 EGL

gl_render.cpp

bool GLRender::InitEGL() {
    // 创立 EglSurface 对象
    m_egl_surface = new EglSurface();
    // 调用 EglSurface 的 init 办法
    return m_egl_surface->Init();}

egl_surface.cpp

PS 咱们下面也说了 EGL 的初始化次要是对 EGLDisplay EGLConfig EGLContext 的操作,所以当初是对 EGLCore 的操作。

EglSurface::EglSurface() {
    // 创立 EGLCore
    m_core = new EglCore();}

bool EglSurface::Init() {
    // 调用 EGLCore 的 init 办法
    return m_core->Init(NULL);
}

egl_core.cpp

EglCore::EglCore() {}


bool EglCore::Init(EGLContext share_ctx) {if (m_egl_dsp != EGL_NO_DISPLAY) {LOGE(TAG, "EGL already set up")
        return true;
     }
    if (share_ctx == NULL) {share_ctx = EGL_NO_CONTEXT;}
     // 获取 Dispaly
    m_egl_dsp = eglGetDisplay(EGL_DEFAULT_DISPLAY);
     if (m_egl_dsp == EGL_NO_DISPLAY || eglGetError() != EGL_SUCCESS) {LOGE(TAG, "EGL init display fail")
            return false;
     }
        EGLint major_ver, minor_ver;
     // 初始化 egl
     EGLBoolean success = eglInitialize(m_egl_dsp, &major_ver, &minor_ver);
     if (success != EGL_TRUE || eglGetError() != EGL_SUCCESS) {LOGE(TAG, "EGL init fail")
            return false;
     }
        LOGI(TAG, "EGL version: %d.%d", major_ver, minor_ver)
     // 获取 EGLConfig   
     m_egl_config = GetEGLConfig();
     const EGLint attr[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
     // 创立 EGLContext
     m_egl_context = eglCreateContext(m_egl_dsp, m_egl_config, share_ctx, attr);
     if (m_egl_context == EGL_NO_CONTEXT) {LOGE(TAG, "EGL create fail, error is %x", eglGetError());
     return false; }
        EGLint egl_format;
     success = eglGetConfigAttrib(m_egl_dsp, m_egl_config, EGL_NATIVE_VISUAL_ID, &egl_format);
     if (success != EGL_TRUE || eglGetError() != EGL_SUCCESS) {LOGE(TAG, "EGL get config fail, error is %x", eglGetError())
            return false;
     }
    LOGI(TAG, "EGL init success")
    return true;
}

EGLConfig EglCore::GetEGLConfig() {
    EGLint numConfigs;
    EGLConfig config;

  // 心愿的最小配置,static const EGLint CONFIG_ATTRIBS[] = {
            EGL_BUFFER_SIZE, EGL_DONT_CARE,
            EGL_RED_SIZE, 8,//R 位数
            EGL_GREEN_SIZE, 8,//G 位数
            EGL_BLUE_SIZE, 8,//B 位数
            EGL_ALPHA_SIZE, 8,//A 位数
            EGL_DEPTH_SIZE, 16,// 深度
            EGL_STENCIL_SIZE, EGL_DONT_CARE,
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
            EGL_NONE // the end 完结标记
    };
  // 依据你所设定的最小配置零碎会抉择一个满足你最低要求的配置,这个真正的配置往往要比你冀望的属性更多
    EGLBoolean success = eglChooseConfig(m_egl_dsp, CONFIG_ATTRIBS, &config, 1, &numConfigs);
    if (!success || eglGetError() != EGL_SUCCESS) {LOGE(TAG, "EGL config fail")
        return NULL;
    }
    return config;
}

(3)创立 Window

gl_render.cpp

void GLRender::InitDspWindow(JNIEnv *env) {
  // 传进来的 Surface 对象的援用
    if (m_surface_ref != NULL) {
        // 初始化窗口
        m_native_window = ANativeWindow_fromSurface(env, m_surface_ref);

        // 绘制区域的宽高
        m_window_width = ANativeWindow_getWidth(m_native_window);
        m_window_height = ANativeWindow_getHeight(m_native_window);

        // 设置宽高限度缓冲区中的像素数量
        ANativeWindow_setBuffersGeometry(m_native_window, m_window_width,
                                         m_window_height, WINDOW_FORMAT_RGBA_8888);

        LOGD(TAG, "View Port width: %d, height: %d", m_window_width, m_window_height)
    }
}

(4)创立 EglSurface 并绑定到线程

gl_render.cpp

void GLRender::CreateSurface() {m_egl_surface->CreateEglSurface(m_native_window, m_window_width, m_window_height);
    glViewport(0, 0, m_window_width, m_window_height);
}

egl_surface.cpp

/**
 * 
 * @param native_window 传入上一步创立的 ANativeWindow
 * @param width 
 * @param height 
 */
void EglSurface::CreateEglSurface(ANativeWindow *native_window, int width, int height) {if (native_window != NULL) {
        this->m_native_window = native_window;
        m_surface = m_core->CreateWindSurface(m_native_window);
    } else {m_surface = m_core->CreateOffScreenSurface(width, height);
    }
    if (m_surface == NULL) {LOGE(TAG, "EGL create window surface fail")
        Release();}
    MakeCurrent();}

void EglSurface::MakeCurrent() {m_core->MakeCurrent(m_surface);
}

egl_core.cpp

EGLSurface EglCore::CreateWindSurface(ANativeWindow *window) {
  // 调用 EGL Native API 创立 Window Surface
    EGLSurface surface = eglCreateWindowSurface(m_egl_dsp, m_egl_config, window, 0);
    if (eglGetError() != EGL_SUCCESS) {LOGI(TAG, "EGL create window surface fail")
        return NULL;
    }
    return surface;
}

void EglCore::MakeCurrent(EGLSurface egl_surface) {
  // 调用 EGL Native API 绑定渲染环境到以后线程
    if (!eglMakeCurrent(m_egl_dsp, egl_surface, egl_surface, m_egl_context)) {LOGE(TAG, "EGL make current fail");
    }
}

(5)渲染

gl_render.cpp

void GLRender::Render() {if (RENDERING == m_state) {pImageRender->DoDraw();// 画画画....
        m_egl_surface->SwapBuffers();}
}

egl_surface.cpp

void EglSurface::SwapBuffers() {m_core->SwapBuffer(m_surface);
}

egl_core.cpp

void EglCore::SwapBuffer(EGLSurface egl_surface) {
  // 调用 EGL Native API
    eglSwapBuffers(m_egl_dsp, egl_surface);
}

前面的进行与销毁就交给读者自行钻研了。

代码

EGLDemoActivity.java

EGL Native

正文完
 0