blob: e88a94ce7f1de93d928aedf0aba1e3523383c47d [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>
16#include <list>
17
kjellandera96e2d72016-02-04 23:52:28 -080018#include "third_party/libyuv/include/libyuv/convert.h"
19#include "third_party/libyuv/include/libyuv/convert_from.h"
20#include "third_party/libyuv/include/libyuv/video_common.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010021#include "webrtc/api/java/jni/androidmediacodeccommon.h"
22#include "webrtc/api/java/jni/classreferenceholder.h"
23#include "webrtc/api/java/jni/native_handle_impl.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000024#include "webrtc/base/bind.h"
25#include "webrtc/base/checks.h"
26#include "webrtc/base/logging.h"
27#include "webrtc/base/thread.h"
perkj9576e542015-11-12 06:43:16 -080028#include "webrtc/base/thread_checker.h"
asapersson1d61a512016-01-20 01:13:46 -080029#include "webrtc/common_types.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020030#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080031#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010032#include "webrtc/modules/video_coding/utility/quality_scaler.h"
33#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010034#include "webrtc/system_wrappers/include/field_trial.h"
35#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000036
37using rtc::Bind;
38using rtc::Thread;
39using rtc::ThreadManager;
40using rtc::scoped_ptr;
41
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.
185 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800186 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000187 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
188 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
189 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800190 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000191 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800192 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800193 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000194 jmethodID j_release_method_;
195 jmethodID j_set_rates_method_;
196 jmethodID j_dequeue_output_buffer_method_;
197 jmethodID j_release_output_buffer_method_;
198 jfieldID j_color_format_field_;
199 jfieldID j_info_index_field_;
200 jfieldID j_info_buffer_field_;
201 jfieldID j_info_is_key_frame_field_;
202 jfieldID j_info_presentation_timestamp_us_field_;
203
204 // State that is valid only between InitEncode() and the next Release().
205 // Touched only on codec_thread_ so no explicit synchronization necessary.
206 int width_; // Frame width in pixels.
207 int height_; // Frame height in pixels.
208 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800209 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000210 uint16_t picture_id_;
211 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
212 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
213 int last_set_fps_; // Last-requested frame rate.
214 int64_t current_timestamp_us_; // Current frame timestamps in us.
215 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000216 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800217 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
218 // Number of dropped frames caused by full queue.
219 int consecutive_full_queue_frame_drops_;
glaznev94291482016-02-01 13:17:18 -0800220 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000221 int current_frames_; // Number of frames in the current statistics interval.
222 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800223 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000224 int current_encoding_time_ms_; // Overall encoding time in the current second
225 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
226 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
Perba7dc722016-04-19 15:01:23 +0200227
228 struct InputFrameInfo {
229 InputFrameInfo(int64_t encode_start_time,
230 int32_t frame_timestamp,
231 int64_t frame_render_time_ms,
232 webrtc::VideoRotation rotation)
233 : encode_start_time(encode_start_time),
234 frame_timestamp(frame_timestamp),
235 frame_render_time_ms(frame_render_time_ms),
236 rotation(rotation) {}
237 // Time when video frame is sent to encoder input.
238 const int64_t encode_start_time;
239
240 // Input frame information.
241 const int32_t frame_timestamp;
242 const int64_t frame_render_time_ms;
243 const webrtc::VideoRotation rotation;
244 };
245 std::list<InputFrameInfo> input_frame_infos_;
246 int32_t output_timestamp_; // Last output frame timestamp from
247 // |input_frame_infos_|.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000248 int64_t output_render_time_ms_; // Last output frame render time from
Perba7dc722016-04-19 15:01:23 +0200249 // |input_frame_infos_|.
250 webrtc::VideoRotation output_rotation_; // Last output frame rotation from
251 // |input_frame_infos_|.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000252 // Frame size in bytes fed to MediaCodec.
253 int yuv_size_;
254 // True only when between a callback_->Encoded() call return a positive value
255 // and the next Encode() call being ignored.
256 bool drop_next_input_frame_;
257 // Global references; must be deleted in Release().
258 std::vector<jobject> input_buffers_;
Alex Glazneva9d08922016-02-19 15:24:06 -0800259 QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700260 // Dynamic resolution change, off by default.
261 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200262
263 // H264 bitstream parser, used to extract QP from encoded bitstreams.
264 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800265
266 // VP9 variables to populate codec specific structure.
267 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
268 // non-flexible VP9 mode.
269 uint8_t tl0_pic_idx_;
270 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800271
272 // EGL context - owned by factory, should not be allocated/destroyed
273 // by MediaCodecVideoEncoder.
274 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800275
276 // Temporary fix for VP8.
277 // Sends a key frame if frames are largely spaced apart (possibly
278 // corresponding to a large image change).
279 int64_t last_frame_received_ms_;
280 int frames_received_since_last_key_;
281 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000282};
283
284MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
285 // Call Release() to ensure no more callbacks to us after we are deleted.
286 Release();
287}
288
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000289MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800290 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000291 codecType_(codecType),
292 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000293 codec_thread_(new Thread()),
294 j_media_codec_video_encoder_class_(
295 jni,
296 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
297 j_media_codec_video_encoder_(
298 jni,
299 jni->NewObject(*j_media_codec_video_encoder_class_,
300 GetMethodID(jni,
301 *j_media_codec_video_encoder_class_,
302 "<init>",
perkj30e91822015-11-20 01:31:25 -0800303 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800304 inited_(false),
305 use_surface_(false),
306 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800307 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000308 ScopedLocalRefFrame local_ref_frame(jni);
309 // It would be nice to avoid spinning up a new thread per MediaCodec, and
310 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
311 // 2732 means that deadlocks abound. This class synchronously trampolines
312 // to |codec_thread_|, so if anything else can be coming to _us_ from
313 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
314 // in the bug, we have a problem. For now work around that with a dedicated
315 // thread.
316 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700317 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800318 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000319 jclass j_output_buffer_info_class =
320 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000321 j_init_encode_method_ = GetMethodID(
322 jni,
323 *j_media_codec_video_encoder_class_,
324 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800325 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800326 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800327 j_get_input_buffers_method_ = GetMethodID(
328 jni,
329 *j_media_codec_video_encoder_class_,
330 "getInputBuffers",
331 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000332 j_dequeue_input_buffer_method_ = GetMethodID(
333 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800334 j_encode_buffer_method_ = GetMethodID(
335 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800336 j_encode_texture_method_ = GetMethodID(
337 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
338 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000339 j_release_method_ =
340 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
341 j_set_rates_method_ = GetMethodID(
342 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000343 j_dequeue_output_buffer_method_ = GetMethodID(
344 jni,
345 *j_media_codec_video_encoder_class_,
346 "dequeueOutputBuffer",
347 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000348 j_release_output_buffer_method_ = GetMethodID(
349 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
350
351 j_color_format_field_ =
352 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
353 j_info_index_field_ =
354 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
355 j_info_buffer_field_ = GetFieldID(
356 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
357 j_info_is_key_frame_field_ =
358 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
359 j_info_presentation_timestamp_us_field_ = GetFieldID(
360 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
361 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800362 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000363 AllowBlockingCalls();
364}
365
366int32_t MediaCodecVideoEncoder::InitEncode(
367 const webrtc::VideoCodec* codec_settings,
368 int32_t /* number_of_cores */,
369 size_t /* max_payload_size */) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000370 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700371 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000372 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
373 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000374 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700375 RTC_CHECK(codec_settings->codecType == codecType_)
376 << "Unsupported codec " << codec_settings->codecType << " for "
377 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000378
asapersson1d61a512016-01-20 01:13:46 -0800379 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800380 int init_width = codec_settings->width;
381 int init_height = codec_settings->height;
Peter Boström7ace4882016-04-14 00:54:56 +0200382 scale_ = codecType_ != kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -0800383
384 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700385 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800386
Peter Boström2bc68c72015-09-24 16:22:28 +0200387 if (scale_) {
388 if (codecType_ == kVideoCodecVP8) {
389 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
390 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
391 // always = 127. Note that in SW, QP is that of the user-level range [0,
392 // 63].
Alex Glaznev79299af2016-04-12 16:39:39 -0700393 const int kLowQpThreshold = 29;
Peter Boström2c8a2962016-04-18 12:58:02 +0200394 const int kBadQpThreshold = 100;
Peter Boström3c6eac22016-04-26 13:37:10 +0200395 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold,
pboscbac40d2016-04-13 02:51:02 -0700396 codec_settings->startBitrate, codec_settings->width,
397 codec_settings->height,
398 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200399 } else if (codecType_ == kVideoCodecH264) {
400 // H264 QP is in the range [0, 51].
Peter Boström2c8a2962016-04-18 12:58:02 +0200401 const int kLowQpThreshold = 24;
402 const int kBadQpThreshold = 39;
Peter Boström3c6eac22016-04-26 13:37:10 +0200403 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold,
pboscbac40d2016-04-13 02:51:02 -0700404 codec_settings->startBitrate, codec_settings->width,
405 codec_settings->height,
406 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200407 } else {
408 // When adding codec support to additional hardware codecs, also configure
409 // their QP thresholds for scaling.
410 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800411 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200412 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800413 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström926dfcd2016-04-14 14:48:10 +0200414 init_width = res.width;
415 init_height = res.height;
Alex Glazneva9d08922016-02-19 15:24:06 -0800416 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700417 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800418
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000419 return codec_thread_->Invoke<int32_t>(
420 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
421 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800422 init_width,
423 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000424 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800425 codec_settings->maxFramerate,
426 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000427}
428
429int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700430 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000431 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700432 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000433 return codec_thread_->Invoke<int32_t>(Bind(
434 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
435}
436
437int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
438 webrtc::EncodedImageCallback* callback) {
439 return codec_thread_->Invoke<int32_t>(
440 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
441 this,
442 callback));
443}
444
445int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700446 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000447 return codec_thread_->Invoke<int32_t>(
448 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
449}
450
451int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
452 int64_t /* rtt */) {
453 return WEBRTC_VIDEO_CODEC_OK;
454}
455
456int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
457 uint32_t frame_rate) {
458 return codec_thread_->Invoke<int32_t>(
459 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
460 this,
461 new_bit_rate,
462 frame_rate));
463}
464
465void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800466 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000467 JNIEnv* jni = AttachCurrentThreadIfNeeded();
468 ScopedLocalRefFrame local_ref_frame(jni);
469
470 // We only ever send one message to |this| directly (not through a Bind()'d
471 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700472 RTC_CHECK(!msg->message_id) << "Unexpected message!";
473 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000474 if (!inited_) {
475 return;
476 }
477
478 // It would be nice to recover from a failure here if one happened, but it's
479 // unclear how to signal such a failure to the app, so instead we stay silent
480 // about it and let the next app-called API method reveal the borkedness.
481 DeliverPendingOutputs(jni);
482 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
483}
484
perkj9576e542015-11-12 06:43:16 -0800485bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
486 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
487 ALOGE << "ResetOnCodecThread";
488 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800489 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
490 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000491 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
492 // degrade to a SW encoder at this point? There isn't one AFAICT :(
493 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800494 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000495 }
perkj9576e542015-11-12 06:43:16 -0800496 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000497}
498
499int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800500 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800501 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800502 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000503 JNIEnv* jni = AttachCurrentThreadIfNeeded();
504 ScopedLocalRefFrame local_ref_frame(jni);
505
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700506 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
507 width << " x " << height << ". Bitrate: " << kbps <<
508 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000509 if (kbps == 0) {
510 kbps = last_set_bitrate_kbps_;
511 }
512 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800513 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000514 }
515
516 width_ = width;
517 height_ = height;
518 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800519 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000520 yuv_size_ = width_ * height_ * 3 / 2;
521 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000522 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800523 frames_dropped_media_encoder_ = 0;
524 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000525 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800526 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000527 current_frames_ = 0;
528 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800529 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000530 current_encoding_time_ms_ = 0;
531 last_input_timestamp_ms_ = -1;
532 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000533 output_timestamp_ = 0;
534 output_render_time_ms_ = 0;
Perba7dc722016-04-19 15:01:23 +0200535 input_frame_infos_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000536 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800537 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800539 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
540 tl0_pic_idx_ = static_cast<uint8_t>(rand());
541 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800542 last_frame_received_ms_ = -1;
543 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800544
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000545 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100546 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000547 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800548 const bool encode_status = jni->CallBooleanMethod(
549 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800550 j_video_codec_enum, width, height, kbps, fps,
551 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800552 if (!encode_status) {
553 ALOGE << "Failed to configure encoder.";
554 return WEBRTC_VIDEO_CODEC_ERROR;
555 }
556 CHECK_EXCEPTION(jni);
557
Per598242a2015-11-26 14:28:55 +0100558 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800559 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
560 jni->CallObjectMethod(*j_media_codec_video_encoder_,
561 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000562 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800563 if (IsNull(jni, input_buffers)) {
564 return WEBRTC_VIDEO_CODEC_ERROR;
565 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000566
perkj30e91822015-11-20 01:31:25 -0800567 switch (GetIntField(jni, *j_media_codec_video_encoder_,
568 j_color_format_field_)) {
569 case COLOR_FormatYUV420Planar:
570 encoder_fourcc_ = libyuv::FOURCC_YU12;
571 break;
572 case COLOR_FormatYUV420SemiPlanar:
573 case COLOR_QCOM_FormatYUV420SemiPlanar:
574 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
575 encoder_fourcc_ = libyuv::FOURCC_NV12;
576 break;
577 default:
578 LOG(LS_ERROR) << "Wrong color format.";
579 return WEBRTC_VIDEO_CODEC_ERROR;
580 }
581 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
582 RTC_CHECK(input_buffers_.empty())
583 << "Unexpected double InitEncode without Release";
584 input_buffers_.resize(num_input_buffers);
585 for (size_t i = 0; i < num_input_buffers; ++i) {
586 input_buffers_[i] =
587 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
588 int64_t yuv_buffer_capacity =
589 jni->GetDirectBufferCapacity(input_buffers_[i]);
590 CHECK_EXCEPTION(jni);
591 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
592 }
593 }
perkj9576e542015-11-12 06:43:16 -0800594
595 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000596 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
597 return WEBRTC_VIDEO_CODEC_OK;
598}
599
600int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700601 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700602 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800603 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000604 JNIEnv* jni = AttachCurrentThreadIfNeeded();
605 ScopedLocalRefFrame local_ref_frame(jni);
606
607 if (!inited_) {
608 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
609 }
perkj9576e542015-11-12 06:43:16 -0800610
asapersson1d61a512016-01-20 01:13:46 -0800611 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800612 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800613 ++frames_received_since_last_key_;
614 int64_t now_ms = GetCurrentTimeMs();
615 if (last_frame_received_ms_ != -1 &&
616 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
617 // Add limit to prevent triggering a key for every frame for very low
618 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
619 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
620 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
621 send_key_frame = true;
622 }
623 frames_received_since_last_key_ = 0;
624 }
625 last_frame_received_ms_ = now_ms;
626 }
627
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000628 frames_received_++;
629 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800630 if (!ResetCodecOnCodecThread())
631 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000632 }
glaznevf4decb52016-01-15 13:49:22 -0800633 if (frames_encoded_ < kMaxEncodedLogFrames) {
Perba7dc722016-04-19 15:01:23 +0200634 ALOGD << "Encoder frame in # " << (frames_received_ - 1)
635 << ". TS: " << (int)(current_timestamp_us_ / 1000)
636 << ". Q: " << input_frame_infos_.size() << ". Fps: " << last_set_fps_
637 << ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800638 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000639
640 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800641 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000642 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800643 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800644 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200645 OnDroppedFrameOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000646 return WEBRTC_VIDEO_CODEC_OK;
647 }
648
henrikg91d6ede2015-09-17 00:24:34 -0700649 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200650
Peter Boströmf7704d12016-04-11 16:42:40 +0200651 // Check if we accumulated too many frames in encoder input buffers and drop
652 // frame if so.
Perba7dc722016-04-19 15:01:23 +0200653 if (input_frame_infos_.size() > MAX_ENCODER_Q_SIZE) {
654 ALOGD << "Already " << input_frame_infos_.size()
655 << " frames in the queue, dropping"
Peter Boströmf7704d12016-04-11 16:42:40 +0200656 << ". TS: " << (int)(current_timestamp_us_ / 1000)
657 << ". Fps: " << last_set_fps_
658 << ". Consecutive drops: " << consecutive_full_queue_frame_drops_;
659 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
660 consecutive_full_queue_frame_drops_++;
661 if (consecutive_full_queue_frame_drops_ >=
662 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
663 ALOGE << "Encoder got stuck. Reset.";
664 ResetCodecOnCodecThread();
665 return WEBRTC_VIDEO_CODEC_ERROR;
glaznevf4decb52016-01-15 13:49:22 -0800666 }
Peter Boströmf7704d12016-04-11 16:42:40 +0200667 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200668 OnDroppedFrameOnCodecThread();
Peter Boströmf7704d12016-04-11 16:42:40 +0200669 return WEBRTC_VIDEO_CODEC_OK;
glaznevf4decb52016-01-15 13:49:22 -0800670 }
glaznev919ff752016-01-27 15:01:03 -0800671 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800672
Per598242a2015-11-26 14:28:55 +0100673 VideoFrame input_frame = frame;
674 if (scale_) {
675 // Check framerate before spatial resolution change.
676 quality_scaler_.OnEncodeFrame(frame);
677 const webrtc::QualityScaler::Resolution scaled_resolution =
678 quality_scaler_.GetScaledResolution();
679 if (scaled_resolution.width != frame.width() ||
680 scaled_resolution.height != frame.height()) {
nisse26acec42016-04-15 03:43:39 -0700681 if (frame.video_frame_buffer()->native_handle() != nullptr) {
Per598242a2015-11-26 14:28:55 +0100682 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
683 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100684 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100685 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100686 scaled_resolution.height,
687 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100688 input_frame.set_video_frame_buffer(scaled_buffer);
689 } else {
690 input_frame = quality_scaler_.GetScaledFrame(frame);
691 }
692 }
693 }
jackychen61b4d512015-04-21 15:30:11 -0700694
perkj9576e542015-11-12 06:43:16 -0800695 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
696 ALOGE << "Failed to reconfigure encoder.";
697 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000698 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000699
Perba7dc722016-04-19 15:01:23 +0200700 const int64_t time_before_calling_encode = GetCurrentTimeMs();
asapersson1d61a512016-01-20 01:13:46 -0800701 const bool key_frame =
702 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800703 bool encode_status = true;
nisse26acec42016-04-15 03:43:39 -0700704 if (!input_frame.video_frame_buffer()->native_handle()) {
perkj30e91822015-11-20 01:31:25 -0800705 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
706 j_dequeue_input_buffer_method_);
707 CHECK_EXCEPTION(jni);
708 if (j_input_buffer_index == -1) {
709 // Video codec falls behind - no input buffer available.
710 ALOGW << "Encoder drop frame - no input buffers available";
glaznev919ff752016-01-27 15:01:03 -0800711 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
712 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200713 OnDroppedFrameOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800714 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
715 }
716 if (j_input_buffer_index == -2) {
717 ResetCodecOnCodecThread();
718 return WEBRTC_VIDEO_CODEC_ERROR;
719 }
720 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
721 j_input_buffer_index);
722 } else {
723 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000724 }
perkj30e91822015-11-20 01:31:25 -0800725
726 if (!encode_status) {
727 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800728 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200729 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000730 }
731
Perba7dc722016-04-19 15:01:23 +0200732 // Save input image timestamps for later output.
733 input_frame_infos_.emplace_back(
734 time_before_calling_encode, input_frame.timestamp(),
735 input_frame.render_time_ms(), input_frame.rotation());
736
perkj9576e542015-11-12 06:43:16 -0800737 last_input_timestamp_ms_ =
738 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000739
perkj9576e542015-11-12 06:43:16 -0800740 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
741
perkj30e91822015-11-20 01:31:25 -0800742 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800743 ALOGE << "Failed deliver pending outputs.";
744 ResetCodecOnCodecThread();
745 return WEBRTC_VIDEO_CODEC_ERROR;
746 }
747 return WEBRTC_VIDEO_CODEC_OK;
748}
749
750bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
751 const webrtc::VideoFrame& frame) {
752 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
753
nisse26acec42016-04-15 03:43:39 -0700754 const bool is_texture_frame =
755 frame.video_frame_buffer()->native_handle() != nullptr;
perkj30e91822015-11-20 01:31:25 -0800756 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800757 const bool reconfigure_due_to_size =
758 frame.width() != width_ || frame.height() != height_;
759
perkj30e91822015-11-20 01:31:25 -0800760 if (reconfigure_due_to_format) {
761 ALOGD << "Reconfigure encoder due to format change. "
762 << (use_surface_ ?
763 "Reconfiguring to encode from byte buffer." :
764 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800765 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800766 }
perkj9576e542015-11-12 06:43:16 -0800767 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800768 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800769 << width_ << " x " << height_ << " to " << frame.width() << " x "
770 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800771 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800772 width_ = frame.width();
773 height_ = frame.height();
774 }
775
perkj30e91822015-11-20 01:31:25 -0800776 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800777 return true;
778
779 ReleaseOnCodecThread();
780
perkj30e91822015-11-20 01:31:25 -0800781 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800782 WEBRTC_VIDEO_CODEC_OK;
783}
784
785bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
786 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
787 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800788 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800789
perkj9576e542015-11-12 06:43:16 -0800790 jobject j_input_buffer = input_buffers_[input_buffer_index];
791 uint8_t* yuv_buffer =
792 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
793 CHECK_EXCEPTION(jni);
794 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
795 RTC_CHECK(!libyuv::ConvertFromI420(
796 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
797 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
798 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
799 yuv_buffer, width_, width_, height_, encoder_fourcc_))
800 << "ConvertFromI420 failed";
801
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000802 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800803 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000804 key_frame,
perkj9576e542015-11-12 06:43:16 -0800805 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000806 yuv_size_,
807 current_timestamp_us_);
808 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800809 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000810}
811
perkj30e91822015-11-20 01:31:25 -0800812bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
813 bool key_frame, const webrtc::VideoFrame& frame) {
814 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
815 RTC_CHECK(use_surface_);
nisse26acec42016-04-15 03:43:39 -0700816 NativeHandleImpl* handle = static_cast<NativeHandleImpl*>(
817 frame.video_frame_buffer()->native_handle());
perkj30e91822015-11-20 01:31:25 -0800818 jfloatArray sampling_matrix = jni->NewFloatArray(16);
819 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
820
821 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
822 j_encode_texture_method_,
823 key_frame,
824 handle->oes_texture_id,
825 sampling_matrix,
826 current_timestamp_us_);
827 CHECK_EXCEPTION(jni);
828 return encode_status;
829}
830
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000831int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
832 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800833 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000834 JNIEnv* jni = AttachCurrentThreadIfNeeded();
835 ScopedLocalRefFrame local_ref_frame(jni);
836 callback_ = callback;
837 return WEBRTC_VIDEO_CODEC_OK;
838}
839
840int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800841 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000842 if (!inited_) {
843 return WEBRTC_VIDEO_CODEC_OK;
844 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000845 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700846 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
847 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800848 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000849 ScopedLocalRefFrame local_ref_frame(jni);
850 for (size_t i = 0; i < input_buffers_.size(); ++i)
851 jni->DeleteGlobalRef(input_buffers_[i]);
852 input_buffers_.clear();
853 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
854 CHECK_EXCEPTION(jni);
855 rtc::MessageQueueManager::Clear(this);
856 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800857 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700858 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000859 return WEBRTC_VIDEO_CODEC_OK;
860}
861
862int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
863 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800864 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800865 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
866 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000867 if (last_set_bitrate_kbps_ == new_bit_rate &&
868 last_set_fps_ == frame_rate) {
869 return WEBRTC_VIDEO_CODEC_OK;
870 }
glaznev919ff752016-01-27 15:01:03 -0800871 if (scale_) {
872 quality_scaler_.ReportFramerate(frame_rate);
873 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000874 JNIEnv* jni = AttachCurrentThreadIfNeeded();
875 ScopedLocalRefFrame local_ref_frame(jni);
876 if (new_bit_rate > 0) {
877 last_set_bitrate_kbps_ = new_bit_rate;
878 }
879 if (frame_rate > 0) {
880 last_set_fps_ = frame_rate;
881 }
882 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
883 j_set_rates_method_,
884 last_set_bitrate_kbps_,
885 last_set_fps_);
886 CHECK_EXCEPTION(jni);
887 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800888 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000889 return WEBRTC_VIDEO_CODEC_ERROR;
890 }
891 return WEBRTC_VIDEO_CODEC_OK;
892}
893
894int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
895 JNIEnv* jni,
896 jobject j_output_buffer_info) {
897 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
898}
899
900jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
901 JNIEnv* jni,
902 jobject j_output_buffer_info) {
903 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
904}
905
906bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
907 JNIEnv* jni,
908 jobject j_output_buffer_info) {
909 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
910}
911
912jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
913 JNIEnv* jni,
914 jobject j_output_buffer_info) {
915 return GetLongField(
916 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
917}
918
919bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800920 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000921 while (true) {
922 jobject j_output_buffer_info = jni->CallObjectMethod(
923 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
924 CHECK_EXCEPTION(jni);
925 if (IsNull(jni, j_output_buffer_info)) {
926 break;
927 }
928
929 int output_buffer_index =
930 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
931 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800932 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000933 return false;
934 }
935
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000936 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000937 jobject j_output_buffer =
938 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
939 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000940
941 // Get frame timestamps from a queue - for non config frames only.
942 int64_t frame_encoding_time_ms = 0;
943 last_output_timestamp_ms_ =
944 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
945 1000;
Perba7dc722016-04-19 15:01:23 +0200946 if (!input_frame_infos_.empty()) {
947 const InputFrameInfo& frame_info = input_frame_infos_.front();
948 output_timestamp_ = frame_info.frame_timestamp;
949 output_render_time_ms_ = frame_info.frame_render_time_ms;
950 output_rotation_ = frame_info.rotation;
951 frame_encoding_time_ms =
952 GetCurrentTimeMs() - frame_info.encode_start_time;
953 input_frame_infos_.pop_front();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000954 }
955
956 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000957 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200958 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000959 jni->GetDirectBufferAddress(j_output_buffer));
960 CHECK_EXCEPTION(jni);
961
glaznevf4decb52016-01-15 13:49:22 -0800962 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800963 int current_latency =
964 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
965 ALOGD << "Encoder frame out # " << frames_encoded_ <<
966 ". Key: " << key_frame <<
967 ". Size: " << payload_size <<
968 ". TS: " << (int)last_output_timestamp_ms_ <<
969 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800970 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000971 }
972
973 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000974 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000975 if (callback_) {
976 scoped_ptr<webrtc::EncodedImage> image(
977 new webrtc::EncodedImage(payload, payload_size, payload_size));
978 image->_encodedWidth = width_;
979 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000980 image->_timeStamp = output_timestamp_;
981 image->capture_time_ms_ = output_render_time_ms_;
Perba7dc722016-04-19 15:01:23 +0200982 image->rotation_ = output_rotation_;
Peter Boström49e196a2015-10-23 15:58:18 +0200983 image->_frameType =
984 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000985 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700986 image->adapt_reason_.quality_resolution_downscales =
987 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000988
989 webrtc::CodecSpecificInfo info;
990 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000991 info.codecType = codecType_;
992 if (codecType_ == kVideoCodecVP8) {
993 info.codecSpecific.VP8.pictureId = picture_id_;
994 info.codecSpecific.VP8.nonReference = false;
995 info.codecSpecific.VP8.simulcastIdx = 0;
996 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
997 info.codecSpecific.VP8.layerSync = false;
998 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
999 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -08001000 } else if (codecType_ == kVideoCodecVP9) {
1001 if (key_frame) {
1002 gof_idx_ = 0;
1003 }
1004 info.codecSpecific.VP9.picture_id = picture_id_;
1005 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
1006 info.codecSpecific.VP9.flexible_mode = false;
1007 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
1008 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1009 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1010 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1011 info.codecSpecific.VP9.temporal_up_switch = true;
1012 info.codecSpecific.VP9.inter_layer_predicted = false;
1013 info.codecSpecific.VP9.gof_idx =
1014 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1015 info.codecSpecific.VP9.num_spatial_layers = 1;
1016 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1017 if (info.codecSpecific.VP9.ss_data_available) {
1018 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1019 info.codecSpecific.VP9.width[0] = width_;
1020 info.codecSpecific.VP9.height[0] = height_;
1021 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1022 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001023 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001024 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001025
1026 // Generate a header describing a single fragment.
1027 webrtc::RTPFragmentationHeader header;
1028 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001029 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001030 header.VerifyAndAllocateFragmentationHeader(1);
1031 header.fragmentationOffset[0] = 0;
1032 header.fragmentationLength[0] = image->_length;
1033 header.fragmentationPlType[0] = 0;
1034 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001035 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001036 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001037 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1038 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001039 quality_scaler_.ReportQP(qp);
asapersson24ebc442016-04-19 23:48:21 -07001040 image->qp_ = qp;
glaznevf4decb52016-01-15 13:49:22 -08001041 }
asapersson86b01602015-10-20 23:55:26 -07001042 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001043 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001044 if (scale_) {
1045 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1046 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001047 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1048 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001049 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001050 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001051 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001052 // For H.264 search for start codes.
1053 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1054 int32_t scPositionsLength = 0;
1055 int32_t scPosition = 0;
1056 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1057 int32_t naluPosition = NextNaluPosition(
1058 payload + scPosition, payload_size - scPosition);
1059 if (naluPosition < 0) {
1060 break;
1061 }
1062 scPosition += naluPosition;
1063 scPositions[scPositionsLength++] = scPosition;
1064 scPosition += H264_SC_LENGTH;
1065 }
1066 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001067 ALOGE << "Start code is not found!";
1068 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1069 << " " << image->_buffer[2] << " " << image->_buffer[3]
1070 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001071 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001072 return false;
1073 }
1074 scPositions[scPositionsLength] = payload_size;
1075 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1076 for (size_t i = 0; i < scPositionsLength; i++) {
1077 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1078 header.fragmentationLength[i] =
1079 scPositions[i + 1] - header.fragmentationOffset[i];
1080 header.fragmentationPlType[i] = 0;
1081 header.fragmentationTimeDiff[i] = 0;
1082 }
1083 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001084
1085 callback_status = callback_->Encoded(*image, &info, &header);
1086 }
1087
1088 // Return output buffer back to the encoder.
1089 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1090 j_release_output_buffer_method_,
1091 output_buffer_index);
1092 CHECK_EXCEPTION(jni);
1093 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001094 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001095 return false;
1096 }
1097
glaznevf4decb52016-01-15 13:49:22 -08001098 // Calculate and print encoding statistics - every 3 seconds.
1099 frames_encoded_++;
1100 current_frames_++;
1101 current_bytes_ += payload_size;
1102 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001103 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001104
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001105 if (callback_status > 0) {
1106 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001107 // Theoretically could handle callback_status<0 here, but unclear what
1108 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001109 }
1110 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001111 return true;
1112}
1113
glaznev94291482016-02-01 13:17:18 -08001114void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1115 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1116 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1117 current_frames_ > 0 && statistic_time_ms > 0) {
1118 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1119 int current_fps =
1120 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1121 ALOGD << "Encoded frames: " << frames_encoded_ <<
1122 ". Bitrate: " << current_bitrate <<
1123 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1124 ", fps: " << current_fps <<
1125 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1126 ". QP: " << (current_acc_qp_ / current_frames_) <<
1127 " for last " << statistic_time_ms << " ms.";
1128 stat_start_time_ms_ = GetCurrentTimeMs();
1129 current_frames_ = 0;
1130 current_bytes_ = 0;
1131 current_acc_qp_ = 0;
1132 current_encoding_time_ms_ = 0;
1133 }
1134}
1135
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001136int32_t MediaCodecVideoEncoder::NextNaluPosition(
1137 uint8_t *buffer, size_t buffer_size) {
1138 if (buffer_size < H264_SC_LENGTH) {
1139 return -1;
1140 }
1141 uint8_t *head = buffer;
1142 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1143 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1144 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1145
1146 while (head < end) {
1147 if (head[0]) {
1148 head++;
1149 continue;
1150 }
1151 if (head[1]) { // got 00xx
1152 head += 2;
1153 continue;
1154 }
1155 if (head[2]) { // got 0000xx
1156 head += 3;
1157 continue;
1158 }
1159 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001160 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001161 continue;
1162 }
1163 return (int32_t)(head - buffer);
1164 }
1165 return -1;
1166}
1167
jackychen61b4d512015-04-21 15:30:11 -07001168void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström53edac62016-04-27 00:08:34 +02001169 // Methods running on the codec thread should call OnDroppedFrameOnCodecThread
1170 // directly.
1171 RTC_DCHECK(!codec_thread_checker_.CalledOnValidThread());
1172 codec_thread_->Invoke<void>(
1173 Bind(&MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread, this));
1174}
1175
1176void MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread() {
1177 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -08001178 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001179 if (scale_)
1180 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001181}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001182
Peter Boströmb7d9a972015-12-18 16:01:11 +01001183const char* MediaCodecVideoEncoder::ImplementationName() const {
1184 return "MediaCodec";
1185}
1186
perkj461121c2016-02-15 06:28:36 -08001187MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1188 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001189 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1190 ScopedLocalRefFrame local_ref_frame(jni);
1191 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001192 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001193
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001194 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1195 j_encoder_class,
1196 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1197 CHECK_EXCEPTION(jni);
1198 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001199 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001200 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1201 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1202 }
1203
Alex Glaznevad948c42015-11-18 13:06:42 -08001204 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1205 j_encoder_class,
1206 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1207 CHECK_EXCEPTION(jni);
1208 if (is_vp9_hw_supported) {
1209 ALOGD << "VP9 HW Encoder supported.";
1210 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1211 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1212 }
1213
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001214 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1215 j_encoder_class,
1216 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1217 CHECK_EXCEPTION(jni);
1218 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001219 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001220 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1221 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1222 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001223}
1224
Perec2922f2016-01-27 15:25:46 +01001225MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1226 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001227 if (egl_context_) {
1228 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1229 jni->DeleteGlobalRef(egl_context_);
1230 }
Perec2922f2016-01-27 15:25:46 +01001231}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001232
perkj30e91822015-11-20 01:31:25 -08001233void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001234 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001235 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001236 if (egl_context_) {
1237 jni->DeleteGlobalRef(egl_context_);
1238 egl_context_ = nullptr;
1239 }
perkj461121c2016-02-15 06:28:36 -08001240 egl_context_ = jni->NewGlobalRef(egl_context);
1241 if (CheckException(jni)) {
1242 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001243 }
1244}
1245
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001246webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001247 VideoCodecType type) {
1248 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001249 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001250 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001251 }
1252 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1253 it != supported_codecs_.end(); ++it) {
1254 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001255 ALOGD << "Create HW video encoder for type " << (int)type <<
1256 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001257 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001258 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001259 }
1260 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001261 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001262 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001263}
1264
1265const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1266MediaCodecVideoEncoderFactory::codecs() const {
1267 return supported_codecs_;
1268}
1269
1270void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1271 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001272 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001273 delete encoder;
1274}
1275
1276} // namespace webrtc_jni