blob: 7a13270b1393ad3a2d01aebc830563c59ac6b2b1 [file] [log] [blame]
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2015 The WebRTC project authors. All Rights Reserved.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +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.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00009 */
10
kjellandera96e2d72016-02-04 23:52:28 -080011// NOTICE: androidmediaencoder_jni.h must be included before
12// androidmediacodeccommon.h to avoid build errors.
Henrik Kjellander15583c12016-02-10 10:53:12 +010013#include "webrtc/api/java/jni/androidmediaencoder_jni.h"
14
Perba7dc722016-04-19 15:01:23 +020015#include <algorithm>
kwibergd1fe2812016-04-27 06:47:29 -070016#include <memory>
Perba7dc722016-04-19 15:01:23 +020017#include <list>
18
kjellandera96e2d72016-02-04 23:52:28 -080019#include "third_party/libyuv/include/libyuv/convert.h"
20#include "third_party/libyuv/include/libyuv/convert_from.h"
21#include "third_party/libyuv/include/libyuv/video_common.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010022#include "webrtc/api/java/jni/androidmediacodeccommon.h"
23#include "webrtc/api/java/jni/classreferenceholder.h"
24#include "webrtc/api/java/jni/native_handle_impl.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000025#include "webrtc/base/bind.h"
26#include "webrtc/base/checks.h"
27#include "webrtc/base/logging.h"
28#include "webrtc/base/thread.h"
perkj9576e542015-11-12 06:43:16 -080029#include "webrtc/base/thread_checker.h"
asapersson1d61a512016-01-20 01:13:46 -080030#include "webrtc/common_types.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020031#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080032#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010033#include "webrtc/modules/video_coding/utility/quality_scaler.h"
34#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010035#include "webrtc/system_wrappers/include/field_trial.h"
36#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000037
38using rtc::Bind;
39using rtc::Thread;
40using rtc::ThreadManager;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000041
42using webrtc::CodecSpecificInfo;
43using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070044using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000045using webrtc::RTPFragmentationHeader;
46using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000047using webrtc::VideoCodecType;
48using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000049using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080050using webrtc::kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -080051using webrtc::QualityScaler;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000052
53namespace webrtc_jni {
54
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000055// H.264 start code length.
56#define H264_SC_LENGTH 4
57// Maximum allowed NALUs in one output frame.
58#define MAX_NALUS_PERFRAME 32
59// Maximum supported HW video encoder resolution.
60#define MAX_VIDEO_WIDTH 1280
61#define MAX_VIDEO_HEIGHT 1280
62// Maximum supported HW video encoder fps.
63#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080064// Maximum allowed fps value in SetRates() call.
65#define MAX_ALLOWED_VIDEO_FPS 60
66// Maximum allowed frames in encoder input queue.
67#define MAX_ENCODER_Q_SIZE 2
glaznev919ff752016-01-27 15:01:03 -080068// Maximum amount of dropped frames caused by full encoder queue - exceeding
69// this threshold means that encoder probably got stuck and need to be reset.
70#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080071
72// Logging macros.
73#define TAG_ENCODER "MediaCodecVideoEncoder"
74#ifdef TRACK_BUFFER_TIMING
75#define ALOGV(...)
76 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
77#else
78#define ALOGV(...)
79#endif
80#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
81#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
82#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000083
asapersson1d61a512016-01-20 01:13:46 -080084namespace {
85// Maximum time limit between incoming frames before requesting a key frame.
86const size_t kFrameDiffThresholdMs = 1100;
87const int kMinKeyFrameInterval = 2;
88} // namespace
89
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000090// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
91// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
92// HW-backed video encode. This C++ class is implemented as a very thin shim,
93// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
94// MediaCodecVideoEncoder is created, operated, and destroyed on a single
95// thread, currently the libjingle Worker thread.
96class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
97 public rtc::MessageHandler {
98 public:
99 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -0800100 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800101 VideoCodecType codecType,
102 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000103
104 // webrtc::VideoEncoder implementation. Everything trampolines to
105 // |codec_thread_| for execution.
106 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
107 int32_t /* number_of_cores */,
108 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700109 int32_t Encode(const webrtc::VideoFrame& input_image,
110 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
111 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000112 int32_t RegisterEncodeCompleteCallback(
113 webrtc::EncodedImageCallback* callback) override;
114 int32_t Release() override;
115 int32_t SetChannelParameters(uint32_t /* packet_loss */,
116 int64_t /* rtt */) override;
117 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
118
119 // rtc::MessageHandler implementation.
120 void OnMessage(rtc::Message* msg) override;
121
jackychen61b4d512015-04-21 15:30:11 -0700122 void OnDroppedFrame() override;
123
Perec2922f2016-01-27 15:25:46 +0100124 bool SupportsNativeHandle() const override { return egl_context_ != nullptr; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100125 const char* ImplementationName() const override;
126
127 private:
perkj9576e542015-11-12 06:43:16 -0800128 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
129 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000130 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800131 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000132
133 // Implementation of webrtc::VideoEncoder methods above, all running on the
134 // codec thread exclusively.
135 //
136 // If width==0 then this is assumed to be a re-initialization and the
137 // previously-current values are reused instead of the passed parameters
138 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800139 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
140 bool use_surface);
141 // Reconfigure to match |frame| in width, height. Also reconfigures the
142 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
143 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800144 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000145 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700146 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700147 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800148 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
149 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800150 bool EncodeTextureOnCodecThread(JNIEnv* jni,
151 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800152
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000153 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
154 webrtc::EncodedImageCallback* callback);
155 int32_t ReleaseOnCodecThread();
156 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
Peter Boström53edac62016-04-27 00:08:34 +0200157 void OnDroppedFrameOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000158
159 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
160 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
161 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
162 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
163 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000164 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000165
166 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
167 // true on success.
168 bool DeliverPendingOutputs(JNIEnv* jni);
169
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000170 // Search for H.264 start codes.
171 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
172
glaznev94291482016-02-01 13:17:18 -0800173 // Displays encoder statistics.
174 void LogStatistics(bool force_log);
175
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000176 // Type of video codec.
177 VideoCodecType codecType_;
178
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000179 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
180 // |codec_thread_| synchronously.
181 webrtc::EncodedImageCallback* callback_;
182
183 // State that is constant for the lifetime of this object once the ctor
184 // returns.
kwibergd1fe2812016-04-27 06:47:29 -0700185 std::unique_ptr<Thread>
186 codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800187 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000188 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
189 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
190 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800191 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000192 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800193 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800194 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000195 jmethodID j_release_method_;
196 jmethodID j_set_rates_method_;
197 jmethodID j_dequeue_output_buffer_method_;
198 jmethodID j_release_output_buffer_method_;
199 jfieldID j_color_format_field_;
200 jfieldID j_info_index_field_;
201 jfieldID j_info_buffer_field_;
202 jfieldID j_info_is_key_frame_field_;
203 jfieldID j_info_presentation_timestamp_us_field_;
204
205 // State that is valid only between InitEncode() and the next Release().
206 // Touched only on codec_thread_ so no explicit synchronization necessary.
207 int width_; // Frame width in pixels.
208 int height_; // Frame height in pixels.
209 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800210 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000211 uint16_t picture_id_;
212 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
213 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
214 int last_set_fps_; // Last-requested frame rate.
215 int64_t current_timestamp_us_; // Current frame timestamps in us.
216 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000217 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800218 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
219 // Number of dropped frames caused by full queue.
220 int consecutive_full_queue_frame_drops_;
glaznev94291482016-02-01 13:17:18 -0800221 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000222 int current_frames_; // Number of frames in the current statistics interval.
223 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800224 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000225 int current_encoding_time_ms_; // Overall encoding time in the current second
226 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
227 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
Perba7dc722016-04-19 15:01:23 +0200228
229 struct InputFrameInfo {
230 InputFrameInfo(int64_t encode_start_time,
231 int32_t frame_timestamp,
232 int64_t frame_render_time_ms,
233 webrtc::VideoRotation rotation)
234 : encode_start_time(encode_start_time),
235 frame_timestamp(frame_timestamp),
236 frame_render_time_ms(frame_render_time_ms),
237 rotation(rotation) {}
238 // Time when video frame is sent to encoder input.
239 const int64_t encode_start_time;
240
241 // Input frame information.
242 const int32_t frame_timestamp;
243 const int64_t frame_render_time_ms;
244 const webrtc::VideoRotation rotation;
245 };
246 std::list<InputFrameInfo> input_frame_infos_;
247 int32_t output_timestamp_; // Last output frame timestamp from
248 // |input_frame_infos_|.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000249 int64_t output_render_time_ms_; // Last output frame render time from
Perba7dc722016-04-19 15:01:23 +0200250 // |input_frame_infos_|.
251 webrtc::VideoRotation output_rotation_; // Last output frame rotation from
252 // |input_frame_infos_|.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000253 // Frame size in bytes fed to MediaCodec.
254 int yuv_size_;
255 // True only when between a callback_->Encoded() call return a positive value
256 // and the next Encode() call being ignored.
257 bool drop_next_input_frame_;
258 // Global references; must be deleted in Release().
259 std::vector<jobject> input_buffers_;
Alex Glazneva9d08922016-02-19 15:24:06 -0800260 QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700261 // Dynamic resolution change, off by default.
262 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200263
264 // H264 bitstream parser, used to extract QP from encoded bitstreams.
265 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800266
267 // VP9 variables to populate codec specific structure.
268 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
269 // non-flexible VP9 mode.
270 uint8_t tl0_pic_idx_;
271 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800272
273 // EGL context - owned by factory, should not be allocated/destroyed
274 // by MediaCodecVideoEncoder.
275 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800276
277 // Temporary fix for VP8.
278 // Sends a key frame if frames are largely spaced apart (possibly
279 // corresponding to a large image change).
280 int64_t last_frame_received_ms_;
281 int frames_received_since_last_key_;
282 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000283};
284
285MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
286 // Call Release() to ensure no more callbacks to us after we are deleted.
287 Release();
288}
289
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000290MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800291 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000292 codecType_(codecType),
293 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000294 codec_thread_(new Thread()),
295 j_media_codec_video_encoder_class_(
296 jni,
297 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
298 j_media_codec_video_encoder_(
299 jni,
300 jni->NewObject(*j_media_codec_video_encoder_class_,
301 GetMethodID(jni,
302 *j_media_codec_video_encoder_class_,
303 "<init>",
perkj30e91822015-11-20 01:31:25 -0800304 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800305 inited_(false),
306 use_surface_(false),
307 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800308 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000309 ScopedLocalRefFrame local_ref_frame(jni);
310 // It would be nice to avoid spinning up a new thread per MediaCodec, and
311 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
312 // 2732 means that deadlocks abound. This class synchronously trampolines
313 // to |codec_thread_|, so if anything else can be coming to _us_ from
314 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
315 // in the bug, we have a problem. For now work around that with a dedicated
316 // thread.
317 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700318 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800319 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000320 jclass j_output_buffer_info_class =
321 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000322 j_init_encode_method_ = GetMethodID(
323 jni,
324 *j_media_codec_video_encoder_class_,
325 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800326 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800327 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800328 j_get_input_buffers_method_ = GetMethodID(
329 jni,
330 *j_media_codec_video_encoder_class_,
331 "getInputBuffers",
332 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000333 j_dequeue_input_buffer_method_ = GetMethodID(
334 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800335 j_encode_buffer_method_ = GetMethodID(
336 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800337 j_encode_texture_method_ = GetMethodID(
338 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
339 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000340 j_release_method_ =
341 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
342 j_set_rates_method_ = GetMethodID(
343 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000344 j_dequeue_output_buffer_method_ = GetMethodID(
345 jni,
346 *j_media_codec_video_encoder_class_,
347 "dequeueOutputBuffer",
348 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000349 j_release_output_buffer_method_ = GetMethodID(
350 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
351
352 j_color_format_field_ =
353 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
354 j_info_index_field_ =
355 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
356 j_info_buffer_field_ = GetFieldID(
357 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
358 j_info_is_key_frame_field_ =
359 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
360 j_info_presentation_timestamp_us_field_ = GetFieldID(
361 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
362 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800363 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000364 AllowBlockingCalls();
365}
366
367int32_t MediaCodecVideoEncoder::InitEncode(
368 const webrtc::VideoCodec* codec_settings,
369 int32_t /* number_of_cores */,
370 size_t /* max_payload_size */) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000371 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700372 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000373 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
374 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000375 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700376 RTC_CHECK(codec_settings->codecType == codecType_)
377 << "Unsupported codec " << codec_settings->codecType << " for "
378 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000379
asapersson1d61a512016-01-20 01:13:46 -0800380 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800381 int init_width = codec_settings->width;
382 int init_height = codec_settings->height;
Peter Boström7ace4882016-04-14 00:54:56 +0200383 scale_ = codecType_ != kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -0800384
385 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700386 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800387
Peter Boström2bc68c72015-09-24 16:22:28 +0200388 if (scale_) {
389 if (codecType_ == kVideoCodecVP8) {
390 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
391 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
392 // always = 127. Note that in SW, QP is that of the user-level range [0,
393 // 63].
Alex Glaznev79299af2016-04-12 16:39:39 -0700394 const int kLowQpThreshold = 29;
Alex Glaznevfac23f02016-05-04 12:58:22 -0700395 const int kBadQpThreshold = 90;
Peter Boström3c6eac22016-04-26 13:37:10 +0200396 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold,
pboscbac40d2016-04-13 02:51:02 -0700397 codec_settings->startBitrate, codec_settings->width,
398 codec_settings->height,
399 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200400 } else if (codecType_ == kVideoCodecH264) {
401 // H264 QP is in the range [0, 51].
Alex Glaznevfac23f02016-05-04 12:58:22 -0700402 const int kLowQpThreshold = 22;
403 const int kBadQpThreshold = 35;
Peter Boström3c6eac22016-04-26 13:37:10 +0200404 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold,
pboscbac40d2016-04-13 02:51:02 -0700405 codec_settings->startBitrate, codec_settings->width,
406 codec_settings->height,
407 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200408 } else {
409 // When adding codec support to additional hardware codecs, also configure
410 // their QP thresholds for scaling.
411 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800412 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200413 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800414 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström926dfcd2016-04-14 14:48:10 +0200415 init_width = res.width;
416 init_height = res.height;
Alex Glazneva9d08922016-02-19 15:24:06 -0800417 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700418 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800419
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000420 return codec_thread_->Invoke<int32_t>(
421 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
422 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800423 init_width,
424 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000425 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800426 codec_settings->maxFramerate,
427 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000428}
429
430int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700431 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000432 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700433 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000434 return codec_thread_->Invoke<int32_t>(Bind(
435 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
436}
437
438int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
439 webrtc::EncodedImageCallback* callback) {
440 return codec_thread_->Invoke<int32_t>(
441 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
442 this,
443 callback));
444}
445
446int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700447 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000448 return codec_thread_->Invoke<int32_t>(
449 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
450}
451
452int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
453 int64_t /* rtt */) {
454 return WEBRTC_VIDEO_CODEC_OK;
455}
456
457int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
458 uint32_t frame_rate) {
459 return codec_thread_->Invoke<int32_t>(
460 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
461 this,
462 new_bit_rate,
463 frame_rate));
464}
465
466void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800467 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000468 JNIEnv* jni = AttachCurrentThreadIfNeeded();
469 ScopedLocalRefFrame local_ref_frame(jni);
470
471 // We only ever send one message to |this| directly (not through a Bind()'d
472 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700473 RTC_CHECK(!msg->message_id) << "Unexpected message!";
474 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000475 if (!inited_) {
476 return;
477 }
478
479 // It would be nice to recover from a failure here if one happened, but it's
480 // unclear how to signal such a failure to the app, so instead we stay silent
481 // about it and let the next app-called API method reveal the borkedness.
482 DeliverPendingOutputs(jni);
483 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
484}
485
perkj9576e542015-11-12 06:43:16 -0800486bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
487 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
488 ALOGE << "ResetOnCodecThread";
489 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800490 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
491 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000492 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
493 // degrade to a SW encoder at this point? There isn't one AFAICT :(
494 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800495 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000496 }
perkj9576e542015-11-12 06:43:16 -0800497 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000498}
499
500int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800501 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800502 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800503 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000504 JNIEnv* jni = AttachCurrentThreadIfNeeded();
505 ScopedLocalRefFrame local_ref_frame(jni);
506
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700507 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
508 width << " x " << height << ". Bitrate: " << kbps <<
509 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000510 if (kbps == 0) {
511 kbps = last_set_bitrate_kbps_;
512 }
513 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800514 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 }
516
517 width_ = width;
518 height_ = height;
519 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800520 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 yuv_size_ = width_ * height_ * 3 / 2;
522 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000523 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800524 frames_dropped_media_encoder_ = 0;
525 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000526 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800527 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000528 current_frames_ = 0;
529 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800530 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000531 current_encoding_time_ms_ = 0;
532 last_input_timestamp_ms_ = -1;
533 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000534 output_timestamp_ = 0;
535 output_render_time_ms_ = 0;
Perba7dc722016-04-19 15:01:23 +0200536 input_frame_infos_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000537 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800538 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000539 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800540 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
541 tl0_pic_idx_ = static_cast<uint8_t>(rand());
542 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800543 last_frame_received_ms_ = -1;
544 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800545
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000546 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100547 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000548 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800549 const bool encode_status = jni->CallBooleanMethod(
550 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800551 j_video_codec_enum, width, height, kbps, fps,
552 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800553 if (!encode_status) {
554 ALOGE << "Failed to configure encoder.";
555 return WEBRTC_VIDEO_CODEC_ERROR;
556 }
557 CHECK_EXCEPTION(jni);
558
Per598242a2015-11-26 14:28:55 +0100559 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800560 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
561 jni->CallObjectMethod(*j_media_codec_video_encoder_,
562 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000563 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800564 if (IsNull(jni, input_buffers)) {
565 return WEBRTC_VIDEO_CODEC_ERROR;
566 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000567
perkj30e91822015-11-20 01:31:25 -0800568 switch (GetIntField(jni, *j_media_codec_video_encoder_,
569 j_color_format_field_)) {
570 case COLOR_FormatYUV420Planar:
571 encoder_fourcc_ = libyuv::FOURCC_YU12;
572 break;
573 case COLOR_FormatYUV420SemiPlanar:
574 case COLOR_QCOM_FormatYUV420SemiPlanar:
575 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
576 encoder_fourcc_ = libyuv::FOURCC_NV12;
577 break;
578 default:
579 LOG(LS_ERROR) << "Wrong color format.";
580 return WEBRTC_VIDEO_CODEC_ERROR;
581 }
582 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
583 RTC_CHECK(input_buffers_.empty())
584 << "Unexpected double InitEncode without Release";
585 input_buffers_.resize(num_input_buffers);
586 for (size_t i = 0; i < num_input_buffers; ++i) {
587 input_buffers_[i] =
588 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
589 int64_t yuv_buffer_capacity =
590 jni->GetDirectBufferCapacity(input_buffers_[i]);
591 CHECK_EXCEPTION(jni);
592 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
593 }
594 }
perkj9576e542015-11-12 06:43:16 -0800595
596 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000597 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
598 return WEBRTC_VIDEO_CODEC_OK;
599}
600
601int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700602 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700603 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800604 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000605 JNIEnv* jni = AttachCurrentThreadIfNeeded();
606 ScopedLocalRefFrame local_ref_frame(jni);
607
608 if (!inited_) {
609 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
610 }
perkj9576e542015-11-12 06:43:16 -0800611
asapersson1d61a512016-01-20 01:13:46 -0800612 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800613 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800614 ++frames_received_since_last_key_;
615 int64_t now_ms = GetCurrentTimeMs();
616 if (last_frame_received_ms_ != -1 &&
617 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
618 // Add limit to prevent triggering a key for every frame for very low
619 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
620 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
621 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
622 send_key_frame = true;
623 }
624 frames_received_since_last_key_ = 0;
625 }
626 last_frame_received_ms_ = now_ms;
627 }
628
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000629 frames_received_++;
630 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800631 if (!ResetCodecOnCodecThread())
632 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000633 }
glaznevf4decb52016-01-15 13:49:22 -0800634 if (frames_encoded_ < kMaxEncodedLogFrames) {
Perba7dc722016-04-19 15:01:23 +0200635 ALOGD << "Encoder frame in # " << (frames_received_ - 1)
636 << ". TS: " << (int)(current_timestamp_us_ / 1000)
637 << ". Q: " << input_frame_infos_.size() << ". Fps: " << last_set_fps_
638 << ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800639 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000640
641 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800642 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000643 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800644 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800645 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200646 OnDroppedFrameOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000647 return WEBRTC_VIDEO_CODEC_OK;
648 }
649
henrikg91d6ede2015-09-17 00:24:34 -0700650 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200651
Peter Boströmf7704d12016-04-11 16:42:40 +0200652 // Check if we accumulated too many frames in encoder input buffers and drop
653 // frame if so.
Perba7dc722016-04-19 15:01:23 +0200654 if (input_frame_infos_.size() > MAX_ENCODER_Q_SIZE) {
655 ALOGD << "Already " << input_frame_infos_.size()
656 << " frames in the queue, dropping"
Peter Boströmf7704d12016-04-11 16:42:40 +0200657 << ". TS: " << (int)(current_timestamp_us_ / 1000)
658 << ". Fps: " << last_set_fps_
659 << ". Consecutive drops: " << consecutive_full_queue_frame_drops_;
660 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
661 consecutive_full_queue_frame_drops_++;
662 if (consecutive_full_queue_frame_drops_ >=
663 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
664 ALOGE << "Encoder got stuck. Reset.";
665 ResetCodecOnCodecThread();
666 return WEBRTC_VIDEO_CODEC_ERROR;
glaznevf4decb52016-01-15 13:49:22 -0800667 }
Peter Boströmf7704d12016-04-11 16:42:40 +0200668 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200669 OnDroppedFrameOnCodecThread();
Peter Boströmf7704d12016-04-11 16:42:40 +0200670 return WEBRTC_VIDEO_CODEC_OK;
glaznevf4decb52016-01-15 13:49:22 -0800671 }
glaznev919ff752016-01-27 15:01:03 -0800672 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800673
Per598242a2015-11-26 14:28:55 +0100674 VideoFrame input_frame = frame;
675 if (scale_) {
676 // Check framerate before spatial resolution change.
677 quality_scaler_.OnEncodeFrame(frame);
678 const webrtc::QualityScaler::Resolution scaled_resolution =
679 quality_scaler_.GetScaledResolution();
680 if (scaled_resolution.width != frame.width() ||
681 scaled_resolution.height != frame.height()) {
nisse26acec42016-04-15 03:43:39 -0700682 if (frame.video_frame_buffer()->native_handle() != nullptr) {
Per598242a2015-11-26 14:28:55 +0100683 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
684 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100685 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100686 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100687 scaled_resolution.height,
688 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100689 input_frame.set_video_frame_buffer(scaled_buffer);
690 } else {
691 input_frame = quality_scaler_.GetScaledFrame(frame);
692 }
693 }
694 }
jackychen61b4d512015-04-21 15:30:11 -0700695
perkj9576e542015-11-12 06:43:16 -0800696 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
697 ALOGE << "Failed to reconfigure encoder.";
698 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000699 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000700
Perba7dc722016-04-19 15:01:23 +0200701 const int64_t time_before_calling_encode = GetCurrentTimeMs();
asapersson1d61a512016-01-20 01:13:46 -0800702 const bool key_frame =
703 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800704 bool encode_status = true;
nisse26acec42016-04-15 03:43:39 -0700705 if (!input_frame.video_frame_buffer()->native_handle()) {
perkj30e91822015-11-20 01:31:25 -0800706 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
707 j_dequeue_input_buffer_method_);
708 CHECK_EXCEPTION(jni);
709 if (j_input_buffer_index == -1) {
710 // Video codec falls behind - no input buffer available.
711 ALOGW << "Encoder drop frame - no input buffers available";
glaznev919ff752016-01-27 15:01:03 -0800712 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
713 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200714 OnDroppedFrameOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800715 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
716 }
717 if (j_input_buffer_index == -2) {
718 ResetCodecOnCodecThread();
719 return WEBRTC_VIDEO_CODEC_ERROR;
720 }
721 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
722 j_input_buffer_index);
723 } else {
724 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000725 }
perkj30e91822015-11-20 01:31:25 -0800726
727 if (!encode_status) {
728 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800729 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200730 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000731 }
732
Perba7dc722016-04-19 15:01:23 +0200733 // Save input image timestamps for later output.
734 input_frame_infos_.emplace_back(
735 time_before_calling_encode, input_frame.timestamp(),
736 input_frame.render_time_ms(), input_frame.rotation());
737
perkj9576e542015-11-12 06:43:16 -0800738 last_input_timestamp_ms_ =
739 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000740
perkj9576e542015-11-12 06:43:16 -0800741 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
742
perkj30e91822015-11-20 01:31:25 -0800743 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800744 ALOGE << "Failed deliver pending outputs.";
745 ResetCodecOnCodecThread();
746 return WEBRTC_VIDEO_CODEC_ERROR;
747 }
748 return WEBRTC_VIDEO_CODEC_OK;
749}
750
751bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
752 const webrtc::VideoFrame& frame) {
753 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
754
nisse26acec42016-04-15 03:43:39 -0700755 const bool is_texture_frame =
756 frame.video_frame_buffer()->native_handle() != nullptr;
perkj30e91822015-11-20 01:31:25 -0800757 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800758 const bool reconfigure_due_to_size =
759 frame.width() != width_ || frame.height() != height_;
760
perkj30e91822015-11-20 01:31:25 -0800761 if (reconfigure_due_to_format) {
762 ALOGD << "Reconfigure encoder due to format change. "
763 << (use_surface_ ?
764 "Reconfiguring to encode from byte buffer." :
765 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800766 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800767 }
perkj9576e542015-11-12 06:43:16 -0800768 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800769 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800770 << width_ << " x " << height_ << " to " << frame.width() << " x "
771 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800772 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800773 width_ = frame.width();
774 height_ = frame.height();
775 }
776
perkj30e91822015-11-20 01:31:25 -0800777 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800778 return true;
779
780 ReleaseOnCodecThread();
781
perkj30e91822015-11-20 01:31:25 -0800782 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800783 WEBRTC_VIDEO_CODEC_OK;
784}
785
786bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
787 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
788 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800789 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800790
perkj9576e542015-11-12 06:43:16 -0800791 jobject j_input_buffer = input_buffers_[input_buffer_index];
792 uint8_t* yuv_buffer =
793 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
794 CHECK_EXCEPTION(jni);
795 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
796 RTC_CHECK(!libyuv::ConvertFromI420(
nisse5b3c4432016-04-29 02:39:24 -0700797 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
798 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
799 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
perkj9576e542015-11-12 06:43:16 -0800800 yuv_buffer, width_, width_, height_, encoder_fourcc_))
801 << "ConvertFromI420 failed";
802
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000803 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800804 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000805 key_frame,
perkj9576e542015-11-12 06:43:16 -0800806 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000807 yuv_size_,
808 current_timestamp_us_);
809 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800810 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000811}
812
perkj30e91822015-11-20 01:31:25 -0800813bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
814 bool key_frame, const webrtc::VideoFrame& frame) {
815 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
816 RTC_CHECK(use_surface_);
nisse26acec42016-04-15 03:43:39 -0700817 NativeHandleImpl* handle = static_cast<NativeHandleImpl*>(
818 frame.video_frame_buffer()->native_handle());
perkj30e91822015-11-20 01:31:25 -0800819 jfloatArray sampling_matrix = jni->NewFloatArray(16);
820 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
821
822 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
823 j_encode_texture_method_,
824 key_frame,
825 handle->oes_texture_id,
826 sampling_matrix,
827 current_timestamp_us_);
828 CHECK_EXCEPTION(jni);
829 return encode_status;
830}
831
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000832int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
833 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800834 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000835 JNIEnv* jni = AttachCurrentThreadIfNeeded();
836 ScopedLocalRefFrame local_ref_frame(jni);
837 callback_ = callback;
838 return WEBRTC_VIDEO_CODEC_OK;
839}
840
841int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800842 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000843 if (!inited_) {
844 return WEBRTC_VIDEO_CODEC_OK;
845 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000846 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700847 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
848 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800849 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000850 ScopedLocalRefFrame local_ref_frame(jni);
851 for (size_t i = 0; i < input_buffers_.size(); ++i)
852 jni->DeleteGlobalRef(input_buffers_[i]);
853 input_buffers_.clear();
854 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
855 CHECK_EXCEPTION(jni);
856 rtc::MessageQueueManager::Clear(this);
857 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800858 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700859 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000860 return WEBRTC_VIDEO_CODEC_OK;
861}
862
863int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
864 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800865 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800866 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
867 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000868 if (last_set_bitrate_kbps_ == new_bit_rate &&
869 last_set_fps_ == frame_rate) {
870 return WEBRTC_VIDEO_CODEC_OK;
871 }
glaznev919ff752016-01-27 15:01:03 -0800872 if (scale_) {
873 quality_scaler_.ReportFramerate(frame_rate);
874 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000875 JNIEnv* jni = AttachCurrentThreadIfNeeded();
876 ScopedLocalRefFrame local_ref_frame(jni);
877 if (new_bit_rate > 0) {
878 last_set_bitrate_kbps_ = new_bit_rate;
879 }
880 if (frame_rate > 0) {
881 last_set_fps_ = frame_rate;
882 }
883 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
884 j_set_rates_method_,
885 last_set_bitrate_kbps_,
886 last_set_fps_);
887 CHECK_EXCEPTION(jni);
888 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800889 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000890 return WEBRTC_VIDEO_CODEC_ERROR;
891 }
892 return WEBRTC_VIDEO_CODEC_OK;
893}
894
895int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
896 JNIEnv* jni,
897 jobject j_output_buffer_info) {
898 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
899}
900
901jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
902 JNIEnv* jni,
903 jobject j_output_buffer_info) {
904 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
905}
906
907bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
908 JNIEnv* jni,
909 jobject j_output_buffer_info) {
910 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
911}
912
913jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
914 JNIEnv* jni,
915 jobject j_output_buffer_info) {
916 return GetLongField(
917 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
918}
919
920bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800921 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000922 while (true) {
923 jobject j_output_buffer_info = jni->CallObjectMethod(
924 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
925 CHECK_EXCEPTION(jni);
926 if (IsNull(jni, j_output_buffer_info)) {
927 break;
928 }
929
930 int output_buffer_index =
931 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
932 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800933 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000934 return false;
935 }
936
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000937 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000938 jobject j_output_buffer =
939 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
940 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000941
942 // Get frame timestamps from a queue - for non config frames only.
943 int64_t frame_encoding_time_ms = 0;
944 last_output_timestamp_ms_ =
945 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
946 1000;
Perba7dc722016-04-19 15:01:23 +0200947 if (!input_frame_infos_.empty()) {
948 const InputFrameInfo& frame_info = input_frame_infos_.front();
949 output_timestamp_ = frame_info.frame_timestamp;
950 output_render_time_ms_ = frame_info.frame_render_time_ms;
951 output_rotation_ = frame_info.rotation;
952 frame_encoding_time_ms =
953 GetCurrentTimeMs() - frame_info.encode_start_time;
954 input_frame_infos_.pop_front();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000955 }
956
957 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000958 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200959 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000960 jni->GetDirectBufferAddress(j_output_buffer));
961 CHECK_EXCEPTION(jni);
962
glaznevf4decb52016-01-15 13:49:22 -0800963 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800964 int current_latency =
965 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
966 ALOGD << "Encoder frame out # " << frames_encoded_ <<
967 ". Key: " << key_frame <<
968 ". Size: " << payload_size <<
969 ". TS: " << (int)last_output_timestamp_ms_ <<
970 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800971 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000972 }
973
974 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000975 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000976 if (callback_) {
kwibergd1fe2812016-04-27 06:47:29 -0700977 std::unique_ptr<webrtc::EncodedImage> image(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000978 new webrtc::EncodedImage(payload, payload_size, payload_size));
979 image->_encodedWidth = width_;
980 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000981 image->_timeStamp = output_timestamp_;
982 image->capture_time_ms_ = output_render_time_ms_;
Perba7dc722016-04-19 15:01:23 +0200983 image->rotation_ = output_rotation_;
Peter Boström49e196a2015-10-23 15:58:18 +0200984 image->_frameType =
985 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000986 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700987 image->adapt_reason_.quality_resolution_downscales =
988 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000989
990 webrtc::CodecSpecificInfo info;
991 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000992 info.codecType = codecType_;
993 if (codecType_ == kVideoCodecVP8) {
994 info.codecSpecific.VP8.pictureId = picture_id_;
995 info.codecSpecific.VP8.nonReference = false;
996 info.codecSpecific.VP8.simulcastIdx = 0;
997 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
998 info.codecSpecific.VP8.layerSync = false;
999 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
1000 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -08001001 } else if (codecType_ == kVideoCodecVP9) {
1002 if (key_frame) {
1003 gof_idx_ = 0;
1004 }
1005 info.codecSpecific.VP9.picture_id = picture_id_;
1006 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
1007 info.codecSpecific.VP9.flexible_mode = false;
1008 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
1009 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1010 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1011 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1012 info.codecSpecific.VP9.temporal_up_switch = true;
1013 info.codecSpecific.VP9.inter_layer_predicted = false;
1014 info.codecSpecific.VP9.gof_idx =
1015 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1016 info.codecSpecific.VP9.num_spatial_layers = 1;
1017 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1018 if (info.codecSpecific.VP9.ss_data_available) {
1019 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1020 info.codecSpecific.VP9.width[0] = width_;
1021 info.codecSpecific.VP9.height[0] = height_;
1022 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1023 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001024 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001025 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001026
1027 // Generate a header describing a single fragment.
1028 webrtc::RTPFragmentationHeader header;
1029 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001030 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001031 header.VerifyAndAllocateFragmentationHeader(1);
1032 header.fragmentationOffset[0] = 0;
1033 header.fragmentationLength[0] = image->_length;
1034 header.fragmentationPlType[0] = 0;
1035 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001036 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001037 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001038 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1039 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001040 quality_scaler_.ReportQP(qp);
asapersson24ebc442016-04-19 23:48:21 -07001041 image->qp_ = qp;
glaznevf4decb52016-01-15 13:49:22 -08001042 }
asapersson86b01602015-10-20 23:55:26 -07001043 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001044 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001045 if (scale_) {
1046 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1047 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001048 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1049 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001050 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001051 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001052 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001053 // For H.264 search for start codes.
1054 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1055 int32_t scPositionsLength = 0;
1056 int32_t scPosition = 0;
1057 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1058 int32_t naluPosition = NextNaluPosition(
1059 payload + scPosition, payload_size - scPosition);
1060 if (naluPosition < 0) {
1061 break;
1062 }
1063 scPosition += naluPosition;
1064 scPositions[scPositionsLength++] = scPosition;
1065 scPosition += H264_SC_LENGTH;
1066 }
1067 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001068 ALOGE << "Start code is not found!";
1069 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1070 << " " << image->_buffer[2] << " " << image->_buffer[3]
1071 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001072 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001073 return false;
1074 }
1075 scPositions[scPositionsLength] = payload_size;
1076 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1077 for (size_t i = 0; i < scPositionsLength; i++) {
1078 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1079 header.fragmentationLength[i] =
1080 scPositions[i + 1] - header.fragmentationOffset[i];
1081 header.fragmentationPlType[i] = 0;
1082 header.fragmentationTimeDiff[i] = 0;
1083 }
1084 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001085
1086 callback_status = callback_->Encoded(*image, &info, &header);
1087 }
1088
1089 // Return output buffer back to the encoder.
1090 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1091 j_release_output_buffer_method_,
1092 output_buffer_index);
1093 CHECK_EXCEPTION(jni);
1094 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001095 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001096 return false;
1097 }
1098
glaznevf4decb52016-01-15 13:49:22 -08001099 // Calculate and print encoding statistics - every 3 seconds.
1100 frames_encoded_++;
1101 current_frames_++;
1102 current_bytes_ += payload_size;
1103 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001104 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001105
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001106 if (callback_status > 0) {
1107 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001108 // Theoretically could handle callback_status<0 here, but unclear what
1109 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001110 }
1111 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001112 return true;
1113}
1114
glaznev94291482016-02-01 13:17:18 -08001115void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1116 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1117 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1118 current_frames_ > 0 && statistic_time_ms > 0) {
1119 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1120 int current_fps =
1121 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1122 ALOGD << "Encoded frames: " << frames_encoded_ <<
1123 ". Bitrate: " << current_bitrate <<
1124 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1125 ", fps: " << current_fps <<
1126 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1127 ". QP: " << (current_acc_qp_ / current_frames_) <<
1128 " for last " << statistic_time_ms << " ms.";
1129 stat_start_time_ms_ = GetCurrentTimeMs();
1130 current_frames_ = 0;
1131 current_bytes_ = 0;
1132 current_acc_qp_ = 0;
1133 current_encoding_time_ms_ = 0;
1134 }
1135}
1136
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001137int32_t MediaCodecVideoEncoder::NextNaluPosition(
1138 uint8_t *buffer, size_t buffer_size) {
1139 if (buffer_size < H264_SC_LENGTH) {
1140 return -1;
1141 }
1142 uint8_t *head = buffer;
1143 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1144 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1145 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1146
1147 while (head < end) {
1148 if (head[0]) {
1149 head++;
1150 continue;
1151 }
1152 if (head[1]) { // got 00xx
1153 head += 2;
1154 continue;
1155 }
1156 if (head[2]) { // got 0000xx
1157 head += 3;
1158 continue;
1159 }
1160 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001161 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001162 continue;
1163 }
1164 return (int32_t)(head - buffer);
1165 }
1166 return -1;
1167}
1168
jackychen61b4d512015-04-21 15:30:11 -07001169void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström53edac62016-04-27 00:08:34 +02001170 // Methods running on the codec thread should call OnDroppedFrameOnCodecThread
1171 // directly.
1172 RTC_DCHECK(!codec_thread_checker_.CalledOnValidThread());
1173 codec_thread_->Invoke<void>(
1174 Bind(&MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread, this));
1175}
1176
1177void MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread() {
1178 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -08001179 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001180 if (scale_)
1181 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001182}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001183
Peter Boströmb7d9a972015-12-18 16:01:11 +01001184const char* MediaCodecVideoEncoder::ImplementationName() const {
1185 return "MediaCodec";
1186}
1187
perkj461121c2016-02-15 06:28:36 -08001188MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1189 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001190 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1191 ScopedLocalRefFrame local_ref_frame(jni);
1192 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001193 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001194
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001195 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1196 j_encoder_class,
1197 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1198 CHECK_EXCEPTION(jni);
1199 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001200 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001201 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1202 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1203 }
1204
Alex Glaznevad948c42015-11-18 13:06:42 -08001205 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1206 j_encoder_class,
1207 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1208 CHECK_EXCEPTION(jni);
1209 if (is_vp9_hw_supported) {
1210 ALOGD << "VP9 HW Encoder supported.";
1211 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1212 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1213 }
1214
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001215 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1216 j_encoder_class,
1217 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1218 CHECK_EXCEPTION(jni);
1219 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001220 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001221 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1222 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1223 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001224}
1225
Perec2922f2016-01-27 15:25:46 +01001226MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1227 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001228 if (egl_context_) {
1229 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1230 jni->DeleteGlobalRef(egl_context_);
1231 }
Perec2922f2016-01-27 15:25:46 +01001232}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001233
perkj30e91822015-11-20 01:31:25 -08001234void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001235 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001236 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001237 if (egl_context_) {
1238 jni->DeleteGlobalRef(egl_context_);
1239 egl_context_ = nullptr;
1240 }
perkj461121c2016-02-15 06:28:36 -08001241 egl_context_ = jni->NewGlobalRef(egl_context);
1242 if (CheckException(jni)) {
1243 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001244 }
1245}
1246
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001247webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001248 VideoCodecType type) {
1249 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001250 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001251 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001252 }
1253 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1254 it != supported_codecs_.end(); ++it) {
1255 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001256 ALOGD << "Create HW video encoder for type " << (int)type <<
1257 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001258 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001259 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001260 }
1261 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001262 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001263 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001264}
1265
1266const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1267MediaCodecVideoEncoderFactory::codecs() const {
1268 return supported_codecs_;
1269}
1270
1271void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1272 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001273 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001274 delete encoder;
1275}
1276
1277} // namespace webrtc_jni