blob: bd9456291f25bc239a7fa56c9b8c9b17d15b50fa [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"
36#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
jackychen61b4d512015-04-21 15:30:11 -070037#include "webrtc/modules/video_coding/utility/include/quality_scaler.h"
jackychen98d8cf52015-05-21 11:12:02 -070038#include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000039#include "webrtc/system_wrappers/interface/logcat_trace_context.h"
40#include "third_party/libyuv/include/libyuv/convert.h"
41#include "third_party/libyuv/include/libyuv/convert_from.h"
42#include "third_party/libyuv/include/libyuv/video_common.h"
43
44using rtc::Bind;
45using rtc::Thread;
46using rtc::ThreadManager;
47using rtc::scoped_ptr;
48
49using webrtc::CodecSpecificInfo;
50using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070051using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000052using webrtc::RTPFragmentationHeader;
53using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000054using webrtc::VideoCodecType;
55using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000056using webrtc::kVideoCodecVP8;
57
58namespace webrtc_jni {
59
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000060// H.264 start code length.
61#define H264_SC_LENGTH 4
62// Maximum allowed NALUs in one output frame.
63#define MAX_NALUS_PERFRAME 32
64// Maximum supported HW video encoder resolution.
65#define MAX_VIDEO_WIDTH 1280
66#define MAX_VIDEO_HEIGHT 1280
67// Maximum supported HW video encoder fps.
68#define MAX_VIDEO_FPS 30
69
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000070// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
71// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
72// HW-backed video encode. This C++ class is implemented as a very thin shim,
73// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
74// MediaCodecVideoEncoder is created, operated, and destroyed on a single
75// thread, currently the libjingle Worker thread.
76class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
77 public rtc::MessageHandler {
78 public:
79 virtual ~MediaCodecVideoEncoder();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000080 explicit MediaCodecVideoEncoder(JNIEnv* jni, VideoCodecType codecType);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000081
82 // webrtc::VideoEncoder implementation. Everything trampolines to
83 // |codec_thread_| for execution.
84 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
85 int32_t /* number_of_cores */,
86 size_t /* max_payload_size */) override;
87 int32_t Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070088 const webrtc::VideoFrame& input_image,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000089 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
90 const std::vector<webrtc::VideoFrameType>* frame_types) override;
91 int32_t RegisterEncodeCompleteCallback(
92 webrtc::EncodedImageCallback* callback) override;
93 int32_t Release() override;
94 int32_t SetChannelParameters(uint32_t /* packet_loss */,
95 int64_t /* rtt */) override;
96 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
97
98 // rtc::MessageHandler implementation.
99 void OnMessage(rtc::Message* msg) override;
100
jackychen61b4d512015-04-21 15:30:11 -0700101 void OnDroppedFrame() override;
102
jackychen6e2ce6e2015-07-13 16:26:33 -0700103 int GetTargetFramerate() override;
104
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000105 private:
106 // CHECK-fail if not running on |codec_thread_|.
107 void CheckOnCodecThread();
108
109 // Release() and InitEncode() in an attempt to restore the codec to an
110 // operable state. Necessary after all manner of OMX-layer errors.
111 void ResetCodec();
112
113 // Implementation of webrtc::VideoEncoder methods above, all running on the
114 // codec thread exclusively.
115 //
116 // If width==0 then this is assumed to be a re-initialization and the
117 // previously-current values are reused instead of the passed parameters
118 // (makes it easier to reason about thread-safety).
119 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps);
120 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700121 const webrtc::VideoFrame& input_image,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000122 const std::vector<webrtc::VideoFrameType>* frame_types);
123 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
124 webrtc::EncodedImageCallback* callback);
125 int32_t ReleaseOnCodecThread();
126 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
127
128 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
129 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
130 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
131 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
132 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000133 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000134
135 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
136 // true on success.
137 bool DeliverPendingOutputs(JNIEnv* jni);
138
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000139 // Search for H.264 start codes.
140 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
141
142 // Type of video codec.
143 VideoCodecType codecType_;
144
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000145 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
146 // |codec_thread_| synchronously.
147 webrtc::EncodedImageCallback* callback_;
148
149 // State that is constant for the lifetime of this object once the ctor
150 // returns.
151 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
152 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
153 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
154 jmethodID j_init_encode_method_;
155 jmethodID j_dequeue_input_buffer_method_;
156 jmethodID j_encode_method_;
157 jmethodID j_release_method_;
158 jmethodID j_set_rates_method_;
159 jmethodID j_dequeue_output_buffer_method_;
160 jmethodID j_release_output_buffer_method_;
161 jfieldID j_color_format_field_;
162 jfieldID j_info_index_field_;
163 jfieldID j_info_buffer_field_;
164 jfieldID j_info_is_key_frame_field_;
165 jfieldID j_info_presentation_timestamp_us_field_;
166
167 // State that is valid only between InitEncode() and the next Release().
168 // Touched only on codec_thread_ so no explicit synchronization necessary.
169 int width_; // Frame width in pixels.
170 int height_; // Frame height in pixels.
171 bool inited_;
172 uint16_t picture_id_;
173 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
174 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
175 int last_set_fps_; // Last-requested frame rate.
176 int64_t current_timestamp_us_; // Current frame timestamps in us.
177 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000178 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000179 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000180 int frames_in_queue_; // Number of frames in encoder queue.
181 int64_t start_time_ms_; // Start time for statistics.
182 int current_frames_; // Number of frames in the current statistics interval.
183 int current_bytes_; // Encoded bytes in the current statistics interval.
184 int current_encoding_time_ms_; // Overall encoding time in the current second
185 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
186 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
187 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
188 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
189 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
190 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000191 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
192 int64_t output_render_time_ms_; // Last output frame render time from
193 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000194 // Frame size in bytes fed to MediaCodec.
195 int yuv_size_;
196 // True only when between a callback_->Encoded() call return a positive value
197 // and the next Encode() call being ignored.
198 bool drop_next_input_frame_;
199 // Global references; must be deleted in Release().
200 std::vector<jobject> input_buffers_;
jackychen61b4d512015-04-21 15:30:11 -0700201 scoped_ptr<webrtc::QualityScaler> quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700202 // Dynamic resolution change, off by default.
203 bool scale_;
jackychen6e2ce6e2015-07-13 16:26:33 -0700204 int updated_framerate_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000205};
206
207MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
208 // Call Release() to ensure no more callbacks to us after we are deleted.
209 Release();
210}
211
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000212MediaCodecVideoEncoder::MediaCodecVideoEncoder(
213 JNIEnv* jni, VideoCodecType codecType) :
214 codecType_(codecType),
215 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000216 inited_(false),
217 picture_id_(0),
218 codec_thread_(new Thread()),
jackychen61b4d512015-04-21 15:30:11 -0700219 quality_scaler_(new webrtc::QualityScaler()),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000220 j_media_codec_video_encoder_class_(
221 jni,
222 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
223 j_media_codec_video_encoder_(
224 jni,
225 jni->NewObject(*j_media_codec_video_encoder_class_,
226 GetMethodID(jni,
227 *j_media_codec_video_encoder_class_,
228 "<init>",
229 "()V"))) {
230 ScopedLocalRefFrame local_ref_frame(jni);
231 // It would be nice to avoid spinning up a new thread per MediaCodec, and
232 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
233 // 2732 means that deadlocks abound. This class synchronously trampolines
234 // to |codec_thread_|, so if anything else can be coming to _us_ from
235 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
236 // in the bug, we have a problem. For now work around that with a dedicated
237 // thread.
238 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700239 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000240
241 jclass j_output_buffer_info_class =
242 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000243 j_init_encode_method_ = GetMethodID(
244 jni,
245 *j_media_codec_video_encoder_class_,
246 "initEncode",
247 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)"
248 "[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000249 j_dequeue_input_buffer_method_ = GetMethodID(
250 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
251 j_encode_method_ = GetMethodID(
252 jni, *j_media_codec_video_encoder_class_, "encode", "(ZIIJ)Z");
253 j_release_method_ =
254 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
255 j_set_rates_method_ = GetMethodID(
256 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000257 j_dequeue_output_buffer_method_ = GetMethodID(
258 jni,
259 *j_media_codec_video_encoder_class_,
260 "dequeueOutputBuffer",
261 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000262 j_release_output_buffer_method_ = GetMethodID(
263 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
264
265 j_color_format_field_ =
266 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
267 j_info_index_field_ =
268 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
269 j_info_buffer_field_ = GetFieldID(
270 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
271 j_info_is_key_frame_field_ =
272 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
273 j_info_presentation_timestamp_us_field_ = GetFieldID(
274 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
275 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
276 AllowBlockingCalls();
277}
278
279int32_t MediaCodecVideoEncoder::InitEncode(
280 const webrtc::VideoCodec* codec_settings,
281 int32_t /* number_of_cores */,
282 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700283 const int kMinWidth = 320;
284 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700285 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
286 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
287 // always = 127. Note that in SW, QP is that of the user-level range [0, 63].
288 const int kMaxQP = 127;
289 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000290 if (codec_settings == NULL) {
291 ALOGE("NULL VideoCodec instance");
292 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
293 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000294 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700295 RTC_CHECK(codec_settings->codecType == codecType_)
296 << "Unsupported codec " << codec_settings->codecType << " for "
297 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000298
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000299 ALOGD("InitEncode request");
jackychen61b4d512015-04-21 15:30:11 -0700300 scale_ = false;
jackychen6e2ce6e2015-07-13 16:26:33 -0700301 if (scale_ && codecType_ == kVideoCodecVP8) {
302 quality_scaler_->Init(kMaxQP / kLowQpThresholdDenominator, true);
jackychen98d8cf52015-05-21 11:12:02 -0700303 quality_scaler_->SetMinResolution(kMinWidth, kMinHeight);
304 quality_scaler_->ReportFramerate(codec_settings->maxFramerate);
jackychene2b34b72015-07-24 14:12:24 -0700305 updated_framerate_ = codec_settings->maxFramerate;
306 } else {
307 updated_framerate_ = -1;
jackychen61b4d512015-04-21 15:30:11 -0700308 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000309 return codec_thread_->Invoke<int32_t>(
310 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
311 this,
312 codec_settings->width,
313 codec_settings->height,
314 codec_settings->startBitrate,
315 codec_settings->maxFramerate));
316}
317
318int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700319 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000320 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
321 const std::vector<webrtc::VideoFrameType>* frame_types) {
322 return codec_thread_->Invoke<int32_t>(Bind(
323 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
324}
325
326int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
327 webrtc::EncodedImageCallback* callback) {
328 return codec_thread_->Invoke<int32_t>(
329 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
330 this,
331 callback));
332}
333
334int32_t MediaCodecVideoEncoder::Release() {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000335 ALOGD("EncoderRelease request");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000336 return codec_thread_->Invoke<int32_t>(
337 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
338}
339
340int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
341 int64_t /* rtt */) {
342 return WEBRTC_VIDEO_CODEC_OK;
343}
344
345int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
346 uint32_t frame_rate) {
jackychen6e2ce6e2015-07-13 16:26:33 -0700347 if (scale_ && codecType_ == kVideoCodecVP8) {
jackychen98d8cf52015-05-21 11:12:02 -0700348 quality_scaler_->ReportFramerate(frame_rate);
jackychen6e2ce6e2015-07-13 16:26:33 -0700349 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000350 return codec_thread_->Invoke<int32_t>(
351 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
352 this,
353 new_bit_rate,
354 frame_rate));
355}
356
357void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
358 JNIEnv* jni = AttachCurrentThreadIfNeeded();
359 ScopedLocalRefFrame local_ref_frame(jni);
360
361 // We only ever send one message to |this| directly (not through a Bind()'d
362 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700363 RTC_CHECK(!msg->message_id) << "Unexpected message!";
364 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000365 CheckOnCodecThread();
366 if (!inited_) {
367 return;
368 }
369
370 // It would be nice to recover from a failure here if one happened, but it's
371 // unclear how to signal such a failure to the app, so instead we stay silent
372 // about it and let the next app-called API method reveal the borkedness.
373 DeliverPendingOutputs(jni);
374 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
375}
376
377void MediaCodecVideoEncoder::CheckOnCodecThread() {
henrikg91d6ede2015-09-17 00:24:34 -0700378 RTC_CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000379 << "Running on wrong thread!";
380}
381
382void MediaCodecVideoEncoder::ResetCodec() {
383 ALOGE("ResetCodec");
384 if (Release() != WEBRTC_VIDEO_CODEC_OK ||
385 codec_thread_->Invoke<int32_t>(Bind(
386 &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this,
387 width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) {
388 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
389 // degrade to a SW encoder at this point? There isn't one AFAICT :(
390 // https://code.google.com/p/webrtc/issues/detail?id=2920
391 }
392}
393
394int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
395 int width, int height, int kbps, int fps) {
396 CheckOnCodecThread();
397 JNIEnv* jni = AttachCurrentThreadIfNeeded();
398 ScopedLocalRefFrame local_ref_frame(jni);
399
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000400 ALOGD("InitEncodeOnCodecThread Type: %d. %d x %d. Bitrate: %d kbps. Fps: %d",
401 (int)codecType_, width, height, kbps, fps);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000402 if (kbps == 0) {
403 kbps = last_set_bitrate_kbps_;
404 }
405 if (fps == 0) {
406 fps = last_set_fps_;
407 }
408
409 width_ = width;
410 height_ = height;
411 last_set_bitrate_kbps_ = kbps;
412 last_set_fps_ = fps;
413 yuv_size_ = width_ * height_ * 3 / 2;
414 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000415 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000416 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000417 frames_in_queue_ = 0;
418 current_timestamp_us_ = 0;
419 start_time_ms_ = GetCurrentTimeMs();
420 current_frames_ = 0;
421 current_bytes_ = 0;
422 current_encoding_time_ms_ = 0;
423 last_input_timestamp_ms_ = -1;
424 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000425 output_timestamp_ = 0;
426 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000427 timestamps_.clear();
428 render_times_ms_.clear();
429 frame_rtc_times_ms_.clear();
430 drop_next_input_frame_ = false;
431 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
432 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000433 jobject j_video_codec_enum = JavaEnumFromIndex(
434 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000435 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
436 jni->CallObjectMethod(*j_media_codec_video_encoder_,
437 j_init_encode_method_,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000438 j_video_codec_enum,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000439 width_,
440 height_,
441 kbps,
442 fps));
443 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000444 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000445 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000446 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000447
448 inited_ = true;
449 switch (GetIntField(jni, *j_media_codec_video_encoder_,
450 j_color_format_field_)) {
451 case COLOR_FormatYUV420Planar:
452 encoder_fourcc_ = libyuv::FOURCC_YU12;
453 break;
454 case COLOR_FormatYUV420SemiPlanar:
455 case COLOR_QCOM_FormatYUV420SemiPlanar:
456 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
457 encoder_fourcc_ = libyuv::FOURCC_NV12;
458 break;
459 default:
460 LOG(LS_ERROR) << "Wrong color format.";
461 return WEBRTC_VIDEO_CODEC_ERROR;
462 }
463 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
henrikg91d6ede2015-09-17 00:24:34 -0700464 RTC_CHECK(input_buffers_.empty())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000465 << "Unexpected double InitEncode without Release";
466 input_buffers_.resize(num_input_buffers);
467 for (size_t i = 0; i < num_input_buffers; ++i) {
468 input_buffers_[i] =
469 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
470 int64 yuv_buffer_capacity =
471 jni->GetDirectBufferCapacity(input_buffers_[i]);
472 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700473 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000474 }
475 CHECK_EXCEPTION(jni);
476
477 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
478 return WEBRTC_VIDEO_CODEC_OK;
479}
480
481int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700482 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000483 const std::vector<webrtc::VideoFrameType>* frame_types) {
484 CheckOnCodecThread();
485 JNIEnv* jni = AttachCurrentThreadIfNeeded();
486 ScopedLocalRefFrame local_ref_frame(jni);
487
488 if (!inited_) {
489 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
490 }
491 frames_received_++;
492 if (!DeliverPendingOutputs(jni)) {
493 ResetCodec();
494 // Continue as if everything's fine.
495 }
496
497 if (drop_next_input_frame_) {
498 ALOGV("Encoder drop frame - failed callback.");
499 drop_next_input_frame_ = false;
500 return WEBRTC_VIDEO_CODEC_OK;
501 }
502
henrikg91d6ede2015-09-17 00:24:34 -0700503 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen6e2ce6e2015-07-13 16:26:33 -0700504 // Check framerate before spatial resolution change.
505 if (scale_ && codecType_ == kVideoCodecVP8) {
506 quality_scaler_->OnEncodeFrame(frame);
507 updated_framerate_ = quality_scaler_->GetTargetFramerate();
508 }
509 const VideoFrame& input_frame = (scale_ && codecType_ == kVideoCodecVP8) ?
510 quality_scaler_->GetScaledFrame(frame) : frame;
jackychen61b4d512015-04-21 15:30:11 -0700511
512 if (input_frame.width() != width_ || input_frame.height() != height_) {
513 ALOGD("Frame resolution change from %d x %d to %d x %d",
514 width_, height_, input_frame.width(), input_frame.height());
515 width_ = input_frame.width();
516 height_ = input_frame.height();
517 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000518 return WEBRTC_VIDEO_CODEC_OK;
519 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000520
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 // Check if we accumulated too many frames in encoder input buffers
522 // or the encoder latency exceeds 70 ms and drop frame if so.
523 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
524 int encoder_latency_ms = last_input_timestamp_ms_ -
525 last_output_timestamp_ms_;
526 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
527 ALOGD("Drop frame - encoder is behind by %d ms. Q size: %d",
528 encoder_latency_ms, frames_in_queue_);
529 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700530 // Report dropped frame to quality_scaler_.
531 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000532 return WEBRTC_VIDEO_CODEC_OK;
533 }
534 }
535
536 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
537 j_dequeue_input_buffer_method_);
538 CHECK_EXCEPTION(jni);
539 if (j_input_buffer_index == -1) {
540 // Video codec falls behind - no input buffer available.
541 ALOGV("Encoder drop frame - no input buffers available");
542 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700543 // Report dropped frame to quality_scaler_.
544 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000545 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
546 }
547 if (j_input_buffer_index == -2) {
548 ResetCodec();
549 return WEBRTC_VIDEO_CODEC_ERROR;
550 }
551
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000552 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
553 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000554
555 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
556 uint8* yuv_buffer =
557 reinterpret_cast<uint8*>(jni->GetDirectBufferAddress(j_input_buffer));
558 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700559 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
560 RTC_CHECK(!libyuv::ConvertFromI420(
561 input_frame.buffer(webrtc::kYPlane), input_frame.stride(webrtc::kYPlane),
562 input_frame.buffer(webrtc::kUPlane), input_frame.stride(webrtc::kUPlane),
563 input_frame.buffer(webrtc::kVPlane), input_frame.stride(webrtc::kVPlane),
564 yuv_buffer, width_, width_, height_, encoder_fourcc_))
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000565 << "ConvertFromI420 failed";
566 last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
567 frames_in_queue_++;
568
569 // Save input image timestamps for later output
jackychen61b4d512015-04-21 15:30:11 -0700570 timestamps_.push_back(input_frame.timestamp());
571 render_times_ms_.push_back(input_frame.render_time_ms());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000572 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
573
jackychen6e2ce6e2015-07-13 16:26:33 -0700574 bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000575 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
576 j_encode_method_,
577 key_frame,
578 j_input_buffer_index,
579 yuv_size_,
580 current_timestamp_us_);
581 CHECK_EXCEPTION(jni);
582 current_timestamp_us_ += 1000000 / last_set_fps_;
583
584 if (!encode_status || !DeliverPendingOutputs(jni)) {
585 ResetCodec();
586 return WEBRTC_VIDEO_CODEC_ERROR;
587 }
588
589 return WEBRTC_VIDEO_CODEC_OK;
590}
591
592int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
593 webrtc::EncodedImageCallback* callback) {
594 CheckOnCodecThread();
595 JNIEnv* jni = AttachCurrentThreadIfNeeded();
596 ScopedLocalRefFrame local_ref_frame(jni);
597 callback_ = callback;
598 return WEBRTC_VIDEO_CODEC_OK;
599}
600
601int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
602 if (!inited_) {
603 return WEBRTC_VIDEO_CODEC_OK;
604 }
605 CheckOnCodecThread();
606 JNIEnv* jni = AttachCurrentThreadIfNeeded();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000607 ALOGD("EncoderReleaseOnCodecThread: Frames received: %d. Encoded: %d. "
608 "Dropped: %d.", frames_received_, frames_encoded_, frames_dropped_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000609 ScopedLocalRefFrame local_ref_frame(jni);
610 for (size_t i = 0; i < input_buffers_.size(); ++i)
611 jni->DeleteGlobalRef(input_buffers_[i]);
612 input_buffers_.clear();
613 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
614 CHECK_EXCEPTION(jni);
615 rtc::MessageQueueManager::Clear(this);
616 inited_ = false;
617 return WEBRTC_VIDEO_CODEC_OK;
618}
619
620int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
621 uint32_t frame_rate) {
622 CheckOnCodecThread();
623 if (last_set_bitrate_kbps_ == new_bit_rate &&
624 last_set_fps_ == frame_rate) {
625 return WEBRTC_VIDEO_CODEC_OK;
626 }
627 JNIEnv* jni = AttachCurrentThreadIfNeeded();
628 ScopedLocalRefFrame local_ref_frame(jni);
629 if (new_bit_rate > 0) {
630 last_set_bitrate_kbps_ = new_bit_rate;
631 }
632 if (frame_rate > 0) {
633 last_set_fps_ = frame_rate;
634 }
635 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
636 j_set_rates_method_,
637 last_set_bitrate_kbps_,
638 last_set_fps_);
639 CHECK_EXCEPTION(jni);
640 if (!ret) {
641 ResetCodec();
642 return WEBRTC_VIDEO_CODEC_ERROR;
643 }
644 return WEBRTC_VIDEO_CODEC_OK;
645}
646
647int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
648 JNIEnv* jni,
649 jobject j_output_buffer_info) {
650 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
651}
652
653jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
654 JNIEnv* jni,
655 jobject j_output_buffer_info) {
656 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
657}
658
659bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
660 JNIEnv* jni,
661 jobject j_output_buffer_info) {
662 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
663}
664
665jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
666 JNIEnv* jni,
667 jobject j_output_buffer_info) {
668 return GetLongField(
669 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
670}
671
672bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
673 while (true) {
674 jobject j_output_buffer_info = jni->CallObjectMethod(
675 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
676 CHECK_EXCEPTION(jni);
677 if (IsNull(jni, j_output_buffer_info)) {
678 break;
679 }
680
681 int output_buffer_index =
682 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
683 if (output_buffer_index == -1) {
684 ResetCodec();
685 return false;
686 }
687
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000688 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000689 jobject j_output_buffer =
690 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
691 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000692
693 // Get frame timestamps from a queue - for non config frames only.
694 int64_t frame_encoding_time_ms = 0;
695 last_output_timestamp_ms_ =
696 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
697 1000;
698 if (frames_in_queue_ > 0) {
699 output_timestamp_ = timestamps_.front();
700 timestamps_.erase(timestamps_.begin());
701 output_render_time_ms_ = render_times_ms_.front();
702 render_times_ms_.erase(render_times_ms_.begin());
703 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
704 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
705 frames_in_queue_--;
706 }
707
708 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000709 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
710 uint8* payload = reinterpret_cast<uint8_t*>(
711 jni->GetDirectBufferAddress(j_output_buffer));
712 CHECK_EXCEPTION(jni);
713
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000714 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
715 " Latency: %lld. EncTime: %lld",
716 frames_encoded_, key_frame, payload_size,
717 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000718 last_input_timestamp_ms_ - last_output_timestamp_ms_,
719 frame_encoding_time_ms);
720
jackychen6e2ce6e2015-07-13 16:26:33 -0700721 if (payload_size && scale_ && codecType_ == kVideoCodecVP8)
jackychen98d8cf52015-05-21 11:12:02 -0700722 quality_scaler_->ReportQP(webrtc::vp8::GetQP(payload));
jackychen61b4d512015-04-21 15:30:11 -0700723
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000724 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000725 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000726 current_frames_++;
727 current_bytes_ += payload_size;
728 current_encoding_time_ms_ += frame_encoding_time_ms;
729 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
730 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
731 current_frames_ > 0) {
732 ALOGD("Encoder bitrate: %d, target: %d kbps, fps: %d,"
733 " encTime: %d for last %d ms",
734 current_bytes_ * 8 / statistic_time_ms,
735 last_set_bitrate_kbps_,
736 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms,
737 current_encoding_time_ms_ / current_frames_, statistic_time_ms);
738 start_time_ms_ = GetCurrentTimeMs();
739 current_frames_ = 0;
740 current_bytes_ = 0;
741 current_encoding_time_ms_ = 0;
742 }
743
744 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000745 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000746 if (callback_) {
747 scoped_ptr<webrtc::EncodedImage> image(
748 new webrtc::EncodedImage(payload, payload_size, payload_size));
749 image->_encodedWidth = width_;
750 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000751 image->_timeStamp = output_timestamp_;
752 image->capture_time_ms_ = output_render_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000753 image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
754 image->_completeFrame = true;
755
756 webrtc::CodecSpecificInfo info;
757 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000758 info.codecType = codecType_;
759 if (codecType_ == kVideoCodecVP8) {
760 info.codecSpecific.VP8.pictureId = picture_id_;
761 info.codecSpecific.VP8.nonReference = false;
762 info.codecSpecific.VP8.simulcastIdx = 0;
763 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
764 info.codecSpecific.VP8.layerSync = false;
765 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
766 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
767 picture_id_ = (picture_id_ + 1) & 0x7FFF;
768 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000769
770 // Generate a header describing a single fragment.
771 webrtc::RTPFragmentationHeader header;
772 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000773 if (codecType_ == kVideoCodecVP8) {
774 header.VerifyAndAllocateFragmentationHeader(1);
775 header.fragmentationOffset[0] = 0;
776 header.fragmentationLength[0] = image->_length;
777 header.fragmentationPlType[0] = 0;
778 header.fragmentationTimeDiff[0] = 0;
779 } else if (codecType_ == kVideoCodecH264) {
780 // For H.264 search for start codes.
781 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
782 int32_t scPositionsLength = 0;
783 int32_t scPosition = 0;
784 while (scPositionsLength < MAX_NALUS_PERFRAME) {
785 int32_t naluPosition = NextNaluPosition(
786 payload + scPosition, payload_size - scPosition);
787 if (naluPosition < 0) {
788 break;
789 }
790 scPosition += naluPosition;
791 scPositions[scPositionsLength++] = scPosition;
792 scPosition += H264_SC_LENGTH;
793 }
794 if (scPositionsLength == 0) {
795 ALOGE("Start code is not found!");
796 ALOGE("Data 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
797 image->_buffer[0], image->_buffer[1], image->_buffer[2],
798 image->_buffer[3], image->_buffer[4], image->_buffer[5]);
799 ResetCodec();
800 return false;
801 }
802 scPositions[scPositionsLength] = payload_size;
803 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
804 for (size_t i = 0; i < scPositionsLength; i++) {
805 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
806 header.fragmentationLength[i] =
807 scPositions[i + 1] - header.fragmentationOffset[i];
808 header.fragmentationPlType[i] = 0;
809 header.fragmentationTimeDiff[i] = 0;
810 }
811 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000812
813 callback_status = callback_->Encoded(*image, &info, &header);
814 }
815
816 // Return output buffer back to the encoder.
817 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
818 j_release_output_buffer_method_,
819 output_buffer_index);
820 CHECK_EXCEPTION(jni);
821 if (!success) {
822 ResetCodec();
823 return false;
824 }
825
826 if (callback_status > 0) {
827 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000828 // Theoretically could handle callback_status<0 here, but unclear what
829 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000830 }
831 }
832
833 return true;
834}
835
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000836int32_t MediaCodecVideoEncoder::NextNaluPosition(
837 uint8_t *buffer, size_t buffer_size) {
838 if (buffer_size < H264_SC_LENGTH) {
839 return -1;
840 }
841 uint8_t *head = buffer;
842 // Set end buffer pointer to 4 bytes before actual buffer end so we can
843 // access head[1], head[2] and head[3] in a loop without buffer overrun.
844 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
845
846 while (head < end) {
847 if (head[0]) {
848 head++;
849 continue;
850 }
851 if (head[1]) { // got 00xx
852 head += 2;
853 continue;
854 }
855 if (head[2]) { // got 0000xx
856 head += 3;
857 continue;
858 }
859 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000860 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000861 continue;
862 }
863 return (int32_t)(head - buffer);
864 }
865 return -1;
866}
867
jackychen61b4d512015-04-21 15:30:11 -0700868void MediaCodecVideoEncoder::OnDroppedFrame() {
jackychen6e2ce6e2015-07-13 16:26:33 -0700869 if (scale_ && codecType_ == kVideoCodecVP8)
jackychen98d8cf52015-05-21 11:12:02 -0700870 quality_scaler_->ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700871}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000872
jackychen6e2ce6e2015-07-13 16:26:33 -0700873int MediaCodecVideoEncoder::GetTargetFramerate() {
874 return updated_framerate_;
875}
876
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000877MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
878 JNIEnv* jni = AttachCurrentThreadIfNeeded();
879 ScopedLocalRefFrame local_ref_frame(jni);
880 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000881 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000882
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000883 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
884 j_encoder_class,
885 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
886 CHECK_EXCEPTION(jni);
887 if (is_vp8_hw_supported) {
888 ALOGD("VP8 HW Encoder supported.");
889 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
890 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
891 }
892
893 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
894 j_encoder_class,
895 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
896 CHECK_EXCEPTION(jni);
897 if (is_h264_hw_supported) {
898 ALOGD("H.264 HW Encoder supported.");
899 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
900 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
901 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000902}
903
904MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
905
906webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000907 VideoCodecType type) {
908 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000909 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000910 }
911 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
912 it != supported_codecs_.end(); ++it) {
913 if (it->type == type) {
914 ALOGD("Create HW video encoder for type %d (%s).",
915 (int)type, it->name.c_str());
916 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
917 }
918 }
919 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000920}
921
922const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
923MediaCodecVideoEncoderFactory::codecs() const {
924 return supported_codecs_;
925}
926
927void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
928 webrtc::VideoEncoder* encoder) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000929 ALOGD("Destroy video encoder.");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000930 delete encoder;
931}
932
933} // namespace webrtc_jni
934