blob: d87c5178f105347ea3e42169764d860363c5a385 [file] [log] [blame]
magjeddf494b02016-10-07 05:32:35 -07001/*
2 * Copyright 2016 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11package org.webrtc;
12
sakalfb0c5732016-11-03 09:15:34 -070013import android.graphics.Bitmap;
sakal6bdcefc2017-08-15 01:56:02 -070014import android.graphics.Matrix;
magjed9ab8a182016-10-20 03:18:09 -070015import android.graphics.SurfaceTexture;
magjeddf494b02016-10-07 05:32:35 -070016import android.opengl.GLES20;
17import android.os.Handler;
18import android.os.HandlerThread;
19import android.os.Looper;
Sami Kalliomäki0d26c992018-10-19 12:53:21 +020020import android.os.Message;
Artem Titarenko69540f42018-12-10 12:30:46 +010021import android.support.annotation.Nullable;
magjeddf494b02016-10-07 05:32:35 -070022import android.view.Surface;
sakalfb0c5732016-11-03 09:15:34 -070023import java.nio.ByteBuffer;
Sami Kalliomäki1659e972018-06-04 14:07:58 +020024import java.text.DecimalFormat;
sakalfb0c5732016-11-03 09:15:34 -070025import java.util.ArrayList;
26import java.util.Iterator;
magjeddf494b02016-10-07 05:32:35 -070027import java.util.concurrent.CountDownLatch;
28import java.util.concurrent.TimeUnit;
29
30/**
Magnus Jedvert431f14e2018-06-09 19:41:58 +020031 * Implements VideoSink by displaying the video stream on an EGL Surface. This class is intended to
32 * be used as a helper class for rendering on SurfaceViews and TextureViews.
magjeddf494b02016-10-07 05:32:35 -070033 */
Magnus Jedvert431f14e2018-06-09 19:41:58 +020034public class EglRenderer implements VideoSink {
magjeddf494b02016-10-07 05:32:35 -070035 private static final String TAG = "EglRenderer";
magjed9ab8a182016-10-20 03:18:09 -070036 private static final long LOG_INTERVAL_SEC = 4;
magjeddf494b02016-10-07 05:32:35 -070037
sakalfb0c5732016-11-03 09:15:34 -070038 public interface FrameListener { void onFrame(Bitmap frame); }
39
sakal3a9bc172016-11-30 08:30:05 -080040 private static class FrameListenerAndParams {
sakalfb0c5732016-11-03 09:15:34 -070041 public final FrameListener listener;
sakal3a9bc172016-11-30 08:30:05 -080042 public final float scale;
43 public final RendererCommon.GlDrawer drawer;
sakal8fdf9572017-05-31 02:43:10 -070044 public final boolean applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070045
sakal8fdf9572017-05-31 02:43:10 -070046 public FrameListenerAndParams(FrameListener listener, float scale,
47 RendererCommon.GlDrawer drawer, boolean applyFpsReduction) {
sakalfb0c5732016-11-03 09:15:34 -070048 this.listener = listener;
sakal3a9bc172016-11-30 08:30:05 -080049 this.scale = scale;
50 this.drawer = drawer;
sakal8fdf9572017-05-31 02:43:10 -070051 this.applyFpsReduction = applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070052 }
53 }
54
magjeddf494b02016-10-07 05:32:35 -070055 private class EglSurfaceCreation implements Runnable {
magjed9ab8a182016-10-20 03:18:09 -070056 private Object surface;
magjeddf494b02016-10-07 05:32:35 -070057
Mirko Bonadei12251b62017-11-05 19:35:31 -080058 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
59 @SuppressWarnings("NoSynchronizedMethodCheck")
magjed9ab8a182016-10-20 03:18:09 -070060 public synchronized void setSurface(Object surface) {
magjeddf494b02016-10-07 05:32:35 -070061 this.surface = surface;
62 }
63
64 @Override
Mirko Bonadei12251b62017-11-05 19:35:31 -080065 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
66 @SuppressWarnings("NoSynchronizedMethodCheck")
magjeddf494b02016-10-07 05:32:35 -070067 public synchronized void run() {
68 if (surface != null && eglBase != null && !eglBase.hasSurface()) {
magjed9ab8a182016-10-20 03:18:09 -070069 if (surface instanceof Surface) {
70 eglBase.createSurface((Surface) surface);
71 } else if (surface instanceof SurfaceTexture) {
72 eglBase.createSurface((SurfaceTexture) surface);
73 } else {
74 throw new IllegalStateException("Invalid surface: " + surface);
75 }
magjeddf494b02016-10-07 05:32:35 -070076 eglBase.makeCurrent();
77 // Necessary for YUV frames with odd width.
78 GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
79 }
80 }
81 }
82
Sami Kalliomäki0d26c992018-10-19 12:53:21 +020083 /**
84 * Handler that triggers a callback when an uncaught exception happens when handling a message.
85 */
86 private static class HandlerWithExceptionCallback extends Handler {
87 private final Runnable exceptionCallback;
88
89 public HandlerWithExceptionCallback(Looper looper, Runnable exceptionCallback) {
90 super(looper);
91 this.exceptionCallback = exceptionCallback;
92 }
93
94 @Override
95 public void dispatchMessage(Message msg) {
96 try {
97 super.dispatchMessage(msg);
98 } catch (Exception e) {
99 Logging.e(TAG, "Exception on EglRenderer thread", e);
100 exceptionCallback.run();
101 throw e;
102 }
103 }
104 }
105
Xiaolei Yu149533a2017-11-03 07:55:01 +0800106 protected final String name;
magjeddf494b02016-10-07 05:32:35 -0700107
108 // |renderThreadHandler| is a handler for communicating with |renderThread|, and is synchronized
109 // on |handlerLock|.
110 private final Object handlerLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100111 @Nullable private Handler renderThreadHandler;
magjeddf494b02016-10-07 05:32:35 -0700112
sakal3a9bc172016-11-30 08:30:05 -0800113 private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>();
sakalfb0c5732016-11-03 09:15:34 -0700114
magjed9ab8a182016-10-20 03:18:09 -0700115 // Variables for fps reduction.
116 private final Object fpsReductionLock = new Object();
117 // Time for when next frame should be rendered.
118 private long nextFrameTimeNs;
119 // Minimum duration between frames when fps reduction is active, or -1 if video is completely
120 // paused.
121 private long minRenderPeriodNs;
122
magjeddf494b02016-10-07 05:32:35 -0700123 // EGL and GL resources for drawing YUV/OES textures. After initilization, these are only accessed
124 // from the render thread.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100125 @Nullable private EglBase eglBase;
magjed7cede372017-09-11 06:12:07 -0700126 private final VideoFrameDrawer frameDrawer = new VideoFrameDrawer();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100127 @Nullable private RendererCommon.GlDrawer drawer;
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100128 private boolean usePresentationTimeStamp;
magjed7cede372017-09-11 06:12:07 -0700129 private final Matrix drawMatrix = new Matrix();
magjeddf494b02016-10-07 05:32:35 -0700130
131 // Pending frame to render. Serves as a queue with size 1. Synchronized on |frameLock|.
132 private final Object frameLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100133 @Nullable private VideoFrame pendingFrame;
magjeddf494b02016-10-07 05:32:35 -0700134
135 // These variables are synchronized on |layoutLock|.
136 private final Object layoutLock = new Object();
magjeddf494b02016-10-07 05:32:35 -0700137 private float layoutAspectRatio;
138 // If true, mirrors the video stream horizontally.
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100139 private boolean mirrorHorizontally;
140 // If true, mirrors the video stream vertically.
141 private boolean mirrorVertically;
magjeddf494b02016-10-07 05:32:35 -0700142
143 // These variables are synchronized on |statisticsLock|.
144 private final Object statisticsLock = new Object();
145 // Total number of video frames received in renderFrame() call.
146 private int framesReceived;
147 // Number of video frames dropped by renderFrame() because previous frame has not been rendered
148 // yet.
149 private int framesDropped;
150 // Number of rendered video frames.
151 private int framesRendered;
magjed9ab8a182016-10-20 03:18:09 -0700152 // Start time for counting these statistics, or 0 if we haven't started measuring yet.
153 private long statisticsStartTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700154 // Time in ns spent in renderFrameOnRenderThread() function.
155 private long renderTimeNs;
magjed9ab8a182016-10-20 03:18:09 -0700156 // Time in ns spent by the render thread in the swapBuffers() function.
157 private long renderSwapBufferTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700158
sakalfb0c5732016-11-03 09:15:34 -0700159 // Used for bitmap capturing.
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200160 private final GlTextureFrameBuffer bitmapTextureFramebuffer =
161 new GlTextureFrameBuffer(GLES20.GL_RGBA);
sakalfb0c5732016-11-03 09:15:34 -0700162
magjed9ab8a182016-10-20 03:18:09 -0700163 private final Runnable logStatisticsRunnable = new Runnable() {
164 @Override
165 public void run() {
166 logStatistics();
167 synchronized (handlerLock) {
168 if (renderThreadHandler != null) {
169 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
170 renderThreadHandler.postDelayed(
171 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
172 }
173 }
174 }
175 };
176
magjeddf494b02016-10-07 05:32:35 -0700177 private final EglSurfaceCreation eglSurfaceCreationRunnable = new EglSurfaceCreation();
178
179 /**
180 * Standard constructor. The name will be used for the render thread name and included when
181 * logging. In order to render something, you must first call init() and createEglSurface.
182 */
183 public EglRenderer(String name) {
184 this.name = name;
185 }
186
187 /**
188 * Initialize this class, sharing resources with |sharedContext|. The custom |drawer| will be used
189 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
190 * |drawer|. It is allowed to call init() to reinitialize the renderer after a previous
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100191 * init()/release() cycle. If usePresentationTimeStamp is true, eglPresentationTimeANDROID will be
192 * set with the frame timestamps, which specifies desired presentation time and might be useful
193 * for e.g. syncing audio and video.
magjeddf494b02016-10-07 05:32:35 -0700194 */
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100195 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100196 RendererCommon.GlDrawer drawer, boolean usePresentationTimeStamp) {
magjeddf494b02016-10-07 05:32:35 -0700197 synchronized (handlerLock) {
198 if (renderThreadHandler != null) {
199 throw new IllegalStateException(name + "Already initialized");
200 }
201 logD("Initializing EglRenderer");
202 this.drawer = drawer;
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100203 this.usePresentationTimeStamp = usePresentationTimeStamp;
magjeddf494b02016-10-07 05:32:35 -0700204
205 final HandlerThread renderThread = new HandlerThread(name + "EglRenderer");
206 renderThread.start();
Sami Kalliomäki0d26c992018-10-19 12:53:21 +0200207 renderThreadHandler =
208 new HandlerWithExceptionCallback(renderThread.getLooper(), new Runnable() {
209 @Override
210 public void run() {
211 synchronized (handlerLock) {
212 renderThreadHandler = null;
213 }
214 }
215 });
magjeddf494b02016-10-07 05:32:35 -0700216 // Create EGL context on the newly created render thread. It should be possibly to create the
217 // context on this thread and make it current on the render thread, but this causes failure on
218 // some Marvel based JB devices. https://bugs.chromium.org/p/webrtc/issues/detail?id=6350.
sakalbf080602017-08-11 01:42:43 -0700219 ThreadUtils.invokeAtFrontUninterruptibly(renderThreadHandler, () -> {
220 // If sharedContext is null, then texture frames are disabled. This is typically for old
221 // devices that might not be fully spec compliant, so force EGL 1.0 since EGL 1.4 has
222 // caused trouble on some weird devices.
223 if (sharedContext == null) {
224 logD("EglBase10.create context");
225 eglBase = EglBase.createEgl10(configAttributes);
226 } else {
227 logD("EglBase.create shared context");
228 eglBase = EglBase.create(sharedContext, configAttributes);
magjeddf494b02016-10-07 05:32:35 -0700229 }
230 });
magjed9ab8a182016-10-20 03:18:09 -0700231 renderThreadHandler.post(eglSurfaceCreationRunnable);
232 final long currentTimeNs = System.nanoTime();
233 resetStatistics(currentTimeNs);
234 renderThreadHandler.postDelayed(
235 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
magjeddf494b02016-10-07 05:32:35 -0700236 }
237 }
238
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100239 /**
240 * Same as above with usePresentationTimeStamp set to false.
241 *
242 * @see #init(EglBase.Context, int[], RendererCommon.GlDrawer, boolean)
243 */
244 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
245 RendererCommon.GlDrawer drawer) {
246 init(sharedContext, configAttributes, drawer, /* usePresentationTimeStamp= */ false);
247 }
248
magjeddf494b02016-10-07 05:32:35 -0700249 public void createEglSurface(Surface surface) {
magjed9ab8a182016-10-20 03:18:09 -0700250 createEglSurfaceInternal(surface);
251 }
252
253 public void createEglSurface(SurfaceTexture surfaceTexture) {
254 createEglSurfaceInternal(surfaceTexture);
255 }
256
257 private void createEglSurfaceInternal(Object surface) {
magjeddf494b02016-10-07 05:32:35 -0700258 eglSurfaceCreationRunnable.setSurface(surface);
magjed9ab8a182016-10-20 03:18:09 -0700259 postToRenderThread(eglSurfaceCreationRunnable);
magjeddf494b02016-10-07 05:32:35 -0700260 }
261
262 /**
263 * Block until any pending frame is returned and all GL resources released, even if an interrupt
264 * occurs. If an interrupt occurs during release(), the interrupt flag will be set. This function
265 * should be called before the Activity is destroyed and the EGLContext is still valid. If you
266 * don't call this function, the GL resources might leak.
267 */
268 public void release() {
magjed9ab8a182016-10-20 03:18:09 -0700269 logD("Releasing.");
magjeddf494b02016-10-07 05:32:35 -0700270 final CountDownLatch eglCleanupBarrier = new CountDownLatch(1);
271 synchronized (handlerLock) {
272 if (renderThreadHandler == null) {
273 logD("Already released");
274 return;
275 }
magjed9ab8a182016-10-20 03:18:09 -0700276 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
magjeddf494b02016-10-07 05:32:35 -0700277 // Release EGL and GL resources on render thread.
sakalbf080602017-08-11 01:42:43 -0700278 renderThreadHandler.postAtFrontOfQueue(() -> {
Magnus Jedvert94c0f262018-12-12 17:35:28 +0100279 // Detach current shader program.
280 GLES20.glUseProgram(/* program= */ 0);
sakalbf080602017-08-11 01:42:43 -0700281 if (drawer != null) {
282 drawer.release();
283 drawer = null;
magjeddf494b02016-10-07 05:32:35 -0700284 }
magjed7cede372017-09-11 06:12:07 -0700285 frameDrawer.release();
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200286 bitmapTextureFramebuffer.release();
sakalbf080602017-08-11 01:42:43 -0700287 if (eglBase != null) {
288 logD("eglBase detach and release.");
289 eglBase.detachCurrent();
290 eglBase.release();
291 eglBase = null;
292 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100293 frameListeners.clear();
sakalbf080602017-08-11 01:42:43 -0700294 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 05:32:35 -0700295 });
296 final Looper renderLooper = renderThreadHandler.getLooper();
297 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 01:42:43 -0700298 renderThreadHandler.post(() -> {
299 logD("Quitting render thread.");
300 renderLooper.quit();
magjeddf494b02016-10-07 05:32:35 -0700301 });
302 // Don't accept any more frames or messages to the render thread.
303 renderThreadHandler = null;
304 }
305 // Make sure the EGL/GL cleanup posted above is executed.
306 ThreadUtils.awaitUninterruptibly(eglCleanupBarrier);
307 synchronized (frameLock) {
308 if (pendingFrame != null) {
sakal6bdcefc2017-08-15 01:56:02 -0700309 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700310 pendingFrame = null;
311 }
312 }
magjeddf494b02016-10-07 05:32:35 -0700313 logD("Releasing done.");
314 }
315
316 /**
magjed9ab8a182016-10-20 03:18:09 -0700317 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 05:32:35 -0700318 */
magjed9ab8a182016-10-20 03:18:09 -0700319 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 05:32:35 -0700320 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700321 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700322 framesReceived = 0;
323 framesDropped = 0;
324 framesRendered = 0;
magjeddf494b02016-10-07 05:32:35 -0700325 renderTimeNs = 0;
magjed9ab8a182016-10-20 03:18:09 -0700326 renderSwapBufferTimeNs = 0;
327 }
328 }
329
330 public void printStackTrace() {
331 synchronized (handlerLock) {
332 final Thread renderThread =
333 (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread();
334 if (renderThread != null) {
335 final StackTraceElement[] renderStackTrace = renderThread.getStackTrace();
336 if (renderStackTrace.length > 0) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100337 logW("EglRenderer stack trace:");
magjed9ab8a182016-10-20 03:18:09 -0700338 for (StackTraceElement traceElem : renderStackTrace) {
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100339 logW(traceElem.toString());
magjed9ab8a182016-10-20 03:18:09 -0700340 }
341 }
342 }
magjeddf494b02016-10-07 05:32:35 -0700343 }
344 }
345
346 /**
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100347 * Set if the video stream should be mirrored horizontally or not.
magjeddf494b02016-10-07 05:32:35 -0700348 */
349 public void setMirror(final boolean mirror) {
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100350 logD("setMirrorHorizontally: " + mirror);
magjeddf494b02016-10-07 05:32:35 -0700351 synchronized (layoutLock) {
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100352 this.mirrorHorizontally = mirror;
353 }
354 }
355
356 /**
357 * Set if the video stream should be mirrored vertically or not.
358 */
359 public void setMirrorVertically(final boolean mirrorVertically) {
360 logD("setMirrorVertically: " + mirrorVertically);
361 synchronized (layoutLock) {
362 this.mirrorVertically = mirrorVertically;
magjeddf494b02016-10-07 05:32:35 -0700363 }
364 }
365
366 /**
367 * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video.
368 * Set this to 0 to disable cropping.
369 */
370 public void setLayoutAspectRatio(float layoutAspectRatio) {
371 logD("setLayoutAspectRatio: " + layoutAspectRatio);
372 synchronized (layoutLock) {
373 this.layoutAspectRatio = layoutAspectRatio;
374 }
375 }
376
magjed9ab8a182016-10-20 03:18:09 -0700377 /**
378 * Limit render framerate.
379 *
380 * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps
381 * reduction.
382 */
383 public void setFpsReduction(float fps) {
384 logD("setFpsReduction: " + fps);
385 synchronized (fpsReductionLock) {
386 final long previousRenderPeriodNs = minRenderPeriodNs;
387 if (fps <= 0) {
388 minRenderPeriodNs = Long.MAX_VALUE;
389 } else {
390 minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps);
391 }
392 if (minRenderPeriodNs != previousRenderPeriodNs) {
393 // Fps reduction changed - reset frame time.
394 nextFrameTimeNs = System.nanoTime();
395 }
396 }
397 }
398
399 public void disableFpsReduction() {
400 setFpsReduction(Float.POSITIVE_INFINITY /* fps */);
401 }
402
403 public void pauseVideo() {
404 setFpsReduction(0 /* fps */);
405 }
406
sakalfb0c5732016-11-03 09:15:34 -0700407 /**
sakal3a9bc172016-11-30 08:30:05 -0800408 * Register a callback to be invoked when a new video frame has been received. This version uses
409 * the drawer of the EglRenderer that was passed in init.
sakalfb0c5732016-11-03 09:15:34 -0700410 *
sakald1516522017-03-13 05:11:48 -0700411 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
412 * It should be lightweight and must not call removeFrameListener.
sakalfb0c5732016-11-03 09:15:34 -0700413 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
414 * required.
415 */
sakalbb584352016-11-28 08:53:44 -0800416 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 02:43:10 -0700417 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 08:30:05 -0800418 }
419
420 /**
421 * Register a callback to be invoked when a new video frame has been received.
422 *
sakald1516522017-03-13 05:11:48 -0700423 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
424 * It should be lightweight and must not call removeFrameListener.
sakal3a9bc172016-11-30 08:30:05 -0800425 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
426 * required.
sakald1516522017-03-13 05:11:48 -0700427 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 08:30:05 -0800428 */
429 public void addFrameListener(
sakald1516522017-03-13 05:11:48 -0700430 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 02:43:10 -0700431 addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */);
432 }
433
434 /**
435 * Register a callback to be invoked when a new video frame has been received.
436 *
437 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
438 * It should be lightweight and must not call removeFrameListener.
439 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
440 * required.
441 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
442 * @param applyFpsReduction This callback will not be called for frames that have been dropped by
443 * FPS reduction.
444 */
445 public void addFrameListener(final FrameListener listener, final float scale,
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100446 @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 01:42:43 -0700447 postToRenderThread(() -> {
448 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
449 frameListeners.add(
450 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 08:53:44 -0800451 });
sakalfb0c5732016-11-03 09:15:34 -0700452 }
453
454 /**
455 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 08:53:44 -0800456 * the queue, nothing happens. It is ensured that callback won't be called after this method
457 * returns.
sakalfb0c5732016-11-03 09:15:34 -0700458 *
459 * @param runnable The callback to remove.
460 */
sakalbb584352016-11-28 08:53:44 -0800461 public void removeFrameListener(final FrameListener listener) {
462 final CountDownLatch latch = new CountDownLatch(1);
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100463 synchronized (handlerLock) {
464 if (renderThreadHandler == null) {
465 return;
sakalfb0c5732016-11-03 09:15:34 -0700466 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100467 if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) {
468 throw new RuntimeException("removeFrameListener must not be called on the render thread.");
469 }
470 postToRenderThread(() -> {
471 latch.countDown();
472 final Iterator<FrameListenerAndParams> iter = frameListeners.iterator();
473 while (iter.hasNext()) {
474 if (iter.next().listener == listener) {
475 iter.remove();
476 }
477 }
478 });
479 }
sakalbb584352016-11-28 08:53:44 -0800480 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 09:15:34 -0700481 }
482
sakal6bdcefc2017-08-15 01:56:02 -0700483 // VideoSink interface.
484 @Override
485 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 05:32:35 -0700486 synchronized (statisticsLock) {
487 ++framesReceived;
488 }
magjed9ab8a182016-10-20 03:18:09 -0700489 final boolean dropOldFrame;
magjeddf494b02016-10-07 05:32:35 -0700490 synchronized (handlerLock) {
491 if (renderThreadHandler == null) {
492 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 05:32:35 -0700493 return;
494 }
magjed9ab8a182016-10-20 03:18:09 -0700495 synchronized (frameLock) {
496 dropOldFrame = (pendingFrame != null);
497 if (dropOldFrame) {
sakal6bdcefc2017-08-15 01:56:02 -0700498 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700499 }
500 pendingFrame = frame;
sakal6bdcefc2017-08-15 01:56:02 -0700501 pendingFrame.retain();
sakalbf080602017-08-11 01:42:43 -0700502 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 05:32:35 -0700503 }
504 }
magjed9ab8a182016-10-20 03:18:09 -0700505 if (dropOldFrame) {
506 synchronized (statisticsLock) {
507 ++framesDropped;
508 }
509 }
magjeddf494b02016-10-07 05:32:35 -0700510 }
511
512 /**
513 * Release EGL surface. This function will block until the EGL surface is released.
514 */
sakal28ec6bd2016-11-09 01:47:12 -0800515 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 05:32:35 -0700516 // Ensure that the render thread is no longer touching the Surface before returning from this
517 // function.
518 eglSurfaceCreationRunnable.setSurface(null /* surface */);
519 synchronized (handlerLock) {
520 if (renderThreadHandler != null) {
521 renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable);
sakalbf080602017-08-11 01:42:43 -0700522 renderThreadHandler.postAtFrontOfQueue(() -> {
523 if (eglBase != null) {
524 eglBase.detachCurrent();
525 eglBase.releaseSurface();
magjeddf494b02016-10-07 05:32:35 -0700526 }
sakalbf080602017-08-11 01:42:43 -0700527 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700528 });
sakal28ec6bd2016-11-09 01:47:12 -0800529 return;
magjeddf494b02016-10-07 05:32:35 -0700530 }
531 }
sakal28ec6bd2016-11-09 01:47:12 -0800532 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700533 }
534
535 /**
magjeddf494b02016-10-07 05:32:35 -0700536 * Private helper function to post tasks safely.
537 */
magjed9ab8a182016-10-20 03:18:09 -0700538 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 05:32:35 -0700539 synchronized (handlerLock) {
540 if (renderThreadHandler != null) {
541 renderThreadHandler.post(runnable);
542 }
543 }
544 }
545
sakalf25a2202017-05-04 06:06:56 -0700546 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 05:32:35 -0700547 if (eglBase != null && eglBase.hasSurface()) {
548 logD("clearSurface");
sakalf25a2202017-05-04 06:06:56 -0700549 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 05:32:35 -0700550 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
551 eglBase.swapBuffers();
552 }
553 }
554
555 /**
sakalf25a2202017-05-04 06:06:56 -0700556 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 03:18:09 -0700557 */
558 public void clearImage() {
sakalf25a2202017-05-04 06:06:56 -0700559 clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
560 }
561
562 /**
563 * Post a task to clear the surface to a specific color.
564 */
565 public void clearImage(final float r, final float g, final float b, final float a) {
magjed9ab8a182016-10-20 03:18:09 -0700566 synchronized (handlerLock) {
567 if (renderThreadHandler == null) {
568 return;
569 }
sakalbf080602017-08-11 01:42:43 -0700570 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 03:18:09 -0700571 }
572 }
573
574 /**
magjeddf494b02016-10-07 05:32:35 -0700575 * Renders and releases |pendingFrame|.
576 */
577 private void renderFrameOnRenderThread() {
578 // Fetch and render |pendingFrame|.
sakal6bdcefc2017-08-15 01:56:02 -0700579 final VideoFrame frame;
magjeddf494b02016-10-07 05:32:35 -0700580 synchronized (frameLock) {
581 if (pendingFrame == null) {
582 return;
583 }
584 frame = pendingFrame;
585 pendingFrame = null;
586 }
587 if (eglBase == null || !eglBase.hasSurface()) {
588 logD("Dropping frame - No surface");
sakal6bdcefc2017-08-15 01:56:02 -0700589 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700590 return;
591 }
sakald1516522017-03-13 05:11:48 -0700592 // Check if fps reduction is active.
593 final boolean shouldRenderFrame;
594 synchronized (fpsReductionLock) {
595 if (minRenderPeriodNs == Long.MAX_VALUE) {
596 // Rendering is paused.
597 shouldRenderFrame = false;
598 } else if (minRenderPeriodNs <= 0) {
599 // FPS reduction is disabled.
600 shouldRenderFrame = true;
601 } else {
602 final long currentTimeNs = System.nanoTime();
603 if (currentTimeNs < nextFrameTimeNs) {
604 logD("Skipping frame rendering - fps reduction is active.");
605 shouldRenderFrame = false;
606 } else {
607 nextFrameTimeNs += minRenderPeriodNs;
608 // The time for the next frame should always be in the future.
609 nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs);
610 shouldRenderFrame = true;
611 }
612 }
613 }
magjeddf494b02016-10-07 05:32:35 -0700614
615 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700616
sakal6bdcefc2017-08-15 01:56:02 -0700617 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
618 final float drawnAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700619 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 01:56:02 -0700620 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700621 }
622
sakal6bdcefc2017-08-15 01:56:02 -0700623 final float scaleX;
624 final float scaleY;
625
626 if (frameAspectRatio > drawnAspectRatio) {
627 scaleX = drawnAspectRatio / frameAspectRatio;
628 scaleY = 1f;
629 } else {
630 scaleX = 1f;
631 scaleY = frameAspectRatio / drawnAspectRatio;
632 }
633
magjed7cede372017-09-11 06:12:07 -0700634 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700635 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100636 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 01:56:02 -0700637 drawMatrix.preScale(scaleX, scaleY);
638 drawMatrix.preTranslate(-0.5f, -0.5f);
639
sakald1516522017-03-13 05:11:48 -0700640 if (shouldRenderFrame) {
641 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
642 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700643 frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */,
644 eglBase.surfaceWidth(), eglBase.surfaceHeight());
sakald1516522017-03-13 05:11:48 -0700645
646 final long swapBuffersStartTimeNs = System.nanoTime();
Magnus Jedvert361dbc12018-11-06 11:32:46 +0100647 if (usePresentationTimeStamp) {
648 eglBase.swapBuffers(frame.getTimestampNs());
649 } else {
650 eglBase.swapBuffers();
651 }
sakald1516522017-03-13 05:11:48 -0700652
653 final long currentTimeNs = System.nanoTime();
654 synchronized (statisticsLock) {
655 ++framesRendered;
656 renderTimeNs += (currentTimeNs - startTimeNs);
657 renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs);
658 }
magjeddf494b02016-10-07 05:32:35 -0700659 }
660
magjed7cede372017-09-11 06:12:07 -0700661 notifyCallbacks(frame, shouldRenderFrame);
662 frame.release();
sakalfb0c5732016-11-03 09:15:34 -0700663 }
664
magjed7cede372017-09-11 06:12:07 -0700665 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 08:53:44 -0800666 if (frameListeners.isEmpty())
667 return;
sakalfb0c5732016-11-03 09:15:34 -0700668
magjed7cede372017-09-11 06:12:07 -0700669 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700670 drawMatrix.preTranslate(0.5f, 0.5f);
Magnus Jedvert3ff71de2018-12-17 10:26:12 +0100671 drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f);
sakal6bdcefc2017-08-15 01:56:02 -0700672 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
673 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 09:15:34 -0700674
sakal8fdf9572017-05-31 02:43:10 -0700675 Iterator<FrameListenerAndParams> it = frameListeners.iterator();
676 while (it.hasNext()) {
677 FrameListenerAndParams listenerAndParams = it.next();
678 if (!wasRendered && listenerAndParams.applyFpsReduction) {
679 continue;
680 }
681 it.remove();
682
sakal6bdcefc2017-08-15 01:56:02 -0700683 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
684 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 09:15:34 -0700685
686 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 08:30:05 -0800687 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 09:15:34 -0700688 continue;
689 }
690
sakalfb0c5732016-11-03 09:15:34 -0700691 bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);
692
693 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
694 GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
695 GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);
696
sakal103988d2017-02-17 09:59:01 -0800697 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
698 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700699 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
700 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 09:15:34 -0700701
702 final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
703 GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
704 GLES20.glReadPixels(
705 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);
706
707 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
708 GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");
709
710 final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
711 bitmap.copyPixelsFromBuffer(bitmapBuffer);
sakal3a9bc172016-11-30 08:30:05 -0800712 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 09:15:34 -0700713 }
magjeddf494b02016-10-07 05:32:35 -0700714 }
715
magjed9ab8a182016-10-20 03:18:09 -0700716 private String averageTimeAsString(long sumTimeNs, int count) {
Magnus Jedvert3bc696f2018-11-12 11:35:20 +0100717 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " us";
magjed9ab8a182016-10-20 03:18:09 -0700718 }
719
magjeddf494b02016-10-07 05:32:35 -0700720 private void logStatistics() {
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200721 final DecimalFormat fpsFormat = new DecimalFormat("#.0");
magjed9ab8a182016-10-20 03:18:09 -0700722 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700723 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700724 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
725 if (elapsedTimeNs <= 0) {
726 return;
magjeddf494b02016-10-07 05:32:35 -0700727 }
magjed9ab8a182016-10-20 03:18:09 -0700728 final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs;
729 logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms."
730 + " Frames received: " + framesReceived + "."
731 + " Dropped: " + framesDropped + "."
732 + " Rendered: " + framesRendered + "."
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200733 + " Render fps: " + fpsFormat.format(renderFps) + "."
magjed9ab8a182016-10-20 03:18:09 -0700734 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
735 + " Average swapBuffer time: "
736 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
737 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 05:32:35 -0700738 }
739 }
740
741 private void logD(String string) {
742 Logging.d(TAG, name + string);
743 }
Magnus Jedvert0cc11b42018-11-27 16:19:55 +0100744
745 private void logW(String string) {
746 Logging.w(TAG, name + string);
747 }
magjeddf494b02016-10-07 05:32:35 -0700748}