blob: 16e89f4d21394dd543d6b9433852779b10f9e1f9 [file] [log] [blame]
magjeddf494b02016-10-07 05:32:35 -07001/*
2 * Copyright 2016 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
sakalfb0c5732016-11-03 09:15:34 -070013import android.graphics.Bitmap;
sakal6bdcefc2017-08-15 01:56:02 -070014import android.graphics.Matrix;
magjed9ab8a182016-10-20 03:18:09 -070015import android.graphics.SurfaceTexture;
magjeddf494b02016-10-07 05:32:35 -070016import android.opengl.GLES20;
17import android.os.Handler;
18import android.os.HandlerThread;
19import android.os.Looper;
20import android.view.Surface;
sakalfb0c5732016-11-03 09:15:34 -070021import java.nio.ByteBuffer;
22import java.util.ArrayList;
23import java.util.Iterator;
sakal037b93a2017-01-16 04:57:32 -080024import java.util.Locale;
magjeddf494b02016-10-07 05:32:35 -070025import java.util.concurrent.CountDownLatch;
26import java.util.concurrent.TimeUnit;
27
28/**
29 * Implements org.webrtc.VideoRenderer.Callbacks by displaying the video stream on an EGL Surface.
30 * This class is intended to be used as a helper class for rendering on SurfaceViews and
31 * TextureViews.
32 */
sakal6bdcefc2017-08-15 01:56:02 -070033public class EglRenderer implements VideoRenderer.Callbacks, VideoSink {
magjeddf494b02016-10-07 05:32:35 -070034 private static final String TAG = "EglRenderer";
magjed9ab8a182016-10-20 03:18:09 -070035 private static final long LOG_INTERVAL_SEC = 4;
magjeddf494b02016-10-07 05:32:35 -070036 private static final int MAX_SURFACE_CLEAR_COUNT = 3;
37
sakalfb0c5732016-11-03 09:15:34 -070038 public interface FrameListener { void onFrame(Bitmap frame); }
39
sakal3a9bc172016-11-30 08:30:05 -080040 private static class FrameListenerAndParams {
sakalfb0c5732016-11-03 09:15:34 -070041 public final FrameListener listener;
sakal3a9bc172016-11-30 08:30:05 -080042 public final float scale;
43 public final RendererCommon.GlDrawer drawer;
sakal8fdf9572017-05-31 02:43:10 -070044 public final boolean applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070045
sakal8fdf9572017-05-31 02:43:10 -070046 public FrameListenerAndParams(FrameListener listener, float scale,
47 RendererCommon.GlDrawer drawer, boolean applyFpsReduction) {
sakalfb0c5732016-11-03 09:15:34 -070048 this.listener = listener;
sakal3a9bc172016-11-30 08:30:05 -080049 this.scale = scale;
50 this.drawer = drawer;
sakal8fdf9572017-05-31 02:43:10 -070051 this.applyFpsReduction = applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070052 }
53 }
54
magjeddf494b02016-10-07 05:32:35 -070055 private class EglSurfaceCreation implements Runnable {
magjed9ab8a182016-10-20 03:18:09 -070056 private Object surface;
magjeddf494b02016-10-07 05:32:35 -070057
magjed9ab8a182016-10-20 03:18:09 -070058 public synchronized void setSurface(Object surface) {
magjeddf494b02016-10-07 05:32:35 -070059 this.surface = surface;
60 }
61
62 @Override
63 public synchronized void run() {
64 if (surface != null && eglBase != null && !eglBase.hasSurface()) {
magjed9ab8a182016-10-20 03:18:09 -070065 if (surface instanceof Surface) {
66 eglBase.createSurface((Surface) surface);
67 } else if (surface instanceof SurfaceTexture) {
68 eglBase.createSurface((SurfaceTexture) surface);
69 } else {
70 throw new IllegalStateException("Invalid surface: " + surface);
71 }
magjeddf494b02016-10-07 05:32:35 -070072 eglBase.makeCurrent();
73 // Necessary for YUV frames with odd width.
74 GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
75 }
76 }
77 }
78
79 private final String name;
80
81 // |renderThreadHandler| is a handler for communicating with |renderThread|, and is synchronized
82 // on |handlerLock|.
83 private final Object handlerLock = new Object();
84 private Handler renderThreadHandler;
85
sakal3a9bc172016-11-30 08:30:05 -080086 private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>();
sakalfb0c5732016-11-03 09:15:34 -070087
magjed9ab8a182016-10-20 03:18:09 -070088 // Variables for fps reduction.
89 private final Object fpsReductionLock = new Object();
90 // Time for when next frame should be rendered.
91 private long nextFrameTimeNs;
92 // Minimum duration between frames when fps reduction is active, or -1 if video is completely
93 // paused.
94 private long minRenderPeriodNs;
95
magjeddf494b02016-10-07 05:32:35 -070096 // EGL and GL resources for drawing YUV/OES textures. After initilization, these are only accessed
97 // from the render thread.
98 private EglBase eglBase;
magjed7cede372017-09-11 06:12:07 -070099 private final VideoFrameDrawer frameDrawer = new VideoFrameDrawer();
magjeddf494b02016-10-07 05:32:35 -0700100 private RendererCommon.GlDrawer drawer;
magjed7cede372017-09-11 06:12:07 -0700101 private final Matrix drawMatrix = new Matrix();
magjeddf494b02016-10-07 05:32:35 -0700102
103 // Pending frame to render. Serves as a queue with size 1. Synchronized on |frameLock|.
104 private final Object frameLock = new Object();
sakal6bdcefc2017-08-15 01:56:02 -0700105 private VideoFrame pendingFrame;
magjeddf494b02016-10-07 05:32:35 -0700106
107 // These variables are synchronized on |layoutLock|.
108 private final Object layoutLock = new Object();
magjeddf494b02016-10-07 05:32:35 -0700109 private float layoutAspectRatio;
110 // If true, mirrors the video stream horizontally.
111 private boolean mirror;
112
113 // These variables are synchronized on |statisticsLock|.
114 private final Object statisticsLock = new Object();
115 // Total number of video frames received in renderFrame() call.
116 private int framesReceived;
117 // Number of video frames dropped by renderFrame() because previous frame has not been rendered
118 // yet.
119 private int framesDropped;
120 // Number of rendered video frames.
121 private int framesRendered;
magjed9ab8a182016-10-20 03:18:09 -0700122 // Start time for counting these statistics, or 0 if we haven't started measuring yet.
123 private long statisticsStartTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700124 // Time in ns spent in renderFrameOnRenderThread() function.
125 private long renderTimeNs;
magjed9ab8a182016-10-20 03:18:09 -0700126 // Time in ns spent by the render thread in the swapBuffers() function.
127 private long renderSwapBufferTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700128
sakalfb0c5732016-11-03 09:15:34 -0700129 // Used for bitmap capturing.
130 private GlTextureFrameBuffer bitmapTextureFramebuffer;
131
magjed9ab8a182016-10-20 03:18:09 -0700132 private final Runnable logStatisticsRunnable = new Runnable() {
133 @Override
134 public void run() {
135 logStatistics();
136 synchronized (handlerLock) {
137 if (renderThreadHandler != null) {
138 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
139 renderThreadHandler.postDelayed(
140 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
141 }
142 }
143 }
144 };
145
magjeddf494b02016-10-07 05:32:35 -0700146 private final EglSurfaceCreation eglSurfaceCreationRunnable = new EglSurfaceCreation();
147
148 /**
149 * Standard constructor. The name will be used for the render thread name and included when
150 * logging. In order to render something, you must first call init() and createEglSurface.
151 */
152 public EglRenderer(String name) {
153 this.name = name;
154 }
155
156 /**
157 * Initialize this class, sharing resources with |sharedContext|. The custom |drawer| will be used
158 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
159 * |drawer|. It is allowed to call init() to reinitialize the renderer after a previous
160 * init()/release() cycle.
161 */
162 public void init(final EglBase.Context sharedContext, final int[] configAttributes,
163 RendererCommon.GlDrawer drawer) {
164 synchronized (handlerLock) {
165 if (renderThreadHandler != null) {
166 throw new IllegalStateException(name + "Already initialized");
167 }
168 logD("Initializing EglRenderer");
169 this.drawer = drawer;
170
171 final HandlerThread renderThread = new HandlerThread(name + "EglRenderer");
172 renderThread.start();
173 renderThreadHandler = new Handler(renderThread.getLooper());
174 // Create EGL context on the newly created render thread. It should be possibly to create the
175 // context on this thread and make it current on the render thread, but this causes failure on
176 // some Marvel based JB devices. https://bugs.chromium.org/p/webrtc/issues/detail?id=6350.
sakalbf080602017-08-11 01:42:43 -0700177 ThreadUtils.invokeAtFrontUninterruptibly(renderThreadHandler, () -> {
178 // If sharedContext is null, then texture frames are disabled. This is typically for old
179 // devices that might not be fully spec compliant, so force EGL 1.0 since EGL 1.4 has
180 // caused trouble on some weird devices.
181 if (sharedContext == null) {
182 logD("EglBase10.create context");
183 eglBase = EglBase.createEgl10(configAttributes);
184 } else {
185 logD("EglBase.create shared context");
186 eglBase = EglBase.create(sharedContext, configAttributes);
magjeddf494b02016-10-07 05:32:35 -0700187 }
188 });
magjed9ab8a182016-10-20 03:18:09 -0700189 renderThreadHandler.post(eglSurfaceCreationRunnable);
190 final long currentTimeNs = System.nanoTime();
191 resetStatistics(currentTimeNs);
192 renderThreadHandler.postDelayed(
193 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
magjeddf494b02016-10-07 05:32:35 -0700194 }
195 }
196
197 public void createEglSurface(Surface surface) {
magjed9ab8a182016-10-20 03:18:09 -0700198 createEglSurfaceInternal(surface);
199 }
200
201 public void createEglSurface(SurfaceTexture surfaceTexture) {
202 createEglSurfaceInternal(surfaceTexture);
203 }
204
205 private void createEglSurfaceInternal(Object surface) {
magjeddf494b02016-10-07 05:32:35 -0700206 eglSurfaceCreationRunnable.setSurface(surface);
magjed9ab8a182016-10-20 03:18:09 -0700207 postToRenderThread(eglSurfaceCreationRunnable);
magjeddf494b02016-10-07 05:32:35 -0700208 }
209
210 /**
211 * Block until any pending frame is returned and all GL resources released, even if an interrupt
212 * occurs. If an interrupt occurs during release(), the interrupt flag will be set. This function
213 * should be called before the Activity is destroyed and the EGLContext is still valid. If you
214 * don't call this function, the GL resources might leak.
215 */
216 public void release() {
magjed9ab8a182016-10-20 03:18:09 -0700217 logD("Releasing.");
magjeddf494b02016-10-07 05:32:35 -0700218 final CountDownLatch eglCleanupBarrier = new CountDownLatch(1);
219 synchronized (handlerLock) {
220 if (renderThreadHandler == null) {
221 logD("Already released");
222 return;
223 }
magjed9ab8a182016-10-20 03:18:09 -0700224 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
magjeddf494b02016-10-07 05:32:35 -0700225 // Release EGL and GL resources on render thread.
sakalbf080602017-08-11 01:42:43 -0700226 renderThreadHandler.postAtFrontOfQueue(() -> {
227 if (drawer != null) {
228 drawer.release();
229 drawer = null;
magjeddf494b02016-10-07 05:32:35 -0700230 }
magjed7cede372017-09-11 06:12:07 -0700231 frameDrawer.release();
sakalbf080602017-08-11 01:42:43 -0700232 if (bitmapTextureFramebuffer != null) {
233 bitmapTextureFramebuffer.release();
234 bitmapTextureFramebuffer = null;
235 }
236 if (eglBase != null) {
237 logD("eglBase detach and release.");
238 eglBase.detachCurrent();
239 eglBase.release();
240 eglBase = null;
241 }
242 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 05:32:35 -0700243 });
244 final Looper renderLooper = renderThreadHandler.getLooper();
245 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 01:42:43 -0700246 renderThreadHandler.post(() -> {
247 logD("Quitting render thread.");
248 renderLooper.quit();
magjeddf494b02016-10-07 05:32:35 -0700249 });
250 // Don't accept any more frames or messages to the render thread.
251 renderThreadHandler = null;
252 }
253 // Make sure the EGL/GL cleanup posted above is executed.
254 ThreadUtils.awaitUninterruptibly(eglCleanupBarrier);
255 synchronized (frameLock) {
256 if (pendingFrame != null) {
sakal6bdcefc2017-08-15 01:56:02 -0700257 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700258 pendingFrame = null;
259 }
260 }
magjeddf494b02016-10-07 05:32:35 -0700261 logD("Releasing done.");
262 }
263
264 /**
magjed9ab8a182016-10-20 03:18:09 -0700265 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 05:32:35 -0700266 */
magjed9ab8a182016-10-20 03:18:09 -0700267 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 05:32:35 -0700268 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700269 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700270 framesReceived = 0;
271 framesDropped = 0;
272 framesRendered = 0;
magjeddf494b02016-10-07 05:32:35 -0700273 renderTimeNs = 0;
magjed9ab8a182016-10-20 03:18:09 -0700274 renderSwapBufferTimeNs = 0;
275 }
276 }
277
278 public void printStackTrace() {
279 synchronized (handlerLock) {
280 final Thread renderThread =
281 (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread();
282 if (renderThread != null) {
283 final StackTraceElement[] renderStackTrace = renderThread.getStackTrace();
284 if (renderStackTrace.length > 0) {
285 logD("EglRenderer stack trace:");
286 for (StackTraceElement traceElem : renderStackTrace) {
287 logD(traceElem.toString());
288 }
289 }
290 }
magjeddf494b02016-10-07 05:32:35 -0700291 }
292 }
293
294 /**
295 * Set if the video stream should be mirrored or not.
296 */
297 public void setMirror(final boolean mirror) {
298 logD("setMirror: " + mirror);
299 synchronized (layoutLock) {
300 this.mirror = mirror;
301 }
302 }
303
304 /**
305 * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video.
306 * Set this to 0 to disable cropping.
307 */
308 public void setLayoutAspectRatio(float layoutAspectRatio) {
309 logD("setLayoutAspectRatio: " + layoutAspectRatio);
310 synchronized (layoutLock) {
311 this.layoutAspectRatio = layoutAspectRatio;
312 }
313 }
314
magjed9ab8a182016-10-20 03:18:09 -0700315 /**
316 * Limit render framerate.
317 *
318 * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps
319 * reduction.
320 */
321 public void setFpsReduction(float fps) {
322 logD("setFpsReduction: " + fps);
323 synchronized (fpsReductionLock) {
324 final long previousRenderPeriodNs = minRenderPeriodNs;
325 if (fps <= 0) {
326 minRenderPeriodNs = Long.MAX_VALUE;
327 } else {
328 minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps);
329 }
330 if (minRenderPeriodNs != previousRenderPeriodNs) {
331 // Fps reduction changed - reset frame time.
332 nextFrameTimeNs = System.nanoTime();
333 }
334 }
335 }
336
337 public void disableFpsReduction() {
338 setFpsReduction(Float.POSITIVE_INFINITY /* fps */);
339 }
340
341 public void pauseVideo() {
342 setFpsReduction(0 /* fps */);
343 }
344
sakalfb0c5732016-11-03 09:15:34 -0700345 /**
sakal3a9bc172016-11-30 08:30:05 -0800346 * Register a callback to be invoked when a new video frame has been received. This version uses
347 * the drawer of the EglRenderer that was passed in init.
sakalfb0c5732016-11-03 09:15:34 -0700348 *
sakald1516522017-03-13 05:11:48 -0700349 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
350 * It should be lightweight and must not call removeFrameListener.
sakalfb0c5732016-11-03 09:15:34 -0700351 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
352 * required.
353 */
sakalbb584352016-11-28 08:53:44 -0800354 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 02:43:10 -0700355 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 08:30:05 -0800356 }
357
358 /**
359 * Register a callback to be invoked when a new video frame has been received.
360 *
sakald1516522017-03-13 05:11:48 -0700361 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
362 * It should be lightweight and must not call removeFrameListener.
sakal3a9bc172016-11-30 08:30:05 -0800363 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
364 * required.
sakald1516522017-03-13 05:11:48 -0700365 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 08:30:05 -0800366 */
367 public void addFrameListener(
sakald1516522017-03-13 05:11:48 -0700368 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 02:43:10 -0700369 addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */);
370 }
371
372 /**
373 * Register a callback to be invoked when a new video frame has been received.
374 *
375 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
376 * It should be lightweight and must not call removeFrameListener.
377 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
378 * required.
379 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
380 * @param applyFpsReduction This callback will not be called for frames that have been dropped by
381 * FPS reduction.
382 */
383 public void addFrameListener(final FrameListener listener, final float scale,
384 final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 01:42:43 -0700385 postToRenderThread(() -> {
386 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
387 frameListeners.add(
388 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 08:53:44 -0800389 });
sakalfb0c5732016-11-03 09:15:34 -0700390 }
391
392 /**
393 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 08:53:44 -0800394 * the queue, nothing happens. It is ensured that callback won't be called after this method
395 * returns.
sakalfb0c5732016-11-03 09:15:34 -0700396 *
397 * @param runnable The callback to remove.
398 */
sakalbb584352016-11-28 08:53:44 -0800399 public void removeFrameListener(final FrameListener listener) {
sakald1516522017-03-13 05:11:48 -0700400 if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) {
401 throw new RuntimeException("removeFrameListener must not be called on the render thread.");
402 }
sakalbb584352016-11-28 08:53:44 -0800403 final CountDownLatch latch = new CountDownLatch(1);
sakalbf080602017-08-11 01:42:43 -0700404 postToRenderThread(() -> {
405 latch.countDown();
406 final Iterator<FrameListenerAndParams> iter = frameListeners.iterator();
407 while (iter.hasNext()) {
408 if (iter.next().listener == listener) {
409 iter.remove();
sakalfb0c5732016-11-03 09:15:34 -0700410 }
411 }
sakalbb584352016-11-28 08:53:44 -0800412 });
413 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 09:15:34 -0700414 }
415
magjeddf494b02016-10-07 05:32:35 -0700416 // VideoRenderer.Callbacks interface.
417 @Override
418 public void renderFrame(VideoRenderer.I420Frame frame) {
sakal6bdcefc2017-08-15 01:56:02 -0700419 VideoFrame videoFrame = frame.toVideoFrame();
420 onFrame(videoFrame);
421 videoFrame.release();
422 }
423
424 // VideoSink interface.
425 @Override
426 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 05:32:35 -0700427 synchronized (statisticsLock) {
428 ++framesReceived;
429 }
magjed9ab8a182016-10-20 03:18:09 -0700430 final boolean dropOldFrame;
magjeddf494b02016-10-07 05:32:35 -0700431 synchronized (handlerLock) {
432 if (renderThreadHandler == null) {
433 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 05:32:35 -0700434 return;
435 }
magjed9ab8a182016-10-20 03:18:09 -0700436 synchronized (frameLock) {
437 dropOldFrame = (pendingFrame != null);
438 if (dropOldFrame) {
sakal6bdcefc2017-08-15 01:56:02 -0700439 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700440 }
441 pendingFrame = frame;
sakal6bdcefc2017-08-15 01:56:02 -0700442 pendingFrame.retain();
sakalbf080602017-08-11 01:42:43 -0700443 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 05:32:35 -0700444 }
445 }
magjed9ab8a182016-10-20 03:18:09 -0700446 if (dropOldFrame) {
447 synchronized (statisticsLock) {
448 ++framesDropped;
449 }
450 }
magjeddf494b02016-10-07 05:32:35 -0700451 }
452
453 /**
454 * Release EGL surface. This function will block until the EGL surface is released.
455 */
sakal28ec6bd2016-11-09 01:47:12 -0800456 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 05:32:35 -0700457 // Ensure that the render thread is no longer touching the Surface before returning from this
458 // function.
459 eglSurfaceCreationRunnable.setSurface(null /* surface */);
460 synchronized (handlerLock) {
461 if (renderThreadHandler != null) {
462 renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable);
sakalbf080602017-08-11 01:42:43 -0700463 renderThreadHandler.postAtFrontOfQueue(() -> {
464 if (eglBase != null) {
465 eglBase.detachCurrent();
466 eglBase.releaseSurface();
magjeddf494b02016-10-07 05:32:35 -0700467 }
sakalbf080602017-08-11 01:42:43 -0700468 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700469 });
sakal28ec6bd2016-11-09 01:47:12 -0800470 return;
magjeddf494b02016-10-07 05:32:35 -0700471 }
472 }
sakal28ec6bd2016-11-09 01:47:12 -0800473 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700474 }
475
476 /**
magjeddf494b02016-10-07 05:32:35 -0700477 * Private helper function to post tasks safely.
478 */
magjed9ab8a182016-10-20 03:18:09 -0700479 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 05:32:35 -0700480 synchronized (handlerLock) {
481 if (renderThreadHandler != null) {
482 renderThreadHandler.post(runnable);
483 }
484 }
485 }
486
sakalf25a2202017-05-04 06:06:56 -0700487 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 05:32:35 -0700488 if (eglBase != null && eglBase.hasSurface()) {
489 logD("clearSurface");
sakalf25a2202017-05-04 06:06:56 -0700490 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 05:32:35 -0700491 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
492 eglBase.swapBuffers();
493 }
494 }
495
496 /**
sakalf25a2202017-05-04 06:06:56 -0700497 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 03:18:09 -0700498 */
499 public void clearImage() {
sakalf25a2202017-05-04 06:06:56 -0700500 clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
501 }
502
503 /**
504 * Post a task to clear the surface to a specific color.
505 */
506 public void clearImage(final float r, final float g, final float b, final float a) {
magjed9ab8a182016-10-20 03:18:09 -0700507 synchronized (handlerLock) {
508 if (renderThreadHandler == null) {
509 return;
510 }
sakalbf080602017-08-11 01:42:43 -0700511 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 03:18:09 -0700512 }
513 }
514
515 /**
magjeddf494b02016-10-07 05:32:35 -0700516 * Renders and releases |pendingFrame|.
517 */
518 private void renderFrameOnRenderThread() {
519 // Fetch and render |pendingFrame|.
sakal6bdcefc2017-08-15 01:56:02 -0700520 final VideoFrame frame;
magjeddf494b02016-10-07 05:32:35 -0700521 synchronized (frameLock) {
522 if (pendingFrame == null) {
523 return;
524 }
525 frame = pendingFrame;
526 pendingFrame = null;
527 }
528 if (eglBase == null || !eglBase.hasSurface()) {
529 logD("Dropping frame - No surface");
sakal6bdcefc2017-08-15 01:56:02 -0700530 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700531 return;
532 }
sakald1516522017-03-13 05:11:48 -0700533 // Check if fps reduction is active.
534 final boolean shouldRenderFrame;
535 synchronized (fpsReductionLock) {
536 if (minRenderPeriodNs == Long.MAX_VALUE) {
537 // Rendering is paused.
538 shouldRenderFrame = false;
539 } else if (minRenderPeriodNs <= 0) {
540 // FPS reduction is disabled.
541 shouldRenderFrame = true;
542 } else {
543 final long currentTimeNs = System.nanoTime();
544 if (currentTimeNs < nextFrameTimeNs) {
545 logD("Skipping frame rendering - fps reduction is active.");
546 shouldRenderFrame = false;
547 } else {
548 nextFrameTimeNs += minRenderPeriodNs;
549 // The time for the next frame should always be in the future.
550 nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs);
551 shouldRenderFrame = true;
552 }
553 }
554 }
magjeddf494b02016-10-07 05:32:35 -0700555
556 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700557
sakal6bdcefc2017-08-15 01:56:02 -0700558 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
559 final float drawnAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700560 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 01:56:02 -0700561 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700562 }
563
sakal6bdcefc2017-08-15 01:56:02 -0700564 final float scaleX;
565 final float scaleY;
566
567 if (frameAspectRatio > drawnAspectRatio) {
568 scaleX = drawnAspectRatio / frameAspectRatio;
569 scaleY = 1f;
570 } else {
571 scaleX = 1f;
572 scaleY = frameAspectRatio / drawnAspectRatio;
573 }
574
magjed7cede372017-09-11 06:12:07 -0700575 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700576 drawMatrix.preTranslate(0.5f, 0.5f);
sakal6bdcefc2017-08-15 01:56:02 -0700577 if (mirror)
578 drawMatrix.preScale(-1f, 1f);
579 drawMatrix.preScale(scaleX, scaleY);
580 drawMatrix.preTranslate(-0.5f, -0.5f);
581
sakald1516522017-03-13 05:11:48 -0700582 if (shouldRenderFrame) {
583 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
584 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700585 frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */,
586 eglBase.surfaceWidth(), eglBase.surfaceHeight());
sakald1516522017-03-13 05:11:48 -0700587
588 final long swapBuffersStartTimeNs = System.nanoTime();
589 eglBase.swapBuffers();
590
591 final long currentTimeNs = System.nanoTime();
592 synchronized (statisticsLock) {
593 ++framesRendered;
594 renderTimeNs += (currentTimeNs - startTimeNs);
595 renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs);
596 }
magjeddf494b02016-10-07 05:32:35 -0700597 }
598
magjed7cede372017-09-11 06:12:07 -0700599 notifyCallbacks(frame, shouldRenderFrame);
600 frame.release();
sakalfb0c5732016-11-03 09:15:34 -0700601 }
602
magjed7cede372017-09-11 06:12:07 -0700603 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 08:53:44 -0800604 if (frameListeners.isEmpty())
605 return;
sakalfb0c5732016-11-03 09:15:34 -0700606
magjed7cede372017-09-11 06:12:07 -0700607 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700608 drawMatrix.preTranslate(0.5f, 0.5f);
sakal6bdcefc2017-08-15 01:56:02 -0700609 if (mirror)
610 drawMatrix.preScale(-1f, 1f);
611 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
612 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 09:15:34 -0700613
sakal8fdf9572017-05-31 02:43:10 -0700614 Iterator<FrameListenerAndParams> it = frameListeners.iterator();
615 while (it.hasNext()) {
616 FrameListenerAndParams listenerAndParams = it.next();
617 if (!wasRendered && listenerAndParams.applyFpsReduction) {
618 continue;
619 }
620 it.remove();
621
sakal6bdcefc2017-08-15 01:56:02 -0700622 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
623 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 09:15:34 -0700624
625 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 08:30:05 -0800626 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 09:15:34 -0700627 continue;
628 }
629
630 if (bitmapTextureFramebuffer == null) {
631 bitmapTextureFramebuffer = new GlTextureFrameBuffer(GLES20.GL_RGBA);
632 }
633 bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);
634
635 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
636 GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
637 GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);
638
sakal103988d2017-02-17 09:59:01 -0800639 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
640 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700641 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
642 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 09:15:34 -0700643
644 final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
645 GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
646 GLES20.glReadPixels(
647 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);
648
649 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
650 GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");
651
652 final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
653 bitmap.copyPixelsFromBuffer(bitmapBuffer);
sakal3a9bc172016-11-30 08:30:05 -0800654 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 09:15:34 -0700655 }
magjeddf494b02016-10-07 05:32:35 -0700656 }
657
magjed9ab8a182016-10-20 03:18:09 -0700658 private String averageTimeAsString(long sumTimeNs, int count) {
659 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " μs";
660 }
661
magjeddf494b02016-10-07 05:32:35 -0700662 private void logStatistics() {
magjed9ab8a182016-10-20 03:18:09 -0700663 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700664 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700665 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
666 if (elapsedTimeNs <= 0) {
667 return;
magjeddf494b02016-10-07 05:32:35 -0700668 }
magjed9ab8a182016-10-20 03:18:09 -0700669 final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs;
670 logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms."
671 + " Frames received: " + framesReceived + "."
672 + " Dropped: " + framesDropped + "."
673 + " Rendered: " + framesRendered + "."
sakal037b93a2017-01-16 04:57:32 -0800674 + " Render fps: " + String.format(Locale.US, "%.1f", renderFps) + "."
magjed9ab8a182016-10-20 03:18:09 -0700675 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
676 + " Average swapBuffer time: "
677 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
678 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 05:32:35 -0700679 }
680 }
681
682 private void logD(String string) {
683 Logging.d(TAG, name + string);
684 }
685}