blob: da0f2e6717420910a2c0d88c77316d039821bbae [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"
Niels Möllerd28db7f2016-05-10 16:31:47 +020030#include "webrtc/base/timeutils.h"
asapersson1d61a512016-01-20 01:13:46 -080031#include "webrtc/common_types.h"
perkj30e91822015-11-20 01:31:25 -080032#include "webrtc/modules/video_coding/include/video_codec_interface.h"
Peter Boströmcc1543a2016-05-24 12:16:26 +020033#include "webrtc/modules/video_coding/utility/h264_bitstream_parser.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010034#include "webrtc/modules/video_coding/utility/quality_scaler.h"
35#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010036#include "webrtc/system_wrappers/include/field_trial.h"
37#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000038
39using rtc::Bind;
40using rtc::Thread;
41using rtc::ThreadManager;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000042
43using webrtc::CodecSpecificInfo;
44using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070045using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000046using webrtc::RTPFragmentationHeader;
47using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000048using webrtc::VideoCodecType;
49using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000050using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080051using webrtc::kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -080052using webrtc::QualityScaler;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000053
54namespace webrtc_jni {
55
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000056// H.264 start code length.
57#define H264_SC_LENGTH 4
58// Maximum allowed NALUs in one output frame.
59#define MAX_NALUS_PERFRAME 32
60// Maximum supported HW video encoder resolution.
61#define MAX_VIDEO_WIDTH 1280
62#define MAX_VIDEO_HEIGHT 1280
63// Maximum supported HW video encoder fps.
64#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080065// Maximum allowed fps value in SetRates() call.
66#define MAX_ALLOWED_VIDEO_FPS 60
67// Maximum allowed frames in encoder input queue.
68#define MAX_ENCODER_Q_SIZE 2
glaznev919ff752016-01-27 15:01:03 -080069// Maximum amount of dropped frames caused by full encoder queue - exceeding
70// this threshold means that encoder probably got stuck and need to be reset.
71#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080072
73// Logging macros.
74#define TAG_ENCODER "MediaCodecVideoEncoder"
75#ifdef TRACK_BUFFER_TIMING
76#define ALOGV(...)
77 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
78#else
79#define ALOGV(...)
80#endif
81#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
82#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
83#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000084
asapersson1d61a512016-01-20 01:13:46 -080085namespace {
86// Maximum time limit between incoming frames before requesting a key frame.
87const size_t kFrameDiffThresholdMs = 1100;
88const int kMinKeyFrameInterval = 2;
89} // namespace
90
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000091// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
92// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
93// HW-backed video encode. This C++ class is implemented as a very thin shim,
94// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
95// MediaCodecVideoEncoder is created, operated, and destroyed on a single
96// thread, currently the libjingle Worker thread.
97class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
98 public rtc::MessageHandler {
99 public:
100 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -0800101 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800102 VideoCodecType codecType,
103 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000104
105 // webrtc::VideoEncoder implementation. Everything trampolines to
106 // |codec_thread_| for execution.
107 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
108 int32_t /* number_of_cores */,
109 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700110 int32_t Encode(const webrtc::VideoFrame& input_image,
111 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
112 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000113 int32_t RegisterEncodeCompleteCallback(
114 webrtc::EncodedImageCallback* callback) override;
115 int32_t Release() override;
116 int32_t SetChannelParameters(uint32_t /* packet_loss */,
117 int64_t /* rtt */) override;
118 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
119
120 // rtc::MessageHandler implementation.
121 void OnMessage(rtc::Message* msg) override;
122
jackychen61b4d512015-04-21 15:30:11 -0700123 void OnDroppedFrame() override;
124
Perec2922f2016-01-27 15:25:46 +0100125 bool SupportsNativeHandle() const override { return egl_context_ != nullptr; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100126 const char* ImplementationName() const override;
127
128 private:
perkj9576e542015-11-12 06:43:16 -0800129 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
130 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000131 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800132 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000133
134 // Implementation of webrtc::VideoEncoder methods above, all running on the
135 // codec thread exclusively.
136 //
137 // If width==0 then this is assumed to be a re-initialization and the
138 // previously-current values are reused instead of the passed parameters
139 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800140 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
141 bool use_surface);
142 // Reconfigure to match |frame| in width, height. Also reconfigures the
143 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
144 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800145 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000146 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700147 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700148 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800149 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
150 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800151 bool EncodeTextureOnCodecThread(JNIEnv* jni,
152 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800153
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000154 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
155 webrtc::EncodedImageCallback* callback);
156 int32_t ReleaseOnCodecThread();
157 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
Peter Boström53edac62016-04-27 00:08:34 +0200158 void OnDroppedFrameOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000159
160 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
161 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
162 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
163 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
164 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000165 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000166
167 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
168 // true on success.
169 bool DeliverPendingOutputs(JNIEnv* jni);
170
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000171 // Search for H.264 start codes.
172 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
173
glaznev94291482016-02-01 13:17:18 -0800174 // Displays encoder statistics.
175 void LogStatistics(bool force_log);
176
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000177 // Type of video codec.
178 VideoCodecType codecType_;
179
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000180 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
181 // |codec_thread_| synchronously.
182 webrtc::EncodedImageCallback* callback_;
183
184 // State that is constant for the lifetime of this object once the ctor
185 // returns.
kwibergd1fe2812016-04-27 06:47:29 -0700186 std::unique_ptr<Thread>
187 codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800188 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000189 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
190 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
191 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800192 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000193 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800194 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800195 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000196 jmethodID j_release_method_;
197 jmethodID j_set_rates_method_;
198 jmethodID j_dequeue_output_buffer_method_;
199 jmethodID j_release_output_buffer_method_;
200 jfieldID j_color_format_field_;
201 jfieldID j_info_index_field_;
202 jfieldID j_info_buffer_field_;
203 jfieldID j_info_is_key_frame_field_;
204 jfieldID j_info_presentation_timestamp_us_field_;
205
206 // State that is valid only between InitEncode() and the next Release().
207 // Touched only on codec_thread_ so no explicit synchronization necessary.
208 int width_; // Frame width in pixels.
209 int height_; // Frame height in pixels.
210 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800211 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000212 uint16_t picture_id_;
213 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
214 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
215 int last_set_fps_; // Last-requested frame rate.
216 int64_t current_timestamp_us_; // Current frame timestamps in us.
217 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000218 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800219 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
220 // Number of dropped frames caused by full queue.
221 int consecutive_full_queue_frame_drops_;
glaznev94291482016-02-01 13:17:18 -0800222 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000223 int current_frames_; // Number of frames in the current statistics interval.
224 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800225 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000226 int current_encoding_time_ms_; // Overall encoding time in the current second
227 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
228 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
sakal47456802016-05-24 00:16:58 -0700229 bool output_delivery_loop_running_; // Is the onMessage loop running
Perba7dc722016-04-19 15:01:23 +0200230
231 struct InputFrameInfo {
232 InputFrameInfo(int64_t encode_start_time,
233 int32_t frame_timestamp,
234 int64_t frame_render_time_ms,
235 webrtc::VideoRotation rotation)
236 : encode_start_time(encode_start_time),
237 frame_timestamp(frame_timestamp),
238 frame_render_time_ms(frame_render_time_ms),
239 rotation(rotation) {}
240 // Time when video frame is sent to encoder input.
241 const int64_t encode_start_time;
242
243 // Input frame information.
244 const int32_t frame_timestamp;
245 const int64_t frame_render_time_ms;
246 const webrtc::VideoRotation rotation;
247 };
248 std::list<InputFrameInfo> input_frame_infos_;
249 int32_t output_timestamp_; // Last output frame timestamp from
250 // |input_frame_infos_|.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000251 int64_t output_render_time_ms_; // Last output frame render time from
Perba7dc722016-04-19 15:01:23 +0200252 // |input_frame_infos_|.
253 webrtc::VideoRotation output_rotation_; // Last output frame rotation from
254 // |input_frame_infos_|.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000255 // Frame size in bytes fed to MediaCodec.
256 int yuv_size_;
257 // True only when between a callback_->Encoded() call return a positive value
258 // and the next Encode() call being ignored.
259 bool drop_next_input_frame_;
260 // Global references; must be deleted in Release().
261 std::vector<jobject> input_buffers_;
Alex Glazneva9d08922016-02-19 15:24:06 -0800262 QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700263 // Dynamic resolution change, off by default.
264 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200265
266 // H264 bitstream parser, used to extract QP from encoded bitstreams.
267 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800268
269 // VP9 variables to populate codec specific structure.
270 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
271 // non-flexible VP9 mode.
272 uint8_t tl0_pic_idx_;
273 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800274
275 // EGL context - owned by factory, should not be allocated/destroyed
276 // by MediaCodecVideoEncoder.
277 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800278
279 // Temporary fix for VP8.
280 // Sends a key frame if frames are largely spaced apart (possibly
281 // corresponding to a large image change).
282 int64_t last_frame_received_ms_;
283 int frames_received_since_last_key_;
284 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000285};
286
287MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
288 // Call Release() to ensure no more callbacks to us after we are deleted.
289 Release();
290}
291
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000292MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800293 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000294 codecType_(codecType),
295 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000296 codec_thread_(new Thread()),
297 j_media_codec_video_encoder_class_(
298 jni,
299 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
300 j_media_codec_video_encoder_(
301 jni,
302 jni->NewObject(*j_media_codec_video_encoder_class_,
303 GetMethodID(jni,
304 *j_media_codec_video_encoder_class_,
305 "<init>",
perkj30e91822015-11-20 01:31:25 -0800306 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800307 inited_(false),
308 use_surface_(false),
309 picture_id_(0),
sakal47456802016-05-24 00:16:58 -0700310 output_delivery_loop_running_(false),
perkj30e91822015-11-20 01:31:25 -0800311 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000312 ScopedLocalRefFrame local_ref_frame(jni);
313 // It would be nice to avoid spinning up a new thread per MediaCodec, and
314 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
315 // 2732 means that deadlocks abound. This class synchronously trampolines
316 // to |codec_thread_|, so if anything else can be coming to _us_ from
317 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
318 // in the bug, we have a problem. For now work around that with a dedicated
319 // thread.
320 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700321 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800322 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000323 jclass j_output_buffer_info_class =
324 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000325 j_init_encode_method_ = GetMethodID(
326 jni,
327 *j_media_codec_video_encoder_class_,
328 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800329 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800330 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800331 j_get_input_buffers_method_ = GetMethodID(
332 jni,
333 *j_media_codec_video_encoder_class_,
334 "getInputBuffers",
335 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000336 j_dequeue_input_buffer_method_ = GetMethodID(
337 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800338 j_encode_buffer_method_ = GetMethodID(
339 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800340 j_encode_texture_method_ = GetMethodID(
341 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
342 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000343 j_release_method_ =
344 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
345 j_set_rates_method_ = GetMethodID(
346 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000347 j_dequeue_output_buffer_method_ = GetMethodID(
348 jni,
349 *j_media_codec_video_encoder_class_,
350 "dequeueOutputBuffer",
351 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000352 j_release_output_buffer_method_ = GetMethodID(
353 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
354
355 j_color_format_field_ =
356 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
357 j_info_index_field_ =
358 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
359 j_info_buffer_field_ = GetFieldID(
360 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
361 j_info_is_key_frame_field_ =
362 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
363 j_info_presentation_timestamp_us_field_ = GetFieldID(
364 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
365 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800366 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000367 AllowBlockingCalls();
368}
369
370int32_t MediaCodecVideoEncoder::InitEncode(
371 const webrtc::VideoCodec* codec_settings,
372 int32_t /* number_of_cores */,
373 size_t /* max_payload_size */) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000374 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700375 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000376 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
377 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000378 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700379 RTC_CHECK(codec_settings->codecType == codecType_)
380 << "Unsupported codec " << codec_settings->codecType << " for "
381 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000382
asapersson1d61a512016-01-20 01:13:46 -0800383 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800384 int init_width = codec_settings->width;
385 int init_height = codec_settings->height;
Peter Boström7ace4882016-04-14 00:54:56 +0200386 scale_ = codecType_ != kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -0800387
388 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700389 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800390
Peter Boström2bc68c72015-09-24 16:22:28 +0200391 if (scale_) {
392 if (codecType_ == kVideoCodecVP8) {
pbos1f534522016-05-13 11:05:35 -0700393 quality_scaler_.Init(
394 QualityScaler::kLowVp8QpThreshold, QualityScaler::kBadVp8QpThreshold,
395 codec_settings->startBitrate, codec_settings->width,
396 codec_settings->height, codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200397 } else if (codecType_ == kVideoCodecH264) {
pbos1f534522016-05-13 11:05:35 -0700398 quality_scaler_.Init(QualityScaler::kLowH264QpThreshold,
399 QualityScaler::kBadH264QpThreshold,
pboscbac40d2016-04-13 02:51:02 -0700400 codec_settings->startBitrate, codec_settings->width,
401 codec_settings->height,
402 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200403 } else {
404 // When adding codec support to additional hardware codecs, also configure
405 // their QP thresholds for scaling.
406 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800407 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200408 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800409 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström926dfcd2016-04-14 14:48:10 +0200410 init_width = res.width;
411 init_height = res.height;
Alex Glazneva9d08922016-02-19 15:24:06 -0800412 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700413 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800414
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000415 return codec_thread_->Invoke<int32_t>(
416 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
417 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800418 init_width,
419 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000420 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800421 codec_settings->maxFramerate,
422 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000423}
424
425int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700426 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000427 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700428 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000429 return codec_thread_->Invoke<int32_t>(Bind(
430 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
431}
432
433int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
434 webrtc::EncodedImageCallback* callback) {
435 return codec_thread_->Invoke<int32_t>(
436 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
437 this,
438 callback));
439}
440
441int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700442 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000443 return codec_thread_->Invoke<int32_t>(
444 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
445}
446
447int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
448 int64_t /* rtt */) {
449 return WEBRTC_VIDEO_CODEC_OK;
450}
451
452int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
453 uint32_t frame_rate) {
454 return codec_thread_->Invoke<int32_t>(
455 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
456 this,
457 new_bit_rate,
458 frame_rate));
459}
460
461void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800462 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000463 JNIEnv* jni = AttachCurrentThreadIfNeeded();
464 ScopedLocalRefFrame local_ref_frame(jni);
465
466 // We only ever send one message to |this| directly (not through a Bind()'d
467 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700468 RTC_CHECK(!msg->message_id) << "Unexpected message!";
469 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000470 if (!inited_) {
471 return;
472 }
473
474 // It would be nice to recover from a failure here if one happened, but it's
475 // unclear how to signal such a failure to the app, so instead we stay silent
476 // about it and let the next app-called API method reveal the borkedness.
477 DeliverPendingOutputs(jni);
sakal47456802016-05-24 00:16:58 -0700478
479 // If there aren't more frames to deliver, we can stop the loop
480 if (!input_frame_infos_.empty()) {
481 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
482 } else {
483 output_delivery_loop_running_ = false;
484 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485}
486
perkj9576e542015-11-12 06:43:16 -0800487bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
488 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
489 ALOGE << "ResetOnCodecThread";
490 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800491 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
492 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000493 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
494 // degrade to a SW encoder at this point? There isn't one AFAICT :(
495 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800496 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000497 }
perkj9576e542015-11-12 06:43:16 -0800498 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000499}
500
501int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800502 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800503 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800504 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000505 JNIEnv* jni = AttachCurrentThreadIfNeeded();
506 ScopedLocalRefFrame local_ref_frame(jni);
507
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700508 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
509 width << " x " << height << ". Bitrate: " << kbps <<
510 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000511 if (kbps == 0) {
512 kbps = last_set_bitrate_kbps_;
513 }
514 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800515 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000516 }
517
518 width_ = width;
519 height_ = height;
520 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800521 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000522 yuv_size_ = width_ * height_ * 3 / 2;
523 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000524 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800525 frames_dropped_media_encoder_ = 0;
526 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000527 current_timestamp_us_ = 0;
Niels Möllerd28db7f2016-05-10 16:31:47 +0200528 stat_start_time_ms_ = rtc::TimeMillis();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000529 current_frames_ = 0;
530 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800531 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000532 current_encoding_time_ms_ = 0;
533 last_input_timestamp_ms_ = -1;
534 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000535 output_timestamp_ = 0;
536 output_render_time_ms_ = 0;
Perba7dc722016-04-19 15:01:23 +0200537 input_frame_infos_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800539 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000540 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800541 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
542 tl0_pic_idx_ = static_cast<uint8_t>(rand());
543 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800544 last_frame_received_ms_ = -1;
545 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800546
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000547 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100548 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000549 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800550 const bool encode_status = jni->CallBooleanMethod(
551 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800552 j_video_codec_enum, width, height, kbps, fps,
553 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800554 if (!encode_status) {
555 ALOGE << "Failed to configure encoder.";
556 return WEBRTC_VIDEO_CODEC_ERROR;
557 }
558 CHECK_EXCEPTION(jni);
559
Per598242a2015-11-26 14:28:55 +0100560 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800561 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
562 jni->CallObjectMethod(*j_media_codec_video_encoder_,
563 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000564 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800565 if (IsNull(jni, input_buffers)) {
566 return WEBRTC_VIDEO_CODEC_ERROR;
567 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000568
perkj30e91822015-11-20 01:31:25 -0800569 switch (GetIntField(jni, *j_media_codec_video_encoder_,
570 j_color_format_field_)) {
571 case COLOR_FormatYUV420Planar:
572 encoder_fourcc_ = libyuv::FOURCC_YU12;
573 break;
574 case COLOR_FormatYUV420SemiPlanar:
575 case COLOR_QCOM_FormatYUV420SemiPlanar:
576 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
577 encoder_fourcc_ = libyuv::FOURCC_NV12;
578 break;
579 default:
580 LOG(LS_ERROR) << "Wrong color format.";
581 return WEBRTC_VIDEO_CODEC_ERROR;
582 }
583 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
584 RTC_CHECK(input_buffers_.empty())
585 << "Unexpected double InitEncode without Release";
586 input_buffers_.resize(num_input_buffers);
587 for (size_t i = 0; i < num_input_buffers; ++i) {
588 input_buffers_[i] =
589 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
590 int64_t yuv_buffer_capacity =
591 jni->GetDirectBufferCapacity(input_buffers_[i]);
592 CHECK_EXCEPTION(jni);
593 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
594 }
595 }
perkj9576e542015-11-12 06:43:16 -0800596
597 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000598 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_;
Niels Möllerd28db7f2016-05-10 16:31:47 +0200615 int64_t now_ms = rtc::TimeMillis();
asapersson1d61a512016-01-20 01:13:46 -0800616 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*>(
Magnus Jedverta3002db2016-05-13 12:51:04 +0200685 frame.video_frame_buffer().get())->CropScaleAndRotate(
686 frame.width(), frame.height(),
687 scaled_resolution.width, scaled_resolution.height,
Per71f5a9a2015-12-11 09:32:37 +0100688 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
Niels Möllerd28db7f2016-05-10 16:31:47 +0200701 const int64_t time_before_calling_encode = rtc::TimeMillis();
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
sakal47456802016-05-24 00:16:58 -0700743 if (!output_delivery_loop_running_) {
744 output_delivery_loop_running_ = true;
745 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
746 }
747
perkj30e91822015-11-20 01:31:25 -0800748 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800749 ALOGE << "Failed deliver pending outputs.";
750 ResetCodecOnCodecThread();
751 return WEBRTC_VIDEO_CODEC_ERROR;
752 }
753 return WEBRTC_VIDEO_CODEC_OK;
754}
755
756bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
757 const webrtc::VideoFrame& frame) {
758 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
759
nisse26acec42016-04-15 03:43:39 -0700760 const bool is_texture_frame =
761 frame.video_frame_buffer()->native_handle() != nullptr;
perkj30e91822015-11-20 01:31:25 -0800762 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800763 const bool reconfigure_due_to_size =
764 frame.width() != width_ || frame.height() != height_;
765
perkj30e91822015-11-20 01:31:25 -0800766 if (reconfigure_due_to_format) {
767 ALOGD << "Reconfigure encoder due to format change. "
768 << (use_surface_ ?
769 "Reconfiguring to encode from byte buffer." :
770 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800771 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800772 }
perkj9576e542015-11-12 06:43:16 -0800773 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800774 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800775 << width_ << " x " << height_ << " to " << frame.width() << " x "
776 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800777 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800778 width_ = frame.width();
779 height_ = frame.height();
780 }
781
perkj30e91822015-11-20 01:31:25 -0800782 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800783 return true;
784
785 ReleaseOnCodecThread();
786
perkj30e91822015-11-20 01:31:25 -0800787 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800788 WEBRTC_VIDEO_CODEC_OK;
789}
790
791bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
792 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
793 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800794 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800795
perkj9576e542015-11-12 06:43:16 -0800796 jobject j_input_buffer = input_buffers_[input_buffer_index];
797 uint8_t* yuv_buffer =
798 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
799 CHECK_EXCEPTION(jni);
800 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
801 RTC_CHECK(!libyuv::ConvertFromI420(
nissec9c142f2016-05-17 04:05:47 -0700802 frame.video_frame_buffer()->DataY(),
803 frame.video_frame_buffer()->StrideY(),
804 frame.video_frame_buffer()->DataU(),
805 frame.video_frame_buffer()->StrideU(),
806 frame.video_frame_buffer()->DataV(),
807 frame.video_frame_buffer()->StrideV(),
perkj9576e542015-11-12 06:43:16 -0800808 yuv_buffer, width_, width_, height_, encoder_fourcc_))
809 << "ConvertFromI420 failed";
810
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000811 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800812 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000813 key_frame,
perkj9576e542015-11-12 06:43:16 -0800814 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000815 yuv_size_,
816 current_timestamp_us_);
817 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800818 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000819}
820
perkj30e91822015-11-20 01:31:25 -0800821bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
822 bool key_frame, const webrtc::VideoFrame& frame) {
823 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
824 RTC_CHECK(use_surface_);
nisse26acec42016-04-15 03:43:39 -0700825 NativeHandleImpl* handle = static_cast<NativeHandleImpl*>(
826 frame.video_frame_buffer()->native_handle());
perkj30e91822015-11-20 01:31:25 -0800827 jfloatArray sampling_matrix = jni->NewFloatArray(16);
828 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
829
830 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
831 j_encode_texture_method_,
832 key_frame,
833 handle->oes_texture_id,
834 sampling_matrix,
835 current_timestamp_us_);
836 CHECK_EXCEPTION(jni);
837 return encode_status;
838}
839
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000840int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
841 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800842 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000843 JNIEnv* jni = AttachCurrentThreadIfNeeded();
844 ScopedLocalRefFrame local_ref_frame(jni);
845 callback_ = callback;
846 return WEBRTC_VIDEO_CODEC_OK;
847}
848
849int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800850 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000851 if (!inited_) {
852 return WEBRTC_VIDEO_CODEC_OK;
853 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000854 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700855 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
856 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800857 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000858 ScopedLocalRefFrame local_ref_frame(jni);
859 for (size_t i = 0; i < input_buffers_.size(); ++i)
860 jni->DeleteGlobalRef(input_buffers_[i]);
861 input_buffers_.clear();
862 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
863 CHECK_EXCEPTION(jni);
864 rtc::MessageQueueManager::Clear(this);
865 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800866 use_surface_ = false;
sakal47456802016-05-24 00:16:58 -0700867 output_delivery_loop_running_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700868 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000869 return WEBRTC_VIDEO_CODEC_OK;
870}
871
872int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
873 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800874 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800875 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
876 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000877 if (last_set_bitrate_kbps_ == new_bit_rate &&
878 last_set_fps_ == frame_rate) {
879 return WEBRTC_VIDEO_CODEC_OK;
880 }
glaznev919ff752016-01-27 15:01:03 -0800881 if (scale_) {
882 quality_scaler_.ReportFramerate(frame_rate);
883 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000884 JNIEnv* jni = AttachCurrentThreadIfNeeded();
885 ScopedLocalRefFrame local_ref_frame(jni);
886 if (new_bit_rate > 0) {
887 last_set_bitrate_kbps_ = new_bit_rate;
888 }
889 if (frame_rate > 0) {
890 last_set_fps_ = frame_rate;
891 }
892 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
893 j_set_rates_method_,
894 last_set_bitrate_kbps_,
895 last_set_fps_);
896 CHECK_EXCEPTION(jni);
897 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800898 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000899 return WEBRTC_VIDEO_CODEC_ERROR;
900 }
901 return WEBRTC_VIDEO_CODEC_OK;
902}
903
904int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
905 JNIEnv* jni,
906 jobject j_output_buffer_info) {
907 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
908}
909
910jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
911 JNIEnv* jni,
912 jobject j_output_buffer_info) {
913 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
914}
915
916bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
917 JNIEnv* jni,
918 jobject j_output_buffer_info) {
919 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
920}
921
922jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
923 JNIEnv* jni,
924 jobject j_output_buffer_info) {
925 return GetLongField(
926 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
927}
928
929bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800930 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000931 while (true) {
932 jobject j_output_buffer_info = jni->CallObjectMethod(
933 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
934 CHECK_EXCEPTION(jni);
935 if (IsNull(jni, j_output_buffer_info)) {
936 break;
937 }
938
939 int output_buffer_index =
940 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
941 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800942 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000943 return false;
944 }
945
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000946 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000947 jobject j_output_buffer =
948 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
949 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000950
951 // Get frame timestamps from a queue - for non config frames only.
952 int64_t frame_encoding_time_ms = 0;
953 last_output_timestamp_ms_ =
954 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
sakal47456802016-05-24 00:16:58 -0700955 rtc::kNumMicrosecsPerMillisec;
Perba7dc722016-04-19 15:01:23 +0200956 if (!input_frame_infos_.empty()) {
957 const InputFrameInfo& frame_info = input_frame_infos_.front();
958 output_timestamp_ = frame_info.frame_timestamp;
959 output_render_time_ms_ = frame_info.frame_render_time_ms;
960 output_rotation_ = frame_info.rotation;
961 frame_encoding_time_ms =
Niels Möllerd28db7f2016-05-10 16:31:47 +0200962 rtc::TimeMillis() - frame_info.encode_start_time;
Perba7dc722016-04-19 15:01:23 +0200963 input_frame_infos_.pop_front();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000964 }
965
966 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000967 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200968 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000969 jni->GetDirectBufferAddress(j_output_buffer));
970 CHECK_EXCEPTION(jni);
971
glaznevf4decb52016-01-15 13:49:22 -0800972 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800973 int current_latency =
974 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
975 ALOGD << "Encoder frame out # " << frames_encoded_ <<
976 ". Key: " << key_frame <<
977 ". Size: " << payload_size <<
978 ". TS: " << (int)last_output_timestamp_ms_ <<
979 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800980 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000981 }
982
983 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000984 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000985 if (callback_) {
kwibergd1fe2812016-04-27 06:47:29 -0700986 std::unique_ptr<webrtc::EncodedImage> image(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000987 new webrtc::EncodedImage(payload, payload_size, payload_size));
988 image->_encodedWidth = width_;
989 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000990 image->_timeStamp = output_timestamp_;
991 image->capture_time_ms_ = output_render_time_ms_;
Perba7dc722016-04-19 15:01:23 +0200992 image->rotation_ = output_rotation_;
Peter Boström49e196a2015-10-23 15:58:18 +0200993 image->_frameType =
994 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000995 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700996 image->adapt_reason_.quality_resolution_downscales =
997 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000998
999 webrtc::CodecSpecificInfo info;
1000 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001001 info.codecType = codecType_;
1002 if (codecType_ == kVideoCodecVP8) {
1003 info.codecSpecific.VP8.pictureId = picture_id_;
1004 info.codecSpecific.VP8.nonReference = false;
1005 info.codecSpecific.VP8.simulcastIdx = 0;
1006 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
1007 info.codecSpecific.VP8.layerSync = false;
1008 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
1009 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -08001010 } else if (codecType_ == kVideoCodecVP9) {
1011 if (key_frame) {
1012 gof_idx_ = 0;
1013 }
1014 info.codecSpecific.VP9.picture_id = picture_id_;
1015 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
1016 info.codecSpecific.VP9.flexible_mode = false;
1017 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
1018 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1019 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1020 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1021 info.codecSpecific.VP9.temporal_up_switch = true;
1022 info.codecSpecific.VP9.inter_layer_predicted = false;
1023 info.codecSpecific.VP9.gof_idx =
1024 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1025 info.codecSpecific.VP9.num_spatial_layers = 1;
1026 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1027 if (info.codecSpecific.VP9.ss_data_available) {
1028 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1029 info.codecSpecific.VP9.width[0] = width_;
1030 info.codecSpecific.VP9.height[0] = height_;
1031 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1032 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001033 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001034 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001035
1036 // Generate a header describing a single fragment.
1037 webrtc::RTPFragmentationHeader header;
1038 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001039 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001040 header.VerifyAndAllocateFragmentationHeader(1);
1041 header.fragmentationOffset[0] = 0;
1042 header.fragmentationLength[0] = image->_length;
1043 header.fragmentationPlType[0] = 0;
1044 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001045 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001046 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001047 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1048 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001049 quality_scaler_.ReportQP(qp);
asapersson24ebc442016-04-19 23:48:21 -07001050 image->qp_ = qp;
glaznevf4decb52016-01-15 13:49:22 -08001051 }
asapersson86b01602015-10-20 23:55:26 -07001052 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001053 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001054 if (scale_) {
1055 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1056 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001057 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1058 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001059 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001060 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001061 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001062 // For H.264 search for start codes.
1063 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1064 int32_t scPositionsLength = 0;
1065 int32_t scPosition = 0;
1066 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1067 int32_t naluPosition = NextNaluPosition(
1068 payload + scPosition, payload_size - scPosition);
1069 if (naluPosition < 0) {
1070 break;
1071 }
1072 scPosition += naluPosition;
1073 scPositions[scPositionsLength++] = scPosition;
1074 scPosition += H264_SC_LENGTH;
1075 }
1076 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001077 ALOGE << "Start code is not found!";
1078 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1079 << " " << image->_buffer[2] << " " << image->_buffer[3]
1080 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001081 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001082 return false;
1083 }
1084 scPositions[scPositionsLength] = payload_size;
1085 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1086 for (size_t i = 0; i < scPositionsLength; i++) {
1087 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1088 header.fragmentationLength[i] =
1089 scPositions[i + 1] - header.fragmentationOffset[i];
1090 header.fragmentationPlType[i] = 0;
1091 header.fragmentationTimeDiff[i] = 0;
1092 }
1093 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001094
1095 callback_status = callback_->Encoded(*image, &info, &header);
1096 }
1097
1098 // Return output buffer back to the encoder.
1099 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1100 j_release_output_buffer_method_,
1101 output_buffer_index);
1102 CHECK_EXCEPTION(jni);
1103 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001104 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001105 return false;
1106 }
1107
glaznevf4decb52016-01-15 13:49:22 -08001108 // Calculate and print encoding statistics - every 3 seconds.
1109 frames_encoded_++;
1110 current_frames_++;
1111 current_bytes_ += payload_size;
1112 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001113 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001114
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001115 if (callback_status > 0) {
1116 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001117 // Theoretically could handle callback_status<0 here, but unclear what
1118 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001119 }
1120 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001121 return true;
1122}
1123
glaznev94291482016-02-01 13:17:18 -08001124void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
Niels Möllerd28db7f2016-05-10 16:31:47 +02001125 int statistic_time_ms = rtc::TimeMillis() - stat_start_time_ms_;
glaznev94291482016-02-01 13:17:18 -08001126 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1127 current_frames_ > 0 && statistic_time_ms > 0) {
1128 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1129 int current_fps =
1130 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1131 ALOGD << "Encoded frames: " << frames_encoded_ <<
1132 ". Bitrate: " << current_bitrate <<
1133 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1134 ", fps: " << current_fps <<
1135 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1136 ". QP: " << (current_acc_qp_ / current_frames_) <<
1137 " for last " << statistic_time_ms << " ms.";
Niels Möllerd28db7f2016-05-10 16:31:47 +02001138 stat_start_time_ms_ = rtc::TimeMillis();
glaznev94291482016-02-01 13:17:18 -08001139 current_frames_ = 0;
1140 current_bytes_ = 0;
1141 current_acc_qp_ = 0;
1142 current_encoding_time_ms_ = 0;
1143 }
1144}
1145
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001146int32_t MediaCodecVideoEncoder::NextNaluPosition(
1147 uint8_t *buffer, size_t buffer_size) {
1148 if (buffer_size < H264_SC_LENGTH) {
1149 return -1;
1150 }
1151 uint8_t *head = buffer;
1152 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1153 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1154 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1155
1156 while (head < end) {
1157 if (head[0]) {
1158 head++;
1159 continue;
1160 }
1161 if (head[1]) { // got 00xx
1162 head += 2;
1163 continue;
1164 }
1165 if (head[2]) { // got 0000xx
1166 head += 3;
1167 continue;
1168 }
1169 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001170 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001171 continue;
1172 }
1173 return (int32_t)(head - buffer);
1174 }
1175 return -1;
1176}
1177
jackychen61b4d512015-04-21 15:30:11 -07001178void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström53edac62016-04-27 00:08:34 +02001179 // Methods running on the codec thread should call OnDroppedFrameOnCodecThread
1180 // directly.
1181 RTC_DCHECK(!codec_thread_checker_.CalledOnValidThread());
1182 codec_thread_->Invoke<void>(
1183 Bind(&MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread, this));
1184}
1185
1186void MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread() {
1187 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -08001188 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001189 if (scale_)
1190 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001191}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001192
Peter Boströmb7d9a972015-12-18 16:01:11 +01001193const char* MediaCodecVideoEncoder::ImplementationName() const {
1194 return "MediaCodec";
1195}
1196
perkj461121c2016-02-15 06:28:36 -08001197MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1198 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001199 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1200 ScopedLocalRefFrame local_ref_frame(jni);
1201 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001202 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001203
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001204 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1205 j_encoder_class,
1206 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1207 CHECK_EXCEPTION(jni);
1208 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001209 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001210 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1211 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1212 }
1213
Alex Glaznevad948c42015-11-18 13:06:42 -08001214 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1215 j_encoder_class,
1216 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1217 CHECK_EXCEPTION(jni);
1218 if (is_vp9_hw_supported) {
1219 ALOGD << "VP9 HW Encoder supported.";
1220 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1221 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1222 }
1223
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001224 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1225 j_encoder_class,
1226 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1227 CHECK_EXCEPTION(jni);
1228 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001229 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001230 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1231 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1232 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001233}
1234
Perec2922f2016-01-27 15:25:46 +01001235MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1236 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001237 if (egl_context_) {
1238 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1239 jni->DeleteGlobalRef(egl_context_);
1240 }
Perec2922f2016-01-27 15:25:46 +01001241}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001242
perkj30e91822015-11-20 01:31:25 -08001243void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001244 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001245 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001246 if (egl_context_) {
1247 jni->DeleteGlobalRef(egl_context_);
1248 egl_context_ = nullptr;
1249 }
perkj461121c2016-02-15 06:28:36 -08001250 egl_context_ = jni->NewGlobalRef(egl_context);
1251 if (CheckException(jni)) {
1252 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001253 }
1254}
1255
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001256webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001257 VideoCodecType type) {
1258 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001259 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001260 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001261 }
1262 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1263 it != supported_codecs_.end(); ++it) {
1264 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001265 ALOGD << "Create HW video encoder for type " << (int)type <<
1266 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001267 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001268 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001269 }
1270 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001271 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001272 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001273}
1274
1275const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1276MediaCodecVideoEncoderFactory::codecs() const {
1277 return supported_codecs_;
1278}
1279
1280void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1281 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001282 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001283 delete encoder;
1284}
1285
1286} // namespace webrtc_jni