blob: a69db8b805168987f5702c255ef8ce44a329d17b [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"
Peter Boström2bc68c72015-09-24 16:22:28 +020036#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000037#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
jackychen61b4d512015-04-21 15:30:11 -070038#include "webrtc/modules/video_coding/utility/include/quality_scaler.h"
jackychen98d8cf52015-05-21 11:12:02 -070039#include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h"
asaperssonef5d5e42015-09-22 01:40:42 -070040#include "webrtc/system_wrappers/interface/field_trial.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000041#include "webrtc/system_wrappers/interface/logcat_trace_context.h"
42#include "third_party/libyuv/include/libyuv/convert.h"
43#include "third_party/libyuv/include/libyuv/convert_from.h"
44#include "third_party/libyuv/include/libyuv/video_common.h"
45
46using rtc::Bind;
47using rtc::Thread;
48using rtc::ThreadManager;
49using rtc::scoped_ptr;
50
51using webrtc::CodecSpecificInfo;
52using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070053using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000054using webrtc::RTPFragmentationHeader;
55using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000056using webrtc::VideoCodecType;
57using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000058using webrtc::kVideoCodecVP8;
59
60namespace webrtc_jni {
61
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000062// H.264 start code length.
63#define H264_SC_LENGTH 4
64// Maximum allowed NALUs in one output frame.
65#define MAX_NALUS_PERFRAME 32
66// Maximum supported HW video encoder resolution.
67#define MAX_VIDEO_WIDTH 1280
68#define MAX_VIDEO_HEIGHT 1280
69// Maximum supported HW video encoder fps.
70#define MAX_VIDEO_FPS 30
71
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000072// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
73// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
74// HW-backed video encode. This C++ class is implemented as a very thin shim,
75// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
76// MediaCodecVideoEncoder is created, operated, and destroyed on a single
77// thread, currently the libjingle Worker thread.
78class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
79 public rtc::MessageHandler {
80 public:
81 virtual ~MediaCodecVideoEncoder();
perkj12f68022015-10-16 13:31:45 +020082 explicit MediaCodecVideoEncoder(JNIEnv* jni, VideoCodecType codecType);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000083
84 // webrtc::VideoEncoder implementation. Everything trampolines to
85 // |codec_thread_| for execution.
86 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
87 int32_t /* number_of_cores */,
88 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -070089 int32_t Encode(const webrtc::VideoFrame& input_image,
90 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
91 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000092 int32_t RegisterEncodeCompleteCallback(
93 webrtc::EncodedImageCallback* callback) override;
94 int32_t Release() override;
95 int32_t SetChannelParameters(uint32_t /* packet_loss */,
96 int64_t /* rtt */) override;
97 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
98
99 // rtc::MessageHandler implementation.
100 void OnMessage(rtc::Message* msg) override;
101
jackychen61b4d512015-04-21 15:30:11 -0700102 void OnDroppedFrame() override;
103
jackychen6e2ce6e2015-07-13 16:26:33 -0700104 int GetTargetFramerate() override;
105
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000106 private:
perkj12f68022015-10-16 13:31:45 +0200107 // CHECK-fail if not running on |codec_thread_|.
108 void CheckOnCodecThread();
109
110 // Release() and InitEncode() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000111 // operable state. Necessary after all manner of OMX-layer errors.
perkj12f68022015-10-16 13:31:45 +0200112 void ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000113
114 // Implementation of webrtc::VideoEncoder methods above, all running on the
115 // codec thread exclusively.
116 //
117 // If width==0 then this is assumed to be a re-initialization and the
118 // previously-current values are reused instead of the passed parameters
119 // (makes it easier to reason about thread-safety).
120 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps);
121 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700122 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700123 const std::vector<webrtc::FrameType>* frame_types);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000124 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
125 webrtc::EncodedImageCallback* callback);
126 int32_t ReleaseOnCodecThread();
127 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
128
129 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
130 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
131 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
132 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
133 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000134 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000135
136 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
137 // true on success.
138 bool DeliverPendingOutputs(JNIEnv* jni);
139
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000140 // Search for H.264 start codes.
141 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
142
143 // Type of video codec.
144 VideoCodecType codecType_;
145
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000146 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
147 // |codec_thread_| synchronously.
148 webrtc::EncodedImageCallback* callback_;
149
150 // State that is constant for the lifetime of this object once the ctor
151 // returns.
152 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
153 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
154 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
155 jmethodID j_init_encode_method_;
156 jmethodID j_dequeue_input_buffer_method_;
perkj12f68022015-10-16 13:31:45 +0200157 jmethodID j_encode_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000158 jmethodID j_release_method_;
159 jmethodID j_set_rates_method_;
160 jmethodID j_dequeue_output_buffer_method_;
161 jmethodID j_release_output_buffer_method_;
162 jfieldID j_color_format_field_;
163 jfieldID j_info_index_field_;
164 jfieldID j_info_buffer_field_;
165 jfieldID j_info_is_key_frame_field_;
166 jfieldID j_info_presentation_timestamp_us_field_;
167
168 // State that is valid only between InitEncode() and the next Release().
169 // Touched only on codec_thread_ so no explicit synchronization necessary.
170 int width_; // Frame width in pixels.
171 int height_; // Frame height in pixels.
172 bool inited_;
173 uint16_t picture_id_;
174 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
175 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
176 int last_set_fps_; // Last-requested frame rate.
177 int64_t current_timestamp_us_; // Current frame timestamps in us.
178 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000179 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000180 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000181 int frames_in_queue_; // Number of frames in encoder queue.
182 int64_t start_time_ms_; // Start time for statistics.
183 int current_frames_; // Number of frames in the current statistics interval.
184 int current_bytes_; // Encoded bytes in the current statistics interval.
185 int current_encoding_time_ms_; // Overall encoding time in the current second
186 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
187 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
188 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
189 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
190 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
191 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000192 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
193 int64_t output_render_time_ms_; // Last output frame render time from
194 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000195 // Frame size in bytes fed to MediaCodec.
196 int yuv_size_;
197 // True only when between a callback_->Encoded() call return a positive value
198 // and the next Encode() call being ignored.
199 bool drop_next_input_frame_;
200 // Global references; must be deleted in Release().
201 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200202 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700203 // Dynamic resolution change, off by default.
204 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200205
206 // H264 bitstream parser, used to extract QP from encoded bitstreams.
207 webrtc::H264BitstreamParser h264_bitstream_parser_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000208};
209
210MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
211 // Call Release() to ensure no more callbacks to us after we are deleted.
212 Release();
213}
214
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000215MediaCodecVideoEncoder::MediaCodecVideoEncoder(
216 JNIEnv* jni, VideoCodecType codecType) :
217 codecType_(codecType),
218 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000219 inited_(false),
220 picture_id_(0),
221 codec_thread_(new Thread()),
222 j_media_codec_video_encoder_class_(
223 jni,
224 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
225 j_media_codec_video_encoder_(
226 jni,
227 jni->NewObject(*j_media_codec_video_encoder_class_,
228 GetMethodID(jni,
229 *j_media_codec_video_encoder_class_,
230 "<init>",
231 "()V"))) {
232 ScopedLocalRefFrame local_ref_frame(jni);
233 // It would be nice to avoid spinning up a new thread per MediaCodec, and
234 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
235 // 2732 means that deadlocks abound. This class synchronously trampolines
236 // to |codec_thread_|, so if anything else can be coming to _us_ from
237 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
238 // in the bug, we have a problem. For now work around that with a dedicated
239 // thread.
240 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700241 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj12f68022015-10-16 13:31:45 +0200242
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000243 jclass j_output_buffer_info_class =
244 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000245 j_init_encode_method_ = GetMethodID(
246 jni,
247 *j_media_codec_video_encoder_class_,
248 "initEncode",
perkj12f68022015-10-16 13:31:45 +0200249 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)"
250 "[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000251 j_dequeue_input_buffer_method_ = GetMethodID(
252 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj12f68022015-10-16 13:31:45 +0200253 j_encode_method_ = GetMethodID(
254 jni, *j_media_codec_video_encoder_class_, "encode", "(ZIIJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000255 j_release_method_ =
256 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
257 j_set_rates_method_ = GetMethodID(
258 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000259 j_dequeue_output_buffer_method_ = GetMethodID(
260 jni,
261 *j_media_codec_video_encoder_class_,
262 "dequeueOutputBuffer",
263 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000264 j_release_output_buffer_method_ = GetMethodID(
265 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
266
267 j_color_format_field_ =
268 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
269 j_info_index_field_ =
270 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
271 j_info_buffer_field_ = GetFieldID(
272 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
273 j_info_is_key_frame_field_ =
274 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
275 j_info_presentation_timestamp_us_field_ = GetFieldID(
276 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
277 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
278 AllowBlockingCalls();
279}
280
281int32_t MediaCodecVideoEncoder::InitEncode(
282 const webrtc::VideoCodec* codec_settings,
283 int32_t /* number_of_cores */,
284 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700285 const int kMinWidth = 320;
286 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700287 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000288 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700289 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000290 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
291 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000292 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700293 RTC_CHECK(codec_settings->codecType == codecType_)
294 << "Unsupported codec " << codec_settings->codecType << " for "
295 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000296
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700297 ALOGD << "InitEncode request";
asaperssonef5d5e42015-09-22 01:40:42 -0700298 scale_ = webrtc::field_trial::FindFullName(
299 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled";
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700300 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200301 if (scale_) {
302 if (codecType_ == kVideoCodecVP8) {
303 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
304 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
305 // always = 127. Note that in SW, QP is that of the user-level range [0,
306 // 63].
307 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200308 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
309 // This effectively disables high QP as VP8 QP can't go above this
310 // threshold.
311 const int kDisabledBadQpThreshold = kMaxQp + 1;
312 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
313 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200314 } else if (codecType_ == kVideoCodecH264) {
315 // H264 QP is in the range [0, 51].
316 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200317 const int kBadQpThreshold = 40;
318 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
319 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200320 } else {
321 // When adding codec support to additional hardware codecs, also configure
322 // their QP thresholds for scaling.
323 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
324 }
325 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
326 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700327 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000328 return codec_thread_->Invoke<int32_t>(
329 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
330 this,
331 codec_settings->width,
332 codec_settings->height,
333 codec_settings->startBitrate,
334 codec_settings->maxFramerate));
335}
336
337int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700338 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000339 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700340 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000341 return codec_thread_->Invoke<int32_t>(Bind(
342 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
343}
344
345int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
346 webrtc::EncodedImageCallback* callback) {
347 return codec_thread_->Invoke<int32_t>(
348 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
349 this,
350 callback));
351}
352
353int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700354 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000355 return codec_thread_->Invoke<int32_t>(
356 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
357}
358
359int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
360 int64_t /* rtt */) {
361 return WEBRTC_VIDEO_CODEC_OK;
362}
363
364int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
365 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200366 if (scale_)
367 quality_scaler_.ReportFramerate(frame_rate);
368
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000369 return codec_thread_->Invoke<int32_t>(
370 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
371 this,
372 new_bit_rate,
373 frame_rate));
374}
375
376void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
377 JNIEnv* jni = AttachCurrentThreadIfNeeded();
378 ScopedLocalRefFrame local_ref_frame(jni);
379
380 // We only ever send one message to |this| directly (not through a Bind()'d
381 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700382 RTC_CHECK(!msg->message_id) << "Unexpected message!";
383 RTC_CHECK(!msg->pdata) << "Unexpected message!";
perkj12f68022015-10-16 13:31:45 +0200384 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000385 if (!inited_) {
386 return;
387 }
388
389 // It would be nice to recover from a failure here if one happened, but it's
390 // unclear how to signal such a failure to the app, so instead we stay silent
391 // about it and let the next app-called API method reveal the borkedness.
392 DeliverPendingOutputs(jni);
393 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
394}
395
perkj12f68022015-10-16 13:31:45 +0200396void MediaCodecVideoEncoder::CheckOnCodecThread() {
397 RTC_CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
398 << "Running on wrong thread!";
399}
400
401void MediaCodecVideoEncoder::ResetCodec() {
402 ALOGE << "ResetCodec";
403 if (Release() != WEBRTC_VIDEO_CODEC_OK ||
404 codec_thread_->Invoke<int32_t>(Bind(
405 &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this,
406 width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000407 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
408 // degrade to a SW encoder at this point? There isn't one AFAICT :(
409 // https://code.google.com/p/webrtc/issues/detail?id=2920
410 }
411}
412
413int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
414 int width, int height, int kbps, int fps) {
perkj12f68022015-10-16 13:31:45 +0200415 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000416 JNIEnv* jni = AttachCurrentThreadIfNeeded();
417 ScopedLocalRefFrame local_ref_frame(jni);
418
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700419 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
420 width << " x " << height << ". Bitrate: " << kbps <<
421 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000422 if (kbps == 0) {
423 kbps = last_set_bitrate_kbps_;
424 }
425 if (fps == 0) {
426 fps = last_set_fps_;
427 }
428
429 width_ = width;
430 height_ = height;
431 last_set_bitrate_kbps_ = kbps;
432 last_set_fps_ = fps;
433 yuv_size_ = width_ * height_ * 3 / 2;
434 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000435 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000436 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000437 frames_in_queue_ = 0;
438 current_timestamp_us_ = 0;
439 start_time_ms_ = GetCurrentTimeMs();
440 current_frames_ = 0;
441 current_bytes_ = 0;
442 current_encoding_time_ms_ = 0;
443 last_input_timestamp_ms_ = -1;
444 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000445 output_timestamp_ = 0;
446 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000447 timestamps_.clear();
448 render_times_ms_.clear();
449 frame_rtc_times_ms_.clear();
450 drop_next_input_frame_ = false;
451 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
452 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000453 jobject j_video_codec_enum = JavaEnumFromIndex(
454 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000455 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
456 jni->CallObjectMethod(*j_media_codec_video_encoder_,
perkj12f68022015-10-16 13:31:45 +0200457 j_init_encode_method_,
458 j_video_codec_enum,
459 width_,
460 height_,
461 kbps,
462 fps));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000463 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000464 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000465 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000466 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000467
perkj12f68022015-10-16 13:31:45 +0200468 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000469 switch (GetIntField(jni, *j_media_codec_video_encoder_,
470 j_color_format_field_)) {
471 case COLOR_FormatYUV420Planar:
472 encoder_fourcc_ = libyuv::FOURCC_YU12;
473 break;
474 case COLOR_FormatYUV420SemiPlanar:
475 case COLOR_QCOM_FormatYUV420SemiPlanar:
476 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
477 encoder_fourcc_ = libyuv::FOURCC_NV12;
478 break;
479 default:
480 LOG(LS_ERROR) << "Wrong color format.";
481 return WEBRTC_VIDEO_CODEC_ERROR;
482 }
483 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
henrikg91d6ede2015-09-17 00:24:34 -0700484 RTC_CHECK(input_buffers_.empty())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485 << "Unexpected double InitEncode without Release";
486 input_buffers_.resize(num_input_buffers);
487 for (size_t i = 0; i < num_input_buffers; ++i) {
488 input_buffers_[i] =
489 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
Peter Boström0c4e06b2015-10-07 12:23:21 +0200490 int64_t yuv_buffer_capacity =
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000491 jni->GetDirectBufferCapacity(input_buffers_[i]);
492 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700493 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000494 }
495 CHECK_EXCEPTION(jni);
496
497 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
498 return WEBRTC_VIDEO_CODEC_OK;
499}
500
501int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700502 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700503 const std::vector<webrtc::FrameType>* frame_types) {
perkj12f68022015-10-16 13:31:45 +0200504 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000505 JNIEnv* jni = AttachCurrentThreadIfNeeded();
506 ScopedLocalRefFrame local_ref_frame(jni);
507
508 if (!inited_) {
509 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
510 }
511 frames_received_++;
512 if (!DeliverPendingOutputs(jni)) {
perkj12f68022015-10-16 13:31:45 +0200513 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000514 // Continue as if everything's fine.
515 }
516
517 if (drop_next_input_frame_) {
perkj12f68022015-10-16 13:31:45 +0200518 ALOGV("Encoder drop frame - failed callback.");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000519 drop_next_input_frame_ = false;
520 return WEBRTC_VIDEO_CODEC_OK;
521 }
522
henrikg91d6ede2015-09-17 00:24:34 -0700523 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen6e2ce6e2015-07-13 16:26:33 -0700524 // Check framerate before spatial resolution change.
Peter Boström2bc68c72015-09-24 16:22:28 +0200525 if (scale_)
526 quality_scaler_.OnEncodeFrame(frame);
527
528 const VideoFrame& input_frame =
529 scale_ ? quality_scaler_.GetScaledFrame(frame) : frame;
jackychen61b4d512015-04-21 15:30:11 -0700530
perkj12f68022015-10-16 13:31:45 +0200531 if (input_frame.width() != width_ || input_frame.height() != height_) {
532 ALOGD << "Frame resolution change from " << width_ << " x " << height_ <<
533 " to " << input_frame.width() << " x " << input_frame.height();
534 width_ = input_frame.width();
535 height_ = input_frame.height();
536 ResetCodec();
537 return WEBRTC_VIDEO_CODEC_OK;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000539
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000540 // Check if we accumulated too many frames in encoder input buffers
541 // or the encoder latency exceeds 70 ms and drop frame if so.
542 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
543 int encoder_latency_ms = last_input_timestamp_ms_ -
544 last_output_timestamp_ms_;
545 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700546 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
547 " ms. Q size: " << frames_in_queue_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000548 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700549 // Report dropped frame to quality_scaler_.
550 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000551 return WEBRTC_VIDEO_CODEC_OK;
552 }
553 }
554
555 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
556 j_dequeue_input_buffer_method_);
557 CHECK_EXCEPTION(jni);
558 if (j_input_buffer_index == -1) {
559 // Video codec falls behind - no input buffer available.
perkj12f68022015-10-16 13:31:45 +0200560 ALOGV("Encoder drop frame - no input buffers available");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000561 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700562 // Report dropped frame to quality_scaler_.
563 OnDroppedFrame();
perkj12f68022015-10-16 13:31:45 +0200564 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000565 }
566 if (j_input_buffer_index == -2) {
perkj12f68022015-10-16 13:31:45 +0200567 ResetCodec();
568 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000569 }
570
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000571 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
572 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000573
574 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200575 uint8_t* yuv_buffer =
576 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000577 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700578 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
579 RTC_CHECK(!libyuv::ConvertFromI420(
perkj12f68022015-10-16 13:31:45 +0200580 input_frame.buffer(webrtc::kYPlane), input_frame.stride(webrtc::kYPlane),
581 input_frame.buffer(webrtc::kUPlane), input_frame.stride(webrtc::kUPlane),
582 input_frame.buffer(webrtc::kVPlane), input_frame.stride(webrtc::kVPlane),
henrikg91d6ede2015-09-17 00:24:34 -0700583 yuv_buffer, width_, width_, height_, encoder_fourcc_))
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000584 << "ConvertFromI420 failed";
perkj12f68022015-10-16 13:31:45 +0200585 last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
586 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000587
perkj12f68022015-10-16 13:31:45 +0200588 // Save input image timestamps for later output
589 timestamps_.push_back(input_frame.timestamp());
590 render_times_ms_.push_back(input_frame.render_time_ms());
591 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000592
Peter Boström49e196a2015-10-23 15:58:18 +0200593 bool key_frame = frame_types->front() != webrtc::kVideoFrameDelta;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000594 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj12f68022015-10-16 13:31:45 +0200595 j_encode_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000596 key_frame,
597 j_input_buffer_index,
598 yuv_size_,
599 current_timestamp_us_);
600 CHECK_EXCEPTION(jni);
perkj12f68022015-10-16 13:31:45 +0200601 current_timestamp_us_ += 1000000 / last_set_fps_;
602
603 if (!encode_status || !DeliverPendingOutputs(jni)) {
604 ResetCodec();
605 return WEBRTC_VIDEO_CODEC_ERROR;
606 }
607
608 return WEBRTC_VIDEO_CODEC_OK;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000609}
610
611int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
612 webrtc::EncodedImageCallback* callback) {
perkj12f68022015-10-16 13:31:45 +0200613 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000614 JNIEnv* jni = AttachCurrentThreadIfNeeded();
615 ScopedLocalRefFrame local_ref_frame(jni);
616 callback_ = callback;
617 return WEBRTC_VIDEO_CODEC_OK;
618}
619
620int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
621 if (!inited_) {
622 return WEBRTC_VIDEO_CODEC_OK;
623 }
perkj12f68022015-10-16 13:31:45 +0200624 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000625 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700626 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
627 frames_received_ << ". Encoded: " << frames_encoded_ <<
628 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000629 ScopedLocalRefFrame local_ref_frame(jni);
630 for (size_t i = 0; i < input_buffers_.size(); ++i)
631 jni->DeleteGlobalRef(input_buffers_[i]);
632 input_buffers_.clear();
633 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
634 CHECK_EXCEPTION(jni);
635 rtc::MessageQueueManager::Clear(this);
636 inited_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700637 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000638 return WEBRTC_VIDEO_CODEC_OK;
639}
640
641int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
642 uint32_t frame_rate) {
perkj12f68022015-10-16 13:31:45 +0200643 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000644 if (last_set_bitrate_kbps_ == new_bit_rate &&
645 last_set_fps_ == frame_rate) {
646 return WEBRTC_VIDEO_CODEC_OK;
647 }
648 JNIEnv* jni = AttachCurrentThreadIfNeeded();
649 ScopedLocalRefFrame local_ref_frame(jni);
650 if (new_bit_rate > 0) {
651 last_set_bitrate_kbps_ = new_bit_rate;
652 }
653 if (frame_rate > 0) {
654 last_set_fps_ = frame_rate;
655 }
656 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
657 j_set_rates_method_,
658 last_set_bitrate_kbps_,
659 last_set_fps_);
660 CHECK_EXCEPTION(jni);
661 if (!ret) {
perkj12f68022015-10-16 13:31:45 +0200662 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000663 return WEBRTC_VIDEO_CODEC_ERROR;
664 }
665 return WEBRTC_VIDEO_CODEC_OK;
666}
667
668int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
669 JNIEnv* jni,
670 jobject j_output_buffer_info) {
671 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
672}
673
674jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
675 JNIEnv* jni,
676 jobject j_output_buffer_info) {
677 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
678}
679
680bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
681 JNIEnv* jni,
682 jobject j_output_buffer_info) {
683 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
684}
685
686jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
687 JNIEnv* jni,
688 jobject j_output_buffer_info) {
689 return GetLongField(
690 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
691}
692
693bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
694 while (true) {
695 jobject j_output_buffer_info = jni->CallObjectMethod(
696 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
697 CHECK_EXCEPTION(jni);
698 if (IsNull(jni, j_output_buffer_info)) {
699 break;
700 }
701
702 int output_buffer_index =
703 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
704 if (output_buffer_index == -1) {
perkj12f68022015-10-16 13:31:45 +0200705 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000706 return false;
707 }
708
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000709 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000710 jobject j_output_buffer =
711 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
712 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000713
714 // Get frame timestamps from a queue - for non config frames only.
715 int64_t frame_encoding_time_ms = 0;
716 last_output_timestamp_ms_ =
717 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
718 1000;
719 if (frames_in_queue_ > 0) {
720 output_timestamp_ = timestamps_.front();
721 timestamps_.erase(timestamps_.begin());
722 output_render_time_ms_ = render_times_ms_.front();
723 render_times_ms_.erase(render_times_ms_.begin());
724 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
725 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
726 frames_in_queue_--;
727 }
728
729 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000730 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200731 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000732 jni->GetDirectBufferAddress(j_output_buffer));
733 CHECK_EXCEPTION(jni);
734
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000735 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
736 " Latency: %lld. EncTime: %lld",
737 frames_encoded_, key_frame, payload_size,
738 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000739 last_input_timestamp_ms_ - last_output_timestamp_ms_,
740 frame_encoding_time_ms);
741
742 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000743 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000744 current_frames_++;
745 current_bytes_ += payload_size;
746 current_encoding_time_ms_ += frame_encoding_time_ms;
747 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
748 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
749 current_frames_ > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700750 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
751 (current_bytes_ * 8 / statistic_time_ms) <<
752 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
753 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
754 << ", encTime: " <<
755 (current_encoding_time_ms_ / current_frames_) << " for last " <<
756 statistic_time_ms << " ms.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000757 start_time_ms_ = GetCurrentTimeMs();
758 current_frames_ = 0;
759 current_bytes_ = 0;
760 current_encoding_time_ms_ = 0;
761 }
762
763 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000764 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000765 if (callback_) {
766 scoped_ptr<webrtc::EncodedImage> image(
767 new webrtc::EncodedImage(payload, payload_size, payload_size));
768 image->_encodedWidth = width_;
769 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000770 image->_timeStamp = output_timestamp_;
771 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200772 image->_frameType =
773 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000774 image->_completeFrame = true;
775
776 webrtc::CodecSpecificInfo info;
777 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000778 info.codecType = codecType_;
779 if (codecType_ == kVideoCodecVP8) {
780 info.codecSpecific.VP8.pictureId = picture_id_;
781 info.codecSpecific.VP8.nonReference = false;
782 info.codecSpecific.VP8.simulcastIdx = 0;
783 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
784 info.codecSpecific.VP8.layerSync = false;
785 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
786 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
787 picture_id_ = (picture_id_ + 1) & 0x7FFF;
788 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000789
790 // Generate a header describing a single fragment.
791 webrtc::RTPFragmentationHeader header;
792 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000793 if (codecType_ == kVideoCodecVP8) {
794 header.VerifyAndAllocateFragmentationHeader(1);
795 header.fragmentationOffset[0] = 0;
796 header.fragmentationLength[0] = image->_length;
797 header.fragmentationPlType[0] = 0;
798 header.fragmentationTimeDiff[0] = 0;
asapersson86b01602015-10-20 23:55:26 -0700799 if (scale_) {
800 int qp;
801 if (webrtc::vp8::GetQp(payload, payload_size, &qp))
802 quality_scaler_.ReportQP(qp);
803 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000804 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200805 if (scale_) {
806 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
807 int qp;
808 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
809 quality_scaler_.ReportQP(qp);
810 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000811 // For H.264 search for start codes.
812 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
813 int32_t scPositionsLength = 0;
814 int32_t scPosition = 0;
815 while (scPositionsLength < MAX_NALUS_PERFRAME) {
816 int32_t naluPosition = NextNaluPosition(
817 payload + scPosition, payload_size - scPosition);
818 if (naluPosition < 0) {
819 break;
820 }
821 scPosition += naluPosition;
822 scPositions[scPositionsLength++] = scPosition;
823 scPosition += H264_SC_LENGTH;
824 }
825 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700826 ALOGE << "Start code is not found!";
827 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
828 << " " << image->_buffer[2] << " " << image->_buffer[3]
829 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj12f68022015-10-16 13:31:45 +0200830 ResetCodec();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000831 return false;
832 }
833 scPositions[scPositionsLength] = payload_size;
834 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
835 for (size_t i = 0; i < scPositionsLength; i++) {
836 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
837 header.fragmentationLength[i] =
838 scPositions[i + 1] - header.fragmentationOffset[i];
839 header.fragmentationPlType[i] = 0;
840 header.fragmentationTimeDiff[i] = 0;
841 }
842 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000843
844 callback_status = callback_->Encoded(*image, &info, &header);
845 }
846
847 // Return output buffer back to the encoder.
848 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
849 j_release_output_buffer_method_,
850 output_buffer_index);
851 CHECK_EXCEPTION(jni);
852 if (!success) {
perkj12f68022015-10-16 13:31:45 +0200853 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000854 return false;
855 }
856
857 if (callback_status > 0) {
858 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000859 // Theoretically could handle callback_status<0 here, but unclear what
860 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000861 }
862 }
863
864 return true;
865}
866
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000867int32_t MediaCodecVideoEncoder::NextNaluPosition(
868 uint8_t *buffer, size_t buffer_size) {
869 if (buffer_size < H264_SC_LENGTH) {
870 return -1;
871 }
872 uint8_t *head = buffer;
873 // Set end buffer pointer to 4 bytes before actual buffer end so we can
874 // access head[1], head[2] and head[3] in a loop without buffer overrun.
875 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
876
877 while (head < end) {
878 if (head[0]) {
879 head++;
880 continue;
881 }
882 if (head[1]) { // got 00xx
883 head += 2;
884 continue;
885 }
886 if (head[2]) { // got 0000xx
887 head += 3;
888 continue;
889 }
890 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000891 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000892 continue;
893 }
894 return (int32_t)(head - buffer);
895 }
896 return -1;
897}
898
jackychen61b4d512015-04-21 15:30:11 -0700899void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200900 if (scale_)
901 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700902}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000903
jackychen6e2ce6e2015-07-13 16:26:33 -0700904int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200905 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -0700906}
907
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000908MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
909 JNIEnv* jni = AttachCurrentThreadIfNeeded();
910 ScopedLocalRefFrame local_ref_frame(jni);
911 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000912 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000913
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000914 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
915 j_encoder_class,
916 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
917 CHECK_EXCEPTION(jni);
918 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700919 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000920 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
921 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
922 }
923
924 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
925 j_encoder_class,
926 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
927 CHECK_EXCEPTION(jni);
928 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700929 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000930 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
931 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
932 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000933}
934
935MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
936
937webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000938 VideoCodecType type) {
939 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000940 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000941 }
942 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
943 it != supported_codecs_.end(); ++it) {
944 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700945 ALOGD << "Create HW video encoder for type " << (int)type <<
946 " (" << it->name << ").";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000947 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
948 }
949 }
950 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000951}
952
953const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
954MediaCodecVideoEncoderFactory::codecs() const {
955 return supported_codecs_;
956}
957
958void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
959 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700960 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000961 delete encoder;
962}
963
964} // namespace webrtc_jni
965