blob: 5ab0868ef314b90e8ddb31c9c00ebef7cae19126 [file] [log] [blame]
magjeddf494b02016-10-07 12:32:351/*
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 16:15:3413import android.graphics.Bitmap;
sakal6bdcefc2017-08-15 08:56:0214import android.graphics.Matrix;
magjed9ab8a182016-10-20 10:18:0915import android.graphics.SurfaceTexture;
magjeddf494b02016-10-07 12:32:3516import android.opengl.GLES20;
17import android.os.Handler;
18import android.os.HandlerThread;
19import android.os.Looper;
Sami Kalliomäki0d26c992018-10-19 10:53:2120import android.os.Message;
magjeddf494b02016-10-07 12:32:3521import android.view.Surface;
Byoungchan Lee02334e02021-08-14 02:41:5922import androidx.annotation.Nullable;
sakalfb0c5732016-11-03 16:15:3423import java.nio.ByteBuffer;
Sami Kalliomäki1659e972018-06-04 12:07:5824import java.text.DecimalFormat;
sakalfb0c5732016-11-03 16:15:3425import java.util.ArrayList;
26import java.util.Iterator;
magjeddf494b02016-10-07 12:32:3527import java.util.concurrent.CountDownLatch;
28import java.util.concurrent.TimeUnit;
29
30/**
Magnus Jedvert431f14e2018-06-09 17:41:5831 * 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 12:32:3533 */
Magnus Jedvert431f14e2018-06-09 17:41:5834public class EglRenderer implements VideoSink {
magjeddf494b02016-10-07 12:32:3535 private static final String TAG = "EglRenderer";
magjed9ab8a182016-10-20 10:18:0936 private static final long LOG_INTERVAL_SEC = 4;
magjeddf494b02016-10-07 12:32:3537
sakalfb0c5732016-11-03 16:15:3438 public interface FrameListener { void onFrame(Bitmap frame); }
39
Magnus Jedvertecae9cd2019-07-05 12:33:1240 /** Callback for clients to be notified about errors encountered during rendering. */
41 public static interface ErrorCallback {
42 /** Called if GLES20.GL_OUT_OF_MEMORY is encountered during rendering. */
43 void onGlOutOfMemory();
44 }
45
sakal3a9bc172016-11-30 16:30:0546 private static class FrameListenerAndParams {
sakalfb0c5732016-11-03 16:15:3447 public final FrameListener listener;
sakal3a9bc172016-11-30 16:30:0548 public final float scale;
49 public final RendererCommon.GlDrawer drawer;
sakal8fdf9572017-05-31 09:43:1050 public final boolean applyFpsReduction;
sakalfb0c5732016-11-03 16:15:3451
sakal8fdf9572017-05-31 09:43:1052 public FrameListenerAndParams(FrameListener listener, float scale,
53 RendererCommon.GlDrawer drawer, boolean applyFpsReduction) {
sakalfb0c5732016-11-03 16:15:3454 this.listener = listener;
sakal3a9bc172016-11-30 16:30:0555 this.scale = scale;
56 this.drawer = drawer;
sakal8fdf9572017-05-31 09:43:1057 this.applyFpsReduction = applyFpsReduction;
sakalfb0c5732016-11-03 16:15:3458 }
59 }
60
magjeddf494b02016-10-07 12:32:3561 private class EglSurfaceCreation implements Runnable {
magjed9ab8a182016-10-20 10:18:0962 private Object surface;
magjeddf494b02016-10-07 12:32:3563
Mirko Bonadei12251b62017-11-06 03:35:3164 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
65 @SuppressWarnings("NoSynchronizedMethodCheck")
magjed9ab8a182016-10-20 10:18:0966 public synchronized void setSurface(Object surface) {
magjeddf494b02016-10-07 12:32:3567 this.surface = surface;
68 }
69
70 @Override
Mirko Bonadei12251b62017-11-06 03:35:3171 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
72 @SuppressWarnings("NoSynchronizedMethodCheck")
magjeddf494b02016-10-07 12:32:3573 public synchronized void run() {
74 if (surface != null && eglBase != null && !eglBase.hasSurface()) {
magjed9ab8a182016-10-20 10:18:0975 if (surface instanceof Surface) {
76 eglBase.createSurface((Surface) surface);
77 } else if (surface instanceof SurfaceTexture) {
78 eglBase.createSurface((SurfaceTexture) surface);
79 } else {
80 throw new IllegalStateException("Invalid surface: " + surface);
81 }
magjeddf494b02016-10-07 12:32:3582 eglBase.makeCurrent();
83 // Necessary for YUV frames with odd width.
84 GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
85 }
86 }
87 }
88
Sami Kalliomäki0d26c992018-10-19 10:53:2189 /**
90 * Handler that triggers a callback when an uncaught exception happens when handling a message.
91 */
92 private static class HandlerWithExceptionCallback extends Handler {
93 private final Runnable exceptionCallback;
94
95 public HandlerWithExceptionCallback(Looper looper, Runnable exceptionCallback) {
96 super(looper);
97 this.exceptionCallback = exceptionCallback;
98 }
99
100 @Override
101 public void dispatchMessage(Message msg) {
102 try {
103 super.dispatchMessage(msg);
104 } catch (Exception e) {
105 Logging.e(TAG, "Exception on EglRenderer thread", e);
106 exceptionCallback.run();
107 throw e;
108 }
109 }
110 }
111
Xiaolei Yu149533a2017-11-02 23:55:01112 protected final String name;
magjeddf494b02016-10-07 12:32:35113
Artem Titovd7ac5812021-07-27 10:23:39114 // `renderThreadHandler` is a handler for communicating with `renderThread`, and is synchronized
115 // on `handlerLock`.
magjeddf494b02016-10-07 12:32:35116 private final Object handlerLock = new Object();
Sami Kalliomäkie7592d82018-03-22 12:32:44117 @Nullable private Handler renderThreadHandler;
magjeddf494b02016-10-07 12:32:35118
sakal3a9bc172016-11-30 16:30:05119 private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>();
sakalfb0c5732016-11-03 16:15:34120
Magnus Jedvertecae9cd2019-07-05 12:33:12121 private volatile ErrorCallback errorCallback;
122
magjed9ab8a182016-10-20 10:18:09123 // Variables for fps reduction.
124 private final Object fpsReductionLock = new Object();
125 // Time for when next frame should be rendered.
126 private long nextFrameTimeNs;
127 // Minimum duration between frames when fps reduction is active, or -1 if video is completely
128 // paused.
129 private long minRenderPeriodNs;
130
Byoungchan Lee02235d52020-02-08 07:32:21131 // EGL and GL resources for drawing YUV/OES textures. After initialization, these are only
132 // accessed from the render thread.
Sami Kalliomäkie7592d82018-03-22 12:32:44133 @Nullable private EglBase eglBase;
Åsa Perssonf2889bb2019-02-25 15:20:01134 private final VideoFrameDrawer frameDrawer;
Sami Kalliomäkie7592d82018-03-22 12:32:44135 @Nullable private RendererCommon.GlDrawer drawer;
Magnus Jedvert361dbc12018-11-06 10:32:46136 private boolean usePresentationTimeStamp;
magjed7cede372017-09-11 13:12:07137 private final Matrix drawMatrix = new Matrix();
magjeddf494b02016-10-07 12:32:35138
Artem Titovd7ac5812021-07-27 10:23:39139 // Pending frame to render. Serves as a queue with size 1. Synchronized on `frameLock`.
magjeddf494b02016-10-07 12:32:35140 private final Object frameLock = new Object();
Sami Kalliomäkie7592d82018-03-22 12:32:44141 @Nullable private VideoFrame pendingFrame;
magjeddf494b02016-10-07 12:32:35142
Artem Titovd7ac5812021-07-27 10:23:39143 // These variables are synchronized on `layoutLock`.
magjeddf494b02016-10-07 12:32:35144 private final Object layoutLock = new Object();
magjeddf494b02016-10-07 12:32:35145 private float layoutAspectRatio;
146 // If true, mirrors the video stream horizontally.
Magnus Jedvert3ff71de2018-12-17 09:26:12147 private boolean mirrorHorizontally;
148 // If true, mirrors the video stream vertically.
149 private boolean mirrorVertically;
magjeddf494b02016-10-07 12:32:35150
Artem Titovd7ac5812021-07-27 10:23:39151 // These variables are synchronized on `statisticsLock`.
magjeddf494b02016-10-07 12:32:35152 private final Object statisticsLock = new Object();
153 // Total number of video frames received in renderFrame() call.
154 private int framesReceived;
155 // Number of video frames dropped by renderFrame() because previous frame has not been rendered
156 // yet.
157 private int framesDropped;
158 // Number of rendered video frames.
159 private int framesRendered;
magjed9ab8a182016-10-20 10:18:09160 // Start time for counting these statistics, or 0 if we haven't started measuring yet.
161 private long statisticsStartTimeNs;
magjeddf494b02016-10-07 12:32:35162 // Time in ns spent in renderFrameOnRenderThread() function.
163 private long renderTimeNs;
magjed9ab8a182016-10-20 10:18:09164 // Time in ns spent by the render thread in the swapBuffers() function.
165 private long renderSwapBufferTimeNs;
magjeddf494b02016-10-07 12:32:35166
sakalfb0c5732016-11-03 16:15:34167 // Used for bitmap capturing.
Magnus Jedvert2ed62b32018-04-11 12:25:14168 private final GlTextureFrameBuffer bitmapTextureFramebuffer =
169 new GlTextureFrameBuffer(GLES20.GL_RGBA);
sakalfb0c5732016-11-03 16:15:34170
magjed9ab8a182016-10-20 10:18:09171 private final Runnable logStatisticsRunnable = new Runnable() {
172 @Override
173 public void run() {
174 logStatistics();
175 synchronized (handlerLock) {
176 if (renderThreadHandler != null) {
177 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
178 renderThreadHandler.postDelayed(
179 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
180 }
181 }
182 }
183 };
184
magjeddf494b02016-10-07 12:32:35185 private final EglSurfaceCreation eglSurfaceCreationRunnable = new EglSurfaceCreation();
186
187 /**
188 * Standard constructor. The name will be used for the render thread name and included when
189 * logging. In order to render something, you must first call init() and createEglSurface.
190 */
191 public EglRenderer(String name) {
Åsa Perssonf2889bb2019-02-25 15:20:01192 this(name, new VideoFrameDrawer());
193 }
194
195 public EglRenderer(String name, VideoFrameDrawer videoFrameDrawer) {
magjeddf494b02016-10-07 12:32:35196 this.name = name;
Åsa Perssonf2889bb2019-02-25 15:20:01197 this.frameDrawer = videoFrameDrawer;
magjeddf494b02016-10-07 12:32:35198 }
199
200 /**
Artem Titovd7ac5812021-07-27 10:23:39201 * Initialize this class, sharing resources with `sharedContext`. The custom `drawer` will be used
magjeddf494b02016-10-07 12:32:35202 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
Artem Titovd7ac5812021-07-27 10:23:39203 * `drawer`. It is allowed to call init() to reinitialize the renderer after a previous
Magnus Jedvert361dbc12018-11-06 10:32:46204 * init()/release() cycle. If usePresentationTimeStamp is true, eglPresentationTimeANDROID will be
205 * set with the frame timestamps, which specifies desired presentation time and might be useful
206 * for e.g. syncing audio and video.
magjeddf494b02016-10-07 12:32:35207 */
Sami Kalliomäkie7592d82018-03-22 12:32:44208 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
Magnus Jedvert361dbc12018-11-06 10:32:46209 RendererCommon.GlDrawer drawer, boolean usePresentationTimeStamp) {
magjeddf494b02016-10-07 12:32:35210 synchronized (handlerLock) {
211 if (renderThreadHandler != null) {
212 throw new IllegalStateException(name + "Already initialized");
213 }
214 logD("Initializing EglRenderer");
215 this.drawer = drawer;
Magnus Jedvert361dbc12018-11-06 10:32:46216 this.usePresentationTimeStamp = usePresentationTimeStamp;
magjeddf494b02016-10-07 12:32:35217
218 final HandlerThread renderThread = new HandlerThread(name + "EglRenderer");
219 renderThread.start();
Sami Kalliomäki0d26c992018-10-19 10:53:21220 renderThreadHandler =
221 new HandlerWithExceptionCallback(renderThread.getLooper(), new Runnable() {
222 @Override
223 public void run() {
224 synchronized (handlerLock) {
225 renderThreadHandler = null;
226 }
227 }
228 });
magjeddf494b02016-10-07 12:32:35229 // Create EGL context on the newly created render thread. It should be possibly to create the
230 // context on this thread and make it current on the render thread, but this causes failure on
231 // some Marvel based JB devices. https://bugs.chromium.org/p/webrtc/issues/detail?id=6350.
sakalbf080602017-08-11 08:42:43232 ThreadUtils.invokeAtFrontUninterruptibly(renderThreadHandler, () -> {
233 // If sharedContext is null, then texture frames are disabled. This is typically for old
234 // devices that might not be fully spec compliant, so force EGL 1.0 since EGL 1.4 has
235 // caused trouble on some weird devices.
236 if (sharedContext == null) {
237 logD("EglBase10.create context");
238 eglBase = EglBase.createEgl10(configAttributes);
239 } else {
240 logD("EglBase.create shared context");
241 eglBase = EglBase.create(sharedContext, configAttributes);
magjeddf494b02016-10-07 12:32:35242 }
243 });
magjed9ab8a182016-10-20 10:18:09244 renderThreadHandler.post(eglSurfaceCreationRunnable);
245 final long currentTimeNs = System.nanoTime();
246 resetStatistics(currentTimeNs);
247 renderThreadHandler.postDelayed(
248 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
magjeddf494b02016-10-07 12:32:35249 }
250 }
251
Magnus Jedvert361dbc12018-11-06 10:32:46252 /**
253 * Same as above with usePresentationTimeStamp set to false.
254 *
255 * @see #init(EglBase.Context, int[], RendererCommon.GlDrawer, boolean)
256 */
257 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
258 RendererCommon.GlDrawer drawer) {
259 init(sharedContext, configAttributes, drawer, /* usePresentationTimeStamp= */ false);
260 }
261
magjeddf494b02016-10-07 12:32:35262 public void createEglSurface(Surface surface) {
magjed9ab8a182016-10-20 10:18:09263 createEglSurfaceInternal(surface);
264 }
265
266 public void createEglSurface(SurfaceTexture surfaceTexture) {
267 createEglSurfaceInternal(surfaceTexture);
268 }
269
270 private void createEglSurfaceInternal(Object surface) {
magjeddf494b02016-10-07 12:32:35271 eglSurfaceCreationRunnable.setSurface(surface);
magjed9ab8a182016-10-20 10:18:09272 postToRenderThread(eglSurfaceCreationRunnable);
magjeddf494b02016-10-07 12:32:35273 }
274
275 /**
276 * Block until any pending frame is returned and all GL resources released, even if an interrupt
277 * occurs. If an interrupt occurs during release(), the interrupt flag will be set. This function
278 * should be called before the Activity is destroyed and the EGLContext is still valid. If you
279 * don't call this function, the GL resources might leak.
280 */
281 public void release() {
magjed9ab8a182016-10-20 10:18:09282 logD("Releasing.");
magjeddf494b02016-10-07 12:32:35283 final CountDownLatch eglCleanupBarrier = new CountDownLatch(1);
284 synchronized (handlerLock) {
285 if (renderThreadHandler == null) {
286 logD("Already released");
287 return;
288 }
magjed9ab8a182016-10-20 10:18:09289 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
magjeddf494b02016-10-07 12:32:35290 // Release EGL and GL resources on render thread.
sakalbf080602017-08-11 08:42:43291 renderThreadHandler.postAtFrontOfQueue(() -> {
Magnus Jedvert94c0f262018-12-12 16:35:28292 // Detach current shader program.
Magnus Jedvertf355e1a2020-04-21 11:52:38293 synchronized (EglBase.lock) {
294 GLES20.glUseProgram(/* program= */ 0);
295 }
sakalbf080602017-08-11 08:42:43296 if (drawer != null) {
297 drawer.release();
298 drawer = null;
magjeddf494b02016-10-07 12:32:35299 }
magjed7cede372017-09-11 13:12:07300 frameDrawer.release();
Magnus Jedvert2ed62b32018-04-11 12:25:14301 bitmapTextureFramebuffer.release();
sakalbf080602017-08-11 08:42:43302 if (eglBase != null) {
303 logD("eglBase detach and release.");
304 eglBase.detachCurrent();
305 eglBase.release();
306 eglBase = null;
307 }
Sami Kalliomäki8ebac242017-11-08 16:13:13308 frameListeners.clear();
sakalbf080602017-08-11 08:42:43309 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 12:32:35310 });
311 final Looper renderLooper = renderThreadHandler.getLooper();
312 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 08:42:43313 renderThreadHandler.post(() -> {
314 logD("Quitting render thread.");
315 renderLooper.quit();
magjeddf494b02016-10-07 12:32:35316 });
317 // Don't accept any more frames or messages to the render thread.
318 renderThreadHandler = null;
319 }
320 // Make sure the EGL/GL cleanup posted above is executed.
321 ThreadUtils.awaitUninterruptibly(eglCleanupBarrier);
322 synchronized (frameLock) {
323 if (pendingFrame != null) {
sakal6bdcefc2017-08-15 08:56:02324 pendingFrame.release();
magjeddf494b02016-10-07 12:32:35325 pendingFrame = null;
326 }
327 }
magjeddf494b02016-10-07 12:32:35328 logD("Releasing done.");
329 }
330
331 /**
magjed9ab8a182016-10-20 10:18:09332 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 12:32:35333 */
magjed9ab8a182016-10-20 10:18:09334 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 12:32:35335 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 10:18:09336 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 12:32:35337 framesReceived = 0;
338 framesDropped = 0;
339 framesRendered = 0;
magjeddf494b02016-10-07 12:32:35340 renderTimeNs = 0;
magjed9ab8a182016-10-20 10:18:09341 renderSwapBufferTimeNs = 0;
342 }
343 }
344
345 public void printStackTrace() {
346 synchronized (handlerLock) {
347 final Thread renderThread =
348 (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread();
349 if (renderThread != null) {
350 final StackTraceElement[] renderStackTrace = renderThread.getStackTrace();
351 if (renderStackTrace.length > 0) {
Magnus Jedvert0cc11b42018-11-27 15:19:55352 logW("EglRenderer stack trace:");
magjed9ab8a182016-10-20 10:18:09353 for (StackTraceElement traceElem : renderStackTrace) {
Magnus Jedvert0cc11b42018-11-27 15:19:55354 logW(traceElem.toString());
magjed9ab8a182016-10-20 10:18:09355 }
356 }
357 }
magjeddf494b02016-10-07 12:32:35358 }
359 }
360
361 /**
Magnus Jedvert3ff71de2018-12-17 09:26:12362 * Set if the video stream should be mirrored horizontally or not.
magjeddf494b02016-10-07 12:32:35363 */
364 public void setMirror(final boolean mirror) {
Magnus Jedvert3ff71de2018-12-17 09:26:12365 logD("setMirrorHorizontally: " + mirror);
magjeddf494b02016-10-07 12:32:35366 synchronized (layoutLock) {
Magnus Jedvert3ff71de2018-12-17 09:26:12367 this.mirrorHorizontally = mirror;
368 }
369 }
370
371 /**
372 * Set if the video stream should be mirrored vertically or not.
373 */
374 public void setMirrorVertically(final boolean mirrorVertically) {
375 logD("setMirrorVertically: " + mirrorVertically);
376 synchronized (layoutLock) {
377 this.mirrorVertically = mirrorVertically;
magjeddf494b02016-10-07 12:32:35378 }
379 }
380
381 /**
382 * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video.
383 * Set this to 0 to disable cropping.
384 */
385 public void setLayoutAspectRatio(float layoutAspectRatio) {
386 logD("setLayoutAspectRatio: " + layoutAspectRatio);
387 synchronized (layoutLock) {
388 this.layoutAspectRatio = layoutAspectRatio;
389 }
390 }
391
magjed9ab8a182016-10-20 10:18:09392 /**
393 * Limit render framerate.
394 *
395 * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps
396 * reduction.
397 */
398 public void setFpsReduction(float fps) {
399 logD("setFpsReduction: " + fps);
400 synchronized (fpsReductionLock) {
401 final long previousRenderPeriodNs = minRenderPeriodNs;
402 if (fps <= 0) {
403 minRenderPeriodNs = Long.MAX_VALUE;
404 } else {
405 minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps);
406 }
407 if (minRenderPeriodNs != previousRenderPeriodNs) {
408 // Fps reduction changed - reset frame time.
409 nextFrameTimeNs = System.nanoTime();
410 }
411 }
412 }
413
414 public void disableFpsReduction() {
415 setFpsReduction(Float.POSITIVE_INFINITY /* fps */);
416 }
417
418 public void pauseVideo() {
419 setFpsReduction(0 /* fps */);
420 }
421
sakalfb0c5732016-11-03 16:15:34422 /**
sakal3a9bc172016-11-30 16:30:05423 * Register a callback to be invoked when a new video frame has been received. This version uses
424 * the drawer of the EglRenderer that was passed in init.
sakalfb0c5732016-11-03 16:15:34425 *
sakald1516522017-03-13 12:11:48426 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
427 * It should be lightweight and must not call removeFrameListener.
sakalfb0c5732016-11-03 16:15:34428 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
429 * required.
430 */
sakalbb584352016-11-28 16:53:44431 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 09:43:10432 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 16:30:05433 }
434
435 /**
436 * Register a callback to be invoked when a new video frame has been received.
437 *
sakald1516522017-03-13 12:11:48438 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
439 * It should be lightweight and must not call removeFrameListener.
sakal3a9bc172016-11-30 16:30:05440 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
441 * required.
sakald1516522017-03-13 12:11:48442 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 16:30:05443 */
444 public void addFrameListener(
sakald1516522017-03-13 12:11:48445 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 09:43:10446 addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */);
447 }
448
449 /**
450 * Register a callback to be invoked when a new video frame has been received.
451 *
452 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
453 * It should be lightweight and must not call removeFrameListener.
454 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
455 * required.
456 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
457 * @param applyFpsReduction This callback will not be called for frames that have been dropped by
458 * FPS reduction.
459 */
460 public void addFrameListener(final FrameListener listener, final float scale,
Sami Kalliomäkie7592d82018-03-22 12:32:44461 @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 08:42:43462 postToRenderThread(() -> {
463 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
464 frameListeners.add(
465 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 16:53:44466 });
sakalfb0c5732016-11-03 16:15:34467 }
468
469 /**
470 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 16:53:44471 * the queue, nothing happens. It is ensured that callback won't be called after this method
472 * returns.
sakalfb0c5732016-11-03 16:15:34473 *
474 * @param runnable The callback to remove.
475 */
sakalbb584352016-11-28 16:53:44476 public void removeFrameListener(final FrameListener listener) {
477 final CountDownLatch latch = new CountDownLatch(1);
Sami Kalliomäki8ebac242017-11-08 16:13:13478 synchronized (handlerLock) {
479 if (renderThreadHandler == null) {
480 return;
sakalfb0c5732016-11-03 16:15:34481 }
Sami Kalliomäki8ebac242017-11-08 16:13:13482 if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) {
483 throw new RuntimeException("removeFrameListener must not be called on the render thread.");
484 }
485 postToRenderThread(() -> {
486 latch.countDown();
487 final Iterator<FrameListenerAndParams> iter = frameListeners.iterator();
488 while (iter.hasNext()) {
489 if (iter.next().listener == listener) {
490 iter.remove();
491 }
492 }
493 });
494 }
sakalbb584352016-11-28 16:53:44495 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 16:15:34496 }
497
Magnus Jedvertecae9cd2019-07-05 12:33:12498 /** Can be set in order to be notified about errors encountered during rendering. */
499 public void setErrorCallback(ErrorCallback errorCallback) {
500 this.errorCallback = errorCallback;
501 }
502
sakal6bdcefc2017-08-15 08:56:02503 // VideoSink interface.
504 @Override
505 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 12:32:35506 synchronized (statisticsLock) {
507 ++framesReceived;
508 }
magjed9ab8a182016-10-20 10:18:09509 final boolean dropOldFrame;
magjeddf494b02016-10-07 12:32:35510 synchronized (handlerLock) {
511 if (renderThreadHandler == null) {
512 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 12:32:35513 return;
514 }
magjed9ab8a182016-10-20 10:18:09515 synchronized (frameLock) {
516 dropOldFrame = (pendingFrame != null);
517 if (dropOldFrame) {
sakal6bdcefc2017-08-15 08:56:02518 pendingFrame.release();
magjeddf494b02016-10-07 12:32:35519 }
520 pendingFrame = frame;
sakal6bdcefc2017-08-15 08:56:02521 pendingFrame.retain();
sakalbf080602017-08-11 08:42:43522 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 12:32:35523 }
524 }
magjed9ab8a182016-10-20 10:18:09525 if (dropOldFrame) {
526 synchronized (statisticsLock) {
527 ++framesDropped;
528 }
529 }
magjeddf494b02016-10-07 12:32:35530 }
531
532 /**
533 * Release EGL surface. This function will block until the EGL surface is released.
534 */
sakal28ec6bd2016-11-09 09:47:12535 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 12:32:35536 // Ensure that the render thread is no longer touching the Surface before returning from this
537 // function.
538 eglSurfaceCreationRunnable.setSurface(null /* surface */);
539 synchronized (handlerLock) {
540 if (renderThreadHandler != null) {
541 renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable);
sakalbf080602017-08-11 08:42:43542 renderThreadHandler.postAtFrontOfQueue(() -> {
543 if (eglBase != null) {
544 eglBase.detachCurrent();
545 eglBase.releaseSurface();
magjeddf494b02016-10-07 12:32:35546 }
sakalbf080602017-08-11 08:42:43547 completionCallback.run();
magjeddf494b02016-10-07 12:32:35548 });
sakal28ec6bd2016-11-09 09:47:12549 return;
magjeddf494b02016-10-07 12:32:35550 }
551 }
sakal28ec6bd2016-11-09 09:47:12552 completionCallback.run();
magjeddf494b02016-10-07 12:32:35553 }
554
555 /**
magjeddf494b02016-10-07 12:32:35556 * Private helper function to post tasks safely.
557 */
magjed9ab8a182016-10-20 10:18:09558 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 12:32:35559 synchronized (handlerLock) {
560 if (renderThreadHandler != null) {
561 renderThreadHandler.post(runnable);
562 }
563 }
564 }
565
sakalf25a2202017-05-04 13:06:56566 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 12:32:35567 if (eglBase != null && eglBase.hasSurface()) {
568 logD("clearSurface");
sakalf25a2202017-05-04 13:06:56569 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 12:32:35570 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
571 eglBase.swapBuffers();
572 }
573 }
574
575 /**
sakalf25a2202017-05-04 13:06:56576 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 10:18:09577 */
578 public void clearImage() {
sakalf25a2202017-05-04 13:06:56579 clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
580 }
581
582 /**
583 * Post a task to clear the surface to a specific color.
584 */
585 public void clearImage(final float r, final float g, final float b, final float a) {
magjed9ab8a182016-10-20 10:18:09586 synchronized (handlerLock) {
587 if (renderThreadHandler == null) {
588 return;
589 }
sakalbf080602017-08-11 08:42:43590 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 10:18:09591 }
592 }
593
594 /**
Artem Titovd7ac5812021-07-27 10:23:39595 * Renders and releases `pendingFrame`.
magjeddf494b02016-10-07 12:32:35596 */
597 private void renderFrameOnRenderThread() {
Artem Titovd7ac5812021-07-27 10:23:39598 // Fetch and render `pendingFrame`.
sakal6bdcefc2017-08-15 08:56:02599 final VideoFrame frame;
magjeddf494b02016-10-07 12:32:35600 synchronized (frameLock) {
601 if (pendingFrame == null) {
602 return;
603 }
604 frame = pendingFrame;
605 pendingFrame = null;
606 }
607 if (eglBase == null || !eglBase.hasSurface()) {
608 logD("Dropping frame - No surface");
sakal6bdcefc2017-08-15 08:56:02609 frame.release();
magjeddf494b02016-10-07 12:32:35610 return;
611 }
sakald1516522017-03-13 12:11:48612 // Check if fps reduction is active.
613 final boolean shouldRenderFrame;
614 synchronized (fpsReductionLock) {
615 if (minRenderPeriodNs == Long.MAX_VALUE) {
616 // Rendering is paused.
617 shouldRenderFrame = false;
618 } else if (minRenderPeriodNs <= 0) {
619 // FPS reduction is disabled.
620 shouldRenderFrame = true;
621 } else {
622 final long currentTimeNs = System.nanoTime();
623 if (currentTimeNs < nextFrameTimeNs) {
624 logD("Skipping frame rendering - fps reduction is active.");
625 shouldRenderFrame = false;
626 } else {
627 nextFrameTimeNs += minRenderPeriodNs;
628 // The time for the next frame should always be in the future.
629 nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs);
630 shouldRenderFrame = true;
631 }
632 }
633 }
magjeddf494b02016-10-07 12:32:35634
635 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 12:32:35636
sakal6bdcefc2017-08-15 08:56:02637 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
638 final float drawnAspectRatio;
magjeddf494b02016-10-07 12:32:35639 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 08:56:02640 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 12:32:35641 }
642
sakal6bdcefc2017-08-15 08:56:02643 final float scaleX;
644 final float scaleY;
645
646 if (frameAspectRatio > drawnAspectRatio) {
647 scaleX = drawnAspectRatio / frameAspectRatio;
648 scaleY = 1f;
649 } else {
650 scaleX = 1f;
651 scaleY = frameAspectRatio / drawnAspectRatio;
652 }
653
magjed7cede372017-09-11 13:12:07654 drawMatrix.reset();
sakal6bdcefc2017-08-15 08:56:02655 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 09:26:12656 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 08:56:02657 drawMatrix.preScale(scaleX, scaleY);
658 drawMatrix.preTranslate(-0.5f, -0.5f);
659
Magnus Jedvertecae9cd2019-07-05 12:33:12660 try {
661 if (shouldRenderFrame) {
662 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
663 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
664 frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */,
665 eglBase.surfaceWidth(), eglBase.surfaceHeight());
sakald1516522017-03-13 12:11:48666
Magnus Jedvertecae9cd2019-07-05 12:33:12667 final long swapBuffersStartTimeNs = System.nanoTime();
668 if (usePresentationTimeStamp) {
669 eglBase.swapBuffers(frame.getTimestampNs());
670 } else {
671 eglBase.swapBuffers();
672 }
673
674 final long currentTimeNs = System.nanoTime();
675 synchronized (statisticsLock) {
676 ++framesRendered;
677 renderTimeNs += (currentTimeNs - startTimeNs);
678 renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs);
679 }
Magnus Jedvert361dbc12018-11-06 10:32:46680 }
sakald1516522017-03-13 12:11:48681
Magnus Jedvertecae9cd2019-07-05 12:33:12682 notifyCallbacks(frame, shouldRenderFrame);
683 } catch (GlUtil.GlOutOfMemoryException e) {
684 logE("Error while drawing frame", e);
685 final ErrorCallback errorCallback = this.errorCallback;
686 if (errorCallback != null) {
687 errorCallback.onGlOutOfMemory();
sakald1516522017-03-13 12:11:48688 }
Magnus Jedvertecae9cd2019-07-05 12:33:12689 // Attempt to free up some resources.
690 drawer.release();
691 frameDrawer.release();
692 bitmapTextureFramebuffer.release();
693 // Continue here on purpose and retry again for next frame. In worst case, this is a continous
694 // problem and no more frames will be drawn.
695 } finally {
696 frame.release();
magjeddf494b02016-10-07 12:32:35697 }
sakalfb0c5732016-11-03 16:15:34698 }
699
magjed7cede372017-09-11 13:12:07700 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 16:53:44701 if (frameListeners.isEmpty())
702 return;
sakalfb0c5732016-11-03 16:15:34703
magjed7cede372017-09-11 13:12:07704 drawMatrix.reset();
sakal6bdcefc2017-08-15 08:56:02705 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 09:26:12706 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 08:56:02707 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
708 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 16:15:34709
sakal8fdf9572017-05-31 09:43:10710 Iterator<FrameListenerAndParams> it = frameListeners.iterator();
711 while (it.hasNext()) {
712 FrameListenerAndParams listenerAndParams = it.next();
713 if (!wasRendered && listenerAndParams.applyFpsReduction) {
714 continue;
715 }
716 it.remove();
717
sakal6bdcefc2017-08-15 08:56:02718 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
719 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 16:15:34720
721 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 16:30:05722 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 16:15:34723 continue;
724 }
725
sakalfb0c5732016-11-03 16:15:34726 bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);
727
728 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
729 GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
730 GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);
731
sakal103988d2017-02-17 17:59:01732 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
733 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 13:12:07734 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
735 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 16:15:34736
737 final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
738 GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
739 GLES20.glReadPixels(
740 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);
741
742 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
743 GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");
744
745 final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
746 bitmap.copyPixelsFromBuffer(bitmapBuffer);
sakal3a9bc172016-11-30 16:30:05747 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 16:15:34748 }
magjeddf494b02016-10-07 12:32:35749 }
750
magjed9ab8a182016-10-20 10:18:09751 private String averageTimeAsString(long sumTimeNs, int count) {
Magnus Jedvert3bc696f2018-11-12 10:35:20752 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " us";
magjed9ab8a182016-10-20 10:18:09753 }
754
magjeddf494b02016-10-07 12:32:35755 private void logStatistics() {
Sami Kalliomäki1659e972018-06-04 12:07:58756 final DecimalFormat fpsFormat = new DecimalFormat("#.0");
magjed9ab8a182016-10-20 10:18:09757 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 12:32:35758 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 10:18:09759 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
Sami Kalliomäki9b661142019-10-21 15:12:25760 if (elapsedTimeNs <= 0 || (minRenderPeriodNs == Long.MAX_VALUE && framesReceived == 0)) {
magjed9ab8a182016-10-20 10:18:09761 return;
magjeddf494b02016-10-07 12:32:35762 }
magjed9ab8a182016-10-20 10:18:09763 final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs;
764 logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms."
765 + " Frames received: " + framesReceived + "."
766 + " Dropped: " + framesDropped + "."
767 + " Rendered: " + framesRendered + "."
Sami Kalliomäki1659e972018-06-04 12:07:58768 + " Render fps: " + fpsFormat.format(renderFps) + "."
magjed9ab8a182016-10-20 10:18:09769 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
770 + " Average swapBuffer time: "
771 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
772 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 12:32:35773 }
774 }
775
Magnus Jedvertecae9cd2019-07-05 12:33:12776 private void logE(String string, Throwable e) {
777 Logging.e(TAG, name + string, e);
778 }
779
magjeddf494b02016-10-07 12:32:35780 private void logD(String string) {
781 Logging.d(TAG, name + string);
782 }
Magnus Jedvert0cc11b42018-11-27 15:19:55783
784 private void logW(String string) {
785 Logging.w(TAG, name + string);
786 }
magjeddf494b02016-10-07 12:32:35787}