blob: 773ed16e8ee00631fdce85819b58229c656c6f12 [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 Jedvert98d85fe2019-03-20 11:17:02 +0100663 eglBase =
664 EglBase.createEgl14((EglBase14.Context) getEglContext(), EglBase.CONFIG_RECORDABLE);
perkj30e91822015-11-20 01:31:25 -0800665 // Create an input surface and keep a reference since we must release the surface when done.
666 inputSurface = mediaCodec.createInputSurface();
667 eglBase.createSurface(inputSurface);
668 drawer = new GlRectDrawer();
669 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000670 mediaCodec.start();
671 outputBuffers = mediaCodec.getOutputBuffers();
perkj9576e542015-11-12 06:43:16 -0800672 Logging.d(TAG, "Output buffers: " + outputBuffers.length);
673
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000674 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700675 Logging.e(TAG, "initEncode failed", e);
sakal996a83c2017-03-15 05:53:14 -0700676 release();
perkj9576e542015-11-12 06:43:16 -0800677 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000678 }
perkj9576e542015-11-12 06:43:16 -0800679 return true;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000680 }
681
Magnus Jedvert655e1962017-12-08 11:05:22 +0100682 @CalledByNativeUnchecked
sakalb6760f92016-09-29 04:12:44 -0700683 ByteBuffer[] getInputBuffers() {
perkj9576e542015-11-12 06:43:16 -0800684 ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
685 Logging.d(TAG, "Input buffers: " + inputBuffers.length);
686 return inputBuffers;
687 }
688
Alex Glaznevc7483a72017-01-05 15:22:24 -0800689 void checkKeyFrameRequired(boolean requestedKeyFrame, long presentationTimestampUs) {
690 long presentationTimestampMs = (presentationTimestampUs + 500) / 1000;
691 if (lastKeyFrameMs < 0) {
692 lastKeyFrameMs = presentationTimestampMs;
693 }
694 boolean forcedKeyFrame = false;
695 if (!requestedKeyFrame && forcedKeyFrameMs > 0
696 && presentationTimestampMs > lastKeyFrameMs + forcedKeyFrameMs) {
697 forcedKeyFrame = true;
698 }
699 if (requestedKeyFrame || forcedKeyFrame) {
700 // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could
701 // indicate this in queueInputBuffer() below and guarantee _this_ frame
702 // be encoded as a key frame, but sadly that flag is ignored. Instead,
703 // we request a key frame "soon".
704 if (requestedKeyFrame) {
705 Logging.d(TAG, "Sync frame request");
706 } else {
707 Logging.d(TAG, "Sync frame forced");
708 }
709 Bundle b = new Bundle();
710 b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0);
711 mediaCodec.setParameters(b);
712 lastKeyFrameMs = presentationTimestampMs;
713 }
714 }
715
Magnus Jedvert655e1962017-12-08 11:05:22 +0100716 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800717 boolean encodeBuffer(
sakalb6760f92016-09-29 04:12:44 -0700718 boolean isKeyframe, int inputBuffer, int size, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000719 checkOnMediaCodecThread();
720 try {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800721 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
sakalb6760f92016-09-29 04:12:44 -0700722 mediaCodec.queueInputBuffer(inputBuffer, 0, size, presentationTimestampUs, 0);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000723 return true;
sakalb6760f92016-09-29 04:12:44 -0700724 } catch (IllegalStateException e) {
perkj9576e542015-11-12 06:43:16 -0800725 Logging.e(TAG, "encodeBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000726 return false;
727 }
728 }
729
sakalb5f5bdc2017-08-10 04:15:42 -0700730 /**
Magnus Jedvert655e1962017-12-08 11:05:22 +0100731 * Encodes a new style VideoFrame. |bufferIndex| is -1 if we are not encoding in surface mode.
sakalb5f5bdc2017-08-10 04:15:42 -0700732 */
Magnus Jedvert655e1962017-12-08 11:05:22 +0100733 @CalledByNativeUnchecked
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100734 boolean encodeFrame(long nativeEncoder, boolean isKeyframe, VideoFrame frame, int bufferIndex,
735 long presentationTimestampUs) {
sakalb5f5bdc2017-08-10 04:15:42 -0700736 checkOnMediaCodecThread();
737 try {
sakalb5f5bdc2017-08-10 04:15:42 -0700738 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
739
740 VideoFrame.Buffer buffer = frame.getBuffer();
741 if (buffer instanceof VideoFrame.TextureBuffer) {
742 VideoFrame.TextureBuffer textureBuffer = (VideoFrame.TextureBuffer) buffer;
743 eglBase.makeCurrent();
744 // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway,
745 // but it's a workaround for bug webrtc:5147.
746 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700747 VideoFrameDrawer.drawTexture(drawer, textureBuffer, new Matrix() /* renderMatrix */, width,
sakal9bc599f2017-09-08 04:46:33 -0700748 height, 0 /* viewportX */, 0 /* viewportY */, width, height);
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100749 eglBase.swapBuffers(TimeUnit.MICROSECONDS.toNanos(presentationTimestampUs));
sakalb5f5bdc2017-08-10 04:15:42 -0700750 } else {
751 VideoFrame.I420Buffer i420Buffer = buffer.toI420();
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200752 final int chromaHeight = (height + 1) / 2;
753 final ByteBuffer dataY = i420Buffer.getDataY();
754 final ByteBuffer dataU = i420Buffer.getDataU();
755 final ByteBuffer dataV = i420Buffer.getDataV();
756 final int strideY = i420Buffer.getStrideY();
757 final int strideU = i420Buffer.getStrideU();
758 final int strideV = i420Buffer.getStrideV();
759 if (dataY.capacity() < strideY * height) {
760 throw new RuntimeException("Y-plane buffer size too small.");
761 }
762 if (dataU.capacity() < strideU * chromaHeight) {
763 throw new RuntimeException("U-plane buffer size too small.");
764 }
765 if (dataV.capacity() < strideV * chromaHeight) {
766 throw new RuntimeException("V-plane buffer size too small.");
767 }
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100768 nativeFillInputBuffer(
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200769 nativeEncoder, bufferIndex, dataY, strideY, dataU, strideU, dataV, strideV);
sakalb5f5bdc2017-08-10 04:15:42 -0700770 i420Buffer.release();
771 // I420 consists of one full-resolution and two half-resolution planes.
772 // 1 + 1 / 4 + 1 / 4 = 3 / 2
773 int yuvSize = width * height * 3 / 2;
774 mediaCodec.queueInputBuffer(bufferIndex, 0, yuvSize, presentationTimestampUs, 0);
775 }
776 return true;
777 } catch (RuntimeException e) {
778 Logging.e(TAG, "encodeFrame failed", e);
779 return false;
780 }
781 }
782
Magnus Jedvert655e1962017-12-08 11:05:22 +0100783 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800784 void release() {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700785 Logging.d(TAG, "Java releaseEncoder");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000786 checkOnMediaCodecThread();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700787
sakal996a83c2017-03-15 05:53:14 -0700788 class CaughtException {
789 Exception e;
790 }
791 final CaughtException caughtException = new CaughtException();
792 boolean stopHung = false;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700793
sakal996a83c2017-03-15 05:53:14 -0700794 if (mediaCodec != null) {
795 // Run Mediacodec stop() and release() on separate thread since sometime
796 // Mediacodec.stop() may hang.
797 final CountDownLatch releaseDone = new CountDownLatch(1);
798
799 Runnable runMediaCodecRelease = new Runnable() {
800 @Override
801 public void run() {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700802 Logging.d(TAG, "Java releaseEncoder on release thread");
sakal996a83c2017-03-15 05:53:14 -0700803 try {
804 mediaCodec.stop();
805 } catch (Exception e) {
806 Logging.e(TAG, "Media encoder stop failed", e);
807 }
808 try {
809 mediaCodec.release();
810 } catch (Exception e) {
811 Logging.e(TAG, "Media encoder release failed", e);
812 caughtException.e = e;
813 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700814 Logging.d(TAG, "Java releaseEncoder on release thread done");
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700815
sakal996a83c2017-03-15 05:53:14 -0700816 releaseDone.countDown();
817 }
818 };
819 new Thread(runMediaCodecRelease).start();
820
821 if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) {
822 Logging.e(TAG, "Media encoder release timeout");
823 stopHung = true;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700824 }
sakal996a83c2017-03-15 05:53:14 -0700825
826 mediaCodec = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000827 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700828
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000829 mediaCodecThread = null;
perkj30e91822015-11-20 01:31:25 -0800830 if (drawer != null) {
831 drawer.release();
832 drawer = null;
833 }
834 if (eglBase != null) {
835 eglBase.release();
836 eglBase = null;
837 }
838 if (inputSurface != null) {
839 inputSurface.release();
840 inputSurface = null;
841 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700842 runningInstance = null;
sakal996a83c2017-03-15 05:53:14 -0700843
844 if (stopHung) {
845 codecErrors++;
846 if (errorCallback != null) {
847 Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors);
848 errorCallback.onMediaCodecVideoEncoderCriticalError(codecErrors);
849 }
850 throw new RuntimeException("Media encoder release timeout.");
851 }
852
853 // Re-throw any runtime exception caught inside the other thread. Since this is an invoke, add
854 // stack trace for the waiting thread as well.
855 if (caughtException.e != null) {
856 final RuntimeException runtimeException = new RuntimeException(caughtException.e);
857 runtimeException.setStackTrace(ThreadUtils.concatStackTraces(
858 caughtException.e.getStackTrace(), runtimeException.getStackTrace()));
859 throw runtimeException;
860 }
861
Alex Glaznev325d4142015-10-12 14:56:02 -0700862 Logging.d(TAG, "Java releaseEncoder done");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000863 }
864
Magnus Jedvert655e1962017-12-08 11:05:22 +0100865 @CalledByNativeUnchecked
Alex Glaznev269fe752016-05-25 16:17:33 -0700866 private boolean setRates(int kbps, int frameRate) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000867 checkOnMediaCodecThread();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700868
869 int codecBitrateBps = 1000 * kbps;
870 if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
871 bitrateAccumulatorMax = codecBitrateBps / 8.0;
872 if (targetBitrateBps > 0 && codecBitrateBps < targetBitrateBps) {
873 // Rescale the accumulator level if the accumulator max decreases
874 bitrateAccumulator = bitrateAccumulator * codecBitrateBps / targetBitrateBps;
875 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700876 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700877 targetBitrateBps = codecBitrateBps;
878 targetFps = frameRate;
879
880 // Adjust actual encoder bitrate based on bitrate adjustment type.
881 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT && targetFps > 0) {
882 codecBitrateBps = BITRATE_ADJUSTMENT_FPS * targetBitrateBps / targetFps;
sakalb6760f92016-09-29 04:12:44 -0700883 Logging.v(TAG,
884 "setRates: " + kbps + " -> " + (codecBitrateBps / 1000) + " kbps. Fps: " + targetFps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700885 } else if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
sakalb6760f92016-09-29 04:12:44 -0700886 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps + ". ExpScale: "
887 + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700888 if (bitrateAdjustmentScaleExp != 0) {
sakalb6760f92016-09-29 04:12:44 -0700889 codecBitrateBps = (int) (codecBitrateBps * getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700890 }
891 } else {
892 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps);
893 }
894
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000895 try {
896 Bundle params = new Bundle();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700897 params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, codecBitrateBps);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000898 mediaCodec.setParameters(params);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000899 return true;
900 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700901 Logging.e(TAG, "setRates failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000902 return false;
903 }
904 }
905
906 // Dequeue an input buffer and return its index, -1 if no input buffer is
907 // available, or -2 if the codec is no longer operative.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100908 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800909 int dequeueInputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000910 checkOnMediaCodecThread();
911 try {
912 return mediaCodec.dequeueInputBuffer(DEQUEUE_TIMEOUT);
913 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700914 Logging.e(TAG, "dequeueIntputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000915 return -2;
916 }
917 }
918
919 // Helper struct for dequeueOutputBuffer() below.
perkj9576e542015-11-12 06:43:16 -0800920 static class OutputBufferInfo {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000921 public OutputBufferInfo(
sakalb6760f92016-09-29 04:12:44 -0700922 int index, ByteBuffer buffer, boolean isKeyFrame, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000923 this.index = index;
924 this.buffer = buffer;
925 this.isKeyFrame = isKeyFrame;
926 this.presentationTimestampUs = presentationTimestampUs;
927 }
928
perkj9576e542015-11-12 06:43:16 -0800929 public final int index;
930 public final ByteBuffer buffer;
931 public final boolean isKeyFrame;
932 public final long presentationTimestampUs;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100933
934 @CalledByNative("OutputBufferInfo")
935 int getIndex() {
936 return index;
937 }
938
939 @CalledByNative("OutputBufferInfo")
940 ByteBuffer getBuffer() {
941 return buffer;
942 }
943
944 @CalledByNative("OutputBufferInfo")
945 boolean isKeyFrame() {
946 return isKeyFrame;
947 }
948
949 @CalledByNative("OutputBufferInfo")
950 long getPresentationTimestampUs() {
951 return presentationTimestampUs;
952 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000953 }
954
955 // Dequeue and return an output buffer, or null if no output is ready. Return
956 // a fake OutputBufferInfo with index -1 if the codec is no longer operable.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100957 @Nullable
Magnus Jedvert655e1962017-12-08 11:05:22 +0100958 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800959 OutputBufferInfo dequeueOutputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000960 checkOnMediaCodecThread();
961 try {
962 MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
963 int result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000964 // Check if this is config frame and save configuration data.
965 if (result >= 0) {
sakalb6760f92016-09-29 04:12:44 -0700966 boolean isConfigFrame = (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000967 if (isConfigFrame) {
sakalb6760f92016-09-29 04:12:44 -0700968 Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000969 configData = ByteBuffer.allocateDirect(info.size);
970 outputBuffers[result].position(info.offset);
971 outputBuffers[result].limit(info.offset + info.size);
972 configData.put(outputBuffers[result]);
glaznev3fc23502017-06-15 16:24:37 -0700973 // Log few SPS header bytes to check profile and level.
974 String spsData = "";
975 for (int i = 0; i < (info.size < 8 ? info.size : 8); i++) {
976 spsData += Integer.toHexString(configData.get(i) & 0xff) + " ";
977 }
978 Logging.d(TAG, spsData);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000979 // Release buffer back.
980 mediaCodec.releaseOutputBuffer(result, false);
981 // Query next output.
982 result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
983 }
984 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000985 if (result >= 0) {
986 // MediaCodec doesn't care about Buffer position/remaining/etc so we can
987 // mess with them to get a slice and avoid having to pass extra
988 // (BufferInfo-related) parameters back to C++.
989 ByteBuffer outputBuffer = outputBuffers[result].duplicate();
990 outputBuffer.position(info.offset);
991 outputBuffer.limit(info.offset + info.size);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700992 reportEncodedFrame(info.size);
993
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000994 // Check key frame flag.
sakalb6760f92016-09-29 04:12:44 -0700995 boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0;
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000996 if (isKeyFrame) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700997 Logging.d(TAG, "Sync frame generated");
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000998 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000999 if (isKeyFrame && type == VideoCodecType.VIDEO_CODEC_H264) {
sakalb6760f92016-09-29 04:12:44 -07001000 Logging.d(TAG, "Appending config frame of size " + configData.capacity()
1001 + " to output buffer with offset " + info.offset + ", size " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001002 // For H.264 key frame append SPS and PPS NALs at the start
sakalb6760f92016-09-29 04:12:44 -07001003 ByteBuffer keyFrameBuffer = ByteBuffer.allocateDirect(configData.capacity() + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001004 configData.rewind();
1005 keyFrameBuffer.put(configData);
1006 keyFrameBuffer.put(outputBuffer);
1007 keyFrameBuffer.position(0);
sakalb6760f92016-09-29 04:12:44 -07001008 return new OutputBufferInfo(result, keyFrameBuffer, isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001009 } else {
sakalb6760f92016-09-29 04:12:44 -07001010 return new OutputBufferInfo(
1011 result, outputBuffer.slice(), isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001012 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001013 } else if (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
1014 outputBuffers = mediaCodec.getOutputBuffers();
1015 return dequeueOutputBuffer();
1016 } else if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
1017 return dequeueOutputBuffer();
1018 } else if (result == MediaCodec.INFO_TRY_AGAIN_LATER) {
1019 return null;
1020 }
1021 throw new RuntimeException("dequeueOutputBuffer: " + result);
1022 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -07001023 Logging.e(TAG, "dequeueOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001024 return new OutputBufferInfo(-1, null, false, -1);
1025 }
1026 }
1027
Alex Glaznevcfaca032016-09-06 14:08:19 -07001028 private double getBitrateScale(int bitrateAdjustmentScaleExp) {
1029 return Math.pow(BITRATE_CORRECTION_MAX_SCALE,
sakalb6760f92016-09-29 04:12:44 -07001030 (double) bitrateAdjustmentScaleExp / BITRATE_CORRECTION_STEPS);
Alex Glaznevcfaca032016-09-06 14:08:19 -07001031 }
1032
1033 private void reportEncodedFrame(int size) {
1034 if (targetFps == 0 || bitrateAdjustmentType != BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
1035 return;
1036 }
1037
1038 // Accumulate the difference between actial and expected frame sizes.
1039 double expectedBytesPerFrame = targetBitrateBps / (8.0 * targetFps);
1040 bitrateAccumulator += (size - expectedBytesPerFrame);
1041 bitrateObservationTimeMs += 1000.0 / targetFps;
1042
1043 // Put a cap on the accumulator, i.e., don't let it grow beyond some level to avoid
1044 // using too old data for bitrate adjustment.
1045 double bitrateAccumulatorCap = BITRATE_CORRECTION_SEC * bitrateAccumulatorMax;
1046 bitrateAccumulator = Math.min(bitrateAccumulator, bitrateAccumulatorCap);
1047 bitrateAccumulator = Math.max(bitrateAccumulator, -bitrateAccumulatorCap);
1048
1049 // Do bitrate adjustment every 3 seconds if actual encoder bitrate deviates too much
1050 // form the target value.
1051 if (bitrateObservationTimeMs > 1000 * BITRATE_CORRECTION_SEC) {
sakalb6760f92016-09-29 04:12:44 -07001052 Logging.d(TAG, "Acc: " + (int) bitrateAccumulator + ". Max: " + (int) bitrateAccumulatorMax
1053 + ". ExpScale: " + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -07001054 boolean bitrateAdjustmentScaleChanged = false;
1055 if (bitrateAccumulator > bitrateAccumulatorMax) {
1056 // Encoder generates too high bitrate - need to reduce the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -08001057 int bitrateAdjustmentInc = (int) (bitrateAccumulator / bitrateAccumulatorMax + 0.5);
1058 bitrateAdjustmentScaleExp -= bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001059 bitrateAccumulator = bitrateAccumulatorMax;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001060 bitrateAdjustmentScaleChanged = true;
1061 } else if (bitrateAccumulator < -bitrateAccumulatorMax) {
1062 // Encoder generates too low bitrate - need to increase the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -08001063 int bitrateAdjustmentInc = (int) (-bitrateAccumulator / bitrateAccumulatorMax + 0.5);
1064 bitrateAdjustmentScaleExp += bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001065 bitrateAccumulator = -bitrateAccumulatorMax;
1066 bitrateAdjustmentScaleChanged = true;
1067 }
1068 if (bitrateAdjustmentScaleChanged) {
1069 bitrateAdjustmentScaleExp = Math.min(bitrateAdjustmentScaleExp, BITRATE_CORRECTION_STEPS);
1070 bitrateAdjustmentScaleExp = Math.max(bitrateAdjustmentScaleExp, -BITRATE_CORRECTION_STEPS);
sakalb6760f92016-09-29 04:12:44 -07001071 Logging.d(TAG, "Adjusting bitrate scale to " + bitrateAdjustmentScaleExp + ". Value: "
1072 + getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -07001073 setRates(targetBitrateBps / 1000, targetFps);
1074 }
1075 bitrateObservationTimeMs = 0;
1076 }
1077 }
1078
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001079 // Release a dequeued output buffer back to the codec for re-use. Return
1080 // false if the codec is no longer operable.
Magnus Jedvert655e1962017-12-08 11:05:22 +01001081 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -08001082 boolean releaseOutputBuffer(int index) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001083 checkOnMediaCodecThread();
1084 try {
1085 mediaCodec.releaseOutputBuffer(index, false);
1086 return true;
1087 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -07001088 Logging.e(TAG, "releaseOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001089 return false;
1090 }
1091 }
sakalb5f5bdc2017-08-10 04:15:42 -07001092
Magnus Jedvert655e1962017-12-08 11:05:22 +01001093 @CalledByNative
1094 int getColorFormat() {
1095 return colorFormat;
1096 }
1097
1098 @CalledByNative
1099 static boolean isTextureBuffer(VideoFrame.Buffer buffer) {
1100 return buffer instanceof VideoFrame.TextureBuffer;
1101 }
1102
sakalb5f5bdc2017-08-10 04:15:42 -07001103 /** Fills an inputBuffer with the given index with data from the byte buffers. */
Magnus Jedvert84d8ae52017-12-20 15:12:10 +01001104 private static native void nativeFillInputBuffer(long encoder, int inputBuffer, ByteBuffer dataY,
1105 int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV);
Magnus Jedverte26ff4b2018-07-13 16:09:20 +02001106 private static native long nativeCreateEncoder(VideoCodecInfo info, boolean hasEgl14Context);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001107}