blob: 5f5d44b581a8945b16df4fdb771784440a58f907 [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,
Danil Chapovalov26762d02019-12-20 13:48:51 +0100143 VIDEO_CODEC_AV1,
Magnus Jedvert655e1962017-12-08 11:05:22 +0100144 VIDEO_CODEC_H264;
145
146 @CalledByNative("VideoCodecType")
147 static VideoCodecType fromNativeIndex(int nativeIndex) {
148 return values()[nativeIndex];
149 }
150 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000151
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700152 private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; // Timeout for codec releasing.
sakalb6760f92016-09-29 04:12:44 -0700153 private static final int DEQUEUE_TIMEOUT = 0; // Non-blocking, no wait.
Alex Glaznev269fe752016-05-25 16:17:33 -0700154 private static final int BITRATE_ADJUSTMENT_FPS = 30;
Alex Glaznevc55c39d2016-09-02 12:16:27 -0700155 private static final int MAXIMUM_INITIAL_FPS = 30;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700156 private static final double BITRATE_CORRECTION_SEC = 3.0;
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800157 // Maximum bitrate correction scale - no more than 4 times.
158 private static final double BITRATE_CORRECTION_MAX_SCALE = 4;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700159 // Amount of correction steps to reach correction maximum scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -0800160 private static final int BITRATE_CORRECTION_STEPS = 20;
Alex Glaznevc7483a72017-01-05 15:22:24 -0800161 // Forced key frame interval - used to reduce color distortions on Qualcomm platform.
alexlau84ee5c62017-06-02 17:36:32 -0700162 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS = 15000;
163 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS = 20000;
Alex Glaznevc7483a72017-01-05 15:22:24 -0800164 private static final long QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS = 15000;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700165
perkj9576e542015-11-12 06:43:16 -0800166 // Active running encoder instance. Set in initEncode() (called from native code)
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700167 // and reset to null in release() call.
Sami Kalliomäki3d50a312018-09-11 11:11:47 +0200168 @Nullable private static MediaCodecVideoEncoder runningInstance;
169 @Nullable private static MediaCodecVideoEncoderErrorCallback errorCallback;
170 private static int codecErrors;
Alex Glazneveee86a62016-01-29 14:17:07 -0800171 // List of disabled codec types - can be set from application.
172 private static Set<String> hwEncoderDisabledTypes = new HashSet<String>();
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200173 @Nullable private static EglBase staticEglBase;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700174
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100175 @Nullable private Thread mediaCodecThread;
176 @Nullable private MediaCodec mediaCodec;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000177 private ByteBuffer[] outputBuffers;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100178 @Nullable private EglBase14 eglBase;
glaznev3fc23502017-06-15 16:24:37 -0700179 private int profile;
Magnus Jedvert51254332015-12-15 16:22:29 +0100180 private int width;
181 private int height;
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100182 @Nullable private Surface inputSurface;
183 @Nullable private GlRectDrawer drawer;
Alex Glaznev269fe752016-05-25 16:17:33 -0700184
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000185 private static final String VP8_MIME_TYPE = "video/x-vnd.on2.vp8";
Alex Glaznevad948c42015-11-18 13:06:42 -0800186 private static final String VP9_MIME_TYPE = "video/x-vnd.on2.vp9";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000187 private static final String H264_MIME_TYPE = "video/avc";
Alex Glaznev269fe752016-05-25 16:17:33 -0700188
glaznev3fc23502017-06-15 16:24:37 -0700189 private static final int VIDEO_AVCProfileHigh = 8;
190 private static final int VIDEO_AVCLevel3 = 0x100;
191
Alex Glaznevcfaca032016-09-06 14:08:19 -0700192 // Type of bitrate adjustment for video encoder.
193 public enum BitrateAdjustmentType {
194 // No adjustment - video encoder has no known bitrate problem.
195 NO_ADJUSTMENT,
196 // Framerate based bitrate adjustment is required - HW encoder does not use frame
197 // timestamps to calculate frame bitrate budget and instead is relying on initial
198 // fps configuration assuming that all frames are coming at fixed initial frame rate.
199 FRAMERATE_ADJUSTMENT,
200 // Dynamic bitrate adjustment is required - HW encoder used frame timestamps, but actual
201 // bitrate deviates too much from the target value.
202 DYNAMIC_ADJUSTMENT
203 }
204
glaznev3fc23502017-06-15 16:24:37 -0700205 // Should be in sync with webrtc::H264::Profile.
206 public static enum H264Profile {
207 CONSTRAINED_BASELINE(0),
208 BASELINE(1),
209 MAIN(2),
210 CONSTRAINED_HIGH(3),
211 HIGH(4);
212
213 private final int value;
214
215 H264Profile(int value) {
216 this.value = value;
217 }
218
219 public int getValue() {
220 return value;
221 }
222 }
223
Alex Glaznev269fe752016-05-25 16:17:33 -0700224 // Class describing supported media codec properties.
225 private static class MediaCodecProperties {
226 public final String codecPrefix;
227 // Minimum Android SDK required for this codec to be used.
228 public final int minSdk;
229 // Flag if encoder implementation does not use frame timestamps to calculate frame bitrate
230 // budget and instead is relying on initial fps configuration assuming that all frames are
231 // coming at fixed initial frame rate. Bitrate adjustment is required for this case.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700232 public final BitrateAdjustmentType bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700233
234 MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700235 String codecPrefix, int minSdk, BitrateAdjustmentType bitrateAdjustmentType) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700236 this.codecPrefix = codecPrefix;
237 this.minSdk = minSdk;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700238 this.bitrateAdjustmentType = bitrateAdjustmentType;
Alex Glaznev269fe752016-05-25 16:17:33 -0700239 }
240 }
241
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200242 /**
243 * Set EGL context used by HW encoding. The EGL context must be shared with the video capturer
244 * and any local render.
245 */
246 public static void setEglContext(EglBase.Context eglContext) {
247 if (staticEglBase != null) {
248 Logging.w(TAG, "Egl context already set.");
249 staticEglBase.release();
250 }
251 staticEglBase = EglBase.create(eglContext);
252 }
253
254 /** Dispose the EGL context used by HW encoding. */
255 public static void disposeEglContext() {
256 if (staticEglBase != null) {
257 staticEglBase.release();
258 staticEglBase = null;
259 }
260 }
261
262 @Nullable
263 static EglBase.Context getEglContext() {
264 return staticEglBase == null ? null : staticEglBase.getEglBaseContext();
265 }
266
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700267 // List of supported HW VP8 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700268 private static final MediaCodecProperties qcomVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700269 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700270 private static final MediaCodecProperties exynosVp8HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700271 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.DYNAMIC_ADJUSTMENT);
magjed295760d2017-01-12 01:11:57 -0800272 private static final MediaCodecProperties intelVp8HwProperties = new MediaCodecProperties(
273 "OMX.Intel.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.NO_ADJUSTMENT);
274 private static MediaCodecProperties[] vp8HwList() {
275 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
276 supported_codecs.add(qcomVp8HwProperties);
277 supported_codecs.add(exynosVp8HwProperties);
278 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-IntelVP8").equals("Enabled")) {
279 supported_codecs.add(intelVp8HwProperties);
280 }
281 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
282 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700283
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700284 // List of supported HW VP9 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700285 private static final MediaCodecProperties qcomVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700286 "OMX.qcom.", Build.VERSION_CODES.N, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700287 private static final MediaCodecProperties exynosVp9HwProperties = new MediaCodecProperties(
glaznev6fac4292017-06-02 20:18:54 -0700288 "OMX.Exynos.", Build.VERSION_CODES.N, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
sakalb6760f92016-09-29 04:12:44 -0700289 private static final MediaCodecProperties[] vp9HwList =
290 new MediaCodecProperties[] {qcomVp9HwProperties, exynosVp9HwProperties};
Alex Glaznev269fe752016-05-25 16:17:33 -0700291
Alex Glaznevdcd730f2016-04-21 17:01:46 -0700292 // List of supported HW H.264 encoders.
Alex Glaznev269fe752016-05-25 16:17:33 -0700293 private static final MediaCodecProperties qcomH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700294 "OMX.qcom.", Build.VERSION_CODES.KITKAT, BitrateAdjustmentType.NO_ADJUSTMENT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700295 private static final MediaCodecProperties exynosH264HwProperties = new MediaCodecProperties(
Alex Glaznevcfaca032016-09-06 14:08:19 -0700296 "OMX.Exynos.", Build.VERSION_CODES.LOLLIPOP, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
Alex Leung5b6891a2018-01-18 10:01:14 -0800297 private static final MediaCodecProperties mediatekH264HwProperties = new MediaCodecProperties(
Alex Leung28e71072018-02-05 13:42:48 -0800298 "OMX.MTK.", Build.VERSION_CODES.O_MR1, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
Alex Leung5b6891a2018-01-18 10:01:14 -0800299 private static final MediaCodecProperties[] h264HwList() {
300 final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
301 supported_codecs.add(qcomH264HwProperties);
302 supported_codecs.add(exynosH264HwProperties);
303 if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekH264").equals("Enabled")) {
304 supported_codecs.add(mediatekH264HwProperties);
305 }
306 return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
307 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700308
glaznev3fc23502017-06-15 16:24:37 -0700309 // List of supported HW H.264 high profile encoders.
310 private static final MediaCodecProperties exynosH264HighProfileHwProperties =
311 new MediaCodecProperties(
312 "OMX.Exynos.", Build.VERSION_CODES.M, BitrateAdjustmentType.FRAMERATE_ADJUSTMENT);
313 private static final MediaCodecProperties[] h264HighProfileHwList =
314 new MediaCodecProperties[] {exynosH264HighProfileHwProperties};
315
Alex Glaznev0c850202015-08-04 10:26:59 -0700316 // List of devices with poor H.264 encoder quality.
sakalb6760f92016-09-29 04:12:44 -0700317 // HW H.264 encoder on below devices has poor bitrate control - actual
318 // bitrates deviates a lot from the target value.
319 private static final String[] H264_HW_EXCEPTION_MODELS =
320 new String[] {"SAMSUNG-SGH-I337", "Nexus 7", "Nexus 4"};
Alex Glaznev0c850202015-08-04 10:26:59 -0700321
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000322 // Bitrate modes - should be in sync with OMX_VIDEO_CONTROLRATETYPE defined
323 // in OMX_Video.h
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000324 private static final int VIDEO_ControlRateConstant = 2;
325 // NV12 color format supported by QCOM codec, but not declared in MediaCodec -
326 // see /hardware/qcom/media/mm-core/inc/OMX_QCOMExtns.h
sakalb6760f92016-09-29 04:12:44 -0700327 private static final int COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m = 0x7FA30C04;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000328 // Allowable color formats supported by codec - in order of preference.
sakalb6760f92016-09-29 04:12:44 -0700329 private static final int[] supportedColorList = {CodecCapabilities.COLOR_FormatYUV420Planar,
330 CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
331 CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
332 COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m};
333 private static final int[] supportedSurfaceColorList = {CodecCapabilities.COLOR_FormatSurface};
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000334 private VideoCodecType type;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100335 private int colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700336
337 // Variables used for dynamic bitrate adjustment.
338 private BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
339 private double bitrateAccumulator;
340 private double bitrateAccumulatorMax;
341 private double bitrateObservationTimeMs;
342 private int bitrateAdjustmentScaleExp;
343 private int targetBitrateBps;
344 private int targetFps;
perkj9576e542015-11-12 06:43:16 -0800345
Alex Glaznevc7483a72017-01-05 15:22:24 -0800346 // Interval in ms to force key frame generation. Used to reduce the time of color distortions
347 // happened sometime when using Qualcomm video encoder.
348 private long forcedKeyFrameMs;
349 private long lastKeyFrameMs;
350
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000351 // SPS and PPS NALs (Config frame) for H.264.
Sami Kalliomäki3d50a312018-09-11 11:11:47 +0200352 @Nullable private ByteBuffer configData;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000353
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700354 // MediaCodec error handler - invoked when critical error happens which may prevent
355 // further use of media codec API. Now it means that one of media codec instances
356 // is hanging and can no longer be used in the next call.
357 public static interface MediaCodecVideoEncoderErrorCallback {
358 void onMediaCodecVideoEncoderCriticalError(int codecErrors);
359 }
360
361 public static void setErrorCallback(MediaCodecVideoEncoderErrorCallback errorCallback) {
362 Logging.d(TAG, "Set error callback");
363 MediaCodecVideoEncoder.errorCallback = errorCallback;
364 }
365
Alex Glazneveee86a62016-01-29 14:17:07 -0800366 // Functions to disable HW encoding - can be called from applications for platforms
367 // which have known HW decoding problems.
368 public static void disableVp8HwCodec() {
369 Logging.w(TAG, "VP8 encoding is disabled by application.");
370 hwEncoderDisabledTypes.add(VP8_MIME_TYPE);
371 }
372
373 public static void disableVp9HwCodec() {
374 Logging.w(TAG, "VP9 encoding is disabled by application.");
375 hwEncoderDisabledTypes.add(VP9_MIME_TYPE);
376 }
377
378 public static void disableH264HwCodec() {
379 Logging.w(TAG, "H.264 encoding is disabled by application.");
380 hwEncoderDisabledTypes.add(H264_MIME_TYPE);
381 }
382
383 // Functions to query if HW encoding is supported.
384 public static boolean isVp8HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700385 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800386 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800387 }
388
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100389 public static @Nullable EncoderProperties vp8HwEncoderProperties() {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800390 if (hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)) {
391 return null;
392 } else {
magjed295760d2017-01-12 01:11:57 -0800393 return findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedColorList);
Alex Glaznevc7483a72017-01-05 15:22:24 -0800394 }
395 }
396
Alex Glazneveee86a62016-01-29 14:17:07 -0800397 public static boolean isVp9HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700398 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
399 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800400 }
401
402 public static boolean isH264HwSupported() {
sakalb6760f92016-09-29 04:12:44 -0700403 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800404 && (findHwEncoder(H264_MIME_TYPE, h264HwList(), supportedColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800405 }
406
glaznev3fc23502017-06-15 16:24:37 -0700407 public static boolean isH264HighProfileHwSupported() {
408 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
409 && (findHwEncoder(H264_MIME_TYPE, h264HighProfileHwList, supportedColorList) != null);
410 }
411
Alex Glazneveee86a62016-01-29 14:17:07 -0800412 public static boolean isVp8HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700413 return !hwEncoderDisabledTypes.contains(VP8_MIME_TYPE)
magjed295760d2017-01-12 01:11:57 -0800414 && (findHwEncoder(VP8_MIME_TYPE, vp8HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800415 }
416
417 public static boolean isVp9HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700418 return !hwEncoderDisabledTypes.contains(VP9_MIME_TYPE)
419 && (findHwEncoder(VP9_MIME_TYPE, vp9HwList, supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800420 }
421
422 public static boolean isH264HwSupportedUsingTextures() {
sakalb6760f92016-09-29 04:12:44 -0700423 return !hwEncoderDisabledTypes.contains(H264_MIME_TYPE)
Alex Leung5b6891a2018-01-18 10:01:14 -0800424 && (findHwEncoder(H264_MIME_TYPE, h264HwList(), supportedSurfaceColorList) != null);
Alex Glazneveee86a62016-01-29 14:17:07 -0800425 }
426
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000427 // Helper struct for findHwEncoder() below.
Alex Glaznevc7483a72017-01-05 15:22:24 -0800428 public static class EncoderProperties {
Alex Glaznevcfaca032016-09-06 14:08:19 -0700429 public EncoderProperties(
430 String codecName, int colorFormat, BitrateAdjustmentType bitrateAdjustmentType) {
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000431 this.codecName = codecName;
432 this.colorFormat = colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700433 this.bitrateAdjustmentType = bitrateAdjustmentType;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000434 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000435 public final String codecName; // OpenMax component name for HW codec.
sakalb6760f92016-09-29 04:12:44 -0700436 public final int colorFormat; // Color format supported by codec.
Alex Glaznevcfaca032016-09-06 14:08:19 -0700437 public final BitrateAdjustmentType bitrateAdjustmentType; // Bitrate adjustment type
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000438 }
439
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100440 private static @Nullable EncoderProperties findHwEncoder(
Alex Glaznev269fe752016-05-25 16:17:33 -0700441 String mime, MediaCodecProperties[] supportedHwCodecProperties, int[] colorList) {
Alex Glaznev0c850202015-08-04 10:26:59 -0700442 // MediaCodec.setParameters is missing for JB and below, so bitrate
443 // can not be adjusted dynamically.
444 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
445 return null;
446 }
447
448 // Check if device is in H.264 exception list.
449 if (mime.equals(H264_MIME_TYPE)) {
450 List<String> exceptionModels = Arrays.asList(H264_HW_EXCEPTION_MODELS);
451 if (exceptionModels.contains(Build.MODEL)) {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700452 Logging.w(TAG, "Model: " + Build.MODEL + " has black listed H.264 encoder.");
Alex Glaznev0c850202015-08-04 10:26:59 -0700453 return null;
454 }
455 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000456
457 for (int i = 0; i < MediaCodecList.getCodecCount(); ++i) {
Alex Glaznev0060c562016-08-08 12:27:24 -0700458 MediaCodecInfo info = null;
459 try {
460 info = MediaCodecList.getCodecInfoAt(i);
461 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700462 Logging.e(TAG, "Cannot retrieve encoder codec info", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700463 }
464 if (info == null || !info.isEncoder()) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000465 continue;
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000466 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000467 String name = null;
468 for (String mimeType : info.getSupportedTypes()) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000469 if (mimeType.equals(mime)) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000470 name = info.getName();
471 break;
472 }
473 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000474 if (name == null) {
sakalb6760f92016-09-29 04:12:44 -0700475 continue; // No HW support in this codec; try the next one.
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000476 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700477 Logging.v(TAG, "Found candidate encoder " + name);
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000478
479 // Check if this is supported HW encoder.
480 boolean supportedCodec = false;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700481 BitrateAdjustmentType bitrateAdjustmentType = BitrateAdjustmentType.NO_ADJUSTMENT;
Alex Glaznev269fe752016-05-25 16:17:33 -0700482 for (MediaCodecProperties codecProperties : supportedHwCodecProperties) {
483 if (name.startsWith(codecProperties.codecPrefix)) {
484 if (Build.VERSION.SDK_INT < codecProperties.minSdk) {
sakalb6760f92016-09-29 04:12:44 -0700485 Logging.w(
486 TAG, "Codec " + name + " is disabled due to SDK version " + Build.VERSION.SDK_INT);
Alex Glaznev269fe752016-05-25 16:17:33 -0700487 continue;
488 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700489 if (codecProperties.bitrateAdjustmentType != BitrateAdjustmentType.NO_ADJUSTMENT) {
490 bitrateAdjustmentType = codecProperties.bitrateAdjustmentType;
sakalb6760f92016-09-29 04:12:44 -0700491 Logging.w(
492 TAG, "Codec " + name + " requires bitrate adjustment: " + bitrateAdjustmentType);
Alex Glaznev269fe752016-05-25 16:17:33 -0700493 }
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000494 supportedCodec = true;
495 break;
496 }
497 }
498 if (!supportedCodec) {
499 continue;
500 }
501
Alex Glaznev269fe752016-05-25 16:17:33 -0700502 // Check if HW codec supports known color format.
Alex Glaznev0060c562016-08-08 12:27:24 -0700503 CodecCapabilities capabilities;
504 try {
505 capabilities = info.getCapabilitiesForType(mime);
506 } catch (IllegalArgumentException e) {
sakalb6760f92016-09-29 04:12:44 -0700507 Logging.e(TAG, "Cannot retrieve encoder capabilities", e);
Alex Glaznev0060c562016-08-08 12:27:24 -0700508 continue;
509 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000510 for (int colorFormat : capabilities.colorFormats) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700511 Logging.v(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000512 }
513
perkj30e91822015-11-20 01:31:25 -0800514 for (int supportedColorFormat : colorList) {
glaznev@webrtc.org99678452014-09-15 17:52:42 +0000515 for (int codecColorFormat : capabilities.colorFormats) {
516 if (codecColorFormat == supportedColorFormat) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000517 // Found supported HW encoder.
sakalb6760f92016-09-29 04:12:44 -0700518 Logging.d(TAG, "Found target encoder for mime " + mime + " : " + name + ". Color: 0x"
519 + Integer.toHexString(codecColorFormat) + ". Bitrate adjustment: "
520 + bitrateAdjustmentType);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700521 return new EncoderProperties(name, codecColorFormat, bitrateAdjustmentType);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000522 }
523 }
524 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000525 }
sakalb6760f92016-09-29 04:12:44 -0700526 return null; // No HW encoder.
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000527 }
528
Magnus Jedvert655e1962017-12-08 11:05:22 +0100529 @CalledByNative
530 MediaCodecVideoEncoder() {}
531
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000532 private void checkOnMediaCodecThread() {
533 if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
sakalb6760f92016-09-29 04:12:44 -0700534 throw new RuntimeException("MediaCodecVideoEncoder previously operated on " + mediaCodecThread
535 + " but is now called on " + Thread.currentThread());
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000536 }
537 }
538
Alex Glaznev325d4142015-10-12 14:56:02 -0700539 public static void printStackTrace() {
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700540 if (runningInstance != null && runningInstance.mediaCodecThread != null) {
541 StackTraceElement[] mediaCodecStackTraces = runningInstance.mediaCodecThread.getStackTrace();
Alex Glaznev325d4142015-10-12 14:56:02 -0700542 if (mediaCodecStackTraces.length > 0) {
543 Logging.d(TAG, "MediaCodecVideoEncoder stacks trace:");
544 for (StackTraceElement stackTrace : mediaCodecStackTraces) {
545 Logging.d(TAG, stackTrace.toString());
546 }
547 }
548 }
549 }
550
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100551 static @Nullable MediaCodec createByCodecName(String codecName) {
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000552 try {
553 // In the L-SDK this call can throw IOException so in order to work in
554 // both cases catch an exception.
555 return MediaCodec.createByCodecName(codecName);
556 } catch (Exception e) {
557 return null;
558 }
559 }
560
Magnus Jedvert655e1962017-12-08 11:05:22 +0100561 @CalledByNativeUnchecked
glaznev3fc23502017-06-15 16:24:37 -0700562 boolean initEncode(VideoCodecType type, int profile, int width, int height, int kbps, int fps,
Magnus Jedvert0f0e7a62018-07-11 14:53:21 +0200563 boolean useSurface) {
glaznev3fc23502017-06-15 16:24:37 -0700564 Logging.d(TAG,
565 "Java initEncode: " + type + ". Profile: " + profile + " : " + width + " x " + height
566 + ". @ " + kbps + " kbps. Fps: " + fps + ". Encode from texture : " + useSurface);
perkj9576e542015-11-12 06:43:16 -0800567
glaznev3fc23502017-06-15 16:24:37 -0700568 this.profile = profile;
Magnus Jedvert51254332015-12-15 16:22:29 +0100569 this.width = width;
570 this.height = height;
Alejandro Luebs69ddaef2015-10-09 15:46:09 -0700571 if (mediaCodecThread != null) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000572 throw new RuntimeException("Forgot to release()?");
573 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000574 EncoderProperties properties = null;
575 String mime = null;
576 int keyFrameIntervalSec = 0;
glaznev3fc23502017-06-15 16:24:37 -0700577 boolean configureH264HighProfile = false;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000578 if (type == VideoCodecType.VIDEO_CODEC_VP8) {
579 mime = VP8_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700580 properties = findHwEncoder(
magjed295760d2017-01-12 01:11:57 -0800581 VP8_MIME_TYPE, vp8HwList(), useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000582 keyFrameIntervalSec = 100;
Alex Glaznevad948c42015-11-18 13:06:42 -0800583 } else if (type == VideoCodecType.VIDEO_CODEC_VP9) {
584 mime = VP9_MIME_TYPE;
Alex Glaznev269fe752016-05-25 16:17:33 -0700585 properties = findHwEncoder(
586 VP9_MIME_TYPE, vp9HwList, useSurface ? supportedSurfaceColorList : supportedColorList);
Alex Glaznevad948c42015-11-18 13:06:42 -0800587 keyFrameIntervalSec = 100;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000588 } else if (type == VideoCodecType.VIDEO_CODEC_H264) {
589 mime = H264_MIME_TYPE;
Alex Leung5b6891a2018-01-18 10:01:14 -0800590 properties = findHwEncoder(H264_MIME_TYPE, h264HwList(),
591 useSurface ? supportedSurfaceColorList : supportedColorList);
glaznev3fc23502017-06-15 16:24:37 -0700592 if (profile == H264Profile.CONSTRAINED_HIGH.getValue()) {
593 EncoderProperties h264HighProfileProperties = findHwEncoder(H264_MIME_TYPE,
594 h264HighProfileHwList, useSurface ? supportedSurfaceColorList : supportedColorList);
595 if (h264HighProfileProperties != null) {
596 Logging.d(TAG, "High profile H.264 encoder supported.");
597 configureH264HighProfile = true;
598 } else {
599 Logging.d(TAG, "High profile H.264 encoder requested, but not supported. Use baseline.");
600 }
601 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000602 keyFrameIntervalSec = 20;
Niels Möller520ca4e2018-06-04 11:14:38 +0200603 } else {
604 throw new RuntimeException("initEncode: Non-supported codec " + type);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000605 }
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000606 if (properties == null) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000607 throw new RuntimeException("Can not find HW encoder for " + type);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000608 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700609 runningInstance = this; // Encoder is now running and can be queried for stack traces.
perkj9576e542015-11-12 06:43:16 -0800610 colorFormat = properties.colorFormat;
Alex Glaznevcfaca032016-09-06 14:08:19 -0700611 bitrateAdjustmentType = properties.bitrateAdjustmentType;
612 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT) {
Alex Glaznev269fe752016-05-25 16:17:33 -0700613 fps = BITRATE_ADJUSTMENT_FPS;
sakalb6760f92016-09-29 04:12:44 -0700614 } else {
Alex Glaznevc55c39d2016-09-02 12:16:27 -0700615 fps = Math.min(fps, MAXIMUM_INITIAL_FPS);
Alex Glaznev269fe752016-05-25 16:17:33 -0700616 }
Alex Glaznevc7483a72017-01-05 15:22:24 -0800617
618 forcedKeyFrameMs = 0;
619 lastKeyFrameMs = -1;
Alex Glaznev512f00b2017-01-05 16:40:46 -0800620 if (type == VideoCodecType.VIDEO_CODEC_VP8
621 && properties.codecName.startsWith(qcomVp8HwProperties.codecPrefix)) {
alexlau84ee5c62017-06-02 17:36:32 -0700622 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP
623 || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
624 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS;
625 } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800626 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS;
627 } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
628 forcedKeyFrameMs = QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS;
629 }
630 }
631
sakalb6760f92016-09-29 04:12:44 -0700632 Logging.d(TAG, "Color format: " + colorFormat + ". Bitrate adjustment: " + bitrateAdjustmentType
Alex Glaznevc7483a72017-01-05 15:22:24 -0800633 + ". Key frame interval: " + forcedKeyFrameMs + " . Initial fps: " + fps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700634 targetBitrateBps = 1000 * kbps;
635 targetFps = fps;
636 bitrateAccumulatorMax = targetBitrateBps / 8.0;
637 bitrateAccumulator = 0;
638 bitrateObservationTimeMs = 0;
639 bitrateAdjustmentScaleExp = 0;
perkj9576e542015-11-12 06:43:16 -0800640
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000641 mediaCodecThread = Thread.currentThread();
642 try {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000643 MediaFormat format = MediaFormat.createVideoFormat(mime, width, height);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700644 format.setInteger(MediaFormat.KEY_BIT_RATE, targetBitrateBps);
Alex Glaznev8a2cd3d2015-08-11 11:32:53 -0700645 format.setInteger("bitrate-mode", VIDEO_ControlRateConstant);
glaznev@webrtc.orga40210a2014-06-10 23:48:29 +0000646 format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700647 format.setInteger(MediaFormat.KEY_FRAME_RATE, targetFps);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000648 format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameIntervalSec);
glaznev3fc23502017-06-15 16:24:37 -0700649 if (configureH264HighProfile) {
650 format.setInteger("profile", VIDEO_AVCProfileHigh);
651 format.setInteger("level", VIDEO_AVCLevel3);
652 }
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700653 Logging.d(TAG, " Format: " + format);
henrike@webrtc.org528fc652014-10-06 17:56:43 +0000654 mediaCodec = createByCodecName(properties.codecName);
perkj9576e542015-11-12 06:43:16 -0800655 this.type = type;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000656 if (mediaCodec == null) {
Alex Glaznev325d4142015-10-12 14:56:02 -0700657 Logging.e(TAG, "Can not create media encoder");
sakal996a83c2017-03-15 05:53:14 -0700658 release();
perkj9576e542015-11-12 06:43:16 -0800659 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000660 }
sakalb6760f92016-09-29 04:12:44 -0700661 mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
perkj9576e542015-11-12 06:43:16 -0800662
perkj30e91822015-11-20 01:31:25 -0800663 if (useSurface) {
Magnus Jedvert98d85fe2019-03-20 11:17:02 +0100664 eglBase =
665 EglBase.createEgl14((EglBase14.Context) getEglContext(), EglBase.CONFIG_RECORDABLE);
perkj30e91822015-11-20 01:31:25 -0800666 // Create an input surface and keep a reference since we must release the surface when done.
667 inputSurface = mediaCodec.createInputSurface();
668 eglBase.createSurface(inputSurface);
669 drawer = new GlRectDrawer();
670 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000671 mediaCodec.start();
672 outputBuffers = mediaCodec.getOutputBuffers();
perkj9576e542015-11-12 06:43:16 -0800673 Logging.d(TAG, "Output buffers: " + outputBuffers.length);
674
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000675 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700676 Logging.e(TAG, "initEncode failed", e);
sakal996a83c2017-03-15 05:53:14 -0700677 release();
perkj9576e542015-11-12 06:43:16 -0800678 return false;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000679 }
perkj9576e542015-11-12 06:43:16 -0800680 return true;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000681 }
682
Magnus Jedvert655e1962017-12-08 11:05:22 +0100683 @CalledByNativeUnchecked
sakalb6760f92016-09-29 04:12:44 -0700684 ByteBuffer[] getInputBuffers() {
perkj9576e542015-11-12 06:43:16 -0800685 ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
686 Logging.d(TAG, "Input buffers: " + inputBuffers.length);
687 return inputBuffers;
688 }
689
Alex Glaznevc7483a72017-01-05 15:22:24 -0800690 void checkKeyFrameRequired(boolean requestedKeyFrame, long presentationTimestampUs) {
691 long presentationTimestampMs = (presentationTimestampUs + 500) / 1000;
692 if (lastKeyFrameMs < 0) {
693 lastKeyFrameMs = presentationTimestampMs;
694 }
695 boolean forcedKeyFrame = false;
696 if (!requestedKeyFrame && forcedKeyFrameMs > 0
697 && presentationTimestampMs > lastKeyFrameMs + forcedKeyFrameMs) {
698 forcedKeyFrame = true;
699 }
700 if (requestedKeyFrame || forcedKeyFrame) {
701 // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could
702 // indicate this in queueInputBuffer() below and guarantee _this_ frame
703 // be encoded as a key frame, but sadly that flag is ignored. Instead,
704 // we request a key frame "soon".
705 if (requestedKeyFrame) {
706 Logging.d(TAG, "Sync frame request");
707 } else {
708 Logging.d(TAG, "Sync frame forced");
709 }
710 Bundle b = new Bundle();
711 b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0);
712 mediaCodec.setParameters(b);
713 lastKeyFrameMs = presentationTimestampMs;
714 }
715 }
716
Magnus Jedvert655e1962017-12-08 11:05:22 +0100717 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800718 boolean encodeBuffer(
sakalb6760f92016-09-29 04:12:44 -0700719 boolean isKeyframe, int inputBuffer, int size, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000720 checkOnMediaCodecThread();
721 try {
Alex Glaznevc7483a72017-01-05 15:22:24 -0800722 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
sakalb6760f92016-09-29 04:12:44 -0700723 mediaCodec.queueInputBuffer(inputBuffer, 0, size, presentationTimestampUs, 0);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000724 return true;
sakalb6760f92016-09-29 04:12:44 -0700725 } catch (IllegalStateException e) {
perkj9576e542015-11-12 06:43:16 -0800726 Logging.e(TAG, "encodeBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000727 return false;
728 }
729 }
730
sakalb5f5bdc2017-08-10 04:15:42 -0700731 /**
Magnus Jedvert655e1962017-12-08 11:05:22 +0100732 * Encodes a new style VideoFrame. |bufferIndex| is -1 if we are not encoding in surface mode.
sakalb5f5bdc2017-08-10 04:15:42 -0700733 */
Magnus Jedvert655e1962017-12-08 11:05:22 +0100734 @CalledByNativeUnchecked
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100735 boolean encodeFrame(long nativeEncoder, boolean isKeyframe, VideoFrame frame, int bufferIndex,
736 long presentationTimestampUs) {
sakalb5f5bdc2017-08-10 04:15:42 -0700737 checkOnMediaCodecThread();
738 try {
sakalb5f5bdc2017-08-10 04:15:42 -0700739 checkKeyFrameRequired(isKeyframe, presentationTimestampUs);
740
741 VideoFrame.Buffer buffer = frame.getBuffer();
742 if (buffer instanceof VideoFrame.TextureBuffer) {
743 VideoFrame.TextureBuffer textureBuffer = (VideoFrame.TextureBuffer) buffer;
744 eglBase.makeCurrent();
745 // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway,
746 // but it's a workaround for bug webrtc:5147.
747 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
magjed7cede372017-09-11 06:12:07 -0700748 VideoFrameDrawer.drawTexture(drawer, textureBuffer, new Matrix() /* renderMatrix */, width,
sakal9bc599f2017-09-08 04:46:33 -0700749 height, 0 /* viewportX */, 0 /* viewportY */, width, height);
Sami Kalliomäkidebbc782018-02-02 10:01:46 +0100750 eglBase.swapBuffers(TimeUnit.MICROSECONDS.toNanos(presentationTimestampUs));
sakalb5f5bdc2017-08-10 04:15:42 -0700751 } else {
752 VideoFrame.I420Buffer i420Buffer = buffer.toI420();
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200753 final int chromaHeight = (height + 1) / 2;
754 final ByteBuffer dataY = i420Buffer.getDataY();
755 final ByteBuffer dataU = i420Buffer.getDataU();
756 final ByteBuffer dataV = i420Buffer.getDataV();
757 final int strideY = i420Buffer.getStrideY();
758 final int strideU = i420Buffer.getStrideU();
759 final int strideV = i420Buffer.getStrideV();
760 if (dataY.capacity() < strideY * height) {
761 throw new RuntimeException("Y-plane buffer size too small.");
762 }
763 if (dataU.capacity() < strideU * chromaHeight) {
764 throw new RuntimeException("U-plane buffer size too small.");
765 }
766 if (dataV.capacity() < strideV * chromaHeight) {
767 throw new RuntimeException("V-plane buffer size too small.");
768 }
Magnus Jedvert84d8ae52017-12-20 15:12:10 +0100769 nativeFillInputBuffer(
Sami Kalliomäkie3044fe2017-10-02 09:41:55 +0200770 nativeEncoder, bufferIndex, dataY, strideY, dataU, strideU, dataV, strideV);
sakalb5f5bdc2017-08-10 04:15:42 -0700771 i420Buffer.release();
772 // I420 consists of one full-resolution and two half-resolution planes.
773 // 1 + 1 / 4 + 1 / 4 = 3 / 2
774 int yuvSize = width * height * 3 / 2;
775 mediaCodec.queueInputBuffer(bufferIndex, 0, yuvSize, presentationTimestampUs, 0);
776 }
777 return true;
778 } catch (RuntimeException e) {
779 Logging.e(TAG, "encodeFrame failed", e);
780 return false;
781 }
782 }
783
Magnus Jedvert655e1962017-12-08 11:05:22 +0100784 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800785 void release() {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700786 Logging.d(TAG, "Java releaseEncoder");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000787 checkOnMediaCodecThread();
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700788
sakal996a83c2017-03-15 05:53:14 -0700789 class CaughtException {
790 Exception e;
791 }
792 final CaughtException caughtException = new CaughtException();
793 boolean stopHung = false;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700794
sakal996a83c2017-03-15 05:53:14 -0700795 if (mediaCodec != null) {
796 // Run Mediacodec stop() and release() on separate thread since sometime
797 // Mediacodec.stop() may hang.
798 final CountDownLatch releaseDone = new CountDownLatch(1);
799
800 Runnable runMediaCodecRelease = new Runnable() {
801 @Override
802 public void run() {
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700803 Logging.d(TAG, "Java releaseEncoder on release thread");
sakal996a83c2017-03-15 05:53:14 -0700804 try {
805 mediaCodec.stop();
806 } catch (Exception e) {
807 Logging.e(TAG, "Media encoder stop failed", e);
808 }
809 try {
810 mediaCodec.release();
811 } catch (Exception e) {
812 Logging.e(TAG, "Media encoder release failed", e);
813 caughtException.e = e;
814 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700815 Logging.d(TAG, "Java releaseEncoder on release thread done");
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700816
sakal996a83c2017-03-15 05:53:14 -0700817 releaseDone.countDown();
818 }
819 };
820 new Thread(runMediaCodecRelease).start();
821
822 if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) {
823 Logging.e(TAG, "Media encoder release timeout");
824 stopHung = true;
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700825 }
sakal996a83c2017-03-15 05:53:14 -0700826
827 mediaCodec = null;
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000828 }
Alex Glaznev5c3da4b2015-10-30 15:31:07 -0700829
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000830 mediaCodecThread = null;
perkj30e91822015-11-20 01:31:25 -0800831 if (drawer != null) {
832 drawer.release();
833 drawer = null;
834 }
835 if (eglBase != null) {
836 eglBase.release();
837 eglBase = null;
838 }
839 if (inputSurface != null) {
840 inputSurface.release();
841 inputSurface = null;
842 }
Alex Glaznevc6aec4b2015-10-19 16:39:19 -0700843 runningInstance = null;
sakal996a83c2017-03-15 05:53:14 -0700844
845 if (stopHung) {
846 codecErrors++;
847 if (errorCallback != null) {
848 Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors);
849 errorCallback.onMediaCodecVideoEncoderCriticalError(codecErrors);
850 }
851 throw new RuntimeException("Media encoder release timeout.");
852 }
853
854 // Re-throw any runtime exception caught inside the other thread. Since this is an invoke, add
855 // stack trace for the waiting thread as well.
856 if (caughtException.e != null) {
857 final RuntimeException runtimeException = new RuntimeException(caughtException.e);
858 runtimeException.setStackTrace(ThreadUtils.concatStackTraces(
859 caughtException.e.getStackTrace(), runtimeException.getStackTrace()));
860 throw runtimeException;
861 }
862
Alex Glaznev325d4142015-10-12 14:56:02 -0700863 Logging.d(TAG, "Java releaseEncoder done");
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000864 }
865
Magnus Jedvert655e1962017-12-08 11:05:22 +0100866 @CalledByNativeUnchecked
Alex Glaznev269fe752016-05-25 16:17:33 -0700867 private boolean setRates(int kbps, int frameRate) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000868 checkOnMediaCodecThread();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700869
870 int codecBitrateBps = 1000 * kbps;
871 if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
872 bitrateAccumulatorMax = codecBitrateBps / 8.0;
873 if (targetBitrateBps > 0 && codecBitrateBps < targetBitrateBps) {
874 // Rescale the accumulator level if the accumulator max decreases
875 bitrateAccumulator = bitrateAccumulator * codecBitrateBps / targetBitrateBps;
876 }
Alex Glaznev269fe752016-05-25 16:17:33 -0700877 }
Alex Glaznevcfaca032016-09-06 14:08:19 -0700878 targetBitrateBps = codecBitrateBps;
879 targetFps = frameRate;
880
881 // Adjust actual encoder bitrate based on bitrate adjustment type.
882 if (bitrateAdjustmentType == BitrateAdjustmentType.FRAMERATE_ADJUSTMENT && targetFps > 0) {
883 codecBitrateBps = BITRATE_ADJUSTMENT_FPS * targetBitrateBps / targetFps;
sakalb6760f92016-09-29 04:12:44 -0700884 Logging.v(TAG,
885 "setRates: " + kbps + " -> " + (codecBitrateBps / 1000) + " kbps. Fps: " + targetFps);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700886 } else if (bitrateAdjustmentType == BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
sakalb6760f92016-09-29 04:12:44 -0700887 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps + ". ExpScale: "
888 + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700889 if (bitrateAdjustmentScaleExp != 0) {
sakalb6760f92016-09-29 04:12:44 -0700890 codecBitrateBps = (int) (codecBitrateBps * getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -0700891 }
892 } else {
893 Logging.v(TAG, "setRates: " + kbps + " kbps. Fps: " + targetFps);
894 }
895
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000896 try {
897 Bundle params = new Bundle();
Alex Glaznevcfaca032016-09-06 14:08:19 -0700898 params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, codecBitrateBps);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000899 mediaCodec.setParameters(params);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000900 return true;
901 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700902 Logging.e(TAG, "setRates failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000903 return false;
904 }
905 }
906
907 // Dequeue an input buffer and return its index, -1 if no input buffer is
908 // available, or -2 if the codec is no longer operative.
Magnus Jedvert655e1962017-12-08 11:05:22 +0100909 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800910 int dequeueInputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000911 checkOnMediaCodecThread();
912 try {
913 return mediaCodec.dequeueInputBuffer(DEQUEUE_TIMEOUT);
914 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700915 Logging.e(TAG, "dequeueIntputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000916 return -2;
917 }
918 }
919
920 // Helper struct for dequeueOutputBuffer() below.
perkj9576e542015-11-12 06:43:16 -0800921 static class OutputBufferInfo {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000922 public OutputBufferInfo(
sakalb6760f92016-09-29 04:12:44 -0700923 int index, ByteBuffer buffer, boolean isKeyFrame, long presentationTimestampUs) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000924 this.index = index;
925 this.buffer = buffer;
926 this.isKeyFrame = isKeyFrame;
927 this.presentationTimestampUs = presentationTimestampUs;
928 }
929
perkj9576e542015-11-12 06:43:16 -0800930 public final int index;
931 public final ByteBuffer buffer;
932 public final boolean isKeyFrame;
933 public final long presentationTimestampUs;
Magnus Jedvert655e1962017-12-08 11:05:22 +0100934
935 @CalledByNative("OutputBufferInfo")
936 int getIndex() {
937 return index;
938 }
939
940 @CalledByNative("OutputBufferInfo")
941 ByteBuffer getBuffer() {
942 return buffer;
943 }
944
945 @CalledByNative("OutputBufferInfo")
946 boolean isKeyFrame() {
947 return isKeyFrame;
948 }
949
950 @CalledByNative("OutputBufferInfo")
951 long getPresentationTimestampUs() {
952 return presentationTimestampUs;
953 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000954 }
955
956 // Dequeue and return an output buffer, or null if no output is ready. Return
957 // a fake OutputBufferInfo with index -1 if the codec is no longer operable.
Sami Kalliomäkie7592d82018-03-22 13:32:44 +0100958 @Nullable
Magnus Jedvert655e1962017-12-08 11:05:22 +0100959 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -0800960 OutputBufferInfo dequeueOutputBuffer() {
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000961 checkOnMediaCodecThread();
962 try {
963 MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
964 int result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000965 // Check if this is config frame and save configuration data.
966 if (result >= 0) {
sakalb6760f92016-09-29 04:12:44 -0700967 boolean isConfigFrame = (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000968 if (isConfigFrame) {
sakalb6760f92016-09-29 04:12:44 -0700969 Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000970 configData = ByteBuffer.allocateDirect(info.size);
971 outputBuffers[result].position(info.offset);
972 outputBuffers[result].limit(info.offset + info.size);
973 configData.put(outputBuffers[result]);
glaznev3fc23502017-06-15 16:24:37 -0700974 // Log few SPS header bytes to check profile and level.
975 String spsData = "";
976 for (int i = 0; i < (info.size < 8 ? info.size : 8); i++) {
977 spsData += Integer.toHexString(configData.get(i) & 0xff) + " ";
978 }
979 Logging.d(TAG, spsData);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000980 // Release buffer back.
981 mediaCodec.releaseOutputBuffer(result, false);
982 // Query next output.
983 result = mediaCodec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT);
984 }
985 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +0000986 if (result >= 0) {
987 // MediaCodec doesn't care about Buffer position/remaining/etc so we can
988 // mess with them to get a slice and avoid having to pass extra
989 // (BufferInfo-related) parameters back to C++.
990 ByteBuffer outputBuffer = outputBuffers[result].duplicate();
991 outputBuffer.position(info.offset);
992 outputBuffer.limit(info.offset + info.size);
Alex Glaznevcfaca032016-09-06 14:08:19 -0700993 reportEncodedFrame(info.size);
994
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000995 // Check key frame flag.
sakalb6760f92016-09-29 04:12:44 -0700996 boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0;
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000997 if (isKeyFrame) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -0700998 Logging.d(TAG, "Sync frame generated");
glaznev@webrtc.orgc6c1dfd2014-06-13 22:59:08 +0000999 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001000 if (isKeyFrame && type == VideoCodecType.VIDEO_CODEC_H264) {
sakalb6760f92016-09-29 04:12:44 -07001001 Logging.d(TAG, "Appending config frame of size " + configData.capacity()
1002 + " to output buffer with offset " + info.offset + ", size " + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001003 // For H.264 key frame append SPS and PPS NALs at the start
sakalb6760f92016-09-29 04:12:44 -07001004 ByteBuffer keyFrameBuffer = ByteBuffer.allocateDirect(configData.capacity() + info.size);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001005 configData.rewind();
1006 keyFrameBuffer.put(configData);
1007 keyFrameBuffer.put(outputBuffer);
1008 keyFrameBuffer.position(0);
sakalb6760f92016-09-29 04:12:44 -07001009 return new OutputBufferInfo(result, keyFrameBuffer, isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001010 } else {
sakalb6760f92016-09-29 04:12:44 -07001011 return new OutputBufferInfo(
1012 result, outputBuffer.slice(), isKeyFrame, info.presentationTimeUs);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001013 }
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001014 } else if (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
1015 outputBuffers = mediaCodec.getOutputBuffers();
1016 return dequeueOutputBuffer();
1017 } else if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
1018 return dequeueOutputBuffer();
1019 } else if (result == MediaCodec.INFO_TRY_AGAIN_LATER) {
1020 return null;
1021 }
1022 throw new RuntimeException("dequeueOutputBuffer: " + result);
1023 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -07001024 Logging.e(TAG, "dequeueOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001025 return new OutputBufferInfo(-1, null, false, -1);
1026 }
1027 }
1028
Alex Glaznevcfaca032016-09-06 14:08:19 -07001029 private double getBitrateScale(int bitrateAdjustmentScaleExp) {
1030 return Math.pow(BITRATE_CORRECTION_MAX_SCALE,
sakalb6760f92016-09-29 04:12:44 -07001031 (double) bitrateAdjustmentScaleExp / BITRATE_CORRECTION_STEPS);
Alex Glaznevcfaca032016-09-06 14:08:19 -07001032 }
1033
1034 private void reportEncodedFrame(int size) {
1035 if (targetFps == 0 || bitrateAdjustmentType != BitrateAdjustmentType.DYNAMIC_ADJUSTMENT) {
1036 return;
1037 }
1038
1039 // Accumulate the difference between actial and expected frame sizes.
1040 double expectedBytesPerFrame = targetBitrateBps / (8.0 * targetFps);
1041 bitrateAccumulator += (size - expectedBytesPerFrame);
1042 bitrateObservationTimeMs += 1000.0 / targetFps;
1043
1044 // Put a cap on the accumulator, i.e., don't let it grow beyond some level to avoid
1045 // using too old data for bitrate adjustment.
1046 double bitrateAccumulatorCap = BITRATE_CORRECTION_SEC * bitrateAccumulatorMax;
1047 bitrateAccumulator = Math.min(bitrateAccumulator, bitrateAccumulatorCap);
1048 bitrateAccumulator = Math.max(bitrateAccumulator, -bitrateAccumulatorCap);
1049
1050 // Do bitrate adjustment every 3 seconds if actual encoder bitrate deviates too much
1051 // form the target value.
1052 if (bitrateObservationTimeMs > 1000 * BITRATE_CORRECTION_SEC) {
sakalb6760f92016-09-29 04:12:44 -07001053 Logging.d(TAG, "Acc: " + (int) bitrateAccumulator + ". Max: " + (int) bitrateAccumulatorMax
1054 + ". ExpScale: " + bitrateAdjustmentScaleExp);
Alex Glaznevcfaca032016-09-06 14:08:19 -07001055 boolean bitrateAdjustmentScaleChanged = false;
1056 if (bitrateAccumulator > bitrateAccumulatorMax) {
1057 // Encoder generates too high bitrate - need to reduce the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -08001058 int bitrateAdjustmentInc = (int) (bitrateAccumulator / bitrateAccumulatorMax + 0.5);
1059 bitrateAdjustmentScaleExp -= bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001060 bitrateAccumulator = bitrateAccumulatorMax;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001061 bitrateAdjustmentScaleChanged = true;
1062 } else if (bitrateAccumulator < -bitrateAccumulatorMax) {
1063 // Encoder generates too low bitrate - need to increase the scale.
Alex Glaznev7fa4a722017-01-17 15:32:02 -08001064 int bitrateAdjustmentInc = (int) (-bitrateAccumulator / bitrateAccumulatorMax + 0.5);
1065 bitrateAdjustmentScaleExp += bitrateAdjustmentInc;
Alex Glaznevcfaca032016-09-06 14:08:19 -07001066 bitrateAccumulator = -bitrateAccumulatorMax;
1067 bitrateAdjustmentScaleChanged = true;
1068 }
1069 if (bitrateAdjustmentScaleChanged) {
1070 bitrateAdjustmentScaleExp = Math.min(bitrateAdjustmentScaleExp, BITRATE_CORRECTION_STEPS);
1071 bitrateAdjustmentScaleExp = Math.max(bitrateAdjustmentScaleExp, -BITRATE_CORRECTION_STEPS);
sakalb6760f92016-09-29 04:12:44 -07001072 Logging.d(TAG, "Adjusting bitrate scale to " + bitrateAdjustmentScaleExp + ". Value: "
1073 + getBitrateScale(bitrateAdjustmentScaleExp));
Alex Glaznevcfaca032016-09-06 14:08:19 -07001074 setRates(targetBitrateBps / 1000, targetFps);
1075 }
1076 bitrateObservationTimeMs = 0;
1077 }
1078 }
1079
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001080 // Release a dequeued output buffer back to the codec for re-use. Return
1081 // false if the codec is no longer operable.
Magnus Jedvert655e1962017-12-08 11:05:22 +01001082 @CalledByNativeUnchecked
perkj9576e542015-11-12 06:43:16 -08001083 boolean releaseOutputBuffer(int index) {
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001084 checkOnMediaCodecThread();
1085 try {
1086 mediaCodec.releaseOutputBuffer(index, false);
1087 return true;
1088 } catch (IllegalStateException e) {
Jiayang Liu5975b3c2015-09-16 13:40:53 -07001089 Logging.e(TAG, "releaseOutputBuffer failed", e);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001090 return false;
1091 }
1092 }
sakalb5f5bdc2017-08-10 04:15:42 -07001093
Magnus Jedvert655e1962017-12-08 11:05:22 +01001094 @CalledByNative
1095 int getColorFormat() {
1096 return colorFormat;
1097 }
1098
1099 @CalledByNative
1100 static boolean isTextureBuffer(VideoFrame.Buffer buffer) {
1101 return buffer instanceof VideoFrame.TextureBuffer;
1102 }
1103
sakalb5f5bdc2017-08-10 04:15:42 -07001104 /** Fills an inputBuffer with the given index with data from the byte buffers. */
Magnus Jedvert84d8ae52017-12-20 15:12:10 +01001105 private static native void nativeFillInputBuffer(long encoder, int inputBuffer, ByteBuffer dataY,
1106 int strideY, ByteBuffer dataU, int strideU, ByteBuffer dataV, int strideV);
Magnus Jedverte26ff4b2018-07-13 16:09:20 +02001107 private static native long nativeCreateEncoder(VideoCodecInfo info, boolean hasEgl14Context);
fischman@webrtc.org540acde2014-02-13 03:56:14 +00001108}