blob: db82be96b78178678781507b917b11ef16412449 [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;
Magnus Jedvert655e1962017-12-08 11:05:22 +010032import org.webrtc.EglBase14;
33import org.webrtc.VideoFrame;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000034
Magnus Jedvert9060eb12017-12-12 12:52:54 +010035// Java-side of peerconnection.cc:MediaCodecVideoEncoder.
fischman@webrtc.org540acde2014-02-13 03:56:14 +000036// This class is an implementation detail of the Java PeerConnection API.
Patrik Höglund68876f92015-11-12 17:36:48 +010037@TargetApi(19)
38@SuppressWarnings("deprecation")
Magnus Jedvert84d8ae52017-12-20 15:12:10 +010039@JNINamespace("webrtc::jni")
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 {
50 VIDEO_CODEC_VP8,
51 VIDEO_CODEC_VP9,
52 VIDEO_CODEC_H264;
53
54 @CalledByNative("VideoCodecType")
55 static VideoCodecType fromNativeIndex(int nativeIndex) {
56 return values()[nativeIndex];
57 }
58 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000059
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070060 private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; // Timeout for codec releasing.
sakalb6760f92016-09-29 04:12:44 -070061 private static final int DEQUEUE_TIMEOUT = 0; // Non-blocking, no wait.
Alex Glaznev269fe752016-05-25 16:17:33 -070062 private static final int BITRATE_ADJUSTMENT_FPS = 30;
Alex Glaznevc55c39d2016-09-02 12:16:27 -070063 private static final int MAXIMUM_INITIAL_FPS = 30;
Alex Glaznevcfaca032016-09-06 14:08:19 -070064 private static final double BITRATE_CORRECTION_SEC = 3.0;
Alex Glaznev7fa4a722017-01-17 15:32:02 -080065 // Maximum bitrate correction scale - no more than 4 times.
66 private static final double BITRATE_CORRECTION_MAX_SCALE = 4;
Alex Glaznevcfaca032016-09-06 14:08:19 -070067 // Amount of correction steps to reach correction maximum scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -080068 private static final int BITRATE_CORRECTION_STEPS = 20;
Alex Glaznevc7483a72017-01-05 15:22:24 -080069 // Forced key frame interval - used to reduce color distortions on Qualcomm platform.
alexlau84ee5c62017-06-02 17:36:32 -070070 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS = 15000;
71 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS = 20000;
Alex Glaznevc7483a72017-01-05 15:22:24 -080072 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS = 15000;
Alex Glaznevcfaca032016-09-06 14:08:19 -070073
perkj9576e542015-11-12 06:43:16 -080074 // Active running encoder instance. Set in initEncode() (called from native code)
Alex Glaznevc6aec4b2015-10-19 16:39:19 -070075 // and reset to null in release() call.
76 private static MediaCodecVideoEncoder runningInstance = null;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070077 private static MediaCodecVideoEncoderErrorCallback errorCallback = null;
78 private static int codecErrors = 0;
Alex Glazneveee86a62016-01-29 14:17:07 -080079 // List of disabled codec types - can be set from application.
80 private static Set<String> hwEncoderDisabledTypes = new HashSet<String>();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070081
Alejandro Luebs69ddaef2015-10-09 15:46:09 -070082 private Thread mediaCodecThread;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000083 private MediaCodec mediaCodec;
84 private ByteBuffer[] outputBuffers;
perkj48477c12015-12-18 00:34:37 -080085 private EglBase14 eglBase;
glaznev3fc23502017-06-15 16:24:37 -070086 private int profile;
Magnus Jedvert51254332015-12-15 16:22:29 +010087 private int width;
88 private int height;
perkj30e91822015-11-20 01:31:25 -080089 private Surface inputSurface;
90 private GlRectDrawer drawer;
Alex Glaznev269fe752016-05-25 16:17:33 -070091
fischman@webrtc.org540acde2014-02-13 03:56:14 +000092 private static final String VP8_MIME_TYPE = "video/x-vnd.on2.vp8";
Alex Glaznevad948c42015-11-18 13:06:42 -080093 private static final String VP9_MIME_TYPE = "video/x-vnd.on2.vp9";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000094 private static final String H264_MIME_TYPE = "video/avc";
Alex Glaznev269fe752016-05-25 16:17:33 -070095
glaznev3fc23502017-06-15 16:24:37 -070096 private static final int VIDEO_AVCProfileHigh = 8;
97 private static final int VIDEO_AVCLevel3 = 0x100;
98
Alex Glaznevcfaca032016-09-06 14:08:19 -070099 // Type of bitrate adjustment for video encoder.
100 public enum BitrateAdjustmentType {
101 // No adjustment - video encoder has no known bitrate problem.
102 NO_ADJUSTMENT,
103 // Framerate based bitrate adjustment is required - HW encoder does not use frame
104 // timestamps to calculate frame bitrate budget and instead is relying on initial
105 // fps configuration assuming that all frames are coming at fixed initial frame rate.
106 FRAMERATE_ADJUSTMENT,
107 // Dynamic bitrate adjustment is required - HW encoder used frame timestamps, but actual
108 // bitrate deviates too much from the target value.
109 DYNAMIC_ADJUSTMENT
110 }
111
glaznev3fc23502017-06-15 16:24:37 -0700112 // Should be in sync with webrtc::H264::Profile.
113 public static enum H264Profile {
114 CONSTRAINED_BASELINE(0),
115 BASELINE(1),
116 MAIN(2),
117 CONSTRAINED_HIGH(3),
118 HIGH(4);
119
120 private final int value;
121
122 H264Profile(int value) {
123 this.value = value;
124 }
125
126 public int getValue() {
127 return value;
128 }
129 }
130
Alex Glaznev269fe752016-05-25 16:17:33 -0700131 // Class describing supported media codec properties.
132 private static class MediaCodecProperties {
133 public final String codecPrefix;
134 // Minimum Android SDK required for this codec to be used.
135 public final int minSdk;
136 // Flag if encoder implementation does not use frame timestamps to calculate frame bitrate
137 // budget and instead is relying on initial fps configuration assuming that all frames are
138 // coming at fixed initial frame rate. Bitrate adjustment is required for this case.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700139 public final BitrateAdjustmentType bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700140
141 MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700142 String codecPrefix, int minSdk, BitrateAdjustmentType bitrateAdjustmentType) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700143 this.codecPrefix = codecPrefix;
144 this.minSdk = minSdk;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700145 this.bitrateAdjustmentType = bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700146 }
147 }
148
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700149 // List of supported HW VP8 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700150 private static final MediaCodecProperties qcomVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700151 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700152 private static final MediaCodecProperties exynosVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700153 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.DYNAMIC_ADJUSTMENT);
magjed295760d2017-01-12 01:11:57 -0800154 private static final MediaCodecProperties intelVp8HwProperties = new MediaCodecProperties(
155 "OMX.Intel.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.NO_ADJUSTMENT);
156 private static MediaCodecProperties[] vp8HwList() {
157 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
158 supported_codecs.add(qcomVp8HwProperties);
159 supported_codecs.add(exynosVp8HwProperties);
160 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-IntelVP8").equals("Enabled")) {
161 supported_codecs.add(intelVp8HwProperties);
162 }
163 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
164 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700165
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700166 // List of supported HW VP9 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700167 private static final MediaCodecProperties qcomVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700168 "OMX.qcom.", Build.VERSION_CODES.N, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700169 private static final MediaCodecProperties exynosVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700170 "OMX.Exynos.", Build.VERSION_CODES.N, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
sakalb6760f92016-09-29 04:12:44 -0700171 private static final MediaCodecProperties[] vp9HwList =
172 new MediaCodecProperties[] {qcomVp9HwProperties, exynosVp9HwProperties};
Alex Glaznev269fe752016-05-25 16:17:33 -0700173
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700174 // List of supported HW H.264 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700175 private static final MediaCodecProperties qcomH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700176 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700177 private static final MediaCodecProperties exynosH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700178 "OMX.Exynos.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
sakalb6760f92016-09-29 04:12:44 -0700179 private static final MediaCodecProperties[] h264HwList =
180 new MediaCodecProperties[] {qcomH264HwProperties, exynosH264HwProperties};
Alex Glaznev269fe752016-05-25 16:17:33 -0700181
glaznev3fc23502017-06-15 16:24:37 -0700182 // List of supported HW H.264 high profile encoders.
183 private static final MediaCodecProperties exynosH264HighProfileHwProperties =
184 new MediaCodecProperties(
185 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
186 private static final MediaCodecProperties[] h264HighProfileHwList =
187 new MediaCodecProperties[] {exynosH264HighProfileHwProperties};
188
Alex Glaznev0c850202015-08-04 10:26:59 -0700189 // List of devices with poor H.264 encoder quality.
sakalb6760f92016-09-29 04:12:44 -0700190 // HW H.264 encoder on below devices has poor bitrate control - actual
191 // bitrates deviates a lot from the target value.
192 private static final String[] H264_HW_EXCEPTION_MODELS =
193 new String[] {"SAMSUNG-SGH-I337", "Nexus 7", "Nexus 4"};
Alex Glaznev0c850202015-08-04 10:26:59 -0700194
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000195 // Bitrate modes - should be in sync with OMX_VIDEO_CONTROLRATETYPE defined
196 // in OMX_Video.h
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000197 private static final int VIDEO_ControlRateConstant = 2;
198 // NV12 color format supported by QCOM codec, but not declared in MediaCodec -
199 // see /hardware/qcom/media/mm-core/inc/OMX_QCOMExtns.h
sakalb6760f92016-09-29 04:12:44 -0700200 private static final int COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m = 0x7FA30C04;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000201 // Allowable color formats supported by codec - in order of preference.
sakalb6760f92016-09-29 04:12:44 -0700202 private static final int[] supportedColorList = {CodecCapabilities.COLOR_FormatYUV420Planar,
203 CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
204 CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
205 COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m};
206 private static final int[] supportedSurfaceColorList = {CodecCapabilities.COLOR_FormatSurface};
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000207 private VideoCodecType type;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100208 private int colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700209
210 // Variables used for dynamic bitrate adjustment.
211 private BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
212 private double bitrateAccumulator;
213 private double bitrateAccumulatorMax;
214 private double bitrateObservationTimeMs;
215 private int bitrateAdjustmentScaleExp;
216 private int targetBitrateBps;
217 private int targetFps;
perkj9576e542015-11-12 06:43:16 -0800218
Alex Glaznevc7483a72017-01-05 15:22:24 -0800219 // Interval in ms to force key frame generation. Used to reduce the time of color distortions
220 // happened sometime when using Qualcomm video encoder.
221 private long forcedKeyFrameMs;
222 private long lastKeyFrameMs;
223
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000224 // SPS and PPS NALs (Config frame) for H.264.
225 private ByteBuffer configData = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000226
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700227 // MediaCodec error handler - invoked when critical error happens which may prevent
228 // further use of media codec API. Now it means that one of media codec instances
229 // is hanging and can no longer be used in the next call.
230 public static interface MediaCodecVideoEncoderErrorCallback {
231 void onMediaCodecVideoEncoderCriticalError(int codecErrors);
232 }
233
234 public static void setErrorCallback(MediaCodecVideoEncoderErrorCallback errorCallback) {
235 Logging.d(TAG, "Set error callback");
236 MediaCodecVideoEncoder.errorCallback = errorCallback;
237 }
238
Alex Glazneveee86a62016-01-29 14:17:07 -0800239 // Functions to disable HW encoding - can be called from applications for platforms
240 // which have known HW decoding problems.
241 public static void disableVp8HwCodec() {
242 Logging.w(TAG, "VP8 encoding is disabled by application.");
243 hwEncoderDisabledTypes.add(VP8_MIME_TYPE);
244 }
245
246 public static void disableVp9HwCodec() {
247 Logging.w(TAG, "VP9 encoding is disabled by application.");
248 hwEncoderDisabledTypes.add(VP9_MIME_TYPE);
249 }
250
251 public static void disableH264HwCodec() {
252 Logging.w(TAG, "H.264 encoding is disabled by application.");
253 hwEncoderDisabledTypes.add(H264_MIME_TYPE);
254 }
255
256 // Functions to query if HW encoding is supported.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100257 @CalledByNative
Alex Glazneveee86a62016-01-29 14:17:07 -0800258 public static boolean isVp8HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700259 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800260 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800261 }
262
Alex Glaznevc7483a72017-01-05 15:22:24 -0800263 public static EncoderProperties vp8HwEncoderProperties() {
264 if (hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)) {
265 return null;
266 } else {
magjed295760d2017-01-12 01:11:57 -0800267 return findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList);
Alex Glaznevc7483a72017-01-05 15:22:24 -0800268 }
269 }
270
Magnus Jedvert655e1962017-12-08 11:05:22 +0100271 @CalledByNative
Alex Glazneveee86a62016-01-29 14:17:07 -0800272 public static boolean isVp9HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700273 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
274 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800275 }
276
Magnus Jedvert655e1962017-12-08 11:05:22 +0100277 @CalledByNative
Alex Glazneveee86a62016-01-29 14:17:07 -0800278 public static boolean isH264HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700279 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
280 && (findHwEncoder(H264_MIME_TYPE, h264HwList, supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800281 }
282
glaznev3fc23502017-06-15 16:24:37 -0700283 public static boolean isH264HighProfileHwSupported() {
284 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
285 && (findHwEncoder(H264_MIME_TYPE, h264HighProfileHwList, supportedColorList) != null);
286 }
287
Alex Glazneveee86a62016-01-29 14:17:07 -0800288 public static boolean isVp8HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700289 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800290 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800291 }
292
293 public static boolean isVp9HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700294 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
295 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800296 }
297
298 public static boolean isH264HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700299 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
300 && (findHwEncoder(H264_MIME_TYPE, h264HwList, supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800301 }
302
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000303 // Helper struct for findHwEncoder() below.
Alex Glaznevc7483a72017-01-05 15:22:24 -0800304 public static class EncoderProperties {
Alex Glaznevcfaca032016-09-06 14:08:19 -0700305 public EncoderProperties(
306 String codecName, int colorFormat, BitrateAdjustmentType bitrateAdjustmentType) {
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000307 this.codecName = codecName;
308 this.colorFormat = colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700309 this.bitrateAdjustmentType = bitrateAdjustmentType;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000310 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000311 public final String codecName; // OpenMax component name for HW codec.
sakalb6760f92016-09-29 04:12:44 -0700312 public final int colorFormat; // Color format supported by codec.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700313 public final BitrateAdjustmentType bitrateAdjustmentType; // Bitrate adjustment type
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000314 }
315
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000316 private static EncoderProperties findHwEncoder(
Alex Glaznev269fe752016-05-25 16:17:33 -0700317 String mime, MediaCodecProperties[] supportedHwCodecProperties, int[] colorList) {
Alex Glaznev0c850202015-08-04 10:26:59 -0700318 // MediaCodec.setParameters is missing for JB and below, so bitrate
319 // can not be adjusted dynamically.
320 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
321 return null;
322 }
323
324 // Check if device is in H.264 exception list.
325 if (mime.equals(H264_MIME_TYPE)) {
326 List<String> exceptionModels = Arrays.asList(H264_HW_EXCEPTION_MODELS);
327 if (exceptionModels.contains(Build.MODEL)) {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700328 Logging.w(TAG, "Model: " + Build.MODEL + " has black listed H.264 encoder.");
Alex Glaznev0c850202015-08-04 10:26:59 -0700329 return null;
330 }
331 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000332
333 for (int i = 0; i < MediaCodecList.getCodecCount(); ++i) {
Alex Glaznev0060c562016-08-08 12:27:24 -0700334 MediaCodecInfo info = null;
335 try {
336 info = MediaCodecList.getCodecInfoAt(i);
337 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700338 Logging.e(TAG, "Cannot retrieve encoder codec info", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700339 }
340 if (info == null || !info.isEncoder()) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000341 continue;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000342 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000343 String name = null;
344 for (String mimeType : info.getSupportedTypes()) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000345 if (mimeType.equals(mime)) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000346 name = info.getName();
347 break;
348 }
349 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000350 if (name == null) {
sakalb6760f92016-09-29 04:12:44 -0700351 continue; // No HW support in this codec; try the next one.
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000352 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700353 Logging.v(TAG, "Found candidate encoder " + name);
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000354
355 // Check if this is supported HW encoder.
356 boolean supportedCodec = false;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700357 BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
Alex Glaznev269fe752016-05-25 16:17:33 -0700358 for (MediaCodecProperties codecProperties : supportedHwCodecProperties) {
359 if (name.startsWith(codecProperties.codecPrefix)) {
360 if (Build.VERSION.SDK_INT < codecProperties.minSdk) {
sakalb6760f92016-09-29 04:12:44 -0700361 Logging.w(
362 TAG, "Codec " + name + " is disabled due to SDK version " + Build.VERSION.SDK_INT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700363 continue;
364 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700365 if (codecProperties.bitrateAdjustmentType != BitrateAdjustmentType.NO_ADJUSTMENT) {
366 bitrateAdjustmentType = codecProperties.bitrateAdjustmentType;
sakalb6760f92016-09-29 04:12:44 -0700367 Logging.w(
368 TAG, "Codec " + name + " requires bitrate adjustment: " + bitrateAdjustmentType);
Alex Glaznev269fe752016-05-25 16:17:33 -0700369 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000370 supportedCodec = true;
371 break;
372 }
373 }
374 if (!supportedCodec) {
375 continue;
376 }
377
Alex Glaznev269fe752016-05-25 16:17:33 -0700378 // Check if HW codec supports known color format.
Alex Glaznev0060c562016-08-08 12:27:24 -0700379 CodecCapabilities capabilities;
380 try {
381 capabilities = info.getCapabilitiesForType(mime);
382 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700383 Logging.e(TAG, "Cannot retrieve encoder capabilities", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700384 continue;
385 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000386 for (int colorFormat : capabilities.colorFormats) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700387 Logging.v(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000388 }
389
perkj30e91822015-11-20 01:31:25 -0800390 for (int supportedColorFormat : colorList) {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000391 for (int codecColorFormat : capabilities.colorFormats) {
392 if (codecColorFormat == supportedColorFormat) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000393 // Found supported HW encoder.
sakalb6760f92016-09-29 04:12:44 -0700394 Logging.d(TAG, "Found target encoder for mime " + mime + " : " + name + ". Color: 0x"
395 + Integer.toHexString(codecColorFormat) + ". Bitrate adjustment: "
396 + bitrateAdjustmentType);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700397 return new EncoderProperties(name, codecColorFormat, bitrateAdjustmentType);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000398 }
399 }
400 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000401 }
sakalb6760f92016-09-29 04:12:44 -0700402 return null; // No HW encoder.
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000403 }
404
Magnus Jedvert655e1962017-12-08 11:05:22 +0100405 @CalledByNative
406 MediaCodecVideoEncoder() {}
407
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000408 private void checkOnMediaCodecThread() {
409 if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
sakalb6760f92016-09-29 04:12:44 -0700410 throw new RuntimeException("MediaCodecVideoEncoder previously operated on " + mediaCodecThread
411 + " but is now called on " + Thread.currentThread());
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000412 }
413 }
414
Alex Glaznev325d4142015-10-12 14:56:02 -0700415 public static void printStackTrace() {
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700416 if (runningInstance != null && runningInstance.mediaCodecThread != null) {
417 StackTraceElement[] mediaCodecStackTraces = runningInstance.mediaCodecThread.getStackTrace();
Alex Glaznev325d4142015-10-12 14:56:02 -0700418 if (mediaCodecStackTraces.length > 0) {
419 Logging.d(TAG, "MediaCodecVideoEncoder stacks trace:");
420 for (StackTraceElement stackTrace : mediaCodecStackTraces) {
421 Logging.d(TAG, stackTrace.toString());
422 }
423 }
424 }
425 }
426
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000427 static MediaCodec createByCodecName(String codecName) {
428 try {
429 // In the L-SDK this call can throw IOException so in order to work in
430 // both cases catch an exception.
431 return MediaCodec.createByCodecName(codecName);
432 } catch (Exception e) {
433 return null;
434 }
435 }
436
Magnus Jedvert655e1962017-12-08 11:05:22 +0100437 @CalledByNativeUnchecked
glaznev3fc23502017-06-15 16:24:37 -0700438 boolean initEncode(VideoCodecType type, int profile, int width, int height, int kbps, int fps,
perkj48477c12015-12-18 00:34:37 -0800439 EglBase14.Context sharedContext) {
perkj30e91822015-11-20 01:31:25 -0800440 final boolean useSurface = sharedContext != null;
glaznev3fc23502017-06-15 16:24:37 -0700441 Logging.d(TAG,
442 "Java initEncode: " + type + ". Profile: " + profile + " : " + width + " x " + height
443 + ". @ " + kbps + " kbps. Fps: " + fps + ". Encode from texture : " + useSurface);
perkj9576e542015-11-12 06:43:16 -0800444
glaznev3fc23502017-06-15 16:24:37 -0700445 this.profile = profile;
Magnus Jedvert51254332015-12-15 16:22:29 +0100446 this.width = width;
447 this.height = height;
Alejandro Luebs69ddaef2015-10-09 15:46:09 -0700448 if (mediaCodecThread != null) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000449 throw new RuntimeException("Forgot to release()?");
450 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000451 EncoderProperties properties = null;
452 String mime = null;
453 int keyFrameIntervalSec = 0;
glaznev3fc23502017-06-15 16:24:37 -0700454 boolean configureH264HighProfile = false;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000455 if (type == VideoCodecType.VIDEO_CODEC_VP8) {
456 mime = VP8_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700457 properties = findHwEncoder(
magjed295760d2017-01-12 01:11:57 -0800458 VP8_MIME_TYPE, vp8HwList(), useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000459 keyFrameIntervalSec = 100;
Alex Glaznevad948c42015-11-18 13:06:42 -0800460 } else if (type == VideoCodecType.VIDEO_CODEC_VP9) {
461 mime = VP9_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700462 properties = findHwEncoder(
463 VP9_MIME_TYPE, vp9HwList, useSurface ? supportedSurfaceColorList : supportedColorList);
Alex Glaznevad948c42015-11-18 13:06:42 -0800464 keyFrameIntervalSec = 100;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000465 } else if (type == VideoCodecType.VIDEO_CODEC_H264) {
466 mime = H264_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700467 properties = findHwEncoder(
468 H264_MIME_TYPE, h264HwList, useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev3fc23502017-06-15 16:24:37 -0700469 if (profile == H264Profile.CONSTRAINED_HIGH.getValue()) {
470 EncoderProperties h264HighProfileProperties = findHwEncoder(H264_MIME_TYPE,
471 h264HighProfileHwList, useSurface ? supportedSurfaceColorList : supportedColorList);
472 if (h264HighProfileProperties != null) {
473 Logging.d(TAG, "High profile H.264 encoder supported.");
474 configureH264HighProfile = true;
475 } else {
476 Logging.d(TAG, "High profile H.264 encoder requested, but not supported. Use baseline.");
477 }
478 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000479 keyFrameIntervalSec = 20;
480 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000481 if (properties == null) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000482 throw new RuntimeException("Can not find HW encoder for " + type);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000483 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700484 runningInstance = this; // Encoder is now running and can be queried for stack traces.
perkj9576e542015-11-12 06:43:16 -0800485 colorFormat = properties.colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700486 bitrateAdjustmentType = properties.bitrateAdjustmentType;
487 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700488 fps = BITRATE_ADJUSTMENT_FPS;
sakalb6760f92016-09-29 04:12:44 -0700489 } else {
Alex Glaznevc55c39d2016-09-02 12:16:27 -0700490 fps = Math.min(fps, MAXIMUM_INITIAL_FPS);
Alex Glaznev269fe752016-05-25 16:17:33 -0700491 }
Alex Glaznevc7483a72017-01-05 15:22:24 -0800492
493 forcedKeyFrameMs = 0;
494 lastKeyFrameMs = -1;
Alex Glaznev512f00b2017-01-05 16:40:46 -0800495 if (type == VideoCodecType.VIDEO_CODEC_VP8
496 && properties.codecName.startsWith(qcomVp8HwProperties.codecPrefix)) {
alexlau84ee5c62017-06-02 17:36:32 -0700497 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP
498 || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
499 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS;
500 } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800501 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS;
502 } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
503 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS;
504 }
505 }
506
sakalb6760f92016-09-29 04:12:44 -0700507 Logging.d(TAG, "Color format: " + colorFormat + ". Bitrate adjustment: " + bitrateAdjustmentType
Alex Glaznevc7483a72017-01-05 15:22:24 -0800508 + ". Key frame interval: " + forcedKeyFrameMs + " . Initial fps: " + fps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700509 targetBitrateBps = 1000 * kbps;
510 targetFps = fps;
511 bitrateAccumulatorMax = targetBitrateBps / 8.0;
512 bitrateAccumulator = 0;
513 bitrateObservationTimeMs = 0;
514 bitrateAdjustmentScaleExp = 0;
perkj9576e542015-11-12 06:43:16 -0800515
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000516 mediaCodecThread = Thread.currentThread();
517 try {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000518 MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700519 format.setInteger(MediaFormat.KEY_BIT_RATE, targetBitrateBps);
Alex Glaznev8a2cd3d2015-08-11 11:32:53 -0700520 format.setInteger("bitrate-mode", VIDEO_ControlRateConstant);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000521 format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700522 format.setInteger(MediaFormat.KEY_FRAME_RATE, targetFps);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000523 format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameIntervalSec);
glaznev3fc23502017-06-15 16:24:37 -0700524 if (configureH264HighProfile) {
525 format.setInteger("profile", VIDEO_AVCProfileHigh);
526 format.setInteger("level", VIDEO_AVCLevel3);
527 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700528 Logging.d(TAG, " Format: " + format);
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000529 mediaCodec = createByCodecName(properties.codecName);
perkj9576e542015-11-12 06:43:16 -0800530 this.type = type;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000531 if (mediaCodec == null) {
Alex Glaznev325d4142015-10-12 14:56:02 -0700532 Logging.e(TAG, "Can not create media encoder");
sakal996a83c2017-03-15 05:53:14 -0700533 release();
perkj9576e542015-11-12 06:43:16 -0800534 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000535 }
sakalb6760f92016-09-29 04:12:44 -0700536 mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
perkj9576e542015-11-12 06:43:16 -0800537
perkj30e91822015-11-20 01:31:25 -0800538 if (useSurface) {
perkj48477c12015-12-18 00:34:37 -0800539 eglBase = new EglBase14(sharedContext, EglBase.CONFIG_RECORDABLE);
perkj30e91822015-11-20 01:31:25 -0800540 // Create an input surface and keep a reference since we must release the surface when done.
541 inputSurface = mediaCodec.createInputSurface();
542 eglBase.createSurface(inputSurface);
543 drawer = new GlRectDrawer();
544 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000545 mediaCodec.start();
546 outputBuffers = mediaCodec.getOutputBuffers();
perkj9576e542015-11-12 06:43:16 -0800547 Logging.d(TAG, "Output buffers: " + outputBuffers.length);
548
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000549 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700550 Logging.e(TAG, "initEncode failed", e);
sakal996a83c2017-03-15 05:53:14 -0700551 release();
perkj9576e542015-11-12 06:43:16 -0800552 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000553 }
perkj9576e542015-11-12 06:43:16 -0800554 return true;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000555 }
556
Magnus Jedvert655e1962017-12-08 11:05:22 +0100557 @CalledByNativeUnchecked
sakalb6760f92016-09-29 04:12:44 -0700558 ByteBuffer[] getInputBuffers() {
perkj9576e542015-11-12 06:43:16 -0800559 ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
560 Logging.d(TAG, "Input buffers: " + inputBuffers.length);
561 return inputBuffers;
562 }
563
Alex Glaznevc7483a72017-01-05 15:22:24 -0800564 void checkKeyFrameRequired(boolean requestedKeyFrame, long presentationTimestampUs) {
565 long presentationTimestampMs = (presentationTimestampUs + 500) / 1000;
566 if (lastKeyFrameMs < 0) {
567 lastKeyFrameMs = presentationTimestampMs;
568 }
569 boolean forcedKeyFrame = false;
570 if (!requestedKeyFrame && forcedKeyFrameMs > 0
571 && presentationTimestampMs > lastKeyFrameMs + forcedKeyFrameMs) {
572 forcedKeyFrame = true;
573 }
574 if (requestedKeyFrame || forcedKeyFrame) {
575 // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could
576 // indicate this in queueInputBuffer() below and guarantee _this_ frame
577 // be encoded as a key frame, but sadly that flag is ignored. Instead,
578 // we request a key frame "soon".
579 if (requestedKeyFrame) {
580 Logging.d(TAG, "Sync frame request");
581 } else {
582 Logging.d(TAG, "Sync frame forced");
583 }
584 Bundle b = new Bundle();
585 b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0);
586 mediaCodec.setParameters(b);
587 lastKeyFrameMs = presentationTimestampMs;
588 }
589 }
590
Magnus Jedvert655e1962017-12-08 11:05:22 +0100591 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800592 boolean encodeBuffer(
sakalb6760f92016-09-29 04:12:44 -0700593 boolean isKeyframe, int inputBuffer, int size, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000594 checkOnMediaCodecThread();
595 try {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800596 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
sakalb6760f92016-09-29 04:12:44 -0700597 mediaCodec.queueInputBuffer(inputBuffer, 0, size, presentationTimestampUs, 0);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000598 return true;
sakalb6760f92016-09-29 04:12:44 -0700599 } catch (IllegalStateException e) {
perkj9576e542015-11-12 06:43:16 -0800600 Logging.e(TAG, "encodeBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000601 return false;
602 }
603 }
604
Magnus Jedvert655e1962017-12-08 11:05:22 +0100605 @CalledByNativeUnchecked
perkj30e91822015-11-20 01:31:25 -0800606 boolean encodeTexture(boolean isKeyframe, int oesTextureId, float[] transformationMatrix,
607 long presentationTimestampUs) {
608 checkOnMediaCodecThread();
609 try {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800610 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
perkj30e91822015-11-20 01:31:25 -0800611 eglBase.makeCurrent();
perkj226a6022015-12-02 02:24:40 -0800612 // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway,
613 // but it's a workaround for bug webrtc:5147.
614 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
ivoc1aa435c2016-05-04 07:14:14 -0700615 drawer.drawOes(oesTextureId, transformationMatrix, width, height, 0, 0, width, height);
perkj48477c12015-12-18 00:34:37 -0800616 eglBase.swapBuffers(TimeUnit.MICROSECONDS.toNanos(presentationTimestampUs));
perkj30e91822015-11-20 01:31:25 -0800617 return true;
sakalb6760f92016-09-29 04:12:44 -0700618 } catch (RuntimeException e) {
perkj30e91822015-11-20 01:31:25 -0800619 Logging.e(TAG, "encodeTexture failed", e);
620 return false;
621 }
622 }
623
sakalb5f5bdc2017-08-10 04:15:42 -0700624 /**
Magnus Jedvert655e1962017-12-08 11:05:22 +0100625 * Encodes a new style VideoFrame. |bufferIndex| is -1 if we are not encoding in surface mode.
sakalb5f5bdc2017-08-10 04:15:42 -0700626 */
Magnus Jedvert655e1962017-12-08 11:05:22 +0100627 @CalledByNativeUnchecked
sakalb5f5bdc2017-08-10 04:15:42 -0700628 boolean encodeFrame(long nativeEncoder, boolean isKeyframe, VideoFrame frame, int bufferIndex) {
629 checkOnMediaCodecThread();
630 try {
631 long presentationTimestampUs = TimeUnit.NANOSECONDS.toMicros(frame.getTimestampNs());
632 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
633
634 VideoFrame.Buffer buffer = frame.getBuffer();
635 if (buffer instanceof VideoFrame.TextureBuffer) {
636 VideoFrame.TextureBuffer textureBuffer = (VideoFrame.TextureBuffer) buffer;
637 eglBase.makeCurrent();
638 // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway,
639 // but it's a workaround for bug webrtc:5147.
640 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700641 VideoFrameDrawer.drawTexture(drawer, textureBuffer, new Matrix() /* renderMatrix */, width,
sakal9bc599f2017-09-08 04:46:33 -0700642 height, 0 /* viewportX */, 0 /* viewportY */, width, height);
sakalb5f5bdc2017-08-10 04:15:42 -0700643 eglBase.swapBuffers(frame.getTimestampNs());
644 } else {
645 VideoFrame.I420Buffer i420Buffer = buffer.toI420();
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200646 final int chromaHeight = (height + 1) / 2;
647 final ByteBuffer dataY = i420Buffer.getDataY();
648 final ByteBuffer dataU = i420Buffer.getDataU();
649 final ByteBuffer dataV = i420Buffer.getDataV();
650 final int strideY = i420Buffer.getStrideY();
651 final int strideU = i420Buffer.getStrideU();
652 final int strideV = i420Buffer.getStrideV();
653 if (dataY.capacity() < strideY * height) {
654 throw new RuntimeException("Y-plane buffer size too small.");
655 }
656 if (dataU.capacity() < strideU * chromaHeight) {
657 throw new RuntimeException("U-plane buffer size too small.");
658 }
659 if (dataV.capacity() < strideV * chromaHeight) {
660 throw new RuntimeException("V-plane buffer size too small.");
661 }
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100662 nativeFillInputBuffer(
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200663 nativeEncoder, bufferIndex, dataY, strideY, dataU, strideU, dataV, strideV);
sakalb5f5bdc2017-08-10 04:15:42 -0700664 i420Buffer.release();
665 // I420 consists of one full-resolution and two half-resolution planes.
666 // 1 + 1 / 4 + 1 / 4 = 3 / 2
667 int yuvSize = width * height * 3 / 2;
668 mediaCodec.queueInputBuffer(bufferIndex, 0, yuvSize, presentationTimestampUs, 0);
669 }
670 return true;
671 } catch (RuntimeException e) {
672 Logging.e(TAG, "encodeFrame failed", e);
673 return false;
674 }
675 }
676
Magnus Jedvert655e1962017-12-08 11:05:22 +0100677 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800678 void release() {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700679 Logging.d(TAG, "Java releaseEncoder");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000680 checkOnMediaCodecThread();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700681
sakal996a83c2017-03-15 05:53:14 -0700682 class CaughtException {
683 Exception e;
684 }
685 final CaughtException caughtException = new CaughtException();
686 boolean stopHung = false;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700687
sakal996a83c2017-03-15 05:53:14 -0700688 if (mediaCodec != null) {
689 // Run Mediacodec stop() and release() on separate thread since sometime
690 // Mediacodec.stop() may hang.
691 final CountDownLatch releaseDone = new CountDownLatch(1);
692
693 Runnable runMediaCodecRelease = new Runnable() {
694 @Override
695 public void run() {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700696 Logging.d(TAG, "Java releaseEncoder on release thread");
sakal996a83c2017-03-15 05:53:14 -0700697 try {
698 mediaCodec.stop();
699 } catch (Exception e) {
700 Logging.e(TAG, "Media encoder stop failed", e);
701 }
702 try {
703 mediaCodec.release();
704 } catch (Exception e) {
705 Logging.e(TAG, "Media encoder release failed", e);
706 caughtException.e = e;
707 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700708 Logging.d(TAG, "Java releaseEncoder on release thread done");
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700709
sakal996a83c2017-03-15 05:53:14 -0700710 releaseDone.countDown();
711 }
712 };
713 new Thread(runMediaCodecRelease).start();
714
715 if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) {
716 Logging.e(TAG, "Media encoder release timeout");
717 stopHung = true;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700718 }
sakal996a83c2017-03-15 05:53:14 -0700719
720 mediaCodec = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000721 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700722
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000723 mediaCodecThread = null;
perkj30e91822015-11-20 01:31:25 -0800724 if (drawer != null) {
725 drawer.release();
726 drawer = null;
727 }
728 if (eglBase != null) {
729 eglBase.release();
730 eglBase = null;
731 }
732 if (inputSurface != null) {
733 inputSurface.release();
734 inputSurface = null;
735 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700736 runningInstance = null;
sakal996a83c2017-03-15 05:53:14 -0700737
738 if (stopHung) {
739 codecErrors++;
740 if (errorCallback != null) {
741 Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors);
742 errorCallback.onMediaCodecVideoEncoderCriticalError(codecErrors);
743 }
744 throw new RuntimeException("Media encoder release timeout.");
745 }
746
747 // Re-throw any runtime exception caught inside the other thread. Since this is an invoke, add
748 // stack trace for the waiting thread as well.
749 if (caughtException.e != null) {
750 final RuntimeException runtimeException = new RuntimeException(caughtException.e);
751 runtimeException.setStackTrace(ThreadUtils.concatStackTraces(
752 caughtException.e.getStackTrace(), runtimeException.getStackTrace()));
753 throw runtimeException;
754 }
755
Alex Glaznev325d4142015-10-12 14:56:02 -0700756 Logging.d(TAG, "Java releaseEncoder done");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000757 }
758
Magnus Jedvert655e1962017-12-08 11:05:22 +0100759 @CalledByNativeUnchecked
Alex Glaznev269fe752016-05-25 16:17:33 -0700760 private boolean setRates(int kbps, int frameRate) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000761 checkOnMediaCodecThread();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700762
763 int codecBitrateBps = 1000 * kbps;
764 if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
765 bitrateAccumulatorMax = codecBitrateBps / 8.0;
766 if (targetBitrateBps > 0 && codecBitrateBps < targetBitrateBps) {
767 // Rescale the accumulator level if the accumulator max decreases
768 bitrateAccumulator = bitrateAccumulator * codecBitrateBps / targetBitrateBps;
769 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700770 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700771 targetBitrateBps = codecBitrateBps;
772 targetFps = frameRate;
773
774 // Adjust actual encoder bitrate based on bitrate adjustment type.
775 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT && targetFps > 0) {
776 codecBitrateBps = BITRATE_ADJUSTMENT_FPS * targetBitrateBps / targetFps;
sakalb6760f92016-09-29 04:12:44 -0700777 Logging.v(TAG,
778 "setRates: " + kbps + " -> " + (codecBitrateBps / 1000) + " kbps. Fps: " + targetFps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700779 } else if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
sakalb6760f92016-09-29 04:12:44 -0700780 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps + ". ExpScale: "
781 + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700782 if (bitrateAdjustmentScaleExp != 0) {
sakalb6760f92016-09-29 04:12:44 -0700783 codecBitrateBps = (int) (codecBitrateBps * getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700784 }
785 } else {
786 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps);
787 }
788
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000789 try {
790 Bundle params = new Bundle();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700791 params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, codecBitrateBps);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000792 mediaCodec.setParameters(params);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000793 return true;
794 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700795 Logging.e(TAG, "setRates failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000796 return false;
797 }
798 }
799
800 // Dequeue an input buffer and return its index, -1 if no input buffer is
801 // available, or -2 if the codec is no longer operative.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100802 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800803 int dequeueInputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000804 checkOnMediaCodecThread();
805 try {
806 return mediaCodec.dequeueInputBuffer(DEQUEUE_TIMEOUT);
807 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700808 Logging.e(TAG, "dequeueIntputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000809 return -2;
810 }
811 }
812
813 // Helper struct for dequeueOutputBuffer() below.
perkj9576e542015-11-12 06:43:16 -0800814 static class OutputBufferInfo {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000815 public OutputBufferInfo(
sakalb6760f92016-09-29 04:12:44 -0700816 int index, ByteBuffer buffer, boolean isKeyFrame, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000817 this.index = index;
818 this.buffer = buffer;
819 this.isKeyFrame = isKeyFrame;
820 this.presentationTimestampUs = presentationTimestampUs;
821 }
822
perkj9576e542015-11-12 06:43:16 -0800823 public final int index;
824 public final ByteBuffer buffer;
825 public final boolean isKeyFrame;
826 public final long presentationTimestampUs;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100827
828 @CalledByNative("OutputBufferInfo")
829 int getIndex() {
830 return index;
831 }
832
833 @CalledByNative("OutputBufferInfo")
834 ByteBuffer getBuffer() {
835 return buffer;
836 }
837
838 @CalledByNative("OutputBufferInfo")
839 boolean isKeyFrame() {
840 return isKeyFrame;
841 }
842
843 @CalledByNative("OutputBufferInfo")
844 long getPresentationTimestampUs() {
845 return presentationTimestampUs;
846 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000847 }
848
849 // Dequeue and return an output buffer, or null if no output is ready. Return
850 // a fake OutputBufferInfo with index -1 if the codec is no longer operable.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100851 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800852 OutputBufferInfo dequeueOutputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000853 checkOnMediaCodecThread();
854 try {
855 MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
856 int result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000857 // Check if this is config frame and save configuration data.
858 if (result >= 0) {
sakalb6760f92016-09-29 04:12:44 -0700859 boolean isConfigFrame = (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000860 if (isConfigFrame) {
sakalb6760f92016-09-29 04:12:44 -0700861 Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000862 configData = ByteBuffer.allocateDirect(info.size);
863 outputBuffers[result].position(info.offset);
864 outputBuffers[result].limit(info.offset + info.size);
865 configData.put(outputBuffers[result]);
glaznev3fc23502017-06-15 16:24:37 -0700866 // Log few SPS header bytes to check profile and level.
867 String spsData = "";
868 for (int i = 0; i < (info.size < 8 ? info.size : 8); i++) {
869 spsData += Integer.toHexString(configData.get(i) & 0xff) + " ";
870 }
871 Logging.d(TAG, spsData);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000872 // Release buffer back.
873 mediaCodec.releaseOutputBuffer(result, false);
874 // Query next output.
875 result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
876 }
877 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000878 if (result >= 0) {
879 // MediaCodec doesn't care about Buffer position/remaining/etc so we can
880 // mess with them to get a slice and avoid having to pass extra
881 // (BufferInfo-related) parameters back to C++.
882 ByteBuffer outputBuffer = outputBuffers[result].duplicate();
883 outputBuffer.position(info.offset);
884 outputBuffer.limit(info.offset + info.size);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700885 reportEncodedFrame(info.size);
886
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000887 // Check key frame flag.
sakalb6760f92016-09-29 04:12:44 -0700888 boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0;
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000889 if (isKeyFrame) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700890 Logging.d(TAG, "Sync frame generated");
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000891 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000892 if (isKeyFrame && type == VideoCodecType.VIDEO_CODEC_H264) {
sakalb6760f92016-09-29 04:12:44 -0700893 Logging.d(TAG, "Appending config frame of size " + configData.capacity()
894 + " to output buffer with offset " + info.offset + ", size " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000895 // For H.264 key frame append SPS and PPS NALs at the start
sakalb6760f92016-09-29 04:12:44 -0700896 ByteBuffer keyFrameBuffer = ByteBuffer.allocateDirect(configData.capacity() + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000897 configData.rewind();
898 keyFrameBuffer.put(configData);
899 keyFrameBuffer.put(outputBuffer);
900 keyFrameBuffer.position(0);
sakalb6760f92016-09-29 04:12:44 -0700901 return new OutputBufferInfo(result, keyFrameBuffer, isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000902 } else {
sakalb6760f92016-09-29 04:12:44 -0700903 return new OutputBufferInfo(
904 result, outputBuffer.slice(), isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000905 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000906 } else if (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
907 outputBuffers = mediaCodec.getOutputBuffers();
908 return dequeueOutputBuffer();
909 } else if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
910 return dequeueOutputBuffer();
911 } else if (result == MediaCodec.INFO_TRY_AGAIN_LATER) {
912 return null;
913 }
914 throw new RuntimeException("dequeueOutputBuffer: " + result);
915 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700916 Logging.e(TAG, "dequeueOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000917 return new OutputBufferInfo(-1, null, false, -1);
918 }
919 }
920
Alex Glaznevcfaca032016-09-06 14:08:19 -0700921 private double getBitrateScale(int bitrateAdjustmentScaleExp) {
922 return Math.pow(BITRATE_CORRECTION_MAX_SCALE,
sakalb6760f92016-09-29 04:12:44 -0700923 (double) bitrateAdjustmentScaleExp / BITRATE_CORRECTION_STEPS);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700924 }
925
926 private void reportEncodedFrame(int size) {
927 if (targetFps == 0 || bitrateAdjustmentType != BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
928 return;
929 }
930
931 // Accumulate the difference between actial and expected frame sizes.
932 double expectedBytesPerFrame = targetBitrateBps / (8.0 * targetFps);
933 bitrateAccumulator += (size - expectedBytesPerFrame);
934 bitrateObservationTimeMs += 1000.0 / targetFps;
935
936 // Put a cap on the accumulator, i.e., don't let it grow beyond some level to avoid
937 // using too old data for bitrate adjustment.
938 double bitrateAccumulatorCap = BITRATE_CORRECTION_SEC * bitrateAccumulatorMax;
939 bitrateAccumulator = Math.min(bitrateAccumulator, bitrateAccumulatorCap);
940 bitrateAccumulator = Math.max(bitrateAccumulator, -bitrateAccumulatorCap);
941
942 // Do bitrate adjustment every 3 seconds if actual encoder bitrate deviates too much
943 // form the target value.
944 if (bitrateObservationTimeMs > 1000 * BITRATE_CORRECTION_SEC) {
sakalb6760f92016-09-29 04:12:44 -0700945 Logging.d(TAG, "Acc: " + (int) bitrateAccumulator + ". Max: " + (int) bitrateAccumulatorMax
946 + ". ExpScale: " + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700947 boolean bitrateAdjustmentScaleChanged = false;
948 if (bitrateAccumulator > bitrateAccumulatorMax) {
949 // Encoder generates too high bitrate - need to reduce 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;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700953 bitrateAdjustmentScaleChanged = true;
954 } else if (bitrateAccumulator < -bitrateAccumulatorMax) {
955 // Encoder generates too low bitrate - need to increase the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800956 int bitrateAdjustmentInc = (int) (-bitrateAccumulator / bitrateAccumulatorMax + 0.5);
957 bitrateAdjustmentScaleExp += bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700958 bitrateAccumulator = -bitrateAccumulatorMax;
959 bitrateAdjustmentScaleChanged = true;
960 }
961 if (bitrateAdjustmentScaleChanged) {
962 bitrateAdjustmentScaleExp = Math.min(bitrateAdjustmentScaleExp, BITRATE_CORRECTION_STEPS);
963 bitrateAdjustmentScaleExp = Math.max(bitrateAdjustmentScaleExp, -BITRATE_CORRECTION_STEPS);
sakalb6760f92016-09-29 04:12:44 -0700964 Logging.d(TAG, "Adjusting bitrate scale to " + bitrateAdjustmentScaleExp + ". Value: "
965 + getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700966 setRates(targetBitrateBps / 1000, targetFps);
967 }
968 bitrateObservationTimeMs = 0;
969 }
970 }
971
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000972 // Release a dequeued output buffer back to the codec for re-use. Return
973 // false if the codec is no longer operable.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100974 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800975 boolean releaseOutputBuffer(int index) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000976 checkOnMediaCodecThread();
977 try {
978 mediaCodec.releaseOutputBuffer(index, false);
979 return true;
980 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700981 Logging.e(TAG, "releaseOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000982 return false;
983 }
984 }
sakalb5f5bdc2017-08-10 04:15:42 -0700985
Magnus Jedvert655e1962017-12-08 11:05:22 +0100986 @CalledByNative
987 int getColorFormat() {
988 return colorFormat;
989 }
990
991 @CalledByNative
992 static boolean isTextureBuffer(VideoFrame.Buffer buffer) {
993 return buffer instanceof VideoFrame.TextureBuffer;
994 }
995
sakalb5f5bdc2017-08-10 04:15:42 -0700996 /** Fills an inputBuffer with the given index with data from the byte buffers. */
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100997 private static native void nativeFillInputBuffer(long encoder, int inputBuffer, ByteBuffer dataY,
998 int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000999}