blob: d0a1d98b2bdefca959dcc4d854c1f69427057c0c [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;
20import android.view.Surface;
sakalfb0c5732016-11-03 09:15:34 -070021import java.nio.ByteBuffer;
Sami Kalliomäki1659e972018-06-04 14:07:58 +020022import java.text.DecimalFormat;
sakalfb0c5732016-11-03 09:15:34 -070023import java.util.ArrayList;
24import java.util.Iterator;
magjeddf494b02016-10-07 05:32:35 -070025import java.util.concurrent.CountDownLatch;
26import java.util.concurrent.TimeUnit;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010027import javax.annotation.Nullable;
magjeddf494b02016-10-07 05:32:35 -070028
29/**
Magnus Jedvert431f14e2018-06-09 19:41:58 +020030 * Implements VideoSink by displaying the video stream on an EGL Surface. This class is intended to
31 * be used as a helper class for rendering on SurfaceViews and TextureViews.
magjeddf494b02016-10-07 05:32:35 -070032 */
Magnus Jedvert431f14e2018-06-09 19:41:58 +020033public class EglRenderer implements VideoSink {
magjeddf494b02016-10-07 05:32:35 -070034 private static final String TAG = "EglRenderer";
magjed9ab8a182016-10-20 03:18:09 -070035 private static final long LOG_INTERVAL_SEC = 4;
magjeddf494b02016-10-07 05:32:35 -070036
sakalfb0c5732016-11-03 09:15:34 -070037 public interface FrameListener { void onFrame(Bitmap frame); }
38
sakal3a9bc172016-11-30 08:30:05 -080039 private static class FrameListenerAndParams {
sakalfb0c5732016-11-03 09:15:34 -070040 public final FrameListener listener;
sakal3a9bc172016-11-30 08:30:05 -080041 public final float scale;
42 public final RendererCommon.GlDrawer drawer;
sakal8fdf9572017-05-31 02:43:10 -070043 public final boolean applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070044
sakal8fdf9572017-05-31 02:43:10 -070045 public FrameListenerAndParams(FrameListener listener, float scale,
46 RendererCommon.GlDrawer drawer, boolean applyFpsReduction) {
sakalfb0c5732016-11-03 09:15:34 -070047 this.listener = listener;
sakal3a9bc172016-11-30 08:30:05 -080048 this.scale = scale;
49 this.drawer = drawer;
sakal8fdf9572017-05-31 02:43:10 -070050 this.applyFpsReduction = applyFpsReduction;
sakalfb0c5732016-11-03 09:15:34 -070051 }
52 }
53
magjeddf494b02016-10-07 05:32:35 -070054 private class EglSurfaceCreation implements Runnable {
magjed9ab8a182016-10-20 03:18:09 -070055 private Object surface;
magjeddf494b02016-10-07 05:32:35 -070056
Mirko Bonadei12251b62017-11-05 19:35:31 -080057 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
58 @SuppressWarnings("NoSynchronizedMethodCheck")
magjed9ab8a182016-10-20 03:18:09 -070059 public synchronized void setSurface(Object surface) {
magjeddf494b02016-10-07 05:32:35 -070060 this.surface = surface;
61 }
62
63 @Override
Mirko Bonadei12251b62017-11-05 19:35:31 -080064 // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression.
65 @SuppressWarnings("NoSynchronizedMethodCheck")
magjeddf494b02016-10-07 05:32:35 -070066 public synchronized void run() {
67 if (surface != null && eglBase != null && !eglBase.hasSurface()) {
magjed9ab8a182016-10-20 03:18:09 -070068 if (surface instanceof Surface) {
69 eglBase.createSurface((Surface) surface);
70 } else if (surface instanceof SurfaceTexture) {
71 eglBase.createSurface((SurfaceTexture) surface);
72 } else {
73 throw new IllegalStateException("Invalid surface: " + surface);
74 }
magjeddf494b02016-10-07 05:32:35 -070075 eglBase.makeCurrent();
76 // Necessary for YUV frames with odd width.
77 GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
78 }
79 }
80 }
81
Xiaolei Yu149533a2017-11-03 07:55:01 +080082 protected final String name;
magjeddf494b02016-10-07 05:32:35 -070083
84 // |renderThreadHandler| is a handler for communicating with |renderThread|, and is synchronized
85 // on |handlerLock|.
86 private final Object handlerLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010087 @Nullable private Handler renderThreadHandler;
magjeddf494b02016-10-07 05:32:35 -070088
sakal3a9bc172016-11-30 08:30:05 -080089 private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>();
sakalfb0c5732016-11-03 09:15:34 -070090
magjed9ab8a182016-10-20 03:18:09 -070091 // Variables for fps reduction.
92 private final Object fpsReductionLock = new Object();
93 // Time for when next frame should be rendered.
94 private long nextFrameTimeNs;
95 // Minimum duration between frames when fps reduction is active, or -1 if video is completely
96 // paused.
97 private long minRenderPeriodNs;
98
magjeddf494b02016-10-07 05:32:35 -070099 // EGL and GL resources for drawing YUV/OES textures. After initilization, these are only accessed
100 // from the render thread.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100101 @Nullable private EglBase eglBase;
magjed7cede372017-09-11 06:12:07 -0700102 private final VideoFrameDrawer frameDrawer = new VideoFrameDrawer();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100103 @Nullable private RendererCommon.GlDrawer drawer;
magjed7cede372017-09-11 06:12:07 -0700104 private final Matrix drawMatrix = new Matrix();
magjeddf494b02016-10-07 05:32:35 -0700105
106 // Pending frame to render. Serves as a queue with size 1. Synchronized on |frameLock|.
107 private final Object frameLock = new Object();
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100108 @Nullable private VideoFrame pendingFrame;
magjeddf494b02016-10-07 05:32:35 -0700109
110 // These variables are synchronized on |layoutLock|.
111 private final Object layoutLock = new Object();
magjeddf494b02016-10-07 05:32:35 -0700112 private float layoutAspectRatio;
113 // If true, mirrors the video stream horizontally.
114 private boolean mirror;
115
116 // These variables are synchronized on |statisticsLock|.
117 private final Object statisticsLock = new Object();
118 // Total number of video frames received in renderFrame() call.
119 private int framesReceived;
120 // Number of video frames dropped by renderFrame() because previous frame has not been rendered
121 // yet.
122 private int framesDropped;
123 // Number of rendered video frames.
124 private int framesRendered;
magjed9ab8a182016-10-20 03:18:09 -0700125 // Start time for counting these statistics, or 0 if we haven't started measuring yet.
126 private long statisticsStartTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700127 // Time in ns spent in renderFrameOnRenderThread() function.
128 private long renderTimeNs;
magjed9ab8a182016-10-20 03:18:09 -0700129 // Time in ns spent by the render thread in the swapBuffers() function.
130 private long renderSwapBufferTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700131
sakalfb0c5732016-11-03 09:15:34 -0700132 // Used for bitmap capturing.
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200133 private final GlTextureFrameBuffer bitmapTextureFramebuffer =
134 new GlTextureFrameBuffer(GLES20.GL_RGBA);
sakalfb0c5732016-11-03 09:15:34 -0700135
magjed9ab8a182016-10-20 03:18:09 -0700136 private final Runnable logStatisticsRunnable = new Runnable() {
137 @Override
138 public void run() {
139 logStatistics();
140 synchronized (handlerLock) {
141 if (renderThreadHandler != null) {
142 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
143 renderThreadHandler.postDelayed(
144 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
145 }
146 }
147 }
148 };
149
magjeddf494b02016-10-07 05:32:35 -0700150 private final EglSurfaceCreation eglSurfaceCreationRunnable = new EglSurfaceCreation();
151
152 /**
153 * Standard constructor. The name will be used for the render thread name and included when
154 * logging. In order to render something, you must first call init() and createEglSurface.
155 */
156 public EglRenderer(String name) {
157 this.name = name;
158 }
159
160 /**
161 * Initialize this class, sharing resources with |sharedContext|. The custom |drawer| will be used
162 * for drawing frames on the EGLSurface. This class is responsible for calling release() on
163 * |drawer|. It is allowed to call init() to reinitialize the renderer after a previous
164 * init()/release() cycle.
165 */
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100166 public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes,
magjeddf494b02016-10-07 05:32:35 -0700167 RendererCommon.GlDrawer drawer) {
168 synchronized (handlerLock) {
169 if (renderThreadHandler != null) {
170 throw new IllegalStateException(name + "Already initialized");
171 }
172 logD("Initializing EglRenderer");
173 this.drawer = drawer;
174
175 final HandlerThread renderThread = new HandlerThread(name + "EglRenderer");
176 renderThread.start();
177 renderThreadHandler = new Handler(renderThread.getLooper());
178 // Create EGL context on the newly created render thread. It should be possibly to create the
179 // context on this thread and make it current on the render thread, but this causes failure on
180 // some Marvel based JB devices. https://bugs.chromium.org/p/webrtc/issues/detail?id=6350.
sakalbf080602017-08-11 01:42:43 -0700181 ThreadUtils.invokeAtFrontUninterruptibly(renderThreadHandler, () -> {
182 // If sharedContext is null, then texture frames are disabled. This is typically for old
183 // devices that might not be fully spec compliant, so force EGL 1.0 since EGL 1.4 has
184 // caused trouble on some weird devices.
185 if (sharedContext == null) {
186 logD("EglBase10.create context");
187 eglBase = EglBase.createEgl10(configAttributes);
188 } else {
189 logD("EglBase.create shared context");
190 eglBase = EglBase.create(sharedContext, configAttributes);
magjeddf494b02016-10-07 05:32:35 -0700191 }
192 });
magjed9ab8a182016-10-20 03:18:09 -0700193 renderThreadHandler.post(eglSurfaceCreationRunnable);
194 final long currentTimeNs = System.nanoTime();
195 resetStatistics(currentTimeNs);
196 renderThreadHandler.postDelayed(
197 logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC));
magjeddf494b02016-10-07 05:32:35 -0700198 }
199 }
200
201 public void createEglSurface(Surface surface) {
magjed9ab8a182016-10-20 03:18:09 -0700202 createEglSurfaceInternal(surface);
203 }
204
205 public void createEglSurface(SurfaceTexture surfaceTexture) {
206 createEglSurfaceInternal(surfaceTexture);
207 }
208
209 private void createEglSurfaceInternal(Object surface) {
magjeddf494b02016-10-07 05:32:35 -0700210 eglSurfaceCreationRunnable.setSurface(surface);
magjed9ab8a182016-10-20 03:18:09 -0700211 postToRenderThread(eglSurfaceCreationRunnable);
magjeddf494b02016-10-07 05:32:35 -0700212 }
213
214 /**
215 * Block until any pending frame is returned and all GL resources released, even if an interrupt
216 * occurs. If an interrupt occurs during release(), the interrupt flag will be set. This function
217 * should be called before the Activity is destroyed and the EGLContext is still valid. If you
218 * don't call this function, the GL resources might leak.
219 */
220 public void release() {
magjed9ab8a182016-10-20 03:18:09 -0700221 logD("Releasing.");
magjeddf494b02016-10-07 05:32:35 -0700222 final CountDownLatch eglCleanupBarrier = new CountDownLatch(1);
223 synchronized (handlerLock) {
224 if (renderThreadHandler == null) {
225 logD("Already released");
226 return;
227 }
magjed9ab8a182016-10-20 03:18:09 -0700228 renderThreadHandler.removeCallbacks(logStatisticsRunnable);
magjeddf494b02016-10-07 05:32:35 -0700229 // Release EGL and GL resources on render thread.
sakalbf080602017-08-11 01:42:43 -0700230 renderThreadHandler.postAtFrontOfQueue(() -> {
231 if (drawer != null) {
232 drawer.release();
233 drawer = null;
magjeddf494b02016-10-07 05:32:35 -0700234 }
magjed7cede372017-09-11 06:12:07 -0700235 frameDrawer.release();
Magnus Jedvert2ed62b32018-04-11 14:25:14 +0200236 bitmapTextureFramebuffer.release();
sakalbf080602017-08-11 01:42:43 -0700237 if (eglBase != null) {
238 logD("eglBase detach and release.");
239 eglBase.detachCurrent();
240 eglBase.release();
241 eglBase = null;
242 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100243 frameListeners.clear();
sakalbf080602017-08-11 01:42:43 -0700244 eglCleanupBarrier.countDown();
magjeddf494b02016-10-07 05:32:35 -0700245 });
246 final Looper renderLooper = renderThreadHandler.getLooper();
247 // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18.
sakalbf080602017-08-11 01:42:43 -0700248 renderThreadHandler.post(() -> {
249 logD("Quitting render thread.");
250 renderLooper.quit();
magjeddf494b02016-10-07 05:32:35 -0700251 });
252 // Don't accept any more frames or messages to the render thread.
253 renderThreadHandler = null;
254 }
255 // Make sure the EGL/GL cleanup posted above is executed.
256 ThreadUtils.awaitUninterruptibly(eglCleanupBarrier);
257 synchronized (frameLock) {
258 if (pendingFrame != null) {
sakal6bdcefc2017-08-15 01:56:02 -0700259 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700260 pendingFrame = null;
261 }
262 }
magjeddf494b02016-10-07 05:32:35 -0700263 logD("Releasing done.");
264 }
265
266 /**
magjed9ab8a182016-10-20 03:18:09 -0700267 * Reset the statistics logged in logStatistics().
magjeddf494b02016-10-07 05:32:35 -0700268 */
magjed9ab8a182016-10-20 03:18:09 -0700269 private void resetStatistics(long currentTimeNs) {
magjeddf494b02016-10-07 05:32:35 -0700270 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700271 statisticsStartTimeNs = currentTimeNs;
magjeddf494b02016-10-07 05:32:35 -0700272 framesReceived = 0;
273 framesDropped = 0;
274 framesRendered = 0;
magjeddf494b02016-10-07 05:32:35 -0700275 renderTimeNs = 0;
magjed9ab8a182016-10-20 03:18:09 -0700276 renderSwapBufferTimeNs = 0;
277 }
278 }
279
280 public void printStackTrace() {
281 synchronized (handlerLock) {
282 final Thread renderThread =
283 (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread();
284 if (renderThread != null) {
285 final StackTraceElement[] renderStackTrace = renderThread.getStackTrace();
286 if (renderStackTrace.length > 0) {
287 logD("EglRenderer stack trace:");
288 for (StackTraceElement traceElem : renderStackTrace) {
289 logD(traceElem.toString());
290 }
291 }
292 }
magjeddf494b02016-10-07 05:32:35 -0700293 }
294 }
295
296 /**
297 * Set if the video stream should be mirrored or not.
298 */
299 public void setMirror(final boolean mirror) {
300 logD("setMirror: " + mirror);
301 synchronized (layoutLock) {
302 this.mirror = mirror;
303 }
304 }
305
306 /**
307 * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video.
308 * Set this to 0 to disable cropping.
309 */
310 public void setLayoutAspectRatio(float layoutAspectRatio) {
311 logD("setLayoutAspectRatio: " + layoutAspectRatio);
312 synchronized (layoutLock) {
313 this.layoutAspectRatio = layoutAspectRatio;
314 }
315 }
316
magjed9ab8a182016-10-20 03:18:09 -0700317 /**
318 * Limit render framerate.
319 *
320 * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps
321 * reduction.
322 */
323 public void setFpsReduction(float fps) {
324 logD("setFpsReduction: " + fps);
325 synchronized (fpsReductionLock) {
326 final long previousRenderPeriodNs = minRenderPeriodNs;
327 if (fps <= 0) {
328 minRenderPeriodNs = Long.MAX_VALUE;
329 } else {
330 minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps);
331 }
332 if (minRenderPeriodNs != previousRenderPeriodNs) {
333 // Fps reduction changed - reset frame time.
334 nextFrameTimeNs = System.nanoTime();
335 }
336 }
337 }
338
339 public void disableFpsReduction() {
340 setFpsReduction(Float.POSITIVE_INFINITY /* fps */);
341 }
342
343 public void pauseVideo() {
344 setFpsReduction(0 /* fps */);
345 }
346
sakalfb0c5732016-11-03 09:15:34 -0700347 /**
sakal3a9bc172016-11-30 08:30:05 -0800348 * Register a callback to be invoked when a new video frame has been received. This version uses
349 * the drawer of the EglRenderer that was passed in init.
sakalfb0c5732016-11-03 09:15:34 -0700350 *
sakald1516522017-03-13 05:11:48 -0700351 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
352 * It should be lightweight and must not call removeFrameListener.
sakalfb0c5732016-11-03 09:15:34 -0700353 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
354 * required.
355 */
sakalbb584352016-11-28 08:53:44 -0800356 public void addFrameListener(final FrameListener listener, final float scale) {
sakal8fdf9572017-05-31 02:43:10 -0700357 addFrameListener(listener, scale, null, false /* applyFpsReduction */);
sakal3a9bc172016-11-30 08:30:05 -0800358 }
359
360 /**
361 * Register a callback to be invoked when a new video frame has been received.
362 *
sakald1516522017-03-13 05:11:48 -0700363 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
364 * It should be lightweight and must not call removeFrameListener.
sakal3a9bc172016-11-30 08:30:05 -0800365 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
366 * required.
sakald1516522017-03-13 05:11:48 -0700367 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
sakal3a9bc172016-11-30 08:30:05 -0800368 */
369 public void addFrameListener(
sakald1516522017-03-13 05:11:48 -0700370 final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) {
sakal8fdf9572017-05-31 02:43:10 -0700371 addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */);
372 }
373
374 /**
375 * Register a callback to be invoked when a new video frame has been received.
376 *
377 * @param listener The callback to be invoked. The callback will be invoked on the render thread.
378 * It should be lightweight and must not call removeFrameListener.
379 * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is
380 * required.
381 * @param drawer Custom drawer to use for this frame listener or null to use the default one.
382 * @param applyFpsReduction This callback will not be called for frames that have been dropped by
383 * FPS reduction.
384 */
385 public void addFrameListener(final FrameListener listener, final float scale,
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100386 @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) {
sakalbf080602017-08-11 01:42:43 -0700387 postToRenderThread(() -> {
388 final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam;
389 frameListeners.add(
390 new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction));
sakalbb584352016-11-28 08:53:44 -0800391 });
sakalfb0c5732016-11-03 09:15:34 -0700392 }
393
394 /**
395 * Remove any pending callback that was added with addFrameListener. If the callback is not in
sakalbb584352016-11-28 08:53:44 -0800396 * the queue, nothing happens. It is ensured that callback won't be called after this method
397 * returns.
sakalfb0c5732016-11-03 09:15:34 -0700398 *
399 * @param runnable The callback to remove.
400 */
sakalbb584352016-11-28 08:53:44 -0800401 public void removeFrameListener(final FrameListener listener) {
402 final CountDownLatch latch = new CountDownLatch(1);
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100403 synchronized (handlerLock) {
404 if (renderThreadHandler == null) {
405 return;
sakalfb0c5732016-11-03 09:15:34 -0700406 }
Sami Kalliomäki8ebac242017-11-08 17:13:13 +0100407 if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) {
408 throw new RuntimeException("removeFrameListener must not be called on the render thread.");
409 }
410 postToRenderThread(() -> {
411 latch.countDown();
412 final Iterator<FrameListenerAndParams> iter = frameListeners.iterator();
413 while (iter.hasNext()) {
414 if (iter.next().listener == listener) {
415 iter.remove();
416 }
417 }
418 });
419 }
sakalbb584352016-11-28 08:53:44 -0800420 ThreadUtils.awaitUninterruptibly(latch);
sakalfb0c5732016-11-03 09:15:34 -0700421 }
422
sakal6bdcefc2017-08-15 01:56:02 -0700423 // VideoSink interface.
424 @Override
425 public void onFrame(VideoFrame frame) {
magjeddf494b02016-10-07 05:32:35 -0700426 synchronized (statisticsLock) {
427 ++framesReceived;
428 }
magjed9ab8a182016-10-20 03:18:09 -0700429 final boolean dropOldFrame;
magjeddf494b02016-10-07 05:32:35 -0700430 synchronized (handlerLock) {
431 if (renderThreadHandler == null) {
432 logD("Dropping frame - Not initialized or already released.");
magjeddf494b02016-10-07 05:32:35 -0700433 return;
434 }
magjed9ab8a182016-10-20 03:18:09 -0700435 synchronized (frameLock) {
436 dropOldFrame = (pendingFrame != null);
437 if (dropOldFrame) {
sakal6bdcefc2017-08-15 01:56:02 -0700438 pendingFrame.release();
magjeddf494b02016-10-07 05:32:35 -0700439 }
440 pendingFrame = frame;
sakal6bdcefc2017-08-15 01:56:02 -0700441 pendingFrame.retain();
sakalbf080602017-08-11 01:42:43 -0700442 renderThreadHandler.post(this ::renderFrameOnRenderThread);
magjeddf494b02016-10-07 05:32:35 -0700443 }
444 }
magjed9ab8a182016-10-20 03:18:09 -0700445 if (dropOldFrame) {
446 synchronized (statisticsLock) {
447 ++framesDropped;
448 }
449 }
magjeddf494b02016-10-07 05:32:35 -0700450 }
451
452 /**
453 * Release EGL surface. This function will block until the EGL surface is released.
454 */
sakal28ec6bd2016-11-09 01:47:12 -0800455 public void releaseEglSurface(final Runnable completionCallback) {
magjeddf494b02016-10-07 05:32:35 -0700456 // Ensure that the render thread is no longer touching the Surface before returning from this
457 // function.
458 eglSurfaceCreationRunnable.setSurface(null /* surface */);
459 synchronized (handlerLock) {
460 if (renderThreadHandler != null) {
461 renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable);
sakalbf080602017-08-11 01:42:43 -0700462 renderThreadHandler.postAtFrontOfQueue(() -> {
463 if (eglBase != null) {
464 eglBase.detachCurrent();
465 eglBase.releaseSurface();
magjeddf494b02016-10-07 05:32:35 -0700466 }
sakalbf080602017-08-11 01:42:43 -0700467 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700468 });
sakal28ec6bd2016-11-09 01:47:12 -0800469 return;
magjeddf494b02016-10-07 05:32:35 -0700470 }
471 }
sakal28ec6bd2016-11-09 01:47:12 -0800472 completionCallback.run();
magjeddf494b02016-10-07 05:32:35 -0700473 }
474
475 /**
magjeddf494b02016-10-07 05:32:35 -0700476 * Private helper function to post tasks safely.
477 */
magjed9ab8a182016-10-20 03:18:09 -0700478 private void postToRenderThread(Runnable runnable) {
magjeddf494b02016-10-07 05:32:35 -0700479 synchronized (handlerLock) {
480 if (renderThreadHandler != null) {
481 renderThreadHandler.post(runnable);
482 }
483 }
484 }
485
sakalf25a2202017-05-04 06:06:56 -0700486 private void clearSurfaceOnRenderThread(float r, float g, float b, float a) {
magjeddf494b02016-10-07 05:32:35 -0700487 if (eglBase != null && eglBase.hasSurface()) {
488 logD("clearSurface");
sakalf25a2202017-05-04 06:06:56 -0700489 GLES20.glClearColor(r, g, b, a);
magjeddf494b02016-10-07 05:32:35 -0700490 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
491 eglBase.swapBuffers();
492 }
493 }
494
495 /**
sakalf25a2202017-05-04 06:06:56 -0700496 * Post a task to clear the surface to a transparent uniform color.
magjed9ab8a182016-10-20 03:18:09 -0700497 */
498 public void clearImage() {
sakalf25a2202017-05-04 06:06:56 -0700499 clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
500 }
501
502 /**
503 * Post a task to clear the surface to a specific color.
504 */
505 public void clearImage(final float r, final float g, final float b, final float a) {
magjed9ab8a182016-10-20 03:18:09 -0700506 synchronized (handlerLock) {
507 if (renderThreadHandler == null) {
508 return;
509 }
sakalbf080602017-08-11 01:42:43 -0700510 renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a));
magjed9ab8a182016-10-20 03:18:09 -0700511 }
512 }
513
514 /**
magjeddf494b02016-10-07 05:32:35 -0700515 * Renders and releases |pendingFrame|.
516 */
517 private void renderFrameOnRenderThread() {
518 // Fetch and render |pendingFrame|.
sakal6bdcefc2017-08-15 01:56:02 -0700519 final VideoFrame frame;
magjeddf494b02016-10-07 05:32:35 -0700520 synchronized (frameLock) {
521 if (pendingFrame == null) {
522 return;
523 }
524 frame = pendingFrame;
525 pendingFrame = null;
526 }
527 if (eglBase == null || !eglBase.hasSurface()) {
528 logD("Dropping frame - No surface");
sakal6bdcefc2017-08-15 01:56:02 -0700529 frame.release();
magjeddf494b02016-10-07 05:32:35 -0700530 return;
531 }
sakald1516522017-03-13 05:11:48 -0700532 // Check if fps reduction is active.
533 final boolean shouldRenderFrame;
534 synchronized (fpsReductionLock) {
535 if (minRenderPeriodNs == Long.MAX_VALUE) {
536 // Rendering is paused.
537 shouldRenderFrame = false;
538 } else if (minRenderPeriodNs <= 0) {
539 // FPS reduction is disabled.
540 shouldRenderFrame = true;
541 } else {
542 final long currentTimeNs = System.nanoTime();
543 if (currentTimeNs < nextFrameTimeNs) {
544 logD("Skipping frame rendering - fps reduction is active.");
545 shouldRenderFrame = false;
546 } else {
547 nextFrameTimeNs += minRenderPeriodNs;
548 // The time for the next frame should always be in the future.
549 nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs);
550 shouldRenderFrame = true;
551 }
552 }
553 }
magjeddf494b02016-10-07 05:32:35 -0700554
555 final long startTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700556
sakal6bdcefc2017-08-15 01:56:02 -0700557 final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight();
558 final float drawnAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700559 synchronized (layoutLock) {
sakal6bdcefc2017-08-15 01:56:02 -0700560 drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio;
magjeddf494b02016-10-07 05:32:35 -0700561 }
562
sakal6bdcefc2017-08-15 01:56:02 -0700563 final float scaleX;
564 final float scaleY;
565
566 if (frameAspectRatio > drawnAspectRatio) {
567 scaleX = drawnAspectRatio / frameAspectRatio;
568 scaleY = 1f;
569 } else {
570 scaleX = 1f;
571 scaleY = frameAspectRatio / drawnAspectRatio;
572 }
573
magjed7cede372017-09-11 06:12:07 -0700574 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700575 drawMatrix.preTranslate(0.5f, 0.5f);
sakal6bdcefc2017-08-15 01:56:02 -0700576 if (mirror)
577 drawMatrix.preScale(-1f, 1f);
578 drawMatrix.preScale(scaleX, scaleY);
579 drawMatrix.preTranslate(-0.5f, -0.5f);
580
sakald1516522017-03-13 05:11:48 -0700581 if (shouldRenderFrame) {
582 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
583 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700584 frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */,
585 eglBase.surfaceWidth(), eglBase.surfaceHeight());
sakald1516522017-03-13 05:11:48 -0700586
587 final long swapBuffersStartTimeNs = System.nanoTime();
588 eglBase.swapBuffers();
589
590 final long currentTimeNs = System.nanoTime();
591 synchronized (statisticsLock) {
592 ++framesRendered;
593 renderTimeNs += (currentTimeNs - startTimeNs);
594 renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs);
595 }
magjeddf494b02016-10-07 05:32:35 -0700596 }
597
magjed7cede372017-09-11 06:12:07 -0700598 notifyCallbacks(frame, shouldRenderFrame);
599 frame.release();
sakalfb0c5732016-11-03 09:15:34 -0700600 }
601
magjed7cede372017-09-11 06:12:07 -0700602 private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
sakalbb584352016-11-28 08:53:44 -0800603 if (frameListeners.isEmpty())
604 return;
sakalfb0c5732016-11-03 09:15:34 -0700605
magjed7cede372017-09-11 06:12:07 -0700606 drawMatrix.reset();
sakal6bdcefc2017-08-15 01:56:02 -0700607 drawMatrix.preTranslate(0.5f, 0.5f);
sakal6bdcefc2017-08-15 01:56:02 -0700608 if (mirror)
609 drawMatrix.preScale(-1f, 1f);
610 drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
611 drawMatrix.preTranslate(-0.5f, -0.5f);
sakalfb0c5732016-11-03 09:15:34 -0700612
sakal8fdf9572017-05-31 02:43:10 -0700613 Iterator<FrameListenerAndParams> it = frameListeners.iterator();
614 while (it.hasNext()) {
615 FrameListenerAndParams listenerAndParams = it.next();
616 if (!wasRendered && listenerAndParams.applyFpsReduction) {
617 continue;
618 }
619 it.remove();
620
sakal6bdcefc2017-08-15 01:56:02 -0700621 final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
622 final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());
sakalfb0c5732016-11-03 09:15:34 -0700623
624 if (scaledWidth == 0 || scaledHeight == 0) {
sakal3a9bc172016-11-30 08:30:05 -0800625 listenerAndParams.listener.onFrame(null);
sakalfb0c5732016-11-03 09:15:34 -0700626 continue;
627 }
628
sakalfb0c5732016-11-03 09:15:34 -0700629 bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);
630
631 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
632 GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
633 GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);
634
sakal103988d2017-02-17 09:59:01 -0800635 GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
636 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700637 frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
638 0 /* viewportY */, scaledWidth, scaledHeight);
sakalfb0c5732016-11-03 09:15:34 -0700639
640 final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
641 GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
642 GLES20.glReadPixels(
643 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);
644
645 GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
646 GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");
647
648 final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
649 bitmap.copyPixelsFromBuffer(bitmapBuffer);
sakal3a9bc172016-11-30 08:30:05 -0800650 listenerAndParams.listener.onFrame(bitmap);
sakalfb0c5732016-11-03 09:15:34 -0700651 }
magjeddf494b02016-10-07 05:32:35 -0700652 }
653
magjed9ab8a182016-10-20 03:18:09 -0700654 private String averageTimeAsString(long sumTimeNs, int count) {
655 return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " μs";
656 }
657
magjeddf494b02016-10-07 05:32:35 -0700658 private void logStatistics() {
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200659 final DecimalFormat fpsFormat = new DecimalFormat("#.0");
magjed9ab8a182016-10-20 03:18:09 -0700660 final long currentTimeNs = System.nanoTime();
magjeddf494b02016-10-07 05:32:35 -0700661 synchronized (statisticsLock) {
magjed9ab8a182016-10-20 03:18:09 -0700662 final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs;
663 if (elapsedTimeNs <= 0) {
664 return;
magjeddf494b02016-10-07 05:32:35 -0700665 }
magjed9ab8a182016-10-20 03:18:09 -0700666 final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs;
667 logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms."
668 + " Frames received: " + framesReceived + "."
669 + " Dropped: " + framesDropped + "."
670 + " Rendered: " + framesRendered + "."
Sami Kalliomäki1659e972018-06-04 14:07:58 +0200671 + " Render fps: " + fpsFormat.format(renderFps) + "."
magjed9ab8a182016-10-20 03:18:09 -0700672 + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "."
673 + " Average swapBuffer time: "
674 + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + ".");
675 resetStatistics(currentTimeNs);
magjeddf494b02016-10-07 05:32:35 -0700676 }
677 }
678
679 private void logD(String string) {
680 Logging.d(TAG, name + string);
681 }
682}