blob: 71e297c948ddbc29839e973961f5d92b5ca13895 [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
kjellandera96e2d72016-02-04 23:52:28 -080015#include "third_party/libyuv/include/libyuv/convert.h"
16#include "third_party/libyuv/include/libyuv/convert_from.h"
17#include "third_party/libyuv/include/libyuv/video_common.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/java/jni/androidmediacodeccommon.h"
19#include "webrtc/api/java/jni/classreferenceholder.h"
20#include "webrtc/api/java/jni/native_handle_impl.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000021#include "webrtc/base/bind.h"
22#include "webrtc/base/checks.h"
23#include "webrtc/base/logging.h"
24#include "webrtc/base/thread.h"
perkj9576e542015-11-12 06:43:16 -080025#include "webrtc/base/thread_checker.h"
asapersson1d61a512016-01-20 01:13:46 -080026#include "webrtc/common_types.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020027#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080028#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010029#include "webrtc/modules/video_coding/utility/quality_scaler.h"
30#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010031#include "webrtc/system_wrappers/include/field_trial.h"
32#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000033
34using rtc::Bind;
35using rtc::Thread;
36using rtc::ThreadManager;
37using rtc::scoped_ptr;
38
39using webrtc::CodecSpecificInfo;
40using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070041using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000042using webrtc::RTPFragmentationHeader;
43using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000044using webrtc::VideoCodecType;
45using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000046using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080047using webrtc::kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -080048using webrtc::QualityScaler;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000049
50namespace webrtc_jni {
51
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000052// H.264 start code length.
53#define H264_SC_LENGTH 4
54// Maximum allowed NALUs in one output frame.
55#define MAX_NALUS_PERFRAME 32
56// Maximum supported HW video encoder resolution.
57#define MAX_VIDEO_WIDTH 1280
58#define MAX_VIDEO_HEIGHT 1280
59// Maximum supported HW video encoder fps.
60#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080061// Maximum allowed fps value in SetRates() call.
62#define MAX_ALLOWED_VIDEO_FPS 60
63// Maximum allowed frames in encoder input queue.
64#define MAX_ENCODER_Q_SIZE 2
65// Maximum allowed latency in ms.
66#define MAX_ENCODER_LATENCY_MS 70
glaznev919ff752016-01-27 15:01:03 -080067// Maximum amount of dropped frames caused by full encoder queue - exceeding
68// this threshold means that encoder probably got stuck and need to be reset.
69#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080070
71// Logging macros.
72#define TAG_ENCODER "MediaCodecVideoEncoder"
73#ifdef TRACK_BUFFER_TIMING
74#define ALOGV(...)
75 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
76#else
77#define ALOGV(...)
78#endif
79#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
80#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
81#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000082
asapersson1d61a512016-01-20 01:13:46 -080083namespace {
84// Maximum time limit between incoming frames before requesting a key frame.
85const size_t kFrameDiffThresholdMs = 1100;
86const int kMinKeyFrameInterval = 2;
87} // namespace
88
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000089// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
90// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
91// HW-backed video encode. This C++ class is implemented as a very thin shim,
92// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
93// MediaCodecVideoEncoder is created, operated, and destroyed on a single
94// thread, currently the libjingle Worker thread.
95class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
96 public rtc::MessageHandler {
97 public:
98 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -080099 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800100 VideoCodecType codecType,
101 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000102
103 // webrtc::VideoEncoder implementation. Everything trampolines to
104 // |codec_thread_| for execution.
105 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
106 int32_t /* number_of_cores */,
107 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700108 int32_t Encode(const webrtc::VideoFrame& input_image,
109 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
110 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000111 int32_t RegisterEncodeCompleteCallback(
112 webrtc::EncodedImageCallback* callback) override;
113 int32_t Release() override;
114 int32_t SetChannelParameters(uint32_t /* packet_loss */,
115 int64_t /* rtt */) override;
116 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
117
118 // rtc::MessageHandler implementation.
119 void OnMessage(rtc::Message* msg) override;
120
jackychen61b4d512015-04-21 15:30:11 -0700121 void OnDroppedFrame() override;
122
jackychen6e2ce6e2015-07-13 16:26:33 -0700123 int GetTargetFramerate() 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:
129 // CHECK-fail if not running on |codec_thread_|.
130 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800131
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000132 private:
perkj9576e542015-11-12 06:43:16 -0800133 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
134 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000135 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800136 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000137
138 // Implementation of webrtc::VideoEncoder methods above, all running on the
139 // codec thread exclusively.
140 //
141 // If width==0 then this is assumed to be a re-initialization and the
142 // previously-current values are reused instead of the passed parameters
143 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800144 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
145 bool use_surface);
146 // Reconfigure to match |frame| in width, height. Also reconfigures the
147 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
148 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800149 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000150 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700151 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700152 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800153 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
154 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800155 bool EncodeTextureOnCodecThread(JNIEnv* jni,
156 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800157
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000158 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
159 webrtc::EncodedImageCallback* callback);
160 int32_t ReleaseOnCodecThread();
161 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
162
163 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
164 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
165 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
166 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
167 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000168 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000169
170 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
171 // true on success.
172 bool DeliverPendingOutputs(JNIEnv* jni);
173
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000174 // Search for H.264 start codes.
175 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
176
glaznev94291482016-02-01 13:17:18 -0800177 // Displays encoder statistics.
178 void LogStatistics(bool force_log);
179
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000180 // Type of video codec.
181 VideoCodecType codecType_;
182
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000183 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
184 // |codec_thread_| synchronously.
185 webrtc::EncodedImageCallback* callback_;
186
187 // State that is constant for the lifetime of this object once the ctor
188 // returns.
189 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800190 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000191 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
192 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
193 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800194 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000195 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800196 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800197 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000198 jmethodID j_release_method_;
199 jmethodID j_set_rates_method_;
200 jmethodID j_dequeue_output_buffer_method_;
201 jmethodID j_release_output_buffer_method_;
202 jfieldID j_color_format_field_;
203 jfieldID j_info_index_field_;
204 jfieldID j_info_buffer_field_;
205 jfieldID j_info_is_key_frame_field_;
206 jfieldID j_info_presentation_timestamp_us_field_;
207
208 // State that is valid only between InitEncode() and the next Release().
209 // Touched only on codec_thread_ so no explicit synchronization necessary.
210 int width_; // Frame width in pixels.
211 int height_; // Frame height in pixels.
212 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800213 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000214 uint16_t picture_id_;
215 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
216 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
217 int last_set_fps_; // Last-requested frame rate.
218 int64_t current_timestamp_us_; // Current frame timestamps in us.
219 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000220 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800221 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
222 // Number of dropped frames caused by full queue.
223 int consecutive_full_queue_frame_drops_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000224 int frames_in_queue_; // Number of frames in encoder queue.
glaznev94291482016-02-01 13:17:18 -0800225 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000226 int current_frames_; // Number of frames in the current statistics interval.
227 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800228 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000229 int current_encoding_time_ms_; // Overall encoding time in the current second
230 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
231 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
232 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
233 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
234 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
235 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000236 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
237 int64_t output_render_time_ms_; // Last output frame render time from
238 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000239 // Frame size in bytes fed to MediaCodec.
240 int yuv_size_;
241 // True only when between a callback_->Encoded() call return a positive value
242 // and the next Encode() call being ignored.
243 bool drop_next_input_frame_;
244 // Global references; must be deleted in Release().
245 std::vector<jobject> input_buffers_;
Alex Glazneva9d08922016-02-19 15:24:06 -0800246 QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700247 // Dynamic resolution change, off by default.
248 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200249
250 // H264 bitstream parser, used to extract QP from encoded bitstreams.
251 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800252
253 // VP9 variables to populate codec specific structure.
254 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
255 // non-flexible VP9 mode.
256 uint8_t tl0_pic_idx_;
257 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800258
259 // EGL context - owned by factory, should not be allocated/destroyed
260 // by MediaCodecVideoEncoder.
261 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800262
263 // Temporary fix for VP8.
264 // Sends a key frame if frames are largely spaced apart (possibly
265 // corresponding to a large image change).
266 int64_t last_frame_received_ms_;
267 int frames_received_since_last_key_;
268 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000269};
270
271MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
272 // Call Release() to ensure no more callbacks to us after we are deleted.
273 Release();
274}
275
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000276MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800277 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000278 codecType_(codecType),
279 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000280 codec_thread_(new Thread()),
281 j_media_codec_video_encoder_class_(
282 jni,
283 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
284 j_media_codec_video_encoder_(
285 jni,
286 jni->NewObject(*j_media_codec_video_encoder_class_,
287 GetMethodID(jni,
288 *j_media_codec_video_encoder_class_,
289 "<init>",
perkj30e91822015-11-20 01:31:25 -0800290 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800291 inited_(false),
292 use_surface_(false),
293 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800294 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000295 ScopedLocalRefFrame local_ref_frame(jni);
296 // It would be nice to avoid spinning up a new thread per MediaCodec, and
297 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
298 // 2732 means that deadlocks abound. This class synchronously trampolines
299 // to |codec_thread_|, so if anything else can be coming to _us_ from
300 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
301 // in the bug, we have a problem. For now work around that with a dedicated
302 // thread.
303 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700304 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800305 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000306 jclass j_output_buffer_info_class =
307 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000308 j_init_encode_method_ = GetMethodID(
309 jni,
310 *j_media_codec_video_encoder_class_,
311 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800312 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800313 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800314 j_get_input_buffers_method_ = GetMethodID(
315 jni,
316 *j_media_codec_video_encoder_class_,
317 "getInputBuffers",
318 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000319 j_dequeue_input_buffer_method_ = GetMethodID(
320 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800321 j_encode_buffer_method_ = GetMethodID(
322 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800323 j_encode_texture_method_ = GetMethodID(
324 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
325 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000326 j_release_method_ =
327 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
328 j_set_rates_method_ = GetMethodID(
329 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000330 j_dequeue_output_buffer_method_ = GetMethodID(
331 jni,
332 *j_media_codec_video_encoder_class_,
333 "dequeueOutputBuffer",
334 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000335 j_release_output_buffer_method_ = GetMethodID(
336 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
337
338 j_color_format_field_ =
339 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
340 j_info_index_field_ =
341 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
342 j_info_buffer_field_ = GetFieldID(
343 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
344 j_info_is_key_frame_field_ =
345 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
346 j_info_presentation_timestamp_us_field_ = GetFieldID(
347 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
348 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800349 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000350 AllowBlockingCalls();
351}
352
353int32_t MediaCodecVideoEncoder::InitEncode(
354 const webrtc::VideoCodec* codec_settings,
355 int32_t /* number_of_cores */,
356 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700357 const int kMinWidth = 320;
358 const int kMinHeight = 180;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000359 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700360 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000361 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
362 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000363 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700364 RTC_CHECK(codec_settings->codecType == codecType_)
365 << "Unsupported codec " << codec_settings->codecType << " for "
366 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000367
asapersson1d61a512016-01-20 01:13:46 -0800368 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800369 int init_width = codec_settings->width;
370 int init_height = codec_settings->height;
Alex Glaznevad948c42015-11-18 13:06:42 -0800371 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
372 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800373
374 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700375 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800376
Peter Boström2bc68c72015-09-24 16:22:28 +0200377 if (scale_) {
378 if (codecType_ == kVideoCodecVP8) {
379 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
380 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
381 // always = 127. Note that in SW, QP is that of the user-level range [0,
382 // 63].
Alex Glazneva9d08922016-02-19 15:24:06 -0800383 const int kLowQpThreshold = 32;
384 const int kBadQpThreshold = 92;
385 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
386 codec_settings->startBitrate,
387 codec_settings->width, codec_settings->height);
Peter Boström2bc68c72015-09-24 16:22:28 +0200388 } else if (codecType_ == kVideoCodecH264) {
389 // H264 QP is in the range [0, 51].
Alex Glazneva9d08922016-02-19 15:24:06 -0800390 const int kLowQpThreshold = 17;
Peter Boström17417702015-09-25 17:03:26 +0200391 const int kBadQpThreshold = 40;
Alex Glazneva9d08922016-02-19 15:24:06 -0800392 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
393 codec_settings->startBitrate,
394 codec_settings->width, codec_settings->height);
Peter Boström2bc68c72015-09-24 16:22:28 +0200395 } else {
396 // When adding codec support to additional hardware codecs, also configure
397 // their QP thresholds for scaling.
398 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800399 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200400 }
401 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
402 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
Alex Glazneva9d08922016-02-19 15:24:06 -0800403 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
404 init_width = std::max(res.width, kMinWidth);
405 init_height = std::max(res.height, kMinHeight);
406 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700407 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800408
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000409 return codec_thread_->Invoke<int32_t>(
410 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
411 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800412 init_width,
413 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000414 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800415 codec_settings->maxFramerate,
416 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000417}
418
419int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700420 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000421 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700422 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000423 return codec_thread_->Invoke<int32_t>(Bind(
424 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
425}
426
427int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
428 webrtc::EncodedImageCallback* callback) {
429 return codec_thread_->Invoke<int32_t>(
430 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
431 this,
432 callback));
433}
434
435int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700436 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000437 return codec_thread_->Invoke<int32_t>(
438 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
439}
440
441int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
442 int64_t /* rtt */) {
443 return WEBRTC_VIDEO_CODEC_OK;
444}
445
446int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
447 uint32_t frame_rate) {
448 return codec_thread_->Invoke<int32_t>(
449 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
450 this,
451 new_bit_rate,
452 frame_rate));
453}
454
455void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800456 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000457 JNIEnv* jni = AttachCurrentThreadIfNeeded();
458 ScopedLocalRefFrame local_ref_frame(jni);
459
460 // We only ever send one message to |this| directly (not through a Bind()'d
461 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700462 RTC_CHECK(!msg->message_id) << "Unexpected message!";
463 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000464 if (!inited_) {
465 return;
466 }
467
468 // It would be nice to recover from a failure here if one happened, but it's
469 // unclear how to signal such a failure to the app, so instead we stay silent
470 // about it and let the next app-called API method reveal the borkedness.
471 DeliverPendingOutputs(jni);
472 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
473}
474
perkj9576e542015-11-12 06:43:16 -0800475bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
476 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
477 ALOGE << "ResetOnCodecThread";
478 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800479 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
480 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000481 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
482 // degrade to a SW encoder at this point? There isn't one AFAICT :(
483 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800484 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485 }
perkj9576e542015-11-12 06:43:16 -0800486 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000487}
488
489int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800490 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800491 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800492 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000493 JNIEnv* jni = AttachCurrentThreadIfNeeded();
494 ScopedLocalRefFrame local_ref_frame(jni);
495
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700496 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
497 width << " x " << height << ". Bitrate: " << kbps <<
498 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000499 if (kbps == 0) {
500 kbps = last_set_bitrate_kbps_;
501 }
502 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800503 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000504 }
505
506 width_ = width;
507 height_ = height;
508 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800509 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000510 yuv_size_ = width_ * height_ * 3 / 2;
511 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000512 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800513 frames_dropped_media_encoder_ = 0;
514 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 frames_in_queue_ = 0;
516 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800517 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000518 current_frames_ = 0;
519 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800520 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 current_encoding_time_ms_ = 0;
522 last_input_timestamp_ms_ = -1;
523 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000524 output_timestamp_ = 0;
525 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000526 timestamps_.clear();
527 render_times_ms_.clear();
528 frame_rtc_times_ms_.clear();
529 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800530 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000531 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800532 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
533 tl0_pic_idx_ = static_cast<uint8_t>(rand());
534 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800535 last_frame_received_ms_ = -1;
536 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800537
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100539 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000540 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800541 const bool encode_status = jni->CallBooleanMethod(
542 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800543 j_video_codec_enum, width, height, kbps, fps,
544 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800545 if (!encode_status) {
546 ALOGE << "Failed to configure encoder.";
547 return WEBRTC_VIDEO_CODEC_ERROR;
548 }
549 CHECK_EXCEPTION(jni);
550
Per598242a2015-11-26 14:28:55 +0100551 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800552 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
553 jni->CallObjectMethod(*j_media_codec_video_encoder_,
554 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000555 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800556 if (IsNull(jni, input_buffers)) {
557 return WEBRTC_VIDEO_CODEC_ERROR;
558 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000559
perkj30e91822015-11-20 01:31:25 -0800560 switch (GetIntField(jni, *j_media_codec_video_encoder_,
561 j_color_format_field_)) {
562 case COLOR_FormatYUV420Planar:
563 encoder_fourcc_ = libyuv::FOURCC_YU12;
564 break;
565 case COLOR_FormatYUV420SemiPlanar:
566 case COLOR_QCOM_FormatYUV420SemiPlanar:
567 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
568 encoder_fourcc_ = libyuv::FOURCC_NV12;
569 break;
570 default:
571 LOG(LS_ERROR) << "Wrong color format.";
572 return WEBRTC_VIDEO_CODEC_ERROR;
573 }
574 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
575 RTC_CHECK(input_buffers_.empty())
576 << "Unexpected double InitEncode without Release";
577 input_buffers_.resize(num_input_buffers);
578 for (size_t i = 0; i < num_input_buffers; ++i) {
579 input_buffers_[i] =
580 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
581 int64_t yuv_buffer_capacity =
582 jni->GetDirectBufferCapacity(input_buffers_[i]);
583 CHECK_EXCEPTION(jni);
584 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
585 }
586 }
perkj9576e542015-11-12 06:43:16 -0800587
588 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000589 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
590 return WEBRTC_VIDEO_CODEC_OK;
591}
592
593int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700594 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700595 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800596 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000597 JNIEnv* jni = AttachCurrentThreadIfNeeded();
598 ScopedLocalRefFrame local_ref_frame(jni);
599
600 if (!inited_) {
601 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
602 }
perkj9576e542015-11-12 06:43:16 -0800603
asapersson1d61a512016-01-20 01:13:46 -0800604 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800605 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800606 ++frames_received_since_last_key_;
607 int64_t now_ms = GetCurrentTimeMs();
608 if (last_frame_received_ms_ != -1 &&
609 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
610 // Add limit to prevent triggering a key for every frame for very low
611 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
612 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
613 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
614 send_key_frame = true;
615 }
616 frames_received_since_last_key_ = 0;
617 }
618 last_frame_received_ms_ = now_ms;
619 }
620
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000621 frames_received_++;
622 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800623 if (!ResetCodecOnCodecThread())
624 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000625 }
glaznevf4decb52016-01-15 13:49:22 -0800626 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800627 ALOGD << "Encoder frame in # " << (frames_received_ - 1) <<
628 ". TS: " << (int)(current_timestamp_us_ / 1000) <<
629 ". Q: " << frames_in_queue_ <<
630 ". 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_++;
glaznevf4decb52016-01-15 13:49:22 -0800639 OnDroppedFrame();
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
glaznevf4decb52016-01-15 13:49:22 -0800645 // Check if we accumulated too many frames in encoder input buffers
646 // or the encoder latency exceeds 70 ms and drop frame if so.
647 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
648 int encoder_latency_ms = last_input_timestamp_ms_ -
649 last_output_timestamp_ms_;
650 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE ||
651 encoder_latency_ms > MAX_ENCODER_LATENCY_MS) {
652 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
glaznev94291482016-02-01 13:17:18 -0800653 " ms. Q size: " << frames_in_queue_ << ". TS: " <<
654 (int)(current_timestamp_us_ / 1000) << ". Fps: " << last_set_fps_ <<
655 ". Consecutive drops: " << consecutive_full_queue_frame_drops_ ;
glaznevf4decb52016-01-15 13:49:22 -0800656 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800657 consecutive_full_queue_frame_drops_++;
658 if (consecutive_full_queue_frame_drops_ >=
659 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
660 ALOGE << "Encoder got stuck. Reset.";
661 ResetCodecOnCodecThread();
662 return WEBRTC_VIDEO_CODEC_ERROR;
663 }
664 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800665 OnDroppedFrame();
666 return WEBRTC_VIDEO_CODEC_OK;
667 }
668 }
glaznev919ff752016-01-27 15:01:03 -0800669 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800670
Per598242a2015-11-26 14:28:55 +0100671 VideoFrame input_frame = frame;
672 if (scale_) {
673 // Check framerate before spatial resolution change.
674 quality_scaler_.OnEncodeFrame(frame);
675 const webrtc::QualityScaler::Resolution scaled_resolution =
676 quality_scaler_.GetScaledResolution();
677 if (scaled_resolution.width != frame.width() ||
678 scaled_resolution.height != frame.height()) {
679 if (frame.native_handle() != nullptr) {
680 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
681 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100682 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100683 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100684 scaled_resolution.height,
685 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100686 input_frame.set_video_frame_buffer(scaled_buffer);
687 } else {
688 input_frame = quality_scaler_.GetScaledFrame(frame);
689 }
690 }
691 }
jackychen61b4d512015-04-21 15:30:11 -0700692
perkj9576e542015-11-12 06:43:16 -0800693 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
694 ALOGE << "Failed to reconfigure encoder.";
695 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000696 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000697
glaznevf4decb52016-01-15 13:49:22 -0800698 // Save time when input frame is sent to the encoder input.
699 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000700
asapersson1d61a512016-01-20 01:13:46 -0800701 const bool key_frame =
702 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800703 bool encode_status = true;
704 if (!input_frame.native_handle()) {
705 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
706 j_dequeue_input_buffer_method_);
707 CHECK_EXCEPTION(jni);
708 if (j_input_buffer_index == -1) {
709 // Video codec falls behind - no input buffer available.
710 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800711 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800712 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
713 frames_dropped_media_encoder_++;
714 OnDroppedFrame();
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
perkj9576e542015-11-12 06:43:16 -0800733 last_input_timestamp_ms_ =
734 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200735 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000736
perkj12f68022015-10-16 13:31:45 +0200737 // Save input image timestamps for later output
738 timestamps_.push_back(input_frame.timestamp());
739 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800740 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
741
perkj30e91822015-11-20 01:31:25 -0800742 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800743 ALOGE << "Failed deliver pending outputs.";
744 ResetCodecOnCodecThread();
745 return WEBRTC_VIDEO_CODEC_ERROR;
746 }
747 return WEBRTC_VIDEO_CODEC_OK;
748}
749
750bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
751 const webrtc::VideoFrame& frame) {
752 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
753
perkj30e91822015-11-20 01:31:25 -0800754 const bool is_texture_frame = frame.native_handle() != nullptr;
755 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800756 const bool reconfigure_due_to_size =
757 frame.width() != width_ || frame.height() != height_;
758
perkj30e91822015-11-20 01:31:25 -0800759 if (reconfigure_due_to_format) {
760 ALOGD << "Reconfigure encoder due to format change. "
761 << (use_surface_ ?
762 "Reconfiguring to encode from byte buffer." :
763 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800764 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800765 }
perkj9576e542015-11-12 06:43:16 -0800766 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800767 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800768 << width_ << " x " << height_ << " to " << frame.width() << " x "
769 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800770 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800771 width_ = frame.width();
772 height_ = frame.height();
773 }
774
perkj30e91822015-11-20 01:31:25 -0800775 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800776 return true;
777
778 ReleaseOnCodecThread();
779
perkj30e91822015-11-20 01:31:25 -0800780 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800781 WEBRTC_VIDEO_CODEC_OK;
782}
783
784bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
785 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
786 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800787 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800788
perkj9576e542015-11-12 06:43:16 -0800789 jobject j_input_buffer = input_buffers_[input_buffer_index];
790 uint8_t* yuv_buffer =
791 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
792 CHECK_EXCEPTION(jni);
793 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
794 RTC_CHECK(!libyuv::ConvertFromI420(
795 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
796 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
797 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
798 yuv_buffer, width_, width_, height_, encoder_fourcc_))
799 << "ConvertFromI420 failed";
800
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000801 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800802 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000803 key_frame,
perkj9576e542015-11-12 06:43:16 -0800804 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000805 yuv_size_,
806 current_timestamp_us_);
807 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800808 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000809}
810
perkj30e91822015-11-20 01:31:25 -0800811bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
812 bool key_frame, const webrtc::VideoFrame& frame) {
813 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
814 RTC_CHECK(use_surface_);
815 NativeHandleImpl* handle =
816 static_cast<NativeHandleImpl*>(frame.native_handle());
817 jfloatArray sampling_matrix = jni->NewFloatArray(16);
818 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
819
820 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
821 j_encode_texture_method_,
822 key_frame,
823 handle->oes_texture_id,
824 sampling_matrix,
825 current_timestamp_us_);
826 CHECK_EXCEPTION(jni);
827 return encode_status;
828}
829
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000830int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
831 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800832 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000833 JNIEnv* jni = AttachCurrentThreadIfNeeded();
834 ScopedLocalRefFrame local_ref_frame(jni);
835 callback_ = callback;
836 return WEBRTC_VIDEO_CODEC_OK;
837}
838
839int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800840 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000841 if (!inited_) {
842 return WEBRTC_VIDEO_CODEC_OK;
843 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000844 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700845 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
846 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800847 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000848 ScopedLocalRefFrame local_ref_frame(jni);
849 for (size_t i = 0; i < input_buffers_.size(); ++i)
850 jni->DeleteGlobalRef(input_buffers_[i]);
851 input_buffers_.clear();
852 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
853 CHECK_EXCEPTION(jni);
854 rtc::MessageQueueManager::Clear(this);
855 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800856 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700857 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000858 return WEBRTC_VIDEO_CODEC_OK;
859}
860
861int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
862 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800863 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800864 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
865 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000866 if (last_set_bitrate_kbps_ == new_bit_rate &&
867 last_set_fps_ == frame_rate) {
868 return WEBRTC_VIDEO_CODEC_OK;
869 }
glaznev919ff752016-01-27 15:01:03 -0800870 if (scale_) {
871 quality_scaler_.ReportFramerate(frame_rate);
872 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000873 JNIEnv* jni = AttachCurrentThreadIfNeeded();
874 ScopedLocalRefFrame local_ref_frame(jni);
875 if (new_bit_rate > 0) {
876 last_set_bitrate_kbps_ = new_bit_rate;
877 }
878 if (frame_rate > 0) {
879 last_set_fps_ = frame_rate;
880 }
881 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
882 j_set_rates_method_,
883 last_set_bitrate_kbps_,
884 last_set_fps_);
885 CHECK_EXCEPTION(jni);
886 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800887 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000888 return WEBRTC_VIDEO_CODEC_ERROR;
889 }
890 return WEBRTC_VIDEO_CODEC_OK;
891}
892
893int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
894 JNIEnv* jni,
895 jobject j_output_buffer_info) {
896 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
897}
898
899jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
900 JNIEnv* jni,
901 jobject j_output_buffer_info) {
902 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
903}
904
905bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
906 JNIEnv* jni,
907 jobject j_output_buffer_info) {
908 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
909}
910
911jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
912 JNIEnv* jni,
913 jobject j_output_buffer_info) {
914 return GetLongField(
915 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
916}
917
918bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800919 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000920 while (true) {
921 jobject j_output_buffer_info = jni->CallObjectMethod(
922 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
923 CHECK_EXCEPTION(jni);
924 if (IsNull(jni, j_output_buffer_info)) {
925 break;
926 }
927
928 int output_buffer_index =
929 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
930 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800931 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000932 return false;
933 }
934
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000935 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000936 jobject j_output_buffer =
937 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
938 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000939
940 // Get frame timestamps from a queue - for non config frames only.
941 int64_t frame_encoding_time_ms = 0;
942 last_output_timestamp_ms_ =
943 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
944 1000;
945 if (frames_in_queue_ > 0) {
946 output_timestamp_ = timestamps_.front();
947 timestamps_.erase(timestamps_.begin());
948 output_render_time_ms_ = render_times_ms_.front();
949 render_times_ms_.erase(render_times_ms_.begin());
950 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
951 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
952 frames_in_queue_--;
953 }
954
955 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000956 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200957 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000958 jni->GetDirectBufferAddress(j_output_buffer));
959 CHECK_EXCEPTION(jni);
960
glaznevf4decb52016-01-15 13:49:22 -0800961 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800962 int current_latency =
963 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
964 ALOGD << "Encoder frame out # " << frames_encoded_ <<
965 ". Key: " << key_frame <<
966 ". Size: " << payload_size <<
967 ". TS: " << (int)last_output_timestamp_ms_ <<
968 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800969 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000970 }
971
972 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000973 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000974 if (callback_) {
975 scoped_ptr<webrtc::EncodedImage> image(
976 new webrtc::EncodedImage(payload, payload_size, payload_size));
977 image->_encodedWidth = width_;
978 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000979 image->_timeStamp = output_timestamp_;
980 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200981 image->_frameType =
982 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000983 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700984 image->adapt_reason_.quality_resolution_downscales =
985 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000986
987 webrtc::CodecSpecificInfo info;
988 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000989 info.codecType = codecType_;
990 if (codecType_ == kVideoCodecVP8) {
991 info.codecSpecific.VP8.pictureId = picture_id_;
992 info.codecSpecific.VP8.nonReference = false;
993 info.codecSpecific.VP8.simulcastIdx = 0;
994 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
995 info.codecSpecific.VP8.layerSync = false;
996 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
997 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800998 } else if (codecType_ == kVideoCodecVP9) {
999 if (key_frame) {
1000 gof_idx_ = 0;
1001 }
1002 info.codecSpecific.VP9.picture_id = picture_id_;
1003 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
1004 info.codecSpecific.VP9.flexible_mode = false;
1005 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
1006 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1007 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1008 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1009 info.codecSpecific.VP9.temporal_up_switch = true;
1010 info.codecSpecific.VP9.inter_layer_predicted = false;
1011 info.codecSpecific.VP9.gof_idx =
1012 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1013 info.codecSpecific.VP9.num_spatial_layers = 1;
1014 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1015 if (info.codecSpecific.VP9.ss_data_available) {
1016 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1017 info.codecSpecific.VP9.width[0] = width_;
1018 info.codecSpecific.VP9.height[0] = height_;
1019 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1020 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001021 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001022 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001023
1024 // Generate a header describing a single fragment.
1025 webrtc::RTPFragmentationHeader header;
1026 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001027 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001028 header.VerifyAndAllocateFragmentationHeader(1);
1029 header.fragmentationOffset[0] = 0;
1030 header.fragmentationLength[0] = image->_length;
1031 header.fragmentationPlType[0] = 0;
1032 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001033 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001034 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001035 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1036 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001037 quality_scaler_.ReportQP(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) {
1112 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1113 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.";
1125 stat_start_time_ms_ = GetCurrentTimeMs();
1126 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() {
glaznevf4decb52016-01-15 13:49:22 -08001166 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001167 if (scale_)
1168 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001169}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001170
jackychen6e2ce6e2015-07-13 16:26:33 -07001171int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001172 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001173}
1174
Peter Boströmb7d9a972015-12-18 16:01:11 +01001175const char* MediaCodecVideoEncoder::ImplementationName() const {
1176 return "MediaCodec";
1177}
1178
perkj461121c2016-02-15 06:28:36 -08001179MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1180 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001181 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1182 ScopedLocalRefFrame local_ref_frame(jni);
1183 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001184 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001185
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001186 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1187 j_encoder_class,
1188 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1189 CHECK_EXCEPTION(jni);
1190 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001191 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001192 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1193 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1194 }
1195
Alex Glaznevad948c42015-11-18 13:06:42 -08001196 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1197 j_encoder_class,
1198 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1199 CHECK_EXCEPTION(jni);
1200 if (is_vp9_hw_supported) {
1201 ALOGD << "VP9 HW Encoder supported.";
1202 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1203 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1204 }
1205
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001206 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1207 j_encoder_class,
1208 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1209 CHECK_EXCEPTION(jni);
1210 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001211 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001212 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1213 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1214 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001215}
1216
Perec2922f2016-01-27 15:25:46 +01001217MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1218 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001219 if (egl_context_) {
1220 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1221 jni->DeleteGlobalRef(egl_context_);
1222 }
Perec2922f2016-01-27 15:25:46 +01001223}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001224
perkj30e91822015-11-20 01:31:25 -08001225void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001226 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001227 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001228 if (egl_context_) {
1229 jni->DeleteGlobalRef(egl_context_);
1230 egl_context_ = nullptr;
1231 }
perkj461121c2016-02-15 06:28:36 -08001232 egl_context_ = jni->NewGlobalRef(egl_context);
1233 if (CheckException(jni)) {
1234 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001235 }
1236}
1237
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001238webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001239 VideoCodecType type) {
1240 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001241 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001242 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001243 }
1244 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1245 it != supported_codecs_.end(); ++it) {
1246 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001247 ALOGD << "Create HW video encoder for type " << (int)type <<
1248 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001249 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001250 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001251 }
1252 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001253 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001254 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001255}
1256
1257const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1258MediaCodecVideoEncoderFactory::codecs() const {
1259 return supported_codecs_;
1260}
1261
1262void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1263 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001264 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001265 delete encoder;
1266}
1267
1268} // namespace webrtc_jni
1269