blob: 8ffe1e2ee2c48978e791e3f15964ef7b9595a5c1 [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;
Artem Titarenko69540f42018-12-10 12:30:46 +010023import android.support.annotation.Nullable;
perkj30e91822015-11-20 01:31:25 -080024import android.view.Surface;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000025import java.nio.ByteBuffer;
magjed295760d2017-01-12 01:11:57 -080026import java.util.ArrayList;
Alex Glaznev0c850202015-08-04 10:26:59 -070027import java.util.Arrays;
Sami Kalliomäki3d50a312018-09-11 11:11:47 +020028import java.util.HashMap;
Alex Glazneveee86a62016-01-29 14:17:07 -080029import java.util.HashSet;
Alex Glaznev0c850202015-08-04 10:26:59 -070030import java.util.List;
Alex Glazneveee86a62016-01-29 14:17:07 -080031import java.util.Set;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -070032import java.util.concurrent.CountDownLatch;
perkj48477c12015-12-18 00:34:37 -080033import java.util.concurrent.TimeUnit;
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +020034import org.webrtc.EglBase;
Magnus Jedvert655e1962017-12-08 11:05:22 +010035import org.webrtc.EglBase14;
36import org.webrtc.VideoFrame;
fischman@webrtc.org540acde2014-02-13 03:56:14 +000037
Magnus Jedvert9060eb12017-12-12 12:52:54 +010038// Java-side of peerconnection.cc:MediaCodecVideoEncoder.
fischman@webrtc.org540acde2014-02-13 03:56:14 +000039// This class is an implementation detail of the Java PeerConnection API.
Patrik Höglund68876f92015-11-12 17:36:48 +010040@TargetApi(19)
41@SuppressWarnings("deprecation")
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +020042@Deprecated
perkj@webrtc.org47098872014-10-24 11:38:19 +000043public class MediaCodecVideoEncoder {
fischman@webrtc.org540acde2014-02-13 03:56:14 +000044 // This class is constructed, operated, and destroyed by its C++ incarnation,
45 // so the class and its methods have non-public visibility. The API this
46 // class exposes aims to mimic the webrtc::VideoEncoder API as closely as
47 // possibly to minimize the amount of translation work necessary.
48
49 private static final String TAG = "MediaCodecVideoEncoder";
50
Magnus Jedverte26ff4b2018-07-13 16:09:20 +020051 /**
52 * Create a VideoEncoderFactory that can be injected in the PeerConnectionFactory and replicate
53 * the old behavior.
54 */
55 public static VideoEncoderFactory createFactory() {
56 return new DefaultVideoEncoderFactory(new HwEncoderFactory());
57 }
58
59 // Factory for creating HW MediaCodecVideoEncoder instances.
60 static class HwEncoderFactory implements VideoEncoderFactory {
61 private static boolean isSameCodec(VideoCodecInfo codecA, VideoCodecInfo codecB) {
62 if (!codecA.name.equalsIgnoreCase(codecB.name)) {
63 return false;
64 }
65 return codecA.name.equalsIgnoreCase("H264")
66 ? H264Utils.isSameH264Profile(codecA.params, codecB.params)
67 : true;
68 }
69
70 private static boolean isCodecSupported(
71 VideoCodecInfo[] supportedCodecs, VideoCodecInfo codec) {
72 for (VideoCodecInfo supportedCodec : supportedCodecs) {
73 if (isSameCodec(supportedCodec, codec)) {
74 return true;
75 }
76 }
77 return false;
78 }
79
80 private static VideoCodecInfo[] getSupportedHardwareCodecs() {
81 final List<VideoCodecInfo> codecs = new ArrayList<VideoCodecInfo>();
82
83 if (isVp8HwSupported()) {
84 Logging.d(TAG, "VP8 HW Encoder supported.");
85 codecs.add(new VideoCodecInfo("VP8", new HashMap<>()));
86 }
87
88 if (isVp9HwSupported()) {
89 Logging.d(TAG, "VP9 HW Encoder supported.");
90 codecs.add(new VideoCodecInfo("VP9", new HashMap<>()));
91 }
92
93 // Check if high profile is supported by decoder. If yes, encoder can always
94 // fall back to baseline profile as a subset as high profile.
95 if (MediaCodecVideoDecoder.isH264HighProfileHwSupported()) {
96 Logging.d(TAG, "H.264 High Profile HW Encoder supported.");
97 codecs.add(H264Utils.DEFAULT_H264_HIGH_PROFILE_CODEC);
98 }
99
100 if (isH264HwSupported()) {
101 Logging.d(TAG, "H.264 HW Encoder supported.");
102 codecs.add(H264Utils.DEFAULT_H264_BASELINE_PROFILE_CODEC);
103 }
104
105 return codecs.toArray(new VideoCodecInfo[codecs.size()]);
106 }
107
108 private final VideoCodecInfo[] supportedHardwareCodecs = getSupportedHardwareCodecs();
109
110 @Override
111 public VideoCodecInfo[] getSupportedCodecs() {
112 return supportedHardwareCodecs;
113 }
114
115 @Nullable
116 @Override
117 public VideoEncoder createEncoder(VideoCodecInfo info) {
118 if (!isCodecSupported(supportedHardwareCodecs, info)) {
119 Logging.d(TAG, "No HW video encoder for codec " + info.name);
120 return null;
121 }
122 Logging.d(TAG, "Create HW video encoder for " + info.name);
123 return new WrappedNativeVideoEncoder() {
124 @Override
125 public long createNativeVideoEncoder() {
126 return nativeCreateEncoder(
127 info, /* hasEgl14Context= */ staticEglBase instanceof EglBase14);
128 }
129
130 @Override
131 public boolean isHardwareEncoder() {
132 return true;
133 }
134 };
135 }
136 }
137
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000138 // Tracks webrtc::VideoCodecType.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100139 public enum VideoCodecType {
Niels Möller520ca4e2018-06-04 11:14:38 +0200140 VIDEO_CODEC_UNKNOWN,
Magnus Jedvert655e1962017-12-08 11:05:22 +0100141 VIDEO_CODEC_VP8,
142 VIDEO_CODEC_VP9,
143 VIDEO_CODEC_H264;
144
145 @CalledByNative("VideoCodecType")
146 static VideoCodecType fromNativeIndex(int nativeIndex) {
147 return values()[nativeIndex];
148 }
149 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000150
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700151 private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; // Timeout for codec releasing.
sakalb6760f92016-09-29 04:12:44 -0700152 private static final int DEQUEUE_TIMEOUT = 0; // Non-blocking, no wait.
Alex Glaznev269fe752016-05-25 16:17:33 -0700153 private static final int BITRATE_ADJUSTMENT_FPS = 30;
Alex Glaznevc55c39d2016-09-02 12:16:27 -0700154 private static final int MAXIMUM_INITIAL_FPS = 30;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700155 private static final double BITRATE_CORRECTION_SEC = 3.0;
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800156 // Maximum bitrate correction scale - no more than 4 times.
157 private static final double BITRATE_CORRECTION_MAX_SCALE = 4;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700158 // Amount of correction steps to reach correction maximum scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800159 private static final int BITRATE_CORRECTION_STEPS = 20;
Alex Glaznevc7483a72017-01-05 15:22:24 -0800160 // Forced key frame interval - used to reduce color distortions on Qualcomm platform.
alexlau84ee5c62017-06-02 17:36:32 -0700161 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS = 15000;
162 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS = 20000;
Alex Glaznevc7483a72017-01-05 15:22:24 -0800163 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS = 15000;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700164
perkj9576e542015-11-12 06:43:16 -0800165 // Active running encoder instance. Set in initEncode() (called from native code)
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700166 // and reset to null in release() call.
Sami Kalliomäki3d50a312018-09-11 11:11:47 +0200167 @Nullable private static MediaCodecVideoEncoder runningInstance;
168 @Nullable private static MediaCodecVideoEncoderErrorCallback errorCallback;
169 private static int codecErrors;
Alex Glazneveee86a62016-01-29 14:17:07 -0800170 // List of disabled codec types - can be set from application.
171 private static Set<String> hwEncoderDisabledTypes = new HashSet<String>();
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200172 @Nullable private static EglBase staticEglBase;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700173
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100174 @Nullable private Thread mediaCodecThread;
175 @Nullable private MediaCodec mediaCodec;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000176 private ByteBuffer[] outputBuffers;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100177 @Nullable private EglBase14 eglBase;
glaznev3fc23502017-06-15 16:24:37 -0700178 private int profile;
Magnus Jedvert51254332015-12-15 16:22:29 +0100179 private int width;
180 private int height;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100181 @Nullable private Surface inputSurface;
182 @Nullable private GlRectDrawer drawer;
Alex Glaznev269fe752016-05-25 16:17:33 -0700183
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000184 private static final String VP8_MIME_TYPE = "video/x-vnd.on2.vp8";
Alex Glaznevad948c42015-11-18 13:06:42 -0800185 private static final String VP9_MIME_TYPE = "video/x-vnd.on2.vp9";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000186 private static final String H264_MIME_TYPE = "video/avc";
Alex Glaznev269fe752016-05-25 16:17:33 -0700187
glaznev3fc23502017-06-15 16:24:37 -0700188 private static final int VIDEO_AVCProfileHigh = 8;
189 private static final int VIDEO_AVCLevel3 = 0x100;
190
Alex Glaznevcfaca032016-09-06 14:08:19 -0700191 // Type of bitrate adjustment for video encoder.
192 public enum BitrateAdjustmentType {
193 // No adjustment - video encoder has no known bitrate problem.
194 NO_ADJUSTMENT,
195 // Framerate based bitrate adjustment is required - HW encoder does not use frame
196 // timestamps to calculate frame bitrate budget and instead is relying on initial
197 // fps configuration assuming that all frames are coming at fixed initial frame rate.
198 FRAMERATE_ADJUSTMENT,
199 // Dynamic bitrate adjustment is required - HW encoder used frame timestamps, but actual
200 // bitrate deviates too much from the target value.
201 DYNAMIC_ADJUSTMENT
202 }
203
glaznev3fc23502017-06-15 16:24:37 -0700204 // Should be in sync with webrtc::H264::Profile.
205 public static enum H264Profile {
206 CONSTRAINED_BASELINE(0),
207 BASELINE(1),
208 MAIN(2),
209 CONSTRAINED_HIGH(3),
210 HIGH(4);
211
212 private final int value;
213
214 H264Profile(int value) {
215 this.value = value;
216 }
217
218 public int getValue() {
219 return value;
220 }
221 }
222
Alex Glaznev269fe752016-05-25 16:17:33 -0700223 // Class describing supported media codec properties.
224 private static class MediaCodecProperties {
225 public final String codecPrefix;
226 // Minimum Android SDK required for this codec to be used.
227 public final int minSdk;
228 // Flag if encoder implementation does not use frame timestamps to calculate frame bitrate
229 // budget and instead is relying on initial fps configuration assuming that all frames are
230 // coming at fixed initial frame rate. Bitrate adjustment is required for this case.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700231 public final BitrateAdjustmentType bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700232
233 MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700234 String codecPrefix, int minSdk, BitrateAdjustmentType bitrateAdjustmentType) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700235 this.codecPrefix = codecPrefix;
236 this.minSdk = minSdk;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700237 this.bitrateAdjustmentType = bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700238 }
239 }
240
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200241 /**
242 * Set EGL context used by HW encoding. The EGL context must be shared with the video capturer
243 * and any local render.
244 */
245 public static void setEglContext(EglBase.Context eglContext) {
246 if (staticEglBase != null) {
247 Logging.w(TAG, "Egl context already set.");
248 staticEglBase.release();
249 }
250 staticEglBase = EglBase.create(eglContext);
251 }
252
253 /** Dispose the EGL context used by HW encoding. */
254 public static void disposeEglContext() {
255 if (staticEglBase != null) {
256 staticEglBase.release();
257 staticEglBase = null;
258 }
259 }
260
261 @Nullable
262 static EglBase.Context getEglContext() {
263 return staticEglBase == null ? null : staticEglBase.getEglBaseContext();
264 }
265
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700266 // List of supported HW VP8 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700267 private static final MediaCodecProperties qcomVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700268 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700269 private static final MediaCodecProperties exynosVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700270 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.DYNAMIC_ADJUSTMENT);
magjed295760d2017-01-12 01:11:57 -0800271 private static final MediaCodecProperties intelVp8HwProperties = new MediaCodecProperties(
272 "OMX.Intel.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.NO_ADJUSTMENT);
273 private static MediaCodecProperties[] vp8HwList() {
274 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
275 supported_codecs.add(qcomVp8HwProperties);
276 supported_codecs.add(exynosVp8HwProperties);
277 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-IntelVP8").equals("Enabled")) {
278 supported_codecs.add(intelVp8HwProperties);
279 }
280 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
281 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700282
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700283 // List of supported HW VP9 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700284 private static final MediaCodecProperties qcomVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700285 "OMX.qcom.", Build.VERSION_CODES.N, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700286 private static final MediaCodecProperties exynosVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700287 "OMX.Exynos.", Build.VERSION_CODES.N, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
sakalb6760f92016-09-29 04:12:44 -0700288 private static final MediaCodecProperties[] vp9HwList =
289 new MediaCodecProperties[] {qcomVp9HwProperties, exynosVp9HwProperties};
Alex Glaznev269fe752016-05-25 16:17:33 -0700290
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700291 // List of supported HW H.264 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700292 private static final MediaCodecProperties qcomH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700293 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700294 private static final MediaCodecProperties exynosH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700295 "OMX.Exynos.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
Alex Leung5b6891a2018-01-18 10:01:14 -0800296 private static final MediaCodecProperties mediatekH264HwProperties = new MediaCodecProperties(
Alex Leung28e71072018-02-05 13:42:48 -0800297 "OMX.MTK.", Build.VERSION_CODES.O_MR1, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
Alex Leung5b6891a2018-01-18 10:01:14 -0800298 private static final MediaCodecProperties[] h264HwList() {
299 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
300 supported_codecs.add(qcomH264HwProperties);
301 supported_codecs.add(exynosH264HwProperties);
302 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekH264").equals("Enabled")) {
303 supported_codecs.add(mediatekH264HwProperties);
304 }
305 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
306 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700307
glaznev3fc23502017-06-15 16:24:37 -0700308 // List of supported HW H.264 high profile encoders.
309 private static final MediaCodecProperties exynosH264HighProfileHwProperties =
310 new MediaCodecProperties(
311 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
312 private static final MediaCodecProperties[] h264HighProfileHwList =
313 new MediaCodecProperties[] {exynosH264HighProfileHwProperties};
314
Alex Glaznev0c850202015-08-04 10:26:59 -0700315 // List of devices with poor H.264 encoder quality.
sakalb6760f92016-09-29 04:12:44 -0700316 // HW H.264 encoder on below devices has poor bitrate control - actual
317 // bitrates deviates a lot from the target value.
318 private static final String[] H264_HW_EXCEPTION_MODELS =
319 new String[] {"SAMSUNG-SGH-I337", "Nexus 7", "Nexus 4"};
Alex Glaznev0c850202015-08-04 10:26:59 -0700320
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000321 // Bitrate modes - should be in sync with OMX_VIDEO_CONTROLRATETYPE defined
322 // in OMX_Video.h
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000323 private static final int VIDEO_ControlRateConstant = 2;
324 // NV12 color format supported by QCOM codec, but not declared in MediaCodec -
325 // see /hardware/qcom/media/mm-core/inc/OMX_QCOMExtns.h
sakalb6760f92016-09-29 04:12:44 -0700326 private static final int COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m = 0x7FA30C04;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000327 // Allowable color formats supported by codec - in order of preference.
sakalb6760f92016-09-29 04:12:44 -0700328 private static final int[] supportedColorList = {CodecCapabilities.COLOR_FormatYUV420Planar,
329 CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
330 CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
331 COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m};
332 private static final int[] supportedSurfaceColorList = {CodecCapabilities.COLOR_FormatSurface};
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000333 private VideoCodecType type;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100334 private int colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700335
336 // Variables used for dynamic bitrate adjustment.
337 private BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
338 private double bitrateAccumulator;
339 private double bitrateAccumulatorMax;
340 private double bitrateObservationTimeMs;
341 private int bitrateAdjustmentScaleExp;
342 private int targetBitrateBps;
343 private int targetFps;
perkj9576e542015-11-12 06:43:16 -0800344
Alex Glaznevc7483a72017-01-05 15:22:24 -0800345 // Interval in ms to force key frame generation. Used to reduce the time of color distortions
346 // happened sometime when using Qualcomm video encoder.
347 private long forcedKeyFrameMs;
348 private long lastKeyFrameMs;
349
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000350 // SPS and PPS NALs (Config frame) for H.264.
Sami Kalliomäki3d50a312018-09-11 11:11:47 +0200351 @Nullable private ByteBuffer configData;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000352
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700353 // MediaCodec error handler - invoked when critical error happens which may prevent
354 // further use of media codec API. Now it means that one of media codec instances
355 // is hanging and can no longer be used in the next call.
356 public static interface MediaCodecVideoEncoderErrorCallback {
357 void onMediaCodecVideoEncoderCriticalError(int codecErrors);
358 }
359
360 public static void setErrorCallback(MediaCodecVideoEncoderErrorCallback errorCallback) {
361 Logging.d(TAG, "Set error callback");
362 MediaCodecVideoEncoder.errorCallback = errorCallback;
363 }
364
Alex Glazneveee86a62016-01-29 14:17:07 -0800365 // Functions to disable HW encoding - can be called from applications for platforms
366 // which have known HW decoding problems.
367 public static void disableVp8HwCodec() {
368 Logging.w(TAG, "VP8 encoding is disabled by application.");
369 hwEncoderDisabledTypes.add(VP8_MIME_TYPE);
370 }
371
372 public static void disableVp9HwCodec() {
373 Logging.w(TAG, "VP9 encoding is disabled by application.");
374 hwEncoderDisabledTypes.add(VP9_MIME_TYPE);
375 }
376
377 public static void disableH264HwCodec() {
378 Logging.w(TAG, "H.264 encoding is disabled by application.");
379 hwEncoderDisabledTypes.add(H264_MIME_TYPE);
380 }
381
382 // Functions to query if HW encoding is supported.
383 public static boolean isVp8HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700384 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800385 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800386 }
387
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100388 public static @Nullable EncoderProperties vp8HwEncoderProperties() {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800389 if (hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)) {
390 return null;
391 } else {
magjed295760d2017-01-12 01:11:57 -0800392 return findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList);
Alex Glaznevc7483a72017-01-05 15:22:24 -0800393 }
394 }
395
Alex Glazneveee86a62016-01-29 14:17:07 -0800396 public static boolean isVp9HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700397 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
398 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800399 }
400
401 public static boolean isH264HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700402 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800403 && (findHwEncoder(H264_MIME_TYPE, h264HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800404 }
405
glaznev3fc23502017-06-15 16:24:37 -0700406 public static boolean isH264HighProfileHwSupported() {
407 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
408 && (findHwEncoder(H264_MIME_TYPE, h264HighProfileHwList, supportedColorList) != null);
409 }
410
Alex Glazneveee86a62016-01-29 14:17:07 -0800411 public static boolean isVp8HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700412 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800413 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800414 }
415
416 public static boolean isVp9HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700417 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
418 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800419 }
420
421 public static boolean isH264HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700422 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800423 && (findHwEncoder(H264_MIME_TYPE, h264HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800424 }
425
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000426 // Helper struct for findHwEncoder() below.
Alex Glaznevc7483a72017-01-05 15:22:24 -0800427 public static class EncoderProperties {
Alex Glaznevcfaca032016-09-06 14:08:19 -0700428 public EncoderProperties(
429 String codecName, int colorFormat, BitrateAdjustmentType bitrateAdjustmentType) {
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000430 this.codecName = codecName;
431 this.colorFormat = colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700432 this.bitrateAdjustmentType = bitrateAdjustmentType;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000433 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000434 public final String codecName; // OpenMax component name for HW codec.
sakalb6760f92016-09-29 04:12:44 -0700435 public final int colorFormat; // Color format supported by codec.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700436 public final BitrateAdjustmentType bitrateAdjustmentType; // Bitrate adjustment type
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000437 }
438
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100439 private static @Nullable EncoderProperties findHwEncoder(
Alex Glaznev269fe752016-05-25 16:17:33 -0700440 String mime, MediaCodecProperties[] supportedHwCodecProperties, int[] colorList) {
Alex Glaznev0c850202015-08-04 10:26:59 -0700441 // MediaCodec.setParameters is missing for JB and below, so bitrate
442 // can not be adjusted dynamically.
443 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
444 return null;
445 }
446
447 // Check if device is in H.264 exception list.
448 if (mime.equals(H264_MIME_TYPE)) {
449 List<String> exceptionModels = Arrays.asList(H264_HW_EXCEPTION_MODELS);
450 if (exceptionModels.contains(Build.MODEL)) {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700451 Logging.w(TAG, "Model: " + Build.MODEL + " has black listed H.264 encoder.");
Alex Glaznev0c850202015-08-04 10:26:59 -0700452 return null;
453 }
454 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000455
456 for (int i = 0; i < MediaCodecList.getCodecCount(); ++i) {
Alex Glaznev0060c562016-08-08 12:27:24 -0700457 MediaCodecInfo info = null;
458 try {
459 info = MediaCodecList.getCodecInfoAt(i);
460 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700461 Logging.e(TAG, "Cannot retrieve encoder codec info", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700462 }
463 if (info == null || !info.isEncoder()) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000464 continue;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000465 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000466 String name = null;
467 for (String mimeType : info.getSupportedTypes()) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000468 if (mimeType.equals(mime)) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000469 name = info.getName();
470 break;
471 }
472 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000473 if (name == null) {
sakalb6760f92016-09-29 04:12:44 -0700474 continue; // No HW support in this codec; try the next one.
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000475 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700476 Logging.v(TAG, "Found candidate encoder " + name);
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000477
478 // Check if this is supported HW encoder.
479 boolean supportedCodec = false;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700480 BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
Alex Glaznev269fe752016-05-25 16:17:33 -0700481 for (MediaCodecProperties codecProperties : supportedHwCodecProperties) {
482 if (name.startsWith(codecProperties.codecPrefix)) {
483 if (Build.VERSION.SDK_INT < codecProperties.minSdk) {
sakalb6760f92016-09-29 04:12:44 -0700484 Logging.w(
485 TAG, "Codec " + name + " is disabled due to SDK version " + Build.VERSION.SDK_INT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700486 continue;
487 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700488 if (codecProperties.bitrateAdjustmentType != BitrateAdjustmentType.NO_ADJUSTMENT) {
489 bitrateAdjustmentType = codecProperties.bitrateAdjustmentType;
sakalb6760f92016-09-29 04:12:44 -0700490 Logging.w(
491 TAG, "Codec " + name + " requires bitrate adjustment: " + bitrateAdjustmentType);
Alex Glaznev269fe752016-05-25 16:17:33 -0700492 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000493 supportedCodec = true;
494 break;
495 }
496 }
497 if (!supportedCodec) {
498 continue;
499 }
500
Alex Glaznev269fe752016-05-25 16:17:33 -0700501 // Check if HW codec supports known color format.
Alex Glaznev0060c562016-08-08 12:27:24 -0700502 CodecCapabilities capabilities;
503 try {
504 capabilities = info.getCapabilitiesForType(mime);
505 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700506 Logging.e(TAG, "Cannot retrieve encoder capabilities", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700507 continue;
508 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000509 for (int colorFormat : capabilities.colorFormats) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700510 Logging.v(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000511 }
512
perkj30e91822015-11-20 01:31:25 -0800513 for (int supportedColorFormat : colorList) {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000514 for (int codecColorFormat : capabilities.colorFormats) {
515 if (codecColorFormat == supportedColorFormat) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000516 // Found supported HW encoder.
sakalb6760f92016-09-29 04:12:44 -0700517 Logging.d(TAG, "Found target encoder for mime " + mime + " : " + name + ". Color: 0x"
518 + Integer.toHexString(codecColorFormat) + ". Bitrate adjustment: "
519 + bitrateAdjustmentType);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700520 return new EncoderProperties(name, codecColorFormat, bitrateAdjustmentType);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000521 }
522 }
523 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000524 }
sakalb6760f92016-09-29 04:12:44 -0700525 return null; // No HW encoder.
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000526 }
527
Magnus Jedvert655e1962017-12-08 11:05:22 +0100528 @CalledByNative
529 MediaCodecVideoEncoder() {}
530
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000531 private void checkOnMediaCodecThread() {
532 if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
sakalb6760f92016-09-29 04:12:44 -0700533 throw new RuntimeException("MediaCodecVideoEncoder previously operated on " + mediaCodecThread
534 + " but is now called on " + Thread.currentThread());
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000535 }
536 }
537
Alex Glaznev325d4142015-10-12 14:56:02 -0700538 public static void printStackTrace() {
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700539 if (runningInstance != null && runningInstance.mediaCodecThread != null) {
540 StackTraceElement[] mediaCodecStackTraces = runningInstance.mediaCodecThread.getStackTrace();
Alex Glaznev325d4142015-10-12 14:56:02 -0700541 if (mediaCodecStackTraces.length > 0) {
542 Logging.d(TAG, "MediaCodecVideoEncoder stacks trace:");
543 for (StackTraceElement stackTrace : mediaCodecStackTraces) {
544 Logging.d(TAG, stackTrace.toString());
545 }
546 }
547 }
548 }
549
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100550 static @Nullable MediaCodec createByCodecName(String codecName) {
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000551 try {
552 // In the L-SDK this call can throw IOException so in order to work in
553 // both cases catch an exception.
554 return MediaCodec.createByCodecName(codecName);
555 } catch (Exception e) {
556 return null;
557 }
558 }
559
Magnus Jedvert655e1962017-12-08 11:05:22 +0100560 @CalledByNativeUnchecked
glaznev3fc23502017-06-15 16:24:37 -0700561 boolean initEncode(VideoCodecType type, int profile, int width, int height, int kbps, int fps,
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200562 boolean useSurface) {
glaznev3fc23502017-06-15 16:24:37 -0700563 Logging.d(TAG,
564 "Java initEncode: " + type + ". Profile: " + profile + " : " + width + " x " + height
565 + ". @ " + kbps + " kbps. Fps: " + fps + ". Encode from texture : " + useSurface);
perkj9576e542015-11-12 06:43:16 -0800566
glaznev3fc23502017-06-15 16:24:37 -0700567 this.profile = profile;
Magnus Jedvert51254332015-12-15 16:22:29 +0100568 this.width = width;
569 this.height = height;
Alejandro Luebs69ddaef2015-10-09 15:46:09 -0700570 if (mediaCodecThread != null) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000571 throw new RuntimeException("Forgot to release()?");
572 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000573 EncoderProperties properties = null;
574 String mime = null;
575 int keyFrameIntervalSec = 0;
glaznev3fc23502017-06-15 16:24:37 -0700576 boolean configureH264HighProfile = false;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000577 if (type == VideoCodecType.VIDEO_CODEC_VP8) {
578 mime = VP8_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700579 properties = findHwEncoder(
magjed295760d2017-01-12 01:11:57 -0800580 VP8_MIME_TYPE, vp8HwList(), useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000581 keyFrameIntervalSec = 100;
Alex Glaznevad948c42015-11-18 13:06:42 -0800582 } else if (type == VideoCodecType.VIDEO_CODEC_VP9) {
583 mime = VP9_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700584 properties = findHwEncoder(
585 VP9_MIME_TYPE, vp9HwList, useSurface ? supportedSurfaceColorList : supportedColorList);
Alex Glaznevad948c42015-11-18 13:06:42 -0800586 keyFrameIntervalSec = 100;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000587 } else if (type == VideoCodecType.VIDEO_CODEC_H264) {
588 mime = H264_MIME_TYPE;
Alex Leung5b6891a2018-01-18 10:01:14 -0800589 properties = findHwEncoder(H264_MIME_TYPE, h264HwList(),
590 useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev3fc23502017-06-15 16:24:37 -0700591 if (profile == H264Profile.CONSTRAINED_HIGH.getValue()) {
592 EncoderProperties h264HighProfileProperties = findHwEncoder(H264_MIME_TYPE,
593 h264HighProfileHwList, useSurface ? supportedSurfaceColorList : supportedColorList);
594 if (h264HighProfileProperties != null) {
595 Logging.d(TAG, "High profile H.264 encoder supported.");
596 configureH264HighProfile = true;
597 } else {
598 Logging.d(TAG, "High profile H.264 encoder requested, but not supported. Use baseline.");
599 }
600 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000601 keyFrameIntervalSec = 20;
Niels Möller520ca4e2018-06-04 11:14:38 +0200602 } else {
603 throw new RuntimeException("initEncode: Non-supported codec " + type);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000604 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000605 if (properties == null) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000606 throw new RuntimeException("Can not find HW encoder for " + type);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000607 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700608 runningInstance = this; // Encoder is now running and can be queried for stack traces.
perkj9576e542015-11-12 06:43:16 -0800609 colorFormat = properties.colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700610 bitrateAdjustmentType = properties.bitrateAdjustmentType;
611 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700612 fps = BITRATE_ADJUSTMENT_FPS;
sakalb6760f92016-09-29 04:12:44 -0700613 } else {
Alex Glaznevc55c39d2016-09-02 12:16:27 -0700614 fps = Math.min(fps, MAXIMUM_INITIAL_FPS);
Alex Glaznev269fe752016-05-25 16:17:33 -0700615 }
Alex Glaznevc7483a72017-01-05 15:22:24 -0800616
617 forcedKeyFrameMs = 0;
618 lastKeyFrameMs = -1;
Alex Glaznev512f00b2017-01-05 16:40:46 -0800619 if (type == VideoCodecType.VIDEO_CODEC_VP8
620 && properties.codecName.startsWith(qcomVp8HwProperties.codecPrefix)) {
alexlau84ee5c62017-06-02 17:36:32 -0700621 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP
622 || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
623 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS;
624 } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800625 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS;
626 } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
627 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS;
628 }
629 }
630
sakalb6760f92016-09-29 04:12:44 -0700631 Logging.d(TAG, "Color format: " + colorFormat + ". Bitrate adjustment: " + bitrateAdjustmentType
Alex Glaznevc7483a72017-01-05 15:22:24 -0800632 + ". Key frame interval: " + forcedKeyFrameMs + " . Initial fps: " + fps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700633 targetBitrateBps = 1000 * kbps;
634 targetFps = fps;
635 bitrateAccumulatorMax = targetBitrateBps / 8.0;
636 bitrateAccumulator = 0;
637 bitrateObservationTimeMs = 0;
638 bitrateAdjustmentScaleExp = 0;
perkj9576e542015-11-12 06:43:16 -0800639
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000640 mediaCodecThread = Thread.currentThread();
641 try {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000642 MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700643 format.setInteger(MediaFormat.KEY_BIT_RATE, targetBitrateBps);
Alex Glaznev8a2cd3d2015-08-11 11:32:53 -0700644 format.setInteger("bitrate-mode", VIDEO_ControlRateConstant);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000645 format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700646 format.setInteger(MediaFormat.KEY_FRAME_RATE, targetFps);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000647 format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameIntervalSec);
glaznev3fc23502017-06-15 16:24:37 -0700648 if (configureH264HighProfile) {
649 format.setInteger("profile", VIDEO_AVCProfileHigh);
650 format.setInteger("level", VIDEO_AVCLevel3);
651 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700652 Logging.d(TAG, " Format: " + format);
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000653 mediaCodec = createByCodecName(properties.codecName);
perkj9576e542015-11-12 06:43:16 -0800654 this.type = type;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000655 if (mediaCodec == null) {
Alex Glaznev325d4142015-10-12 14:56:02 -0700656 Logging.e(TAG, "Can not create media encoder");
sakal996a83c2017-03-15 05:53:14 -0700657 release();
perkj9576e542015-11-12 06:43:16 -0800658 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000659 }
sakalb6760f92016-09-29 04:12:44 -0700660 mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
perkj9576e542015-11-12 06:43:16 -0800661
perkj30e91822015-11-20 01:31:25 -0800662 if (useSurface) {
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200663 eglBase = new EglBase14((EglBase14.Context) getEglContext(), EglBase.CONFIG_RECORDABLE);
perkj30e91822015-11-20 01:31:25 -0800664 // Create an input surface and keep a reference since we must release the surface when done.
665 inputSurface = mediaCodec.createInputSurface();
666 eglBase.createSurface(inputSurface);
667 drawer = new GlRectDrawer();
668 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000669 mediaCodec.start();
670 outputBuffers = mediaCodec.getOutputBuffers();
perkj9576e542015-11-12 06:43:16 -0800671 Logging.d(TAG, "Output buffers: " + outputBuffers.length);
672
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000673 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700674 Logging.e(TAG, "initEncode failed", e);
sakal996a83c2017-03-15 05:53:14 -0700675 release();
perkj9576e542015-11-12 06:43:16 -0800676 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000677 }
perkj9576e542015-11-12 06:43:16 -0800678 return true;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000679 }
680
Magnus Jedvert655e1962017-12-08 11:05:22 +0100681 @CalledByNativeUnchecked
sakalb6760f92016-09-29 04:12:44 -0700682 ByteBuffer[] getInputBuffers() {
perkj9576e542015-11-12 06:43:16 -0800683 ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
684 Logging.d(TAG, "Input buffers: " + inputBuffers.length);
685 return inputBuffers;
686 }
687
Alex Glaznevc7483a72017-01-05 15:22:24 -0800688 void checkKeyFrameRequired(boolean requestedKeyFrame, long presentationTimestampUs) {
689 long presentationTimestampMs = (presentationTimestampUs + 500) / 1000;
690 if (lastKeyFrameMs < 0) {
691 lastKeyFrameMs = presentationTimestampMs;
692 }
693 boolean forcedKeyFrame = false;
694 if (!requestedKeyFrame && forcedKeyFrameMs > 0
695 && presentationTimestampMs > lastKeyFrameMs + forcedKeyFrameMs) {
696 forcedKeyFrame = true;
697 }
698 if (requestedKeyFrame || forcedKeyFrame) {
699 // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could
700 // indicate this in queueInputBuffer() below and guarantee _this_ frame
701 // be encoded as a key frame, but sadly that flag is ignored. Instead,
702 // we request a key frame "soon".
703 if (requestedKeyFrame) {
704 Logging.d(TAG, "Sync frame request");
705 } else {
706 Logging.d(TAG, "Sync frame forced");
707 }
708 Bundle b = new Bundle();
709 b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0);
710 mediaCodec.setParameters(b);
711 lastKeyFrameMs = presentationTimestampMs;
712 }
713 }
714
Magnus Jedvert655e1962017-12-08 11:05:22 +0100715 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800716 boolean encodeBuffer(
sakalb6760f92016-09-29 04:12:44 -0700717 boolean isKeyframe, int inputBuffer, int size, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000718 checkOnMediaCodecThread();
719 try {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800720 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
sakalb6760f92016-09-29 04:12:44 -0700721 mediaCodec.queueInputBuffer(inputBuffer, 0, size, presentationTimestampUs, 0);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000722 return true;
sakalb6760f92016-09-29 04:12:44 -0700723 } catch (IllegalStateException e) {
perkj9576e542015-11-12 06:43:16 -0800724 Logging.e(TAG, "encodeBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000725 return false;
726 }
727 }
728
sakalb5f5bdc2017-08-10 04:15:42 -0700729 /**
Magnus Jedvert655e1962017-12-08 11:05:22 +0100730 * Encodes a new style VideoFrame. |bufferIndex| is -1 if we are not encoding in surface mode.
sakalb5f5bdc2017-08-10 04:15:42 -0700731 */
Magnus Jedvert655e1962017-12-08 11:05:22 +0100732 @CalledByNativeUnchecked
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100733 boolean encodeFrame(long nativeEncoder, boolean isKeyframe, VideoFrame frame, int bufferIndex,
734 long presentationTimestampUs) {
sakalb5f5bdc2017-08-10 04:15:42 -0700735 checkOnMediaCodecThread();
736 try {
sakalb5f5bdc2017-08-10 04:15:42 -0700737 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
738
739 VideoFrame.Buffer buffer = frame.getBuffer();
740 if (buffer instanceof VideoFrame.TextureBuffer) {
741 VideoFrame.TextureBuffer textureBuffer = (VideoFrame.TextureBuffer) buffer;
742 eglBase.makeCurrent();
743 // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway,
744 // but it's a workaround for bug webrtc:5147.
745 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700746 VideoFrameDrawer.drawTexture(drawer, textureBuffer, new Matrix() /* renderMatrix */, width,
sakal9bc599f2017-09-08 04:46:33 -0700747 height, 0 /* viewportX */, 0 /* viewportY */, width, height);
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100748 eglBase.swapBuffers(TimeUnit.MICROSECONDS.toNanos(presentationTimestampUs));
sakalb5f5bdc2017-08-10 04:15:42 -0700749 } else {
750 VideoFrame.I420Buffer i420Buffer = buffer.toI420();
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200751 final int chromaHeight = (height + 1) / 2;
752 final ByteBuffer dataY = i420Buffer.getDataY();
753 final ByteBuffer dataU = i420Buffer.getDataU();
754 final ByteBuffer dataV = i420Buffer.getDataV();
755 final int strideY = i420Buffer.getStrideY();
756 final int strideU = i420Buffer.getStrideU();
757 final int strideV = i420Buffer.getStrideV();
758 if (dataY.capacity() < strideY * height) {
759 throw new RuntimeException("Y-plane buffer size too small.");
760 }
761 if (dataU.capacity() < strideU * chromaHeight) {
762 throw new RuntimeException("U-plane buffer size too small.");
763 }
764 if (dataV.capacity() < strideV * chromaHeight) {
765 throw new RuntimeException("V-plane buffer size too small.");
766 }
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100767 nativeFillInputBuffer(
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200768 nativeEncoder, bufferIndex, dataY, strideY, dataU, strideU, dataV, strideV);
sakalb5f5bdc2017-08-10 04:15:42 -0700769 i420Buffer.release();
770 // I420 consists of one full-resolution and two half-resolution planes.
771 // 1 + 1 / 4 + 1 / 4 = 3 / 2
772 int yuvSize = width * height * 3 / 2;
773 mediaCodec.queueInputBuffer(bufferIndex, 0, yuvSize, presentationTimestampUs, 0);
774 }
775 return true;
776 } catch (RuntimeException e) {
777 Logging.e(TAG, "encodeFrame failed", e);
778 return false;
779 }
780 }
781
Magnus Jedvert655e1962017-12-08 11:05:22 +0100782 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800783 void release() {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700784 Logging.d(TAG, "Java releaseEncoder");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000785 checkOnMediaCodecThread();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700786
sakal996a83c2017-03-15 05:53:14 -0700787 class CaughtException {
788 Exception e;
789 }
790 final CaughtException caughtException = new CaughtException();
791 boolean stopHung = false;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700792
sakal996a83c2017-03-15 05:53:14 -0700793 if (mediaCodec != null) {
794 // Run Mediacodec stop() and release() on separate thread since sometime
795 // Mediacodec.stop() may hang.
796 final CountDownLatch releaseDone = new CountDownLatch(1);
797
798 Runnable runMediaCodecRelease = new Runnable() {
799 @Override
800 public void run() {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700801 Logging.d(TAG, "Java releaseEncoder on release thread");
sakal996a83c2017-03-15 05:53:14 -0700802 try {
803 mediaCodec.stop();
804 } catch (Exception e) {
805 Logging.e(TAG, "Media encoder stop failed", e);
806 }
807 try {
808 mediaCodec.release();
809 } catch (Exception e) {
810 Logging.e(TAG, "Media encoder release failed", e);
811 caughtException.e = e;
812 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700813 Logging.d(TAG, "Java releaseEncoder on release thread done");
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700814
sakal996a83c2017-03-15 05:53:14 -0700815 releaseDone.countDown();
816 }
817 };
818 new Thread(runMediaCodecRelease).start();
819
820 if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) {
821 Logging.e(TAG, "Media encoder release timeout");
822 stopHung = true;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700823 }
sakal996a83c2017-03-15 05:53:14 -0700824
825 mediaCodec = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000826 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700827
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000828 mediaCodecThread = null;
perkj30e91822015-11-20 01:31:25 -0800829 if (drawer != null) {
830 drawer.release();
831 drawer = null;
832 }
833 if (eglBase != null) {
834 eglBase.release();
835 eglBase = null;
836 }
837 if (inputSurface != null) {
838 inputSurface.release();
839 inputSurface = null;
840 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700841 runningInstance = null;
sakal996a83c2017-03-15 05:53:14 -0700842
843 if (stopHung) {
844 codecErrors++;
845 if (errorCallback != null) {
846 Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors);
847 errorCallback.onMediaCodecVideoEncoderCriticalError(codecErrors);
848 }
849 throw new RuntimeException("Media encoder release timeout.");
850 }
851
852 // Re-throw any runtime exception caught inside the other thread. Since this is an invoke, add
853 // stack trace for the waiting thread as well.
854 if (caughtException.e != null) {
855 final RuntimeException runtimeException = new RuntimeException(caughtException.e);
856 runtimeException.setStackTrace(ThreadUtils.concatStackTraces(
857 caughtException.e.getStackTrace(), runtimeException.getStackTrace()));
858 throw runtimeException;
859 }
860
Alex Glaznev325d4142015-10-12 14:56:02 -0700861 Logging.d(TAG, "Java releaseEncoder done");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000862 }
863
Magnus Jedvert655e1962017-12-08 11:05:22 +0100864 @CalledByNativeUnchecked
Alex Glaznev269fe752016-05-25 16:17:33 -0700865 private boolean setRates(int kbps, int frameRate) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000866 checkOnMediaCodecThread();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700867
868 int codecBitrateBps = 1000 * kbps;
869 if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
870 bitrateAccumulatorMax = codecBitrateBps / 8.0;
871 if (targetBitrateBps > 0 && codecBitrateBps < targetBitrateBps) {
872 // Rescale the accumulator level if the accumulator max decreases
873 bitrateAccumulator = bitrateAccumulator * codecBitrateBps / targetBitrateBps;
874 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700875 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700876 targetBitrateBps = codecBitrateBps;
877 targetFps = frameRate;
878
879 // Adjust actual encoder bitrate based on bitrate adjustment type.
880 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT && targetFps > 0) {
881 codecBitrateBps = BITRATE_ADJUSTMENT_FPS * targetBitrateBps / targetFps;
sakalb6760f92016-09-29 04:12:44 -0700882 Logging.v(TAG,
883 "setRates: " + kbps + " -> " + (codecBitrateBps / 1000) + " kbps. Fps: " + targetFps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700884 } else if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
sakalb6760f92016-09-29 04:12:44 -0700885 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps + ". ExpScale: "
886 + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700887 if (bitrateAdjustmentScaleExp != 0) {
sakalb6760f92016-09-29 04:12:44 -0700888 codecBitrateBps = (int) (codecBitrateBps * getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700889 }
890 } else {
891 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps);
892 }
893
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000894 try {
895 Bundle params = new Bundle();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700896 params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, codecBitrateBps);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000897 mediaCodec.setParameters(params);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000898 return true;
899 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700900 Logging.e(TAG, "setRates failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000901 return false;
902 }
903 }
904
905 // Dequeue an input buffer and return its index, -1 if no input buffer is
906 // available, or -2 if the codec is no longer operative.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100907 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800908 int dequeueInputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000909 checkOnMediaCodecThread();
910 try {
911 return mediaCodec.dequeueInputBuffer(DEQUEUE_TIMEOUT);
912 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700913 Logging.e(TAG, "dequeueIntputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000914 return -2;
915 }
916 }
917
918 // Helper struct for dequeueOutputBuffer() below.
perkj9576e542015-11-12 06:43:16 -0800919 static class OutputBufferInfo {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000920 public OutputBufferInfo(
sakalb6760f92016-09-29 04:12:44 -0700921 int index, ByteBuffer buffer, boolean isKeyFrame, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000922 this.index = index;
923 this.buffer = buffer;
924 this.isKeyFrame = isKeyFrame;
925 this.presentationTimestampUs = presentationTimestampUs;
926 }
927
perkj9576e542015-11-12 06:43:16 -0800928 public final int index;
929 public final ByteBuffer buffer;
930 public final boolean isKeyFrame;
931 public final long presentationTimestampUs;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100932
933 @CalledByNative("OutputBufferInfo")
934 int getIndex() {
935 return index;
936 }
937
938 @CalledByNative("OutputBufferInfo")
939 ByteBuffer getBuffer() {
940 return buffer;
941 }
942
943 @CalledByNative("OutputBufferInfo")
944 boolean isKeyFrame() {
945 return isKeyFrame;
946 }
947
948 @CalledByNative("OutputBufferInfo")
949 long getPresentationTimestampUs() {
950 return presentationTimestampUs;
951 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000952 }
953
954 // Dequeue and return an output buffer, or null if no output is ready. Return
955 // a fake OutputBufferInfo with index -1 if the codec is no longer operable.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100956 @Nullable
Magnus Jedvert655e1962017-12-08 11:05:22 +0100957 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800958 OutputBufferInfo dequeueOutputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000959 checkOnMediaCodecThread();
960 try {
961 MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
962 int result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000963 // Check if this is config frame and save configuration data.
964 if (result >= 0) {
sakalb6760f92016-09-29 04:12:44 -0700965 boolean isConfigFrame = (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000966 if (isConfigFrame) {
sakalb6760f92016-09-29 04:12:44 -0700967 Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000968 configData = ByteBuffer.allocateDirect(info.size);
969 outputBuffers[result].position(info.offset);
970 outputBuffers[result].limit(info.offset + info.size);
971 configData.put(outputBuffers[result]);
glaznev3fc23502017-06-15 16:24:37 -0700972 // Log few SPS header bytes to check profile and level.
973 String spsData = "";
974 for (int i = 0; i < (info.size < 8 ? info.size : 8); i++) {
975 spsData += Integer.toHexString(configData.get(i) & 0xff) + " ";
976 }
977 Logging.d(TAG, spsData);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000978 // Release buffer back.
979 mediaCodec.releaseOutputBuffer(result, false);
980 // Query next output.
981 result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
982 }
983 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000984 if (result >= 0) {
985 // MediaCodec doesn't care about Buffer position/remaining/etc so we can
986 // mess with them to get a slice and avoid having to pass extra
987 // (BufferInfo-related) parameters back to C++.
988 ByteBuffer outputBuffer = outputBuffers[result].duplicate();
989 outputBuffer.position(info.offset);
990 outputBuffer.limit(info.offset + info.size);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700991 reportEncodedFrame(info.size);
992
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000993 // Check key frame flag.
sakalb6760f92016-09-29 04:12:44 -0700994 boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0;
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000995 if (isKeyFrame) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700996 Logging.d(TAG, "Sync frame generated");
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000997 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000998 if (isKeyFrame && type == VideoCodecType.VIDEO_CODEC_H264) {
sakalb6760f92016-09-29 04:12:44 -0700999 Logging.d(TAG, "Appending config frame of size " + configData.capacity()
1000 + " to output buffer with offset " + info.offset + ", size " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001001 // For H.264 key frame append SPS and PPS NALs at the start
sakalb6760f92016-09-29 04:12:44 -07001002 ByteBuffer keyFrameBuffer = ByteBuffer.allocateDirect(configData.capacity() + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001003 configData.rewind();
1004 keyFrameBuffer.put(configData);
1005 keyFrameBuffer.put(outputBuffer);
1006 keyFrameBuffer.position(0);
sakalb6760f92016-09-29 04:12:44 -07001007 return new OutputBufferInfo(result, keyFrameBuffer, isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001008 } else {
sakalb6760f92016-09-29 04:12:44 -07001009 return new OutputBufferInfo(
1010 result, outputBuffer.slice(), isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001011 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001012 } else if (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
1013 outputBuffers = mediaCodec.getOutputBuffers();
1014 return dequeueOutputBuffer();
1015 } else if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
1016 return dequeueOutputBuffer();
1017 } else if (result == MediaCodec.INFO_TRY_AGAIN_LATER) {
1018 return null;
1019 }
1020 throw new RuntimeException("dequeueOutputBuffer: " + result);
1021 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -07001022 Logging.e(TAG, "dequeueOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001023 return new OutputBufferInfo(-1, null, false, -1);
1024 }
1025 }
1026
Alex Glaznevcfaca032016-09-06 14:08:19 -07001027 private double getBitrateScale(int bitrateAdjustmentScaleExp) {
1028 return Math.pow(BITRATE_CORRECTION_MAX_SCALE,
sakalb6760f92016-09-29 04:12:44 -07001029 (double) bitrateAdjustmentScaleExp / BITRATE_CORRECTION_STEPS);
Alex Glaznevcfaca032016-09-06 14:08:19 -07001030 }
1031
1032 private void reportEncodedFrame(int size) {
1033 if (targetFps == 0 || bitrateAdjustmentType != BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
1034 return;
1035 }
1036
1037 // Accumulate the difference between actial and expected frame sizes.
1038 double expectedBytesPerFrame = targetBitrateBps / (8.0 * targetFps);
1039 bitrateAccumulator += (size - expectedBytesPerFrame);
1040 bitrateObservationTimeMs += 1000.0 / targetFps;
1041
1042 // Put a cap on the accumulator, i.e., don't let it grow beyond some level to avoid
1043 // using too old data for bitrate adjustment.
1044 double bitrateAccumulatorCap = BITRATE_CORRECTION_SEC * bitrateAccumulatorMax;
1045 bitrateAccumulator = Math.min(bitrateAccumulator, bitrateAccumulatorCap);
1046 bitrateAccumulator = Math.max(bitrateAccumulator, -bitrateAccumulatorCap);
1047
1048 // Do bitrate adjustment every 3 seconds if actual encoder bitrate deviates too much
1049 // form the target value.
1050 if (bitrateObservationTimeMs > 1000 * BITRATE_CORRECTION_SEC) {
sakalb6760f92016-09-29 04:12:44 -07001051 Logging.d(TAG, "Acc: " + (int) bitrateAccumulator + ". Max: " + (int) bitrateAccumulatorMax
1052 + ". ExpScale: " + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -07001053 boolean bitrateAdjustmentScaleChanged = false;
1054 if (bitrateAccumulator > bitrateAccumulatorMax) {
1055 // Encoder generates too high bitrate - need to reduce the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -08001056 int bitrateAdjustmentInc = (int) (bitrateAccumulator / bitrateAccumulatorMax + 0.5);
1057 bitrateAdjustmentScaleExp -= bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001058 bitrateAccumulator = bitrateAccumulatorMax;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001059 bitrateAdjustmentScaleChanged = true;
1060 } else if (bitrateAccumulator < -bitrateAccumulatorMax) {
1061 // Encoder generates too low bitrate - need to increase the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -08001062 int bitrateAdjustmentInc = (int) (-bitrateAccumulator / bitrateAccumulatorMax + 0.5);
1063 bitrateAdjustmentScaleExp += bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001064 bitrateAccumulator = -bitrateAccumulatorMax;
1065 bitrateAdjustmentScaleChanged = true;
1066 }
1067 if (bitrateAdjustmentScaleChanged) {
1068 bitrateAdjustmentScaleExp = Math.min(bitrateAdjustmentScaleExp, BITRATE_CORRECTION_STEPS);
1069 bitrateAdjustmentScaleExp = Math.max(bitrateAdjustmentScaleExp, -BITRATE_CORRECTION_STEPS);
sakalb6760f92016-09-29 04:12:44 -07001070 Logging.d(TAG, "Adjusting bitrate scale to " + bitrateAdjustmentScaleExp + ". Value: "
1071 + getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -07001072 setRates(targetBitrateBps / 1000, targetFps);
1073 }
1074 bitrateObservationTimeMs = 0;
1075 }
1076 }
1077
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001078 // Release a dequeued output buffer back to the codec for re-use. Return
1079 // false if the codec is no longer operable.
Magnus Jedvert655e1962017-12-08 11:05:22 +01001080 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -08001081 boolean releaseOutputBuffer(int index) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001082 checkOnMediaCodecThread();
1083 try {
1084 mediaCodec.releaseOutputBuffer(index, false);
1085 return true;
1086 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -07001087 Logging.e(TAG, "releaseOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001088 return false;
1089 }
1090 }
sakalb5f5bdc2017-08-10 04:15:42 -07001091
Magnus Jedvert655e1962017-12-08 11:05:22 +01001092 @CalledByNative
1093 int getColorFormat() {
1094 return colorFormat;
1095 }
1096
1097 @CalledByNative
1098 static boolean isTextureBuffer(VideoFrame.Buffer buffer) {
1099 return buffer instanceof VideoFrame.TextureBuffer;
1100 }
1101
sakalb5f5bdc2017-08-10 04:15:42 -07001102 /** Fills an inputBuffer with the given index with data from the byte buffers. */
Magnus Jedvert84d8ae52017-12-20 15:12:10 +01001103 private static native void nativeFillInputBuffer(long encoder, int inputBuffer, ByteBuffer dataY,
1104 int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV);
Magnus Jedverte26ff4b2018-07-13 16:09:20 +02001105 private static native long nativeCreateEncoder(VideoCodecInfo info, boolean hasEgl14Context);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001106}