blob: 950f0b593fdc4d69ac0beceacf2e29b0f0bb811d [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
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
114 // |renderThreadHandler| is a handler for communicating with |renderThread|, and is synchronized
115 // on |handlerLock|.
116 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
magjeddf494b02016-10-07 05:32:35 -0700131 // EGL and GL resources for drawing YUV/OES textures. After initilization, these are only accessed
132 // 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
139 // Pending frame to render. Serves as a queue with size 1. Synchronized on |frameLock|.
140 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
143 // These variables are synchronized on |layoutLock|.
144 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
151 // These variables are synchronized on |statisticsLock|.
152 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 /**
201 * Initialize this class, sharing resources with |sharedContext|. The custom |drawer| will be used
202 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
203 * |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.
293 GLES20.glUseProgram(/* program= */ 0);
sakalbf080602017-08-11 01:42:43 -0700294 if (drawer != null) {
295 drawer.release();
296 drawer = null;
magjeddf494b02016-10-07 05:32:35 -0700297 }
magjed7cede372017-09-11 06:12:07 -0700298 frameDrawer.release();
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200299 bitmapTextureFramebuffer.release();
sakalbf080602017-08-11 01:42:43 -0700300 if (eglBase != null) {
301 logD("eglBase detach and release.");
302 eglBase.detachCurrent();
303 eglBase.release();
304 eglBase = null;
305 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100306 frameListeners.clear();
sakalbf080602017-08-11 01:42:43 -0700307 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 05:32:35 -0700308 });
309 final Looper renderLooper = renderThreadHandler.getLooper();
310 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 01:42:43 -0700311 renderThreadHandler.post(() -> {
312 logD("Quitting render thread.");
313 renderLooper.quit();
magjeddf494b02016-10-07 05:32:35 -0700314 });
315 // Don't accept any more frames or messages to the render thread.
316 renderThreadHandler = null;
317 }
318 // Make sure the EGL/GL cleanup posted above is executed.
319 ThreadUtils.awaitUninterruptibly(eglCleanupBarrier);
320 synchronized (frameLock) {
321 if (pendingFrame != null) {
sakal6bdcefc2017-08-15 01:56:02 -0700322 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700323 pendingFrame = null;
324 }
325 }
magjeddf494b02016-10-07 05:32:35 -0700326 logD("Releasing done.");
327 }
328
329 /**
magjed9ab8a182016-10-20 03:18:09 -0700330 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 05:32:35 -0700331 */
magjed9ab8a182016-10-20 03:18:09 -0700332 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 05:32:35 -0700333 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700334 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700335 framesReceived = 0;
336 framesDropped = 0;
337 framesRendered = 0;
magjeddf494b02016-10-07 05:32:35 -0700338 renderTimeNs = 0;
magjed9ab8a182016-10-20 03:18:09 -0700339 renderSwapBufferTimeNs = 0;
340 }
341 }
342
343 public void printStackTrace() {
344 synchronized (handlerLock) {
345 final Thread renderThread =
346 (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread();
347 if (renderThread != null) {
348 final StackTraceElement[] renderStackTrace = renderThread.getStackTrace();
349 if (renderStackTrace.length > 0) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100350 logW("EglRenderer stack trace:");
magjed9ab8a182016-10-20 03:18:09 -0700351 for (StackTraceElement traceElem : renderStackTrace) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100352 logW(traceElem.toString());
magjed9ab8a182016-10-20 03:18:09 -0700353 }
354 }
355 }
magjeddf494b02016-10-07 05:32:35 -0700356 }
357 }
358
359 /**
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100360 * Set if the video stream should be mirrored horizontally or not.
magjeddf494b02016-10-07 05:32:35 -0700361 */
362 public void setMirror(final boolean mirror) {
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100363 logD("setMirrorHorizontally: " + mirror);
magjeddf494b02016-10-07 05:32:35 -0700364 synchronized (layoutLock) {
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100365 this.mirrorHorizontally = mirror;
366 }
367 }
368
369 /**
370 * Set if the video stream should be mirrored vertically or not.
371 */
372 public void setMirrorVertically(final boolean mirrorVertically) {
373 logD("setMirrorVertically: " + mirrorVertically);
374 synchronized (layoutLock) {
375 this.mirrorVertically = mirrorVertically;
magjeddf494b02016-10-07 05:32:35 -0700376 }
377 }
378
379 /**
380 * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video.
381 * Set this to 0 to disable cropping.
382 */
383 public void setLayoutAspectRatio(float layoutAspectRatio) {
384 logD("setLayoutAspectRatio: " + layoutAspectRatio);
385 synchronized (layoutLock) {
386 this.layoutAspectRatio = layoutAspectRatio;
387 }
388 }
389
magjed9ab8a182016-10-20 03:18:09 -0700390 /**
391 * Limit render framerate.
392 *
393 * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps
394 * reduction.
395 */
396 public void setFpsReduction(float fps) {
397 logD("setFpsReduction: " + fps);
398 synchronized (fpsReductionLock) {
399 final long previousRenderPeriodNs = minRenderPeriodNs;
400 if (fps <= 0) {
401 minRenderPeriodNs = Long.MAX_VALUE;
402 } else {
403 minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps);
404 }
405 if (minRenderPeriodNs != previousRenderPeriodNs) {
406 // Fps reduction changed - reset frame time.
407 nextFrameTimeNs = System.nanoTime();
408 }
409 }
410 }
411
412 public void disableFpsReduction() {
413 setFpsReduction(Float.POSITIVE_INFINITY /* fps */);
414 }
415
416 public void pauseVideo() {
417 setFpsReduction(0 /* fps */);
418 }
419
sakalfb0c5732016-11-03 09:15:34 -0700420 /**
sakal3a9bc172016-11-30 08:30:05 -0800421 * Register a callback to be invoked when a new video frame has been received. This version uses
422 * the drawer of the EglRenderer that was passed in init.
sakalfb0c5732016-11-03 09:15:34 -0700423 *
sakald1516522017-03-13 05:11:48 -0700424 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
425 * It should be lightweight and must not call removeFrameListener.
sakalfb0c5732016-11-03 09:15:34 -0700426 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
427 * required.
428 */
sakalbb584352016-11-28 08:53:44 -0800429 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 02:43:10 -0700430 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 08:30:05 -0800431 }
432
433 /**
434 * Register a callback to be invoked when a new video frame has been received.
435 *
sakald1516522017-03-13 05:11:48 -0700436 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
437 * It should be lightweight and must not call removeFrameListener.
sakal3a9bc172016-11-30 08:30:05 -0800438 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
439 * required.
sakald1516522017-03-13 05:11:48 -0700440 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 08:30:05 -0800441 */
442 public void addFrameListener(
sakald1516522017-03-13 05:11:48 -0700443 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 02:43:10 -0700444 addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */);
445 }
446
447 /**
448 * Register a callback to be invoked when a new video frame has been received.
449 *
450 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
451 * It should be lightweight and must not call removeFrameListener.
452 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
453 * required.
454 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
455 * @param applyFpsReduction This callback will not be called for frames that have been dropped by
456 * FPS reduction.
457 */
458 public void addFrameListener(final FrameListener listener, final float scale,
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100459 @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 01:42:43 -0700460 postToRenderThread(() -> {
461 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
462 frameListeners.add(
463 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 08:53:44 -0800464 });
sakalfb0c5732016-11-03 09:15:34 -0700465 }
466
467 /**
468 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 08:53:44 -0800469 * the queue, nothing happens. It is ensured that callback won't be called after this method
470 * returns.
sakalfb0c5732016-11-03 09:15:34 -0700471 *
472 * @param runnable The callback to remove.
473 */
sakalbb584352016-11-28 08:53:44 -0800474 public void removeFrameListener(final FrameListener listener) {
475 final CountDownLatch latch = new CountDownLatch(1);
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100476 synchronized (handlerLock) {
477 if (renderThreadHandler == null) {
478 return;
sakalfb0c5732016-11-03 09:15:34 -0700479 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100480 if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) {
481 throw new RuntimeException("removeFrameListener must not be called on the render thread.");
482 }
483 postToRenderThread(() -> {
484 latch.countDown();
485 final Iterator<FrameListenerAndParams> iter = frameListeners.iterator();
486 while (iter.hasNext()) {
487 if (iter.next().listener == listener) {
488 iter.remove();
489 }
490 }
491 });
492 }
sakalbb584352016-11-28 08:53:44 -0800493 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 09:15:34 -0700494 }
495
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200496 /** Can be set in order to be notified about errors encountered during rendering. */
497 public void setErrorCallback(ErrorCallback errorCallback) {
498 this.errorCallback = errorCallback;
499 }
500
sakal6bdcefc2017-08-15 01:56:02 -0700501 // VideoSink interface.
502 @Override
503 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 05:32:35 -0700504 synchronized (statisticsLock) {
505 ++framesReceived;
506 }
magjed9ab8a182016-10-20 03:18:09 -0700507 final boolean dropOldFrame;
magjeddf494b02016-10-07 05:32:35 -0700508 synchronized (handlerLock) {
509 if (renderThreadHandler == null) {
510 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 05:32:35 -0700511 return;
512 }
magjed9ab8a182016-10-20 03:18:09 -0700513 synchronized (frameLock) {
514 dropOldFrame = (pendingFrame != null);
515 if (dropOldFrame) {
sakal6bdcefc2017-08-15 01:56:02 -0700516 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700517 }
518 pendingFrame = frame;
sakal6bdcefc2017-08-15 01:56:02 -0700519 pendingFrame.retain();
sakalbf080602017-08-11 01:42:43 -0700520 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 05:32:35 -0700521 }
522 }
magjed9ab8a182016-10-20 03:18:09 -0700523 if (dropOldFrame) {
524 synchronized (statisticsLock) {
525 ++framesDropped;
526 }
527 }
magjeddf494b02016-10-07 05:32:35 -0700528 }
529
530 /**
531 * Release EGL surface. This function will block until the EGL surface is released.
532 */
sakal28ec6bd2016-11-09 01:47:12 -0800533 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 05:32:35 -0700534 // Ensure that the render thread is no longer touching the Surface before returning from this
535 // function.
536 eglSurfaceCreationRunnable.setSurface(null /* surface */);
537 synchronized (handlerLock) {
538 if (renderThreadHandler != null) {
539 renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable);
sakalbf080602017-08-11 01:42:43 -0700540 renderThreadHandler.postAtFrontOfQueue(() -> {
541 if (eglBase != null) {
542 eglBase.detachCurrent();
543 eglBase.releaseSurface();
magjeddf494b02016-10-07 05:32:35 -0700544 }
sakalbf080602017-08-11 01:42:43 -0700545 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700546 });
sakal28ec6bd2016-11-09 01:47:12 -0800547 return;
magjeddf494b02016-10-07 05:32:35 -0700548 }
549 }
sakal28ec6bd2016-11-09 01:47:12 -0800550 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700551 }
552
553 /**
magjeddf494b02016-10-07 05:32:35 -0700554 * Private helper function to post tasks safely.
555 */
magjed9ab8a182016-10-20 03:18:09 -0700556 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 05:32:35 -0700557 synchronized (handlerLock) {
558 if (renderThreadHandler != null) {
559 renderThreadHandler.post(runnable);
560 }
561 }
562 }
563
sakalf25a2202017-05-04 06:06:56 -0700564 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 05:32:35 -0700565 if (eglBase != null && eglBase.hasSurface()) {
566 logD("clearSurface");
sakalf25a2202017-05-04 06:06:56 -0700567 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 05:32:35 -0700568 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
569 eglBase.swapBuffers();
570 }
571 }
572
573 /**
sakalf25a2202017-05-04 06:06:56 -0700574 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 03:18:09 -0700575 */
576 public void clearImage() {
sakalf25a2202017-05-04 06:06:56 -0700577 clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
578 }
579
580 /**
581 * Post a task to clear the surface to a specific color.
582 */
583 public void clearImage(final float r, final float g, final float b, final float a) {
magjed9ab8a182016-10-20 03:18:09 -0700584 synchronized (handlerLock) {
585 if (renderThreadHandler == null) {
586 return;
587 }
sakalbf080602017-08-11 01:42:43 -0700588 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 03:18:09 -0700589 }
590 }
591
592 /**
magjeddf494b02016-10-07 05:32:35 -0700593 * Renders and releases |pendingFrame|.
594 */
595 private void renderFrameOnRenderThread() {
596 // Fetch and render |pendingFrame|.
sakal6bdcefc2017-08-15 01:56:02 -0700597 final VideoFrame frame;
magjeddf494b02016-10-07 05:32:35 -0700598 synchronized (frameLock) {
599 if (pendingFrame == null) {
600 return;
601 }
602 frame = pendingFrame;
603 pendingFrame = null;
604 }
605 if (eglBase == null || !eglBase.hasSurface()) {
606 logD("Dropping frame - No surface");
sakal6bdcefc2017-08-15 01:56:02 -0700607 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700608 return;
609 }
sakald1516522017-03-13 05:11:48 -0700610 // Check if fps reduction is active.
611 final boolean shouldRenderFrame;
612 synchronized (fpsReductionLock) {
613 if (minRenderPeriodNs == Long.MAX_VALUE) {
614 // Rendering is paused.
615 shouldRenderFrame = false;
616 } else if (minRenderPeriodNs <= 0) {
617 // FPS reduction is disabled.
618 shouldRenderFrame = true;
619 } else {
620 final long currentTimeNs = System.nanoTime();
621 if (currentTimeNs < nextFrameTimeNs) {
622 logD("Skipping frame rendering - fps reduction is active.");
623 shouldRenderFrame = false;
624 } else {
625 nextFrameTimeNs += minRenderPeriodNs;
626 // The time for the next frame should always be in the future.
627 nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs);
628 shouldRenderFrame = true;
629 }
630 }
631 }
magjeddf494b02016-10-07 05:32:35 -0700632
633 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700634
sakal6bdcefc2017-08-15 01:56:02 -0700635 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
636 final float drawnAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700637 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 01:56:02 -0700638 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700639 }
640
sakal6bdcefc2017-08-15 01:56:02 -0700641 final float scaleX;
642 final float scaleY;
643
644 if (frameAspectRatio > drawnAspectRatio) {
645 scaleX = drawnAspectRatio / frameAspectRatio;
646 scaleY = 1f;
647 } else {
648 scaleX = 1f;
649 scaleY = frameAspectRatio / drawnAspectRatio;
650 }
651
magjed7cede372017-09-11 06:12:07 -0700652 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700653 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100654 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 01:56:02 -0700655 drawMatrix.preScale(scaleX, scaleY);
656 drawMatrix.preTranslate(-0.5f, -0.5f);
657
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200658 try {
659 if (shouldRenderFrame) {
660 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
661 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
662 frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */,
663 eglBase.surfaceWidth(), eglBase.surfaceHeight());
sakald1516522017-03-13 05:11:48 -0700664
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200665 final long swapBuffersStartTimeNs = System.nanoTime();
666 if (usePresentationTimeStamp) {
667 eglBase.swapBuffers(frame.getTimestampNs());
668 } else {
669 eglBase.swapBuffers();
670 }
671
672 final long currentTimeNs = System.nanoTime();
673 synchronized (statisticsLock) {
674 ++framesRendered;
675 renderTimeNs += (currentTimeNs - startTimeNs);
676 renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs);
677 }
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100678 }
sakald1516522017-03-13 05:11:48 -0700679
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200680 notifyCallbacks(frame, shouldRenderFrame);
681 } catch (GlUtil.GlOutOfMemoryException e) {
682 logE("Error while drawing frame", e);
683 final ErrorCallback errorCallback = this.errorCallback;
684 if (errorCallback != null) {
685 errorCallback.onGlOutOfMemory();
sakald1516522017-03-13 05:11:48 -0700686 }
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200687 // Attempt to free up some resources.
688 drawer.release();
689 frameDrawer.release();
690 bitmapTextureFramebuffer.release();
691 // Continue here on purpose and retry again for next frame. In worst case, this is a continous
692 // problem and no more frames will be drawn.
693 } finally {
694 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700695 }
sakalfb0c5732016-11-03 09:15:34 -0700696 }
697
magjed7cede372017-09-11 06:12:07 -0700698 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 08:53:44 -0800699 if (frameListeners.isEmpty())
700 return;
sakalfb0c5732016-11-03 09:15:34 -0700701
magjed7cede372017-09-11 06:12:07 -0700702 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700703 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100704 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 01:56:02 -0700705 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
706 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 09:15:34 -0700707
sakal8fdf9572017-05-31 02:43:10 -0700708 Iterator<FrameListenerAndParams> it = frameListeners.iterator();
709 while (it.hasNext()) {
710 FrameListenerAndParams listenerAndParams = it.next();
711 if (!wasRendered && listenerAndParams.applyFpsReduction) {
712 continue;
713 }
714 it.remove();
715
sakal6bdcefc2017-08-15 01:56:02 -0700716 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
717 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 09:15:34 -0700718
719 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 08:30:05 -0800720 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 09:15:34 -0700721 continue;
722 }
723
sakalfb0c5732016-11-03 09:15:34 -0700724 bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);
725
726 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
727 GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
728 GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);
729
sakal103988d2017-02-17 09:59:01 -0800730 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
731 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700732 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
733 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 09:15:34 -0700734
735 final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
736 GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
737 GLES20.glReadPixels(
738 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);
739
740 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
741 GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");
742
743 final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
744 bitmap.copyPixelsFromBuffer(bitmapBuffer);
sakal3a9bc172016-11-30 08:30:05 -0800745 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 09:15:34 -0700746 }
magjeddf494b02016-10-07 05:32:35 -0700747 }
748
magjed9ab8a182016-10-20 03:18:09 -0700749 private String averageTimeAsString(long sumTimeNs, int count) {
Magnus Jedvert3bc696f2018-11-12 11:35:20 +0100750 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " us";
magjed9ab8a182016-10-20 03:18:09 -0700751 }
752
magjeddf494b02016-10-07 05:32:35 -0700753 private void logStatistics() {
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200754 final DecimalFormat fpsFormat = new DecimalFormat("#.0");
magjed9ab8a182016-10-20 03:18:09 -0700755 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700756 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700757 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
758 if (elapsedTimeNs <= 0) {
759 return;
magjeddf494b02016-10-07 05:32:35 -0700760 }
magjed9ab8a182016-10-20 03:18:09 -0700761 final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs;
762 logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms."
763 + " Frames received: " + framesReceived + "."
764 + " Dropped: " + framesDropped + "."
765 + " Rendered: " + framesRendered + "."
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200766 + " Render fps: " + fpsFormat.format(renderFps) + "."
magjed9ab8a182016-10-20 03:18:09 -0700767 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
768 + " Average swapBuffer time: "
769 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
770 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 05:32:35 -0700771 }
772 }
773
Magnus Jedvertecae9cd2019-07-05 14:33:12 +0200774 private void logE(String string, Throwable e) {
775 Logging.e(TAG, name + string, e);
776 }
777
magjeddf494b02016-10-07 05:32:35 -0700778 private void logD(String string) {
779 Logging.d(TAG, name + string);
780 }
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100781
782 private void logW(String string) {
783 Logging.w(TAG, name + string);
784 }
magjeddf494b02016-10-07 05:32:35 -0700785}