blob: 169874d06df410d3bf3898670ba1024745b3f42d [file] [log] [blame]
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2014 The WebRTC project authors. All Rights Reserved.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +00009 */
10
11package org.webrtc;
12
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010013import android.graphics.SurfaceTexture;
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000014import android.media.MediaCodec;
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000015import android.media.MediaCodecInfo;
glaznev@webrtc.org99678452014-09-15 17:52:42 +000016import android.media.MediaCodecInfo.CodecCapabilities;
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000017import android.media.MediaCodecList;
18import android.media.MediaFormat;
19import android.os.Build;
Per488e75f2015-11-19 10:43:36 +010020import android.os.SystemClock;
glaznev@webrtc.org99678452014-09-15 17:52:42 +000021import android.view.Surface;
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000022import java.nio.ByteBuffer;
Magnus Jedvert6062f372017-11-16 16:53:12 +010023import java.util.ArrayDeque;
Alex Leung5b6891a2018-01-18 10:01:14 -080024import java.util.ArrayList;
Magnus Jedvert7e319372015-10-02 15:49:38 +020025import java.util.Arrays;
Alex Glazneveee86a62016-01-29 14:17:07 -080026import java.util.HashSet;
Magnus Jedvert91b348c2015-10-07 22:57:06 +020027import java.util.List;
Sami Kalliomakid3235f02016-08-02 15:44:04 +020028import java.util.Queue;
Alex Glazneveee86a62016-01-29 14:17:07 -080029import java.util.Set;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070030import java.util.concurrent.CountDownLatch;
Per488e75f2015-11-19 10:43:36 +010031import java.util.concurrent.TimeUnit;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010032import javax.annotation.Nullable;
Magnus Jedvertb9ac1212018-04-23 11:29:05 +020033import org.webrtc.EglBase;
34import org.webrtc.VideoFrame;
magjed8c425aa2015-10-22 16:52:39 -070035
Magnus Jedvert9060eb12017-12-12 12:52:54 +010036// Java-side of peerconnection.cc:MediaCodecVideoDecoder.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000037// This class is an implementation detail of the Java PeerConnection API.
Patrik Höglund68876f92015-11-12 17:36:48 +010038@SuppressWarnings("deprecation")
Alex Glaznev908e77b2015-04-22 09:25:34 -070039public class MediaCodecVideoDecoder {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000040 // This class is constructed, operated, and destroyed by its C++ incarnation,
41 // so the class and its methods have non-public visibility. The API this
42 // class exposes aims to mimic the webrtc::VideoDecoder API as closely as
43 // possibly to minimize the amount of translation work necessary.
44
45 private static final String TAG = "MediaCodecVideoDecoder";
magjedcedddbd2016-02-26 09:36:04 -080046 private static final long MAX_DECODE_TIME_MS = 200;
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000047
magjed0c29de52017-03-02 00:55:32 -080048 // TODO(magjed): Use MediaFormat constants when part of the public API.
49 private static final String FORMAT_KEY_STRIDE = "stride";
50 private static final String FORMAT_KEY_SLICE_HEIGHT = "slice-height";
51 private static final String FORMAT_KEY_CROP_LEFT = "crop-left";
52 private static final String FORMAT_KEY_CROP_RIGHT = "crop-right";
53 private static final String FORMAT_KEY_CROP_TOP = "crop-top";
54 private static final String FORMAT_KEY_CROP_BOTTOM = "crop-bottom";
55
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000056 // Tracks webrtc::VideoCodecType.
Magnus Jedvert655e1962017-12-08 11:05:22 +010057 public enum VideoCodecType {
Niels Möller520ca4e2018-06-04 11:14:38 +020058 VIDEO_CODEC_UNKNOWN,
Magnus Jedvert655e1962017-12-08 11:05:22 +010059 VIDEO_CODEC_VP8,
60 VIDEO_CODEC_VP9,
61 VIDEO_CODEC_H264;
62
63 @CalledByNative("VideoCodecType")
64 static VideoCodecType fromNativeIndex(int nativeIndex) {
65 return values()[nativeIndex];
66 }
67 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000068
Alex Glazneveee86a62016-01-29 14:17:07 -080069 // Timeout for input buffer dequeue.
70 private static final int DEQUEUE_INPUT_TIMEOUT = 500000;
71 // Timeout for codec releasing.
72 private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000;
73 // Max number of output buffers queued before starting to drop decoded frames.
74 private static final int MAX_QUEUED_OUTPUTBUFFERS = 3;
Alex Glaznevc6aec4b2015-10-19 16:39:19 -070075 // Active running decoder instance. Set in initDecode() (called from native code)
76 // and reset to null in release() call.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010077 @Nullable private static MediaCodecVideoDecoder runningInstance = null;
78 @Nullable private static MediaCodecVideoDecoderErrorCallback errorCallback = null;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070079 private static int codecErrors = 0;
Alex Glazneveee86a62016-01-29 14:17:07 -080080 // List of disabled codec types - can be set from application.
81 private static Set<String> hwDecoderDisabledTypes = new HashSet<String>();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070082
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010083 @Nullable private Thread mediaCodecThread;
84 @Nullable private MediaCodec mediaCodec;
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000085 private ByteBuffer[] inputBuffers;
86 private ByteBuffer[] outputBuffers;
87 private static final String VP8_MIME_TYPE = "video/x-vnd.on2.vp8";
Alex Glaznev69a7fd52015-11-10 10:25:40 -080088 private static final String VP9_MIME_TYPE = "video/x-vnd.on2.vp9";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000089 private static final String H264_MIME_TYPE = "video/avc";
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +000090 // List of supported HW VP8 decoders.
Alex Leung5b6891a2018-01-18 10:01:14 -080091 private static final String[] supportedVp8HwCodecPrefixes() {
92 ArrayList<String> supportedPrefixes = new ArrayList<String>();
93 supportedPrefixes.add("OMX.qcom.");
94 supportedPrefixes.add("OMX.Nvidia.");
95 supportedPrefixes.add("OMX.Exynos.");
96 supportedPrefixes.add("OMX.Intel.");
97 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekVP8").equals("Enabled")
98 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
99 supportedPrefixes.add("OMX.MTK.");
100 }
101 return supportedPrefixes.toArray(new String[supportedPrefixes.size()]);
102 }
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800103 // List of supported HW VP9 decoders.
sakalb6760f92016-09-29 04:12:44 -0700104 private static final String[] supportedVp9HwCodecPrefixes = {"OMX.qcom.", "OMX.Exynos."};
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000105 // List of supported HW H.264 decoders.
Alex Leung5b6891a2018-01-18 10:01:14 -0800106 private static final String[] supportedH264HwCodecPrefixes() {
107 ArrayList<String> supportedPrefixes = new ArrayList<String>();
108 supportedPrefixes.add("OMX.qcom.");
109 supportedPrefixes.add("OMX.Intel.");
110 supportedPrefixes.add("OMX.Exynos.");
111 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekH264").equals("Enabled")
Alex Leung28e71072018-02-05 13:42:48 -0800112 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Alex Leung5b6891a2018-01-18 10:01:14 -0800113 supportedPrefixes.add("OMX.MTK.");
114 }
115 return supportedPrefixes.toArray(new String[supportedPrefixes.size()]);
116 }
117
glaznev0c1d0602017-01-27 12:24:24 -0800118 // List of supported HW H.264 high profile decoders.
glaznevcca0f6c2017-06-14 10:20:54 -0700119 private static final String supportedQcomH264HighProfileHwCodecPrefix = "OMX.qcom.";
120 private static final String supportedExynosH264HighProfileHwCodecPrefix = "OMX.Exynos.";
Alex Leung5b6891a2018-01-18 10:01:14 -0800121 private static final String supportedMediaTekH264HighProfileHwCodecPrefix = "OMX.MTK.";
glaznev893a7ee2016-09-22 10:44:30 -0700122
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000123 // NV12 color format supported by QCOM codec, but not declared in MediaCodec -
124 // see /hardware/qcom/media/mm-core/inc/OMX_QCOMExtns.h
glaznev893a7ee2016-09-22 10:44:30 -0700125 private static final int COLOR_QCOM_FORMATYVU420PackedSemiPlanar32m4ka = 0x7FA30C01;
126 private static final int COLOR_QCOM_FORMATYVU420PackedSemiPlanar16m4ka = 0x7FA30C02;
127 private static final int COLOR_QCOM_FORMATYVU420PackedSemiPlanar64x32Tile2m8ka = 0x7FA30C03;
128 private static final int COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m = 0x7FA30C04;
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000129 // Allowable color formats supported by codec - in order of preference.
Magnus Jedvert7e319372015-10-02 15:49:38 +0200130 private static final List<Integer> supportedColorList = Arrays.asList(
sakalb6760f92016-09-29 04:12:44 -0700131 CodecCapabilities.COLOR_FormatYUV420Planar, CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
132 CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
133 COLOR_QCOM_FORMATYVU420PackedSemiPlanar32m4ka, COLOR_QCOM_FORMATYVU420PackedSemiPlanar16m4ka,
134 COLOR_QCOM_FORMATYVU420PackedSemiPlanar64x32Tile2m8ka,
135 COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m);
glaznev893a7ee2016-09-22 10:44:30 -0700136
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000137 private int colorFormat;
138 private int width;
139 private int height;
140 private int stride;
141 private int sliceHeight;
Per488e75f2015-11-19 10:43:36 +0100142 private boolean hasDecodedFirstFrame;
Magnus Jedvert6062f372017-11-16 16:53:12 +0100143 private final Queue<TimeStamps> decodeStartTimeMs = new ArrayDeque<TimeStamps>();
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000144 private boolean useSurface;
Perc01c2542015-11-13 16:58:26 +0100145
Per488e75f2015-11-19 10:43:36 +0100146 // The below variables are only used when decoding to a Surface.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100147 @Nullable private TextureListener textureListener;
Per488e75f2015-11-19 10:43:36 +0100148 private int droppedFrames;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100149 @Nullable private Surface surface = null;
sakalb6760f92016-09-29 04:12:44 -0700150 private final Queue<DecodedOutputBuffer> dequeuedSurfaceOutputBuffers =
Magnus Jedvert6062f372017-11-16 16:53:12 +0100151 new ArrayDeque<DecodedOutputBuffer>();
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000152
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700153 // MediaCodec error handler - invoked when critical error happens which may prevent
154 // further use of media codec API. Now it means that one of media codec instances
155 // is hanging and can no longer be used in the next call.
156 public static interface MediaCodecVideoDecoderErrorCallback {
157 void onMediaCodecVideoDecoderCriticalError(int codecErrors);
158 }
159
160 public static void setErrorCallback(MediaCodecVideoDecoderErrorCallback errorCallback) {
161 Logging.d(TAG, "Set error callback");
162 MediaCodecVideoDecoder.errorCallback = errorCallback;
163 }
164
Alex Glazneveee86a62016-01-29 14:17:07 -0800165 // Functions to disable HW decoding - can be called from applications for platforms
166 // which have known HW decoding problems.
167 public static void disableVp8HwCodec() {
168 Logging.w(TAG, "VP8 decoding is disabled by application.");
169 hwDecoderDisabledTypes.add(VP8_MIME_TYPE);
170 }
171
172 public static void disableVp9HwCodec() {
173 Logging.w(TAG, "VP9 decoding is disabled by application.");
174 hwDecoderDisabledTypes.add(VP9_MIME_TYPE);
175 }
176
177 public static void disableH264HwCodec() {
178 Logging.w(TAG, "H.264 decoding is disabled by application.");
179 hwDecoderDisabledTypes.add(H264_MIME_TYPE);
180 }
181
182 // Functions to query if HW decoding is supported.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100183 @CalledByNativeUnchecked
Alex Glazneveee86a62016-01-29 14:17:07 -0800184 public static boolean isVp8HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700185 return !hwDecoderDisabledTypes.contains(VP8_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800186 && (findDecoder(VP8_MIME_TYPE, supportedVp8HwCodecPrefixes()) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800187 }
188
Magnus Jedvert655e1962017-12-08 11:05:22 +0100189 @CalledByNativeUnchecked
Alex Glazneveee86a62016-01-29 14:17:07 -0800190 public static boolean isVp9HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700191 return !hwDecoderDisabledTypes.contains(VP9_MIME_TYPE)
192 && (findDecoder(VP9_MIME_TYPE, supportedVp9HwCodecPrefixes) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800193 }
194
Magnus Jedvert655e1962017-12-08 11:05:22 +0100195 @CalledByNativeUnchecked
Alex Glazneveee86a62016-01-29 14:17:07 -0800196 public static boolean isH264HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700197 return !hwDecoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800198 && (findDecoder(H264_MIME_TYPE, supportedH264HwCodecPrefixes()) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800199 }
200
Magnus Jedvert655e1962017-12-08 11:05:22 +0100201 @CalledByNative
glaznev0c1d0602017-01-27 12:24:24 -0800202 public static boolean isH264HighProfileHwSupported() {
glaznevcca0f6c2017-06-14 10:20:54 -0700203 if (hwDecoderDisabledTypes.contains(H264_MIME_TYPE)) {
204 return false;
205 }
206 // Support H.264 HP decoding on QCOM chips for Android L and above.
207 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
208 && findDecoder(H264_MIME_TYPE, new String[] {supportedQcomH264HighProfileHwCodecPrefix})
209 != null) {
210 return true;
211 }
212 // Support H.264 HP decoding on Exynos chips for Android M and above.
213 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
214 && findDecoder(H264_MIME_TYPE, new String[] {supportedExynosH264HighProfileHwCodecPrefix})
215 != null) {
216 return true;
217 }
Alex Leung28e71072018-02-05 13:42:48 -0800218 // Support H.264 HP decoding on MediaTek chips for Android O_MR1 and above
Alex Leung5b6891a2018-01-18 10:01:14 -0800219 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekH264").equals("Enabled")
Alex Leung28e71072018-02-05 13:42:48 -0800220 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1
Alex Leung5b6891a2018-01-18 10:01:14 -0800221 && findDecoder(H264_MIME_TYPE, new String[] {supportedMediaTekH264HighProfileHwCodecPrefix})
222 != null) {
223 return true;
224 }
glaznevcca0f6c2017-06-14 10:20:54 -0700225 return false;
glaznev0c1d0602017-01-27 12:24:24 -0800226 }
227
Alex Glazneveee86a62016-01-29 14:17:07 -0800228 public static void printStackTrace() {
229 if (runningInstance != null && runningInstance.mediaCodecThread != null) {
230 StackTraceElement[] mediaCodecStackTraces = runningInstance.mediaCodecThread.getStackTrace();
231 if (mediaCodecStackTraces.length > 0) {
232 Logging.d(TAG, "MediaCodecVideoDecoder stacks trace:");
233 for (StackTraceElement stackTrace : mediaCodecStackTraces) {
234 Logging.d(TAG, stackTrace.toString());
235 }
236 }
237 }
238 }
239
240 // Helper struct for findDecoder() below.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000241 private static class DecoderProperties {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000242 public DecoderProperties(String codecName, int colorFormat) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000243 this.codecName = codecName;
244 this.colorFormat = colorFormat;
245 }
246 public final String codecName; // OpenMax component name for VP8 codec.
sakalb6760f92016-09-29 04:12:44 -0700247 public final int colorFormat; // Color format supported by codec.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000248 }
249
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100250 private static @Nullable DecoderProperties findDecoder(
251 String mime, String[] supportedCodecPrefixes) {
glaznev@webrtc.org25cc7452014-10-02 16:58:05 +0000252 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000253 return null; // MediaCodec.setParameters is missing.
glaznev@webrtc.org25cc7452014-10-02 16:58:05 +0000254 }
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800255 Logging.d(TAG, "Trying to find HW decoder for mime " + mime);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000256 for (int i = 0; i < MediaCodecList.getCodecCount(); ++i) {
Alex Glaznev0060c562016-08-08 12:27:24 -0700257 MediaCodecInfo info = null;
258 try {
259 info = MediaCodecList.getCodecInfoAt(i);
260 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700261 Logging.e(TAG, "Cannot retrieve decoder codec info", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700262 }
263 if (info == null || info.isEncoder()) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000264 continue;
265 }
266 String name = null;
267 for (String mimeType : info.getSupportedTypes()) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000268 if (mimeType.equals(mime)) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000269 name = info.getName();
270 break;
271 }
272 }
273 if (name == null) {
sakalb6760f92016-09-29 04:12:44 -0700274 continue; // No HW support in this codec; try the next one.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000275 }
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800276 Logging.d(TAG, "Found candidate decoder " + name);
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000277
glaznev@webrtc.org25cc7452014-10-02 16:58:05 +0000278 // Check if this is supported decoder.
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000279 boolean supportedCodec = false;
glaznev@webrtc.org25cc7452014-10-02 16:58:05 +0000280 for (String codecPrefix : supportedCodecPrefixes) {
281 if (name.startsWith(codecPrefix)) {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000282 supportedCodec = true;
283 break;
284 }
285 }
286 if (!supportedCodec) {
287 continue;
288 }
289
290 // Check if codec supports either yuv420 or nv12.
Alex Glaznev0060c562016-08-08 12:27:24 -0700291 CodecCapabilities capabilities;
292 try {
293 capabilities = info.getCapabilitiesForType(mime);
294 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700295 Logging.e(TAG, "Cannot retrieve decoder capabilities", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700296 continue;
297 }
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000298 for (int colorFormat : capabilities.colorFormats) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700299 Logging.v(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000300 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000301 for (int supportedColorFormat : supportedColorList) {
302 for (int codecColorFormat : capabilities.colorFormats) {
303 if (codecColorFormat == supportedColorFormat) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000304 // Found supported HW decoder.
sakalb6760f92016-09-29 04:12:44 -0700305 Logging.d(TAG, "Found target decoder " + name + ". Color: 0x"
306 + Integer.toHexString(codecColorFormat));
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000307 return new DecoderProperties(name, codecColorFormat);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000308 }
309 }
310 }
311 }
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800312 Logging.d(TAG, "No HW decoder found for mime " + mime);
sakalb6760f92016-09-29 04:12:44 -0700313 return null; // No HW decoder.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000314 }
315
Magnus Jedvert655e1962017-12-08 11:05:22 +0100316 @CalledByNative
317 MediaCodecVideoDecoder() {}
318
Magnus Jedvert7e319372015-10-02 15:49:38 +0200319 private void checkOnMediaCodecThread() throws IllegalStateException {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000320 if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
sakalb6760f92016-09-29 04:12:44 -0700321 throw new IllegalStateException("MediaCodecVideoDecoder previously operated on "
322 + mediaCodecThread + " but is now called on " + Thread.currentThread());
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000323 }
324 }
325
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200326 // Pass null in |eglContext| to configure the codec for ByteBuffer output.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100327 @CalledByNativeUnchecked
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200328 private boolean initDecode(
329 VideoCodecType type, int width, int height, @Nullable EglBase.Context eglContext) {
Alejandro Luebs69ddaef2015-10-09 15:46:09 -0700330 if (mediaCodecThread != null) {
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800331 throw new RuntimeException("initDecode: Forgot to release()?");
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000332 }
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800333
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000334 String mime = null;
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200335 useSurface = (eglContext != null);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000336 String[] supportedCodecPrefixes = null;
337 if (type == VideoCodecType.VIDEO_CODEC_VP8) {
338 mime = VP8_MIME_TYPE;
Alex Leung5b6891a2018-01-18 10:01:14 -0800339 supportedCodecPrefixes = supportedVp8HwCodecPrefixes();
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800340 } else if (type == VideoCodecType.VIDEO_CODEC_VP9) {
341 mime = VP9_MIME_TYPE;
342 supportedCodecPrefixes = supportedVp9HwCodecPrefixes;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000343 } else if (type == VideoCodecType.VIDEO_CODEC_H264) {
344 mime = H264_MIME_TYPE;
Alex Leung5b6891a2018-01-18 10:01:14 -0800345 supportedCodecPrefixes = supportedH264HwCodecPrefixes();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000346 } else {
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800347 throw new RuntimeException("initDecode: Non-supported codec " + type);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000348 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000349 DecoderProperties properties = findDecoder(mime, supportedCodecPrefixes);
350 if (properties == null) {
351 throw new RuntimeException("Cannot find HW decoder for " + type);
352 }
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800353
sakalb6760f92016-09-29 04:12:44 -0700354 Logging.d(TAG, "Java initDecode: " + type + " : " + width + " x " + height + ". Color: 0x"
355 + Integer.toHexString(properties.colorFormat) + ". Use Surface: " + useSurface);
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800356
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700357 runningInstance = this; // Decoder is now running and can be queried for stack traces.
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000358 mediaCodecThread = Thread.currentThread();
359 try {
360 this.width = width;
361 this.height = height;
362 stride = width;
363 sliceHeight = height;
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000364
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200365 if (useSurface) {
366 @Nullable
367 final SurfaceTextureHelper surfaceTextureHelper =
368 SurfaceTextureHelper.create("Decoder SurfaceTextureHelper", eglContext);
369 if (surfaceTextureHelper != null) {
370 textureListener = new TextureListener(surfaceTextureHelper);
371 surface = new Surface(surfaceTextureHelper.getSurfaceTexture());
372 }
Magnus Jedvert80cf97c2015-06-11 10:08:59 +0200373 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000374
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000375 MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000376 if (!useSurface) {
377 format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
378 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700379 Logging.d(TAG, " Format: " + format);
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800380 mediaCodec = MediaCodecVideoEncoder.createByCodecName(properties.codecName);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000381 if (mediaCodec == null) {
Alex Glaznev325d4142015-10-12 14:56:02 -0700382 Logging.e(TAG, "Can not create media decoder");
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000383 return false;
384 }
Magnus Jedvert7e319372015-10-02 15:49:38 +0200385 mediaCodec.configure(format, surface, null, 0);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000386 mediaCodec.start();
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800387
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000388 colorFormat = properties.colorFormat;
389 outputBuffers = mediaCodec.getOutputBuffers();
390 inputBuffers = mediaCodec.getInputBuffers();
Per488e75f2015-11-19 10:43:36 +0100391 decodeStartTimeMs.clear();
392 hasDecodedFirstFrame = false;
393 dequeuedSurfaceOutputBuffers.clear();
394 droppedFrames = 0;
sakalb6760f92016-09-29 04:12:44 -0700395 Logging.d(TAG,
396 "Input buffers: " + inputBuffers.length + ". Output buffers: " + outputBuffers.length);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000397 return true;
398 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700399 Logging.e(TAG, "initDecode failed", e);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000400 return false;
401 }
402 }
403
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800404 // Resets the decoder so it can start decoding frames with new resolution.
405 // Flushes MediaCodec and clears decoder output buffers.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100406 @CalledByNativeUnchecked
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800407 private void reset(int width, int height) {
408 if (mediaCodecThread == null || mediaCodec == null) {
409 throw new RuntimeException("Incorrect reset call for non-initialized decoder.");
410 }
411 Logging.d(TAG, "Java reset: " + width + " x " + height);
412
413 mediaCodec.flush();
414
415 this.width = width;
416 this.height = height;
417 decodeStartTimeMs.clear();
418 dequeuedSurfaceOutputBuffers.clear();
419 hasDecodedFirstFrame = false;
420 droppedFrames = 0;
421 }
422
Magnus Jedvert655e1962017-12-08 11:05:22 +0100423 @CalledByNativeUnchecked
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000424 private void release() {
Per488e75f2015-11-19 10:43:36 +0100425 Logging.d(TAG, "Java releaseDecoder. Total number of dropped frames: " + droppedFrames);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000426 checkOnMediaCodecThread();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700427
428 // Run Mediacodec stop() and release() on separate thread since sometime
429 // Mediacodec.stop() may hang.
430 final CountDownLatch releaseDone = new CountDownLatch(1);
431
432 Runnable runMediaCodecRelease = new Runnable() {
433 @Override
434 public void run() {
435 try {
436 Logging.d(TAG, "Java releaseDecoder on release thread");
437 mediaCodec.stop();
438 mediaCodec.release();
439 Logging.d(TAG, "Java releaseDecoder on release thread done");
440 } catch (Exception e) {
441 Logging.e(TAG, "Media decoder release failed", e);
442 }
443 releaseDone.countDown();
444 }
445 };
446 new Thread(runMediaCodecRelease).start();
447
448 if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) {
449 Logging.e(TAG, "Media decoder release timeout");
450 codecErrors++;
451 if (errorCallback != null) {
452 Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors);
453 errorCallback.onMediaCodecVideoDecoderCriticalError(codecErrors);
454 }
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000455 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700456
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000457 mediaCodec = null;
458 mediaCodecThread = null;
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700459 runningInstance = null;
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000460 if (useSurface) {
461 surface.release();
Magnus Jedvert7e319372015-10-02 15:49:38 +0200462 surface = null;
Per488e75f2015-11-19 10:43:36 +0100463 textureListener.release();
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000464 }
Alex Glaznev325d4142015-10-12 14:56:02 -0700465 Logging.d(TAG, "Java releaseDecoder done");
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000466 }
467
468 // Dequeue an input buffer and return its index, -1 if no input buffer is
469 // available, or -2 if the codec is no longer operative.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100470 @CalledByNativeUnchecked
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000471 private int dequeueInputBuffer() {
472 checkOnMediaCodecThread();
473 try {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000474 return mediaCodec.dequeueInputBuffer(DEQUEUE_INPUT_TIMEOUT);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000475 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700476 Logging.e(TAG, "dequeueIntputBuffer failed", e);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000477 return -2;
478 }
479 }
480
Magnus Jedvert655e1962017-12-08 11:05:22 +0100481 @CalledByNativeUnchecked
Per488e75f2015-11-19 10:43:36 +0100482 private boolean queueInputBuffer(int inputBufferIndex, int size, long presentationTimeStamUs,
483 long timeStampMs, long ntpTimeStamp) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000484 checkOnMediaCodecThread();
485 try {
486 inputBuffers[inputBufferIndex].position(0);
487 inputBuffers[inputBufferIndex].limit(size);
sakalb6760f92016-09-29 04:12:44 -0700488 decodeStartTimeMs.add(
489 new TimeStamps(SystemClock.elapsedRealtime(), timeStampMs, ntpTimeStamp));
Per488e75f2015-11-19 10:43:36 +0100490 mediaCodec.queueInputBuffer(inputBufferIndex, 0, size, presentationTimeStamUs, 0);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000491 return true;
sakalb6760f92016-09-29 04:12:44 -0700492 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700493 Logging.e(TAG, "decode failed", e);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000494 return false;
495 }
496 }
497
Per488e75f2015-11-19 10:43:36 +0100498 private static class TimeStamps {
499 public TimeStamps(long decodeStartTimeMs, long timeStampMs, long ntpTimeStampMs) {
500 this.decodeStartTimeMs = decodeStartTimeMs;
501 this.timeStampMs = timeStampMs;
502 this.ntpTimeStampMs = ntpTimeStampMs;
503 }
Alex Glazneveee86a62016-01-29 14:17:07 -0800504 // Time when this frame was queued for decoding.
505 private final long decodeStartTimeMs;
506 // Only used for bookkeeping in Java. Stores C++ inputImage._timeStamp value for input frame.
507 private final long timeStampMs;
508 // Only used for bookkeeping in Java. Stores C++ inputImage.ntp_time_ms_ value for input frame.
509 private final long ntpTimeStampMs;
Per488e75f2015-11-19 10:43:36 +0100510 }
511
512 // Helper struct for dequeueOutputBuffer() below.
513 private static class DecodedOutputBuffer {
glaznev94291482016-02-01 13:17:18 -0800514 public DecodedOutputBuffer(int index, int offset, int size, long presentationTimeStampMs,
515 long timeStampMs, long ntpTimeStampMs, long decodeTime, long endDecodeTime) {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000516 this.index = index;
517 this.offset = offset;
518 this.size = size;
glaznev94291482016-02-01 13:17:18 -0800519 this.presentationTimeStampMs = presentationTimeStampMs;
Per488e75f2015-11-19 10:43:36 +0100520 this.timeStampMs = timeStampMs;
521 this.ntpTimeStampMs = ntpTimeStampMs;
522 this.decodeTimeMs = decodeTime;
523 this.endDecodeTimeMs = endDecodeTime;
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000524 }
525
526 private final int index;
527 private final int offset;
528 private final int size;
glaznev94291482016-02-01 13:17:18 -0800529 // Presentation timestamp returned in dequeueOutputBuffer call.
530 private final long presentationTimeStampMs;
Alex Glazneveee86a62016-01-29 14:17:07 -0800531 // C++ inputImage._timeStamp value for output frame.
Per488e75f2015-11-19 10:43:36 +0100532 private final long timeStampMs;
Alex Glazneveee86a62016-01-29 14:17:07 -0800533 // C++ inputImage.ntp_time_ms_ value for output frame.
Per488e75f2015-11-19 10:43:36 +0100534 private final long ntpTimeStampMs;
535 // Number of ms it took to decode this frame.
536 private final long decodeTimeMs;
Alex Glazneveee86a62016-01-29 14:17:07 -0800537 // System time when this frame decoding finished.
Per488e75f2015-11-19 10:43:36 +0100538 private final long endDecodeTimeMs;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100539
540 @CalledByNative("DecodedOutputBuffer")
541 int getIndex() {
542 return index;
543 }
544
545 @CalledByNative("DecodedOutputBuffer")
546 int getOffset() {
547 return offset;
548 }
549
550 @CalledByNative("DecodedOutputBuffer")
551 int getSize() {
552 return size;
553 }
554
555 @CalledByNative("DecodedOutputBuffer")
556 long getPresentationTimestampMs() {
557 return presentationTimeStampMs;
558 }
559
560 @CalledByNative("DecodedOutputBuffer")
561 long getTimestampMs() {
562 return timeStampMs;
563 }
564
565 @CalledByNative("DecodedOutputBuffer")
566 long getNtpTimestampMs() {
567 return ntpTimeStampMs;
568 }
569
570 @CalledByNative("DecodedOutputBuffer")
571 long getDecodeTimeMs() {
572 return decodeTimeMs;
573 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000574 }
575
Per488e75f2015-11-19 10:43:36 +0100576 // Helper struct for dequeueTextureBuffer() below.
magjed44bf6f52015-10-03 02:08:00 -0700577 private static class DecodedTextureBuffer {
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200578 private final VideoFrame.Buffer videoFrameBuffer;
glaznev94291482016-02-01 13:17:18 -0800579 // Presentation timestamp returned in dequeueOutputBuffer call.
580 private final long presentationTimeStampMs;
Alex Glazneveee86a62016-01-29 14:17:07 -0800581 // C++ inputImage._timeStamp value for output frame.
Per488e75f2015-11-19 10:43:36 +0100582 private final long timeStampMs;
Alex Glazneveee86a62016-01-29 14:17:07 -0800583 // C++ inputImage.ntp_time_ms_ value for output frame.
Per488e75f2015-11-19 10:43:36 +0100584 private final long ntpTimeStampMs;
Alex Glazneveee86a62016-01-29 14:17:07 -0800585 // Number of ms it took to decode this frame.
Per488e75f2015-11-19 10:43:36 +0100586 private final long decodeTimeMs;
587 // Interval from when the frame finished decoding until this buffer has been created.
588 // Since there is only one texture, this interval depend on the time from when
589 // a frame is decoded and provided to C++ and until that frame is returned to the MediaCodec
590 // so that the texture can be updated with the next decoded frame.
591 private final long frameDelayMs;
magjed44bf6f52015-10-03 02:08:00 -0700592
Per488e75f2015-11-19 10:43:36 +0100593 // A DecodedTextureBuffer with zero |textureID| has special meaning and represents a frame
594 // that was dropped.
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200595 public DecodedTextureBuffer(VideoFrame.Buffer videoFrameBuffer, long presentationTimeStampMs,
596 long timeStampMs, long ntpTimeStampMs, long decodeTimeMs, long frameDelay) {
597 this.videoFrameBuffer = videoFrameBuffer;
glaznev94291482016-02-01 13:17:18 -0800598 this.presentationTimeStampMs = presentationTimeStampMs;
Per488e75f2015-11-19 10:43:36 +0100599 this.timeStampMs = timeStampMs;
600 this.ntpTimeStampMs = ntpTimeStampMs;
601 this.decodeTimeMs = decodeTimeMs;
602 this.frameDelayMs = frameDelay;
magjed44bf6f52015-10-03 02:08:00 -0700603 }
Magnus Jedvert655e1962017-12-08 11:05:22 +0100604
605 @CalledByNative("DecodedTextureBuffer")
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200606 VideoFrame.Buffer getVideoFrameBuffer() {
607 return videoFrameBuffer;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100608 }
609
610 @CalledByNative("DecodedTextureBuffer")
611 long getPresentationTimestampMs() {
612 return presentationTimeStampMs;
613 }
614
615 @CalledByNative("DecodedTextureBuffer")
616 long getTimeStampMs() {
617 return timeStampMs;
618 }
619
620 @CalledByNative("DecodedTextureBuffer")
621 long getNtpTimestampMs() {
622 return ntpTimeStampMs;
623 }
624
625 @CalledByNative("DecodedTextureBuffer")
626 long getDecodeTimeMs() {
627 return decodeTimeMs;
628 }
629
630 @CalledByNative("DecodedTextureBuffer")
631 long getFrameDelayMs() {
632 return frameDelayMs;
633 }
magjed44bf6f52015-10-03 02:08:00 -0700634 }
635
Per488e75f2015-11-19 10:43:36 +0100636 // Poll based texture listener.
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200637 private class TextureListener implements SurfaceTextureHelper.OnTextureFrameAvailableListener {
Per488e75f2015-11-19 10:43:36 +0100638 private final SurfaceTextureHelper surfaceTextureHelper;
639 // |newFrameLock| is used to synchronize arrival of new frames with wait()/notifyAll().
640 private final Object newFrameLock = new Object();
641 // |bufferToRender| is non-null when waiting for transition between addBufferToRender() to
642 // onTextureFrameAvailable().
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100643 @Nullable private DecodedOutputBuffer bufferToRender;
644 @Nullable private DecodedTextureBuffer renderedBuffer;
Per488e75f2015-11-19 10:43:36 +0100645
646 public TextureListener(SurfaceTextureHelper surfaceTextureHelper) {
647 this.surfaceTextureHelper = surfaceTextureHelper;
magjed81e8e372016-03-03 02:11:44 -0800648 surfaceTextureHelper.startListening(this);
Per488e75f2015-11-19 10:43:36 +0100649 }
650
651 public void addBufferToRender(DecodedOutputBuffer buffer) {
652 if (bufferToRender != null) {
sakalb6760f92016-09-29 04:12:44 -0700653 Logging.e(TAG, "Unexpected addBufferToRender() called while waiting for a texture.");
Per488e75f2015-11-19 10:43:36 +0100654 throw new IllegalStateException("Waiting for a texture.");
655 }
656 bufferToRender = buffer;
657 }
658
659 public boolean isWaitingForTexture() {
660 synchronized (newFrameLock) {
661 return bufferToRender != null;
662 }
663 }
664
665 // Callback from |surfaceTextureHelper|. May be called on an arbitrary thread.
666 @Override
667 public void onTextureFrameAvailable(
668 int oesTextureId, float[] transformMatrix, long timestampNs) {
669 synchronized (newFrameLock) {
670 if (renderedBuffer != null) {
sakalb6760f92016-09-29 04:12:44 -0700671 Logging.e(
672 TAG, "Unexpected onTextureFrameAvailable() called while already holding a texture.");
Per488e75f2015-11-19 10:43:36 +0100673 throw new IllegalStateException("Already holding a texture.");
674 }
675 // |timestampNs| is always zero on some Android versions.
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200676 final VideoFrame.Buffer buffer = surfaceTextureHelper.createTextureBuffer(
677 width, height, RendererCommon.convertMatrixToAndroidGraphicsMatrix(transformMatrix));
678 renderedBuffer = new DecodedTextureBuffer(buffer, bufferToRender.presentationTimeStampMs,
679 bufferToRender.timeStampMs, bufferToRender.ntpTimeStampMs, bufferToRender.decodeTimeMs,
Per488e75f2015-11-19 10:43:36 +0100680 SystemClock.elapsedRealtime() - bufferToRender.endDecodeTimeMs);
681 bufferToRender = null;
682 newFrameLock.notifyAll();
683 }
684 }
685
686 // Dequeues and returns a DecodedTextureBuffer if available, or null otherwise.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100687 @Nullable
Sami Kalliomäki9828beb2017-10-26 16:21:22 +0200688 @SuppressWarnings("WaitNotInLoop")
Per488e75f2015-11-19 10:43:36 +0100689 public DecodedTextureBuffer dequeueTextureBuffer(int timeoutMs) {
690 synchronized (newFrameLock) {
691 if (renderedBuffer == null && timeoutMs > 0 && isWaitingForTexture()) {
692 try {
693 newFrameLock.wait(timeoutMs);
sakalb6760f92016-09-29 04:12:44 -0700694 } catch (InterruptedException e) {
Per488e75f2015-11-19 10:43:36 +0100695 // Restore the interrupted status by reinterrupting the thread.
696 Thread.currentThread().interrupt();
697 }
698 }
699 DecodedTextureBuffer returnedBuffer = renderedBuffer;
700 renderedBuffer = null;
701 return returnedBuffer;
702 }
703 }
704
705 public void release() {
nissea44e72c2016-05-27 00:27:59 -0700706 // SurfaceTextureHelper.stopListening() will block until any onTextureFrameAvailable() in
707 // progress is done. Therefore, the call must be outside any synchronized
Per488e75f2015-11-19 10:43:36 +0100708 // statement that is also used in the onTextureFrameAvailable() above to avoid deadlocks.
nissea44e72c2016-05-27 00:27:59 -0700709 surfaceTextureHelper.stopListening();
Per488e75f2015-11-19 10:43:36 +0100710 synchronized (newFrameLock) {
711 if (renderedBuffer != null) {
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200712 renderedBuffer.getVideoFrameBuffer().release();
Per488e75f2015-11-19 10:43:36 +0100713 renderedBuffer = null;
714 }
715 }
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200716 surfaceTextureHelper.dispose();
Per488e75f2015-11-19 10:43:36 +0100717 }
718 }
719
720 // Returns null if no decoded buffer is available, and otherwise a DecodedByteBuffer.
Magnus Jedvert7e319372015-10-02 15:49:38 +0200721 // Throws IllegalStateException if call is made on the wrong thread, if color format changes to an
722 // unsupported format, or if |mediaCodec| is not in the Executing state. Throws CodecException
723 // upon codec error.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100724 @CalledByNativeUnchecked
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100725 private @Nullable DecodedOutputBuffer dequeueOutputBuffer(int dequeueTimeoutMs) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000726 checkOnMediaCodecThread();
Per488e75f2015-11-19 10:43:36 +0100727 if (decodeStartTimeMs.isEmpty()) {
728 return null;
729 }
Magnus Jedvert7e319372015-10-02 15:49:38 +0200730 // Drain the decoder until receiving a decoded buffer or hitting
731 // MediaCodec.INFO_TRY_AGAIN_LATER.
732 final MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
733 while (true) {
sakalb6760f92016-09-29 04:12:44 -0700734 final int result =
735 mediaCodec.dequeueOutputBuffer(info, TimeUnit.MILLISECONDS.toMicros(dequeueTimeoutMs));
Magnus Jedvert7e319372015-10-02 15:49:38 +0200736 switch (result) {
Magnus Jedvert7e319372015-10-02 15:49:38 +0200737 case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000738 outputBuffers = mediaCodec.getOutputBuffers();
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700739 Logging.d(TAG, "Decoder output buffers changed: " + outputBuffers.length);
Per488e75f2015-11-19 10:43:36 +0100740 if (hasDecodedFirstFrame) {
741 throw new RuntimeException("Unexpected output buffer change event.");
742 }
Magnus Jedvert7e319372015-10-02 15:49:38 +0200743 break;
744 case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000745 MediaFormat format = mediaCodec.getOutputFormat();
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700746 Logging.d(TAG, "Decoder format changed: " + format.toString());
magjed0c29de52017-03-02 00:55:32 -0800747 final int newWidth;
748 final int newHeight;
749 if (format.containsKey(FORMAT_KEY_CROP_LEFT) && format.containsKey(FORMAT_KEY_CROP_RIGHT)
750 && format.containsKey(FORMAT_KEY_CROP_BOTTOM)
751 && format.containsKey(FORMAT_KEY_CROP_TOP)) {
752 newWidth = 1 + format.getInteger(FORMAT_KEY_CROP_RIGHT)
753 - format.getInteger(FORMAT_KEY_CROP_LEFT);
754 newHeight = 1 + format.getInteger(FORMAT_KEY_CROP_BOTTOM)
755 - format.getInteger(FORMAT_KEY_CROP_TOP);
756 } else {
757 newWidth = format.getInteger(MediaFormat.KEY_WIDTH);
758 newHeight = format.getInteger(MediaFormat.KEY_HEIGHT);
Per488e75f2015-11-19 10:43:36 +0100759 }
magjed0c29de52017-03-02 00:55:32 -0800760 if (hasDecodedFirstFrame && (newWidth != width || newHeight != height)) {
761 throw new RuntimeException("Unexpected size change. Configured " + width + "*" + height
762 + ". New " + newWidth + "*" + newHeight);
763 }
764 width = newWidth;
765 height = newHeight;
Per488e75f2015-11-19 10:43:36 +0100766
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000767 if (!useSurface && format.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000768 colorFormat = format.getInteger(MediaFormat.KEY_COLOR_FORMAT);
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700769 Logging.d(TAG, "Color: 0x" + Integer.toHexString(colorFormat));
Magnus Jedvert7e319372015-10-02 15:49:38 +0200770 if (!supportedColorList.contains(colorFormat)) {
771 throw new IllegalStateException("Non supported color format: " + colorFormat);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000772 }
773 }
magjed0c29de52017-03-02 00:55:32 -0800774 if (format.containsKey(FORMAT_KEY_STRIDE)) {
775 stride = format.getInteger(FORMAT_KEY_STRIDE);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000776 }
magjed0c29de52017-03-02 00:55:32 -0800777 if (format.containsKey(FORMAT_KEY_SLICE_HEIGHT)) {
778 sliceHeight = format.getInteger(FORMAT_KEY_SLICE_HEIGHT);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000779 }
Magnus Jedvert7e319372015-10-02 15:49:38 +0200780 Logging.d(TAG, "Frame stride and slice height: " + stride + " x " + sliceHeight);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000781 stride = Math.max(width, stride);
782 sliceHeight = Math.max(height, sliceHeight);
Magnus Jedvert7e319372015-10-02 15:49:38 +0200783 break;
Per488e75f2015-11-19 10:43:36 +0100784 case MediaCodec.INFO_TRY_AGAIN_LATER:
785 return null;
Magnus Jedvert7e319372015-10-02 15:49:38 +0200786 default:
Per488e75f2015-11-19 10:43:36 +0100787 hasDecodedFirstFrame = true;
788 TimeStamps timeStamps = decodeStartTimeMs.remove();
magjedcedddbd2016-02-26 09:36:04 -0800789 long decodeTimeMs = SystemClock.elapsedRealtime() - timeStamps.decodeStartTimeMs;
790 if (decodeTimeMs > MAX_DECODE_TIME_MS) {
Alex Glaznevd5704842016-06-27 11:51:10 -0700791 Logging.e(TAG, "Very high decode time: " + decodeTimeMs + "ms"
sakalb6760f92016-09-29 04:12:44 -0700792 + ". Q size: " + decodeStartTimeMs.size()
793 + ". Might be caused by resuming H264 decoding after a pause.");
magjedcedddbd2016-02-26 09:36:04 -0800794 decodeTimeMs = MAX_DECODE_TIME_MS;
795 }
sakalb6760f92016-09-29 04:12:44 -0700796 return new DecodedOutputBuffer(result, info.offset, info.size,
797 TimeUnit.MICROSECONDS.toMillis(info.presentationTimeUs), timeStamps.timeStampMs,
798 timeStamps.ntpTimeStampMs, decodeTimeMs, SystemClock.elapsedRealtime());
799 }
perkj9cb89822015-11-11 03:27:01 -0800800 }
perkj9cb89822015-11-11 03:27:01 -0800801 }
802
Per488e75f2015-11-19 10:43:36 +0100803 // Returns null if no decoded buffer is available, and otherwise a DecodedTextureBuffer.
804 // Throws IllegalStateException if call is made on the wrong thread, if color format changes to an
805 // unsupported format, or if |mediaCodec| is not in the Executing state. Throws CodecException
806 // upon codec error. If |dequeueTimeoutMs| > 0, the oldest decoded frame will be dropped if
807 // a frame can't be returned.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100808 @CalledByNativeUnchecked
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100809 private @Nullable DecodedTextureBuffer dequeueTextureBuffer(int dequeueTimeoutMs) {
Per488e75f2015-11-19 10:43:36 +0100810 checkOnMediaCodecThread();
811 if (!useSurface) {
812 throw new IllegalStateException("dequeueTexture() called for byte buffer decoding.");
813 }
814 DecodedOutputBuffer outputBuffer = dequeueOutputBuffer(dequeueTimeoutMs);
815 if (outputBuffer != null) {
816 dequeuedSurfaceOutputBuffers.add(outputBuffer);
817 }
818
819 MaybeRenderDecodedTextureBuffer();
820 // Check if there is texture ready now by waiting max |dequeueTimeoutMs|.
821 DecodedTextureBuffer renderedBuffer = textureListener.dequeueTextureBuffer(dequeueTimeoutMs);
822 if (renderedBuffer != null) {
823 MaybeRenderDecodedTextureBuffer();
824 return renderedBuffer;
825 }
826
827 if ((dequeuedSurfaceOutputBuffers.size()
sakalb6760f92016-09-29 04:12:44 -0700828 >= Math.min(MAX_QUEUED_OUTPUTBUFFERS, outputBuffers.length)
829 || (dequeueTimeoutMs > 0 && !dequeuedSurfaceOutputBuffers.isEmpty()))) {
Per488e75f2015-11-19 10:43:36 +0100830 ++droppedFrames;
831 // Drop the oldest frame still in dequeuedSurfaceOutputBuffers.
832 // The oldest frame is owned by |textureListener| and can't be dropped since
833 // mediaCodec.releaseOutputBuffer has already been called.
834 final DecodedOutputBuffer droppedFrame = dequeuedSurfaceOutputBuffers.remove();
835 if (dequeueTimeoutMs > 0) {
perkj7baf79f2015-11-24 06:26:38 -0800836 // TODO(perkj): Re-add the below log when VideoRenderGUI has been removed or fixed to
837 // return the one and only texture even if it does not render.
glaznevae95ff32016-02-04 11:47:12 -0800838 Logging.w(TAG, "Draining decoder. Dropping frame with TS: "
sakalb6760f92016-09-29 04:12:44 -0700839 + droppedFrame.presentationTimeStampMs + ". Total number of dropped frames: "
840 + droppedFrames);
Per488e75f2015-11-19 10:43:36 +0100841 } else {
sakalb6760f92016-09-29 04:12:44 -0700842 Logging.w(TAG, "Too many output buffers " + dequeuedSurfaceOutputBuffers.size()
843 + ". Dropping frame with TS: " + droppedFrame.presentationTimeStampMs
844 + ". Total number of dropped frames: " + droppedFrames);
Per488e75f2015-11-19 10:43:36 +0100845 }
846
847 mediaCodec.releaseOutputBuffer(droppedFrame.index, false /* render */);
Magnus Jedvertb9ac1212018-04-23 11:29:05 +0200848 return new DecodedTextureBuffer(null /* videoFrameBuffer */,
849 droppedFrame.presentationTimeStampMs, droppedFrame.timeStampMs,
850 droppedFrame.ntpTimeStampMs, droppedFrame.decodeTimeMs,
Per488e75f2015-11-19 10:43:36 +0100851 SystemClock.elapsedRealtime() - droppedFrame.endDecodeTimeMs);
852 }
853 return null;
854 }
855
856 private void MaybeRenderDecodedTextureBuffer() {
857 if (dequeuedSurfaceOutputBuffers.isEmpty() || textureListener.isWaitingForTexture()) {
858 return;
859 }
860 // Get the first frame in the queue and render to the decoder output surface.
861 final DecodedOutputBuffer buffer = dequeuedSurfaceOutputBuffers.remove();
862 textureListener.addBufferToRender(buffer);
863 mediaCodec.releaseOutputBuffer(buffer.index, true /* render */);
864 }
865
magjed44bf6f52015-10-03 02:08:00 -0700866 // Release a dequeued output byte buffer back to the codec for re-use. Should only be called for
867 // non-surface decoding.
868 // Throws IllegalStateException if the call is made on the wrong thread, if codec is configured
869 // for surface decoding, or if |mediaCodec| is not in the Executing state. Throws
870 // MediaCodec.CodecException upon codec error.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100871 @CalledByNativeUnchecked
Per488e75f2015-11-19 10:43:36 +0100872 private void returnDecodedOutputBuffer(int index)
Magnus Jedvert7e319372015-10-02 15:49:38 +0200873 throws IllegalStateException, MediaCodec.CodecException {
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000874 checkOnMediaCodecThread();
magjed44bf6f52015-10-03 02:08:00 -0700875 if (useSurface) {
Per488e75f2015-11-19 10:43:36 +0100876 throw new IllegalStateException("returnDecodedOutputBuffer() called for surface decoding.");
magjed44bf6f52015-10-03 02:08:00 -0700877 }
878 mediaCodec.releaseOutputBuffer(index, false /* render */);
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000879 }
Magnus Jedvert655e1962017-12-08 11:05:22 +0100880
881 @CalledByNative
882 ByteBuffer[] getInputBuffers() {
883 return inputBuffers;
884 }
885
886 @CalledByNative
887 ByteBuffer[] getOutputBuffers() {
888 return outputBuffers;
889 }
890
891 @CalledByNative
892 int getColorFormat() {
893 return colorFormat;
894 }
895
896 @CalledByNative
897 int getWidth() {
898 return width;
899 }
900
901 @CalledByNative
902 int getHeight() {
903 return height;
904 }
905
906 @CalledByNative
907 int getStride() {
908 return stride;
909 }
910
911 @CalledByNative
912 int getSliceHeight() {
913 return sliceHeight;
914 }
glaznev@webrtc.orgefe4b9a2014-07-22 17:44:53 +0000915}