Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(49)

Side by Side Diff: talk/app/webrtc/java/android/org/webrtc/SurfaceTextureHelper.java

Issue 1460703002: Implement AndroidTextureBuffer::NativeToI420. (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Comment improvements and some cleanup. Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * libjingle 2 * libjingle
3 * Copyright 2015 Google Inc. 3 * Copyright 2015 Google Inc.
4 * 4 *
5 * Redistribution and use in source and binary forms, with or without 5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met: 6 * modification, are permitted provided that the following conditions are met:
7 * 7 *
8 * 1. Redistributions of source code must retain the above copyright notice, 8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer. 9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * 2. Redistributions in binary form must reproduce the above copyright notice,
(...skipping 17 matching lines...) Expand all
28 package org.webrtc; 28 package org.webrtc;
29 29
30 import android.graphics.SurfaceTexture; 30 import android.graphics.SurfaceTexture;
31 import android.opengl.GLES11Ext; 31 import android.opengl.GLES11Ext;
32 import android.opengl.GLES20; 32 import android.opengl.GLES20;
33 import android.os.Build; 33 import android.os.Build;
34 import android.os.Handler; 34 import android.os.Handler;
35 import android.os.HandlerThread; 35 import android.os.HandlerThread;
36 import android.os.SystemClock; 36 import android.os.SystemClock;
37 37
38 import java.nio.ByteBuffer;
39 import java.nio.FloatBuffer;
38 import java.util.concurrent.Callable; 40 import java.util.concurrent.Callable;
39 import java.util.concurrent.CountDownLatch; 41 import java.util.concurrent.CountDownLatch;
40 import java.util.concurrent.TimeUnit; 42 import java.util.concurrent.TimeUnit;
41 43
42 /** 44 /**
43 * Helper class to create and synchronize access to a SurfaceTexture. The caller will get notified 45 * Helper class to create and synchronize access to a SurfaceTexture. The caller will get notified
44 * of new frames in onTextureFrameAvailable(), and should call returnTextureFram e() when done with 46 * of new frames in onTextureFrameAvailable(), and should call returnTextureFram e() when done with
45 * the frame. Only one texture frame can be in flight at once, so returnTextureF rame() must be 47 * the frame. Only one texture frame can be in flight at once, so returnTextureF rame() must be
46 * called in order to receive a new frame. Call disconnect() to stop receiveing new frames and 48 * called in order to receive a new frame. Call disconnect() to stop receiveing new frames and
47 * release all resources. 49 * release all resources.
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
86 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.andr oid/android/5.1.1_r1/android/graphics/SurfaceTexture.java#195. 88 // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.andr oid/android/5.1.1_r1/android/graphics/SurfaceTexture.java#195.
87 // Therefore, in order to control the callback thread on API lvl < 21, the S urfaceTextureHelper 89 // Therefore, in order to control the callback thread on API lvl < 21, the S urfaceTextureHelper
88 // is constructed on the |handler| thread. 90 // is constructed on the |handler| thread.
89 return ThreadUtils.invokeUninterruptibly(finalHandler, new Callable<SurfaceT extureHelper>() { 91 return ThreadUtils.invokeUninterruptibly(finalHandler, new Callable<SurfaceT extureHelper>() {
90 @Override public SurfaceTextureHelper call() { 92 @Override public SurfaceTextureHelper call() {
91 return new SurfaceTextureHelper(sharedContext, finalHandler, (handler == null)); 93 return new SurfaceTextureHelper(sharedContext, finalHandler, (handler == null));
92 } 94 }
93 }); 95 });
94 } 96 }
95 97
98 // State for YUV conversion, instantiated on demand.
99 static private class YuvConverter {
100 private final EglBase eglBase;
101 private final GlShader shader;
102 private boolean released = false;
103
104 // Vertex coordinates in Normalized Device Coordinates, i.e.
105 // (-1, -1) is bottom-left and (1, 1) is top-right.
106 private static final FloatBuffer DEVICE_RECTANGLE =
107 GlUtil.createFloatBuffer(new float[] {
108 -1.0f, -1.0f, // Bottom left.
109 1.0f, -1.0f, // Bottom right.
110 -1.0f, 1.0f, // Top left.
111 1.0f, 1.0f, // Top right.
112 });
113
114 // Texture coordinates - (0, 0) is bottom-left and (1, 1) is top-right.
115 private static final FloatBuffer TEXTURE_RECTANGLE =
116 GlUtil.createFloatBuffer(new float[] {
117 0.0f, 0.0f, // Bottom left.
118 1.0f, 0.0f, // Bottom right.
119 0.0f, 1.0f, // Top left.
120 1.0f, 1.0f // Top right.
121 });
122
123 private static final String VERTEX_SHADER =
124 "varying vec2 interp_tc;\n"
125 + "attribute vec4 in_pos;\n"
126 + "attribute vec4 in_tc;\n"
127 + "\n"
128 + "uniform mat4 texMatrix;\n"
129 + "\n"
130 + "void main() {\n"
131 + " gl_Position = in_pos;\n"
132 + " interp_tc = (texMatrix * in_tc).xy;\n"
133 + "}\n";
134
135 private static final String FRAGMENT_SHADER =
136 "#extension GL_OES_EGL_image_external : require\n"
137 + "precision mediump float;\n"
138 + "varying vec2 interp_tc;\n"
139 + "\n"
140 + "uniform samplerExternalOES oesTex;\n"
141 // Difference in texture coordinate corresponding to one
142 // sub-pixel in the x direction.
143 + "uniform vec2 xUnit;\n"
144 // Color conversion coefficients, including constant term
145 + "uniform vec4 coeffs;\n"
146 + "\n"
147 + "void main() {\n"
148 // Since the alpha read from the texture is always 1, this could
149 // be written as a mat4 x vec4 multiply. However, that seems to
150 // give a worse framerate, possibly because the additional
151 // multiplies by 1.0 consume resources. TODO(nisse): Could also
152 // try to do it as a vec3 x mat3x4, followed by an add in of a
153 // constant vector.
154 + " gl_FragColor.r = coeffs.a + dot(coeffs.rgb,\n"
155 + " texture2D(oesTex, interp_tc - 1.5 * xUnit).rgb);\n"
156 + " gl_FragColor.g = coeffs.a + dot(coeffs.rgb,\n"
157 + " texture2D(oesTex, interp_tc - 0.5 * xUnit).rgb);\n"
158 + " gl_FragColor.b = coeffs.a + dot(coeffs.rgb,\n"
159 + " texture2D(oesTex, interp_tc + 0.5 * xUnit).rgb);\n"
160 + " gl_FragColor.a = coeffs.a + dot(coeffs.rgb,\n"
161 + " texture2D(oesTex, interp_tc + 1.5 * xUnit).rgb);\n"
162 + "}\n";
163
164 private int texMatrixLoc;
165 private int xUnitLoc;
166 private int coeffsLoc;;
167
168 YuvConverter (EglBase.Context sharedContext) {
169 eglBase = EglBase.create(sharedContext, EglBase.CONFIG_PIXEL_RGBA_BUFFER);
170 eglBase.createDummyPbufferSurface();
171 eglBase.makeCurrent();
172
173 shader = new GlShader(VERTEX_SHADER, FRAGMENT_SHADER);
174 shader.useProgram();
175 texMatrixLoc = shader.getUniformLocation("texMatrix");
176 xUnitLoc = shader.getUniformLocation("xUnit");
177 coeffsLoc = shader.getUniformLocation("coeffs");
178 GLES20.glUniform1i(shader.getUniformLocation("oesTex"), 0);
179 GlUtil.checkNoGLES2Error("Initialize fragment shader uniform values.");
180 // Initialize vertex shader attributes.
181 shader.setVertexAttribArray("in_pos", 2, DEVICE_RECTANGLE);
182 // If the width is not a multiple of 4 pixels, the texture
183 // will be scaled up slightly and clipped at the right border.
184 shader.setVertexAttribArray("in_tc", 2, TEXTURE_RECTANGLE);
185 }
186
187 synchronized void convert(ByteBuffer buf,
188 int width, int height, int stride, int textureId, float [] transformMatr ix) {
189 if (released) {
190 throw new IllegalStateException(
191 "YuvConverter.convert called on released object");
192 }
193
194 // We draw into a buffer laid out like
195 //
196 // +---------+
197 // | |
198 // | Y |
199 // | |
200 // | |
201 // +----+----+
202 // | U | V |
203 // | | |
204 // +----+----+
205 //
206 // In memory, we use the same stride for all of Y, U and V. The
207 // U data starts at offset |height| * |stride| from the Y data,
208 // and the V data starts at at offset |stride/2| from the U
209 // data, with rows of U and V data alternating.
210 //
211 // Now, it would have made sense to allocate a pixel buffer with
212 // a single byte per pixel (EGL10.EGL_COLOR_BUFFER_TYPE,
213 // EGL10.EGL_LUMINANCE_BUFFER,), but that seems to be
214 // unsupported by devices. So do the following hack: Allocate an
215 // RGBA buffer, of width |stride|/4. To render each of these
216 // large pixels, sample the texture at 4 different x coordinates
217 // and store the results in the four components.
218 //
219 // Since the V data needs to start on a boundary of such a
220 // larger pixel, it is not sufficient that |stride| is even, it
221 // has to be a multiple of 8 pixels.
222
223 if (stride % 8 != 0) {
224 throw new IllegalArgumentException(
225 "Invalid stride, must be a multiple of 8");
226 }
227 if (stride < width){
228 throw new IllegalArgumentException(
229 "Invalid stride, must >= width");
230 }
231
232 int y_width = (width+3) / 4;
233 int uv_width = (width+7) / 8;
234 int uv_height = (height+1)/2;
235 int total_height = height + uv_height;
236 int size = stride * total_height;
237
238 if (buf.capacity() < size) {
239 throw new IllegalArgumentException("YuvConverter.convert called with too small buffer");
240 }
241 // Produce a frame buffer starting at top-left corner, not
242 // bottom-left.
243 transformMatrix =
244 RendererCommon.multiplyMatrices(transformMatrix,
245 RendererCommon.verticalFlipMatrix());
246
247 eglBase.withPbufferSurface(stride/4, total_height);
248
249 eglBase.makeCurrent();
250
251 GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
252 GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
253 GLES20.glUniformMatrix4fv(texMatrixLoc, 1, false, transformMatrix, 0);
254
255 // Draw Y
256 GLES20.glViewport(0, 0, y_width, height);
257 // Matrix * (1;0;0;0) / width. Note that opengl uses column major order.
258 GLES20.glUniform2f(xUnitLoc,
259 transformMatrix[0] / width,
260 transformMatrix[1] / width);
261 // Y'UV444 to RGB888, see
262 // https://en.wikipedia.org/wiki/YUV#Y.27UV444_to_RGB888_conversion
263 GLES20.glUniform4f(coeffsLoc, 0.299f, 0.587f, 0.114f, 0.0f);
264 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
265
266 // Draw U
267 GLES20.glViewport(0, height, uv_width, uv_height);
268 // Matrix * (1;0;0;0) / (2*width). Note that opengl uses column major orde r.
269 GLES20.glUniform2f(xUnitLoc,
270 transformMatrix[0] / (2.0f*width),
271 transformMatrix[1] / (2.0f*width));
272 /* Use ITU-R coefficients for U and V */
273 GLES20.glUniform4f(coeffsLoc, -0.169f, -0.331f, 0.499f, 0.5f);
274 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
275
276 // Draw V
277 GLES20.glViewport(stride/8, height, uv_width, uv_height);
278 /* Use ITU-R coefficients for U and V */
279 GLES20.glUniform4f(coeffsLoc, 0.499f, -0.418f, -0.0813f, 0.5f);
280 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
281
282 GLES20.glReadPixels(0, 0, stride/4, total_height, GLES20.GL_RGBA,
283 GLES20.GL_UNSIGNED_BYTE, buf);
284 // Only a single call to at the end, when operations are complete.
perkj_webrtc 2015/12/09 13:57:36 remove this comment please, it is not needed.
285 GlUtil.checkNoGLES2Error("YuvConverter.convert");
286
287 // Unbind texture. Reportedly needed on some devices to get
288 // the texture updated from the camera.
289 GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
290 }
291
292 synchronized public void release() {
perkj_webrtc 2015/12/09 13:57:36 not public please.
293 released = true;
294 eglBase.makeCurrent();
295 shader.release();
296 eglBase.release();
297 }
298 }
299
96 private final Handler handler; 300 private final Handler handler;
97 private boolean isOwningThread; 301 private boolean isOwningThread;
98 private final EglBase eglBase; 302 private final EglBase eglBase;
99 private final SurfaceTexture surfaceTexture; 303 private final SurfaceTexture surfaceTexture;
100 private final int oesTextureId; 304 private final int oesTextureId;
305 private YuvConverter yuvConverter;
306
101 private OnTextureFrameAvailableListener listener; 307 private OnTextureFrameAvailableListener listener;
102 // The possible states of this class. 308 // The possible states of this class.
103 private boolean hasPendingTexture = false; 309 private boolean hasPendingTexture = false;
104 private boolean isTextureInUse = false; 310 private boolean isTextureInUse = false;
105 private boolean isQuitting = false; 311 private boolean isQuitting = false;
106 312
107 private SurfaceTextureHelper(EglBase.Context sharedContext, 313 private SurfaceTextureHelper(EglBase.Context sharedContext,
108 Handler handler, boolean isOwningThread) { 314 Handler handler, boolean isOwningThread) {
109 if (handler.getLooper().getThread() != Thread.currentThread()) { 315 if (handler.getLooper().getThread() != Thread.currentThread()) {
110 throw new IllegalStateException("SurfaceTextureHelper must be created on t he handler thread"); 316 throw new IllegalStateException("SurfaceTextureHelper must be created on t he handler thread");
111 } 317 }
112 this.handler = handler; 318 this.handler = handler;
113 this.isOwningThread = isOwningThread; 319 this.isOwningThread = isOwningThread;
114 320
115 eglBase = EglBase.create(sharedContext, EglBase.CONFIG_PIXEL_BUFFER); 321 eglBase = EglBase.create(sharedContext, EglBase.CONFIG_PIXEL_BUFFER);
116 eglBase.createDummyPbufferSurface(); 322 eglBase.createDummyPbufferSurface();
117 eglBase.makeCurrent(); 323 eglBase.makeCurrent();
118 324
119 oesTextureId = GlUtil.generateTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES); 325 oesTextureId = GlUtil.generateTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES);
120 surfaceTexture = new SurfaceTexture(oesTextureId); 326 surfaceTexture = new SurfaceTexture(oesTextureId);
121 } 327 }
122 328
329 private YuvConverter getYuvConverter() {
330 // yuvConverter is assign once
perkj_webrtc 2015/12/09 13:57:36 s/ assigned
331 if (yuvConverter != null)
332 return yuvConverter;
333
334 synchronized(this) {
335 if (yuvConverter == null)
336 yuvConverter = new YuvConverter(eglBase.getEglBaseContext());
337 return yuvConverter;
338 }
339 }
340
123 /** 341 /**
124 * Start to stream textures to the given |listener|. 342 * Start to stream textures to the given |listener|.
125 * A Listener can only be set once. 343 * A Listener can only be set once.
126 */ 344 */
127 public void setListener(OnTextureFrameAvailableListener listener) { 345 public void setListener(OnTextureFrameAvailableListener listener) {
128 if (this.listener != null) { 346 if (this.listener != null) {
129 throw new IllegalStateException("SurfaceTextureHelper listener has already been set."); 347 throw new IllegalStateException("SurfaceTextureHelper listener has already been set.");
130 } 348 }
131 this.listener = listener; 349 this.listener = listener;
132 surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailab leListener() { 350 surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailab leListener() {
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
200 * onTextureFrameAvailable() after this function returns. 418 * onTextureFrameAvailable() after this function returns.
201 */ 419 */
202 public void disconnect(Handler handler) { 420 public void disconnect(Handler handler) {
203 if (this.handler != handler) { 421 if (this.handler != handler) {
204 throw new IllegalStateException("Wrong handler."); 422 throw new IllegalStateException("Wrong handler.");
205 } 423 }
206 isOwningThread = true; 424 isOwningThread = true;
207 disconnect(); 425 disconnect();
208 } 426 }
209 427
428 public void textureToYUV(ByteBuffer buf,
429 int width, int height, int stride, int textureId, float [] transformMatrix ) {
430 if (textureId != oesTextureId)
431 throw new IllegalStateException("textureToByteBuffer called with unexpecte d textureId");
432
433 getYuvConverter().convert(buf, width, height, stride, textureId, transformMa trix);
434 }
435
210 private void tryDeliverTextureFrame() { 436 private void tryDeliverTextureFrame() {
211 if (handler.getLooper().getThread() != Thread.currentThread()) { 437 if (handler.getLooper().getThread() != Thread.currentThread()) {
212 throw new IllegalStateException("Wrong thread."); 438 throw new IllegalStateException("Wrong thread.");
213 } 439 }
214 if (isQuitting || !hasPendingTexture || isTextureInUse) { 440 if (isQuitting || !hasPendingTexture || isTextureInUse) {
215 return; 441 return;
216 } 442 }
217 isTextureInUse = true; 443 isTextureInUse = true;
218 hasPendingTexture = false; 444 hasPendingTexture = false;
219 445
220 eglBase.makeCurrent(); 446 eglBase.makeCurrent();
221 surfaceTexture.updateTexImage(); 447 surfaceTexture.updateTexImage();
222 448
223 final float[] transformMatrix = new float[16]; 449 final float[] transformMatrix = new float[16];
224 surfaceTexture.getTransformMatrix(transformMatrix); 450 surfaceTexture.getTransformMatrix(transformMatrix);
225 final long timestampNs = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_C REAM_SANDWICH) 451 final long timestampNs = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_C REAM_SANDWICH)
226 ? surfaceTexture.getTimestamp() 452 ? surfaceTexture.getTimestamp()
227 : TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime()); 453 : TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime());
228 listener.onTextureFrameAvailable(oesTextureId, transformMatrix, timestampNs) ; 454 listener.onTextureFrameAvailable(oesTextureId, transformMatrix, timestampNs) ;
229 } 455 }
230 456
231 private void release() { 457 private void release() {
232 if (handler.getLooper().getThread() != Thread.currentThread()) { 458 if (handler.getLooper().getThread() != Thread.currentThread()) {
233 throw new IllegalStateException("Wrong thread."); 459 throw new IllegalStateException("Wrong thread.");
234 } 460 }
235 if (isTextureInUse || !isQuitting) { 461 if (isTextureInUse || !isQuitting) {
236 throw new IllegalStateException("Unexpected release."); 462 throw new IllegalStateException("Unexpected release.");
237 } 463 }
464 synchronized (this) {
465 if (yuvConverter != null)
466 yuvConverter.release();
467 }
238 eglBase.makeCurrent(); 468 eglBase.makeCurrent();
239 GLES20.glDeleteTextures(1, new int[] {oesTextureId}, 0); 469 GLES20.glDeleteTextures(1, new int[] {oesTextureId}, 0);
240 surfaceTexture.release(); 470 surfaceTexture.release();
241 eglBase.release(); 471 eglBase.release();
242 handler.getLooper().quit(); 472 handler.getLooper().quit();
243 } 473 }
244 } 474 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698