blob: c36952714e9ca4b2b3328ec4a5f6106f99db2a61 [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;
Sami Kalliomäki0d26c992018-10-19 12:53:21 +020020import android.os.Message;
Artem Titarenko69540f42018-12-10 12:30:46 +010021import android.support.annotation.Nullable;
magjeddf494b02016-10-07 05:32:35 -070022import android.view.Surface;
sakalfb0c5732016-11-03 09:15:34 -070023import java.nio.ByteBuffer;
Sami Kalliomäki1659e972018-06-04 14:07:58 +020024import java.text.DecimalFormat;
sakalfb0c5732016-11-03 09:15:34 -070025import java.util.ArrayList;
26import java.util.Iterator;
magjeddf494b02016-10-07 05:32:35 -070027import java.util.concurrent.CountDownLatch;
28import java.util.concurrent.TimeUnit;
29
30/**
Magnus Jedvert431f14e2018-06-09 19:41:58 +020031 * Implements VideoSink by displaying the video stream on an EGL Surface. This class is intended to
32 * be used as a helper class for rendering on SurfaceViews and TextureViews.
magjeddf494b02016-10-07 05:32:35 -070033 */
Magnus Jedvert431f14e2018-06-09 19:41:58 +020034public class EglRenderer implements VideoSink {
magjeddf494b02016-10-07 05:32:35 -070035 private static final String TAG = "EglRenderer";
magjed9ab8a182016-10-20 03:18:09 -070036 private static final long LOG_INTERVAL_SEC = 4;
magjeddf494b02016-10-07 05:32:35 -070037
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
Mirko Bonadei12251b62017-11-05 19:35:31 -080058 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
59 @SuppressWarnings("NoSynchronizedMethodCheck")
magjed9ab8a182016-10-20 03:18:09 -070060 public synchronized void setSurface(Object surface) {
magjeddf494b02016-10-07 05:32:35 -070061 this.surface = surface;
62 }
63
64 @Override
Mirko Bonadei12251b62017-11-05 19:35:31 -080065 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
66 @SuppressWarnings("NoSynchronizedMethodCheck")
magjeddf494b02016-10-07 05:32:35 -070067 public synchronized void run() {
68 if (surface != null && eglBase != null && !eglBase.hasSurface()) {
magjed9ab8a182016-10-20 03:18:09 -070069 if (surface instanceof Surface) {
70 eglBase.createSurface((Surface) surface);
71 } else if (surface instanceof SurfaceTexture) {
72 eglBase.createSurface((SurfaceTexture) surface);
73 } else {
74 throw new IllegalStateException("Invalid surface: " + surface);
75 }
magjeddf494b02016-10-07 05:32:35 -070076 eglBase.makeCurrent();
77 // Necessary for YUV frames with odd width.
78 GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
79 }
80 }
81 }
82
Sami Kalliomäki0d26c992018-10-19 12:53:21 +020083 /**
84 * Handler that triggers a callback when an uncaught exception happens when handling a message.
85 */
86 private static class HandlerWithExceptionCallback extends Handler {
87 private final Runnable exceptionCallback;
88
89 public HandlerWithExceptionCallback(Looper looper, Runnable exceptionCallback) {
90 super(looper);
91 this.exceptionCallback = exceptionCallback;
92 }
93
94 @Override
95 public void dispatchMessage(Message msg) {
96 try {
97 super.dispatchMessage(msg);
98 } catch (Exception e) {
99 Logging.e(TAG, "Exception on EglRenderer thread", e);
100 exceptionCallback.run();
101 throw e;
102 }
103 }
104 }
105
Xiaolei Yu149533a2017-11-03 07:55:01 +0800106 protected final String name;
magjeddf494b02016-10-07 05:32:35 -0700107
108 // |renderThreadHandler| is a handler for communicating with |renderThread|, and is synchronized
109 // on |handlerLock|.
110 private final Object handlerLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100111 @Nullable private Handler renderThreadHandler;
magjeddf494b02016-10-07 05:32:35 -0700112
sakal3a9bc172016-11-30 08:30:05 -0800113 private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>();
sakalfb0c5732016-11-03 09:15:34 -0700114
magjed9ab8a182016-10-20 03:18:09 -0700115 // Variables for fps reduction.
116 private final Object fpsReductionLock = new Object();
117 // Time for when next frame should be rendered.
118 private long nextFrameTimeNs;
119 // Minimum duration between frames when fps reduction is active, or -1 if video is completely
120 // paused.
121 private long minRenderPeriodNs;
122
magjeddf494b02016-10-07 05:32:35 -0700123 // EGL and GL resources for drawing YUV/OES textures. After initilization, these are only accessed
124 // from the render thread.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100125 @Nullable private EglBase eglBase;
magjed7cede372017-09-11 06:12:07 -0700126 private final VideoFrameDrawer frameDrawer = new VideoFrameDrawer();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100127 @Nullable private RendererCommon.GlDrawer drawer;
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100128 private boolean usePresentationTimeStamp;
magjed7cede372017-09-11 06:12:07 -0700129 private final Matrix drawMatrix = new Matrix();
magjeddf494b02016-10-07 05:32:35 -0700130
131 // Pending frame to render. Serves as a queue with size 1. Synchronized on |frameLock|.
132 private final Object frameLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100133 @Nullable private VideoFrame pendingFrame;
magjeddf494b02016-10-07 05:32:35 -0700134
135 // These variables are synchronized on |layoutLock|.
136 private final Object layoutLock = new Object();
magjeddf494b02016-10-07 05:32:35 -0700137 private float layoutAspectRatio;
138 // If true, mirrors the video stream horizontally.
139 private boolean mirror;
140
141 // These variables are synchronized on |statisticsLock|.
142 private final Object statisticsLock = new Object();
143 // Total number of video frames received in renderFrame() call.
144 private int framesReceived;
145 // Number of video frames dropped by renderFrame() because previous frame has not been rendered
146 // yet.
147 private int framesDropped;
148 // Number of rendered video frames.
149 private int framesRendered;
magjed9ab8a182016-10-20 03:18:09 -0700150 // Start time for counting these statistics, or 0 if we haven't started measuring yet.
151 private long statisticsStartTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700152 // Time in ns spent in renderFrameOnRenderThread() function.
153 private long renderTimeNs;
magjed9ab8a182016-10-20 03:18:09 -0700154 // Time in ns spent by the render thread in the swapBuffers() function.
155 private long renderSwapBufferTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700156
sakalfb0c5732016-11-03 09:15:34 -0700157 // Used for bitmap capturing.
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200158 private final GlTextureFrameBuffer bitmapTextureFramebuffer =
159 new GlTextureFrameBuffer(GLES20.GL_RGBA);
sakalfb0c5732016-11-03 09:15:34 -0700160
magjed9ab8a182016-10-20 03:18:09 -0700161 private final Runnable logStatisticsRunnable = new Runnable() {
162 @Override
163 public void run() {
164 logStatistics();
165 synchronized (handlerLock) {
166 if (renderThreadHandler != null) {
167 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
168 renderThreadHandler.postDelayed(
169 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
170 }
171 }
172 }
173 };
174
magjeddf494b02016-10-07 05:32:35 -0700175 private final EglSurfaceCreation eglSurfaceCreationRunnable = new EglSurfaceCreation();
176
177 /**
178 * Standard constructor. The name will be used for the render thread name and included when
179 * logging. In order to render something, you must first call init() and createEglSurface.
180 */
181 public EglRenderer(String name) {
182 this.name = name;
183 }
184
185 /**
186 * Initialize this class, sharing resources with |sharedContext|. The custom |drawer| will be used
187 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
188 * |drawer|. It is allowed to call init() to reinitialize the renderer after a previous
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100189 * init()/release() cycle. If usePresentationTimeStamp is true, eglPresentationTimeANDROID will be
190 * set with the frame timestamps, which specifies desired presentation time and might be useful
191 * for e.g. syncing audio and video.
magjeddf494b02016-10-07 05:32:35 -0700192 */
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100193 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100194 RendererCommon.GlDrawer drawer, boolean usePresentationTimeStamp) {
magjeddf494b02016-10-07 05:32:35 -0700195 synchronized (handlerLock) {
196 if (renderThreadHandler != null) {
197 throw new IllegalStateException(name + "Already initialized");
198 }
199 logD("Initializing EglRenderer");
200 this.drawer = drawer;
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100201 this.usePresentationTimeStamp = usePresentationTimeStamp;
magjeddf494b02016-10-07 05:32:35 -0700202
203 final HandlerThread renderThread = new HandlerThread(name + "EglRenderer");
204 renderThread.start();
Sami Kalliomäki0d26c992018-10-19 12:53:21 +0200205 renderThreadHandler =
206 new HandlerWithExceptionCallback(renderThread.getLooper(), new Runnable() {
207 @Override
208 public void run() {
209 synchronized (handlerLock) {
210 renderThreadHandler = null;
211 }
212 }
213 });
magjeddf494b02016-10-07 05:32:35 -0700214 // Create EGL context on the newly created render thread. It should be possibly to create the
215 // context on this thread and make it current on the render thread, but this causes failure on
216 // some Marvel based JB devices. https://bugs.chromium.org/p/webrtc/issues/detail?id=6350.
sakalbf080602017-08-11 01:42:43 -0700217 ThreadUtils.invokeAtFrontUninterruptibly(renderThreadHandler, () -> {
218 // If sharedContext is null, then texture frames are disabled. This is typically for old
219 // devices that might not be fully spec compliant, so force EGL 1.0 since EGL 1.4 has
220 // caused trouble on some weird devices.
221 if (sharedContext == null) {
222 logD("EglBase10.create context");
223 eglBase = EglBase.createEgl10(configAttributes);
224 } else {
225 logD("EglBase.create shared context");
226 eglBase = EglBase.create(sharedContext, configAttributes);
magjeddf494b02016-10-07 05:32:35 -0700227 }
228 });
magjed9ab8a182016-10-20 03:18:09 -0700229 renderThreadHandler.post(eglSurfaceCreationRunnable);
230 final long currentTimeNs = System.nanoTime();
231 resetStatistics(currentTimeNs);
232 renderThreadHandler.postDelayed(
233 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
magjeddf494b02016-10-07 05:32:35 -0700234 }
235 }
236
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100237 /**
238 * Same as above with usePresentationTimeStamp set to false.
239 *
240 * @see #init(EglBase.Context, int[], RendererCommon.GlDrawer, boolean)
241 */
242 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
243 RendererCommon.GlDrawer drawer) {
244 init(sharedContext, configAttributes, drawer, /* usePresentationTimeStamp= */ false);
245 }
246
magjeddf494b02016-10-07 05:32:35 -0700247 public void createEglSurface(Surface surface) {
magjed9ab8a182016-10-20 03:18:09 -0700248 createEglSurfaceInternal(surface);
249 }
250
251 public void createEglSurface(SurfaceTexture surfaceTexture) {
252 createEglSurfaceInternal(surfaceTexture);
253 }
254
255 private void createEglSurfaceInternal(Object surface) {
magjeddf494b02016-10-07 05:32:35 -0700256 eglSurfaceCreationRunnable.setSurface(surface);
magjed9ab8a182016-10-20 03:18:09 -0700257 postToRenderThread(eglSurfaceCreationRunnable);
magjeddf494b02016-10-07 05:32:35 -0700258 }
259
260 /**
261 * Block until any pending frame is returned and all GL resources released, even if an interrupt
262 * occurs. If an interrupt occurs during release(), the interrupt flag will be set. This function
263 * should be called before the Activity is destroyed and the EGLContext is still valid. If you
264 * don't call this function, the GL resources might leak.
265 */
266 public void release() {
magjed9ab8a182016-10-20 03:18:09 -0700267 logD("Releasing.");
magjeddf494b02016-10-07 05:32:35 -0700268 final CountDownLatch eglCleanupBarrier = new CountDownLatch(1);
269 synchronized (handlerLock) {
270 if (renderThreadHandler == null) {
271 logD("Already released");
272 return;
273 }
magjed9ab8a182016-10-20 03:18:09 -0700274 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
magjeddf494b02016-10-07 05:32:35 -0700275 // Release EGL and GL resources on render thread.
sakalbf080602017-08-11 01:42:43 -0700276 renderThreadHandler.postAtFrontOfQueue(() -> {
Magnus Jedvert94c0f262018-12-12 17:35:28 +0100277 // Detach current shader program.
278 GLES20.glUseProgram(/* program= */ 0);
sakalbf080602017-08-11 01:42:43 -0700279 if (drawer != null) {
280 drawer.release();
281 drawer = null;
magjeddf494b02016-10-07 05:32:35 -0700282 }
magjed7cede372017-09-11 06:12:07 -0700283 frameDrawer.release();
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200284 bitmapTextureFramebuffer.release();
sakalbf080602017-08-11 01:42:43 -0700285 if (eglBase != null) {
286 logD("eglBase detach and release.");
287 eglBase.detachCurrent();
288 eglBase.release();
289 eglBase = null;
290 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100291 frameListeners.clear();
sakalbf080602017-08-11 01:42:43 -0700292 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 05:32:35 -0700293 });
294 final Looper renderLooper = renderThreadHandler.getLooper();
295 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 01:42:43 -0700296 renderThreadHandler.post(() -> {
297 logD("Quitting render thread.");
298 renderLooper.quit();
magjeddf494b02016-10-07 05:32:35 -0700299 });
300 // Don't accept any more frames or messages to the render thread.
301 renderThreadHandler = null;
302 }
303 // Make sure the EGL/GL cleanup posted above is executed.
304 ThreadUtils.awaitUninterruptibly(eglCleanupBarrier);
305 synchronized (frameLock) {
306 if (pendingFrame != null) {
sakal6bdcefc2017-08-15 01:56:02 -0700307 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700308 pendingFrame = null;
309 }
310 }
magjeddf494b02016-10-07 05:32:35 -0700311 logD("Releasing done.");
312 }
313
314 /**
magjed9ab8a182016-10-20 03:18:09 -0700315 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 05:32:35 -0700316 */
magjed9ab8a182016-10-20 03:18:09 -0700317 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 05:32:35 -0700318 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700319 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700320 framesReceived = 0;
321 framesDropped = 0;
322 framesRendered = 0;
magjeddf494b02016-10-07 05:32:35 -0700323 renderTimeNs = 0;
magjed9ab8a182016-10-20 03:18:09 -0700324 renderSwapBufferTimeNs = 0;
325 }
326 }
327
328 public void printStackTrace() {
329 synchronized (handlerLock) {
330 final Thread renderThread =
331 (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread();
332 if (renderThread != null) {
333 final StackTraceElement[] renderStackTrace = renderThread.getStackTrace();
334 if (renderStackTrace.length > 0) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100335 logW("EglRenderer stack trace:");
magjed9ab8a182016-10-20 03:18:09 -0700336 for (StackTraceElement traceElem : renderStackTrace) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100337 logW(traceElem.toString());
magjed9ab8a182016-10-20 03:18:09 -0700338 }
339 }
340 }
magjeddf494b02016-10-07 05:32:35 -0700341 }
342 }
343
344 /**
345 * Set if the video stream should be mirrored or not.
346 */
347 public void setMirror(final boolean mirror) {
348 logD("setMirror: " + mirror);
349 synchronized (layoutLock) {
350 this.mirror = mirror;
351 }
352 }
353
354 /**
355 * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video.
356 * Set this to 0 to disable cropping.
357 */
358 public void setLayoutAspectRatio(float layoutAspectRatio) {
359 logD("setLayoutAspectRatio: " + layoutAspectRatio);
360 synchronized (layoutLock) {
361 this.layoutAspectRatio = layoutAspectRatio;
362 }
363 }
364
magjed9ab8a182016-10-20 03:18:09 -0700365 /**
366 * Limit render framerate.
367 *
368 * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps
369 * reduction.
370 */
371 public void setFpsReduction(float fps) {
372 logD("setFpsReduction: " + fps);
373 synchronized (fpsReductionLock) {
374 final long previousRenderPeriodNs = minRenderPeriodNs;
375 if (fps <= 0) {
376 minRenderPeriodNs = Long.MAX_VALUE;
377 } else {
378 minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps);
379 }
380 if (minRenderPeriodNs != previousRenderPeriodNs) {
381 // Fps reduction changed - reset frame time.
382 nextFrameTimeNs = System.nanoTime();
383 }
384 }
385 }
386
387 public void disableFpsReduction() {
388 setFpsReduction(Float.POSITIVE_INFINITY /* fps */);
389 }
390
391 public void pauseVideo() {
392 setFpsReduction(0 /* fps */);
393 }
394
sakalfb0c5732016-11-03 09:15:34 -0700395 /**
sakal3a9bc172016-11-30 08:30:05 -0800396 * Register a callback to be invoked when a new video frame has been received. This version uses
397 * the drawer of the EglRenderer that was passed in init.
sakalfb0c5732016-11-03 09:15:34 -0700398 *
sakald1516522017-03-13 05:11:48 -0700399 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
400 * It should be lightweight and must not call removeFrameListener.
sakalfb0c5732016-11-03 09:15:34 -0700401 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
402 * required.
403 */
sakalbb584352016-11-28 08:53:44 -0800404 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 02:43:10 -0700405 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 08:30:05 -0800406 }
407
408 /**
409 * Register a callback to be invoked when a new video frame has been received.
410 *
sakald1516522017-03-13 05:11:48 -0700411 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
412 * It should be lightweight and must not call removeFrameListener.
sakal3a9bc172016-11-30 08:30:05 -0800413 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
414 * required.
sakald1516522017-03-13 05:11:48 -0700415 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 08:30:05 -0800416 */
417 public void addFrameListener(
sakald1516522017-03-13 05:11:48 -0700418 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 02:43:10 -0700419 addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */);
420 }
421
422 /**
423 * Register a callback to be invoked when a new video frame has been received.
424 *
425 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
426 * It should be lightweight and must not call removeFrameListener.
427 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
428 * required.
429 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
430 * @param applyFpsReduction This callback will not be called for frames that have been dropped by
431 * FPS reduction.
432 */
433 public void addFrameListener(final FrameListener listener, final float scale,
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100434 @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 01:42:43 -0700435 postToRenderThread(() -> {
436 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
437 frameListeners.add(
438 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 08:53:44 -0800439 });
sakalfb0c5732016-11-03 09:15:34 -0700440 }
441
442 /**
443 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 08:53:44 -0800444 * the queue, nothing happens. It is ensured that callback won't be called after this method
445 * returns.
sakalfb0c5732016-11-03 09:15:34 -0700446 *
447 * @param runnable The callback to remove.
448 */
sakalbb584352016-11-28 08:53:44 -0800449 public void removeFrameListener(final FrameListener listener) {
450 final CountDownLatch latch = new CountDownLatch(1);
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100451 synchronized (handlerLock) {
452 if (renderThreadHandler == null) {
453 return;
sakalfb0c5732016-11-03 09:15:34 -0700454 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100455 if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) {
456 throw new RuntimeException("removeFrameListener must not be called on the render thread.");
457 }
458 postToRenderThread(() -> {
459 latch.countDown();
460 final Iterator<FrameListenerAndParams> iter = frameListeners.iterator();
461 while (iter.hasNext()) {
462 if (iter.next().listener == listener) {
463 iter.remove();
464 }
465 }
466 });
467 }
sakalbb584352016-11-28 08:53:44 -0800468 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 09:15:34 -0700469 }
470
sakal6bdcefc2017-08-15 01:56:02 -0700471 // VideoSink interface.
472 @Override
473 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 05:32:35 -0700474 synchronized (statisticsLock) {
475 ++framesReceived;
476 }
magjed9ab8a182016-10-20 03:18:09 -0700477 final boolean dropOldFrame;
magjeddf494b02016-10-07 05:32:35 -0700478 synchronized (handlerLock) {
479 if (renderThreadHandler == null) {
480 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 05:32:35 -0700481 return;
482 }
magjed9ab8a182016-10-20 03:18:09 -0700483 synchronized (frameLock) {
484 dropOldFrame = (pendingFrame != null);
485 if (dropOldFrame) {
sakal6bdcefc2017-08-15 01:56:02 -0700486 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700487 }
488 pendingFrame = frame;
sakal6bdcefc2017-08-15 01:56:02 -0700489 pendingFrame.retain();
sakalbf080602017-08-11 01:42:43 -0700490 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 05:32:35 -0700491 }
492 }
magjed9ab8a182016-10-20 03:18:09 -0700493 if (dropOldFrame) {
494 synchronized (statisticsLock) {
495 ++framesDropped;
496 }
497 }
magjeddf494b02016-10-07 05:32:35 -0700498 }
499
500 /**
501 * Release EGL surface. This function will block until the EGL surface is released.
502 */
sakal28ec6bd2016-11-09 01:47:12 -0800503 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 05:32:35 -0700504 // Ensure that the render thread is no longer touching the Surface before returning from this
505 // function.
506 eglSurfaceCreationRunnable.setSurface(null /* surface */);
507 synchronized (handlerLock) {
508 if (renderThreadHandler != null) {
509 renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable);
sakalbf080602017-08-11 01:42:43 -0700510 renderThreadHandler.postAtFrontOfQueue(() -> {
511 if (eglBase != null) {
512 eglBase.detachCurrent();
513 eglBase.releaseSurface();
magjeddf494b02016-10-07 05:32:35 -0700514 }
sakalbf080602017-08-11 01:42:43 -0700515 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700516 });
sakal28ec6bd2016-11-09 01:47:12 -0800517 return;
magjeddf494b02016-10-07 05:32:35 -0700518 }
519 }
sakal28ec6bd2016-11-09 01:47:12 -0800520 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700521 }
522
523 /**
magjeddf494b02016-10-07 05:32:35 -0700524 * Private helper function to post tasks safely.
525 */
magjed9ab8a182016-10-20 03:18:09 -0700526 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 05:32:35 -0700527 synchronized (handlerLock) {
528 if (renderThreadHandler != null) {
529 renderThreadHandler.post(runnable);
530 }
531 }
532 }
533
sakalf25a2202017-05-04 06:06:56 -0700534 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 05:32:35 -0700535 if (eglBase != null && eglBase.hasSurface()) {
536 logD("clearSurface");
sakalf25a2202017-05-04 06:06:56 -0700537 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 05:32:35 -0700538 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
539 eglBase.swapBuffers();
540 }
541 }
542
543 /**
sakalf25a2202017-05-04 06:06:56 -0700544 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 03:18:09 -0700545 */
546 public void clearImage() {
sakalf25a2202017-05-04 06:06:56 -0700547 clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
548 }
549
550 /**
551 * Post a task to clear the surface to a specific color.
552 */
553 public void clearImage(final float r, final float g, final float b, final float a) {
magjed9ab8a182016-10-20 03:18:09 -0700554 synchronized (handlerLock) {
555 if (renderThreadHandler == null) {
556 return;
557 }
sakalbf080602017-08-11 01:42:43 -0700558 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 03:18:09 -0700559 }
560 }
561
562 /**
magjeddf494b02016-10-07 05:32:35 -0700563 * Renders and releases |pendingFrame|.
564 */
565 private void renderFrameOnRenderThread() {
566 // Fetch and render |pendingFrame|.
sakal6bdcefc2017-08-15 01:56:02 -0700567 final VideoFrame frame;
magjeddf494b02016-10-07 05:32:35 -0700568 synchronized (frameLock) {
569 if (pendingFrame == null) {
570 return;
571 }
572 frame = pendingFrame;
573 pendingFrame = null;
574 }
575 if (eglBase == null || !eglBase.hasSurface()) {
576 logD("Dropping frame - No surface");
sakal6bdcefc2017-08-15 01:56:02 -0700577 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700578 return;
579 }
sakald1516522017-03-13 05:11:48 -0700580 // Check if fps reduction is active.
581 final boolean shouldRenderFrame;
582 synchronized (fpsReductionLock) {
583 if (minRenderPeriodNs == Long.MAX_VALUE) {
584 // Rendering is paused.
585 shouldRenderFrame = false;
586 } else if (minRenderPeriodNs <= 0) {
587 // FPS reduction is disabled.
588 shouldRenderFrame = true;
589 } else {
590 final long currentTimeNs = System.nanoTime();
591 if (currentTimeNs < nextFrameTimeNs) {
592 logD("Skipping frame rendering - fps reduction is active.");
593 shouldRenderFrame = false;
594 } else {
595 nextFrameTimeNs += minRenderPeriodNs;
596 // The time for the next frame should always be in the future.
597 nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs);
598 shouldRenderFrame = true;
599 }
600 }
601 }
magjeddf494b02016-10-07 05:32:35 -0700602
603 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700604
sakal6bdcefc2017-08-15 01:56:02 -0700605 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
606 final float drawnAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700607 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 01:56:02 -0700608 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700609 }
610
sakal6bdcefc2017-08-15 01:56:02 -0700611 final float scaleX;
612 final float scaleY;
613
614 if (frameAspectRatio > drawnAspectRatio) {
615 scaleX = drawnAspectRatio / frameAspectRatio;
616 scaleY = 1f;
617 } else {
618 scaleX = 1f;
619 scaleY = frameAspectRatio / drawnAspectRatio;
620 }
621
magjed7cede372017-09-11 06:12:07 -0700622 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700623 drawMatrix.preTranslate(0.5f, 0.5f);
sakal6bdcefc2017-08-15 01:56:02 -0700624 if (mirror)
625 drawMatrix.preScale(-1f, 1f);
626 drawMatrix.preScale(scaleX, scaleY);
627 drawMatrix.preTranslate(-0.5f, -0.5f);
628
sakald1516522017-03-13 05:11:48 -0700629 if (shouldRenderFrame) {
630 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
631 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700632 frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */,
633 eglBase.surfaceWidth(), eglBase.surfaceHeight());
sakald1516522017-03-13 05:11:48 -0700634
635 final long swapBuffersStartTimeNs = System.nanoTime();
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100636 if (usePresentationTimeStamp) {
637 eglBase.swapBuffers(frame.getTimestampNs());
638 } else {
639 eglBase.swapBuffers();
640 }
sakald1516522017-03-13 05:11:48 -0700641
642 final long currentTimeNs = System.nanoTime();
643 synchronized (statisticsLock) {
644 ++framesRendered;
645 renderTimeNs += (currentTimeNs - startTimeNs);
646 renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs);
647 }
magjeddf494b02016-10-07 05:32:35 -0700648 }
649
magjed7cede372017-09-11 06:12:07 -0700650 notifyCallbacks(frame, shouldRenderFrame);
651 frame.release();
sakalfb0c5732016-11-03 09:15:34 -0700652 }
653
magjed7cede372017-09-11 06:12:07 -0700654 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 08:53:44 -0800655 if (frameListeners.isEmpty())
656 return;
sakalfb0c5732016-11-03 09:15:34 -0700657
magjed7cede372017-09-11 06:12:07 -0700658 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700659 drawMatrix.preTranslate(0.5f, 0.5f);
sakal6bdcefc2017-08-15 01:56:02 -0700660 if (mirror)
661 drawMatrix.preScale(-1f, 1f);
662 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
663 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 09:15:34 -0700664
sakal8fdf9572017-05-31 02:43:10 -0700665 Iterator<FrameListenerAndParams> it = frameListeners.iterator();
666 while (it.hasNext()) {
667 FrameListenerAndParams listenerAndParams = it.next();
668 if (!wasRendered && listenerAndParams.applyFpsReduction) {
669 continue;
670 }
671 it.remove();
672
sakal6bdcefc2017-08-15 01:56:02 -0700673 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
674 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 09:15:34 -0700675
676 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 08:30:05 -0800677 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 09:15:34 -0700678 continue;
679 }
680
sakalfb0c5732016-11-03 09:15:34 -0700681 bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);
682
683 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
684 GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
685 GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);
686
sakal103988d2017-02-17 09:59:01 -0800687 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
688 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700689 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
690 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 09:15:34 -0700691
692 final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
693 GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
694 GLES20.glReadPixels(
695 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);
696
697 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
698 GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");
699
700 final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
701 bitmap.copyPixelsFromBuffer(bitmapBuffer);
sakal3a9bc172016-11-30 08:30:05 -0800702 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 09:15:34 -0700703 }
magjeddf494b02016-10-07 05:32:35 -0700704 }
705
magjed9ab8a182016-10-20 03:18:09 -0700706 private String averageTimeAsString(long sumTimeNs, int count) {
Magnus Jedvert3bc696f2018-11-12 11:35:20 +0100707 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " us";
magjed9ab8a182016-10-20 03:18:09 -0700708 }
709
magjeddf494b02016-10-07 05:32:35 -0700710 private void logStatistics() {
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200711 final DecimalFormat fpsFormat = new DecimalFormat("#.0");
magjed9ab8a182016-10-20 03:18:09 -0700712 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700713 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700714 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
715 if (elapsedTimeNs <= 0) {
716 return;
magjeddf494b02016-10-07 05:32:35 -0700717 }
magjed9ab8a182016-10-20 03:18:09 -0700718 final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs;
719 logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms."
720 + " Frames received: " + framesReceived + "."
721 + " Dropped: " + framesDropped + "."
722 + " Rendered: " + framesRendered + "."
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200723 + " Render fps: " + fpsFormat.format(renderFps) + "."
magjed9ab8a182016-10-20 03:18:09 -0700724 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
725 + " Average swapBuffer time: "
726 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
727 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 05:32:35 -0700728 }
729 }
730
731 private void logD(String string) {
732 Logging.d(TAG, name + string);
733 }
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100734
735 private void logW(String string) {
736 Logging.w(TAG, name + string);
737 }
magjeddf494b02016-10-07 05:32:35 -0700738}