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