blob: 8fcc20b6f1f0426c7b7a4755a3ea99a8f32d774d [file] [log] [blame]
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001/*
2 * libjingle
3 * Copyright 2015 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 *
27 */
28
29#include "talk/app/webrtc/java/jni/androidmediaencoder_jni.h"
30#include "talk/app/webrtc/java/jni/classreferenceholder.h"
31#include "talk/app/webrtc/java/jni/androidmediacodeccommon.h"
32#include "webrtc/base/bind.h"
33#include "webrtc/base/checks.h"
34#include "webrtc/base/logging.h"
35#include "webrtc/base/thread.h"
perkj90754172015-10-12 03:04:15 -070036#include "webrtc/base/thread_checker.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020037#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000038#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
jackychen61b4d512015-04-21 15:30:11 -070039#include "webrtc/modules/video_coding/utility/include/quality_scaler.h"
jackychen98d8cf52015-05-21 11:12:02 -070040#include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h"
asaperssonef5d5e42015-09-22 01:40:42 -070041#include "webrtc/system_wrappers/interface/field_trial.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000042#include "webrtc/system_wrappers/interface/logcat_trace_context.h"
43#include "third_party/libyuv/include/libyuv/convert.h"
44#include "third_party/libyuv/include/libyuv/convert_from.h"
45#include "third_party/libyuv/include/libyuv/video_common.h"
46
47using rtc::Bind;
48using rtc::Thread;
49using rtc::ThreadManager;
50using rtc::scoped_ptr;
51
52using webrtc::CodecSpecificInfo;
53using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070054using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000055using webrtc::RTPFragmentationHeader;
56using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000057using webrtc::VideoCodecType;
58using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000059using webrtc::kVideoCodecVP8;
60
61namespace webrtc_jni {
62
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000063// H.264 start code length.
64#define H264_SC_LENGTH 4
65// Maximum allowed NALUs in one output frame.
66#define MAX_NALUS_PERFRAME 32
67// Maximum supported HW video encoder resolution.
68#define MAX_VIDEO_WIDTH 1280
69#define MAX_VIDEO_HEIGHT 1280
70// Maximum supported HW video encoder fps.
71#define MAX_VIDEO_FPS 30
72
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000073// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
74// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
75// HW-backed video encode. This C++ class is implemented as a very thin shim,
76// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
77// MediaCodecVideoEncoder is created, operated, and destroyed on a single
78// thread, currently the libjingle Worker thread.
79class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
80 public rtc::MessageHandler {
81 public:
82 virtual ~MediaCodecVideoEncoder();
perkj90754172015-10-12 03:04:15 -070083 MediaCodecVideoEncoder(JNIEnv* jni,
84 VideoCodecType codecType);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000085
86 // webrtc::VideoEncoder implementation. Everything trampolines to
87 // |codec_thread_| for execution.
88 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
89 int32_t /* number_of_cores */,
90 size_t /* max_payload_size */) override;
91 int32_t Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070092 const webrtc::VideoFrame& input_image,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000093 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
94 const std::vector<webrtc::VideoFrameType>* frame_types) override;
95 int32_t RegisterEncodeCompleteCallback(
96 webrtc::EncodedImageCallback* callback) override;
97 int32_t Release() override;
98 int32_t SetChannelParameters(uint32_t /* packet_loss */,
99 int64_t /* rtt */) override;
100 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
101
102 // rtc::MessageHandler implementation.
103 void OnMessage(rtc::Message* msg) override;
104
jackychen61b4d512015-04-21 15:30:11 -0700105 void OnDroppedFrame() override;
106
jackychen6e2ce6e2015-07-13 16:26:33 -0700107 int GetTargetFramerate() override;
108
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000109 private:
perkj90754172015-10-12 03:04:15 -0700110 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
111 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000112 // operable state. Necessary after all manner of OMX-layer errors.
perkj90754172015-10-12 03:04:15 -0700113 void ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000114
115 // Implementation of webrtc::VideoEncoder methods above, all running on the
116 // codec thread exclusively.
117 //
118 // If width==0 then this is assumed to be a re-initialization and the
119 // previously-current values are reused instead of the passed parameters
120 // (makes it easier to reason about thread-safety).
121 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps);
perkj90754172015-10-12 03:04:15 -0700122 // Reconfigure to match |frame| in width, height. Returns false if
123 // reconfiguring fails.
124 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000125 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700126 const webrtc::VideoFrame& input_image,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000127 const std::vector<webrtc::VideoFrameType>* frame_types);
perkj90754172015-10-12 03:04:15 -0700128 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
129 bool key_frame, const webrtc::VideoFrame& frame);
130
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000131 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
132 webrtc::EncodedImageCallback* callback);
133 int32_t ReleaseOnCodecThread();
134 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
135
136 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
137 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
138 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
139 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
140 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000141 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000142
143 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
144 // true on success.
145 bool DeliverPendingOutputs(JNIEnv* jni);
146
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000147 // Search for H.264 start codes.
148 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
149
150 // Type of video codec.
151 VideoCodecType codecType_;
152
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000153 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
154 // |codec_thread_| synchronously.
155 webrtc::EncodedImageCallback* callback_;
156
157 // State that is constant for the lifetime of this object once the ctor
158 // returns.
159 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj90754172015-10-12 03:04:15 -0700160 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000161 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
162 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
163 jmethodID j_init_encode_method_;
perkj90754172015-10-12 03:04:15 -0700164 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000165 jmethodID j_dequeue_input_buffer_method_;
perkj90754172015-10-12 03:04:15 -0700166 jmethodID j_encode_buffer_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000167 jmethodID j_release_method_;
168 jmethodID j_set_rates_method_;
169 jmethodID j_dequeue_output_buffer_method_;
170 jmethodID j_release_output_buffer_method_;
171 jfieldID j_color_format_field_;
172 jfieldID j_info_index_field_;
173 jfieldID j_info_buffer_field_;
174 jfieldID j_info_is_key_frame_field_;
175 jfieldID j_info_presentation_timestamp_us_field_;
176
177 // State that is valid only between InitEncode() and the next Release().
178 // Touched only on codec_thread_ so no explicit synchronization necessary.
179 int width_; // Frame width in pixels.
180 int height_; // Frame height in pixels.
181 bool inited_;
182 uint16_t picture_id_;
183 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
184 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
185 int last_set_fps_; // Last-requested frame rate.
186 int64_t current_timestamp_us_; // Current frame timestamps in us.
187 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000188 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000189 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000190 int frames_in_queue_; // Number of frames in encoder queue.
191 int64_t start_time_ms_; // Start time for statistics.
192 int current_frames_; // Number of frames in the current statistics interval.
193 int current_bytes_; // Encoded bytes in the current statistics interval.
194 int current_encoding_time_ms_; // Overall encoding time in the current second
195 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
196 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
197 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
198 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
199 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
200 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000201 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
202 int64_t output_render_time_ms_; // Last output frame render time from
203 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000204 // Frame size in bytes fed to MediaCodec.
205 int yuv_size_;
206 // True only when between a callback_->Encoded() call return a positive value
207 // and the next Encode() call being ignored.
208 bool drop_next_input_frame_;
209 // Global references; must be deleted in Release().
210 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200211 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700212 // Dynamic resolution change, off by default.
213 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200214
215 // H264 bitstream parser, used to extract QP from encoded bitstreams.
216 webrtc::H264BitstreamParser h264_bitstream_parser_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000217};
218
219MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
220 // Call Release() to ensure no more callbacks to us after we are deleted.
221 Release();
222}
223
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000224MediaCodecVideoEncoder::MediaCodecVideoEncoder(
225 JNIEnv* jni, VideoCodecType codecType) :
226 codecType_(codecType),
227 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000228 inited_(false),
229 picture_id_(0),
230 codec_thread_(new Thread()),
231 j_media_codec_video_encoder_class_(
232 jni,
233 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
234 j_media_codec_video_encoder_(
235 jni,
236 jni->NewObject(*j_media_codec_video_encoder_class_,
237 GetMethodID(jni,
238 *j_media_codec_video_encoder_class_,
239 "<init>",
240 "()V"))) {
241 ScopedLocalRefFrame local_ref_frame(jni);
242 // It would be nice to avoid spinning up a new thread per MediaCodec, and
243 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
244 // 2732 means that deadlocks abound. This class synchronously trampolines
245 // to |codec_thread_|, so if anything else can be coming to _us_ from
246 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
247 // in the bug, we have a problem. For now work around that with a dedicated
248 // thread.
249 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700250 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj90754172015-10-12 03:04:15 -0700251 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000252 jclass j_output_buffer_info_class =
253 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000254 j_init_encode_method_ = GetMethodID(
255 jni,
256 *j_media_codec_video_encoder_class_,
257 "initEncode",
perkj90754172015-10-12 03:04:15 -0700258 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)Z");
259 j_get_input_buffers_method_ = GetMethodID(
260 jni,
261 *j_media_codec_video_encoder_class_,
262 "getInputBuffers",
263 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000264 j_dequeue_input_buffer_method_ = GetMethodID(
265 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj90754172015-10-12 03:04:15 -0700266 j_encode_buffer_method_ = GetMethodID(
267 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000268 j_release_method_ =
269 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
270 j_set_rates_method_ = GetMethodID(
271 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000272 j_dequeue_output_buffer_method_ = GetMethodID(
273 jni,
274 *j_media_codec_video_encoder_class_,
275 "dequeueOutputBuffer",
276 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000277 j_release_output_buffer_method_ = GetMethodID(
278 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
279
280 j_color_format_field_ =
281 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
282 j_info_index_field_ =
283 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
284 j_info_buffer_field_ = GetFieldID(
285 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
286 j_info_is_key_frame_field_ =
287 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
288 j_info_presentation_timestamp_us_field_ = GetFieldID(
289 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
290 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
291 AllowBlockingCalls();
292}
293
294int32_t MediaCodecVideoEncoder::InitEncode(
295 const webrtc::VideoCodec* codec_settings,
296 int32_t /* number_of_cores */,
297 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700298 const int kMinWidth = 320;
299 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700300 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000301 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700302 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000303 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
304 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000305 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700306 RTC_CHECK(codec_settings->codecType == codecType_)
307 << "Unsupported codec " << codec_settings->codecType << " for "
308 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000309
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700310 ALOGD << "InitEncode request";
asaperssonef5d5e42015-09-22 01:40:42 -0700311 scale_ = webrtc::field_trial::FindFullName(
312 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled";
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700313 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200314 if (scale_) {
315 if (codecType_ == kVideoCodecVP8) {
316 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
317 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
318 // always = 127. Note that in SW, QP is that of the user-level range [0,
319 // 63].
320 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200321 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
322 // This effectively disables high QP as VP8 QP can't go above this
323 // threshold.
324 const int kDisabledBadQpThreshold = kMaxQp + 1;
325 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
326 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200327 } else if (codecType_ == kVideoCodecH264) {
328 // H264 QP is in the range [0, 51].
329 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200330 const int kBadQpThreshold = 40;
331 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
332 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200333 } else {
334 // When adding codec support to additional hardware codecs, also configure
335 // their QP thresholds for scaling.
336 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
337 }
338 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
339 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700340 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000341 return codec_thread_->Invoke<int32_t>(
342 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
343 this,
344 codec_settings->width,
345 codec_settings->height,
346 codec_settings->startBitrate,
347 codec_settings->maxFramerate));
348}
349
350int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700351 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000352 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
353 const std::vector<webrtc::VideoFrameType>* frame_types) {
354 return codec_thread_->Invoke<int32_t>(Bind(
355 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
356}
357
358int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
359 webrtc::EncodedImageCallback* callback) {
360 return codec_thread_->Invoke<int32_t>(
361 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
362 this,
363 callback));
364}
365
366int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700367 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000368 return codec_thread_->Invoke<int32_t>(
369 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
370}
371
372int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
373 int64_t /* rtt */) {
374 return WEBRTC_VIDEO_CODEC_OK;
375}
376
377int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
378 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200379 if (scale_)
380 quality_scaler_.ReportFramerate(frame_rate);
381
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000382 return codec_thread_->Invoke<int32_t>(
383 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
384 this,
385 new_bit_rate,
386 frame_rate));
387}
388
389void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj90754172015-10-12 03:04:15 -0700390 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000391 JNIEnv* jni = AttachCurrentThreadIfNeeded();
392 ScopedLocalRefFrame local_ref_frame(jni);
393
394 // We only ever send one message to |this| directly (not through a Bind()'d
395 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700396 RTC_CHECK(!msg->message_id) << "Unexpected message!";
397 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000398 if (!inited_) {
399 return;
400 }
401
402 // It would be nice to recover from a failure here if one happened, but it's
403 // unclear how to signal such a failure to the app, so instead we stay silent
404 // about it and let the next app-called API method reveal the borkedness.
405 DeliverPendingOutputs(jni);
406 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
407}
408
perkj90754172015-10-12 03:04:15 -0700409void MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
410 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
411 ALOGE << "ResetOnCodecThread";
412 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
413 InitEncodeOnCodecThread(width_, height_, 0, 0)
414 != WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000415 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
416 // degrade to a SW encoder at this point? There isn't one AFAICT :(
417 // https://code.google.com/p/webrtc/issues/detail?id=2920
418 }
419}
420
421int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
422 int width, int height, int kbps, int fps) {
perkj90754172015-10-12 03:04:15 -0700423 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000424 JNIEnv* jni = AttachCurrentThreadIfNeeded();
425 ScopedLocalRefFrame local_ref_frame(jni);
426
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700427 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
428 width << " x " << height << ". Bitrate: " << kbps <<
429 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000430 if (kbps == 0) {
431 kbps = last_set_bitrate_kbps_;
432 }
433 if (fps == 0) {
434 fps = last_set_fps_;
435 }
436
437 width_ = width;
438 height_ = height;
439 last_set_bitrate_kbps_ = kbps;
440 last_set_fps_ = fps;
441 yuv_size_ = width_ * height_ * 3 / 2;
442 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000443 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000444 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000445 frames_in_queue_ = 0;
446 current_timestamp_us_ = 0;
447 start_time_ms_ = GetCurrentTimeMs();
448 current_frames_ = 0;
449 current_bytes_ = 0;
450 current_encoding_time_ms_ = 0;
451 last_input_timestamp_ms_ = -1;
452 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000453 output_timestamp_ = 0;
454 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000455 timestamps_.clear();
456 render_times_ms_.clear();
457 frame_rtc_times_ms_.clear();
458 drop_next_input_frame_ = false;
459 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
perkj90754172015-10-12 03:04:15 -0700460
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000461 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000462 jobject j_video_codec_enum = JavaEnumFromIndex(
463 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj90754172015-10-12 03:04:15 -0700464 const bool encode_status = jni->CallBooleanMethod(
465 *j_media_codec_video_encoder_, j_init_encode_method_,
466 j_video_codec_enum, width, height, kbps, fps);
467 if (!encode_status) {
468 ALOGE << "Failed to configure encoder.";
469 return WEBRTC_VIDEO_CODEC_ERROR;
470 }
471 CHECK_EXCEPTION(jni);
472
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000473 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
474 jni->CallObjectMethod(*j_media_codec_video_encoder_,
perkj90754172015-10-12 03:04:15 -0700475 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000476 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000477 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000478 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000479 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000480
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000481 switch (GetIntField(jni, *j_media_codec_video_encoder_,
482 j_color_format_field_)) {
483 case COLOR_FormatYUV420Planar:
484 encoder_fourcc_ = libyuv::FOURCC_YU12;
485 break;
486 case COLOR_FormatYUV420SemiPlanar:
487 case COLOR_QCOM_FormatYUV420SemiPlanar:
488 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
489 encoder_fourcc_ = libyuv::FOURCC_NV12;
490 break;
491 default:
492 LOG(LS_ERROR) << "Wrong color format.";
493 return WEBRTC_VIDEO_CODEC_ERROR;
494 }
495 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
henrikg91d6ede2015-09-17 00:24:34 -0700496 RTC_CHECK(input_buffers_.empty())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000497 << "Unexpected double InitEncode without Release";
498 input_buffers_.resize(num_input_buffers);
499 for (size_t i = 0; i < num_input_buffers; ++i) {
500 input_buffers_[i] =
501 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
Peter Boström0c4e06b2015-10-07 12:23:21 +0200502 int64_t yuv_buffer_capacity =
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000503 jni->GetDirectBufferCapacity(input_buffers_[i]);
504 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700505 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000506 }
507 CHECK_EXCEPTION(jni);
508
perkj90754172015-10-12 03:04:15 -0700509
510 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000511 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
512 return WEBRTC_VIDEO_CODEC_OK;
513}
514
515int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700516 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000517 const std::vector<webrtc::VideoFrameType>* frame_types) {
perkj90754172015-10-12 03:04:15 -0700518 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000519 JNIEnv* jni = AttachCurrentThreadIfNeeded();
520 ScopedLocalRefFrame local_ref_frame(jni);
521
522 if (!inited_) {
523 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
524 }
perkj90754172015-10-12 03:04:15 -0700525
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000526 frames_received_++;
527 if (!DeliverPendingOutputs(jni)) {
perkj90754172015-10-12 03:04:15 -0700528 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000529 // Continue as if everything's fine.
530 }
531
532 if (drop_next_input_frame_) {
perkj90754172015-10-12 03:04:15 -0700533 ALOGD << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000534 drop_next_input_frame_ = false;
535 return WEBRTC_VIDEO_CODEC_OK;
536 }
537
henrikg91d6ede2015-09-17 00:24:34 -0700538 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen6e2ce6e2015-07-13 16:26:33 -0700539 // Check framerate before spatial resolution change.
Peter Boström2bc68c72015-09-24 16:22:28 +0200540 if (scale_)
541 quality_scaler_.OnEncodeFrame(frame);
542
543 const VideoFrame& input_frame =
544 scale_ ? quality_scaler_.GetScaledFrame(frame) : frame;
jackychen61b4d512015-04-21 15:30:11 -0700545
perkj90754172015-10-12 03:04:15 -0700546 if (!MaybeReconfigureEncoderOnCodecThread(frame)) {
547 ALOGE << "Failed to reconfigure encoder.";
548 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000549 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000550
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000551 // Check if we accumulated too many frames in encoder input buffers
552 // or the encoder latency exceeds 70 ms and drop frame if so.
553 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
554 int encoder_latency_ms = last_input_timestamp_ms_ -
555 last_output_timestamp_ms_;
556 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700557 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
558 " ms. Q size: " << frames_in_queue_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000559 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700560 // Report dropped frame to quality_scaler_.
561 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000562 return WEBRTC_VIDEO_CODEC_OK;
563 }
564 }
565
perkj90754172015-10-12 03:04:15 -0700566 last_input_timestamp_ms_ =
567 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
568 frames_in_queue_++;
569
570 // Save input image timestamps for later output
571 timestamps_.push_back(input_frame.timestamp());
572 render_times_ms_.push_back(input_frame.render_time_ms());
573 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
574
575 const bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
576 const bool encode_status =
577 EncodeByteBufferOnCodecThread(jni, key_frame, input_frame);
578
579 current_timestamp_us_ += 1000000 / last_set_fps_;
580
581 if (!encode_status || !DeliverPendingOutputs(jni)) {
582 ALOGE << "Failed deliver pending outputs.";
583 ResetCodecOnCodecThread();
584 return WEBRTC_VIDEO_CODEC_ERROR;
585 }
586 return WEBRTC_VIDEO_CODEC_OK;
587}
588
589bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
590 const webrtc::VideoFrame& frame) {
591 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
592
593 const bool reconfigure_due_to_size =
594 frame.width() != width_ || frame.height() != height_;
595
596 if (reconfigure_due_to_size) {
597 ALOGD << "Reconfigure encoder due to frame resolution change from "
598 << width_ << " x " << height_ << " to " << frame.width() << " x "
599 << frame.height();
600 width_ = frame.width();
601 height_ = frame.height();
602 }
603
604 if (!reconfigure_due_to_size)
605 return true;
606
607 ReleaseOnCodecThread();
608
609 return InitEncodeOnCodecThread(width_, height_, 0, 0) ==
610 WEBRTC_VIDEO_CODEC_OK;
611}
612
613bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
614 bool key_frame, const webrtc::VideoFrame& frame) {
615 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000616 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
617 j_dequeue_input_buffer_method_);
618 CHECK_EXCEPTION(jni);
619 if (j_input_buffer_index == -1) {
620 // Video codec falls behind - no input buffer available.
perkj90754172015-10-12 03:04:15 -0700621 ALOGD <<"Encoder drop frame - no input buffers available";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000622 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700623 // Report dropped frame to quality_scaler_.
624 OnDroppedFrame();
perkj90754172015-10-12 03:04:15 -0700625 return true; // TODO(fischman): see webrtc bug 2887.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000626 }
627 if (j_input_buffer_index == -2) {
perkj90754172015-10-12 03:04:15 -0700628 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000629 }
630
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000631 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
632 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000633
634 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200635 uint8_t* yuv_buffer =
636 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000637 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700638 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
639 RTC_CHECK(!libyuv::ConvertFromI420(
perkj90754172015-10-12 03:04:15 -0700640 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
641 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
642 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
henrikg91d6ede2015-09-17 00:24:34 -0700643 yuv_buffer, width_, width_, height_, encoder_fourcc_))
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000644 << "ConvertFromI420 failed";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000645
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000646
647 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj90754172015-10-12 03:04:15 -0700648 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000649 key_frame,
650 j_input_buffer_index,
651 yuv_size_,
652 current_timestamp_us_);
653 CHECK_EXCEPTION(jni);
perkj90754172015-10-12 03:04:15 -0700654 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000655}
656
657int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
658 webrtc::EncodedImageCallback* callback) {
perkj90754172015-10-12 03:04:15 -0700659 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000660 JNIEnv* jni = AttachCurrentThreadIfNeeded();
661 ScopedLocalRefFrame local_ref_frame(jni);
662 callback_ = callback;
663 return WEBRTC_VIDEO_CODEC_OK;
664}
665
666int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj90754172015-10-12 03:04:15 -0700667 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000668 if (!inited_) {
669 return WEBRTC_VIDEO_CODEC_OK;
670 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000671 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700672 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
673 frames_received_ << ". Encoded: " << frames_encoded_ <<
674 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000675 ScopedLocalRefFrame local_ref_frame(jni);
676 for (size_t i = 0; i < input_buffers_.size(); ++i)
677 jni->DeleteGlobalRef(input_buffers_[i]);
678 input_buffers_.clear();
679 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
680 CHECK_EXCEPTION(jni);
681 rtc::MessageQueueManager::Clear(this);
682 inited_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700683 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000684 return WEBRTC_VIDEO_CODEC_OK;
685}
686
687int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
688 uint32_t frame_rate) {
perkj90754172015-10-12 03:04:15 -0700689 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000690 if (last_set_bitrate_kbps_ == new_bit_rate &&
691 last_set_fps_ == frame_rate) {
692 return WEBRTC_VIDEO_CODEC_OK;
693 }
694 JNIEnv* jni = AttachCurrentThreadIfNeeded();
695 ScopedLocalRefFrame local_ref_frame(jni);
696 if (new_bit_rate > 0) {
697 last_set_bitrate_kbps_ = new_bit_rate;
698 }
699 if (frame_rate > 0) {
700 last_set_fps_ = frame_rate;
701 }
702 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
703 j_set_rates_method_,
704 last_set_bitrate_kbps_,
705 last_set_fps_);
706 CHECK_EXCEPTION(jni);
707 if (!ret) {
perkj90754172015-10-12 03:04:15 -0700708 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000709 return WEBRTC_VIDEO_CODEC_ERROR;
710 }
711 return WEBRTC_VIDEO_CODEC_OK;
712}
713
714int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
715 JNIEnv* jni,
716 jobject j_output_buffer_info) {
717 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
718}
719
720jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
721 JNIEnv* jni,
722 jobject j_output_buffer_info) {
723 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
724}
725
726bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
727 JNIEnv* jni,
728 jobject j_output_buffer_info) {
729 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
730}
731
732jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
733 JNIEnv* jni,
734 jobject j_output_buffer_info) {
735 return GetLongField(
736 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
737}
738
739bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj90754172015-10-12 03:04:15 -0700740 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000741 while (true) {
742 jobject j_output_buffer_info = jni->CallObjectMethod(
743 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
744 CHECK_EXCEPTION(jni);
745 if (IsNull(jni, j_output_buffer_info)) {
746 break;
747 }
748
749 int output_buffer_index =
750 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
751 if (output_buffer_index == -1) {
perkj90754172015-10-12 03:04:15 -0700752 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000753 return false;
754 }
755
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000756 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000757 jobject j_output_buffer =
758 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
759 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000760
761 // Get frame timestamps from a queue - for non config frames only.
762 int64_t frame_encoding_time_ms = 0;
763 last_output_timestamp_ms_ =
764 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
765 1000;
766 if (frames_in_queue_ > 0) {
767 output_timestamp_ = timestamps_.front();
768 timestamps_.erase(timestamps_.begin());
769 output_render_time_ms_ = render_times_ms_.front();
770 render_times_ms_.erase(render_times_ms_.begin());
771 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
772 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
773 frames_in_queue_--;
774 }
775
776 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000777 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200778 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000779 jni->GetDirectBufferAddress(j_output_buffer));
780 CHECK_EXCEPTION(jni);
781
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000782 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
783 " Latency: %lld. EncTime: %lld",
784 frames_encoded_, key_frame, payload_size,
785 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000786 last_input_timestamp_ms_ - last_output_timestamp_ms_,
787 frame_encoding_time_ms);
788
789 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000790 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000791 current_frames_++;
792 current_bytes_ += payload_size;
793 current_encoding_time_ms_ += frame_encoding_time_ms;
794 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
795 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
796 current_frames_ > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700797 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
798 (current_bytes_ * 8 / statistic_time_ms) <<
799 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
800 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
801 << ", encTime: " <<
802 (current_encoding_time_ms_ / current_frames_) << " for last " <<
803 statistic_time_ms << " ms.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000804 start_time_ms_ = GetCurrentTimeMs();
805 current_frames_ = 0;
806 current_bytes_ = 0;
807 current_encoding_time_ms_ = 0;
808 }
809
810 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000811 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000812 if (callback_) {
813 scoped_ptr<webrtc::EncodedImage> image(
814 new webrtc::EncodedImage(payload, payload_size, payload_size));
815 image->_encodedWidth = width_;
816 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000817 image->_timeStamp = output_timestamp_;
818 image->capture_time_ms_ = output_render_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000819 image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
820 image->_completeFrame = true;
821
822 webrtc::CodecSpecificInfo info;
823 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000824 info.codecType = codecType_;
825 if (codecType_ == kVideoCodecVP8) {
826 info.codecSpecific.VP8.pictureId = picture_id_;
827 info.codecSpecific.VP8.nonReference = false;
828 info.codecSpecific.VP8.simulcastIdx = 0;
829 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
830 info.codecSpecific.VP8.layerSync = false;
831 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
832 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
833 picture_id_ = (picture_id_ + 1) & 0x7FFF;
834 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000835
836 // Generate a header describing a single fragment.
837 webrtc::RTPFragmentationHeader header;
838 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000839 if (codecType_ == kVideoCodecVP8) {
840 header.VerifyAndAllocateFragmentationHeader(1);
841 header.fragmentationOffset[0] = 0;
842 header.fragmentationLength[0] = image->_length;
843 header.fragmentationPlType[0] = 0;
844 header.fragmentationTimeDiff[0] = 0;
Peter Boström2bc68c72015-09-24 16:22:28 +0200845 if (scale_)
846 quality_scaler_.ReportQP(webrtc::vp8::GetQP(payload));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000847 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200848 if (scale_) {
849 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
850 int qp;
851 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
852 quality_scaler_.ReportQP(qp);
853 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000854 // For H.264 search for start codes.
855 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
856 int32_t scPositionsLength = 0;
857 int32_t scPosition = 0;
858 while (scPositionsLength < MAX_NALUS_PERFRAME) {
859 int32_t naluPosition = NextNaluPosition(
860 payload + scPosition, payload_size - scPosition);
861 if (naluPosition < 0) {
862 break;
863 }
864 scPosition += naluPosition;
865 scPositions[scPositionsLength++] = scPosition;
866 scPosition += H264_SC_LENGTH;
867 }
868 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700869 ALOGE << "Start code is not found!";
870 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
871 << " " << image->_buffer[2] << " " << image->_buffer[3]
872 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj90754172015-10-12 03:04:15 -0700873 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000874 return false;
875 }
876 scPositions[scPositionsLength] = payload_size;
877 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
878 for (size_t i = 0; i < scPositionsLength; i++) {
879 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
880 header.fragmentationLength[i] =
881 scPositions[i + 1] - header.fragmentationOffset[i];
882 header.fragmentationPlType[i] = 0;
883 header.fragmentationTimeDiff[i] = 0;
884 }
885 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000886
887 callback_status = callback_->Encoded(*image, &info, &header);
888 }
889
890 // Return output buffer back to the encoder.
891 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
892 j_release_output_buffer_method_,
893 output_buffer_index);
894 CHECK_EXCEPTION(jni);
895 if (!success) {
perkj90754172015-10-12 03:04:15 -0700896 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000897 return false;
898 }
899
900 if (callback_status > 0) {
901 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000902 // Theoretically could handle callback_status<0 here, but unclear what
903 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000904 }
905 }
906
907 return true;
908}
909
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000910int32_t MediaCodecVideoEncoder::NextNaluPosition(
911 uint8_t *buffer, size_t buffer_size) {
912 if (buffer_size < H264_SC_LENGTH) {
913 return -1;
914 }
915 uint8_t *head = buffer;
916 // Set end buffer pointer to 4 bytes before actual buffer end so we can
917 // access head[1], head[2] and head[3] in a loop without buffer overrun.
918 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
919
920 while (head < end) {
921 if (head[0]) {
922 head++;
923 continue;
924 }
925 if (head[1]) { // got 00xx
926 head += 2;
927 continue;
928 }
929 if (head[2]) { // got 0000xx
930 head += 3;
931 continue;
932 }
933 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000934 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000935 continue;
936 }
937 return (int32_t)(head - buffer);
938 }
939 return -1;
940}
941
jackychen61b4d512015-04-21 15:30:11 -0700942void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200943 if (scale_)
944 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700945}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000946
jackychen6e2ce6e2015-07-13 16:26:33 -0700947int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200948 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -0700949}
950
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000951MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
952 JNIEnv* jni = AttachCurrentThreadIfNeeded();
953 ScopedLocalRefFrame local_ref_frame(jni);
954 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000955 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000956
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000957 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
958 j_encoder_class,
959 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
960 CHECK_EXCEPTION(jni);
961 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700962 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000963 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
964 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
965 }
966
967 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
968 j_encoder_class,
969 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
970 CHECK_EXCEPTION(jni);
971 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700972 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000973 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
974 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
975 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000976}
977
978MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
979
980webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000981 VideoCodecType type) {
982 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000983 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000984 }
985 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
986 it != supported_codecs_.end(); ++it) {
987 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700988 ALOGD << "Create HW video encoder for type " << (int)type <<
989 " (" << it->name << ").";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000990 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
991 }
992 }
993 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000994}
995
996const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
997MediaCodecVideoEncoderFactory::codecs() const {
998 return supported_codecs_;
999}
1000
1001void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1002 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001003 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001004 delete encoder;
1005}
1006
1007} // namespace webrtc_jni
1008