blob: 5ab0868ef314b90e8ddb31c9c00ebef7cae19126 [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;
magjeddf494b02016-10-07 05:32:35 -070021import android.view.Surface;
Byoungchan Lee02334e02021-08-14 11:41:59 +090022import androidx.annotation.Nullable;
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
Magnus Jedvertecae9cd2019-07-05 14:33:12 +020040 /** 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 08:30:05 -080046 private static class FrameListenerAndParams {
sakalfb0c5732016-11-03 09:15:34 -070047 public final FrameListener listener;
sakal3a9bc172016-11-30 08:30:05 -080048 public final float scale;
49 public final RendererCommon.GlDrawer drawer;
sakal8fdf9572017-05-31 02:43:10 -070050 public final boolean applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070051
sakal8fdf9572017-05-31 02:43:10 -070052 public FrameListenerAndParams(FrameListener listener, float scale,
53 RendererCommon.GlDrawer drawer, boolean applyFpsReduction) {
sakalfb0c5732016-11-03 09:15:34 -070054 this.listener = listener;
sakal3a9bc172016-11-30 08:30:05 -080055 this.scale = scale;
56 this.drawer = drawer;
sakal8fdf9572017-05-31 02:43:10 -070057 this.applyFpsReduction = applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070058 }
59 }
60
magjeddf494b02016-10-07 05:32:35 -070061 private class EglSurfaceCreation implements Runnable {
magjed9ab8a182016-10-20 03:18:09 -070062 private Object surface;
magjeddf494b02016-10-07 05:32:35 -070063
Mirko Bonadei12251b62017-11-05 19:35:31 -080064 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
65 @SuppressWarnings("NoSynchronizedMethodCheck")
magjed9ab8a182016-10-20 03:18:09 -070066 public synchronized void setSurface(Object surface) {
magjeddf494b02016-10-07 05:32:35 -070067 this.surface = surface;
68 }
69
70 @Override
Mirko Bonadei12251b62017-11-05 19:35:31 -080071 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
72 @SuppressWarnings("NoSynchronizedMethodCheck")
magjeddf494b02016-10-07 05:32:35 -070073 public synchronized void run() {
74 if (surface != null && eglBase != null && !eglBase.hasSurface()) {
magjed9ab8a182016-10-20 03:18:09 -070075 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 05:32:35 -070082 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 12:53:21 +020089 /**
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-03 07:55:01 +0800112 protected final String name;
magjeddf494b02016-10-07 05:32:35 -0700113
Artem Titovd7ac5812021-07-27 12:23:39 +0200114 // `renderThreadHandler` is a handler for communicating with `renderThread`, and is synchronized
115 // on `handlerLock`.
magjeddf494b02016-10-07 05:32:35 -0700116 private final Object handlerLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100117 @Nullable private Handler renderThreadHandler;
magjeddf494b02016-10-07 05:32:35 -0700118
sakal3a9bc172016-11-30 08:30:05 -0800119 private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>();
sakalfb0c5732016-11-03 09:15:34 -0700120
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200121 private volatile ErrorCallback errorCallback;
122
magjed9ab8a182016-10-20 03:18:09 -0700123 // 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 16:32:21 +0900131 // 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 13:32:44 +0100133 @Nullable private EglBase eglBase;
Åsa Perssonf2889bb2019-02-25 16:20:01 +0100134 private final VideoFrameDrawer frameDrawer;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100135 @Nullable private RendererCommon.GlDrawer drawer;
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100136 private boolean usePresentationTimeStamp;
magjed7cede372017-09-11 06:12:07 -0700137 private final Matrix drawMatrix = new Matrix();
magjeddf494b02016-10-07 05:32:35 -0700138
Artem Titovd7ac5812021-07-27 12:23:39 +0200139 // Pending frame to render. Serves as a queue with size 1. Synchronized on `frameLock`.
magjeddf494b02016-10-07 05:32:35 -0700140 private final Object frameLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100141 @Nullable private VideoFrame pendingFrame;
magjeddf494b02016-10-07 05:32:35 -0700142
Artem Titovd7ac5812021-07-27 12:23:39 +0200143 // These variables are synchronized on `layoutLock`.
magjeddf494b02016-10-07 05:32:35 -0700144 private final Object layoutLock = new Object();
magjeddf494b02016-10-07 05:32:35 -0700145 private float layoutAspectRatio;
146 // If true, mirrors the video stream horizontally.
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100147 private boolean mirrorHorizontally;
148 // If true, mirrors the video stream vertically.
149 private boolean mirrorVertically;
magjeddf494b02016-10-07 05:32:35 -0700150
Artem Titovd7ac5812021-07-27 12:23:39 +0200151 // These variables are synchronized on `statisticsLock`.
magjeddf494b02016-10-07 05:32:35 -0700152 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 03:18:09 -0700160 // Start time for counting these statistics, or 0 if we haven't started measuring yet.
161 private long statisticsStartTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700162 // Time in ns spent in renderFrameOnRenderThread() function.
163 private long renderTimeNs;
magjed9ab8a182016-10-20 03:18:09 -0700164 // Time in ns spent by the render thread in the swapBuffers() function.
165 private long renderSwapBufferTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700166
sakalfb0c5732016-11-03 09:15:34 -0700167 // Used for bitmap capturing.
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200168 private final GlTextureFrameBuffer bitmapTextureFramebuffer =
169 new GlTextureFrameBuffer(GLES20.GL_RGBA);
sakalfb0c5732016-11-03 09:15:34 -0700170
magjed9ab8a182016-10-20 03:18:09 -0700171 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 05:32:35 -0700185 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 16:20:01 +0100192 this(name, new VideoFrameDrawer());
193 }
194
195 public EglRenderer(String name, VideoFrameDrawer videoFrameDrawer) {
magjeddf494b02016-10-07 05:32:35 -0700196 this.name = name;
Åsa Perssonf2889bb2019-02-25 16:20:01 +0100197 this.frameDrawer = videoFrameDrawer;
magjeddf494b02016-10-07 05:32:35 -0700198 }
199
200 /**
Artem Titovd7ac5812021-07-27 12:23:39 +0200201 * Initialize this class, sharing resources with `sharedContext`. The custom `drawer` will be used
magjeddf494b02016-10-07 05:32:35 -0700202 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
Artem Titovd7ac5812021-07-27 12:23:39 +0200203 * `drawer`. It is allowed to call init() to reinitialize the renderer after a previous
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100204 * 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 05:32:35 -0700207 */
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100208 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100209 RendererCommon.GlDrawer drawer, boolean usePresentationTimeStamp) {
magjeddf494b02016-10-07 05:32:35 -0700210 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 11:32:46 +0100216 this.usePresentationTimeStamp = usePresentationTimeStamp;
magjeddf494b02016-10-07 05:32:35 -0700217
218 final HandlerThread renderThread = new HandlerThread(name + "EglRenderer");
219 renderThread.start();
Sami Kalliomäki0d26c992018-10-19 12:53:21 +0200220 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 05:32:35 -0700229 // 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 01:42:43 -0700232 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 05:32:35 -0700242 }
243 });
magjed9ab8a182016-10-20 03:18:09 -0700244 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 05:32:35 -0700249 }
250 }
251
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100252 /**
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 05:32:35 -0700262 public void createEglSurface(Surface surface) {
magjed9ab8a182016-10-20 03:18:09 -0700263 createEglSurfaceInternal(surface);
264 }
265
266 public void createEglSurface(SurfaceTexture surfaceTexture) {
267 createEglSurfaceInternal(surfaceTexture);
268 }
269
270 private void createEglSurfaceInternal(Object surface) {
magjeddf494b02016-10-07 05:32:35 -0700271 eglSurfaceCreationRunnable.setSurface(surface);
magjed9ab8a182016-10-20 03:18:09 -0700272 postToRenderThread(eglSurfaceCreationRunnable);
magjeddf494b02016-10-07 05:32:35 -0700273 }
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 03:18:09 -0700282 logD("Releasing.");
magjeddf494b02016-10-07 05:32:35 -0700283 final CountDownLatch eglCleanupBarrier = new CountDownLatch(1);
284 synchronized (handlerLock) {
285 if (renderThreadHandler == null) {
286 logD("Already released");
287 return;
288 }
magjed9ab8a182016-10-20 03:18:09 -0700289 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
magjeddf494b02016-10-07 05:32:35 -0700290 // Release EGL and GL resources on render thread.
sakalbf080602017-08-11 01:42:43 -0700291 renderThreadHandler.postAtFrontOfQueue(() -> {
Magnus Jedvert94c0f262018-12-12 17:35:28 +0100292 // Detach current shader program.
Magnus Jedvertf355e1a2020-04-21 13:52:38 +0200293 synchronized (EglBase.lock) {
294 GLES20.glUseProgram(/* program= */ 0);
295 }
sakalbf080602017-08-11 01:42:43 -0700296 if (drawer != null) {
297 drawer.release();
298 drawer = null;
magjeddf494b02016-10-07 05:32:35 -0700299 }
magjed7cede372017-09-11 06:12:07 -0700300 frameDrawer.release();
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200301 bitmapTextureFramebuffer.release();
sakalbf080602017-08-11 01:42:43 -0700302 if (eglBase != null) {
303 logD("eglBase detach and release.");
304 eglBase.detachCurrent();
305 eglBase.release();
306 eglBase = null;
307 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100308 frameListeners.clear();
sakalbf080602017-08-11 01:42:43 -0700309 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 05:32:35 -0700310 });
311 final Looper renderLooper = renderThreadHandler.getLooper();
312 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 01:42:43 -0700313 renderThreadHandler.post(() -> {
314 logD("Quitting render thread.");
315 renderLooper.quit();
magjeddf494b02016-10-07 05:32:35 -0700316 });
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 01:56:02 -0700324 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700325 pendingFrame = null;
326 }
327 }
magjeddf494b02016-10-07 05:32:35 -0700328 logD("Releasing done.");
329 }
330
331 /**
magjed9ab8a182016-10-20 03:18:09 -0700332 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 05:32:35 -0700333 */
magjed9ab8a182016-10-20 03:18:09 -0700334 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 05:32:35 -0700335 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700336 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700337 framesReceived = 0;
338 framesDropped = 0;
339 framesRendered = 0;
magjeddf494b02016-10-07 05:32:35 -0700340 renderTimeNs = 0;
magjed9ab8a182016-10-20 03:18:09 -0700341 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 16:19:55 +0100352 logW("EglRenderer stack trace:");
magjed9ab8a182016-10-20 03:18:09 -0700353 for (StackTraceElement traceElem : renderStackTrace) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100354 logW(traceElem.toString());
magjed9ab8a182016-10-20 03:18:09 -0700355 }
356 }
357 }
magjeddf494b02016-10-07 05:32:35 -0700358 }
359 }
360
361 /**
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100362 * Set if the video stream should be mirrored horizontally or not.
magjeddf494b02016-10-07 05:32:35 -0700363 */
364 public void setMirror(final boolean mirror) {
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100365 logD("setMirrorHorizontally: " + mirror);
magjeddf494b02016-10-07 05:32:35 -0700366 synchronized (layoutLock) {
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100367 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 05:32:35 -0700378 }
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 03:18:09 -0700392 /**
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 09:15:34 -0700422 /**
sakal3a9bc172016-11-30 08:30:05 -0800423 * 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 09:15:34 -0700425 *
sakald1516522017-03-13 05:11:48 -0700426 * @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 09:15:34 -0700428 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
429 * required.
430 */
sakalbb584352016-11-28 08:53:44 -0800431 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 02:43:10 -0700432 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 08:30:05 -0800433 }
434
435 /**
436 * Register a callback to be invoked when a new video frame has been received.
437 *
sakald1516522017-03-13 05:11:48 -0700438 * @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 08:30:05 -0800440 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
441 * required.
sakald1516522017-03-13 05:11:48 -0700442 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 08:30:05 -0800443 */
444 public void addFrameListener(
sakald1516522017-03-13 05:11:48 -0700445 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 02:43:10 -0700446 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 13:32:44 +0100461 @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 01:42:43 -0700462 postToRenderThread(() -> {
463 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
464 frameListeners.add(
465 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 08:53:44 -0800466 });
sakalfb0c5732016-11-03 09:15:34 -0700467 }
468
469 /**
470 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 08:53:44 -0800471 * the queue, nothing happens. It is ensured that callback won't be called after this method
472 * returns.
sakalfb0c5732016-11-03 09:15:34 -0700473 *
474 * @param runnable The callback to remove.
475 */
sakalbb584352016-11-28 08:53:44 -0800476 public void removeFrameListener(final FrameListener listener) {
477 final CountDownLatch latch = new CountDownLatch(1);
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100478 synchronized (handlerLock) {
479 if (renderThreadHandler == null) {
480 return;
sakalfb0c5732016-11-03 09:15:34 -0700481 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100482 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 08:53:44 -0800495 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 09:15:34 -0700496 }
497
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200498 /** 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 01:56:02 -0700503 // VideoSink interface.
504 @Override
505 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 05:32:35 -0700506 synchronized (statisticsLock) {
507 ++framesReceived;
508 }
magjed9ab8a182016-10-20 03:18:09 -0700509 final boolean dropOldFrame;
magjeddf494b02016-10-07 05:32:35 -0700510 synchronized (handlerLock) {
511 if (renderThreadHandler == null) {
512 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 05:32:35 -0700513 return;
514 }
magjed9ab8a182016-10-20 03:18:09 -0700515 synchronized (frameLock) {
516 dropOldFrame = (pendingFrame != null);
517 if (dropOldFrame) {
sakal6bdcefc2017-08-15 01:56:02 -0700518 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700519 }
520 pendingFrame = frame;
sakal6bdcefc2017-08-15 01:56:02 -0700521 pendingFrame.retain();
sakalbf080602017-08-11 01:42:43 -0700522 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 05:32:35 -0700523 }
524 }
magjed9ab8a182016-10-20 03:18:09 -0700525 if (dropOldFrame) {
526 synchronized (statisticsLock) {
527 ++framesDropped;
528 }
529 }
magjeddf494b02016-10-07 05:32:35 -0700530 }
531
532 /**
533 * Release EGL surface. This function will block until the EGL surface is released.
534 */
sakal28ec6bd2016-11-09 01:47:12 -0800535 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 05:32:35 -0700536 // 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 01:42:43 -0700542 renderThreadHandler.postAtFrontOfQueue(() -> {
543 if (eglBase != null) {
544 eglBase.detachCurrent();
545 eglBase.releaseSurface();
magjeddf494b02016-10-07 05:32:35 -0700546 }
sakalbf080602017-08-11 01:42:43 -0700547 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700548 });
sakal28ec6bd2016-11-09 01:47:12 -0800549 return;
magjeddf494b02016-10-07 05:32:35 -0700550 }
551 }
sakal28ec6bd2016-11-09 01:47:12 -0800552 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700553 }
554
555 /**
magjeddf494b02016-10-07 05:32:35 -0700556 * Private helper function to post tasks safely.
557 */
magjed9ab8a182016-10-20 03:18:09 -0700558 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 05:32:35 -0700559 synchronized (handlerLock) {
560 if (renderThreadHandler != null) {
561 renderThreadHandler.post(runnable);
562 }
563 }
564 }
565
sakalf25a2202017-05-04 06:06:56 -0700566 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 05:32:35 -0700567 if (eglBase != null && eglBase.hasSurface()) {
568 logD("clearSurface");
sakalf25a2202017-05-04 06:06:56 -0700569 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 05:32:35 -0700570 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
571 eglBase.swapBuffers();
572 }
573 }
574
575 /**
sakalf25a2202017-05-04 06:06:56 -0700576 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 03:18:09 -0700577 */
578 public void clearImage() {
sakalf25a2202017-05-04 06:06:56 -0700579 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 03:18:09 -0700586 synchronized (handlerLock) {
587 if (renderThreadHandler == null) {
588 return;
589 }
sakalbf080602017-08-11 01:42:43 -0700590 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 03:18:09 -0700591 }
592 }
593
594 /**
Artem Titovd7ac5812021-07-27 12:23:39 +0200595 * Renders and releases `pendingFrame`.
magjeddf494b02016-10-07 05:32:35 -0700596 */
597 private void renderFrameOnRenderThread() {
Artem Titovd7ac5812021-07-27 12:23:39 +0200598 // Fetch and render `pendingFrame`.
sakal6bdcefc2017-08-15 01:56:02 -0700599 final VideoFrame frame;
magjeddf494b02016-10-07 05:32:35 -0700600 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 01:56:02 -0700609 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700610 return;
611 }
sakald1516522017-03-13 05:11:48 -0700612 // 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 05:32:35 -0700634
635 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700636
sakal6bdcefc2017-08-15 01:56:02 -0700637 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
638 final float drawnAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700639 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 01:56:02 -0700640 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700641 }
642
sakal6bdcefc2017-08-15 01:56:02 -0700643 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 06:12:07 -0700654 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700655 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100656 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 01:56:02 -0700657 drawMatrix.preScale(scaleX, scaleY);
658 drawMatrix.preTranslate(-0.5f, -0.5f);
659
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200660 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 05:11:48 -0700666
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200667 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 11:32:46 +0100680 }
sakald1516522017-03-13 05:11:48 -0700681
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200682 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 05:11:48 -0700688 }
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200689 // 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 05:32:35 -0700697 }
sakalfb0c5732016-11-03 09:15:34 -0700698 }
699
magjed7cede372017-09-11 06:12:07 -0700700 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 08:53:44 -0800701 if (frameListeners.isEmpty())
702 return;
sakalfb0c5732016-11-03 09:15:34 -0700703
magjed7cede372017-09-11 06:12:07 -0700704 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700705 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100706 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 01:56:02 -0700707 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
708 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 09:15:34 -0700709
sakal8fdf9572017-05-31 02:43:10 -0700710 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 01:56:02 -0700718 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
719 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 09:15:34 -0700720
721 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 08:30:05 -0800722 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 09:15:34 -0700723 continue;
724 }
725
sakalfb0c5732016-11-03 09:15:34 -0700726 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 09:59:01 -0800732 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
733 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700734 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
735 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 09:15:34 -0700736
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 08:30:05 -0800747 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 09:15:34 -0700748 }
magjeddf494b02016-10-07 05:32:35 -0700749 }
750
magjed9ab8a182016-10-20 03:18:09 -0700751 private String averageTimeAsString(long sumTimeNs, int count) {
Magnus Jedvert3bc696f2018-11-12 11:35:20 +0100752 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " us";
magjed9ab8a182016-10-20 03:18:09 -0700753 }
754
magjeddf494b02016-10-07 05:32:35 -0700755 private void logStatistics() {
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200756 final DecimalFormat fpsFormat = new DecimalFormat("#.0");
magjed9ab8a182016-10-20 03:18:09 -0700757 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700758 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700759 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
Sami Kalliomäki9b661142019-10-21 17:12:25 +0200760 if (elapsedTimeNs <= 0 || (minRenderPeriodNs == Long.MAX_VALUE && framesReceived == 0)) {
magjed9ab8a182016-10-20 03:18:09 -0700761 return;
magjeddf494b02016-10-07 05:32:35 -0700762 }
magjed9ab8a182016-10-20 03:18:09 -0700763 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 14:07:58 +0200768 + " Render fps: " + fpsFormat.format(renderFps) + "."
magjed9ab8a182016-10-20 03:18:09 -0700769 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
770 + " Average swapBuffer time: "
771 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
772 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 05:32:35 -0700773 }
774 }
775
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200776 private void logE(String string, Throwable e) {
777 Logging.e(TAG, name + string, e);
778 }
779
magjeddf494b02016-10-07 05:32:35 -0700780 private void logD(String string) {
781 Logging.d(TAG, name + string);
782 }
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100783
784 private void logW(String string) {
785 Logging.w(TAG, name + string);
786 }
magjeddf494b02016-10-07 05:32:35 -0700787}