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

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

Issue 1257043004: AppRTCDemo: Render each video in a separate SurfaceView (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Created 5 years, 4 months 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
(Empty)
1 /*
2 * libjingle
3 * Copyright 2015 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 package org.webrtc;
29
30 import android.content.Context;
31 import android.graphics.Point;
32 import android.graphics.SurfaceTexture;
33 import android.opengl.EGLContext;
34 import android.opengl.GLES20;
35 import android.os.Handler;
36 import android.os.HandlerThread;
37 import android.util.AttributeSet;
38 import android.util.Log;
39 import android.view.SurfaceHolder;
40 import android.view.SurfaceView;
41
42 /**
43 * Implements org.webrtc.VideoRenderer.Callbacks by displaying the video stream on a SurfaceView.
44 * renderFrame() is asynchronous to avoid blocking the calling thread. Instead, a shallow copy of
45 * the frame is posted to a dedicated render thread.
46 * This class is thread safe and handles access from potentially four different threads:
47 * Interaction from the main app in init, release, setMirror, and setScalingtype .
48 * Interaction from C++ webrtc::VideoRendererInterface in renderFrame and canApp lyRotation.
49 * Interaction from the Activity lifecycle in surfaceCreated, surfaceChanged, an d surfaceDestroyed.
50 * Interaction with the layout framework in onMeasure and onSizeChanged.
51 */
52 public class SurfaceViewRenderer extends SurfaceView
53 implements SurfaceHolder.Callback, VideoRenderer.Callbacks {
54 private static final String TAG = "SurfaceViewRenderer";
55
56 // Dedicated render thread. Synchronized on |this|.
57 private HandlerThread renderThread;
58 // Handler for inter-thread communication. Synchronized on |this|.
59 private Handler renderThreadHandler;
60 // Pending frame to render. Serves as a queue with size 1. Synchronized on |th is|.
61 private VideoRenderer.I420Frame pendingFrame;
62
63 // EGL and GL resources for drawing YUV/OES textures. After initilization, the se are only accessed
64 // from the render thread.
65 private EglBase eglBase;
66 private GlRectDrawer drawer;
67 // Texture ids for YUV frames. Allocated on first arrival of a YUV frame.
68 private int[] yuvTextures = null;
69
70 // These variables are synchronized on |layoutLock|.
71 private final Object layoutLock = new Object();
72 // Aspect ratio on screen.
73 private float layoutAspectRatio;
74 // Aspect ratio of the most recent video frame.
75 private float videoAspectRatio;
76 // |scalingType| determines how the video will fill the allowed layout area in onMeasure().
77 private VideoRendererGui.ScalingType scalingType =
78 VideoRendererGui.ScalingType.SCALE_ASPECT_BALANCED;
79 // If true, mirrors the video stream horizontally.
80 private boolean mirror;
81
82 // These variables are synchronized on |statisticsLock|.
83 private final Object statisticsLock = new Object();
84 // Total number of video frames received in renderFrame() call.
85 private int framesReceived;
86 // Number of video frames dropped by renderFrame() because previous frame has not been rendered
87 // yet.
88 private int framesDropped;
89 // Number of rendered video frames.
90 private int framesRendered;
91 // Time in ns when the first video frame was rendered.
92 private long firstFrameTimeNs;
93 // Time in ns spent in renderFrameOnRenderThread() function.
94 private long renderTimeNs;
95
96 /**
97 * Standard View constructor. In order to render something, you must first cal l init().
98 */
99 public SurfaceViewRenderer(Context context) {
100 super(context);
101 }
102
103 /**
104 * Standard View constructor. In order to render something, you must first cal l init().
105 */
106 public SurfaceViewRenderer(Context context, AttributeSet attrs) {
107 super(context, attrs);
108 }
109
110 /**
111 * Initialize this class, sharing resources with |sharedContext|.
112 */
113 public synchronized void init(EGLContext sharedContext) {
114 if (renderThreadHandler != null) {
115 throw new IllegalStateException("Already initialized");
116 }
117 Log.d(TAG, "Initializing");
118 renderThread = new HandlerThread(TAG);
119 renderThread.start();
120 renderThreadHandler = new Handler(renderThread.getLooper());
121 eglBase = new EglBase(sharedContext, EglBase.ConfigType.PLAIN);
122 drawer = new GlRectDrawer();
123 getHolder().addCallback(this);
124 }
125
126 /**
127 * Release all resources. This needs to be done manually, otherwise the resour ces are leaked.
128 */
129 public synchronized void release() {
130 if (renderThreadHandler == null) {
131 Log.d(TAG, "Already released");
132 return;
133 }
134 // Release EGL and GL resources on render thread.
135 renderThreadHandler.post(new Runnable() {
136 @Override public void run() {
137 drawer.release();
138 drawer = null;
139 if (yuvTextures != null) {
140 GLES20.glDeleteTextures(3, yuvTextures, 0);
141 yuvTextures = null;
142 }
143 eglBase.release();
144 eglBase = null;
145 }
146 });
147 // Don't accept any more messages to the render thread.
148 renderThreadHandler = null;
149 renderThread.quitSafely();
AlexG 2015/08/04 00:27:23 use quit() here to reduce exit latency - we don't
magjed_webrtc 2015/08/04 17:05:05 I want to make sure that the EGL/GL cleanup posted
150 renderThread = null;
151
152 getHolder().removeCallback(this);
153 if (pendingFrame != null) {
154 pendingFrame.release();
155 pendingFrame = null;
156 }
157 }
158
159 /**
160 * Set if the video stream should be mirrored or not.
161 */
162 public void setMirror(final boolean mirror) {
163 synchronized (layoutLock) {
164 this.mirror = mirror;
165 }
166 }
167
168 /**
169 * Set how the video will fill the allowed layout area.
170 */
171 public void setScalingType(VideoRendererGui.ScalingType scalingType) {
172 synchronized (layoutLock) {
173 this.scalingType = scalingType;
174 }
175 }
176
177 // VideoRenderer.Callbacks interface.
178 @Override
179 public void renderFrame(VideoRenderer.I420Frame frame) {
180 synchronized (statisticsLock) {
181 ++framesReceived;
182 }
183 // Trigger layout update if video aspect ratio changed.
184 synchronized (layoutLock) {
AlexG 2015/08/04 00:27:23 Do you think it's worth skip rendering of the fram
magjed_webrtc 2015/08/04 17:05:05 Do you mean dropping the frame or delay renderFram
AlexG 2015/08/05 00:47:11 I often seen the cases when for bad connection rem
magjed_webrtc 2015/08/07 17:14:50 Done. I block rendering while a layout update is p
185 final float videoAspectRatio = (float) frame.rotatedWidth() / frame.rotate dHeight();
186 if (videoAspectRatio != this.videoAspectRatio) {
187 this.videoAspectRatio = videoAspectRatio;
188 // Need to request layout update from the UI thread.
189 post(new Runnable() {
190 @Override public void run() {
191 requestLayout();
192 }
193 });
194 }
195 }
196 synchronized (this) {
197 if (renderThreadHandler == null) {
198 Log.d(TAG, "Dropping frame - SurfaceViewRenderer not initialized or alre ady released.");
199 return;
200 }
201 if (pendingFrame != null) {
202 synchronized (statisticsLock) {
203 ++framesDropped;
204 }
205 Log.d(TAG, "Dropping frame - previous frame has not been rendered yet.") ;
206 return;
207 }
208 pendingFrame = frame.shallowCopy();
209 renderThreadHandler.post(new Runnable() {
210 @Override public void run() {
211 renderFrameOnRenderThread();
212 }
213 });
214 }
215 }
216
217 @Override
218 public boolean canApplyRotation() {
219 return true;
220 }
221
222 // View layout interface.
223 @Override
224 protected void onMeasure(int widthSpec, int heightSpec) {
225 final int maxWidth = getDefaultSize(Integer.MAX_VALUE, widthSpec);
226 final int maxHeight = getDefaultSize(Integer.MAX_VALUE, heightSpec);
227 final Point suggestedSize;
228 synchronized (layoutLock) {
229 suggestedSize = VideoRendererGui.getDisplaySize(
230 VideoRendererGui.convertScalingTypeToVisibleFraction(scalingType),
231 videoAspectRatio, maxWidth, maxHeight);
232 }
233 setMeasuredDimension(
234 MeasureSpec.getMode(widthSpec) == MeasureSpec.EXACTLY ? maxWidth : sugge stedSize.x,
235 MeasureSpec.getMode(heightSpec) == MeasureSpec.EXACTLY ? maxHeight : sug gestedSize.y);
236 }
237
238 @Override
239 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
240 synchronized (layoutLock) {
241 layoutAspectRatio = (float) w / h;
242 }
243 }
244
245 // SurfaceHolder.Callback interface.
246 @Override
247 public void surfaceCreated(final SurfaceHolder holder) {
248 Log.d(TAG, "Surface created");
249 runOnRenderThread(new Runnable() {
250 @Override public void run() {
251 eglBase.createSurface(holder.getSurface());
252 eglBase.makeCurrent();
253 // Might have a pending frame waiting for a surface to be created.
254 renderFrameOnRenderThread();
255 }
256 });
257 }
258
259 @Override
260 public void surfaceDestroyed(SurfaceHolder holder) {
261 Log.d(TAG, "Surface destroyed");
262 runOnRenderThread(new Runnable() {
263 @Override public void run() {
264 eglBase.releaseSurface();
265 }
266 });
267 }
268
269 @Override
270 public void surfaceChanged(SurfaceHolder holder, int format, int width, int he ight) {
271 }
272
273 /**
274 * Private helper function to post tasks safely.
275 */
276 private synchronized void runOnRenderThread(Runnable runnable) {
277 if (renderThreadHandler != null) {
278 renderThreadHandler.post(runnable);
279 }
280 }
281
282 /**
283 * Renders and releases |pendingFrame|.
284 */
285 private void renderFrameOnRenderThread() {
286 if (eglBase == null || !eglBase.hasSurface()) {
287 Log.d(TAG, "No surface to draw on");
288 return;
289 }
290 // Synchronized fetch of |pendingFrame|.
291 final VideoRenderer.I420Frame frame;
292 synchronized (this) {
293 if (pendingFrame == null) {
294 return;
295 }
296 frame = pendingFrame;
297 pendingFrame = null;
298 }
299
300 final long startTimeNs = System.nanoTime();
301 final float[] texMatrix = new float[16];
302 synchronized (layoutLock) {
303 VideoRendererGui.getTextureMatrix(
304 texMatrix, frame.rotationDegree, mirror, videoAspectRatio, layoutAspec tRatio);
305 }
306
307 GLES20.glViewport(0, 0, eglBase.surfaceWidth(), eglBase.surfaceHeight());
308 if (frame.yuvFrame) {
309 // Make sure YUV textures are allocated.
310 if (yuvTextures == null) {
311 yuvTextures = new int[3];
312 // Generate 3 texture ids for Y/U/V and place them into |yuvTextures|.
313 GLES20.glGenTextures(3, yuvTextures, 0);
314 for (int i = 0; i < 3; i++) {
315 GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
316 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]);
317 GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
318 GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
319 GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
320 GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
321 GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
322 GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
323 GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
324 GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
325 }
326 GlUtil.checkNoGLES2Error("y/u/v glGenTextures");
327 }
328
329 // Upload YUV data.
330 for (int i = 0; i < 3; ++i) {
331 GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
332 GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]);
333 int w = (i == 0) ? frame.width : frame.width / 2;
334 int h = (i == 0) ? frame.height : frame.height / 2;
335 GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, w, h, 0,
336 GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, frame.yuvPlanes[i]);
337 }
338
339 drawer.drawYuv(frame.width, frame.height, yuvTextures, texMatrix);
340 } else {
341 SurfaceTexture surfaceTexture = (SurfaceTexture) frame.textureObject;
342 // TODO(magjed): Move updateTexImage() to the video source instead.
343 surfaceTexture.updateTexImage();
344 drawer.drawOes(frame.textureId, texMatrix);
345 }
346
347 eglBase.swapBuffers();
348 frame.release();
349 synchronized (statisticsLock) {
350 if (framesRendered == 0) {
351 firstFrameTimeNs = startTimeNs;
352 }
353 ++framesRendered;
354 renderTimeNs += (System.nanoTime() - startTimeNs);
355 if (framesRendered % 300 == 0) {
356 logStatistics();
357 }
358 }
359 }
360
361 private void logStatistics() {
362 synchronized (statisticsLock) {
363 Log.d(TAG, "ID: " + getResources().getResourceEntryName(getId()) + ". Fram es received: "
364 + framesReceived + ". Dropped: " + framesDropped + ". Rendered: " + fr amesRendered);
365 if (framesReceived > 0 && framesRendered > 0) {
366 final long timeSinceFirstFrameNs = System.nanoTime() - firstFrameTimeNs;
367 Log.d(TAG, "Duration: " + (int) (timeSinceFirstFrameNs / 1e6) +
368 " ms. FPS: " + (float) framesRendered * 1e9 / timeSinceFirstFrameNs) ;
369 Log.d(TAG, "Average render time: "
370 + (int) (renderTimeNs / (1000 * framesRendered)) + " us.");
371 }
372 }
373 }
374 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698