OpenGL ES 相机预览
OpenGL ES 相机预览
相机开发是 OpenGL ES 开发的重要应用,利用 OpenGL 可以很方便地实现相机美颜、滤镜、塑型以及一些动态特效,其性能显著优于对应功能的 CPU 实现。
相机的预览实现一般有 2 种方式,一种是基于 Android 原生 SurfaceTexture 的纯 GPU 实现方式。
另一种是通过相机的预览回调接口获取帧的 YUV 数据,利用 CPU 算法处理完成之后,传入显存,再利用 GPU 实现 YUV 转 RGBA 进行渲染,即 CPU + GPU 的实现方式。
基于 Android 原生 SurfaceTexture 的纯 GPU 实现方式,相机可以使用 SurfaceTexture 作为预览载体,SurfaceTexture 可来自于 GLSurfaceView、TextureView 或 SurfaceView 这些独立拥有 Surface 的封装类,也可以自定义实现。
类似于普通 2D 纹理的创建,OES 纹理创建的实现如下:
private int createOESTexture(){
int[] texture = new int[1];
GLES20.glGenTextures(1, texture, 0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, texture[0]);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_LINEAR);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
return texture[0];
}
#extension GL_OES_EGL_image_external : require
#version 300 es
#extension GL_OES_EGL_image_external : require
precision mediump float;
in vec2 v_texCoord;
uniform samplerExternalOES s_TexSampler;
void main() {
gl_FragColor = texture(s_TexSampler, v_texCoord);
}
实际上当使用 TextureView 时,实际上也不需要自己去创建 OES 纹理,只需要绑定相机,配置好变换矩阵后即可实现相机预览。具体例子可直接参考Android 官方的 Samples https://github.com/android/camera-samples 。
相机预览基于 Android 原生 API 的纯 GPU 实现方式,操作简单,代码量很少,原生 API 已经做了很多封装,可以利用片段着色器轻易实现美颜滤镜等相机特效,缺点是扩展性差,例如要使用传统的 CPU 算法做一些滤镜或者美颜特效就很不方便,图像数据需要多次在内存与显存之间拷贝,会造成性能和功耗问题。
本文主要介绍将预览图像数据取出,传入 Native 层,然后对数据做一些处理(可选),最后做渲染的相机预览方式,这种方式相对复杂一些。
相机预览数据的常见格式是 YUV420P 或者 YUV420SP(NV21) ,需要将图像数据对应 YUV 3 个分量使用 3 个纹理传入显存,在片段着色器中将 YUV 数据转为 RGBA ,相关原理可参考NDK OpenGL ES 3.0 开发(三):YUV 渲染一文。
相机预览数据获取,以 Camera2 为例,主要是通过 ImageReader 实现,该类封装了 Surface :
private ImageReader.OnImageAvailableListener mOnPreviewImageAvailableListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image != null) {
if (mCamera2FrameCallback != null) {
mCamera2FrameCallback.onPreviewFrame(CameraUtil.YUV_420_888_data(image), image.getWidth(), image.getHeight());
}
image.close();
}
}
};
mPreviewImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 2);
mPreviewImageReader.setOnImageAvailableListener(mOnPreviewImageAvailableListener, mBackgroundHandler);
CaptureRequest.Builder builder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.addTarget(mPreviewImageReader.getSurface());
ession.setRepeatingRequest(mPreviewRequest, null, mBackgroundHandler);
//在自定义接口中获取预览数据,通过 JNI 传入到 C++ 层
public void onPreviewFrame(byte[] data, int width, int height) {
Log.d(TAG, "onPreviewFrame() called with: data = [" + data + "], width = [" + width + "], height = [" + height + "]");
mByteFlowRender.setRenderFrame(IMAGE_FORMAT_I420, data, width, height);
//每次传入新数据,请求重新渲染
mByteFlowRender.requestRender();
}
主要的 JNI :
public abstract class ByteFlowRender {
public static final int GL_RENDER_TYPE = 0;
public static final int CL_RENDER_TYPE = 1;
public static final int IMAGE_FORMAT_RGBA = 0x01;
public static final int IMAGE_FORMAT_NV21 = 0x02;
public static final int IMAGE_FORMAT_NV12 = 0x03;
public static final int IMAGE_FORMAT_I420 = 0x04;
public static final int PARAM_TYPE_SET_SHADER_INDEX = 201;
static {
System.loadLibrary("byteflow_render");
}
private long mNativeContextHandle;
protected native void native_CreateContext(int renderType);
protected native void native_DestroyContext();
protected native int native_Init(int initType);
protected native int native_UnInit();
protected native void native_UpdateFrame(int format, byte[] data, int width, int height);
protected native void native_LoadFilterData(int index, int format, int width, int height, byte[] bytes);
protected native void native_LoadShaderScript(int shaderIndex, String scriptStr);
protected native void native_SetTransformMatrix(float translateX, float translateY, float scaleX, float scaleY, int degree, int mirror);
protected native void native_SetParamsInt(int paramType, int value);
protected native int native_GetParamsInt(int paramType);
protected native void native_OnSurfaceCreated();
protected native void native_OnSurfaceChanged(int width, int height);
protected native void native_OnDrawFrame();
}
渲染 YUV 数据用到的着色器脚本,主要是将 3 个纹理对应的 YUV 分量,分别采样后转成 RGBA :
//顶点着色器
#version 100
varying vec2 v_texcoord;
attribute vec4 position;
attribute vec2 texcoord;
uniform mat4 MVP;
void main() {
v_texcoord = texcoord;
gl_Position = MVP*position;
}
//片段着色器
#version 100
precision highp float;
varying vec2 v_texcoord;
uniform lowp sampler2D s_textureY;
uniform lowp sampler2D s_textureU;
uniform lowp sampler2D s_textureV;
void main() {
float y, u, v, r, g, b;
y = texture2D(s_textureY, v_texcoord).r;
u = texture2D(s_textureU, v_texcoord).r;
v = texture2D(s_textureV, v_texcoord).r;
u = u - 0.5;
v = v - 0.5;
r = y + 1.403 * v;
g = y - 0.344 * u - 0.714 * v;
b = y + 1.770 * u;
gl_FragColor = vec4(r, g, b, 1.0);
}
C++ 层的主要实现:
//编译链接着色器
int GLByteFlowRender::CreateProgram(const char *pVertexShaderSource, const char *pFragShaderSource)
{
m_Program = GLUtils::CreateProgram(pVertexShaderSource, pFragShaderSource, m_VertexShader,
m_FragShader);
if (!m_Program)
{
GLUtils::CheckGLError("Create Program");
LOGCATE("GLByteFlowRender::CreateProgram Could not create program.");
return 0;
}
m_YTextureHandle = glGetUniformLocation(m_Program, "s_textureY");
m_UTextureHandle = glGetUniformLocation(m_Program, "s_textureU");
m_VTextureHandle = glGetUniformLocation(m_Program, "s_textureV");
m_VertexCoorHandle = (GLuint) glGetAttribLocation(m_Program, "position");
m_TextureCoorHandle = (GLuint) glGetAttribLocation(m_Program, "texcoord");
m_MVPHandle = glGetUniformLocation(m_Program, "MVP");
return m_Program;
}
//创建 YUV 分量对应的 3 个纹理
bool GLByteFlowRender::CreateTextures()
{
LOGCATE("GLByteFlowRender::CreateTextures");
GLsizei yWidth = static_cast<GLsizei>(m_RenderFrame.width);
GLsizei yHeight = static_cast<GLsizei>(m_RenderFrame.height);
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &m_YTextureId);
glBindTexture(GL_TEXTURE_2D, m_YTextureId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, yWidth, yHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE,
NULL);
if (!m_YTextureId)
{
GLUtils::CheckGLError("Create Y texture");
return false;
}
GLsizei uWidth = static_cast<GLsizei>(m_RenderFrame.width / 2);
GLsizei uHeight = yHeight / 2;
glActiveTexture(GL_TEXTURE1);
glGenTextures(1, &m_UTextureId);
glBindTexture(GL_TEXTURE_2D, m_UTextureId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, uWidth, uHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE,
NULL);
if (!m_UTextureId)
{
GLUtils::CheckGLError("Create U texture");
return false;
}
GLsizei vWidth = static_cast<GLsizei>(m_RenderFrame.width / 2);
GLsizei vHeight = (GLsizei) yHeight / 2;
glActiveTexture(GL_TEXTURE2);
glGenTextures(1, &m_VTextureId);
glBindTexture(GL_TEXTURE_2D, m_VTextureId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, vWidth, vHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE,
NULL);
if (!m_VTextureId)
{
GLUtils::CheckGLError("Create V texture");
return false;
}
return true;
}
//每传入一帧新数据后,更新纹理
bool GLByteFlowRender::UpdateTextures()
{
LOGCATE("GLByteFlowRender::UpdateTextures");
if (m_RenderFrame.ppPlane[0] == NULL)
{
return false;
}
if (!m_YTextureId && !m_UTextureId && !m_VTextureId && !CreateTextures())
{
return false;
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_YTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, (GLsizei) m_RenderFrame.width,
(GLsizei) m_RenderFrame.height, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, m_RenderFrame.ppPlane[0]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_UTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, (GLsizei) m_RenderFrame.width >> 1,
(GLsizei) m_RenderFrame.height >> 1, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, m_RenderFrame.ppPlane[1]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, m_VTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, (GLsizei) m_RenderFrame.width >> 1,
(GLsizei) m_RenderFrame.height >> 1, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, m_RenderFrame.ppPlane[2]);
return true;
}
//绑定纹理到着色器,传入顶点和纹理坐标数据
GLuint GLByteFlowRender::UseProgram()
{
LOGCATE("GLByteFlowRender::UseProgram");
ByteFlowLock lock(&m_ShaderBufLock);
if (m_IsShaderChanged)
{
GLUtils::DeleteProgram(m_Program);
CreateProgram(kVertexShader, m_pFragShaderBuf);
m_IsShaderChanged = false;
m_IsProgramChanged = true;
}
if (!m_Program)
{
LOGCATE("GLByteFlowRender::UseProgram Could not use program.");
return 0;
}
if (m_IsProgramChanged)
{
glUseProgram(m_Program);
GLUtils::CheckGLError("GLByteFlowRender::UseProgram");
glVertexAttribPointer(m_VertexCoorHandle, 2, GL_FLOAT, GL_FALSE, 2 * 4, VERTICES_COORS);
glEnableVertexAttribArray(m_VertexCoorHandle);
glUniform1i(m_YTextureHandle, 0);
glUniform1i(m_UTextureHandle, 1);
glUniform1i(m_VTextureHandle, 2);
glVertexAttribPointer(m_TextureCoorHandle, 2, GL_FLOAT, GL_FALSE, 2 * 4, TEXTURE_COORS);
glEnableVertexAttribArray(m_TextureCoorHandle);
m_IsProgramChanged = false;
}
return m_Program;
}
//渲染预览图像
void GLByteFlowRender::OnDrawFrame()
{
LOGCATE("GLByteFlowRender::OnDrawFrame");
glViewport(0, 0, m_ViewportWidth, m_ViewportHeight);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glDisable(GL_CULL_FACE);
if (!UpdateTextures() || !UseProgram())
{
LOGCATE("GLByteFlowRender::OnDrawFrame skip frame");
return;
}
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
后面文章会基于该预览实现添加一些滤镜效果。
进技术交流群,添加我的微信:Byte-Flow
本文来自作者投稿,版权归原作者所有。如需转载,请注明出处:https://www.nxrte.com/jishu/17998.html