| 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 |
| 11 | package org.webrtc; |
| 12 |
| 13 | import android.graphics.Bitmap; |
| 14 | import android.graphics.Matrix; |
| 15 | import android.graphics.SurfaceTexture; |
| 16 | import android.opengl.GLES20; |
| 17 | import android.os.Handler; |
| 18 | import android.os.HandlerThread; |
| 19 | import android.os.Looper; |
| 20 | import android.os.Message; |
| 21 | import androidx.annotation.Nullable; |
| 22 | import android.view.Surface; |
| 23 | import java.nio.ByteBuffer; |
| 24 | import java.text.DecimalFormat; |
| 25 | import java.util.ArrayList; |
| 26 | import java.util.Iterator; |
| 27 | import java.util.concurrent.CountDownLatch; |
| 28 | import java.util.concurrent.TimeUnit; |
| 29 |
| 30 | /** |
| 31 | * 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. |
| 33 | */ |
| 34 | public class EglRenderer implements VideoSink { |
| 35 | private static final String TAG = "EglRenderer"; |
| 36 | private static final long LOG_INTERVAL_SEC = 4; |
| 37 |
| 38 | private boolean firstFrameRendered; |
| 39 |
| 40 | public interface FrameListener { void onFrame(Bitmap frame); } |
| 41 |
| 42 | /** Callback for clients to be notified about errors encountered during rendering. */ |
| 43 | public static interface ErrorCallback { |
| 44 | /** Called if GLES20.GL_OUT_OF_MEMORY is encountered during rendering. */ |
| 45 | void onGlOutOfMemory(); |
| 46 | } |
| 47 |
| 48 | private static class FrameListenerAndParams { |
| 49 | public final FrameListener listener; |
| 50 | public final float scale; |
| 51 | public final RendererCommon.GlDrawer drawer; |
| 52 | public final boolean applyFpsReduction; |
| 53 |
| 54 | public FrameListenerAndParams(FrameListener listener, float scale, |
| 55 | RendererCommon.GlDrawer drawer, boolean applyFpsReduction) { |
| 56 | this.listener = listener; |
| 57 | this.scale = scale; |
| 58 | this.drawer = drawer; |
| 59 | this.applyFpsReduction = applyFpsReduction; |
| 60 | } |
| 61 | } |
| 62 |
| 63 | private class EglSurfaceCreation implements Runnable { |
| 64 | private Object surface; |
| 65 |
| 66 | // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression. |
| 67 | @SuppressWarnings("NoSynchronizedMethodCheck") |
| 68 | public synchronized void setSurface(Object surface) { |
| 69 | this.surface = surface; |
| 70 | } |
| 71 |
| 72 | @Override |
| 73 | // TODO(bugs.webrtc.org/8491): Remove NoSynchronizedMethodCheck suppression. |
| 74 | @SuppressWarnings("NoSynchronizedMethodCheck") |
| 75 | public synchronized void run() { |
| 76 | if (surface != null && eglBase != null && !eglBase.hasSurface()) { |
| 77 | if (surface instanceof Surface) { |
| 78 | eglBase.createSurface((Surface) surface); |
| 79 | } else if (surface instanceof SurfaceTexture) { |
| 80 | eglBase.createSurface((SurfaceTexture) surface); |
| 81 | } else { |
| 82 | throw new IllegalStateException("Invalid surface: " + surface); |
| 83 | } |
| 84 | eglBase.makeCurrent(); |
| 85 | // Necessary for YUV frames with odd width. |
| 86 | GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1); |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 |
| 91 | /** |
| 92 | * Handler that triggers a callback when an uncaught exception happens when handling a message. |
| 93 | */ |
| 94 | private static class HandlerWithExceptionCallback extends Handler { |
| 95 | private final Runnable exceptionCallback; |
| 96 |
| 97 | public HandlerWithExceptionCallback(Looper looper, Runnable exceptionCallback) { |
| 98 | super(looper); |
| 99 | this.exceptionCallback = exceptionCallback; |
| 100 | } |
| 101 |
| 102 | @Override |
| 103 | public void dispatchMessage(Message msg) { |
| 104 | try { |
| 105 | super.dispatchMessage(msg); |
| 106 | } catch (Exception e) { |
| 107 | Logging.e(TAG, "Exception on EglRenderer thread", e); |
| 108 | exceptionCallback.run(); |
| 109 | throw e; |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 |
| 114 | protected final String name; |
| 115 |
| 116 | // |renderThreadHandler| is a handler for communicating with |renderThread|, and is synchronized |
| 117 | // on |handlerLock|. |
| 118 | private final Object handlerLock = new Object(); |
| 119 | @Nullable private Handler renderThreadHandler; |
| 120 |
| 121 | private final ArrayList<FrameListenerAndParams> frameListeners = new ArrayList<>(); |
| 122 |
| 123 | private volatile ErrorCallback errorCallback; |
| 124 |
| 125 | // Variables for fps reduction. |
| 126 | private final Object fpsReductionLock = new Object(); |
| 127 | // Time for when next frame should be rendered. |
| 128 | private long nextFrameTimeNs; |
| 129 | // Minimum duration between frames when fps reduction is active, or -1 if video is completely |
| 130 | // paused. |
| 131 | private long minRenderPeriodNs; |
| 132 |
| 133 | // EGL and GL resources for drawing YUV/OES textures. After initialization, these are only |
| 134 | // accessed from the render thread. |
| 135 | @Nullable private EglBase eglBase; |
| 136 | private final VideoFrameDrawer frameDrawer; |
| 137 | @Nullable private RendererCommon.GlDrawer drawer; |
| 138 | private boolean usePresentationTimeStamp; |
| 139 | private final Matrix drawMatrix = new Matrix(); |
| 140 |
| 141 | // Pending frame to render. Serves as a queue with size 1. Synchronized on |frameLock|. |
| 142 | private final Object frameLock = new Object(); |
| 143 | @Nullable private VideoFrame pendingFrame; |
| 144 |
| 145 | // These variables are synchronized on |layoutLock|. |
| 146 | private final Object layoutLock = new Object(); |
| 147 | private float layoutAspectRatio; |
| 148 | // If true, mirrors the video stream horizontally. |
| 149 | private boolean mirrorHorizontally; |
| 150 | // If true, mirrors the video stream vertically. |
| 151 | private boolean mirrorVertically; |
| 152 |
| 153 | // These variables are synchronized on |statisticsLock|. |
| 154 | private final Object statisticsLock = new Object(); |
| 155 | // Total number of video frames received in renderFrame() call. |
| 156 | private int framesReceived; |
| 157 | // Number of video frames dropped by renderFrame() because previous frame has not been rendered |
| 158 | // yet. |
| 159 | private int framesDropped; |
| 160 | // Number of rendered video frames. |
| 161 | private int framesRendered; |
| 162 | // Start time for counting these statistics, or 0 if we haven't started measuring yet. |
| 163 | private long statisticsStartTimeNs; |
| 164 | // Time in ns spent in renderFrameOnRenderThread() function. |
| 165 | private long renderTimeNs; |
| 166 | // Time in ns spent by the render thread in the swapBuffers() function. |
| 167 | private long renderSwapBufferTimeNs; |
| 168 |
| 169 | // Used for bitmap capturing. |
| 170 | private final GlTextureFrameBuffer bitmapTextureFramebuffer = |
| 171 | new GlTextureFrameBuffer(GLES20.GL_RGBA); |
| 172 |
| 173 | private final Runnable logStatisticsRunnable = new Runnable() { |
| 174 | @Override |
| 175 | public void run() { |
| 176 | logStatistics(); |
| 177 | synchronized (handlerLock) { |
| 178 | if (renderThreadHandler != null) { |
| 179 | renderThreadHandler.removeCallbacks(logStatisticsRunnable); |
| 180 | renderThreadHandler.postDelayed( |
| 181 | logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC)); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | }; |
| 186 |
| 187 | private final EglSurfaceCreation eglSurfaceCreationRunnable = new EglSurfaceCreation(); |
| 188 |
| 189 | /** |
| 190 | * Standard constructor. The name will be used for the render thread name and included when |
| 191 | * logging. In order to render something, you must first call init() and createEglSurface. |
| 192 | */ |
| 193 | public EglRenderer(String name) { |
| 194 | this(name, new VideoFrameDrawer()); |
| 195 | } |
| 196 |
| 197 | public EglRenderer(String name, VideoFrameDrawer videoFrameDrawer) { |
| 198 | this.name = name; |
| 199 | this.frameDrawer = videoFrameDrawer; |
| 200 | } |
| 201 |
| 202 | /** |
| 203 | * Initialize this class, sharing resources with |sharedContext|. The custom |drawer| will be used |
| 204 | * for drawing frames on the EGLSurface. This class is responsible for calling release() on |
| 205 | * |drawer|. It is allowed to call init() to reinitialize the renderer after a previous |
| 206 | * init()/release() cycle. If usePresentationTimeStamp is true, eglPresentationTimeANDROID will be |
| 207 | * set with the frame timestamps, which specifies desired presentation time and might be useful |
| 208 | * for e.g. syncing audio and video. |
| 209 | */ |
| 210 | public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes, |
| 211 | RendererCommon.GlDrawer drawer, boolean usePresentationTimeStamp) { |
| 212 | synchronized (handlerLock) { |
| 213 | if (renderThreadHandler != null) { |
| 214 | throw new IllegalStateException(name + "Already initialized"); |
| 215 | } |
| 216 | logD("Initializing EglRenderer"); |
| 217 | this.drawer = drawer; |
| 218 | this.usePresentationTimeStamp = usePresentationTimeStamp; |
| 219 | firstFrameRendered = false; |
| 220 |
| 221 | final HandlerThread renderThread = new HandlerThread(name + "EglRenderer"); |
| 222 | renderThread.start(); |
| 223 | renderThreadHandler = |
| 224 | new HandlerWithExceptionCallback(renderThread.getLooper(), new Runnable() { |
| 225 | @Override |
| 226 | public void run() { |
| 227 | synchronized (handlerLock) { |
| 228 | renderThreadHandler = null; |
| 229 | } |
| 230 | } |
| 231 | }); |
| 232 | // Create EGL context on the newly created render thread. It should be possibly to create the |
| 233 | // context on this thread and make it current on the render thread, but this causes failure on |
| 234 | // some Marvel based JB devices. https://bugs.chromium.org/p/webrtc/issues/detail?id=6350. |
| 235 | ThreadUtils.invokeAtFrontUninterruptibly(renderThreadHandler, () -> { |
| 236 | // If sharedContext is null, then texture frames are disabled. This is typically for old |
| 237 | // devices that might not be fully spec compliant, so force EGL 1.0 since EGL 1.4 has |
| 238 | // caused trouble on some weird devices. |
| 239 | if (sharedContext == null) { |
| 240 | logD("EglBase10.create context"); |
| 241 | eglBase = EglBase.createEgl10(configAttributes); |
| 242 | } else { |
| 243 | logD("EglBase.create shared context"); |
| 244 | eglBase = EglBase.create(sharedContext, configAttributes); |
| 245 | } |
| 246 | }); |
| 247 | renderThreadHandler.post(eglSurfaceCreationRunnable); |
| 248 | final long currentTimeNs = System.nanoTime(); |
| 249 | resetStatistics(currentTimeNs); |
| 250 | renderThreadHandler.postDelayed( |
| 251 | logStatisticsRunnable, TimeUnit.SECONDS.toMillis(LOG_INTERVAL_SEC)); |
| 252 | } |
| 253 | } |
| 254 |
| 255 | /** |
| 256 | * Same as above with usePresentationTimeStamp set to false. |
| 257 | * |
| 258 | * @see #init(EglBase.Context, int[], RendererCommon.GlDrawer, boolean) |
| 259 | */ |
| 260 | public void init(@Nullable final EglBase.Context sharedContext, final int[] configAttributes, |
| 261 | RendererCommon.GlDrawer drawer) { |
| 262 | init(sharedContext, configAttributes, drawer, /* usePresentationTimeStamp= */ false); |
| 263 | } |
| 264 |
| 265 | public void createEglSurface(Surface surface) { |
| 266 | createEglSurfaceInternal(surface); |
| 267 | } |
| 268 |
| 269 | public void createEglSurface(SurfaceTexture surfaceTexture) { |
| 270 | createEglSurfaceInternal(surfaceTexture); |
| 271 | } |
| 272 |
| 273 | private void createEglSurfaceInternal(Object surface) { |
| 274 | eglSurfaceCreationRunnable.setSurface(surface); |
| 275 | postToRenderThread(eglSurfaceCreationRunnable); |
| 276 | } |
| 277 |
| 278 | /** |
| 279 | * Block until any pending frame is returned and all GL resources released, even if an interrupt |
| 280 | * occurs. If an interrupt occurs during release(), the interrupt flag will be set. This function |
| 281 | * should be called before the Activity is destroyed and the EGLContext is still valid. If you |
| 282 | * don't call this function, the GL resources might leak. |
| 283 | */ |
| 284 | public void release() { |
| 285 | logD("Releasing."); |
| 286 | final CountDownLatch eglCleanupBarrier = new CountDownLatch(1); |
| 287 | synchronized (handlerLock) { |
| 288 | if (renderThreadHandler == null) { |
| 289 | logD("Already released"); |
| 290 | return; |
| 291 | } |
| 292 | renderThreadHandler.removeCallbacks(logStatisticsRunnable); |
| 293 | // Release EGL and GL resources on render thread. |
| 294 | renderThreadHandler.postAtFrontOfQueue(() -> { |
| 295 | // Detach current shader program. |
| 296 | synchronized (EglBase.lock) { |
| 297 | GLES20.glUseProgram(/* program= */ 0); |
| 298 | } |
| 299 | if (drawer != null) { |
| 300 | drawer.release(); |
| 301 | drawer = null; |
| 302 | } |
| 303 | frameDrawer.release(); |
| 304 | bitmapTextureFramebuffer.release(); |
| 305 | if (eglBase != null) { |
| 306 | logD("eglBase detach and release."); |
| 307 | eglBase.detachCurrent(); |
| 308 | eglBase.release(); |
| 309 | eglBase = null; |
| 310 | } |
| 311 | frameListeners.clear(); |
| 312 | eglCleanupBarrier.countDown(); |
| 313 | }); |
| 314 | final Looper renderLooper = renderThreadHandler.getLooper(); |
| 315 | // TODO(magjed): Replace this post() with renderLooper.quitSafely() when API support >= 18. |
| 316 | renderThreadHandler.post(() -> { |
| 317 | logD("Quitting render thread."); |
| 318 | renderLooper.quit(); |
| 319 | }); |
| 320 | // Don't accept any more frames or messages to the render thread. |
| 321 | renderThreadHandler = null; |
| 322 | } |
| 323 | // Make sure the EGL/GL cleanup posted above is executed. |
| 324 | ThreadUtils.awaitUninterruptibly(eglCleanupBarrier); |
| 325 | synchronized (frameLock) { |
| 326 | if (pendingFrame != null) { |
| 327 | pendingFrame.release(); |
| 328 | pendingFrame = null; |
| 329 | } |
| 330 | } |
| 331 | logD("Releasing done."); |
| 332 | } |
| 333 |
| 334 | /** |
| 335 | * Reset the statistics logged in logStatistics(). |
| 336 | */ |
| 337 | private void resetStatistics(long currentTimeNs) { |
| 338 | synchronized (statisticsLock) { |
| 339 | statisticsStartTimeNs = currentTimeNs; |
| 340 | framesReceived = 0; |
| 341 | framesDropped = 0; |
| 342 | framesRendered = 0; |
| 343 | renderTimeNs = 0; |
| 344 | renderSwapBufferTimeNs = 0; |
| 345 | } |
| 346 | } |
| 347 |
| 348 | public void printStackTrace() { |
| 349 | synchronized (handlerLock) { |
| 350 | final Thread renderThread = |
| 351 | (renderThreadHandler == null) ? null : renderThreadHandler.getLooper().getThread(); |
| 352 | if (renderThread != null) { |
| 353 | final StackTraceElement[] renderStackTrace = renderThread.getStackTrace(); |
| 354 | if (renderStackTrace.length > 0) { |
| 355 | logW("EglRenderer stack trace:"); |
| 356 | for (StackTraceElement traceElem : renderStackTrace) { |
| 357 | logW(traceElem.toString()); |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 |
| 364 | /** |
| 365 | * Set if the video stream should be mirrored horizontally or not. |
| 366 | */ |
| 367 | public void setMirror(final boolean mirror) { |
| 368 | logD("setMirrorHorizontally: " + mirror); |
| 369 | synchronized (layoutLock) { |
| 370 | this.mirrorHorizontally = mirror; |
| 371 | } |
| 372 | } |
| 373 |
| 374 | /** |
| 375 | * Set if the video stream should be mirrored vertically or not. |
| 376 | */ |
| 377 | public void setMirrorVertically(final boolean mirrorVertically) { |
| 378 | logD("setMirrorVertically: " + mirrorVertically); |
| 379 | synchronized (layoutLock) { |
| 380 | this.mirrorVertically = mirrorVertically; |
| 381 | } |
| 382 | } |
| 383 |
| 384 | /** |
| 385 | * Set layout aspect ratio. This is used to crop frames when rendering to avoid stretched video. |
| 386 | * Set this to 0 to disable cropping. |
| 387 | */ |
| 388 | public void setLayoutAspectRatio(float layoutAspectRatio) { |
| 389 | logD("setLayoutAspectRatio: " + layoutAspectRatio); |
| 390 | synchronized (layoutLock) { |
| 391 | this.layoutAspectRatio = layoutAspectRatio; |
| 392 | } |
| 393 | } |
| 394 |
| 395 | /** |
| 396 | * Limit render framerate. |
| 397 | * |
| 398 | * @param fps Limit render framerate to this value, or use Float.POSITIVE_INFINITY to disable fps |
| 399 | * reduction. |
| 400 | */ |
| 401 | public void setFpsReduction(float fps) { |
| 402 | logD("setFpsReduction: " + fps); |
| 403 | synchronized (fpsReductionLock) { |
| 404 | final long previousRenderPeriodNs = minRenderPeriodNs; |
| 405 | if (fps <= 0) { |
| 406 | minRenderPeriodNs = Long.MAX_VALUE; |
| 407 | } else { |
| 408 | minRenderPeriodNs = (long) (TimeUnit.SECONDS.toNanos(1) / fps); |
| 409 | } |
| 410 | if (minRenderPeriodNs != previousRenderPeriodNs) { |
| 411 | // Fps reduction changed - reset frame time. |
| 412 | nextFrameTimeNs = System.nanoTime(); |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 |
| 417 | public void disableFpsReduction() { |
| 418 | setFpsReduction(Float.POSITIVE_INFINITY /* fps */); |
| 419 | } |
| 420 |
| 421 | public void pauseVideo() { |
| 422 | setFpsReduction(0 /* fps */); |
| 423 | } |
| 424 |
| 425 | /** |
| 426 | * Register a callback to be invoked when a new video frame has been received. This version uses |
| 427 | * the drawer of the EglRenderer that was passed in init. |
| 428 | * |
| 429 | * @param listener The callback to be invoked. The callback will be invoked on the render thread. |
| 430 | * It should be lightweight and must not call removeFrameListener. |
| 431 | * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is |
| 432 | * required. |
| 433 | */ |
| 434 | public void addFrameListener(final FrameListener listener, final float scale) { |
| 435 | addFrameListener(listener, scale, null, false /* applyFpsReduction */); |
| 436 | } |
| 437 |
| 438 | /** |
| 439 | * Register a callback to be invoked when a new video frame has been received. |
| 440 | * |
| 441 | * @param listener The callback to be invoked. The callback will be invoked on the render thread. |
| 442 | * It should be lightweight and must not call removeFrameListener. |
| 443 | * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is |
| 444 | * required. |
| 445 | * @param drawer Custom drawer to use for this frame listener or null to use the default one. |
| 446 | */ |
| 447 | public void addFrameListener( |
| 448 | final FrameListener listener, final float scale, final RendererCommon.GlDrawer drawerParam) { |
| 449 | addFrameListener(listener, scale, drawerParam, false /* applyFpsReduction */); |
| 450 | } |
| 451 |
| 452 | /** |
| 453 | * Register a callback to be invoked when a new video frame has been received. |
| 454 | * |
| 455 | * @param listener The callback to be invoked. The callback will be invoked on the render thread. |
| 456 | * It should be lightweight and must not call removeFrameListener. |
| 457 | * @param scale The scale of the Bitmap passed to the callback, or 0 if no Bitmap is |
| 458 | * required. |
| 459 | * @param drawer Custom drawer to use for this frame listener or null to use the default one. |
| 460 | * @param applyFpsReduction This callback will not be called for frames that have been dropped by |
| 461 | * FPS reduction. |
| 462 | */ |
| 463 | public void addFrameListener(final FrameListener listener, final float scale, |
| 464 | @Nullable final RendererCommon.GlDrawer drawerParam, final boolean applyFpsReduction) { |
| 465 | postToRenderThread(() -> { |
| 466 | final RendererCommon.GlDrawer listenerDrawer = drawerParam == null ? drawer : drawerParam; |
| 467 | frameListeners.add( |
| 468 | new FrameListenerAndParams(listener, scale, listenerDrawer, applyFpsReduction)); |
| 469 | }); |
| 470 | } |
| 471 |
| 472 | /** |
| 473 | * Remove any pending callback that was added with addFrameListener. If the callback is not in |
| 474 | * the queue, nothing happens. It is ensured that callback won't be called after this method |
| 475 | * returns. |
| 476 | * |
| 477 | * @param runnable The callback to remove. |
| 478 | */ |
| 479 | public void removeFrameListener(final FrameListener listener) { |
| 480 | final CountDownLatch latch = new CountDownLatch(1); |
| 481 | synchronized (handlerLock) { |
| 482 | if (renderThreadHandler == null) { |
| 483 | return; |
| 484 | } |
| 485 | if (Thread.currentThread() == renderThreadHandler.getLooper().getThread()) { |
| 486 | throw new RuntimeException("removeFrameListener must not be called on the render thread."); |
| 487 | } |
| 488 | postToRenderThread(() -> { |
| 489 | latch.countDown(); |
| 490 | final Iterator<FrameListenerAndParams> iter = frameListeners.iterator(); |
| 491 | while (iter.hasNext()) { |
| 492 | if (iter.next().listener == listener) { |
| 493 | iter.remove(); |
| 494 | } |
| 495 | } |
| 496 | }); |
| 497 | } |
| 498 | ThreadUtils.awaitUninterruptibly(latch); |
| 499 | } |
| 500 |
| 501 | /** Can be set in order to be notified about errors encountered during rendering. */ |
| 502 | public void setErrorCallback(ErrorCallback errorCallback) { |
| 503 | this.errorCallback = errorCallback; |
| 504 | } |
| 505 |
| 506 | // VideoSink interface. |
| 507 | @Override |
| 508 | public void onFrame(VideoFrame frame) { |
| 509 | synchronized (statisticsLock) { |
| 510 | ++framesReceived; |
| 511 | } |
| 512 | final boolean dropOldFrame; |
| 513 | synchronized (handlerLock) { |
| 514 | if (renderThreadHandler == null) { |
| 515 | logD("Dropping frame - Not initialized or already released."); |
| 516 | return; |
| 517 | } |
| 518 | synchronized (frameLock) { |
| 519 | dropOldFrame = (pendingFrame != null); |
| 520 | if (dropOldFrame) { |
| 521 | pendingFrame.release(); |
| 522 | } |
| 523 | pendingFrame = frame; |
| 524 | pendingFrame.retain(); |
| 525 | renderThreadHandler.post(this ::renderFrameOnRenderThread); |
| 526 | } |
| 527 | } |
| 528 | if (dropOldFrame) { |
| 529 | synchronized (statisticsLock) { |
| 530 | ++framesDropped; |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 |
| 535 | /** |
| 536 | * Release EGL surface. This function will block until the EGL surface is released. |
| 537 | */ |
| 538 | public void releaseEglSurface(final Runnable completionCallback) { |
| 539 | // Ensure that the render thread is no longer touching the Surface before returning from this |
| 540 | // function. |
| 541 | eglSurfaceCreationRunnable.setSurface(null /* surface */); |
| 542 | synchronized (handlerLock) { |
| 543 | if (renderThreadHandler != null) { |
| 544 | renderThreadHandler.removeCallbacks(eglSurfaceCreationRunnable); |
| 545 | renderThreadHandler.postAtFrontOfQueue(() -> { |
| 546 | if (eglBase != null) { |
| 547 | eglBase.detachCurrent(); |
| 548 | eglBase.releaseSurface(); |
| 549 | } |
| 550 | completionCallback.run(); |
| 551 | }); |
| 552 | return; |
| 553 | } |
| 554 | } |
| 555 | completionCallback.run(); |
| 556 | } |
| 557 |
| 558 | /** |
| 559 | * Private helper function to post tasks safely. |
| 560 | */ |
| 561 | private void postToRenderThread(Runnable runnable) { |
| 562 | synchronized (handlerLock) { |
| 563 | if (renderThreadHandler != null) { |
| 564 | renderThreadHandler.post(runnable); |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 |
| 569 | private void clearSurfaceOnRenderThread(float r, float g, float b, float a) { |
| 570 | if (eglBase != null && eglBase.hasSurface()) { |
| 571 | logD("clearSurface"); |
| 572 | GLES20.glClearColor(r, g, b, a); |
| 573 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); |
| 574 | eglBase.swapBuffers(); |
| 575 | } |
| 576 | } |
| 577 |
| 578 | /** |
| 579 | * Post a task to clear the surface to a transparent uniform color. |
| 580 | */ |
| 581 | public void clearImage() { |
| 582 | clearImage(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */); |
| 583 | } |
| 584 |
| 585 | /** |
| 586 | * Post a task to clear the surface to a specific color. |
| 587 | */ |
| 588 | public void clearImage(final float r, final float g, final float b, final float a) { |
| 589 | synchronized (handlerLock) { |
| 590 | if (renderThreadHandler == null) { |
| 591 | return; |
| 592 | } |
| 593 | renderThreadHandler.postAtFrontOfQueue(() -> clearSurfaceOnRenderThread(r, g, b, a)); |
| 594 | } |
| 595 | } |
| 596 |
| 597 | /** |
| 598 | * Renders and releases |pendingFrame|. |
| 599 | */ |
| 600 | private void renderFrameOnRenderThread() { |
| 601 | // Fetch and render |pendingFrame|. |
| 602 | final VideoFrame frame; |
| 603 | synchronized (frameLock) { |
| 604 | if (pendingFrame == null) { |
| 605 | return; |
| 606 | } |
| 607 | frame = pendingFrame; |
| 608 | pendingFrame = null; |
| 609 | } |
| 610 | if (eglBase == null || !eglBase.hasSurface()) { |
| 611 | logD("Dropping frame - No surface"); |
| 612 | frame.release(); |
| 613 | return; |
| 614 | } |
| 615 | // Check if fps reduction is active. |
| 616 | final boolean shouldRenderFrame; |
| 617 | synchronized (fpsReductionLock) { |
| 618 | if (minRenderPeriodNs == Long.MAX_VALUE) { |
| 619 | // Rendering is paused. |
| 620 | shouldRenderFrame = false; |
| 621 | } else if (minRenderPeriodNs <= 0) { |
| 622 | // FPS reduction is disabled. |
| 623 | shouldRenderFrame = true; |
| 624 | } else { |
| 625 | final long currentTimeNs = System.nanoTime(); |
| 626 | if (currentTimeNs < nextFrameTimeNs) { |
| 627 | logD("Skipping frame rendering - fps reduction is active."); |
| 628 | shouldRenderFrame = false; |
| 629 | } else { |
| 630 | nextFrameTimeNs += minRenderPeriodNs; |
| 631 | // The time for the next frame should always be in the future. |
| 632 | nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs); |
| 633 | shouldRenderFrame = true; |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 |
| 638 | final long startTimeNs = System.nanoTime(); |
| 639 |
| 640 | final float frameAspectRatio = frame.getRotatedWidth() / (float) frame.getRotatedHeight(); |
| 641 | final float drawnAspectRatio; |
| 642 | synchronized (layoutLock) { |
| 643 | drawnAspectRatio = layoutAspectRatio != 0f ? layoutAspectRatio : frameAspectRatio; |
| 644 | } |
| 645 |
| 646 | final float scaleX; |
| 647 | final float scaleY; |
| 648 |
| 649 | if (frameAspectRatio > drawnAspectRatio) { |
| 650 | scaleX = drawnAspectRatio / frameAspectRatio; |
| 651 | scaleY = 1f; |
| 652 | } else { |
| 653 | scaleX = 1f; |
| 654 | scaleY = frameAspectRatio / drawnAspectRatio; |
| 655 | } |
| 656 |
| 657 | drawMatrix.reset(); |
| 658 | drawMatrix.preTranslate(0.5f, 0.5f); |
| 659 | drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f); |
| 660 | drawMatrix.preScale(scaleX, scaleY); |
| 661 | drawMatrix.preTranslate(-0.5f, -0.5f); |
| 662 |
| 663 | try { |
| 664 | if (shouldRenderFrame) { |
| 665 | GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */); |
| 666 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); |
| 667 | frameDrawer.drawFrame(frame, drawer, drawMatrix, 0 /* viewportX */, 0 /* viewportY */, |
| 668 | eglBase.surfaceWidth(), eglBase.surfaceHeight()); |
| 669 |
| 670 | final long swapBuffersStartTimeNs = System.nanoTime(); |
| 671 | if (usePresentationTimeStamp) { |
| 672 | eglBase.swapBuffers(frame.getTimestampNs()); |
| 673 | } else { |
| 674 | eglBase.swapBuffers(); |
| 675 | } |
| 676 |
| 677 | if (!firstFrameRendered) { |
| 678 | firstFrameRendered = true; |
| 679 | onFirstFrameRendered(); |
| 680 | } |
| 681 |
| 682 | final long currentTimeNs = System.nanoTime(); |
| 683 | synchronized (statisticsLock) { |
| 684 | ++framesRendered; |
| 685 | renderTimeNs += (currentTimeNs - startTimeNs); |
| 686 | renderSwapBufferTimeNs += (currentTimeNs - swapBuffersStartTimeNs); |
| 687 | } |
| 688 | } |
| 689 |
| 690 | notifyCallbacks(frame, shouldRenderFrame); |
| 691 | } catch (GlUtil.GlOutOfMemoryException e) { |
| 692 | logE("Error while drawing frame", e); |
| 693 | final ErrorCallback errorCallback = this.errorCallback; |
| 694 | if (errorCallback != null) { |
| 695 | errorCallback.onGlOutOfMemory(); |
| 696 | } |
| 697 | // Attempt to free up some resources. |
| 698 | drawer.release(); |
| 699 | frameDrawer.release(); |
| 700 | bitmapTextureFramebuffer.release(); |
| 701 | // Continue here on purpose and retry again for next frame. In worst case, this is a continous |
| 702 | // problem and no more frames will be drawn. |
| 703 | } finally { |
| 704 | frame.release(); |
| 705 | } |
| 706 | } |
| 707 |
| 708 | protected void onFirstFrameRendered() { |
| 709 |
| 710 | } |
| 711 |
| 712 | private void notifyCallbacks(VideoFrame frame, boolean wasRendered) { |
| 713 | if (frameListeners.isEmpty()) |
| 714 | return; |
| 715 |
| 716 | drawMatrix.reset(); |
| 717 | drawMatrix.preTranslate(0.5f, 0.5f); |
| 718 | drawMatrix.preScale(mirrorHorizontally ? -1f : 1f, mirrorVertically ? -1f : 1f); |
| 719 | drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap. |
| 720 | drawMatrix.preTranslate(-0.5f, -0.5f); |
| 721 |
| 722 | Iterator<FrameListenerAndParams> it = frameListeners.iterator(); |
| 723 | while (it.hasNext()) { |
| 724 | FrameListenerAndParams listenerAndParams = it.next(); |
| 725 | if (!wasRendered && listenerAndParams.applyFpsReduction) { |
| 726 | continue; |
| 727 | } |
| 728 | it.remove(); |
| 729 |
| 730 | final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth()); |
| 731 | final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight()); |
| 732 |
| 733 | if (scaledWidth == 0 || scaledHeight == 0) { |
| 734 | listenerAndParams.listener.onFrame(null); |
| 735 | continue; |
| 736 | } |
| 737 |
| 738 | bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight); |
| 739 |
| 740 | GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId()); |
| 741 | GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, |
| 742 | GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0); |
| 743 |
| 744 | GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */); |
| 745 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); |
| 746 | frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */, |
| 747 | 0 /* viewportY */, scaledWidth, scaledHeight); |
| 748 |
| 749 | final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4); |
| 750 | GLES20.glViewport(0, 0, scaledWidth, scaledHeight); |
| 751 | GLES20.glReadPixels( |
| 752 | 0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer); |
| 753 |
| 754 | GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); |
| 755 | GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks"); |
| 756 |
| 757 | final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888); |
| 758 | bitmap.copyPixelsFromBuffer(bitmapBuffer); |
| 759 | listenerAndParams.listener.onFrame(bitmap); |
| 760 | } |
| 761 | } |
| 762 |
| 763 | private String averageTimeAsString(long sumTimeNs, int count) { |
| 764 | return (count <= 0) ? "NA" : TimeUnit.NANOSECONDS.toMicros(sumTimeNs / count) + " us"; |
| 765 | } |
| 766 |
| 767 | private void logStatistics() { |
| 768 | final DecimalFormat fpsFormat = new DecimalFormat("#.0"); |
| 769 | final long currentTimeNs = System.nanoTime(); |
| 770 | synchronized (statisticsLock) { |
| 771 | final long elapsedTimeNs = currentTimeNs - statisticsStartTimeNs; |
| 772 | if (elapsedTimeNs <= 0 || (minRenderPeriodNs == Long.MAX_VALUE && framesReceived == 0)) { |
| 773 | return; |
| 774 | } |
| 775 | final float renderFps = framesRendered * TimeUnit.SECONDS.toNanos(1) / (float) elapsedTimeNs; |
| 776 | logD("Duration: " + TimeUnit.NANOSECONDS.toMillis(elapsedTimeNs) + " ms." |
| 777 | + " Frames received: " + framesReceived + "." |
| 778 | + " Dropped: " + framesDropped + "." |
| 779 | + " Rendered: " + framesRendered + "." |
| 780 | + " Render fps: " + fpsFormat.format(renderFps) + "." |
| 781 | + " Average render time: " + averageTimeAsString(renderTimeNs, framesRendered) + "." |
| 782 | + " Average swapBuffer time: " |
| 783 | + averageTimeAsString(renderSwapBufferTimeNs, framesRendered) + "."); |
| 784 | resetStatistics(currentTimeNs); |
| 785 | } |
| 786 | } |
| 787 |
| 788 | private void logE(String string, Throwable e) { |
| 789 | Logging.e(TAG, name + string, e); |
| 790 | } |
| 791 |
| 792 | private void logD(String string) { |
| 793 | Logging.d(TAG, name + string); |
| 794 | } |
| 795 |
| 796 | private void logW(String string) { |
| 797 | Logging.w(TAG, name + string); |
| 798 | } |
| 799 | } |
| 800 |