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