| 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 static android.media.MediaCodecInfo.CodecProfileLevel.AVCLevel3; |
| 14 | import static android.media.MediaCodecInfo.CodecProfileLevel.AVCProfileHigh; |
| 15 | import static android.media.MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR; |
| 16 |
| 17 | import android.media.MediaCodec; |
| 18 | import android.media.MediaCodecInfo; |
| 19 | import android.media.MediaCodecInfo.CodecCapabilities; |
| 20 | import android.media.MediaFormat; |
| 21 | import android.opengl.GLES20; |
| 22 | import android.os.Build; |
| 23 | import android.os.Bundle; |
| 24 | import android.view.Surface; |
| 25 | import androidx.annotation.Nullable; |
| 26 | import java.io.IOException; |
| 27 | import java.nio.ByteBuffer; |
| 28 | import java.util.Map; |
| 29 | import java.util.concurrent.BlockingDeque; |
| 30 | import java.util.concurrent.LinkedBlockingDeque; |
| 31 | import java.util.concurrent.TimeUnit; |
| 32 |
| 33 | import org.telegram.messenger.FileLog; |
| 34 | import org.webrtc.ThreadUtils.ThreadChecker; |
| 35 |
| 36 | /** |
| 37 | * Android hardware video encoder. |
| 38 | */ |
| 39 | class HardwareVideoEncoder implements VideoEncoder { |
| 40 | private static final String TAG = "HardwareVideoEncoder"; |
| 41 |
| 42 | private static final int MAX_VIDEO_FRAMERATE = 30; |
| 43 |
| 44 | // See MAX_ENCODER_Q_SIZE in androidmediaencoder.cc. |
| 45 | private static final int MAX_ENCODER_Q_SIZE = 2; |
| 46 |
| 47 | private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; |
| 48 | private static final int DEQUEUE_OUTPUT_BUFFER_TIMEOUT_US = 100000; |
| 49 |
| 50 | // Size of the input frames should be multiple of 16 for the H/W encoder. |
| 51 | private static final int REQUIRED_RESOLUTION_ALIGNMENT = 16; |
| 52 |
| 53 | /** |
| 54 | * Keeps track of the number of output buffers that have been passed down the pipeline and not yet |
| 55 | * released. We need to wait for this to go down to zero before operations invalidating the output |
| 56 | * buffers, i.e., stop() and getOutputBuffer(). |
| 57 | */ |
| 58 | private static class BusyCount { |
| 59 | private final Object countLock = new Object(); |
| 60 | private int count; |
| 61 |
| 62 | public void increment() { |
| 63 | synchronized (countLock) { |
| 64 | count++; |
| 65 | } |
| 66 | } |
| 67 |
| 68 | // This method may be called on an arbitrary thread. |
| 69 | public void decrement() { |
| 70 | synchronized (countLock) { |
| 71 | count--; |
| 72 | if (count == 0) { |
| 73 | countLock.notifyAll(); |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 |
| 78 | // The increment and waitForZero methods are called on the same thread (deliverEncodedImage, |
| 79 | // running on the output thread). Hence, after waitForZero returns, the count will stay zero |
| 80 | // until the same thread calls increment. |
| 81 | public void waitForZero() { |
| 82 | boolean wasInterrupted = false; |
| 83 | synchronized (countLock) { |
| 84 | while (count > 0) { |
| 85 | try { |
| 86 | countLock.wait(); |
| 87 | } catch (InterruptedException e) { |
| 88 | Logging.e(TAG, "Interrupted while waiting on busy count", e); |
| 89 | wasInterrupted = true; |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 |
| 94 | if (wasInterrupted) { |
| 95 | Thread.currentThread().interrupt(); |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | // --- Initialized on construction. |
| 100 | private final MediaCodecWrapperFactory mediaCodecWrapperFactory; |
| 101 | private final String codecName; |
| 102 | private final VideoCodecMimeType codecType; |
| 103 | private final Integer surfaceColorFormat; |
| 104 | private final Integer yuvColorFormat; |
| 105 | private final Map<String, String> params; |
| 106 | private final int keyFrameIntervalSec; // Base interval for generating key frames. |
| 107 | // Interval at which to force a key frame. Used to reduce color distortions caused by some |
| 108 | // Qualcomm video encoders. |
| 109 | private final long forcedKeyFrameNs; |
| 110 | private final BitrateAdjuster bitrateAdjuster; |
| 111 | // EGL context shared with the application. Used to access texture inputs. |
| 112 | private final EglBase14.Context sharedContext; |
| 113 |
| 114 | // Drawer used to draw input textures onto the codec's input surface. |
| 115 | private final GlRectDrawer textureDrawer = new GlRectDrawer(); |
| 116 | private final VideoFrameDrawer videoFrameDrawer = new VideoFrameDrawer(); |
| 117 | // A queue of EncodedImage.Builders that correspond to frames in the codec. These builders are |
| 118 | // pre-populated with all the information that can't be sent through MediaCodec. |
| 119 | private final BlockingDeque<EncodedImage.Builder> outputBuilders = new LinkedBlockingDeque<>(); |
| 120 |
| 121 | private final ThreadChecker encodeThreadChecker = new ThreadChecker(); |
| 122 | private final ThreadChecker outputThreadChecker = new ThreadChecker(); |
| 123 | private final BusyCount outputBuffersBusyCount = new BusyCount(); |
| 124 |
| 125 | // --- Set on initialize and immutable until release. |
| 126 | private Callback callback; |
| 127 | private boolean automaticResizeOn; |
| 128 |
| 129 | // --- Valid and immutable while an encoding session is running. |
| 130 | @Nullable private MediaCodecWrapper codec; |
| 131 | // Thread that delivers encoded frames to the user callback. |
| 132 | @Nullable private Thread outputThread; |
| 133 |
| 134 | // EGL base wrapping the shared texture context. Holds hooks to both the shared context and the |
| 135 | // input surface. Making this base current allows textures from the context to be drawn onto the |
| 136 | // surface. |
| 137 | @Nullable private EglBase14 textureEglBase; |
| 138 | // Input surface for the codec. The encoder will draw input textures onto this surface. |
| 139 | @Nullable private Surface textureInputSurface; |
| 140 |
| 141 | private int width; |
| 142 | private int height; |
| 143 | // Y-plane strides in the encoder's input |
| 144 | private int stride; |
| 145 | // Y-plane slice-height in the encoder's input |
| 146 | private int sliceHeight; |
| 147 | // True if encoder input color format is semi-planar (NV12). |
| 148 | private boolean isSemiPlanar; |
| 149 | // Size of frame for current color format and stride, in bytes. |
| 150 | private int frameSizeBytes; |
| 151 | private boolean useSurfaceMode; |
| 152 |
| 153 | // --- Only accessed from the encoding thread. |
| 154 | // Presentation timestamp of next frame to encode. |
| 155 | private long nextPresentationTimestampUs; |
| 156 | // Presentation timestamp of the last requested (or forced) key frame. |
| 157 | private long lastKeyFrameNs; |
| 158 |
| 159 | // --- Only accessed on the output thread. |
| 160 | // Contents of the last observed config frame output by the MediaCodec. Used by H.264. |
| 161 | @Nullable private ByteBuffer configBuffer; |
| 162 | private int adjustedBitrate; |
| 163 |
| 164 | // Whether the encoder is running. Volatile so that the output thread can watch this value and |
| 165 | // exit when the encoder stops. |
| 166 | private volatile boolean running; |
| 167 | // Any exception thrown during shutdown. The output thread releases the MediaCodec and uses this |
| 168 | // value to send exceptions thrown during release back to the encoder thread. |
| 169 | @Nullable private volatile Exception shutdownException; |
| 170 |
| 171 | // True if collection of encoding statistics is enabled. |
| 172 | private boolean isEncodingStatisticsEnabled; |
| 173 |
| 174 | /** |
| 175 | * Creates a new HardwareVideoEncoder with the given codecName, codecType, colorFormat, key frame |
| 176 | * intervals, and bitrateAdjuster. |
| 177 | * |
| 178 | * @param codecName the hardware codec implementation to use |
| 179 | * @param codecType the type of the given video codec (eg. VP8, VP9, H264, H265, AV1) |
| 180 | * @param surfaceColorFormat color format for surface mode or null if not available |
| 181 | * @param yuvColorFormat color format for bytebuffer mode |
| 182 | * @param keyFrameIntervalSec interval in seconds between key frames; used to initialize the codec |
| 183 | * @param forceKeyFrameIntervalMs interval at which to force a key frame if one is not requested; |
| 184 | * used to reduce distortion caused by some codec implementations |
| 185 | * @param bitrateAdjuster algorithm used to correct codec implementations that do not produce the |
| 186 | * desired bitrates |
| 187 | * @throws IllegalArgumentException if colorFormat is unsupported |
| 188 | */ |
| 189 | public HardwareVideoEncoder(MediaCodecWrapperFactory mediaCodecWrapperFactory, String codecName, |
| 190 | VideoCodecMimeType codecType, Integer surfaceColorFormat, Integer yuvColorFormat, |
| 191 | Map<String, String> params, int keyFrameIntervalSec, int forceKeyFrameIntervalMs, |
| 192 | BitrateAdjuster bitrateAdjuster, EglBase14.Context sharedContext) { |
| 193 | this.mediaCodecWrapperFactory = mediaCodecWrapperFactory; |
| 194 | this.codecName = codecName; |
| 195 | this.codecType = codecType; |
| 196 | this.surfaceColorFormat = surfaceColorFormat; |
| 197 | this.yuvColorFormat = yuvColorFormat; |
| 198 | this.params = params; |
| 199 | this.keyFrameIntervalSec = keyFrameIntervalSec; |
| 200 | this.forcedKeyFrameNs = TimeUnit.MILLISECONDS.toNanos(forceKeyFrameIntervalMs); |
| 201 | this.bitrateAdjuster = bitrateAdjuster; |
| 202 | this.sharedContext = sharedContext; |
| 203 |
| 204 | // Allow construction on a different thread. |
| 205 | encodeThreadChecker.detachThread(); |
| 206 | } |
| 207 |
| 208 | @Override |
| 209 | public VideoCodecStatus initEncode(Settings settings, Callback callback) { |
| 210 | encodeThreadChecker.checkIsOnValidThread(); |
| 211 |
| 212 | this.callback = callback; |
| 213 | automaticResizeOn = settings.automaticResizeOn; |
| 214 |
| 215 | this.width = settings.width; |
| 216 | this.height = settings.height; |
| 217 | useSurfaceMode = canUseSurface(); |
| 218 |
| 219 | if (settings.startBitrate != 0 && settings.maxFramerate != 0) { |
| 220 | bitrateAdjuster.setTargets(settings.startBitrate * 1000, settings.maxFramerate); |
| 221 | } |
| 222 | adjustedBitrate = bitrateAdjuster.getAdjustedBitrateBps(); |
| 223 |
| 224 | Logging.d(TAG, |
| 225 | "initEncode name: " + codecName + " type: " + codecType + " width: " + width |
| 226 | + " height: " + height + " framerate_fps: " + settings.maxFramerate |
| 227 | + " bitrate_kbps: " + settings.startBitrate + " surface mode: " + useSurfaceMode); |
| 228 | return initEncodeInternal(); |
| 229 | } |
| 230 |
| 231 | private VideoCodecStatus initEncodeInternal() { |
| 232 | encodeThreadChecker.checkIsOnValidThread(); |
| 233 |
| 234 | nextPresentationTimestampUs = 0; |
| 235 | lastKeyFrameNs = -1; |
| 236 |
| 237 | isEncodingStatisticsEnabled = false; |
| 238 |
| 239 | try { |
| 240 | codec = mediaCodecWrapperFactory.createByCodecName(codecName); |
| 241 | } catch (IOException | IllegalArgumentException e) { |
| 242 | Logging.e(TAG, "Cannot create media encoder " + codecName); |
| 243 | return VideoCodecStatus.FALLBACK_SOFTWARE; |
| 244 | } |
| 245 |
| 246 | final int colorFormat = useSurfaceMode ? surfaceColorFormat : yuvColorFormat; |
| 247 | try { |
| 248 | MediaFormat format = MediaFormat.createVideoFormat(codecType.mimeType(), width, height); |
| 249 | format.setInteger(MediaFormat.KEY_BIT_RATE, adjustedBitrate); |
| 250 | format.setInteger(MediaFormat.KEY_BITRATE_MODE, BITRATE_MODE_CBR); |
| 251 | format.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat); |
| 252 | format.setFloat( |
| 253 | MediaFormat.KEY_FRAME_RATE, (float) bitrateAdjuster.getAdjustedFramerateFps()); |
| 254 | format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameIntervalSec); |
| 255 | if (codecType == VideoCodecMimeType.H264) { |
| 256 | String profileLevelId = params.get(VideoCodecInfo.H264_FMTP_PROFILE_LEVEL_ID); |
| 257 | if (profileLevelId == null) { |
| 258 | profileLevelId = VideoCodecInfo.H264_CONSTRAINED_BASELINE_3_1; |
| 259 | } |
| 260 | switch (profileLevelId) { |
| 261 | case VideoCodecInfo.H264_CONSTRAINED_HIGH_3_1: |
| 262 | format.setInteger("profile", AVCProfileHigh); |
| 263 | format.setInteger("level", AVCLevel3); |
| 264 | break; |
| 265 | case VideoCodecInfo.H264_CONSTRAINED_BASELINE_3_1: |
| 266 | break; |
| 267 | default: |
| 268 | Logging.w(TAG, "Unknown profile level id: " + profileLevelId); |
| 269 | } |
| 270 | } |
| 271 |
| 272 | if (codecName.equals("c2.google.av1.encoder")) { |
| 273 | // Enable RTC mode in AV1 HW encoder. |
| 274 | format.setInteger("vendor.google-av1enc.encoding-preset.int32.value", 1); |
| 275 | } |
| 276 |
| 277 | if (isEncodingStatisticsSupported()) { |
| 278 | format.setInteger(MediaFormat.KEY_VIDEO_ENCODING_STATISTICS_LEVEL, |
| 279 | MediaFormat.VIDEO_ENCODING_STATISTICS_LEVEL_1); |
| 280 | isEncodingStatisticsEnabled = true; |
| 281 | } |
| 282 |
| 283 | Logging.d(TAG, "Format: " + format); |
| 284 | codec.configure( |
| 285 | format, null /* surface */, null /* crypto */, MediaCodec.CONFIGURE_FLAG_ENCODE); |
| 286 |
| 287 | if (useSurfaceMode) { |
| 288 | textureEglBase = EglBase.createEgl14(sharedContext, EglBase.CONFIG_RECORDABLE); |
| 289 | textureInputSurface = codec.createInputSurface(); |
| 290 | textureEglBase.createSurface(textureInputSurface); |
| 291 | textureEglBase.makeCurrent(); |
| 292 | } |
| 293 |
| 294 | updateInputFormat(codec.getInputFormat()); |
| 295 |
| 296 | codec.start(); |
| 297 | } catch (IllegalArgumentException | IllegalStateException e) { |
| 298 | Logging.e(TAG, "initEncodeInternal failed", e); |
| 299 | release(); |
| 300 | return VideoCodecStatus.FALLBACK_SOFTWARE; |
| 301 | } |
| 302 |
| 303 | running = true; |
| 304 | outputThreadChecker.detachThread(); |
| 305 | outputThread = createOutputThread(); |
| 306 | outputThread.start(); |
| 307 |
| 308 | return VideoCodecStatus.OK; |
| 309 | } |
| 310 |
| 311 | @Override |
| 312 | public VideoCodecStatus release() { |
| 313 | encodeThreadChecker.checkIsOnValidThread(); |
| 314 |
| 315 | final VideoCodecStatus returnValue; |
| 316 | if (outputThread == null) { |
| 317 | returnValue = VideoCodecStatus.OK; |
| 318 | } else { |
| 319 | // The outputThread actually stops and releases the codec once running is false. |
| 320 | running = false; |
| 321 | if (!ThreadUtils.joinUninterruptibly(outputThread, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) { |
| 322 | Logging.e(TAG, "Media encoder release timeout"); |
| 323 | returnValue = VideoCodecStatus.TIMEOUT; |
| 324 | } else if (shutdownException != null) { |
| 325 | // Log the exception and turn it into an error. |
| 326 | Logging.e(TAG, "Media encoder release exception", shutdownException); |
| 327 | returnValue = VideoCodecStatus.ERROR; |
| 328 | } else { |
| 329 | returnValue = VideoCodecStatus.OK; |
| 330 | } |
| 331 | } |
| 332 |
| 333 | textureDrawer.release(); |
| 334 | videoFrameDrawer.release(); |
| 335 | if (textureEglBase != null) { |
| 336 | textureEglBase.release(); |
| 337 | textureEglBase = null; |
| 338 | } |
| 339 | if (textureInputSurface != null) { |
| 340 | textureInputSurface.release(); |
| 341 | textureInputSurface = null; |
| 342 | } |
| 343 | outputBuilders.clear(); |
| 344 |
| 345 | codec = null; |
| 346 | outputThread = null; |
| 347 |
| 348 | // Allow changing thread after release. |
| 349 | encodeThreadChecker.detachThread(); |
| 350 |
| 351 | return returnValue; |
| 352 | } |
| 353 |
| 354 | @Override |
| 355 | public VideoCodecStatus encode(VideoFrame videoFrame, EncodeInfo encodeInfo) { |
| 356 | encodeThreadChecker.checkIsOnValidThread(); |
| 357 | if (codec == null) { |
| 358 | return VideoCodecStatus.UNINITIALIZED; |
| 359 | } |
| 360 |
| 361 | final VideoFrame.Buffer videoFrameBuffer = videoFrame.getBuffer(); |
| 362 | final boolean isTextureBuffer = videoFrame.getBuffer() instanceof VideoFrame.TextureBuffer; |
| 363 |
| 364 | // If input resolution changed, restart the codec with the new resolution. |
| 365 | final int frameWidth = videoFrame.getBuffer().getWidth(); |
| 366 | final int frameHeight = videoFrame.getBuffer().getHeight(); |
| 367 | final boolean shouldUseSurfaceMode = canUseSurface() && isTextureBuffer; |
| 368 | if (frameWidth != width || frameHeight != height || shouldUseSurfaceMode != useSurfaceMode) { |
| 369 | VideoCodecStatus status = resetCodec(frameWidth, frameHeight, shouldUseSurfaceMode); |
| 370 | if (status != VideoCodecStatus.OK) { |
| 371 | return status; |
| 372 | } |
| 373 | } |
| 374 |
| 375 | if (outputBuilders.size() > MAX_ENCODER_Q_SIZE) { |
| 376 | // Too many frames in the encoder. Drop this frame. |
| 377 | Logging.e(TAG, "Dropped frame, encoder queue full"); |
| 378 | return VideoCodecStatus.NO_OUTPUT; // See webrtc bug 2887. |
| 379 | } |
| 380 |
| 381 | boolean requestedKeyFrame = false; |
| 382 | for (EncodedImage.FrameType frameType : encodeInfo.frameTypes) { |
| 383 | if (frameType == EncodedImage.FrameType.VideoFrameKey) { |
| 384 | requestedKeyFrame = true; |
| 385 | } |
| 386 | } |
| 387 |
| 388 | if (requestedKeyFrame || shouldForceKeyFrame(videoFrame.getTimestampNs())) { |
| 389 | requestKeyFrame(videoFrame.getTimestampNs()); |
| 390 | } |
| 391 |
| 392 | // Number of bytes in the video buffer. Y channel is sampled at one byte per pixel; U and V are |
| 393 | // subsampled at one byte per four pixels. |
| 394 | int bufferSize = videoFrameBuffer.getHeight() * videoFrameBuffer.getWidth() * 3 / 2; |
| 395 | EncodedImage.Builder builder = EncodedImage.builder() |
| 396 | .setCaptureTimeNs(videoFrame.getTimestampNs()) |
| 397 | .setEncodedWidth(videoFrame.getBuffer().getWidth()) |
| 398 | .setEncodedHeight(videoFrame.getBuffer().getHeight()) |
| 399 | .setRotation(videoFrame.getRotation()); |
| 400 | outputBuilders.offer(builder); |
| 401 |
| 402 | long presentationTimestampUs = nextPresentationTimestampUs; |
| 403 | // Round frame duration down to avoid bitrate overshoot. |
| 404 | long frameDurationUs = |
| 405 | (long) (TimeUnit.SECONDS.toMicros(1) / bitrateAdjuster.getAdjustedFramerateFps()); |
| 406 | nextPresentationTimestampUs += frameDurationUs; |
| 407 |
| 408 | final VideoCodecStatus returnValue; |
| 409 | if (useSurfaceMode) { |
| 410 | returnValue = encodeTextureBuffer(videoFrame, presentationTimestampUs); |
| 411 | } else { |
| 412 | returnValue = encodeByteBuffer(videoFrame, videoFrameBuffer, bufferSize); |
| 413 | } |
| 414 |
| 415 | // Check if the queue was successful. |
| 416 | if (returnValue != VideoCodecStatus.OK) { |
| 417 | // Keep the output builders in sync with buffers in the codec. |
| 418 | outputBuilders.pollLast(); |
| 419 | } |
| 420 |
| 421 | return returnValue; |
| 422 | } |
| 423 |
| 424 | private VideoCodecStatus encodeTextureBuffer( |
| 425 | VideoFrame videoFrame, long presentationTimestampUs) { |
| 426 | encodeThreadChecker.checkIsOnValidThread(); |
| 427 | try { |
| 428 | textureEglBase.makeCurrent(); |
| 429 | // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway, |
| 430 | // but it's a workaround for bug webrtc:5147. |
| 431 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); |
| 432 | // It is not necessary to release this frame because it doesn't own the buffer. |
| 433 | VideoFrame derotatedFrame = |
| 434 | new VideoFrame(videoFrame.getBuffer(), 0 /* rotation */, videoFrame.getTimestampNs()); |
| 435 | videoFrameDrawer.drawFrame(derotatedFrame, textureDrawer, null /* additionalRenderMatrix */); |
| 436 | textureEglBase.swapBuffers(TimeUnit.MICROSECONDS.toNanos(presentationTimestampUs), false); |
| 437 | } catch (RuntimeException e) { |
| 438 | Logging.e(TAG, "encodeTexture failed", e); |
| 439 | return VideoCodecStatus.ERROR; |
| 440 | } |
| 441 | return VideoCodecStatus.OK; |
| 442 | } |
| 443 |
| 444 | @Override |
| 445 | public VideoCodecStatus setRateAllocation(BitrateAllocation bitrateAllocation, int framerate) { |
| 446 | encodeThreadChecker.checkIsOnValidThread(); |
| 447 | if (framerate > MAX_VIDEO_FRAMERATE) { |
| 448 | framerate = MAX_VIDEO_FRAMERATE; |
| 449 | } |
| 450 | bitrateAdjuster.setTargets(bitrateAllocation.getSum(), framerate); |
| 451 | return VideoCodecStatus.OK; |
| 452 | } |
| 453 |
| 454 | private VideoCodecStatus encodeByteBuffer( |
| 455 | VideoFrame videoFrame, VideoFrame.Buffer videoFrameBuffer, int bufferSize) { |
| 456 | encodeThreadChecker.checkIsOnValidThread(); |
| 457 | // Frame timestamp rounded to the nearest microsecond. |
| 458 | long presentationTimestampUs = (videoFrame.getTimestampNs() + 500) / 1000; |
| 459 |
| 460 | // No timeout. Don't block for an input buffer, drop frames if the encoder falls behind. |
| 461 | int index; |
| 462 | try { |
| 463 | index = codec.dequeueInputBuffer(0 /* timeout */); |
| 464 | } catch (IllegalStateException e) { |
| 465 | Logging.e(TAG, "dequeueInputBuffer failed", e); |
| 466 | return VideoCodecStatus.ERROR; |
| 467 | } |
| 468 |
| 469 | if (index == -1) { |
| 470 | // Encoder is falling behind. No input buffers available. Drop the frame. |
| 471 | Logging.d(TAG, "Dropped frame, no input buffers available"); |
| 472 | return VideoCodecStatus.NO_OUTPUT; // See webrtc bug 2887. |
| 473 | } |
| 474 |
| 475 | ByteBuffer buffer; |
| 476 | try { |
| 477 | buffer = codec.getInputBuffer(index); |
| 478 | } catch (IllegalStateException e) { |
| 479 | Logging.e(TAG, "getInputBuffer with index=" + index + " failed", e); |
| 480 | return VideoCodecStatus.ERROR; |
| 481 | } |
| 482 |
| 483 | if (buffer.capacity() < frameSizeBytes) { |
| 484 | Logging.e(TAG, |
| 485 | "Input buffer size: " + buffer.capacity() |
| 486 | + " is smaller than frame size: " + frameSizeBytes); |
| 487 | return VideoCodecStatus.ERROR; |
| 488 | } |
| 489 |
| 490 | fillInputBuffer(buffer, videoFrame.getBuffer()); |
| 491 |
| 492 | try { |
| 493 | codec.queueInputBuffer( |
| 494 | index, 0 /* offset */, frameSizeBytes, presentationTimestampUs, 0 /* flags */); |
| 495 | } catch (IllegalStateException e) { |
| 496 | Logging.e(TAG, "queueInputBuffer failed", e); |
| 497 | // IllegalStateException thrown when the codec is in the wrong state. |
| 498 | return VideoCodecStatus.ERROR; |
| 499 | } |
| 500 | return VideoCodecStatus.OK; |
| 501 | } |
| 502 |
| 503 | @Override |
| 504 | public VideoCodecStatus setRates(RateControlParameters rcParameters) { |
| 505 | encodeThreadChecker.checkIsOnValidThread(); |
| 506 | bitrateAdjuster.setTargets(rcParameters.bitrate.getSum(), rcParameters.framerateFps); |
| 507 | return VideoCodecStatus.OK; |
| 508 | } |
| 509 |
| 510 | @Override |
| 511 | public ScalingSettings getScalingSettings() { |
| 512 | if (automaticResizeOn) { |
| 513 | if (codecType == VideoCodecMimeType.VP8) { |
| 514 | final int kLowVp8QpThreshold = 29; |
| 515 | final int kHighVp8QpThreshold = 95; |
| 516 | return new ScalingSettings(kLowVp8QpThreshold, kHighVp8QpThreshold); |
| 517 | } else if (codecType == VideoCodecMimeType.H264) { |
| 518 | final int kLowH264QpThreshold = 24; |
| 519 | final int kHighH264QpThreshold = 37; |
| 520 | return new ScalingSettings(kLowH264QpThreshold, kHighH264QpThreshold); |
| 521 | } |
| 522 | } |
| 523 | return ScalingSettings.OFF; |
| 524 | } |
| 525 |
| 526 | @Override |
| 527 | public String getImplementationName() { |
| 528 | return codecName; |
| 529 | } |
| 530 |
| 531 | @Override |
| 532 | public EncoderInfo getEncoderInfo() { |
| 533 | // Since our MediaCodec is guaranteed to encode 16-pixel-aligned frames only, we set alignment |
| 534 | // value to be 16. Additionally, this encoder produces a single stream. So it should not require |
| 535 | // alignment for all layers. |
| 536 | return new EncoderInfo( |
| 537 | /* requestedResolutionAlignment= */ REQUIRED_RESOLUTION_ALIGNMENT, |
| 538 | /* applyAlignmentToAllSimulcastLayers= */ false); |
| 539 | } |
| 540 |
| 541 | private VideoCodecStatus resetCodec(int newWidth, int newHeight, boolean newUseSurfaceMode) { |
| 542 | FileLog.d("resetCodec " + newWidth + "x" + newHeight); |
| 543 | encodeThreadChecker.checkIsOnValidThread(); |
| 544 | VideoCodecStatus status = release(); |
| 545 | if (status != VideoCodecStatus.OK) { |
| 546 | return status; |
| 547 | } |
| 548 | width = newWidth; |
| 549 | height = newHeight; |
| 550 | useSurfaceMode = newUseSurfaceMode; |
| 551 | return initEncodeInternal(); |
| 552 | } |
| 553 |
| 554 | private boolean shouldForceKeyFrame(long presentationTimestampNs) { |
| 555 | encodeThreadChecker.checkIsOnValidThread(); |
| 556 | return forcedKeyFrameNs > 0 && presentationTimestampNs > lastKeyFrameNs + forcedKeyFrameNs; |
| 557 | } |
| 558 |
| 559 | private void requestKeyFrame(long presentationTimestampNs) { |
| 560 | encodeThreadChecker.checkIsOnValidThread(); |
| 561 | // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could |
| 562 | // indicate this in queueInputBuffer() below and guarantee _this_ frame |
| 563 | // be encoded as a key frame, but sadly that flag is ignored. Instead, |
| 564 | // we request a key frame "soon". |
| 565 | try { |
| 566 | Bundle b = new Bundle(); |
| 567 | b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0); |
| 568 | codec.setParameters(b); |
| 569 | } catch (IllegalStateException e) { |
| 570 | Logging.e(TAG, "requestKeyFrame failed", e); |
| 571 | return; |
| 572 | } |
| 573 | lastKeyFrameNs = presentationTimestampNs; |
| 574 | } |
| 575 |
| 576 | private Thread createOutputThread() { |
| 577 | return new Thread() { |
| 578 | @Override |
| 579 | public void run() { |
| 580 | while (running) { |
| 581 | deliverEncodedImage(); |
| 582 | } |
| 583 | releaseCodecOnOutputThread(); |
| 584 | } |
| 585 | }; |
| 586 | } |
| 587 |
| 588 | // Visible for testing. |
| 589 | protected void deliverEncodedImage() { |
| 590 | outputThreadChecker.checkIsOnValidThread(); |
| 591 | try { |
| 592 | MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); |
| 593 | int index = codec.dequeueOutputBuffer(info, DEQUEUE_OUTPUT_BUFFER_TIMEOUT_US); |
| 594 | if (index < 0) { |
| 595 | if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { |
| 596 | outputBuffersBusyCount.waitForZero(); |
| 597 | } |
| 598 | return; |
| 599 | } |
| 600 |
| 601 | ByteBuffer outputBuffer = codec.getOutputBuffer(index); |
| 602 | outputBuffer.position(info.offset); |
| 603 | outputBuffer.limit(info.offset + info.size); |
| 604 |
| 605 | if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { |
| 606 | Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size); |
| 607 | if (info.size > 0 |
| 608 | && (codecType == VideoCodecMimeType.H264 || codecType == VideoCodecMimeType.H265)) { |
| 609 | // In case of H264 and H265 config buffer contains SPS and PPS headers. Presence of these |
| 610 | // headers makes IDR frame a truly keyframe. Some encoders issue IDR frames without SPS |
| 611 | // and PPS. We save config buffer here to prepend it to all IDR frames encoder delivers. |
| 612 | configBuffer = ByteBuffer.allocateDirect(info.size); |
| 613 | configBuffer.put(outputBuffer); |
| 614 | } |
| 615 | return; |
| 616 | } |
| 617 |
| 618 | bitrateAdjuster.reportEncodedFrame(info.size); |
| 619 | if (adjustedBitrate != bitrateAdjuster.getAdjustedBitrateBps()) { |
| 620 | updateBitrate(); |
| 621 | } |
| 622 |
| 623 | final boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0; |
| 624 | if (isKeyFrame) { |
| 625 | Logging.d(TAG, "Sync frame generated"); |
| 626 | } |
| 627 |
| 628 | // Extract QP before releasing output buffer. |
| 629 | Integer qp = null; |
| 630 | if (isEncodingStatisticsEnabled) { |
| 631 | MediaFormat format = codec.getOutputFormat(index); |
| 632 | if (format != null && format.containsKey(MediaFormat.KEY_VIDEO_QP_AVERAGE)) { |
| 633 | qp = format.getInteger(MediaFormat.KEY_VIDEO_QP_AVERAGE); |
| 634 | } |
| 635 | } |
| 636 |
| 637 | final ByteBuffer frameBuffer; |
| 638 | final Runnable releaseCallback; |
| 639 | if (isKeyFrame && configBuffer != null) { |
| 640 | Logging.d(TAG, |
| 641 | "Prepending config buffer of size " + configBuffer.capacity() |
| 642 | + " to output buffer with offset " + info.offset + ", size " + info.size); |
| 643 | frameBuffer = ByteBuffer.allocateDirect(info.size + configBuffer.capacity()); |
| 644 | configBuffer.rewind(); |
| 645 | frameBuffer.put(configBuffer); |
| 646 | frameBuffer.put(outputBuffer); |
| 647 | frameBuffer.rewind(); |
| 648 | codec.releaseOutputBuffer(index, /* render= */ false); |
| 649 | releaseCallback = null; |
| 650 | } else { |
| 651 | frameBuffer = outputBuffer.slice(); |
| 652 | outputBuffersBusyCount.increment(); |
| 653 | releaseCallback = () -> { |
| 654 | // This callback should not throw any exceptions since |
| 655 | // it may be called on an arbitrary thread. |
| 656 | // Check bug webrtc:11230 for more details. |
| 657 | try { |
| 658 | codec.releaseOutputBuffer(index, /* render= */ false); |
| 659 | } catch (Exception e) { |
| 660 | Logging.e(TAG, "releaseOutputBuffer failed", e); |
| 661 | } |
| 662 | outputBuffersBusyCount.decrement(); |
| 663 | }; |
| 664 | } |
| 665 |
| 666 | final EncodedImage.FrameType frameType = isKeyFrame ? EncodedImage.FrameType.VideoFrameKey |
| 667 | : EncodedImage.FrameType.VideoFrameDelta; |
| 668 |
| 669 | EncodedImage.Builder builder = outputBuilders.poll(); |
| 670 | builder.setBuffer(frameBuffer, releaseCallback); |
| 671 | builder.setFrameType(frameType); |
| 672 | builder.setQp(qp); |
| 673 |
| 674 | EncodedImage encodedImage = builder.createEncodedImage(); |
| 675 | // TODO(mellem): Set codec-specific info. |
| 676 | callback.onEncodedFrame(encodedImage, new CodecSpecificInfo()); |
| 677 | // Note that the callback may have retained the image. |
| 678 | encodedImage.release(); |
| 679 | } catch (IllegalStateException e) { |
| 680 | Logging.e(TAG, "deliverOutput failed", e); |
| 681 | } |
| 682 | } |
| 683 |
| 684 | private void releaseCodecOnOutputThread() { |
| 685 | outputThreadChecker.checkIsOnValidThread(); |
| 686 | Logging.d(TAG, "Releasing MediaCodec on output thread"); |
| 687 | outputBuffersBusyCount.waitForZero(); |
| 688 | try { |
| 689 | codec.stop(); |
| 690 | } catch (Exception e) { |
| 691 | Logging.e(TAG, "Media encoder stop failed", e); |
| 692 | } |
| 693 | try { |
| 694 | codec.release(); |
| 695 | } catch (Exception e) { |
| 696 | Logging.e(TAG, "Media encoder release failed", e); |
| 697 | // Propagate exceptions caught during release back to the main thread. |
| 698 | shutdownException = e; |
| 699 | } |
| 700 | configBuffer = null; |
| 701 | Logging.d(TAG, "Release on output thread done"); |
| 702 | } |
| 703 |
| 704 | private VideoCodecStatus updateBitrate() { |
| 705 | outputThreadChecker.checkIsOnValidThread(); |
| 706 | adjustedBitrate = bitrateAdjuster.getAdjustedBitrateBps(); |
| 707 | try { |
| 708 | Bundle params = new Bundle(); |
| 709 | params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, adjustedBitrate); |
| 710 | codec.setParameters(params); |
| 711 | return VideoCodecStatus.OK; |
| 712 | } catch (IllegalStateException e) { |
| 713 | Logging.e(TAG, "updateBitrate failed", e); |
| 714 | return VideoCodecStatus.ERROR; |
| 715 | } |
| 716 | } |
| 717 |
| 718 | private boolean canUseSurface() { |
| 719 | return sharedContext != null && surfaceColorFormat != null; |
| 720 | } |
| 721 |
| 722 | /** Fetches stride and slice height from input media format */ |
| 723 | private void updateInputFormat(MediaFormat format) { |
| 724 | stride = width; |
| 725 | sliceHeight = height; |
| 726 |
| 727 | if (format != null) { |
| 728 | if (format.containsKey(MediaFormat.KEY_STRIDE)) { |
| 729 | stride = format.getInteger(MediaFormat.KEY_STRIDE); |
| 730 | stride = Math.max(stride, width); |
| 731 | } |
| 732 |
| 733 | if (format.containsKey(MediaFormat.KEY_SLICE_HEIGHT)) { |
| 734 | sliceHeight = format.getInteger(MediaFormat.KEY_SLICE_HEIGHT); |
| 735 | sliceHeight = Math.max(sliceHeight, height); |
| 736 | } |
| 737 | } |
| 738 |
| 739 | isSemiPlanar = isSemiPlanar(yuvColorFormat); |
| 740 | if (isSemiPlanar) { |
| 741 | int chromaHeight = (height + 1) / 2; |
| 742 | frameSizeBytes = sliceHeight * stride + chromaHeight * stride; |
| 743 | } else { |
| 744 | int chromaStride = (stride + 1) / 2; |
| 745 | int chromaSliceHeight = (sliceHeight + 1) / 2; |
| 746 | frameSizeBytes = sliceHeight * stride + chromaSliceHeight * chromaStride * 2; |
| 747 | } |
| 748 |
| 749 | Logging.d(TAG, |
| 750 | "updateInputFormat format: " + format + " stride: " + stride |
| 751 | + " sliceHeight: " + sliceHeight + " isSemiPlanar: " + isSemiPlanar |
| 752 | + " frameSizeBytes: " + frameSizeBytes); |
| 753 | } |
| 754 |
| 755 | protected boolean isEncodingStatisticsSupported() { |
| 756 | // WebRTC quality scaler, which adjusts resolution and/or frame rate based on encoded QP, |
| 757 | // expects QP to be in native bitstream range for given codec. Native QP range for VP8 is |
| 758 | // [0, 127] and for VP9 is [0, 255]. MediaCodec VP8 and VP9 encoders (perhaps not all) |
| 759 | // return QP in range [0, 64], which is libvpx API specific range. Due to this mismatch we |
| 760 | // can't use QP feedback from these codecs. |
| 761 | if (codecType == VideoCodecMimeType.VP8 || codecType == VideoCodecMimeType.VP9) { |
| 762 | return false; |
| 763 | } |
| 764 |
| 765 | MediaCodecInfo codecInfo = codec.getCodecInfo(); |
| 766 | if (codecInfo == null) { |
| 767 | return false; |
| 768 | } |
| 769 |
| 770 | CodecCapabilities codecCaps = codecInfo.getCapabilitiesForType(codecType.mimeType()); |
| 771 | if (codecCaps == null) { |
| 772 | return false; |
| 773 | } |
| 774 |
| 775 | return codecCaps.isFeatureSupported(CodecCapabilities.FEATURE_EncodingStatistics); |
| 776 | } |
| 777 |
| 778 | // Visible for testing. |
| 779 | protected void fillInputBuffer(ByteBuffer buffer, VideoFrame.Buffer frame) { |
| 780 | VideoFrame.I420Buffer i420 = frame.toI420(); |
| 781 | if (isSemiPlanar) { |
| 782 | YuvHelper.I420ToNV12(i420.getDataY(), i420.getStrideY(), i420.getDataU(), i420.getStrideU(), |
| 783 | i420.getDataV(), i420.getStrideV(), buffer, i420.getWidth(), i420.getHeight(), stride, |
| 784 | sliceHeight); |
| 785 | } else { |
| 786 | YuvHelper.I420Copy(i420.getDataY(), i420.getStrideY(), i420.getDataU(), i420.getStrideU(), |
| 787 | i420.getDataV(), i420.getStrideV(), buffer, i420.getWidth(), i420.getHeight(), stride, |
| 788 | sliceHeight); |
| 789 | } |
| 790 | i420.release(); |
| 791 | } |
| 792 |
| 793 | protected boolean isSemiPlanar(int colorFormat) { |
| 794 | switch (colorFormat) { |
| 795 | case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: |
| 796 | return false; |
| 797 | case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: |
| 798 | case MediaCodecInfo.CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar: |
| 799 | case MediaCodecUtils.COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m: |
| 800 | return true; |
| 801 | default: |
| 802 | throw new IllegalArgumentException("Unsupported colorFormat: " + colorFormat); |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 |