blob: 8817df42df191569e8f0c388107a2bdf1af872ad [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();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000082 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;
89 int32_t Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070090 const webrtc::VideoFrame& input_image,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000091 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
92 const std::vector<webrtc::VideoFrameType>* frame_types) override;
93 int32_t RegisterEncodeCompleteCallback(
94 webrtc::EncodedImageCallback* callback) override;
95 int32_t Release() override;
96 int32_t SetChannelParameters(uint32_t /* packet_loss */,
97 int64_t /* rtt */) override;
98 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
99
100 // rtc::MessageHandler implementation.
101 void OnMessage(rtc::Message* msg) override;
102
jackychen61b4d512015-04-21 15:30:11 -0700103 void OnDroppedFrame() override;
104
jackychen6e2ce6e2015-07-13 16:26:33 -0700105 int GetTargetFramerate() override;
106
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000107 private:
108 // CHECK-fail if not running on |codec_thread_|.
109 void CheckOnCodecThread();
110
111 // Release() and InitEncode() in an attempt to restore the codec to an
112 // operable state. Necessary after all manner of OMX-layer errors.
113 void ResetCodec();
114
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);
122 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700123 const webrtc::VideoFrame& input_image,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000124 const std::vector<webrtc::VideoFrameType>* frame_types);
125 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
126 webrtc::EncodedImageCallback* callback);
127 int32_t ReleaseOnCodecThread();
128 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
129
130 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
131 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
132 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
133 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
134 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000135 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000136
137 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
138 // true on success.
139 bool DeliverPendingOutputs(JNIEnv* jni);
140
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000141 // Search for H.264 start codes.
142 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
143
144 // Type of video codec.
145 VideoCodecType codecType_;
146
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000147 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
148 // |codec_thread_| synchronously.
149 webrtc::EncodedImageCallback* callback_;
150
151 // State that is constant for the lifetime of this object once the ctor
152 // returns.
153 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
154 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
155 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
156 jmethodID j_init_encode_method_;
157 jmethodID j_dequeue_input_buffer_method_;
158 jmethodID j_encode_method_;
159 jmethodID j_release_method_;
160 jmethodID j_set_rates_method_;
161 jmethodID j_dequeue_output_buffer_method_;
162 jmethodID j_release_output_buffer_method_;
163 jfieldID j_color_format_field_;
164 jfieldID j_info_index_field_;
165 jfieldID j_info_buffer_field_;
166 jfieldID j_info_is_key_frame_field_;
167 jfieldID j_info_presentation_timestamp_us_field_;
168
169 // State that is valid only between InitEncode() and the next Release().
170 // Touched only on codec_thread_ so no explicit synchronization necessary.
171 int width_; // Frame width in pixels.
172 int height_; // Frame height in pixels.
173 bool inited_;
174 uint16_t picture_id_;
175 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
176 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
177 int last_set_fps_; // Last-requested frame rate.
178 int64_t current_timestamp_us_; // Current frame timestamps in us.
179 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000180 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000181 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000182 int frames_in_queue_; // Number of frames in encoder queue.
183 int64_t start_time_ms_; // Start time for statistics.
184 int current_frames_; // Number of frames in the current statistics interval.
185 int current_bytes_; // Encoded bytes in the current statistics interval.
186 int current_encoding_time_ms_; // Overall encoding time in the current second
187 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
188 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
189 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
190 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
191 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
192 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000193 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
194 int64_t output_render_time_ms_; // Last output frame render time from
195 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000196 // Frame size in bytes fed to MediaCodec.
197 int yuv_size_;
198 // True only when between a callback_->Encoded() call return a positive value
199 // and the next Encode() call being ignored.
200 bool drop_next_input_frame_;
201 // Global references; must be deleted in Release().
202 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200203 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700204 // Dynamic resolution change, off by default.
205 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200206
207 // H264 bitstream parser, used to extract QP from encoded bitstreams.
208 webrtc::H264BitstreamParser h264_bitstream_parser_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000209};
210
211MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
212 // Call Release() to ensure no more callbacks to us after we are deleted.
213 Release();
214}
215
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000216MediaCodecVideoEncoder::MediaCodecVideoEncoder(
217 JNIEnv* jni, VideoCodecType codecType) :
218 codecType_(codecType),
219 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000220 inited_(false),
221 picture_id_(0),
222 codec_thread_(new Thread()),
223 j_media_codec_video_encoder_class_(
224 jni,
225 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
226 j_media_codec_video_encoder_(
227 jni,
228 jni->NewObject(*j_media_codec_video_encoder_class_,
229 GetMethodID(jni,
230 *j_media_codec_video_encoder_class_,
231 "<init>",
232 "()V"))) {
233 ScopedLocalRefFrame local_ref_frame(jni);
234 // It would be nice to avoid spinning up a new thread per MediaCodec, and
235 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
236 // 2732 means that deadlocks abound. This class synchronously trampolines
237 // to |codec_thread_|, so if anything else can be coming to _us_ from
238 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
239 // in the bug, we have a problem. For now work around that with a dedicated
240 // thread.
241 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700242 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000243
244 jclass j_output_buffer_info_class =
245 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000246 j_init_encode_method_ = GetMethodID(
247 jni,
248 *j_media_codec_video_encoder_class_,
249 "initEncode",
250 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)"
251 "[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000252 j_dequeue_input_buffer_method_ = GetMethodID(
253 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
254 j_encode_method_ = GetMethodID(
255 jni, *j_media_codec_video_encoder_class_, "encode", "(ZIIJ)Z");
256 j_release_method_ =
257 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
258 j_set_rates_method_ = GetMethodID(
259 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000260 j_dequeue_output_buffer_method_ = GetMethodID(
261 jni,
262 *j_media_codec_video_encoder_class_,
263 "dequeueOutputBuffer",
264 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000265 j_release_output_buffer_method_ = GetMethodID(
266 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
267
268 j_color_format_field_ =
269 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
270 j_info_index_field_ =
271 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
272 j_info_buffer_field_ = GetFieldID(
273 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
274 j_info_is_key_frame_field_ =
275 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
276 j_info_presentation_timestamp_us_field_ = GetFieldID(
277 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
278 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
279 AllowBlockingCalls();
280}
281
282int32_t MediaCodecVideoEncoder::InitEncode(
283 const webrtc::VideoCodec* codec_settings,
284 int32_t /* number_of_cores */,
285 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700286 const int kMinWidth = 320;
287 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700288 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000289 if (codec_settings == NULL) {
290 ALOGE("NULL VideoCodec instance");
291 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
292 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000293 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700294 RTC_CHECK(codec_settings->codecType == codecType_)
295 << "Unsupported codec " << codec_settings->codecType << " for "
296 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000297
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000298 ALOGD("InitEncode request");
asaperssonef5d5e42015-09-22 01:40:42 -0700299 scale_ = webrtc::field_trial::FindFullName(
300 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled";
301 ALOGD("Automatic resize: %s", scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200302 if (scale_) {
303 if (codecType_ == kVideoCodecVP8) {
304 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
305 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
306 // always = 127. Note that in SW, QP is that of the user-level range [0,
307 // 63].
308 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200309 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
310 // This effectively disables high QP as VP8 QP can't go above this
311 // threshold.
312 const int kDisabledBadQpThreshold = kMaxQp + 1;
313 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
314 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200315 } else if (codecType_ == kVideoCodecH264) {
316 // H264 QP is in the range [0, 51].
317 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200318 const int kBadQpThreshold = 40;
319 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
320 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200321 } else {
322 // When adding codec support to additional hardware codecs, also configure
323 // their QP thresholds for scaling.
324 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
325 }
326 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
327 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700328 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000329 return codec_thread_->Invoke<int32_t>(
330 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
331 this,
332 codec_settings->width,
333 codec_settings->height,
334 codec_settings->startBitrate,
335 codec_settings->maxFramerate));
336}
337
338int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700339 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000340 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
341 const std::vector<webrtc::VideoFrameType>* frame_types) {
342 return codec_thread_->Invoke<int32_t>(Bind(
343 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
344}
345
346int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
347 webrtc::EncodedImageCallback* callback) {
348 return codec_thread_->Invoke<int32_t>(
349 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
350 this,
351 callback));
352}
353
354int32_t MediaCodecVideoEncoder::Release() {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000355 ALOGD("EncoderRelease request");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000356 return codec_thread_->Invoke<int32_t>(
357 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
358}
359
360int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
361 int64_t /* rtt */) {
362 return WEBRTC_VIDEO_CODEC_OK;
363}
364
365int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
366 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200367 if (scale_)
368 quality_scaler_.ReportFramerate(frame_rate);
369
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000370 return codec_thread_->Invoke<int32_t>(
371 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
372 this,
373 new_bit_rate,
374 frame_rate));
375}
376
377void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
378 JNIEnv* jni = AttachCurrentThreadIfNeeded();
379 ScopedLocalRefFrame local_ref_frame(jni);
380
381 // We only ever send one message to |this| directly (not through a Bind()'d
382 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700383 RTC_CHECK(!msg->message_id) << "Unexpected message!";
384 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000385 CheckOnCodecThread();
386 if (!inited_) {
387 return;
388 }
389
390 // It would be nice to recover from a failure here if one happened, but it's
391 // unclear how to signal such a failure to the app, so instead we stay silent
392 // about it and let the next app-called API method reveal the borkedness.
393 DeliverPendingOutputs(jni);
394 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
395}
396
397void MediaCodecVideoEncoder::CheckOnCodecThread() {
henrikg91d6ede2015-09-17 00:24:34 -0700398 RTC_CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000399 << "Running on wrong thread!";
400}
401
402void MediaCodecVideoEncoder::ResetCodec() {
403 ALOGE("ResetCodec");
404 if (Release() != WEBRTC_VIDEO_CODEC_OK ||
405 codec_thread_->Invoke<int32_t>(Bind(
406 &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this,
407 width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) {
408 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
409 // degrade to a SW encoder at this point? There isn't one AFAICT :(
410 // https://code.google.com/p/webrtc/issues/detail?id=2920
411 }
412}
413
414int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
415 int width, int height, int kbps, int fps) {
416 CheckOnCodecThread();
417 JNIEnv* jni = AttachCurrentThreadIfNeeded();
418 ScopedLocalRefFrame local_ref_frame(jni);
419
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000420 ALOGD("InitEncodeOnCodecThread Type: %d. %d x %d. Bitrate: %d kbps. Fps: %d",
421 (int)codecType_, width, height, kbps, 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_,
457 j_init_encode_method_,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000458 j_video_codec_enum,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000459 width_,
460 height_,
461 kbps,
462 fps));
463 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
468 inited_ = true;
469 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,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000503 const std::vector<webrtc::VideoFrameType>* frame_types) {
504 CheckOnCodecThread();
505 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)) {
513 ResetCodec();
514 // Continue as if everything's fine.
515 }
516
517 if (drop_next_input_frame_) {
518 ALOGV("Encoder drop frame - failed callback.");
519 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
531 if (input_frame.width() != width_ || input_frame.height() != height_) {
532 ALOGD("Frame resolution change from %d x %d to %d x %d",
533 width_, height_, input_frame.width(), input_frame.height());
534 width_ = input_frame.width();
535 height_ = input_frame.height();
536 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000537 return WEBRTC_VIDEO_CODEC_OK;
538 }
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) {
546 ALOGD("Drop frame - encoder is behind by %d ms. Q size: %d",
547 encoder_latency_ms, frames_in_queue_);
548 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.
560 ALOGV("Encoder drop frame - no input buffers available");
561 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700562 // Report dropped frame to quality_scaler_.
563 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000564 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
565 }
566 if (j_input_buffer_index == -2) {
567 ResetCodec();
568 return WEBRTC_VIDEO_CODEC_ERROR;
569 }
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(
580 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),
583 yuv_buffer, width_, width_, height_, encoder_fourcc_))
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000584 << "ConvertFromI420 failed";
585 last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
586 frames_in_queue_++;
587
588 // Save input image timestamps for later output
jackychen61b4d512015-04-21 15:30:11 -0700589 timestamps_.push_back(input_frame.timestamp());
590 render_times_ms_.push_back(input_frame.render_time_ms());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000591 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
592
jackychen6e2ce6e2015-07-13 16:26:33 -0700593 bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000594 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
595 j_encode_method_,
596 key_frame,
597 j_input_buffer_index,
598 yuv_size_,
599 current_timestamp_us_);
600 CHECK_EXCEPTION(jni);
601 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;
609}
610
611int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
612 webrtc::EncodedImageCallback* callback) {
613 CheckOnCodecThread();
614 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 }
624 CheckOnCodecThread();
625 JNIEnv* jni = AttachCurrentThreadIfNeeded();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000626 ALOGD("EncoderReleaseOnCodecThread: Frames received: %d. Encoded: %d. "
627 "Dropped: %d.", frames_received_, frames_encoded_, frames_dropped_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000628 ScopedLocalRefFrame local_ref_frame(jni);
629 for (size_t i = 0; i < input_buffers_.size(); ++i)
630 jni->DeleteGlobalRef(input_buffers_[i]);
631 input_buffers_.clear();
632 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
633 CHECK_EXCEPTION(jni);
634 rtc::MessageQueueManager::Clear(this);
635 inited_ = false;
636 return WEBRTC_VIDEO_CODEC_OK;
637}
638
639int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
640 uint32_t frame_rate) {
641 CheckOnCodecThread();
642 if (last_set_bitrate_kbps_ == new_bit_rate &&
643 last_set_fps_ == frame_rate) {
644 return WEBRTC_VIDEO_CODEC_OK;
645 }
646 JNIEnv* jni = AttachCurrentThreadIfNeeded();
647 ScopedLocalRefFrame local_ref_frame(jni);
648 if (new_bit_rate > 0) {
649 last_set_bitrate_kbps_ = new_bit_rate;
650 }
651 if (frame_rate > 0) {
652 last_set_fps_ = frame_rate;
653 }
654 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
655 j_set_rates_method_,
656 last_set_bitrate_kbps_,
657 last_set_fps_);
658 CHECK_EXCEPTION(jni);
659 if (!ret) {
660 ResetCodec();
661 return WEBRTC_VIDEO_CODEC_ERROR;
662 }
663 return WEBRTC_VIDEO_CODEC_OK;
664}
665
666int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
667 JNIEnv* jni,
668 jobject j_output_buffer_info) {
669 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
670}
671
672jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
673 JNIEnv* jni,
674 jobject j_output_buffer_info) {
675 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
676}
677
678bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
679 JNIEnv* jni,
680 jobject j_output_buffer_info) {
681 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
682}
683
684jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
685 JNIEnv* jni,
686 jobject j_output_buffer_info) {
687 return GetLongField(
688 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
689}
690
691bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
692 while (true) {
693 jobject j_output_buffer_info = jni->CallObjectMethod(
694 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
695 CHECK_EXCEPTION(jni);
696 if (IsNull(jni, j_output_buffer_info)) {
697 break;
698 }
699
700 int output_buffer_index =
701 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
702 if (output_buffer_index == -1) {
703 ResetCodec();
704 return false;
705 }
706
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000707 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000708 jobject j_output_buffer =
709 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
710 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000711
712 // Get frame timestamps from a queue - for non config frames only.
713 int64_t frame_encoding_time_ms = 0;
714 last_output_timestamp_ms_ =
715 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
716 1000;
717 if (frames_in_queue_ > 0) {
718 output_timestamp_ = timestamps_.front();
719 timestamps_.erase(timestamps_.begin());
720 output_render_time_ms_ = render_times_ms_.front();
721 render_times_ms_.erase(render_times_ms_.begin());
722 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
723 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
724 frames_in_queue_--;
725 }
726
727 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000728 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200729 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000730 jni->GetDirectBufferAddress(j_output_buffer));
731 CHECK_EXCEPTION(jni);
732
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000733 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
734 " Latency: %lld. EncTime: %lld",
735 frames_encoded_, key_frame, payload_size,
736 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000737 last_input_timestamp_ms_ - last_output_timestamp_ms_,
738 frame_encoding_time_ms);
739
740 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000741 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000742 current_frames_++;
743 current_bytes_ += payload_size;
744 current_encoding_time_ms_ += frame_encoding_time_ms;
745 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
746 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
747 current_frames_ > 0) {
748 ALOGD("Encoder bitrate: %d, target: %d kbps, fps: %d,"
749 " encTime: %d for last %d ms",
750 current_bytes_ * 8 / statistic_time_ms,
751 last_set_bitrate_kbps_,
752 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms,
753 current_encoding_time_ms_ / current_frames_, statistic_time_ms);
754 start_time_ms_ = GetCurrentTimeMs();
755 current_frames_ = 0;
756 current_bytes_ = 0;
757 current_encoding_time_ms_ = 0;
758 }
759
760 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000761 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000762 if (callback_) {
763 scoped_ptr<webrtc::EncodedImage> image(
764 new webrtc::EncodedImage(payload, payload_size, payload_size));
765 image->_encodedWidth = width_;
766 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000767 image->_timeStamp = output_timestamp_;
768 image->capture_time_ms_ = output_render_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000769 image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
770 image->_completeFrame = true;
771
772 webrtc::CodecSpecificInfo info;
773 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000774 info.codecType = codecType_;
775 if (codecType_ == kVideoCodecVP8) {
776 info.codecSpecific.VP8.pictureId = picture_id_;
777 info.codecSpecific.VP8.nonReference = false;
778 info.codecSpecific.VP8.simulcastIdx = 0;
779 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
780 info.codecSpecific.VP8.layerSync = false;
781 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
782 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
783 picture_id_ = (picture_id_ + 1) & 0x7FFF;
784 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000785
786 // Generate a header describing a single fragment.
787 webrtc::RTPFragmentationHeader header;
788 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000789 if (codecType_ == kVideoCodecVP8) {
790 header.VerifyAndAllocateFragmentationHeader(1);
791 header.fragmentationOffset[0] = 0;
792 header.fragmentationLength[0] = image->_length;
793 header.fragmentationPlType[0] = 0;
794 header.fragmentationTimeDiff[0] = 0;
Peter Boström2bc68c72015-09-24 16:22:28 +0200795 if (scale_)
796 quality_scaler_.ReportQP(webrtc::vp8::GetQP(payload));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000797 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200798 if (scale_) {
799 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
800 int qp;
801 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
802 quality_scaler_.ReportQP(qp);
803 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000804 // For H.264 search for start codes.
805 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
806 int32_t scPositionsLength = 0;
807 int32_t scPosition = 0;
808 while (scPositionsLength < MAX_NALUS_PERFRAME) {
809 int32_t naluPosition = NextNaluPosition(
810 payload + scPosition, payload_size - scPosition);
811 if (naluPosition < 0) {
812 break;
813 }
814 scPosition += naluPosition;
815 scPositions[scPositionsLength++] = scPosition;
816 scPosition += H264_SC_LENGTH;
817 }
818 if (scPositionsLength == 0) {
819 ALOGE("Start code is not found!");
820 ALOGE("Data 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
821 image->_buffer[0], image->_buffer[1], image->_buffer[2],
822 image->_buffer[3], image->_buffer[4], image->_buffer[5]);
823 ResetCodec();
824 return false;
825 }
826 scPositions[scPositionsLength] = payload_size;
827 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
828 for (size_t i = 0; i < scPositionsLength; i++) {
829 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
830 header.fragmentationLength[i] =
831 scPositions[i + 1] - header.fragmentationOffset[i];
832 header.fragmentationPlType[i] = 0;
833 header.fragmentationTimeDiff[i] = 0;
834 }
835 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000836
837 callback_status = callback_->Encoded(*image, &info, &header);
838 }
839
840 // Return output buffer back to the encoder.
841 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
842 j_release_output_buffer_method_,
843 output_buffer_index);
844 CHECK_EXCEPTION(jni);
845 if (!success) {
846 ResetCodec();
847 return false;
848 }
849
850 if (callback_status > 0) {
851 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000852 // Theoretically could handle callback_status<0 here, but unclear what
853 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000854 }
855 }
856
857 return true;
858}
859
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000860int32_t MediaCodecVideoEncoder::NextNaluPosition(
861 uint8_t *buffer, size_t buffer_size) {
862 if (buffer_size < H264_SC_LENGTH) {
863 return -1;
864 }
865 uint8_t *head = buffer;
866 // Set end buffer pointer to 4 bytes before actual buffer end so we can
867 // access head[1], head[2] and head[3] in a loop without buffer overrun.
868 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
869
870 while (head < end) {
871 if (head[0]) {
872 head++;
873 continue;
874 }
875 if (head[1]) { // got 00xx
876 head += 2;
877 continue;
878 }
879 if (head[2]) { // got 0000xx
880 head += 3;
881 continue;
882 }
883 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000884 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000885 continue;
886 }
887 return (int32_t)(head - buffer);
888 }
889 return -1;
890}
891
jackychen61b4d512015-04-21 15:30:11 -0700892void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200893 if (scale_)
894 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700895}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000896
jackychen6e2ce6e2015-07-13 16:26:33 -0700897int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200898 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -0700899}
900
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000901MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
902 JNIEnv* jni = AttachCurrentThreadIfNeeded();
903 ScopedLocalRefFrame local_ref_frame(jni);
904 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000905 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000906
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000907 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
908 j_encoder_class,
909 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
910 CHECK_EXCEPTION(jni);
911 if (is_vp8_hw_supported) {
912 ALOGD("VP8 HW Encoder supported.");
913 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
914 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
915 }
916
917 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
918 j_encoder_class,
919 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
920 CHECK_EXCEPTION(jni);
921 if (is_h264_hw_supported) {
922 ALOGD("H.264 HW Encoder supported.");
923 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
924 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
925 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000926}
927
928MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
929
930webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000931 VideoCodecType type) {
932 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000933 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000934 }
935 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
936 it != supported_codecs_.end(); ++it) {
937 if (it->type == type) {
938 ALOGD("Create HW video encoder for type %d (%s).",
939 (int)type, it->name.c_str());
940 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
941 }
942 }
943 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000944}
945
946const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
947MediaCodecVideoEncoderFactory::codecs() const {
948 return supported_codecs_;
949}
950
951void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
952 webrtc::VideoEncoder* encoder) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000953 ALOGD("Destroy video encoder.");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000954 delete encoder;
955}
956
957} // namespace webrtc_jni
958