blob: 63aa2727810c92673a4ac6e25ae9b55ebc51cbfc [file] [log] [blame]
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2013 The WebRTC project authors. All Rights Reserved.
fischman@webrtc.org540acde2014-02-13 03:56:14 +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.
fischman@webrtc.org540acde2014-02-13 03:56:14 +00009 */
10
fischman@webrtc.org540acde2014-02-13 03:56:14 +000011package org.webrtc;
12
Patrik Höglund68876f92015-11-12 17:36:48 +010013import android.annotation.TargetApi;
sakalb5f5bdc2017-08-10 04:15:42 -070014import android.graphics.Matrix;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000015import android.media.MediaCodec;
16import android.media.MediaCodecInfo;
Sami Kalliomakid3235f02016-08-02 15:44:04 +020017import android.media.MediaCodecInfo.CodecCapabilities;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000018import android.media.MediaCodecList;
19import android.media.MediaFormat;
perkj30e91822015-11-20 01:31:25 -080020import android.opengl.GLES20;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000021import android.os.Build;
22import android.os.Bundle;
perkj30e91822015-11-20 01:31:25 -080023import android.view.Surface;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000024import java.nio.ByteBuffer;
magjed295760d2017-01-12 01:11:57 -080025import java.util.ArrayList;
Alex Glaznev0c850202015-08-04 10:26:59 -070026import java.util.Arrays;
Alex Glazneveee86a62016-01-29 14:17:07 -080027import java.util.HashSet;
Alex Glaznev0c850202015-08-04 10:26:59 -070028import java.util.List;
Alex Glazneveee86a62016-01-29 14:17:07 -080029import java.util.Set;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070030import java.util.concurrent.CountDownLatch;
perkj48477c12015-12-18 00:34:37 -080031import java.util.concurrent.TimeUnit;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010032import javax.annotation.Nullable;
Magnus Jedvert655e1962017-12-08 11:05:22 +010033import org.webrtc.EglBase14;
34import org.webrtc.VideoFrame;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000035
Magnus Jedvert9060eb12017-12-12 12:52:54 +010036// Java-side of peerconnection.cc:MediaCodecVideoEncoder.
fischman@webrtc.org540acde2014-02-13 03:56:14 +000037// This class is an implementation detail of the Java PeerConnection API.
Patrik Höglund68876f92015-11-12 17:36:48 +010038@TargetApi(19)
39@SuppressWarnings("deprecation")
perkj@webrtc.org47098872014-10-24 11:38:19 +000040public class MediaCodecVideoEncoder {
fischman@webrtc.org540acde2014-02-13 03:56:14 +000041 // This class is constructed, operated, and destroyed by its C++ incarnation,
42 // so the class and its methods have non-public visibility. The API this
43 // class exposes aims to mimic the webrtc::VideoEncoder API as closely as
44 // possibly to minimize the amount of translation work necessary.
45
46 private static final String TAG = "MediaCodecVideoEncoder";
47
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000048 // Tracks webrtc::VideoCodecType.
Magnus Jedvert655e1962017-12-08 11:05:22 +010049 public enum VideoCodecType {
Niels Möller520ca4e2018-06-04 11:14:38 +020050 VIDEO_CODEC_UNKNOWN,
Magnus Jedvert655e1962017-12-08 11:05:22 +010051 VIDEO_CODEC_VP8,
52 VIDEO_CODEC_VP9,
53 VIDEO_CODEC_H264;
54
55 @CalledByNative("VideoCodecType")
56 static VideoCodecType fromNativeIndex(int nativeIndex) {
57 return values()[nativeIndex];
58 }
59 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000060
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070061 private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; // Timeout for codec releasing.
sakalb6760f92016-09-29 04:12:44 -070062 private static final int DEQUEUE_TIMEOUT = 0; // Non-blocking, no wait.
Alex Glaznev269fe752016-05-25 16:17:33 -070063 private static final int BITRATE_ADJUSTMENT_FPS = 30;
Alex Glaznevc55c39d2016-09-02 12:16:27 -070064 private static final int MAXIMUM_INITIAL_FPS = 30;
Alex Glaznevcfaca032016-09-06 14:08:19 -070065 private static final double BITRATE_CORRECTION_SEC = 3.0;
Alex Glaznev7fa4a722017-01-17 15:32:02 -080066 // Maximum bitrate correction scale - no more than 4 times.
67 private static final double BITRATE_CORRECTION_MAX_SCALE = 4;
Alex Glaznevcfaca032016-09-06 14:08:19 -070068 // Amount of correction steps to reach correction maximum scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -080069 private static final int BITRATE_CORRECTION_STEPS = 20;
Alex Glaznevc7483a72017-01-05 15:22:24 -080070 // Forced key frame interval - used to reduce color distortions on Qualcomm platform.
alexlau84ee5c62017-06-02 17:36:32 -070071 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS = 15000;
72 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS = 20000;
Alex Glaznevc7483a72017-01-05 15:22:24 -080073 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS = 15000;
Alex Glaznevcfaca032016-09-06 14:08:19 -070074
perkj9576e542015-11-12 06:43:16 -080075 // Active running encoder instance. Set in initEncode() (called from native code)
Alex Glaznevc6aec4b2015-10-19 16:39:19 -070076 // and reset to null in release() call.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010077 @Nullable private static MediaCodecVideoEncoder runningInstance = null;
78 @Nullable private static MediaCodecVideoEncoderErrorCallback 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> hwEncoderDisabledTypes = 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;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000085 private ByteBuffer[] outputBuffers;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010086 @Nullable private EglBase14 eglBase;
glaznev3fc23502017-06-15 16:24:37 -070087 private int profile;
Magnus Jedvert51254332015-12-15 16:22:29 +010088 private int width;
89 private int height;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +010090 @Nullable private Surface inputSurface;
91 @Nullable private GlRectDrawer drawer;
Alex Glaznev269fe752016-05-25 16:17:33 -070092
fischman@webrtc.org540acde2014-02-13 03:56:14 +000093 private static final String VP8_MIME_TYPE = "video/x-vnd.on2.vp8";
Alex Glaznevad948c42015-11-18 13:06:42 -080094 private static final String VP9_MIME_TYPE = "video/x-vnd.on2.vp9";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000095 private static final String H264_MIME_TYPE = "video/avc";
Alex Glaznev269fe752016-05-25 16:17:33 -070096
glaznev3fc23502017-06-15 16:24:37 -070097 private static final int VIDEO_AVCProfileHigh = 8;
98 private static final int VIDEO_AVCLevel3 = 0x100;
99
Alex Glaznevcfaca032016-09-06 14:08:19 -0700100 // Type of bitrate adjustment for video encoder.
101 public enum BitrateAdjustmentType {
102 // No adjustment - video encoder has no known bitrate problem.
103 NO_ADJUSTMENT,
104 // Framerate based bitrate adjustment is required - HW encoder does not use frame
105 // timestamps to calculate frame bitrate budget and instead is relying on initial
106 // fps configuration assuming that all frames are coming at fixed initial frame rate.
107 FRAMERATE_ADJUSTMENT,
108 // Dynamic bitrate adjustment is required - HW encoder used frame timestamps, but actual
109 // bitrate deviates too much from the target value.
110 DYNAMIC_ADJUSTMENT
111 }
112
glaznev3fc23502017-06-15 16:24:37 -0700113 // Should be in sync with webrtc::H264::Profile.
114 public static enum H264Profile {
115 CONSTRAINED_BASELINE(0),
116 BASELINE(1),
117 MAIN(2),
118 CONSTRAINED_HIGH(3),
119 HIGH(4);
120
121 private final int value;
122
123 H264Profile(int value) {
124 this.value = value;
125 }
126
127 public int getValue() {
128 return value;
129 }
130 }
131
Alex Glaznev269fe752016-05-25 16:17:33 -0700132 // Class describing supported media codec properties.
133 private static class MediaCodecProperties {
134 public final String codecPrefix;
135 // Minimum Android SDK required for this codec to be used.
136 public final int minSdk;
137 // Flag if encoder implementation does not use frame timestamps to calculate frame bitrate
138 // budget and instead is relying on initial fps configuration assuming that all frames are
139 // coming at fixed initial frame rate. Bitrate adjustment is required for this case.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700140 public final BitrateAdjustmentType bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700141
142 MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700143 String codecPrefix, int minSdk, BitrateAdjustmentType bitrateAdjustmentType) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700144 this.codecPrefix = codecPrefix;
145 this.minSdk = minSdk;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700146 this.bitrateAdjustmentType = bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700147 }
148 }
149
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700150 // List of supported HW VP8 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700151 private static final MediaCodecProperties qcomVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700152 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700153 private static final MediaCodecProperties exynosVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700154 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.DYNAMIC_ADJUSTMENT);
magjed295760d2017-01-12 01:11:57 -0800155 private static final MediaCodecProperties intelVp8HwProperties = new MediaCodecProperties(
156 "OMX.Intel.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.NO_ADJUSTMENT);
157 private static MediaCodecProperties[] vp8HwList() {
158 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
159 supported_codecs.add(qcomVp8HwProperties);
160 supported_codecs.add(exynosVp8HwProperties);
161 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-IntelVP8").equals("Enabled")) {
162 supported_codecs.add(intelVp8HwProperties);
163 }
164 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
165 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700166
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700167 // List of supported HW VP9 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700168 private static final MediaCodecProperties qcomVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700169 "OMX.qcom.", Build.VERSION_CODES.N, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700170 private static final MediaCodecProperties exynosVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700171 "OMX.Exynos.", Build.VERSION_CODES.N, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
sakalb6760f92016-09-29 04:12:44 -0700172 private static final MediaCodecProperties[] vp9HwList =
173 new MediaCodecProperties[] {qcomVp9HwProperties, exynosVp9HwProperties};
Alex Glaznev269fe752016-05-25 16:17:33 -0700174
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700175 // List of supported HW H.264 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700176 private static final MediaCodecProperties qcomH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700177 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700178 private static final MediaCodecProperties exynosH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700179 "OMX.Exynos.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
Alex Leung5b6891a2018-01-18 10:01:14 -0800180 private static final MediaCodecProperties mediatekH264HwProperties = new MediaCodecProperties(
Alex Leung28e71072018-02-05 13:42:48 -0800181 "OMX.MTK.", Build.VERSION_CODES.O_MR1, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
Alex Leung5b6891a2018-01-18 10:01:14 -0800182 private static final MediaCodecProperties[] h264HwList() {
183 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
184 supported_codecs.add(qcomH264HwProperties);
185 supported_codecs.add(exynosH264HwProperties);
186 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekH264").equals("Enabled")) {
187 supported_codecs.add(mediatekH264HwProperties);
188 }
189 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
190 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700191
glaznev3fc23502017-06-15 16:24:37 -0700192 // List of supported HW H.264 high profile encoders.
193 private static final MediaCodecProperties exynosH264HighProfileHwProperties =
194 new MediaCodecProperties(
195 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
196 private static final MediaCodecProperties[] h264HighProfileHwList =
197 new MediaCodecProperties[] {exynosH264HighProfileHwProperties};
198
Alex Glaznev0c850202015-08-04 10:26:59 -0700199 // List of devices with poor H.264 encoder quality.
sakalb6760f92016-09-29 04:12:44 -0700200 // HW H.264 encoder on below devices has poor bitrate control - actual
201 // bitrates deviates a lot from the target value.
202 private static final String[] H264_HW_EXCEPTION_MODELS =
203 new String[] {"SAMSUNG-SGH-I337", "Nexus 7", "Nexus 4"};
Alex Glaznev0c850202015-08-04 10:26:59 -0700204
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000205 // Bitrate modes - should be in sync with OMX_VIDEO_CONTROLRATETYPE defined
206 // in OMX_Video.h
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000207 private static final int VIDEO_ControlRateConstant = 2;
208 // NV12 color format supported by QCOM codec, but not declared in MediaCodec -
209 // see /hardware/qcom/media/mm-core/inc/OMX_QCOMExtns.h
sakalb6760f92016-09-29 04:12:44 -0700210 private static final int COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m = 0x7FA30C04;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000211 // Allowable color formats supported by codec - in order of preference.
sakalb6760f92016-09-29 04:12:44 -0700212 private static final int[] supportedColorList = {CodecCapabilities.COLOR_FormatYUV420Planar,
213 CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
214 CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
215 COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m};
216 private static final int[] supportedSurfaceColorList = {CodecCapabilities.COLOR_FormatSurface};
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000217 private VideoCodecType type;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100218 private int colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700219
220 // Variables used for dynamic bitrate adjustment.
221 private BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
222 private double bitrateAccumulator;
223 private double bitrateAccumulatorMax;
224 private double bitrateObservationTimeMs;
225 private int bitrateAdjustmentScaleExp;
226 private int targetBitrateBps;
227 private int targetFps;
perkj9576e542015-11-12 06:43:16 -0800228
Alex Glaznevc7483a72017-01-05 15:22:24 -0800229 // Interval in ms to force key frame generation. Used to reduce the time of color distortions
230 // happened sometime when using Qualcomm video encoder.
231 private long forcedKeyFrameMs;
232 private long lastKeyFrameMs;
233
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000234 // SPS and PPS NALs (Config frame) for H.264.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100235 @Nullable private ByteBuffer configData = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000236
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700237 // MediaCodec error handler - invoked when critical error happens which may prevent
238 // further use of media codec API. Now it means that one of media codec instances
239 // is hanging and can no longer be used in the next call.
240 public static interface MediaCodecVideoEncoderErrorCallback {
241 void onMediaCodecVideoEncoderCriticalError(int codecErrors);
242 }
243
244 public static void setErrorCallback(MediaCodecVideoEncoderErrorCallback errorCallback) {
245 Logging.d(TAG, "Set error callback");
246 MediaCodecVideoEncoder.errorCallback = errorCallback;
247 }
248
Alex Glazneveee86a62016-01-29 14:17:07 -0800249 // Functions to disable HW encoding - can be called from applications for platforms
250 // which have known HW decoding problems.
251 public static void disableVp8HwCodec() {
252 Logging.w(TAG, "VP8 encoding is disabled by application.");
253 hwEncoderDisabledTypes.add(VP8_MIME_TYPE);
254 }
255
256 public static void disableVp9HwCodec() {
257 Logging.w(TAG, "VP9 encoding is disabled by application.");
258 hwEncoderDisabledTypes.add(VP9_MIME_TYPE);
259 }
260
261 public static void disableH264HwCodec() {
262 Logging.w(TAG, "H.264 encoding is disabled by application.");
263 hwEncoderDisabledTypes.add(H264_MIME_TYPE);
264 }
265
266 // Functions to query if HW encoding is supported.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100267 @CalledByNative
Alex Glazneveee86a62016-01-29 14:17:07 -0800268 public static boolean isVp8HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700269 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800270 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800271 }
272
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100273 public static @Nullable EncoderProperties vp8HwEncoderProperties() {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800274 if (hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)) {
275 return null;
276 } else {
magjed295760d2017-01-12 01:11:57 -0800277 return findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList);
Alex Glaznevc7483a72017-01-05 15:22:24 -0800278 }
279 }
280
Magnus Jedvert655e1962017-12-08 11:05:22 +0100281 @CalledByNative
Alex Glazneveee86a62016-01-29 14:17:07 -0800282 public static boolean isVp9HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700283 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
284 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800285 }
286
Magnus Jedvert655e1962017-12-08 11:05:22 +0100287 @CalledByNative
Alex Glazneveee86a62016-01-29 14:17:07 -0800288 public static boolean isH264HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700289 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800290 && (findHwEncoder(H264_MIME_TYPE, h264HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800291 }
292
glaznev3fc23502017-06-15 16:24:37 -0700293 public static boolean isH264HighProfileHwSupported() {
294 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
295 && (findHwEncoder(H264_MIME_TYPE, h264HighProfileHwList, supportedColorList) != null);
296 }
297
Alex Glazneveee86a62016-01-29 14:17:07 -0800298 public static boolean isVp8HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700299 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800300 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800301 }
302
303 public static boolean isVp9HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700304 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
305 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800306 }
307
308 public static boolean isH264HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700309 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800310 && (findHwEncoder(H264_MIME_TYPE, h264HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800311 }
312
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000313 // Helper struct for findHwEncoder() below.
Alex Glaznevc7483a72017-01-05 15:22:24 -0800314 public static class EncoderProperties {
Alex Glaznevcfaca032016-09-06 14:08:19 -0700315 public EncoderProperties(
316 String codecName, int colorFormat, BitrateAdjustmentType bitrateAdjustmentType) {
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000317 this.codecName = codecName;
318 this.colorFormat = colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700319 this.bitrateAdjustmentType = bitrateAdjustmentType;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000320 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000321 public final String codecName; // OpenMax component name for HW codec.
sakalb6760f92016-09-29 04:12:44 -0700322 public final int colorFormat; // Color format supported by codec.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700323 public final BitrateAdjustmentType bitrateAdjustmentType; // Bitrate adjustment type
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000324 }
325
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100326 private static @Nullable EncoderProperties findHwEncoder(
Alex Glaznev269fe752016-05-25 16:17:33 -0700327 String mime, MediaCodecProperties[] supportedHwCodecProperties, int[] colorList) {
Alex Glaznev0c850202015-08-04 10:26:59 -0700328 // MediaCodec.setParameters is missing for JB and below, so bitrate
329 // can not be adjusted dynamically.
330 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
331 return null;
332 }
333
334 // Check if device is in H.264 exception list.
335 if (mime.equals(H264_MIME_TYPE)) {
336 List<String> exceptionModels = Arrays.asList(H264_HW_EXCEPTION_MODELS);
337 if (exceptionModels.contains(Build.MODEL)) {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700338 Logging.w(TAG, "Model: " + Build.MODEL + " has black listed H.264 encoder.");
Alex Glaznev0c850202015-08-04 10:26:59 -0700339 return null;
340 }
341 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000342
343 for (int i = 0; i < MediaCodecList.getCodecCount(); ++i) {
Alex Glaznev0060c562016-08-08 12:27:24 -0700344 MediaCodecInfo info = null;
345 try {
346 info = MediaCodecList.getCodecInfoAt(i);
347 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700348 Logging.e(TAG, "Cannot retrieve encoder codec info", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700349 }
350 if (info == null || !info.isEncoder()) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000351 continue;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000352 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000353 String name = null;
354 for (String mimeType : info.getSupportedTypes()) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000355 if (mimeType.equals(mime)) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000356 name = info.getName();
357 break;
358 }
359 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000360 if (name == null) {
sakalb6760f92016-09-29 04:12:44 -0700361 continue; // No HW support in this codec; try the next one.
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000362 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700363 Logging.v(TAG, "Found candidate encoder " + name);
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000364
365 // Check if this is supported HW encoder.
366 boolean supportedCodec = false;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700367 BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
Alex Glaznev269fe752016-05-25 16:17:33 -0700368 for (MediaCodecProperties codecProperties : supportedHwCodecProperties) {
369 if (name.startsWith(codecProperties.codecPrefix)) {
370 if (Build.VERSION.SDK_INT < codecProperties.minSdk) {
sakalb6760f92016-09-29 04:12:44 -0700371 Logging.w(
372 TAG, "Codec " + name + " is disabled due to SDK version " + Build.VERSION.SDK_INT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700373 continue;
374 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700375 if (codecProperties.bitrateAdjustmentType != BitrateAdjustmentType.NO_ADJUSTMENT) {
376 bitrateAdjustmentType = codecProperties.bitrateAdjustmentType;
sakalb6760f92016-09-29 04:12:44 -0700377 Logging.w(
378 TAG, "Codec " + name + " requires bitrate adjustment: " + bitrateAdjustmentType);
Alex Glaznev269fe752016-05-25 16:17:33 -0700379 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000380 supportedCodec = true;
381 break;
382 }
383 }
384 if (!supportedCodec) {
385 continue;
386 }
387
Alex Glaznev269fe752016-05-25 16:17:33 -0700388 // Check if HW codec supports known color format.
Alex Glaznev0060c562016-08-08 12:27:24 -0700389 CodecCapabilities capabilities;
390 try {
391 capabilities = info.getCapabilitiesForType(mime);
392 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700393 Logging.e(TAG, "Cannot retrieve encoder capabilities", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700394 continue;
395 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000396 for (int colorFormat : capabilities.colorFormats) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700397 Logging.v(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000398 }
399
perkj30e91822015-11-20 01:31:25 -0800400 for (int supportedColorFormat : colorList) {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000401 for (int codecColorFormat : capabilities.colorFormats) {
402 if (codecColorFormat == supportedColorFormat) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000403 // Found supported HW encoder.
sakalb6760f92016-09-29 04:12:44 -0700404 Logging.d(TAG, "Found target encoder for mime " + mime + " : " + name + ". Color: 0x"
405 + Integer.toHexString(codecColorFormat) + ". Bitrate adjustment: "
406 + bitrateAdjustmentType);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700407 return new EncoderProperties(name, codecColorFormat, bitrateAdjustmentType);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000408 }
409 }
410 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000411 }
sakalb6760f92016-09-29 04:12:44 -0700412 return null; // No HW encoder.
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000413 }
414
Magnus Jedvert655e1962017-12-08 11:05:22 +0100415 @CalledByNative
416 MediaCodecVideoEncoder() {}
417
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000418 private void checkOnMediaCodecThread() {
419 if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
sakalb6760f92016-09-29 04:12:44 -0700420 throw new RuntimeException("MediaCodecVideoEncoder previously operated on " + mediaCodecThread
421 + " but is now called on " + Thread.currentThread());
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000422 }
423 }
424
Alex Glaznev325d4142015-10-12 14:56:02 -0700425 public static void printStackTrace() {
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700426 if (runningInstance != null && runningInstance.mediaCodecThread != null) {
427 StackTraceElement[] mediaCodecStackTraces = runningInstance.mediaCodecThread.getStackTrace();
Alex Glaznev325d4142015-10-12 14:56:02 -0700428 if (mediaCodecStackTraces.length > 0) {
429 Logging.d(TAG, "MediaCodecVideoEncoder stacks trace:");
430 for (StackTraceElement stackTrace : mediaCodecStackTraces) {
431 Logging.d(TAG, stackTrace.toString());
432 }
433 }
434 }
435 }
436
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100437 static @Nullable MediaCodec createByCodecName(String codecName) {
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000438 try {
439 // In the L-SDK this call can throw IOException so in order to work in
440 // both cases catch an exception.
441 return MediaCodec.createByCodecName(codecName);
442 } catch (Exception e) {
443 return null;
444 }
445 }
446
Magnus Jedvert655e1962017-12-08 11:05:22 +0100447 @CalledByNativeUnchecked
glaznev3fc23502017-06-15 16:24:37 -0700448 boolean initEncode(VideoCodecType type, int profile, int width, int height, int kbps, int fps,
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100449 @Nullable EglBase14.Context sharedContext) {
perkj30e91822015-11-20 01:31:25 -0800450 final boolean useSurface = sharedContext != null;
glaznev3fc23502017-06-15 16:24:37 -0700451 Logging.d(TAG,
452 "Java initEncode: " + type + ". Profile: " + profile + " : " + width + " x " + height
453 + ". @ " + kbps + " kbps. Fps: " + fps + ". Encode from texture : " + useSurface);
perkj9576e542015-11-12 06:43:16 -0800454
glaznev3fc23502017-06-15 16:24:37 -0700455 this.profile = profile;
Magnus Jedvert51254332015-12-15 16:22:29 +0100456 this.width = width;
457 this.height = height;
Alejandro Luebs69ddaef2015-10-09 15:46:09 -0700458 if (mediaCodecThread != null) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000459 throw new RuntimeException("Forgot to release()?");
460 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000461 EncoderProperties properties = null;
462 String mime = null;
463 int keyFrameIntervalSec = 0;
glaznev3fc23502017-06-15 16:24:37 -0700464 boolean configureH264HighProfile = false;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000465 if (type == VideoCodecType.VIDEO_CODEC_VP8) {
466 mime = VP8_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700467 properties = findHwEncoder(
magjed295760d2017-01-12 01:11:57 -0800468 VP8_MIME_TYPE, vp8HwList(), useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000469 keyFrameIntervalSec = 100;
Alex Glaznevad948c42015-11-18 13:06:42 -0800470 } else if (type == VideoCodecType.VIDEO_CODEC_VP9) {
471 mime = VP9_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700472 properties = findHwEncoder(
473 VP9_MIME_TYPE, vp9HwList, useSurface ? supportedSurfaceColorList : supportedColorList);
Alex Glaznevad948c42015-11-18 13:06:42 -0800474 keyFrameIntervalSec = 100;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000475 } else if (type == VideoCodecType.VIDEO_CODEC_H264) {
476 mime = H264_MIME_TYPE;
Alex Leung5b6891a2018-01-18 10:01:14 -0800477 properties = findHwEncoder(H264_MIME_TYPE, h264HwList(),
478 useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev3fc23502017-06-15 16:24:37 -0700479 if (profile == H264Profile.CONSTRAINED_HIGH.getValue()) {
480 EncoderProperties h264HighProfileProperties = findHwEncoder(H264_MIME_TYPE,
481 h264HighProfileHwList, useSurface ? supportedSurfaceColorList : supportedColorList);
482 if (h264HighProfileProperties != null) {
483 Logging.d(TAG, "High profile H.264 encoder supported.");
484 configureH264HighProfile = true;
485 } else {
486 Logging.d(TAG, "High profile H.264 encoder requested, but not supported. Use baseline.");
487 }
488 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000489 keyFrameIntervalSec = 20;
Niels Möller520ca4e2018-06-04 11:14:38 +0200490 } else {
491 throw new RuntimeException("initEncode: Non-supported codec " + type);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000492 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000493 if (properties == null) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000494 throw new RuntimeException("Can not find HW encoder for " + type);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000495 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700496 runningInstance = this; // Encoder is now running and can be queried for stack traces.
perkj9576e542015-11-12 06:43:16 -0800497 colorFormat = properties.colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700498 bitrateAdjustmentType = properties.bitrateAdjustmentType;
499 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700500 fps = BITRATE_ADJUSTMENT_FPS;
sakalb6760f92016-09-29 04:12:44 -0700501 } else {
Alex Glaznevc55c39d2016-09-02 12:16:27 -0700502 fps = Math.min(fps, MAXIMUM_INITIAL_FPS);
Alex Glaznev269fe752016-05-25 16:17:33 -0700503 }
Alex Glaznevc7483a72017-01-05 15:22:24 -0800504
505 forcedKeyFrameMs = 0;
506 lastKeyFrameMs = -1;
Alex Glaznev512f00b2017-01-05 16:40:46 -0800507 if (type == VideoCodecType.VIDEO_CODEC_VP8
508 && properties.codecName.startsWith(qcomVp8HwProperties.codecPrefix)) {
alexlau84ee5c62017-06-02 17:36:32 -0700509 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP
510 || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
511 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS;
512 } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800513 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS;
514 } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
515 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS;
516 }
517 }
518
sakalb6760f92016-09-29 04:12:44 -0700519 Logging.d(TAG, "Color format: " + colorFormat + ". Bitrate adjustment: " + bitrateAdjustmentType
Alex Glaznevc7483a72017-01-05 15:22:24 -0800520 + ". Key frame interval: " + forcedKeyFrameMs + " . Initial fps: " + fps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700521 targetBitrateBps = 1000 * kbps;
522 targetFps = fps;
523 bitrateAccumulatorMax = targetBitrateBps / 8.0;
524 bitrateAccumulator = 0;
525 bitrateObservationTimeMs = 0;
526 bitrateAdjustmentScaleExp = 0;
perkj9576e542015-11-12 06:43:16 -0800527
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000528 mediaCodecThread = Thread.currentThread();
529 try {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000530 MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700531 format.setInteger(MediaFormat.KEY_BIT_RATE, targetBitrateBps);
Alex Glaznev8a2cd3d2015-08-11 11:32:53 -0700532 format.setInteger("bitrate-mode", VIDEO_ControlRateConstant);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000533 format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700534 format.setInteger(MediaFormat.KEY_FRAME_RATE, targetFps);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000535 format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameIntervalSec);
glaznev3fc23502017-06-15 16:24:37 -0700536 if (configureH264HighProfile) {
537 format.setInteger("profile", VIDEO_AVCProfileHigh);
538 format.setInteger("level", VIDEO_AVCLevel3);
539 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700540 Logging.d(TAG, " Format: " + format);
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000541 mediaCodec = createByCodecName(properties.codecName);
perkj9576e542015-11-12 06:43:16 -0800542 this.type = type;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000543 if (mediaCodec == null) {
Alex Glaznev325d4142015-10-12 14:56:02 -0700544 Logging.e(TAG, "Can not create media encoder");
sakal996a83c2017-03-15 05:53:14 -0700545 release();
perkj9576e542015-11-12 06:43:16 -0800546 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000547 }
sakalb6760f92016-09-29 04:12:44 -0700548 mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
perkj9576e542015-11-12 06:43:16 -0800549
perkj30e91822015-11-20 01:31:25 -0800550 if (useSurface) {
perkj48477c12015-12-18 00:34:37 -0800551 eglBase = new EglBase14(sharedContext, EglBase.CONFIG_RECORDABLE);
perkj30e91822015-11-20 01:31:25 -0800552 // Create an input surface and keep a reference since we must release the surface when done.
553 inputSurface = mediaCodec.createInputSurface();
554 eglBase.createSurface(inputSurface);
555 drawer = new GlRectDrawer();
556 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000557 mediaCodec.start();
558 outputBuffers = mediaCodec.getOutputBuffers();
perkj9576e542015-11-12 06:43:16 -0800559 Logging.d(TAG, "Output buffers: " + outputBuffers.length);
560
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000561 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700562 Logging.e(TAG, "initEncode failed", e);
sakal996a83c2017-03-15 05:53:14 -0700563 release();
perkj9576e542015-11-12 06:43:16 -0800564 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000565 }
perkj9576e542015-11-12 06:43:16 -0800566 return true;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000567 }
568
Magnus Jedvert655e1962017-12-08 11:05:22 +0100569 @CalledByNativeUnchecked
sakalb6760f92016-09-29 04:12:44 -0700570 ByteBuffer[] getInputBuffers() {
perkj9576e542015-11-12 06:43:16 -0800571 ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
572 Logging.d(TAG, "Input buffers: " + inputBuffers.length);
573 return inputBuffers;
574 }
575
Alex Glaznevc7483a72017-01-05 15:22:24 -0800576 void checkKeyFrameRequired(boolean requestedKeyFrame, long presentationTimestampUs) {
577 long presentationTimestampMs = (presentationTimestampUs + 500) / 1000;
578 if (lastKeyFrameMs < 0) {
579 lastKeyFrameMs = presentationTimestampMs;
580 }
581 boolean forcedKeyFrame = false;
582 if (!requestedKeyFrame && forcedKeyFrameMs > 0
583 && presentationTimestampMs > lastKeyFrameMs + forcedKeyFrameMs) {
584 forcedKeyFrame = true;
585 }
586 if (requestedKeyFrame || forcedKeyFrame) {
587 // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could
588 // indicate this in queueInputBuffer() below and guarantee _this_ frame
589 // be encoded as a key frame, but sadly that flag is ignored. Instead,
590 // we request a key frame "soon".
591 if (requestedKeyFrame) {
592 Logging.d(TAG, "Sync frame request");
593 } else {
594 Logging.d(TAG, "Sync frame forced");
595 }
596 Bundle b = new Bundle();
597 b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0);
598 mediaCodec.setParameters(b);
599 lastKeyFrameMs = presentationTimestampMs;
600 }
601 }
602
Magnus Jedvert655e1962017-12-08 11:05:22 +0100603 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800604 boolean encodeBuffer(
sakalb6760f92016-09-29 04:12:44 -0700605 boolean isKeyframe, int inputBuffer, int size, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000606 checkOnMediaCodecThread();
607 try {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800608 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
sakalb6760f92016-09-29 04:12:44 -0700609 mediaCodec.queueInputBuffer(inputBuffer, 0, size, presentationTimestampUs, 0);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000610 return true;
sakalb6760f92016-09-29 04:12:44 -0700611 } catch (IllegalStateException e) {
perkj9576e542015-11-12 06:43:16 -0800612 Logging.e(TAG, "encodeBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000613 return false;
614 }
615 }
616
sakalb5f5bdc2017-08-10 04:15:42 -0700617 /**
Magnus Jedvert655e1962017-12-08 11:05:22 +0100618 * Encodes a new style VideoFrame. |bufferIndex| is -1 if we are not encoding in surface mode.
sakalb5f5bdc2017-08-10 04:15:42 -0700619 */
Magnus Jedvert655e1962017-12-08 11:05:22 +0100620 @CalledByNativeUnchecked
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100621 boolean encodeFrame(long nativeEncoder, boolean isKeyframe, VideoFrame frame, int bufferIndex,
622 long presentationTimestampUs) {
sakalb5f5bdc2017-08-10 04:15:42 -0700623 checkOnMediaCodecThread();
624 try {
sakalb5f5bdc2017-08-10 04:15:42 -0700625 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
626
627 VideoFrame.Buffer buffer = frame.getBuffer();
628 if (buffer instanceof VideoFrame.TextureBuffer) {
629 VideoFrame.TextureBuffer textureBuffer = (VideoFrame.TextureBuffer) buffer;
630 eglBase.makeCurrent();
631 // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway,
632 // but it's a workaround for bug webrtc:5147.
633 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700634 VideoFrameDrawer.drawTexture(drawer, textureBuffer, new Matrix() /* renderMatrix */, width,
sakal9bc599f2017-09-08 04:46:33 -0700635 height, 0 /* viewportX */, 0 /* viewportY */, width, height);
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100636 eglBase.swapBuffers(TimeUnit.MICROSECONDS.toNanos(presentationTimestampUs));
sakalb5f5bdc2017-08-10 04:15:42 -0700637 } else {
638 VideoFrame.I420Buffer i420Buffer = buffer.toI420();
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200639 final int chromaHeight = (height + 1) / 2;
640 final ByteBuffer dataY = i420Buffer.getDataY();
641 final ByteBuffer dataU = i420Buffer.getDataU();
642 final ByteBuffer dataV = i420Buffer.getDataV();
643 final int strideY = i420Buffer.getStrideY();
644 final int strideU = i420Buffer.getStrideU();
645 final int strideV = i420Buffer.getStrideV();
646 if (dataY.capacity() < strideY * height) {
647 throw new RuntimeException("Y-plane buffer size too small.");
648 }
649 if (dataU.capacity() < strideU * chromaHeight) {
650 throw new RuntimeException("U-plane buffer size too small.");
651 }
652 if (dataV.capacity() < strideV * chromaHeight) {
653 throw new RuntimeException("V-plane buffer size too small.");
654 }
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100655 nativeFillInputBuffer(
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200656 nativeEncoder, bufferIndex, dataY, strideY, dataU, strideU, dataV, strideV);
sakalb5f5bdc2017-08-10 04:15:42 -0700657 i420Buffer.release();
658 // I420 consists of one full-resolution and two half-resolution planes.
659 // 1 + 1 / 4 + 1 / 4 = 3 / 2
660 int yuvSize = width * height * 3 / 2;
661 mediaCodec.queueInputBuffer(bufferIndex, 0, yuvSize, presentationTimestampUs, 0);
662 }
663 return true;
664 } catch (RuntimeException e) {
665 Logging.e(TAG, "encodeFrame failed", e);
666 return false;
667 }
668 }
669
Magnus Jedvert655e1962017-12-08 11:05:22 +0100670 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800671 void release() {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700672 Logging.d(TAG, "Java releaseEncoder");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000673 checkOnMediaCodecThread();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700674
sakal996a83c2017-03-15 05:53:14 -0700675 class CaughtException {
676 Exception e;
677 }
678 final CaughtException caughtException = new CaughtException();
679 boolean stopHung = false;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700680
sakal996a83c2017-03-15 05:53:14 -0700681 if (mediaCodec != null) {
682 // Run Mediacodec stop() and release() on separate thread since sometime
683 // Mediacodec.stop() may hang.
684 final CountDownLatch releaseDone = new CountDownLatch(1);
685
686 Runnable runMediaCodecRelease = new Runnable() {
687 @Override
688 public void run() {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700689 Logging.d(TAG, "Java releaseEncoder on release thread");
sakal996a83c2017-03-15 05:53:14 -0700690 try {
691 mediaCodec.stop();
692 } catch (Exception e) {
693 Logging.e(TAG, "Media encoder stop failed", e);
694 }
695 try {
696 mediaCodec.release();
697 } catch (Exception e) {
698 Logging.e(TAG, "Media encoder release failed", e);
699 caughtException.e = e;
700 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700701 Logging.d(TAG, "Java releaseEncoder on release thread done");
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700702
sakal996a83c2017-03-15 05:53:14 -0700703 releaseDone.countDown();
704 }
705 };
706 new Thread(runMediaCodecRelease).start();
707
708 if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) {
709 Logging.e(TAG, "Media encoder release timeout");
710 stopHung = true;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700711 }
sakal996a83c2017-03-15 05:53:14 -0700712
713 mediaCodec = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000714 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700715
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000716 mediaCodecThread = null;
perkj30e91822015-11-20 01:31:25 -0800717 if (drawer != null) {
718 drawer.release();
719 drawer = null;
720 }
721 if (eglBase != null) {
722 eglBase.release();
723 eglBase = null;
724 }
725 if (inputSurface != null) {
726 inputSurface.release();
727 inputSurface = null;
728 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700729 runningInstance = null;
sakal996a83c2017-03-15 05:53:14 -0700730
731 if (stopHung) {
732 codecErrors++;
733 if (errorCallback != null) {
734 Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors);
735 errorCallback.onMediaCodecVideoEncoderCriticalError(codecErrors);
736 }
737 throw new RuntimeException("Media encoder release timeout.");
738 }
739
740 // Re-throw any runtime exception caught inside the other thread. Since this is an invoke, add
741 // stack trace for the waiting thread as well.
742 if (caughtException.e != null) {
743 final RuntimeException runtimeException = new RuntimeException(caughtException.e);
744 runtimeException.setStackTrace(ThreadUtils.concatStackTraces(
745 caughtException.e.getStackTrace(), runtimeException.getStackTrace()));
746 throw runtimeException;
747 }
748
Alex Glaznev325d4142015-10-12 14:56:02 -0700749 Logging.d(TAG, "Java releaseEncoder done");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000750 }
751
Magnus Jedvert655e1962017-12-08 11:05:22 +0100752 @CalledByNativeUnchecked
Alex Glaznev269fe752016-05-25 16:17:33 -0700753 private boolean setRates(int kbps, int frameRate) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000754 checkOnMediaCodecThread();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700755
756 int codecBitrateBps = 1000 * kbps;
757 if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
758 bitrateAccumulatorMax = codecBitrateBps / 8.0;
759 if (targetBitrateBps > 0 && codecBitrateBps < targetBitrateBps) {
760 // Rescale the accumulator level if the accumulator max decreases
761 bitrateAccumulator = bitrateAccumulator * codecBitrateBps / targetBitrateBps;
762 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700763 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700764 targetBitrateBps = codecBitrateBps;
765 targetFps = frameRate;
766
767 // Adjust actual encoder bitrate based on bitrate adjustment type.
768 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT && targetFps > 0) {
769 codecBitrateBps = BITRATE_ADJUSTMENT_FPS * targetBitrateBps / targetFps;
sakalb6760f92016-09-29 04:12:44 -0700770 Logging.v(TAG,
771 "setRates: " + kbps + " -> " + (codecBitrateBps / 1000) + " kbps. Fps: " + targetFps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700772 } else if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
sakalb6760f92016-09-29 04:12:44 -0700773 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps + ". ExpScale: "
774 + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700775 if (bitrateAdjustmentScaleExp != 0) {
sakalb6760f92016-09-29 04:12:44 -0700776 codecBitrateBps = (int) (codecBitrateBps * getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700777 }
778 } else {
779 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps);
780 }
781
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000782 try {
783 Bundle params = new Bundle();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700784 params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, codecBitrateBps);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000785 mediaCodec.setParameters(params);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000786 return true;
787 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700788 Logging.e(TAG, "setRates failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000789 return false;
790 }
791 }
792
793 // Dequeue an input buffer and return its index, -1 if no input buffer is
794 // available, or -2 if the codec is no longer operative.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100795 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800796 int dequeueInputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000797 checkOnMediaCodecThread();
798 try {
799 return mediaCodec.dequeueInputBuffer(DEQUEUE_TIMEOUT);
800 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700801 Logging.e(TAG, "dequeueIntputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000802 return -2;
803 }
804 }
805
806 // Helper struct for dequeueOutputBuffer() below.
perkj9576e542015-11-12 06:43:16 -0800807 static class OutputBufferInfo {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000808 public OutputBufferInfo(
sakalb6760f92016-09-29 04:12:44 -0700809 int index, ByteBuffer buffer, boolean isKeyFrame, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000810 this.index = index;
811 this.buffer = buffer;
812 this.isKeyFrame = isKeyFrame;
813 this.presentationTimestampUs = presentationTimestampUs;
814 }
815
perkj9576e542015-11-12 06:43:16 -0800816 public final int index;
817 public final ByteBuffer buffer;
818 public final boolean isKeyFrame;
819 public final long presentationTimestampUs;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100820
821 @CalledByNative("OutputBufferInfo")
822 int getIndex() {
823 return index;
824 }
825
826 @CalledByNative("OutputBufferInfo")
827 ByteBuffer getBuffer() {
828 return buffer;
829 }
830
831 @CalledByNative("OutputBufferInfo")
832 boolean isKeyFrame() {
833 return isKeyFrame;
834 }
835
836 @CalledByNative("OutputBufferInfo")
837 long getPresentationTimestampUs() {
838 return presentationTimestampUs;
839 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000840 }
841
842 // Dequeue and return an output buffer, or null if no output is ready. Return
843 // a fake OutputBufferInfo with index -1 if the codec is no longer operable.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100844 @Nullable
Magnus Jedvert655e1962017-12-08 11:05:22 +0100845 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800846 OutputBufferInfo dequeueOutputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000847 checkOnMediaCodecThread();
848 try {
849 MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
850 int result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000851 // Check if this is config frame and save configuration data.
852 if (result >= 0) {
sakalb6760f92016-09-29 04:12:44 -0700853 boolean isConfigFrame = (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000854 if (isConfigFrame) {
sakalb6760f92016-09-29 04:12:44 -0700855 Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000856 configData = ByteBuffer.allocateDirect(info.size);
857 outputBuffers[result].position(info.offset);
858 outputBuffers[result].limit(info.offset + info.size);
859 configData.put(outputBuffers[result]);
glaznev3fc23502017-06-15 16:24:37 -0700860 // Log few SPS header bytes to check profile and level.
861 String spsData = "";
862 for (int i = 0; i < (info.size < 8 ? info.size : 8); i++) {
863 spsData += Integer.toHexString(configData.get(i) & 0xff) + " ";
864 }
865 Logging.d(TAG, spsData);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000866 // Release buffer back.
867 mediaCodec.releaseOutputBuffer(result, false);
868 // Query next output.
869 result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
870 }
871 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000872 if (result >= 0) {
873 // MediaCodec doesn't care about Buffer position/remaining/etc so we can
874 // mess with them to get a slice and avoid having to pass extra
875 // (BufferInfo-related) parameters back to C++.
876 ByteBuffer outputBuffer = outputBuffers[result].duplicate();
877 outputBuffer.position(info.offset);
878 outputBuffer.limit(info.offset + info.size);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700879 reportEncodedFrame(info.size);
880
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000881 // Check key frame flag.
sakalb6760f92016-09-29 04:12:44 -0700882 boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0;
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000883 if (isKeyFrame) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700884 Logging.d(TAG, "Sync frame generated");
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000885 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000886 if (isKeyFrame && type == VideoCodecType.VIDEO_CODEC_H264) {
sakalb6760f92016-09-29 04:12:44 -0700887 Logging.d(TAG, "Appending config frame of size " + configData.capacity()
888 + " to output buffer with offset " + info.offset + ", size " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000889 // For H.264 key frame append SPS and PPS NALs at the start
sakalb6760f92016-09-29 04:12:44 -0700890 ByteBuffer keyFrameBuffer = ByteBuffer.allocateDirect(configData.capacity() + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000891 configData.rewind();
892 keyFrameBuffer.put(configData);
893 keyFrameBuffer.put(outputBuffer);
894 keyFrameBuffer.position(0);
sakalb6760f92016-09-29 04:12:44 -0700895 return new OutputBufferInfo(result, keyFrameBuffer, isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000896 } else {
sakalb6760f92016-09-29 04:12:44 -0700897 return new OutputBufferInfo(
898 result, outputBuffer.slice(), isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000899 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000900 } else if (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
901 outputBuffers = mediaCodec.getOutputBuffers();
902 return dequeueOutputBuffer();
903 } else if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
904 return dequeueOutputBuffer();
905 } else if (result == MediaCodec.INFO_TRY_AGAIN_LATER) {
906 return null;
907 }
908 throw new RuntimeException("dequeueOutputBuffer: " + result);
909 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700910 Logging.e(TAG, "dequeueOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000911 return new OutputBufferInfo(-1, null, false, -1);
912 }
913 }
914
Alex Glaznevcfaca032016-09-06 14:08:19 -0700915 private double getBitrateScale(int bitrateAdjustmentScaleExp) {
916 return Math.pow(BITRATE_CORRECTION_MAX_SCALE,
sakalb6760f92016-09-29 04:12:44 -0700917 (double) bitrateAdjustmentScaleExp / BITRATE_CORRECTION_STEPS);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700918 }
919
920 private void reportEncodedFrame(int size) {
921 if (targetFps == 0 || bitrateAdjustmentType != BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
922 return;
923 }
924
925 // Accumulate the difference between actial and expected frame sizes.
926 double expectedBytesPerFrame = targetBitrateBps / (8.0 * targetFps);
927 bitrateAccumulator += (size - expectedBytesPerFrame);
928 bitrateObservationTimeMs += 1000.0 / targetFps;
929
930 // Put a cap on the accumulator, i.e., don't let it grow beyond some level to avoid
931 // using too old data for bitrate adjustment.
932 double bitrateAccumulatorCap = BITRATE_CORRECTION_SEC * bitrateAccumulatorMax;
933 bitrateAccumulator = Math.min(bitrateAccumulator, bitrateAccumulatorCap);
934 bitrateAccumulator = Math.max(bitrateAccumulator, -bitrateAccumulatorCap);
935
936 // Do bitrate adjustment every 3 seconds if actual encoder bitrate deviates too much
937 // form the target value.
938 if (bitrateObservationTimeMs > 1000 * BITRATE_CORRECTION_SEC) {
sakalb6760f92016-09-29 04:12:44 -0700939 Logging.d(TAG, "Acc: " + (int) bitrateAccumulator + ". Max: " + (int) bitrateAccumulatorMax
940 + ". ExpScale: " + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700941 boolean bitrateAdjustmentScaleChanged = false;
942 if (bitrateAccumulator > bitrateAccumulatorMax) {
943 // Encoder generates too high bitrate - need to reduce the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800944 int bitrateAdjustmentInc = (int) (bitrateAccumulator / bitrateAccumulatorMax + 0.5);
945 bitrateAdjustmentScaleExp -= bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700946 bitrateAccumulator = bitrateAccumulatorMax;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700947 bitrateAdjustmentScaleChanged = true;
948 } else if (bitrateAccumulator < -bitrateAccumulatorMax) {
949 // Encoder generates too low bitrate - need to increase the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800950 int bitrateAdjustmentInc = (int) (-bitrateAccumulator / bitrateAccumulatorMax + 0.5);
951 bitrateAdjustmentScaleExp += bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700952 bitrateAccumulator = -bitrateAccumulatorMax;
953 bitrateAdjustmentScaleChanged = true;
954 }
955 if (bitrateAdjustmentScaleChanged) {
956 bitrateAdjustmentScaleExp = Math.min(bitrateAdjustmentScaleExp, BITRATE_CORRECTION_STEPS);
957 bitrateAdjustmentScaleExp = Math.max(bitrateAdjustmentScaleExp, -BITRATE_CORRECTION_STEPS);
sakalb6760f92016-09-29 04:12:44 -0700958 Logging.d(TAG, "Adjusting bitrate scale to " + bitrateAdjustmentScaleExp + ". Value: "
959 + getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700960 setRates(targetBitrateBps / 1000, targetFps);
961 }
962 bitrateObservationTimeMs = 0;
963 }
964 }
965
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000966 // Release a dequeued output buffer back to the codec for re-use. Return
967 // false if the codec is no longer operable.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100968 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800969 boolean releaseOutputBuffer(int index) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000970 checkOnMediaCodecThread();
971 try {
972 mediaCodec.releaseOutputBuffer(index, false);
973 return true;
974 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700975 Logging.e(TAG, "releaseOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000976 return false;
977 }
978 }
sakalb5f5bdc2017-08-10 04:15:42 -0700979
Magnus Jedvert655e1962017-12-08 11:05:22 +0100980 @CalledByNative
981 int getColorFormat() {
982 return colorFormat;
983 }
984
985 @CalledByNative
986 static boolean isTextureBuffer(VideoFrame.Buffer buffer) {
987 return buffer instanceof VideoFrame.TextureBuffer;
988 }
989
sakalb5f5bdc2017-08-10 04:15:42 -0700990 /** Fills an inputBuffer with the given index with data from the byte buffers. */
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100991 private static native void nativeFillInputBuffer(long encoder, int inputBuffer, ByteBuffer dataY,
992 int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000993}