blob: f6a3b650a6b8aaf481fa941e3bbb777a09dc84b6 [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;
309 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, true);
310 } else if (codecType_ == kVideoCodecH264) {
311 // H264 QP is in the range [0, 51].
312 const int kMaxQp = 51;
313 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, true);
314 } else {
315 // When adding codec support to additional hardware codecs, also configure
316 // their QP thresholds for scaling.
317 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
318 }
319 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
320 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700321 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000322 return codec_thread_->Invoke<int32_t>(
323 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
324 this,
325 codec_settings->width,
326 codec_settings->height,
327 codec_settings->startBitrate,
328 codec_settings->maxFramerate));
329}
330
331int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700332 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000333 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
334 const std::vector<webrtc::VideoFrameType>* frame_types) {
335 return codec_thread_->Invoke<int32_t>(Bind(
336 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
337}
338
339int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
340 webrtc::EncodedImageCallback* callback) {
341 return codec_thread_->Invoke<int32_t>(
342 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
343 this,
344 callback));
345}
346
347int32_t MediaCodecVideoEncoder::Release() {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000348 ALOGD("EncoderRelease request");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000349 return codec_thread_->Invoke<int32_t>(
350 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
351}
352
353int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
354 int64_t /* rtt */) {
355 return WEBRTC_VIDEO_CODEC_OK;
356}
357
358int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
359 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200360 if (scale_)
361 quality_scaler_.ReportFramerate(frame_rate);
362
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000363 return codec_thread_->Invoke<int32_t>(
364 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
365 this,
366 new_bit_rate,
367 frame_rate));
368}
369
370void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
371 JNIEnv* jni = AttachCurrentThreadIfNeeded();
372 ScopedLocalRefFrame local_ref_frame(jni);
373
374 // We only ever send one message to |this| directly (not through a Bind()'d
375 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700376 RTC_CHECK(!msg->message_id) << "Unexpected message!";
377 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000378 CheckOnCodecThread();
379 if (!inited_) {
380 return;
381 }
382
383 // It would be nice to recover from a failure here if one happened, but it's
384 // unclear how to signal such a failure to the app, so instead we stay silent
385 // about it and let the next app-called API method reveal the borkedness.
386 DeliverPendingOutputs(jni);
387 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
388}
389
390void MediaCodecVideoEncoder::CheckOnCodecThread() {
henrikg91d6ede2015-09-17 00:24:34 -0700391 RTC_CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000392 << "Running on wrong thread!";
393}
394
395void MediaCodecVideoEncoder::ResetCodec() {
396 ALOGE("ResetCodec");
397 if (Release() != WEBRTC_VIDEO_CODEC_OK ||
398 codec_thread_->Invoke<int32_t>(Bind(
399 &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this,
400 width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) {
401 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
402 // degrade to a SW encoder at this point? There isn't one AFAICT :(
403 // https://code.google.com/p/webrtc/issues/detail?id=2920
404 }
405}
406
407int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
408 int width, int height, int kbps, int fps) {
409 CheckOnCodecThread();
410 JNIEnv* jni = AttachCurrentThreadIfNeeded();
411 ScopedLocalRefFrame local_ref_frame(jni);
412
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000413 ALOGD("InitEncodeOnCodecThread Type: %d. %d x %d. Bitrate: %d kbps. Fps: %d",
414 (int)codecType_, width, height, kbps, fps);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000415 if (kbps == 0) {
416 kbps = last_set_bitrate_kbps_;
417 }
418 if (fps == 0) {
419 fps = last_set_fps_;
420 }
421
422 width_ = width;
423 height_ = height;
424 last_set_bitrate_kbps_ = kbps;
425 last_set_fps_ = fps;
426 yuv_size_ = width_ * height_ * 3 / 2;
427 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000428 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000429 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000430 frames_in_queue_ = 0;
431 current_timestamp_us_ = 0;
432 start_time_ms_ = GetCurrentTimeMs();
433 current_frames_ = 0;
434 current_bytes_ = 0;
435 current_encoding_time_ms_ = 0;
436 last_input_timestamp_ms_ = -1;
437 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000438 output_timestamp_ = 0;
439 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000440 timestamps_.clear();
441 render_times_ms_.clear();
442 frame_rtc_times_ms_.clear();
443 drop_next_input_frame_ = false;
444 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
445 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000446 jobject j_video_codec_enum = JavaEnumFromIndex(
447 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000448 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
449 jni->CallObjectMethod(*j_media_codec_video_encoder_,
450 j_init_encode_method_,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000451 j_video_codec_enum,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000452 width_,
453 height_,
454 kbps,
455 fps));
456 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000457 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000458 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000459 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000460
461 inited_ = true;
462 switch (GetIntField(jni, *j_media_codec_video_encoder_,
463 j_color_format_field_)) {
464 case COLOR_FormatYUV420Planar:
465 encoder_fourcc_ = libyuv::FOURCC_YU12;
466 break;
467 case COLOR_FormatYUV420SemiPlanar:
468 case COLOR_QCOM_FormatYUV420SemiPlanar:
469 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
470 encoder_fourcc_ = libyuv::FOURCC_NV12;
471 break;
472 default:
473 LOG(LS_ERROR) << "Wrong color format.";
474 return WEBRTC_VIDEO_CODEC_ERROR;
475 }
476 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
henrikg91d6ede2015-09-17 00:24:34 -0700477 RTC_CHECK(input_buffers_.empty())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000478 << "Unexpected double InitEncode without Release";
479 input_buffers_.resize(num_input_buffers);
480 for (size_t i = 0; i < num_input_buffers; ++i) {
481 input_buffers_[i] =
482 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
483 int64 yuv_buffer_capacity =
484 jni->GetDirectBufferCapacity(input_buffers_[i]);
485 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700486 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000487 }
488 CHECK_EXCEPTION(jni);
489
490 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
491 return WEBRTC_VIDEO_CODEC_OK;
492}
493
494int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700495 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000496 const std::vector<webrtc::VideoFrameType>* frame_types) {
497 CheckOnCodecThread();
498 JNIEnv* jni = AttachCurrentThreadIfNeeded();
499 ScopedLocalRefFrame local_ref_frame(jni);
500
501 if (!inited_) {
502 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
503 }
504 frames_received_++;
505 if (!DeliverPendingOutputs(jni)) {
506 ResetCodec();
507 // Continue as if everything's fine.
508 }
509
510 if (drop_next_input_frame_) {
511 ALOGV("Encoder drop frame - failed callback.");
512 drop_next_input_frame_ = false;
513 return WEBRTC_VIDEO_CODEC_OK;
514 }
515
henrikg91d6ede2015-09-17 00:24:34 -0700516 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen6e2ce6e2015-07-13 16:26:33 -0700517 // Check framerate before spatial resolution change.
Peter Boström2bc68c72015-09-24 16:22:28 +0200518 if (scale_)
519 quality_scaler_.OnEncodeFrame(frame);
520
521 const VideoFrame& input_frame =
522 scale_ ? quality_scaler_.GetScaledFrame(frame) : frame;
jackychen61b4d512015-04-21 15:30:11 -0700523
524 if (input_frame.width() != width_ || input_frame.height() != height_) {
525 ALOGD("Frame resolution change from %d x %d to %d x %d",
526 width_, height_, input_frame.width(), input_frame.height());
527 width_ = input_frame.width();
528 height_ = input_frame.height();
529 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000530 return WEBRTC_VIDEO_CODEC_OK;
531 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000532
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000533 // Check if we accumulated too many frames in encoder input buffers
534 // or the encoder latency exceeds 70 ms and drop frame if so.
535 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
536 int encoder_latency_ms = last_input_timestamp_ms_ -
537 last_output_timestamp_ms_;
538 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
539 ALOGD("Drop frame - encoder is behind by %d ms. Q size: %d",
540 encoder_latency_ms, frames_in_queue_);
541 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700542 // Report dropped frame to quality_scaler_.
543 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000544 return WEBRTC_VIDEO_CODEC_OK;
545 }
546 }
547
548 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
549 j_dequeue_input_buffer_method_);
550 CHECK_EXCEPTION(jni);
551 if (j_input_buffer_index == -1) {
552 // Video codec falls behind - no input buffer available.
553 ALOGV("Encoder drop frame - no input buffers available");
554 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700555 // Report dropped frame to quality_scaler_.
556 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000557 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
558 }
559 if (j_input_buffer_index == -2) {
560 ResetCodec();
561 return WEBRTC_VIDEO_CODEC_ERROR;
562 }
563
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000564 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
565 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000566
567 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
568 uint8* yuv_buffer =
569 reinterpret_cast<uint8*>(jni->GetDirectBufferAddress(j_input_buffer));
570 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700571 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
572 RTC_CHECK(!libyuv::ConvertFromI420(
573 input_frame.buffer(webrtc::kYPlane), input_frame.stride(webrtc::kYPlane),
574 input_frame.buffer(webrtc::kUPlane), input_frame.stride(webrtc::kUPlane),
575 input_frame.buffer(webrtc::kVPlane), input_frame.stride(webrtc::kVPlane),
576 yuv_buffer, width_, width_, height_, encoder_fourcc_))
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000577 << "ConvertFromI420 failed";
578 last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
579 frames_in_queue_++;
580
581 // Save input image timestamps for later output
jackychen61b4d512015-04-21 15:30:11 -0700582 timestamps_.push_back(input_frame.timestamp());
583 render_times_ms_.push_back(input_frame.render_time_ms());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000584 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
585
jackychen6e2ce6e2015-07-13 16:26:33 -0700586 bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000587 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
588 j_encode_method_,
589 key_frame,
590 j_input_buffer_index,
591 yuv_size_,
592 current_timestamp_us_);
593 CHECK_EXCEPTION(jni);
594 current_timestamp_us_ += 1000000 / last_set_fps_;
595
596 if (!encode_status || !DeliverPendingOutputs(jni)) {
597 ResetCodec();
598 return WEBRTC_VIDEO_CODEC_ERROR;
599 }
600
601 return WEBRTC_VIDEO_CODEC_OK;
602}
603
604int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
605 webrtc::EncodedImageCallback* callback) {
606 CheckOnCodecThread();
607 JNIEnv* jni = AttachCurrentThreadIfNeeded();
608 ScopedLocalRefFrame local_ref_frame(jni);
609 callback_ = callback;
610 return WEBRTC_VIDEO_CODEC_OK;
611}
612
613int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
614 if (!inited_) {
615 return WEBRTC_VIDEO_CODEC_OK;
616 }
617 CheckOnCodecThread();
618 JNIEnv* jni = AttachCurrentThreadIfNeeded();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000619 ALOGD("EncoderReleaseOnCodecThread: Frames received: %d. Encoded: %d. "
620 "Dropped: %d.", frames_received_, frames_encoded_, frames_dropped_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000621 ScopedLocalRefFrame local_ref_frame(jni);
622 for (size_t i = 0; i < input_buffers_.size(); ++i)
623 jni->DeleteGlobalRef(input_buffers_[i]);
624 input_buffers_.clear();
625 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
626 CHECK_EXCEPTION(jni);
627 rtc::MessageQueueManager::Clear(this);
628 inited_ = false;
629 return WEBRTC_VIDEO_CODEC_OK;
630}
631
632int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
633 uint32_t frame_rate) {
634 CheckOnCodecThread();
635 if (last_set_bitrate_kbps_ == new_bit_rate &&
636 last_set_fps_ == frame_rate) {
637 return WEBRTC_VIDEO_CODEC_OK;
638 }
639 JNIEnv* jni = AttachCurrentThreadIfNeeded();
640 ScopedLocalRefFrame local_ref_frame(jni);
641 if (new_bit_rate > 0) {
642 last_set_bitrate_kbps_ = new_bit_rate;
643 }
644 if (frame_rate > 0) {
645 last_set_fps_ = frame_rate;
646 }
647 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
648 j_set_rates_method_,
649 last_set_bitrate_kbps_,
650 last_set_fps_);
651 CHECK_EXCEPTION(jni);
652 if (!ret) {
653 ResetCodec();
654 return WEBRTC_VIDEO_CODEC_ERROR;
655 }
656 return WEBRTC_VIDEO_CODEC_OK;
657}
658
659int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
660 JNIEnv* jni,
661 jobject j_output_buffer_info) {
662 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
663}
664
665jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
666 JNIEnv* jni,
667 jobject j_output_buffer_info) {
668 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
669}
670
671bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
672 JNIEnv* jni,
673 jobject j_output_buffer_info) {
674 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
675}
676
677jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
678 JNIEnv* jni,
679 jobject j_output_buffer_info) {
680 return GetLongField(
681 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
682}
683
684bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
685 while (true) {
686 jobject j_output_buffer_info = jni->CallObjectMethod(
687 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
688 CHECK_EXCEPTION(jni);
689 if (IsNull(jni, j_output_buffer_info)) {
690 break;
691 }
692
693 int output_buffer_index =
694 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
695 if (output_buffer_index == -1) {
696 ResetCodec();
697 return false;
698 }
699
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000700 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000701 jobject j_output_buffer =
702 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
703 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000704
705 // Get frame timestamps from a queue - for non config frames only.
706 int64_t frame_encoding_time_ms = 0;
707 last_output_timestamp_ms_ =
708 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
709 1000;
710 if (frames_in_queue_ > 0) {
711 output_timestamp_ = timestamps_.front();
712 timestamps_.erase(timestamps_.begin());
713 output_render_time_ms_ = render_times_ms_.front();
714 render_times_ms_.erase(render_times_ms_.begin());
715 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
716 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
717 frames_in_queue_--;
718 }
719
720 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000721 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
722 uint8* payload = reinterpret_cast<uint8_t*>(
723 jni->GetDirectBufferAddress(j_output_buffer));
724 CHECK_EXCEPTION(jni);
725
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000726 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
727 " Latency: %lld. EncTime: %lld",
728 frames_encoded_, key_frame, payload_size,
729 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000730 last_input_timestamp_ms_ - last_output_timestamp_ms_,
731 frame_encoding_time_ms);
732
733 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000734 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000735 current_frames_++;
736 current_bytes_ += payload_size;
737 current_encoding_time_ms_ += frame_encoding_time_ms;
738 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
739 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
740 current_frames_ > 0) {
741 ALOGD("Encoder bitrate: %d, target: %d kbps, fps: %d,"
742 " encTime: %d for last %d ms",
743 current_bytes_ * 8 / statistic_time_ms,
744 last_set_bitrate_kbps_,
745 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms,
746 current_encoding_time_ms_ / current_frames_, statistic_time_ms);
747 start_time_ms_ = GetCurrentTimeMs();
748 current_frames_ = 0;
749 current_bytes_ = 0;
750 current_encoding_time_ms_ = 0;
751 }
752
753 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000754 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000755 if (callback_) {
756 scoped_ptr<webrtc::EncodedImage> image(
757 new webrtc::EncodedImage(payload, payload_size, payload_size));
758 image->_encodedWidth = width_;
759 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000760 image->_timeStamp = output_timestamp_;
761 image->capture_time_ms_ = output_render_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000762 image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
763 image->_completeFrame = true;
764
765 webrtc::CodecSpecificInfo info;
766 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000767 info.codecType = codecType_;
768 if (codecType_ == kVideoCodecVP8) {
769 info.codecSpecific.VP8.pictureId = picture_id_;
770 info.codecSpecific.VP8.nonReference = false;
771 info.codecSpecific.VP8.simulcastIdx = 0;
772 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
773 info.codecSpecific.VP8.layerSync = false;
774 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
775 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
776 picture_id_ = (picture_id_ + 1) & 0x7FFF;
777 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000778
779 // Generate a header describing a single fragment.
780 webrtc::RTPFragmentationHeader header;
781 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000782 if (codecType_ == kVideoCodecVP8) {
783 header.VerifyAndAllocateFragmentationHeader(1);
784 header.fragmentationOffset[0] = 0;
785 header.fragmentationLength[0] = image->_length;
786 header.fragmentationPlType[0] = 0;
787 header.fragmentationTimeDiff[0] = 0;
Peter Boström2bc68c72015-09-24 16:22:28 +0200788 if (scale_)
789 quality_scaler_.ReportQP(webrtc::vp8::GetQP(payload));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000790 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200791 if (scale_) {
792 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
793 int qp;
794 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
795 quality_scaler_.ReportQP(qp);
796 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000797 // For H.264 search for start codes.
798 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
799 int32_t scPositionsLength = 0;
800 int32_t scPosition = 0;
801 while (scPositionsLength < MAX_NALUS_PERFRAME) {
802 int32_t naluPosition = NextNaluPosition(
803 payload + scPosition, payload_size - scPosition);
804 if (naluPosition < 0) {
805 break;
806 }
807 scPosition += naluPosition;
808 scPositions[scPositionsLength++] = scPosition;
809 scPosition += H264_SC_LENGTH;
810 }
811 if (scPositionsLength == 0) {
812 ALOGE("Start code is not found!");
813 ALOGE("Data 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
814 image->_buffer[0], image->_buffer[1], image->_buffer[2],
815 image->_buffer[3], image->_buffer[4], image->_buffer[5]);
816 ResetCodec();
817 return false;
818 }
819 scPositions[scPositionsLength] = payload_size;
820 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
821 for (size_t i = 0; i < scPositionsLength; i++) {
822 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
823 header.fragmentationLength[i] =
824 scPositions[i + 1] - header.fragmentationOffset[i];
825 header.fragmentationPlType[i] = 0;
826 header.fragmentationTimeDiff[i] = 0;
827 }
828 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000829
830 callback_status = callback_->Encoded(*image, &info, &header);
831 }
832
833 // Return output buffer back to the encoder.
834 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
835 j_release_output_buffer_method_,
836 output_buffer_index);
837 CHECK_EXCEPTION(jni);
838 if (!success) {
839 ResetCodec();
840 return false;
841 }
842
843 if (callback_status > 0) {
844 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000845 // Theoretically could handle callback_status<0 here, but unclear what
846 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000847 }
848 }
849
850 return true;
851}
852
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000853int32_t MediaCodecVideoEncoder::NextNaluPosition(
854 uint8_t *buffer, size_t buffer_size) {
855 if (buffer_size < H264_SC_LENGTH) {
856 return -1;
857 }
858 uint8_t *head = buffer;
859 // Set end buffer pointer to 4 bytes before actual buffer end so we can
860 // access head[1], head[2] and head[3] in a loop without buffer overrun.
861 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
862
863 while (head < end) {
864 if (head[0]) {
865 head++;
866 continue;
867 }
868 if (head[1]) { // got 00xx
869 head += 2;
870 continue;
871 }
872 if (head[2]) { // got 0000xx
873 head += 3;
874 continue;
875 }
876 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000877 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000878 continue;
879 }
880 return (int32_t)(head - buffer);
881 }
882 return -1;
883}
884
jackychen61b4d512015-04-21 15:30:11 -0700885void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200886 if (scale_)
887 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700888}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000889
jackychen6e2ce6e2015-07-13 16:26:33 -0700890int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200891 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -0700892}
893
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000894MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
895 JNIEnv* jni = AttachCurrentThreadIfNeeded();
896 ScopedLocalRefFrame local_ref_frame(jni);
897 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000898 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000899
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000900 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
901 j_encoder_class,
902 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
903 CHECK_EXCEPTION(jni);
904 if (is_vp8_hw_supported) {
905 ALOGD("VP8 HW Encoder supported.");
906 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
907 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
908 }
909
910 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
911 j_encoder_class,
912 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
913 CHECK_EXCEPTION(jni);
914 if (is_h264_hw_supported) {
915 ALOGD("H.264 HW Encoder supported.");
916 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
917 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
918 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000919}
920
921MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
922
923webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000924 VideoCodecType type) {
925 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000926 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000927 }
928 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
929 it != supported_codecs_.end(); ++it) {
930 if (it->type == type) {
931 ALOGD("Create HW video encoder for type %d (%s).",
932 (int)type, it->name.c_str());
933 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
934 }
935 }
936 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000937}
938
939const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
940MediaCodecVideoEncoderFactory::codecs() const {
941 return supported_codecs_;
942}
943
944void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
945 webrtc::VideoEncoder* encoder) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000946 ALOGD("Destroy video encoder.");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000947 delete encoder;
948}
949
950} // namespace webrtc_jni
951