blob: 6a1c58110777f2d43a3513c5c645259af3668441 [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"
Peter Boström2bc68c72015-09-24 16:22:28 +020032#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080033#include "webrtc/modules/video_coding/include/video_codec_interface.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.
Perba7dc722016-04-19 15:01:23 +0200229
230 struct InputFrameInfo {
231 InputFrameInfo(int64_t encode_start_time,
232 int32_t frame_timestamp,
233 int64_t frame_render_time_ms,
234 webrtc::VideoRotation rotation)
235 : encode_start_time(encode_start_time),
236 frame_timestamp(frame_timestamp),
237 frame_render_time_ms(frame_render_time_ms),
238 rotation(rotation) {}
239 // Time when video frame is sent to encoder input.
240 const int64_t encode_start_time;
241
242 // Input frame information.
243 const int32_t frame_timestamp;
244 const int64_t frame_render_time_ms;
245 const webrtc::VideoRotation rotation;
246 };
247 std::list<InputFrameInfo> input_frame_infos_;
248 int32_t output_timestamp_; // Last output frame timestamp from
249 // |input_frame_infos_|.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000250 int64_t output_render_time_ms_; // Last output frame render time from
Perba7dc722016-04-19 15:01:23 +0200251 // |input_frame_infos_|.
252 webrtc::VideoRotation output_rotation_; // Last output frame rotation from
253 // |input_frame_infos_|.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000254 // Frame size in bytes fed to MediaCodec.
255 int yuv_size_;
256 // True only when between a callback_->Encoded() call return a positive value
257 // and the next Encode() call being ignored.
258 bool drop_next_input_frame_;
259 // Global references; must be deleted in Release().
260 std::vector<jobject> input_buffers_;
Alex Glazneva9d08922016-02-19 15:24:06 -0800261 QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700262 // Dynamic resolution change, off by default.
263 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200264
265 // H264 bitstream parser, used to extract QP from encoded bitstreams.
266 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800267
268 // VP9 variables to populate codec specific structure.
269 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
270 // non-flexible VP9 mode.
271 uint8_t tl0_pic_idx_;
272 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800273
274 // EGL context - owned by factory, should not be allocated/destroyed
275 // by MediaCodecVideoEncoder.
276 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800277
278 // Temporary fix for VP8.
279 // Sends a key frame if frames are largely spaced apart (possibly
280 // corresponding to a large image change).
281 int64_t last_frame_received_ms_;
282 int frames_received_since_last_key_;
283 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000284};
285
286MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
287 // Call Release() to ensure no more callbacks to us after we are deleted.
288 Release();
289}
290
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000291MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800292 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000293 codecType_(codecType),
294 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000295 codec_thread_(new Thread()),
296 j_media_codec_video_encoder_class_(
297 jni,
298 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
299 j_media_codec_video_encoder_(
300 jni,
301 jni->NewObject(*j_media_codec_video_encoder_class_,
302 GetMethodID(jni,
303 *j_media_codec_video_encoder_class_,
304 "<init>",
perkj30e91822015-11-20 01:31:25 -0800305 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800306 inited_(false),
307 use_surface_(false),
308 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800309 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000310 ScopedLocalRefFrame local_ref_frame(jni);
311 // It would be nice to avoid spinning up a new thread per MediaCodec, and
312 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
313 // 2732 means that deadlocks abound. This class synchronously trampolines
314 // to |codec_thread_|, so if anything else can be coming to _us_ from
315 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
316 // in the bug, we have a problem. For now work around that with a dedicated
317 // thread.
318 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700319 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800320 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000321 jclass j_output_buffer_info_class =
322 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000323 j_init_encode_method_ = GetMethodID(
324 jni,
325 *j_media_codec_video_encoder_class_,
326 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800327 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800328 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800329 j_get_input_buffers_method_ = GetMethodID(
330 jni,
331 *j_media_codec_video_encoder_class_,
332 "getInputBuffers",
333 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000334 j_dequeue_input_buffer_method_ = GetMethodID(
335 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800336 j_encode_buffer_method_ = GetMethodID(
337 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800338 j_encode_texture_method_ = GetMethodID(
339 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
340 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000341 j_release_method_ =
342 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
343 j_set_rates_method_ = GetMethodID(
344 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000345 j_dequeue_output_buffer_method_ = GetMethodID(
346 jni,
347 *j_media_codec_video_encoder_class_,
348 "dequeueOutputBuffer",
349 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000350 j_release_output_buffer_method_ = GetMethodID(
351 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
352
353 j_color_format_field_ =
354 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
355 j_info_index_field_ =
356 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
357 j_info_buffer_field_ = GetFieldID(
358 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
359 j_info_is_key_frame_field_ =
360 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
361 j_info_presentation_timestamp_us_field_ = GetFieldID(
362 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
363 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800364 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000365 AllowBlockingCalls();
366}
367
368int32_t MediaCodecVideoEncoder::InitEncode(
369 const webrtc::VideoCodec* codec_settings,
370 int32_t /* number_of_cores */,
371 size_t /* max_payload_size */) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000372 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700373 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000374 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
375 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000376 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700377 RTC_CHECK(codec_settings->codecType == codecType_)
378 << "Unsupported codec " << codec_settings->codecType << " for "
379 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000380
asapersson1d61a512016-01-20 01:13:46 -0800381 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800382 int init_width = codec_settings->width;
383 int init_height = codec_settings->height;
Peter Boström7ace4882016-04-14 00:54:56 +0200384 scale_ = codecType_ != kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -0800385
386 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700387 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800388
Peter Boström2bc68c72015-09-24 16:22:28 +0200389 if (scale_) {
390 if (codecType_ == kVideoCodecVP8) {
pbos1f534522016-05-13 11:05:35 -0700391 quality_scaler_.Init(
392 QualityScaler::kLowVp8QpThreshold, QualityScaler::kBadVp8QpThreshold,
393 codec_settings->startBitrate, codec_settings->width,
394 codec_settings->height, codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200395 } else if (codecType_ == kVideoCodecH264) {
pbos1f534522016-05-13 11:05:35 -0700396 quality_scaler_.Init(QualityScaler::kLowH264QpThreshold,
397 QualityScaler::kBadH264QpThreshold,
pboscbac40d2016-04-13 02:51:02 -0700398 codec_settings->startBitrate, codec_settings->width,
399 codec_settings->height,
400 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200401 } else {
402 // When adding codec support to additional hardware codecs, also configure
403 // their QP thresholds for scaling.
404 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800405 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200406 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800407 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström926dfcd2016-04-14 14:48:10 +0200408 init_width = res.width;
409 init_height = res.height;
Alex Glazneva9d08922016-02-19 15:24:06 -0800410 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700411 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800412
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000413 return codec_thread_->Invoke<int32_t>(
414 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
415 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800416 init_width,
417 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000418 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800419 codec_settings->maxFramerate,
420 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000421}
422
423int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700424 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000425 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700426 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000427 return codec_thread_->Invoke<int32_t>(Bind(
428 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
429}
430
431int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
432 webrtc::EncodedImageCallback* callback) {
433 return codec_thread_->Invoke<int32_t>(
434 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
435 this,
436 callback));
437}
438
439int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700440 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000441 return codec_thread_->Invoke<int32_t>(
442 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
443}
444
445int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
446 int64_t /* rtt */) {
447 return WEBRTC_VIDEO_CODEC_OK;
448}
449
450int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
451 uint32_t frame_rate) {
452 return codec_thread_->Invoke<int32_t>(
453 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
454 this,
455 new_bit_rate,
456 frame_rate));
457}
458
459void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800460 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000461 JNIEnv* jni = AttachCurrentThreadIfNeeded();
462 ScopedLocalRefFrame local_ref_frame(jni);
463
464 // We only ever send one message to |this| directly (not through a Bind()'d
465 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700466 RTC_CHECK(!msg->message_id) << "Unexpected message!";
467 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000468 if (!inited_) {
469 return;
470 }
471
472 // It would be nice to recover from a failure here if one happened, but it's
473 // unclear how to signal such a failure to the app, so instead we stay silent
474 // about it and let the next app-called API method reveal the borkedness.
475 DeliverPendingOutputs(jni);
476 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
477}
478
perkj9576e542015-11-12 06:43:16 -0800479bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
480 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
481 ALOGE << "ResetOnCodecThread";
482 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800483 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
484 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
486 // degrade to a SW encoder at this point? There isn't one AFAICT :(
487 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800488 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000489 }
perkj9576e542015-11-12 06:43:16 -0800490 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000491}
492
493int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800494 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800495 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800496 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000497 JNIEnv* jni = AttachCurrentThreadIfNeeded();
498 ScopedLocalRefFrame local_ref_frame(jni);
499
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700500 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
501 width << " x " << height << ". Bitrate: " << kbps <<
502 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000503 if (kbps == 0) {
504 kbps = last_set_bitrate_kbps_;
505 }
506 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800507 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000508 }
509
510 width_ = width;
511 height_ = height;
512 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800513 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000514 yuv_size_ = width_ * height_ * 3 / 2;
515 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000516 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800517 frames_dropped_media_encoder_ = 0;
518 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000519 current_timestamp_us_ = 0;
Niels Möllerd28db7f2016-05-10 16:31:47 +0200520 stat_start_time_ms_ = rtc::TimeMillis();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 current_frames_ = 0;
522 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800523 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000524 current_encoding_time_ms_ = 0;
525 last_input_timestamp_ms_ = -1;
526 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000527 output_timestamp_ = 0;
528 output_render_time_ms_ = 0;
Perba7dc722016-04-19 15:01:23 +0200529 input_frame_infos_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000530 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800531 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000532 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800533 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
534 tl0_pic_idx_ = static_cast<uint8_t>(rand());
535 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800536 last_frame_received_ms_ = -1;
537 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800538
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000539 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100540 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000541 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800542 const bool encode_status = jni->CallBooleanMethod(
543 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800544 j_video_codec_enum, width, height, kbps, fps,
545 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800546 if (!encode_status) {
547 ALOGE << "Failed to configure encoder.";
548 return WEBRTC_VIDEO_CODEC_ERROR;
549 }
550 CHECK_EXCEPTION(jni);
551
Per598242a2015-11-26 14:28:55 +0100552 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800553 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
554 jni->CallObjectMethod(*j_media_codec_video_encoder_,
555 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000556 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800557 if (IsNull(jni, input_buffers)) {
558 return WEBRTC_VIDEO_CODEC_ERROR;
559 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000560
perkj30e91822015-11-20 01:31:25 -0800561 switch (GetIntField(jni, *j_media_codec_video_encoder_,
562 j_color_format_field_)) {
563 case COLOR_FormatYUV420Planar:
564 encoder_fourcc_ = libyuv::FOURCC_YU12;
565 break;
566 case COLOR_FormatYUV420SemiPlanar:
567 case COLOR_QCOM_FormatYUV420SemiPlanar:
568 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
569 encoder_fourcc_ = libyuv::FOURCC_NV12;
570 break;
571 default:
572 LOG(LS_ERROR) << "Wrong color format.";
573 return WEBRTC_VIDEO_CODEC_ERROR;
574 }
575 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
576 RTC_CHECK(input_buffers_.empty())
577 << "Unexpected double InitEncode without Release";
578 input_buffers_.resize(num_input_buffers);
579 for (size_t i = 0; i < num_input_buffers; ++i) {
580 input_buffers_[i] =
581 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
582 int64_t yuv_buffer_capacity =
583 jni->GetDirectBufferCapacity(input_buffers_[i]);
584 CHECK_EXCEPTION(jni);
585 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
586 }
587 }
perkj9576e542015-11-12 06:43:16 -0800588
589 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000590 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
591 return WEBRTC_VIDEO_CODEC_OK;
592}
593
594int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700595 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700596 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800597 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000598 JNIEnv* jni = AttachCurrentThreadIfNeeded();
599 ScopedLocalRefFrame local_ref_frame(jni);
600
601 if (!inited_) {
602 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
603 }
perkj9576e542015-11-12 06:43:16 -0800604
asapersson1d61a512016-01-20 01:13:46 -0800605 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800606 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800607 ++frames_received_since_last_key_;
Niels Möllerd28db7f2016-05-10 16:31:47 +0200608 int64_t now_ms = rtc::TimeMillis();
asapersson1d61a512016-01-20 01:13:46 -0800609 if (last_frame_received_ms_ != -1 &&
610 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
611 // Add limit to prevent triggering a key for every frame for very low
612 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
613 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
614 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
615 send_key_frame = true;
616 }
617 frames_received_since_last_key_ = 0;
618 }
619 last_frame_received_ms_ = now_ms;
620 }
621
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000622 frames_received_++;
623 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800624 if (!ResetCodecOnCodecThread())
625 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000626 }
glaznevf4decb52016-01-15 13:49:22 -0800627 if (frames_encoded_ < kMaxEncodedLogFrames) {
Perba7dc722016-04-19 15:01:23 +0200628 ALOGD << "Encoder frame in # " << (frames_received_ - 1)
629 << ". TS: " << (int)(current_timestamp_us_ / 1000)
630 << ". Q: " << input_frame_infos_.size() << ". Fps: " << last_set_fps_
631 << ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800632 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000633
634 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800635 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000636 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800637 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800638 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200639 OnDroppedFrameOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000640 return WEBRTC_VIDEO_CODEC_OK;
641 }
642
henrikg91d6ede2015-09-17 00:24:34 -0700643 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200644
Peter Boströmf7704d12016-04-11 16:42:40 +0200645 // Check if we accumulated too many frames in encoder input buffers and drop
646 // frame if so.
Perba7dc722016-04-19 15:01:23 +0200647 if (input_frame_infos_.size() > MAX_ENCODER_Q_SIZE) {
648 ALOGD << "Already " << input_frame_infos_.size()
649 << " frames in the queue, dropping"
Peter Boströmf7704d12016-04-11 16:42:40 +0200650 << ". TS: " << (int)(current_timestamp_us_ / 1000)
651 << ". Fps: " << last_set_fps_
652 << ". Consecutive drops: " << consecutive_full_queue_frame_drops_;
653 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
654 consecutive_full_queue_frame_drops_++;
655 if (consecutive_full_queue_frame_drops_ >=
656 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
657 ALOGE << "Encoder got stuck. Reset.";
658 ResetCodecOnCodecThread();
659 return WEBRTC_VIDEO_CODEC_ERROR;
glaznevf4decb52016-01-15 13:49:22 -0800660 }
Peter Boströmf7704d12016-04-11 16:42:40 +0200661 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200662 OnDroppedFrameOnCodecThread();
Peter Boströmf7704d12016-04-11 16:42:40 +0200663 return WEBRTC_VIDEO_CODEC_OK;
glaznevf4decb52016-01-15 13:49:22 -0800664 }
glaznev919ff752016-01-27 15:01:03 -0800665 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800666
Per598242a2015-11-26 14:28:55 +0100667 VideoFrame input_frame = frame;
668 if (scale_) {
669 // Check framerate before spatial resolution change.
670 quality_scaler_.OnEncodeFrame(frame);
671 const webrtc::QualityScaler::Resolution scaled_resolution =
672 quality_scaler_.GetScaledResolution();
673 if (scaled_resolution.width != frame.width() ||
674 scaled_resolution.height != frame.height()) {
nisse26acec42016-04-15 03:43:39 -0700675 if (frame.video_frame_buffer()->native_handle() != nullptr) {
Per598242a2015-11-26 14:28:55 +0100676 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
677 static_cast<AndroidTextureBuffer*>(
Magnus Jedverta3002db2016-05-13 12:51:04 +0200678 frame.video_frame_buffer().get())->CropScaleAndRotate(
679 frame.width(), frame.height(),
680 scaled_resolution.width, scaled_resolution.height,
Per71f5a9a2015-12-11 09:32:37 +0100681 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100682 input_frame.set_video_frame_buffer(scaled_buffer);
683 } else {
684 input_frame = quality_scaler_.GetScaledFrame(frame);
685 }
686 }
687 }
jackychen61b4d512015-04-21 15:30:11 -0700688
perkj9576e542015-11-12 06:43:16 -0800689 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
690 ALOGE << "Failed to reconfigure encoder.";
691 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000692 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000693
Niels Möllerd28db7f2016-05-10 16:31:47 +0200694 const int64_t time_before_calling_encode = rtc::TimeMillis();
asapersson1d61a512016-01-20 01:13:46 -0800695 const bool key_frame =
696 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800697 bool encode_status = true;
nisse26acec42016-04-15 03:43:39 -0700698 if (!input_frame.video_frame_buffer()->native_handle()) {
perkj30e91822015-11-20 01:31:25 -0800699 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
700 j_dequeue_input_buffer_method_);
701 CHECK_EXCEPTION(jni);
702 if (j_input_buffer_index == -1) {
703 // Video codec falls behind - no input buffer available.
704 ALOGW << "Encoder drop frame - no input buffers available";
glaznev919ff752016-01-27 15:01:03 -0800705 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
706 frames_dropped_media_encoder_++;
Peter Boström53edac62016-04-27 00:08:34 +0200707 OnDroppedFrameOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800708 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
709 }
710 if (j_input_buffer_index == -2) {
711 ResetCodecOnCodecThread();
712 return WEBRTC_VIDEO_CODEC_ERROR;
713 }
714 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
715 j_input_buffer_index);
716 } else {
717 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000718 }
perkj30e91822015-11-20 01:31:25 -0800719
720 if (!encode_status) {
721 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800722 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200723 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000724 }
725
Perba7dc722016-04-19 15:01:23 +0200726 // Save input image timestamps for later output.
727 input_frame_infos_.emplace_back(
728 time_before_calling_encode, input_frame.timestamp(),
729 input_frame.render_time_ms(), input_frame.rotation());
730
perkj9576e542015-11-12 06:43:16 -0800731 last_input_timestamp_ms_ =
732 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000733
perkj9576e542015-11-12 06:43:16 -0800734 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
735
perkj30e91822015-11-20 01:31:25 -0800736 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800737 ALOGE << "Failed deliver pending outputs.";
738 ResetCodecOnCodecThread();
739 return WEBRTC_VIDEO_CODEC_ERROR;
740 }
741 return WEBRTC_VIDEO_CODEC_OK;
742}
743
744bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
745 const webrtc::VideoFrame& frame) {
746 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
747
nisse26acec42016-04-15 03:43:39 -0700748 const bool is_texture_frame =
749 frame.video_frame_buffer()->native_handle() != nullptr;
perkj30e91822015-11-20 01:31:25 -0800750 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800751 const bool reconfigure_due_to_size =
752 frame.width() != width_ || frame.height() != height_;
753
perkj30e91822015-11-20 01:31:25 -0800754 if (reconfigure_due_to_format) {
755 ALOGD << "Reconfigure encoder due to format change. "
756 << (use_surface_ ?
757 "Reconfiguring to encode from byte buffer." :
758 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800759 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800760 }
perkj9576e542015-11-12 06:43:16 -0800761 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800762 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800763 << width_ << " x " << height_ << " to " << frame.width() << " x "
764 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800765 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800766 width_ = frame.width();
767 height_ = frame.height();
768 }
769
perkj30e91822015-11-20 01:31:25 -0800770 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800771 return true;
772
773 ReleaseOnCodecThread();
774
perkj30e91822015-11-20 01:31:25 -0800775 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800776 WEBRTC_VIDEO_CODEC_OK;
777}
778
779bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
780 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
781 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800782 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800783
perkj9576e542015-11-12 06:43:16 -0800784 jobject j_input_buffer = input_buffers_[input_buffer_index];
785 uint8_t* yuv_buffer =
786 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
787 CHECK_EXCEPTION(jni);
788 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
789 RTC_CHECK(!libyuv::ConvertFromI420(
nissed0dc66e2016-05-13 04:12:41 -0700790 frame.video_frame_buffer()->DataY(),
791 frame.video_frame_buffer()->StrideY(),
792 frame.video_frame_buffer()->DataU(),
793 frame.video_frame_buffer()->StrideU(),
794 frame.video_frame_buffer()->DataV(),
795 frame.video_frame_buffer()->StrideV(),
perkj9576e542015-11-12 06:43:16 -0800796 yuv_buffer, width_, width_, height_, encoder_fourcc_))
797 << "ConvertFromI420 failed";
798
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000799 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800800 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000801 key_frame,
perkj9576e542015-11-12 06:43:16 -0800802 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000803 yuv_size_,
804 current_timestamp_us_);
805 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800806 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000807}
808
perkj30e91822015-11-20 01:31:25 -0800809bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
810 bool key_frame, const webrtc::VideoFrame& frame) {
811 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
812 RTC_CHECK(use_surface_);
nisse26acec42016-04-15 03:43:39 -0700813 NativeHandleImpl* handle = static_cast<NativeHandleImpl*>(
814 frame.video_frame_buffer()->native_handle());
perkj30e91822015-11-20 01:31:25 -0800815 jfloatArray sampling_matrix = jni->NewFloatArray(16);
816 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
817
818 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
819 j_encode_texture_method_,
820 key_frame,
821 handle->oes_texture_id,
822 sampling_matrix,
823 current_timestamp_us_);
824 CHECK_EXCEPTION(jni);
825 return encode_status;
826}
827
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000828int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
829 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800830 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000831 JNIEnv* jni = AttachCurrentThreadIfNeeded();
832 ScopedLocalRefFrame local_ref_frame(jni);
833 callback_ = callback;
834 return WEBRTC_VIDEO_CODEC_OK;
835}
836
837int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800838 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000839 if (!inited_) {
840 return WEBRTC_VIDEO_CODEC_OK;
841 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000842 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700843 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
844 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800845 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000846 ScopedLocalRefFrame local_ref_frame(jni);
847 for (size_t i = 0; i < input_buffers_.size(); ++i)
848 jni->DeleteGlobalRef(input_buffers_[i]);
849 input_buffers_.clear();
850 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
851 CHECK_EXCEPTION(jni);
852 rtc::MessageQueueManager::Clear(this);
853 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800854 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700855 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000856 return WEBRTC_VIDEO_CODEC_OK;
857}
858
859int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
860 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800861 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800862 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
863 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000864 if (last_set_bitrate_kbps_ == new_bit_rate &&
865 last_set_fps_ == frame_rate) {
866 return WEBRTC_VIDEO_CODEC_OK;
867 }
glaznev919ff752016-01-27 15:01:03 -0800868 if (scale_) {
869 quality_scaler_.ReportFramerate(frame_rate);
870 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000871 JNIEnv* jni = AttachCurrentThreadIfNeeded();
872 ScopedLocalRefFrame local_ref_frame(jni);
873 if (new_bit_rate > 0) {
874 last_set_bitrate_kbps_ = new_bit_rate;
875 }
876 if (frame_rate > 0) {
877 last_set_fps_ = frame_rate;
878 }
879 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
880 j_set_rates_method_,
881 last_set_bitrate_kbps_,
882 last_set_fps_);
883 CHECK_EXCEPTION(jni);
884 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800885 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000886 return WEBRTC_VIDEO_CODEC_ERROR;
887 }
888 return WEBRTC_VIDEO_CODEC_OK;
889}
890
891int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
892 JNIEnv* jni,
893 jobject j_output_buffer_info) {
894 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
895}
896
897jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
898 JNIEnv* jni,
899 jobject j_output_buffer_info) {
900 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
901}
902
903bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
904 JNIEnv* jni,
905 jobject j_output_buffer_info) {
906 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
907}
908
909jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
910 JNIEnv* jni,
911 jobject j_output_buffer_info) {
912 return GetLongField(
913 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
914}
915
916bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800917 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000918 while (true) {
919 jobject j_output_buffer_info = jni->CallObjectMethod(
920 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
921 CHECK_EXCEPTION(jni);
922 if (IsNull(jni, j_output_buffer_info)) {
923 break;
924 }
925
926 int output_buffer_index =
927 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
928 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800929 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000930 return false;
931 }
932
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000933 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000934 jobject j_output_buffer =
935 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
936 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000937
938 // Get frame timestamps from a queue - for non config frames only.
939 int64_t frame_encoding_time_ms = 0;
940 last_output_timestamp_ms_ =
941 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
942 1000;
Perba7dc722016-04-19 15:01:23 +0200943 if (!input_frame_infos_.empty()) {
944 const InputFrameInfo& frame_info = input_frame_infos_.front();
945 output_timestamp_ = frame_info.frame_timestamp;
946 output_render_time_ms_ = frame_info.frame_render_time_ms;
947 output_rotation_ = frame_info.rotation;
948 frame_encoding_time_ms =
Niels Möllerd28db7f2016-05-10 16:31:47 +0200949 rtc::TimeMillis() - frame_info.encode_start_time;
Perba7dc722016-04-19 15:01:23 +0200950 input_frame_infos_.pop_front();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000951 }
952
953 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000954 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200955 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000956 jni->GetDirectBufferAddress(j_output_buffer));
957 CHECK_EXCEPTION(jni);
958
glaznevf4decb52016-01-15 13:49:22 -0800959 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800960 int current_latency =
961 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
962 ALOGD << "Encoder frame out # " << frames_encoded_ <<
963 ". Key: " << key_frame <<
964 ". Size: " << payload_size <<
965 ". TS: " << (int)last_output_timestamp_ms_ <<
966 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800967 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000968 }
969
970 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000971 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000972 if (callback_) {
kwibergd1fe2812016-04-27 06:47:29 -0700973 std::unique_ptr<webrtc::EncodedImage> image(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000974 new webrtc::EncodedImage(payload, payload_size, payload_size));
975 image->_encodedWidth = width_;
976 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000977 image->_timeStamp = output_timestamp_;
978 image->capture_time_ms_ = output_render_time_ms_;
Perba7dc722016-04-19 15:01:23 +0200979 image->rotation_ = output_rotation_;
Peter Boström49e196a2015-10-23 15:58:18 +0200980 image->_frameType =
981 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000982 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700983 image->adapt_reason_.quality_resolution_downscales =
984 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000985
986 webrtc::CodecSpecificInfo info;
987 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000988 info.codecType = codecType_;
989 if (codecType_ == kVideoCodecVP8) {
990 info.codecSpecific.VP8.pictureId = picture_id_;
991 info.codecSpecific.VP8.nonReference = false;
992 info.codecSpecific.VP8.simulcastIdx = 0;
993 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
994 info.codecSpecific.VP8.layerSync = false;
995 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
996 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800997 } else if (codecType_ == kVideoCodecVP9) {
998 if (key_frame) {
999 gof_idx_ = 0;
1000 }
1001 info.codecSpecific.VP9.picture_id = picture_id_;
1002 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
1003 info.codecSpecific.VP9.flexible_mode = false;
1004 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
1005 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1006 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1007 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1008 info.codecSpecific.VP9.temporal_up_switch = true;
1009 info.codecSpecific.VP9.inter_layer_predicted = false;
1010 info.codecSpecific.VP9.gof_idx =
1011 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1012 info.codecSpecific.VP9.num_spatial_layers = 1;
1013 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1014 if (info.codecSpecific.VP9.ss_data_available) {
1015 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1016 info.codecSpecific.VP9.width[0] = width_;
1017 info.codecSpecific.VP9.height[0] = height_;
1018 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1019 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001020 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001021 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001022
1023 // Generate a header describing a single fragment.
1024 webrtc::RTPFragmentationHeader header;
1025 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001026 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001027 header.VerifyAndAllocateFragmentationHeader(1);
1028 header.fragmentationOffset[0] = 0;
1029 header.fragmentationLength[0] = image->_length;
1030 header.fragmentationPlType[0] = 0;
1031 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001032 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001033 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001034 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1035 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001036 quality_scaler_.ReportQP(qp);
asapersson24ebc442016-04-19 23:48:21 -07001037 image->qp_ = qp;
glaznevf4decb52016-01-15 13:49:22 -08001038 }
asapersson86b01602015-10-20 23:55:26 -07001039 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001040 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001041 if (scale_) {
1042 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1043 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001044 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1045 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001046 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001047 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001048 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001049 // For H.264 search for start codes.
1050 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1051 int32_t scPositionsLength = 0;
1052 int32_t scPosition = 0;
1053 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1054 int32_t naluPosition = NextNaluPosition(
1055 payload + scPosition, payload_size - scPosition);
1056 if (naluPosition < 0) {
1057 break;
1058 }
1059 scPosition += naluPosition;
1060 scPositions[scPositionsLength++] = scPosition;
1061 scPosition += H264_SC_LENGTH;
1062 }
1063 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001064 ALOGE << "Start code is not found!";
1065 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1066 << " " << image->_buffer[2] << " " << image->_buffer[3]
1067 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001068 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001069 return false;
1070 }
1071 scPositions[scPositionsLength] = payload_size;
1072 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1073 for (size_t i = 0; i < scPositionsLength; i++) {
1074 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1075 header.fragmentationLength[i] =
1076 scPositions[i + 1] - header.fragmentationOffset[i];
1077 header.fragmentationPlType[i] = 0;
1078 header.fragmentationTimeDiff[i] = 0;
1079 }
1080 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001081
1082 callback_status = callback_->Encoded(*image, &info, &header);
1083 }
1084
1085 // Return output buffer back to the encoder.
1086 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1087 j_release_output_buffer_method_,
1088 output_buffer_index);
1089 CHECK_EXCEPTION(jni);
1090 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001091 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001092 return false;
1093 }
1094
glaznevf4decb52016-01-15 13:49:22 -08001095 // Calculate and print encoding statistics - every 3 seconds.
1096 frames_encoded_++;
1097 current_frames_++;
1098 current_bytes_ += payload_size;
1099 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001100 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001101
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001102 if (callback_status > 0) {
1103 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001104 // Theoretically could handle callback_status<0 here, but unclear what
1105 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001106 }
1107 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001108 return true;
1109}
1110
glaznev94291482016-02-01 13:17:18 -08001111void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
Niels Möllerd28db7f2016-05-10 16:31:47 +02001112 int statistic_time_ms = rtc::TimeMillis() - stat_start_time_ms_;
glaznev94291482016-02-01 13:17:18 -08001113 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1114 current_frames_ > 0 && statistic_time_ms > 0) {
1115 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1116 int current_fps =
1117 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1118 ALOGD << "Encoded frames: " << frames_encoded_ <<
1119 ". Bitrate: " << current_bitrate <<
1120 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1121 ", fps: " << current_fps <<
1122 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1123 ". QP: " << (current_acc_qp_ / current_frames_) <<
1124 " for last " << statistic_time_ms << " ms.";
Niels Möllerd28db7f2016-05-10 16:31:47 +02001125 stat_start_time_ms_ = rtc::TimeMillis();
glaznev94291482016-02-01 13:17:18 -08001126 current_frames_ = 0;
1127 current_bytes_ = 0;
1128 current_acc_qp_ = 0;
1129 current_encoding_time_ms_ = 0;
1130 }
1131}
1132
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001133int32_t MediaCodecVideoEncoder::NextNaluPosition(
1134 uint8_t *buffer, size_t buffer_size) {
1135 if (buffer_size < H264_SC_LENGTH) {
1136 return -1;
1137 }
1138 uint8_t *head = buffer;
1139 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1140 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1141 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1142
1143 while (head < end) {
1144 if (head[0]) {
1145 head++;
1146 continue;
1147 }
1148 if (head[1]) { // got 00xx
1149 head += 2;
1150 continue;
1151 }
1152 if (head[2]) { // got 0000xx
1153 head += 3;
1154 continue;
1155 }
1156 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001157 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001158 continue;
1159 }
1160 return (int32_t)(head - buffer);
1161 }
1162 return -1;
1163}
1164
jackychen61b4d512015-04-21 15:30:11 -07001165void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström53edac62016-04-27 00:08:34 +02001166 // Methods running on the codec thread should call OnDroppedFrameOnCodecThread
1167 // directly.
1168 RTC_DCHECK(!codec_thread_checker_.CalledOnValidThread());
1169 codec_thread_->Invoke<void>(
1170 Bind(&MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread, this));
1171}
1172
1173void MediaCodecVideoEncoder::OnDroppedFrameOnCodecThread() {
1174 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -08001175 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001176 if (scale_)
1177 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001178}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001179
Peter Boströmb7d9a972015-12-18 16:01:11 +01001180const char* MediaCodecVideoEncoder::ImplementationName() const {
1181 return "MediaCodec";
1182}
1183
perkj461121c2016-02-15 06:28:36 -08001184MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1185 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001186 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1187 ScopedLocalRefFrame local_ref_frame(jni);
1188 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001189 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001190
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001191 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1192 j_encoder_class,
1193 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1194 CHECK_EXCEPTION(jni);
1195 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001196 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001197 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1198 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1199 }
1200
Alex Glaznevad948c42015-11-18 13:06:42 -08001201 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1202 j_encoder_class,
1203 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1204 CHECK_EXCEPTION(jni);
1205 if (is_vp9_hw_supported) {
1206 ALOGD << "VP9 HW Encoder supported.";
1207 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1208 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1209 }
1210
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001211 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1212 j_encoder_class,
1213 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1214 CHECK_EXCEPTION(jni);
1215 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001216 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001217 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1218 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1219 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001220}
1221
Perec2922f2016-01-27 15:25:46 +01001222MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1223 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001224 if (egl_context_) {
1225 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1226 jni->DeleteGlobalRef(egl_context_);
1227 }
Perec2922f2016-01-27 15:25:46 +01001228}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001229
perkj30e91822015-11-20 01:31:25 -08001230void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001231 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001232 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001233 if (egl_context_) {
1234 jni->DeleteGlobalRef(egl_context_);
1235 egl_context_ = nullptr;
1236 }
perkj461121c2016-02-15 06:28:36 -08001237 egl_context_ = jni->NewGlobalRef(egl_context);
1238 if (CheckException(jni)) {
1239 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001240 }
1241}
1242
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001243webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001244 VideoCodecType type) {
1245 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001246 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001247 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001248 }
1249 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1250 it != supported_codecs_.end(); ++it) {
1251 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001252 ALOGD << "Create HW video encoder for type " << (int)type <<
1253 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001254 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001255 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001256 }
1257 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001258 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001259 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001260}
1261
1262const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1263MediaCodecVideoEncoderFactory::codecs() const {
1264 return supported_codecs_;
1265}
1266
1267void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1268 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001269 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001270 delete encoder;
1271}
1272
1273} // namespace webrtc_jni