| 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.media.MediaCodec; |
| 14 | import android.media.MediaCodecInfo.CodecCapabilities; |
| 15 | import android.media.MediaFormat; |
| 16 | import android.os.SystemClock; |
| 17 | import androidx.annotation.Nullable; |
| 18 | import android.view.Surface; |
| 19 | import java.io.IOException; |
| 20 | import java.nio.ByteBuffer; |
| 21 | import java.util.concurrent.BlockingDeque; |
| 22 | import java.util.concurrent.LinkedBlockingDeque; |
| 23 | import java.util.concurrent.TimeUnit; |
| 24 |
| 25 | import org.telegram.messenger.FileLog; |
| 26 | import org.webrtc.ThreadUtils.ThreadChecker; |
| 27 |
| 28 | /** |
| 29 | * Android hardware video decoder. |
| 30 | */ |
| 31 | @SuppressWarnings("deprecation") |
| 32 | // Cannot support API 16 without using deprecated methods. |
| 33 | // TODO(sakal): Rename to MediaCodecVideoDecoder once the deprecated implementation is removed. |
| 34 | class AndroidVideoDecoder implements VideoDecoder, VideoSink { |
| 35 | private static final String TAG = "AndroidVideoDecoder"; |
| 36 |
| 37 | // TODO(magjed): Use MediaFormat.KEY_* constants when part of the public API. |
| 38 | private static final String MEDIA_FORMAT_KEY_STRIDE = "stride"; |
| 39 | private static final String MEDIA_FORMAT_KEY_SLICE_HEIGHT = "slice-height"; |
| 40 | private static final String MEDIA_FORMAT_KEY_CROP_LEFT = "crop-left"; |
| 41 | private static final String MEDIA_FORMAT_KEY_CROP_RIGHT = "crop-right"; |
| 42 | private static final String MEDIA_FORMAT_KEY_CROP_TOP = "crop-top"; |
| 43 | private static final String MEDIA_FORMAT_KEY_CROP_BOTTOM = "crop-bottom"; |
| 44 |
| 45 | // MediaCodec.release() occasionally hangs. Release stops waiting and reports failure after |
| 46 | // this timeout. |
| 47 | private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; |
| 48 |
| 49 | // WebRTC queues input frames quickly in the beginning on the call. Wait for input buffers with a |
| 50 | // long timeout (500 ms) to prevent this from causing the codec to return an error. |
| 51 | private static final int DEQUEUE_INPUT_TIMEOUT_US = 500000; |
| 52 |
| 53 | // Dequeuing an output buffer will block until a buffer is available (up to 100 milliseconds). |
| 54 | // If this timeout is exceeded, the output thread will unblock and check if the decoder is still |
| 55 | // running. If it is, it will block on dequeue again. Otherwise, it will stop and release the |
| 56 | // MediaCodec. |
| 57 | private static final int DEQUEUE_OUTPUT_BUFFER_TIMEOUT_US = 100000; |
| 58 |
| 59 | private final MediaCodecWrapperFactory mediaCodecWrapperFactory; |
| 60 | private final String codecName; |
| 61 | private final VideoCodecMimeType codecType; |
| 62 |
| 63 | private static class FrameInfo { |
| 64 | final long decodeStartTimeMs; |
| 65 | final int rotation; |
| 66 |
| 67 | FrameInfo(long decodeStartTimeMs, int rotation) { |
| 68 | this.decodeStartTimeMs = decodeStartTimeMs; |
| 69 | this.rotation = rotation; |
| 70 | } |
| 71 | } |
| 72 |
| 73 | private final BlockingDeque<FrameInfo> frameInfos; |
| 74 | private int colorFormat; |
| 75 |
| 76 | // Output thread runs a loop which polls MediaCodec for decoded output buffers. It reformats |
| 77 | // those buffers into VideoFrames and delivers them to the callback. Variable is set on decoder |
| 78 | // thread and is immutable while the codec is running. |
| 79 | @Nullable private Thread outputThread; |
| 80 |
| 81 | // Checker that ensures work is run on the output thread. |
| 82 | private ThreadChecker outputThreadChecker; |
| 83 |
| 84 | // Checker that ensures work is run on the decoder thread. The decoder thread is owned by the |
| 85 | // caller and must be used to call initDecode, decode, and release. |
| 86 | private ThreadChecker decoderThreadChecker; |
| 87 |
| 88 | private volatile boolean running; |
| 89 | @Nullable private volatile Exception shutdownException; |
| 90 |
| 91 | // Dimensions (width, height, stride, and sliceHeight) may be accessed by either the decode thread |
| 92 | // or the output thread. Accesses should be protected with this lock. |
| 93 | private final Object dimensionLock = new Object(); |
| 94 | private int width; |
| 95 | private int height; |
| 96 | private int stride; |
| 97 | private int sliceHeight; |
| 98 |
| 99 | // Whether the decoder has finished the first frame. The codec may not change output dimensions |
| 100 | // after delivering the first frame. Only accessed on the output thread while the decoder is |
| 101 | // running. |
| 102 | private boolean hasDecodedFirstFrame; |
| 103 | // Whether the decoder has seen a key frame. The first frame must be a key frame. Only accessed |
| 104 | // on the decoder thread. |
| 105 | private boolean keyFrameRequired; |
| 106 |
| 107 | private final @Nullable EglBase.Context sharedContext; |
| 108 | // Valid and immutable while the decoder is running. |
| 109 | @Nullable private SurfaceTextureHelper surfaceTextureHelper; |
| 110 | @Nullable private Surface surface; |
| 111 |
| 112 | private static class DecodedTextureMetadata { |
| 113 | final long presentationTimestampUs; |
| 114 | final Integer decodeTimeMs; |
| 115 |
| 116 | DecodedTextureMetadata(long presentationTimestampUs, Integer decodeTimeMs) { |
| 117 | this.presentationTimestampUs = presentationTimestampUs; |
| 118 | this.decodeTimeMs = decodeTimeMs; |
| 119 | } |
| 120 | } |
| 121 |
| 122 | // Metadata for the last frame rendered to the texture. |
| 123 | private final Object renderedTextureMetadataLock = new Object(); |
| 124 | @Nullable private DecodedTextureMetadata renderedTextureMetadata; |
| 125 |
| 126 | // Decoding proceeds asynchronously. This callback returns decoded frames to the caller. Valid |
| 127 | // and immutable while the decoder is running. |
| 128 | @Nullable private Callback callback; |
| 129 |
| 130 | // Valid and immutable while the decoder is running. |
| 131 | @Nullable private MediaCodecWrapper codec; |
| 132 |
| 133 | AndroidVideoDecoder(MediaCodecWrapperFactory mediaCodecWrapperFactory, String codecName, |
| 134 | VideoCodecMimeType codecType, int colorFormat, @Nullable EglBase.Context sharedContext) { |
| 135 | if (!isSupportedColorFormat(colorFormat)) { |
| 136 | throw new IllegalArgumentException("Unsupported color format: " + colorFormat); |
| 137 | } |
| 138 | Logging.d(TAG, |
| 139 | "ctor name: " + codecName + " type: " + codecType + " color format: " + colorFormat |
| 140 | + " context: " + sharedContext); |
| 141 | this.mediaCodecWrapperFactory = mediaCodecWrapperFactory; |
| 142 | this.codecName = codecName; |
| 143 | this.codecType = codecType; |
| 144 | this.colorFormat = colorFormat; |
| 145 | this.sharedContext = sharedContext; |
| 146 | this.frameInfos = new LinkedBlockingDeque<>(); |
| 147 | } |
| 148 |
| 149 | @Override |
| 150 | public VideoCodecStatus initDecode(Settings settings, Callback callback) { |
| 151 | this.decoderThreadChecker = new ThreadChecker(); |
| 152 |
| 153 | this.callback = callback; |
| 154 | if (sharedContext != null) { |
| 155 | surfaceTextureHelper = createSurfaceTextureHelper(); |
| 156 | surface = new Surface(surfaceTextureHelper.getSurfaceTexture()); |
| 157 | surfaceTextureHelper.startListening(this); |
| 158 | } |
| 159 | return initDecodeInternal(settings.width, settings.height); |
| 160 | } |
| 161 |
| 162 | // Internal variant is used when restarting the codec due to reconfiguration. |
| 163 | private VideoCodecStatus initDecodeInternal(int width, int height) { |
| 164 | decoderThreadChecker.checkIsOnValidThread(); |
| 165 | Logging.d(TAG, |
| 166 | "initDecodeInternal name: " + codecName + " type: " + codecType + " width: " + width |
| 167 | + " height: " + height); |
| 168 | if (outputThread != null) { |
| 169 | Logging.e(TAG, "initDecodeInternal called while the codec is already running"); |
| 170 | return VideoCodecStatus.FALLBACK_SOFTWARE; |
| 171 | } |
| 172 |
| 173 | // Note: it is not necessary to initialize dimensions under the lock, since the output thread |
| 174 | // is not running. |
| 175 | this.width = width; |
| 176 | this.height = height; |
| 177 |
| 178 | stride = width; |
| 179 | sliceHeight = height; |
| 180 | hasDecodedFirstFrame = false; |
| 181 | keyFrameRequired = true; |
| 182 |
| 183 | try { |
| 184 | codec = mediaCodecWrapperFactory.createByCodecName(codecName); |
| 185 | } catch (IOException | IllegalArgumentException | IllegalStateException e) { |
| 186 | Logging.e(TAG, "Cannot create media decoder " + codecName); |
| 187 | return VideoCodecStatus.FALLBACK_SOFTWARE; |
| 188 | } |
| 189 | try { |
| 190 | MediaFormat format = MediaFormat.createVideoFormat(codecType.mimeType(), width, height); |
| 191 | if (sharedContext == null) { |
| 192 | format.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat); |
| 193 | } |
| 194 | codec.configure(format, surface, null, 0); |
| 195 | codec.start(); |
| 196 | } catch (IllegalStateException | IllegalArgumentException e) { |
| 197 | Logging.e(TAG, "initDecode failed", e); |
| 198 | release(); |
| 199 | return VideoCodecStatus.FALLBACK_SOFTWARE; |
| 200 | } |
| 201 | running = true; |
| 202 | outputThread = createOutputThread(); |
| 203 | outputThread.start(); |
| 204 |
| 205 | Logging.d(TAG, "initDecodeInternal done"); |
| 206 | return VideoCodecStatus.OK; |
| 207 | } |
| 208 |
| 209 | @Override |
| 210 | public VideoCodecStatus decode(EncodedImage frame, DecodeInfo info) { |
| 211 | decoderThreadChecker.checkIsOnValidThread(); |
| 212 | if (codec == null || callback == null) { |
| 213 | Logging.d(TAG, "decode uninitalized, codec: " + (codec != null) + ", callback: " + callback); |
| 214 | return VideoCodecStatus.UNINITIALIZED; |
| 215 | } |
| 216 |
| 217 | if (frame.buffer == null) { |
| 218 | Logging.e(TAG, "decode() - no input data"); |
| 219 | return VideoCodecStatus.ERR_PARAMETER; |
| 220 | } |
| 221 |
| 222 | int size = frame.buffer.remaining(); |
| 223 | if (size == 0) { |
| 224 | Logging.e(TAG, "decode() - input buffer empty"); |
| 225 | return VideoCodecStatus.ERR_PARAMETER; |
| 226 | } |
| 227 |
| 228 | // Load dimensions from shared memory under the dimension lock. |
| 229 | final int width; |
| 230 | final int height; |
| 231 | synchronized (dimensionLock) { |
| 232 | width = this.width; |
| 233 | height = this.height; |
| 234 | } |
| 235 |
| 236 | // Check if the resolution changed and reset the codec if necessary. |
| 237 | if (frame.encodedWidth * frame.encodedHeight > 0 |
| 238 | && (frame.encodedWidth != width || frame.encodedHeight != height)) { |
| 239 | VideoCodecStatus status = reinitDecode(frame.encodedWidth, frame.encodedHeight); |
| 240 | if (status != VideoCodecStatus.OK) { |
| 241 | return status; |
| 242 | } |
| 243 | } |
| 244 |
| 245 | if (keyFrameRequired) { |
| 246 | // Need to process a key frame first. |
| 247 | if (frame.frameType != EncodedImage.FrameType.VideoFrameKey) { |
| 248 | Logging.e(TAG, "decode() - key frame required first"); |
| 249 | return VideoCodecStatus.NO_OUTPUT; |
| 250 | } |
| 251 | } |
| 252 |
| 253 | int index; |
| 254 | try { |
| 255 | index = codec.dequeueInputBuffer(DEQUEUE_INPUT_TIMEOUT_US); |
| 256 | } catch (IllegalStateException e) { |
| 257 | Logging.e(TAG, "dequeueInputBuffer failed", e); |
| 258 | return VideoCodecStatus.ERROR; |
| 259 | } |
| 260 | if (index < 0) { |
| 261 | // Decoder is falling behind. No input buffers available. |
| 262 | // The decoder can't simply drop frames; it might lose a key frame. |
| 263 | Logging.e(TAG, "decode() - no HW buffers available; decoder falling behind"); |
| 264 | return VideoCodecStatus.ERROR; |
| 265 | } |
| 266 |
| 267 | ByteBuffer buffer; |
| 268 | try { |
| 269 | buffer = codec.getInputBuffers()[index]; |
| 270 | } catch (IllegalStateException e) { |
| 271 | Logging.e(TAG, "getInputBuffers failed", e); |
| 272 | return VideoCodecStatus.ERROR; |
| 273 | } |
| 274 |
| 275 | if (buffer.capacity() < size) { |
| 276 | Logging.e(TAG, "decode() - HW buffer too small"); |
| 277 | return VideoCodecStatus.ERROR; |
| 278 | } |
| 279 | buffer.put(frame.buffer); |
| 280 |
| 281 | frameInfos.offer(new FrameInfo(SystemClock.elapsedRealtime(), frame.rotation)); |
| 282 | try { |
| 283 | codec.queueInputBuffer(index, 0 /* offset */, size, |
| 284 | TimeUnit.NANOSECONDS.toMicros(frame.captureTimeNs), 0 /* flags */); |
| 285 | } catch (IllegalStateException e) { |
| 286 | Logging.e(TAG, "queueInputBuffer failed", e); |
| 287 | frameInfos.pollLast(); |
| 288 | return VideoCodecStatus.ERROR; |
| 289 | } |
| 290 | if (keyFrameRequired) { |
| 291 | keyFrameRequired = false; |
| 292 | } |
| 293 | return VideoCodecStatus.OK; |
| 294 | } |
| 295 |
| 296 | @Override |
| 297 | public boolean getPrefersLateDecoding() { |
| 298 | return true; |
| 299 | } |
| 300 |
| 301 | @Override |
| 302 | public String getImplementationName() { |
| 303 | return codecName; |
| 304 | } |
| 305 |
| 306 | @Override |
| 307 | public VideoCodecStatus release() { |
| 308 | // TODO(sakal): This is not called on the correct thread but is still called synchronously. |
| 309 | // Re-enable the check once this is called on the correct thread. |
| 310 | // decoderThreadChecker.checkIsOnValidThread(); |
| 311 | Logging.d(TAG, "release"); |
| 312 | VideoCodecStatus status = releaseInternal(); |
| 313 | if (surface != null) { |
| 314 | releaseSurface(); |
| 315 | surface = null; |
| 316 | surfaceTextureHelper.stopListening(); |
| 317 | surfaceTextureHelper.dispose(); |
| 318 | surfaceTextureHelper = null; |
| 319 | } |
| 320 | synchronized (renderedTextureMetadataLock) { |
| 321 | renderedTextureMetadata = null; |
| 322 | } |
| 323 | callback = null; |
| 324 | frameInfos.clear(); |
| 325 | return status; |
| 326 | } |
| 327 |
| 328 | // Internal variant is used when restarting the codec due to reconfiguration. |
| 329 | private VideoCodecStatus releaseInternal() { |
| 330 | if (!running) { |
| 331 | Logging.d(TAG, "release: Decoder is not running."); |
| 332 | return VideoCodecStatus.OK; |
| 333 | } |
| 334 | try { |
| 335 | // The outputThread actually stops and releases the codec once running is false. |
| 336 | running = false; |
| 337 | if (!ThreadUtils.joinUninterruptibly(outputThread, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) { |
| 338 | // Log an exception to capture the stack trace and turn it into a TIMEOUT error. |
| 339 | Logging.e(TAG, "Media decoder release timeout", new RuntimeException()); |
| 340 | return VideoCodecStatus.TIMEOUT; |
| 341 | } |
| 342 | if (shutdownException != null) { |
| 343 | // Log the exception and turn it into an error. Wrap the exception in a new exception to |
| 344 | // capture both the output thread's stack trace and this thread's stack trace. |
| 345 | Logging.e(TAG, "Media decoder release error", new RuntimeException(shutdownException)); |
| 346 | shutdownException = null; |
| 347 | return VideoCodecStatus.ERROR; |
| 348 | } |
| 349 | } finally { |
| 350 | codec = null; |
| 351 | outputThread = null; |
| 352 | } |
| 353 | return VideoCodecStatus.OK; |
| 354 | } |
| 355 |
| 356 | private VideoCodecStatus reinitDecode(int newWidth, int newHeight) { |
| 357 | decoderThreadChecker.checkIsOnValidThread(); |
| 358 | VideoCodecStatus status = releaseInternal(); |
| 359 | if (status != VideoCodecStatus.OK) { |
| 360 | return status; |
| 361 | } |
| 362 | return initDecodeInternal(newWidth, newHeight); |
| 363 | } |
| 364 |
| 365 | private Thread createOutputThread() { |
| 366 | return new Thread("AndroidVideoDecoder.outputThread") { |
| 367 | @Override |
| 368 | public void run() { |
| 369 | outputThreadChecker = new ThreadChecker(); |
| 370 | while (running) { |
| 371 | deliverDecodedFrame(); |
| 372 | } |
| 373 | releaseCodecOnOutputThread(); |
| 374 | } |
| 375 | }; |
| 376 | } |
| 377 |
| 378 | // Visible for testing. |
| 379 | protected void deliverDecodedFrame() { |
| 380 | outputThreadChecker.checkIsOnValidThread(); |
| 381 | try { |
| 382 | MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); |
| 383 | // Block until an output buffer is available (up to 100 milliseconds). If the timeout is |
| 384 | // exceeded, deliverDecodedFrame() will be called again on the next iteration of the output |
| 385 | // thread's loop. Blocking here prevents the output thread from busy-waiting while the codec |
| 386 | // is idle. |
| 387 | int result = codec.dequeueOutputBuffer(info, DEQUEUE_OUTPUT_BUFFER_TIMEOUT_US); |
| 388 | if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { |
| 389 | reformat(codec.getOutputFormat()); |
| 390 | return; |
| 391 | } |
| 392 |
| 393 | if (result < 0) { |
| 394 | Logging.v(TAG, "dequeueOutputBuffer returned " + result); |
| 395 | return; |
| 396 | } |
| 397 |
| 398 | FrameInfo frameInfo = frameInfos.poll(); |
| 399 | Integer decodeTimeMs = null; |
| 400 | int rotation = 0; |
| 401 | if (frameInfo != null) { |
| 402 | decodeTimeMs = (int) (SystemClock.elapsedRealtime() - frameInfo.decodeStartTimeMs); |
| 403 | rotation = frameInfo.rotation; |
| 404 | } |
| 405 |
| 406 | hasDecodedFirstFrame = true; |
| 407 |
| 408 | if (surfaceTextureHelper != null) { |
| 409 | deliverTextureFrame(result, info, rotation, decodeTimeMs); |
| 410 | } else { |
| 411 | deliverByteFrame(result, info, rotation, decodeTimeMs); |
| 412 | } |
| 413 |
| 414 | } catch (IllegalStateException e) { |
| 415 | Logging.e(TAG, "deliverDecodedFrame failed", e); |
| 416 | } |
| 417 | } |
| 418 |
| 419 | private void deliverTextureFrame(final int index, final MediaCodec.BufferInfo info, |
| 420 | final int rotation, final Integer decodeTimeMs) { |
| 421 | // Load dimensions from shared memory under the dimension lock. |
| 422 | final int width; |
| 423 | final int height; |
| 424 | synchronized (dimensionLock) { |
| 425 | width = this.width; |
| 426 | height = this.height; |
| 427 | } |
| 428 |
| 429 | synchronized (renderedTextureMetadataLock) { |
| 430 | if (renderedTextureMetadata != null) { |
| 431 | codec.releaseOutputBuffer(index, false); |
| 432 | return; // We are still waiting for texture for the previous frame, drop this one. |
| 433 | } |
| 434 | surfaceTextureHelper.setTextureSize(width, height); |
| 435 | surfaceTextureHelper.setFrameRotation(rotation); |
| 436 | renderedTextureMetadata = new DecodedTextureMetadata(info.presentationTimeUs, decodeTimeMs); |
| 437 | codec.releaseOutputBuffer(index, /* render= */ true); |
| 438 | } |
| 439 | } |
| 440 |
| 441 | @Override |
| 442 | public void onFrame(VideoFrame frame) { |
| 443 | final VideoFrame newFrame; |
| 444 | final Integer decodeTimeMs; |
| 445 | final long timestampNs; |
| 446 | synchronized (renderedTextureMetadataLock) { |
| 447 | if (renderedTextureMetadata == null) { |
| 448 | throw new IllegalStateException( |
| 449 | "Rendered texture metadata was null in onTextureFrameAvailable."); |
| 450 | } |
| 451 | timestampNs = renderedTextureMetadata.presentationTimestampUs * 1000; |
| 452 | decodeTimeMs = renderedTextureMetadata.decodeTimeMs; |
| 453 | renderedTextureMetadata = null; |
| 454 | } |
| 455 | // Change timestamp of frame. |
| 456 | final VideoFrame frameWithModifiedTimeStamp = |
| 457 | new VideoFrame(frame.getBuffer(), frame.getRotation(), timestampNs); |
| 458 | callback.onDecodedFrame(frameWithModifiedTimeStamp, decodeTimeMs, null /* qp */); |
| 459 | } |
| 460 |
| 461 | private void deliverByteFrame( |
| 462 | int result, MediaCodec.BufferInfo info, int rotation, Integer decodeTimeMs) { |
| 463 | // Load dimensions from shared memory under the dimension lock. |
| 464 | int width; |
| 465 | int height; |
| 466 | int stride; |
| 467 | int sliceHeight; |
| 468 | synchronized (dimensionLock) { |
| 469 | width = this.width; |
| 470 | height = this.height; |
| 471 | stride = this.stride; |
| 472 | sliceHeight = this.sliceHeight; |
| 473 | } |
| 474 |
| 475 | // Output must be at least width * height bytes for Y channel, plus (width / 2) * (height / 2) |
| 476 | // bytes for each of the U and V channels. |
| 477 | if (info.size < width * height * 3 / 2) { |
| 478 | Logging.e(TAG, "Insufficient output buffer size: " + info.size); |
| 479 | return; |
| 480 | } |
| 481 |
| 482 | if (info.size < stride * height * 3 / 2 && sliceHeight == height && stride > width) { |
| 483 | // Some codecs (Exynos) report an incorrect stride. Correct it here. |
| 484 | // Expected size == stride * height * 3 / 2. A bit of algebra gives the correct stride as |
| 485 | // 2 * size / (3 * height). |
| 486 | stride = info.size * 2 / (height * 3); |
| 487 | } |
| 488 |
| 489 | ByteBuffer buffer = codec.getOutputBuffers()[result]; |
| 490 | buffer.position(info.offset); |
| 491 | buffer.limit(info.offset + info.size); |
| 492 | buffer = buffer.slice(); |
| 493 |
| 494 | final VideoFrame.Buffer frameBuffer; |
| 495 | if (colorFormat == CodecCapabilities.COLOR_FormatYUV420Planar) { |
| 496 | frameBuffer = copyI420Buffer(buffer, stride, sliceHeight, width, height); |
| 497 | } else { |
| 498 | // All other supported color formats are NV12. |
| 499 | frameBuffer = copyNV12ToI420Buffer(buffer, stride, sliceHeight, width, height); |
| 500 | } |
| 501 | codec.releaseOutputBuffer(result, /* render= */ false); |
| 502 |
| 503 | long presentationTimeNs = info.presentationTimeUs * 1000; |
| 504 | VideoFrame frame = new VideoFrame(frameBuffer, rotation, presentationTimeNs); |
| 505 |
| 506 | // Note that qp is parsed on the C++ side. |
| 507 | callback.onDecodedFrame(frame, decodeTimeMs, null /* qp */); |
| 508 | frame.release(); |
| 509 | } |
| 510 |
| 511 | private VideoFrame.Buffer copyNV12ToI420Buffer( |
| 512 | ByteBuffer buffer, int stride, int sliceHeight, int width, int height) { |
| 513 | // toI420 copies the buffer. |
| 514 | return new NV12Buffer(width, height, stride, sliceHeight, buffer, null /* releaseCallback */) |
| 515 | .toI420(); |
| 516 | } |
| 517 |
| 518 | private VideoFrame.Buffer copyI420Buffer( |
| 519 | ByteBuffer buffer, int stride, int sliceHeight, int width, int height) { |
| 520 | if (stride % 2 != 0) { |
| 521 | throw new AssertionError("Stride is not divisible by two: " + stride); |
| 522 | } |
| 523 |
| 524 | // Note that the case with odd |sliceHeight| is handled in a special way. |
| 525 | // The chroma height contained in the payload is rounded down instead of |
| 526 | // up, making it one row less than what we expect in WebRTC. Therefore, we |
| 527 | // have to duplicate the last chroma rows for this case. Also, the offset |
| 528 | // between the Y plane and the U plane is unintuitive for this case. See |
| 529 | // http://bugs.webrtc.org/6651 for more info. |
| 530 | final int chromaWidth = (width + 1) / 2; |
| 531 | final int chromaHeight = (sliceHeight % 2 == 0) ? (height + 1) / 2 : height / 2; |
| 532 |
| 533 | final int uvStride = stride / 2; |
| 534 |
| 535 | final int yPos = 0; |
| 536 | final int yEnd = yPos + stride * height; |
| 537 | final int uPos = yPos + stride * sliceHeight; |
| 538 | final int uEnd = uPos + uvStride * chromaHeight; |
| 539 | final int vPos = uPos + uvStride * sliceHeight / 2; |
| 540 | final int vEnd = vPos + uvStride * chromaHeight; |
| 541 |
| 542 | VideoFrame.I420Buffer frameBuffer = allocateI420Buffer(width, height); |
| 543 | try { //don't crash |
| 544 | buffer.limit(yEnd); |
| 545 | buffer.position(yPos); |
| 546 | copyPlane( |
| 547 | buffer.slice(), stride, frameBuffer.getDataY(), frameBuffer.getStrideY(), width, height); |
| 548 |
| 549 | buffer.limit(uEnd); |
| 550 | buffer.position(uPos); |
| 551 | copyPlane(buffer.slice(), uvStride, frameBuffer.getDataU(), frameBuffer.getStrideU(), |
| 552 | chromaWidth, chromaHeight); |
| 553 | if (sliceHeight % 2 == 1) { |
| 554 | buffer.position(uPos + uvStride * (chromaHeight - 1)); // Seek to beginning of last full row. |
| 555 |
| 556 | ByteBuffer dataU = frameBuffer.getDataU(); |
| 557 | dataU.position(frameBuffer.getStrideU() * chromaHeight); // Seek to beginning of last row. |
| 558 | dataU.put(buffer); // Copy the last row. |
| 559 | } |
| 560 |
| 561 | buffer.limit(vEnd); |
| 562 | buffer.position(vPos); |
| 563 | copyPlane(buffer.slice(), uvStride, frameBuffer.getDataV(), frameBuffer.getStrideV(), |
| 564 | chromaWidth, chromaHeight); |
| 565 | if (sliceHeight % 2 == 1) { |
| 566 | buffer.position(vPos + uvStride * (chromaHeight - 1)); // Seek to beginning of last full row. |
| 567 |
| 568 | ByteBuffer dataV = frameBuffer.getDataV(); |
| 569 | dataV.position(frameBuffer.getStrideV() * chromaHeight); // Seek to beginning of last row. |
| 570 | dataV.put(buffer); // Copy the last row. |
| 571 | } |
| 572 | } catch (Throwable e) { |
| 573 | FileLog.e(e); |
| 574 | } |
| 575 |
| 576 | return frameBuffer; |
| 577 | } |
| 578 |
| 579 | private void reformat(MediaFormat format) { |
| 580 | outputThreadChecker.checkIsOnValidThread(); |
| 581 | Logging.d(TAG, "Decoder format changed: " + format.toString()); |
| 582 | final int newWidth; |
| 583 | final int newHeight; |
| 584 | if (format.containsKey(MEDIA_FORMAT_KEY_CROP_LEFT) |
| 585 | && format.containsKey(MEDIA_FORMAT_KEY_CROP_RIGHT) |
| 586 | && format.containsKey(MEDIA_FORMAT_KEY_CROP_BOTTOM) |
| 587 | && format.containsKey(MEDIA_FORMAT_KEY_CROP_TOP)) { |
| 588 | newWidth = 1 + format.getInteger(MEDIA_FORMAT_KEY_CROP_RIGHT) |
| 589 | - format.getInteger(MEDIA_FORMAT_KEY_CROP_LEFT); |
| 590 | newHeight = 1 + format.getInteger(MEDIA_FORMAT_KEY_CROP_BOTTOM) |
| 591 | - format.getInteger(MEDIA_FORMAT_KEY_CROP_TOP); |
| 592 | } else { |
| 593 | newWidth = format.getInteger(MediaFormat.KEY_WIDTH); |
| 594 | newHeight = format.getInteger(MediaFormat.KEY_HEIGHT); |
| 595 | } |
| 596 | // Compare to existing width, height, and save values under the dimension lock. |
| 597 | synchronized (dimensionLock) { |
| 598 | if (newWidth != width || newHeight != height) { |
| 599 | if (hasDecodedFirstFrame) { |
| 600 | stopOnOutputThread(new RuntimeException("Unexpected size change. " |
| 601 | + "Configured " + width + "*" + height + ". " |
| 602 | + "New " + newWidth + "*" + newHeight)); |
| 603 | return; |
| 604 | } else if (newWidth <= 0 || newHeight <= 0) { |
| 605 | Logging.w(TAG, |
| 606 | "Unexpected format dimensions. Configured " + width + "*" + height + ". " |
| 607 | + "New " + newWidth + "*" + newHeight + ". Skip it"); |
| 608 | return; |
| 609 | } |
| 610 | width = newWidth; |
| 611 | height = newHeight; |
| 612 | } |
| 613 | } |
| 614 |
| 615 | // Note: texture mode ignores colorFormat. Hence, if the texture helper is non-null, skip |
| 616 | // color format updates. |
| 617 | if (surfaceTextureHelper == null && format.containsKey(MediaFormat.KEY_COLOR_FORMAT)) { |
| 618 | colorFormat = format.getInteger(MediaFormat.KEY_COLOR_FORMAT); |
| 619 | Logging.d(TAG, "Color: 0x" + Integer.toHexString(colorFormat)); |
| 620 | if (!isSupportedColorFormat(colorFormat)) { |
| 621 | stopOnOutputThread(new IllegalStateException("Unsupported color format: " + colorFormat)); |
| 622 | return; |
| 623 | } |
| 624 | } |
| 625 |
| 626 | // Save stride and sliceHeight under the dimension lock. |
| 627 | synchronized (dimensionLock) { |
| 628 | if (format.containsKey(MEDIA_FORMAT_KEY_STRIDE)) { |
| 629 | stride = format.getInteger(MEDIA_FORMAT_KEY_STRIDE); |
| 630 | } |
| 631 | if (format.containsKey(MEDIA_FORMAT_KEY_SLICE_HEIGHT)) { |
| 632 | sliceHeight = format.getInteger(MEDIA_FORMAT_KEY_SLICE_HEIGHT); |
| 633 | } |
| 634 | Logging.d(TAG, "Frame stride and slice height: " + stride + " x " + sliceHeight); |
| 635 | stride = Math.max(width, stride); |
| 636 | sliceHeight = Math.max(height, sliceHeight); |
| 637 | } |
| 638 | } |
| 639 |
| 640 | private void releaseCodecOnOutputThread() { |
| 641 | outputThreadChecker.checkIsOnValidThread(); |
| 642 | Logging.d(TAG, "Releasing MediaCodec on output thread"); |
| 643 | try { |
| 644 | codec.stop(); |
| 645 | } catch (Exception e) { |
| 646 | Logging.e(TAG, "Media decoder stop failed", e); |
| 647 | } |
| 648 | try { |
| 649 | codec.release(); |
| 650 | } catch (Exception e) { |
| 651 | Logging.e(TAG, "Media decoder release failed", e); |
| 652 | // Propagate exceptions caught during release back to the main thread. |
| 653 | shutdownException = e; |
| 654 | } |
| 655 | Logging.d(TAG, "Release on output thread done"); |
| 656 | } |
| 657 |
| 658 | private void stopOnOutputThread(Exception e) { |
| 659 | outputThreadChecker.checkIsOnValidThread(); |
| 660 | running = false; |
| 661 | shutdownException = e; |
| 662 | } |
| 663 |
| 664 | private boolean isSupportedColorFormat(int colorFormat) { |
| 665 | for (int supported : MediaCodecUtils.DECODER_COLOR_FORMATS) { |
| 666 | if (supported == colorFormat) { |
| 667 | return true; |
| 668 | } |
| 669 | } |
| 670 | return false; |
| 671 | } |
| 672 |
| 673 | // Visible for testing. |
| 674 | protected SurfaceTextureHelper createSurfaceTextureHelper() { |
| 675 | return SurfaceTextureHelper.create("decoder-texture-thread", sharedContext); |
| 676 | } |
| 677 |
| 678 | // Visible for testing. |
| 679 | // TODO(sakal): Remove once Robolectric commit fa991a0 has been rolled to WebRTC. |
| 680 | protected void releaseSurface() { |
| 681 | surface.release(); |
| 682 | } |
| 683 |
| 684 | // Visible for testing. |
| 685 | protected VideoFrame.I420Buffer allocateI420Buffer(int width, int height) { |
| 686 | return JavaI420Buffer.allocate(width, height); |
| 687 | } |
| 688 |
| 689 | // Visible for testing. |
| 690 | protected void copyPlane( |
| 691 | ByteBuffer src, int srcStride, ByteBuffer dst, int dstStride, int width, int height) { |
| 692 | YuvHelper.copyPlane(src, srcStride, dst, dstStride, width, height); |
| 693 | } |
| 694 | } |
| 695 |