blob: 844ab58bfe021460dbd08b434403f4f427b3fa90 [file] [log] [blame]
Magnus Jedvert577bc192016-10-19 15:29:02 +02001/*
2 * Copyright 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11package org.webrtc;
12
13import android.opengl.GLES11Ext;
14import android.opengl.GLES20;
15import java.nio.ByteBuffer;
16import java.nio.FloatBuffer;
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020017import org.webrtc.VideoFrame.I420Buffer;
18import org.webrtc.VideoFrame.TextureBuffer;
Magnus Jedvert577bc192016-10-19 15:29:02 +020019
20/**
magjed1cb48232016-10-20 03:19:16 -070021 * Class for converting OES textures to a YUV ByteBuffer. It should be constructed on a thread with
22 * an active EGL context, and only be used from that thread.
Magnus Jedvert577bc192016-10-19 15:29:02 +020023 */
Sami Kalliomäki6bf70d22017-10-17 09:22:23 +020024public class YuvConverter {
Magnus Jedvert577bc192016-10-19 15:29:02 +020025 // Vertex coordinates in Normalized Device Coordinates, i.e.
26 // (-1, -1) is bottom-left and (1, 1) is top-right.
27 private static final FloatBuffer DEVICE_RECTANGLE = GlUtil.createFloatBuffer(new float[] {
28 -1.0f, -1.0f, // Bottom left.
29 1.0f, -1.0f, // Bottom right.
30 -1.0f, 1.0f, // Top left.
31 1.0f, 1.0f, // Top right.
32 });
33
34 // Texture coordinates - (0, 0) is bottom-left and (1, 1) is top-right.
35 private static final FloatBuffer TEXTURE_RECTANGLE = GlUtil.createFloatBuffer(new float[] {
36 0.0f, 0.0f, // Bottom left.
37 1.0f, 0.0f, // Bottom right.
38 0.0f, 1.0f, // Top left.
39 1.0f, 1.0f // Top right.
40 });
41
42 // clang-format off
43 private static final String VERTEX_SHADER =
44 "varying vec2 interp_tc;\n"
45 + "attribute vec4 in_pos;\n"
46 + "attribute vec4 in_tc;\n"
47 + "\n"
48 + "uniform mat4 texMatrix;\n"
49 + "\n"
50 + "void main() {\n"
51 + " gl_Position = in_pos;\n"
52 + " interp_tc = (texMatrix * in_tc).xy;\n"
53 + "}\n";
54
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020055 private static final String OES_FRAGMENT_SHADER =
Magnus Jedvert577bc192016-10-19 15:29:02 +020056 "#extension GL_OES_EGL_image_external : require\n"
57 + "precision mediump float;\n"
58 + "varying vec2 interp_tc;\n"
59 + "\n"
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020060 + "uniform samplerExternalOES tex;\n"
Magnus Jedvert577bc192016-10-19 15:29:02 +020061 // Difference in texture coordinate corresponding to one
62 // sub-pixel in the x direction.
63 + "uniform vec2 xUnit;\n"
64 // Color conversion coefficients, including constant term
65 + "uniform vec4 coeffs;\n"
66 + "\n"
67 + "void main() {\n"
68 // Since the alpha read from the texture is always 1, this could
69 // be written as a mat4 x vec4 multiply. However, that seems to
70 // give a worse framerate, possibly because the additional
71 // multiplies by 1.0 consume resources. TODO(nisse): Could also
72 // try to do it as a vec3 x mat3x4, followed by an add in of a
73 // constant vector.
74 + " gl_FragColor.r = coeffs.a + dot(coeffs.rgb,\n"
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020075 + " texture2D(tex, interp_tc - 1.5 * xUnit).rgb);\n"
Magnus Jedvert577bc192016-10-19 15:29:02 +020076 + " gl_FragColor.g = coeffs.a + dot(coeffs.rgb,\n"
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020077 + " texture2D(tex, interp_tc - 0.5 * xUnit).rgb);\n"
Magnus Jedvert577bc192016-10-19 15:29:02 +020078 + " gl_FragColor.b = coeffs.a + dot(coeffs.rgb,\n"
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020079 + " texture2D(tex, interp_tc + 0.5 * xUnit).rgb);\n"
Magnus Jedvert577bc192016-10-19 15:29:02 +020080 + " gl_FragColor.a = coeffs.a + dot(coeffs.rgb,\n"
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020081 + " texture2D(tex, interp_tc + 1.5 * xUnit).rgb);\n"
82 + "}\n";
83
84 private static final String RGB_FRAGMENT_SHADER =
85 "precision mediump float;\n"
86 + "varying vec2 interp_tc;\n"
87 + "\n"
Sami Kalliomäki033ea5f2017-10-18 09:16:22 +020088 + "uniform sampler2D tex;\n"
Sami Kalliomäkicb98b112017-10-16 11:20:26 +020089 // Difference in texture coordinate corresponding to one
90 // sub-pixel in the x direction.
91 + "uniform vec2 xUnit;\n"
92 // Color conversion coefficients, including constant term
93 + "uniform vec4 coeffs;\n"
94 + "\n"
95 + "void main() {\n"
96 // Since the alpha read from the texture is always 1, this could
97 // be written as a mat4 x vec4 multiply. However, that seems to
98 // give a worse framerate, possibly because the additional
99 // multiplies by 1.0 consume resources. TODO(nisse): Could also
100 // try to do it as a vec3 x mat3x4, followed by an add in of a
101 // constant vector.
102 + " gl_FragColor.r = coeffs.a + dot(coeffs.rgb,\n"
103 + " texture2D(tex, interp_tc - 1.5 * xUnit).rgb);\n"
104 + " gl_FragColor.g = coeffs.a + dot(coeffs.rgb,\n"
105 + " texture2D(tex, interp_tc - 0.5 * xUnit).rgb);\n"
106 + " gl_FragColor.b = coeffs.a + dot(coeffs.rgb,\n"
107 + " texture2D(tex, interp_tc + 0.5 * xUnit).rgb);\n"
108 + " gl_FragColor.a = coeffs.a + dot(coeffs.rgb,\n"
109 + " texture2D(tex, interp_tc + 1.5 * xUnit).rgb);\n"
Magnus Jedvert577bc192016-10-19 15:29:02 +0200110 + "}\n";
111 // clang-format on
112
magjed1cb48232016-10-20 03:19:16 -0700113 private final ThreadUtils.ThreadChecker threadChecker = new ThreadUtils.ThreadChecker();
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200114 private final GlTextureFrameBuffer textureFrameBuffer;
115 private TextureBuffer.Type shaderTextureType;
116 private GlShader shader;
117 private int texMatrixLoc;
118 private int xUnitLoc;
119 private int coeffsLoc;
magjed1cb48232016-10-20 03:19:16 -0700120 private boolean released = false;
Magnus Jedvert577bc192016-10-19 15:29:02 +0200121
magjed1cb48232016-10-20 03:19:16 -0700122 /**
123 * This class should be constructed on a thread that has an active EGL context.
124 */
125 public YuvConverter() {
126 threadChecker.checkIsOnValidThread();
sakal2fcd2dd2017-01-18 03:21:10 -0800127 textureFrameBuffer = new GlTextureFrameBuffer(GLES20.GL_RGBA);
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200128 }
129
130 /** Converts the texture buffer to I420. */
131 public I420Buffer convert(TextureBuffer textureBuffer) {
132 final int width = textureBuffer.getWidth();
133 final int height = textureBuffer.getHeight();
134
135 // SurfaceTextureHelper requires a stride that is divisible by 8. Round width up.
136 // See SurfaceTextureHelper for details on the size and format.
137 final int stride = ((width + 7) / 8) * 8;
138 final int uvHeight = (height + 1) / 2;
139 // Due to the layout used by SurfaceTextureHelper, vPos + stride * uvHeight would overrun the
140 // buffer. Add one row at the bottom to compensate for this. There will never be data in the
141 // extra row, but now other code does not have to deal with v stride * v height exceeding the
142 // buffer's capacity.
143 final int size = stride * (height + uvHeight + 1);
144 ByteBuffer buffer = JniCommon.allocateNativeByteBuffer(size);
145 convert(buffer, width, height, stride, textureBuffer.getTextureId(),
146 RendererCommon.convertMatrixFromAndroidGraphicsMatrix(textureBuffer.getTransformMatrix()),
147 textureBuffer.getType());
148
149 final int yPos = 0;
150 final int uPos = yPos + stride * height;
151 // Rows of U and V alternate in the buffer, so V data starts after the first row of U.
152 final int vPos = uPos + stride / 2;
153
154 buffer.position(yPos);
155 buffer.limit(yPos + stride * height);
156 ByteBuffer dataY = buffer.slice();
157
158 buffer.position(uPos);
159 buffer.limit(uPos + stride * uvHeight);
160 ByteBuffer dataU = buffer.slice();
161
162 buffer.position(vPos);
163 buffer.limit(vPos + stride * uvHeight);
164 ByteBuffer dataV = buffer.slice();
165
166 // SurfaceTextureHelper uses the same stride for Y, U, and V data.
167 return JavaI420Buffer.wrap(width, height, dataY, stride, dataU, stride, dataV, stride,
168 () -> { JniCommon.freeNativeByteBuffer(buffer); });
169 }
170
171 /** Deprecated, use convert(TextureBuffer). */
172 @Deprecated
173 void convert(ByteBuffer buf, int width, int height, int stride, int srcTextureId,
174 float[] transformMatrix) {
175 convert(buf, width, height, stride, srcTextureId, transformMatrix, TextureBuffer.Type.OES);
176 }
177
178 private void initShader(TextureBuffer.Type textureType) {
179 if (shader != null) {
180 shader.release();
181 }
182
183 final String fragmentShader;
184 switch (textureType) {
185 case OES:
186 fragmentShader = OES_FRAGMENT_SHADER;
187 break;
188 case RGB:
189 fragmentShader = RGB_FRAGMENT_SHADER;
190 break;
191 default:
192 throw new IllegalArgumentException("Unsupported texture type.");
193 }
194
195 shaderTextureType = textureType;
196 shader = new GlShader(VERTEX_SHADER, fragmentShader);
Magnus Jedvert577bc192016-10-19 15:29:02 +0200197 shader.useProgram();
198 texMatrixLoc = shader.getUniformLocation("texMatrix");
199 xUnitLoc = shader.getUniformLocation("xUnit");
200 coeffsLoc = shader.getUniformLocation("coeffs");
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200201 GLES20.glUniform1i(shader.getUniformLocation("tex"), 0);
Magnus Jedvert577bc192016-10-19 15:29:02 +0200202 GlUtil.checkNoGLES2Error("Initialize fragment shader uniform values.");
203 // Initialize vertex shader attributes.
204 shader.setVertexAttribArray("in_pos", 2, DEVICE_RECTANGLE);
205 // If the width is not a multiple of 4 pixels, the texture
206 // will be scaled up slightly and clipped at the right border.
207 shader.setVertexAttribArray("in_tc", 2, TEXTURE_RECTANGLE);
Magnus Jedvert577bc192016-10-19 15:29:02 +0200208 }
209
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200210 private void convert(ByteBuffer buf, int width, int height, int stride, int srcTextureId,
211 float[] transformMatrix, TextureBuffer.Type textureType) {
magjed1cb48232016-10-20 03:19:16 -0700212 threadChecker.checkIsOnValidThread();
Magnus Jedvert577bc192016-10-19 15:29:02 +0200213 if (released) {
214 throw new IllegalStateException("YuvConverter.convert called on released object");
215 }
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200216 if (textureType != shaderTextureType) {
217 initShader(textureType);
218 }
Magnus Jedvertc040dae2017-11-17 16:50:17 +0100219 shader.useProgram();
Magnus Jedvert577bc192016-10-19 15:29:02 +0200220
221 // We draw into a buffer laid out like
222 //
223 // +---------+
224 // | |
225 // | Y |
226 // | |
227 // | |
228 // +----+----+
229 // | U | V |
230 // | | |
231 // +----+----+
232 //
233 // In memory, we use the same stride for all of Y, U and V. The
234 // U data starts at offset |height| * |stride| from the Y data,
235 // and the V data starts at at offset |stride/2| from the U
236 // data, with rows of U and V data alternating.
237 //
238 // Now, it would have made sense to allocate a pixel buffer with
239 // a single byte per pixel (EGL10.EGL_COLOR_BUFFER_TYPE,
240 // EGL10.EGL_LUMINANCE_BUFFER,), but that seems to be
241 // unsupported by devices. So do the following hack: Allocate an
242 // RGBA buffer, of width |stride|/4. To render each of these
243 // large pixels, sample the texture at 4 different x coordinates
244 // and store the results in the four components.
245 //
246 // Since the V data needs to start on a boundary of such a
247 // larger pixel, it is not sufficient that |stride| is even, it
248 // has to be a multiple of 8 pixels.
249
250 if (stride % 8 != 0) {
251 throw new IllegalArgumentException("Invalid stride, must be a multiple of 8");
252 }
253 if (stride < width) {
254 throw new IllegalArgumentException("Invalid stride, must >= width");
255 }
256
257 int y_width = (width + 3) / 4;
258 int uv_width = (width + 7) / 8;
259 int uv_height = (height + 1) / 2;
260 int total_height = height + uv_height;
261 int size = stride * total_height;
262
263 if (buf.capacity() < size) {
264 throw new IllegalArgumentException("YuvConverter.convert called with too small buffer");
265 }
266 // Produce a frame buffer starting at top-left corner, not
267 // bottom-left.
268 transformMatrix =
269 RendererCommon.multiplyMatrices(transformMatrix, RendererCommon.verticalFlipMatrix());
270
sakal2fcd2dd2017-01-18 03:21:10 -0800271 final int frameBufferWidth = stride / 4;
272 final int frameBufferHeight = total_height;
273 textureFrameBuffer.setSize(frameBufferWidth, frameBufferHeight);
274
magjed1cb48232016-10-20 03:19:16 -0700275 // Bind our framebuffer.
sakal2fcd2dd2017-01-18 03:21:10 -0800276 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, textureFrameBuffer.getFrameBufferId());
magjed1cb48232016-10-20 03:19:16 -0700277 GlUtil.checkNoGLES2Error("glBindFramebuffer");
278
Magnus Jedvert577bc192016-10-19 15:29:02 +0200279 GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200280 GLES20.glBindTexture(textureType.getGlTarget(), srcTextureId);
Magnus Jedvert577bc192016-10-19 15:29:02 +0200281 GLES20.glUniformMatrix4fv(texMatrixLoc, 1, false, transformMatrix, 0);
282
283 // Draw Y
284 GLES20.glViewport(0, 0, y_width, height);
285 // Matrix * (1;0;0;0) / width. Note that opengl uses column major order.
286 GLES20.glUniform2f(xUnitLoc, transformMatrix[0] / width, transformMatrix[1] / width);
287 // Y'UV444 to RGB888, see
288 // https://en.wikipedia.org/wiki/YUV#Y.27UV444_to_RGB888_conversion.
289 // We use the ITU-R coefficients for U and V */
290 GLES20.glUniform4f(coeffsLoc, 0.299f, 0.587f, 0.114f, 0.0f);
291 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
292
293 // Draw U
294 GLES20.glViewport(0, height, uv_width, uv_height);
295 // Matrix * (1;0;0;0) / (width / 2). Note that opengl uses column major order.
296 GLES20.glUniform2f(
297 xUnitLoc, 2.0f * transformMatrix[0] / width, 2.0f * transformMatrix[1] / width);
298 GLES20.glUniform4f(coeffsLoc, -0.169f, -0.331f, 0.499f, 0.5f);
299 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
300
301 // Draw V
302 GLES20.glViewport(stride / 8, height, uv_width, uv_height);
303 GLES20.glUniform4f(coeffsLoc, 0.499f, -0.418f, -0.0813f, 0.5f);
304 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
305
306 GLES20.glReadPixels(
magjed1cb48232016-10-20 03:19:16 -0700307 0, 0, frameBufferWidth, frameBufferHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
Magnus Jedvert577bc192016-10-19 15:29:02 +0200308
309 GlUtil.checkNoGLES2Error("YuvConverter.convert");
310
magjed1cb48232016-10-20 03:19:16 -0700311 // Restore normal framebuffer.
312 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
313 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
314
Magnus Jedvert577bc192016-10-19 15:29:02 +0200315 // Unbind texture. Reportedly needed on some devices to get
316 // the texture updated from the camera.
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200317 GLES20.glBindTexture(textureType.getGlTarget(), 0);
Magnus Jedvert577bc192016-10-19 15:29:02 +0200318 }
319
magjed1cb48232016-10-20 03:19:16 -0700320 public void release() {
321 threadChecker.checkIsOnValidThread();
Magnus Jedvert577bc192016-10-19 15:29:02 +0200322 released = true;
Sami Kalliomäkicb98b112017-10-16 11:20:26 +0200323 if (shader != null) {
324 shader.release();
325 }
sakal2fcd2dd2017-01-18 03:21:10 -0800326 textureFrameBuffer.release();
Magnus Jedvert577bc192016-10-19 15:29:02 +0200327 }
328}