blob: 76a675d97643af2408cf665dca4b238ed0a631a6 [file] [log] [blame]
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001/*
2 * libjingle
3 * Copyright 2015 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 *
27 */
28
29#include "talk/app/webrtc/java/jni/androidmediaencoder_jni.h"
30#include "talk/app/webrtc/java/jni/classreferenceholder.h"
31#include "talk/app/webrtc/java/jni/androidmediacodeccommon.h"
32#include "webrtc/base/bind.h"
33#include "webrtc/base/checks.h"
34#include "webrtc/base/logging.h"
35#include "webrtc/base/thread.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020036#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000037#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
jackychen61b4d512015-04-21 15:30:11 -070038#include "webrtc/modules/video_coding/utility/include/quality_scaler.h"
jackychen98d8cf52015-05-21 11:12:02 -070039#include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h"
asaperssonef5d5e42015-09-22 01:40:42 -070040#include "webrtc/system_wrappers/interface/field_trial.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000041#include "webrtc/system_wrappers/interface/logcat_trace_context.h"
42#include "third_party/libyuv/include/libyuv/convert.h"
43#include "third_party/libyuv/include/libyuv/convert_from.h"
44#include "third_party/libyuv/include/libyuv/video_common.h"
45
46using rtc::Bind;
47using rtc::Thread;
48using rtc::ThreadManager;
49using rtc::scoped_ptr;
50
51using webrtc::CodecSpecificInfo;
52using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070053using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000054using webrtc::RTPFragmentationHeader;
55using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000056using webrtc::VideoCodecType;
57using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000058using webrtc::kVideoCodecVP8;
59
60namespace webrtc_jni {
61
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000062// H.264 start code length.
63#define H264_SC_LENGTH 4
64// Maximum allowed NALUs in one output frame.
65#define MAX_NALUS_PERFRAME 32
66// Maximum supported HW video encoder resolution.
67#define MAX_VIDEO_WIDTH 1280
68#define MAX_VIDEO_HEIGHT 1280
69// Maximum supported HW video encoder fps.
70#define MAX_VIDEO_FPS 30
71
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000072// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
73// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
74// HW-backed video encode. This C++ class is implemented as a very thin shim,
75// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
76// MediaCodecVideoEncoder is created, operated, and destroyed on a single
77// thread, currently the libjingle Worker thread.
78class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
79 public rtc::MessageHandler {
80 public:
81 virtual ~MediaCodecVideoEncoder();
perkj12f68022015-10-16 13:31:45 +020082 explicit MediaCodecVideoEncoder(JNIEnv* jni, VideoCodecType codecType);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000083
84 // webrtc::VideoEncoder implementation. Everything trampolines to
85 // |codec_thread_| for execution.
86 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
87 int32_t /* number_of_cores */,
88 size_t /* max_payload_size */) override;
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:
perkj12f68022015-10-16 13:31:45 +0200108 // 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
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000112 // operable state. Necessary after all manner of OMX-layer errors.
perkj12f68022015-10-16 13:31:45 +0200113 void ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000114
115 // Implementation of webrtc::VideoEncoder methods above, all running on the
116 // codec thread exclusively.
117 //
118 // If width==0 then this is assumed to be a re-initialization and the
119 // previously-current values are reused instead of the passed parameters
120 // (makes it easier to reason about thread-safety).
121 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps);
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_;
perkj12f68022015-10-16 13:31:45 +0200158 jmethodID j_encode_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000159 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";
perkj12f68022015-10-16 13:31:45 +0200243
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000244 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",
perkj12f68022015-10-16 13:31:45 +0200250 "(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");
perkj12f68022015-10-16 13:31:45 +0200254 j_encode_method_ = GetMethodID(
255 jni, *j_media_codec_video_encoder_class_, "encode", "(ZIIJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000256 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) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700290 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000291 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
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700298 ALOGD << "InitEncode request";
asaperssonef5d5e42015-09-22 01:40:42 -0700299 scale_ = webrtc::field_trial::FindFullName(
300 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled";
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700301 ALOGD << "Encoder automatic resize " << (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() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700355 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!";
perkj12f68022015-10-16 13:31:45 +0200385 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000386 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
perkj12f68022015-10-16 13:31:45 +0200397void MediaCodecVideoEncoder::CheckOnCodecThread() {
398 RTC_CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
399 << "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) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000408 // 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) {
perkj12f68022015-10-16 13:31:45 +0200416 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000417 JNIEnv* jni = AttachCurrentThreadIfNeeded();
418 ScopedLocalRefFrame local_ref_frame(jni);
419
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700420 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
421 width << " x " << height << ". Bitrate: " << kbps <<
422 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000423 if (kbps == 0) {
424 kbps = last_set_bitrate_kbps_;
425 }
426 if (fps == 0) {
427 fps = last_set_fps_;
428 }
429
430 width_ = width;
431 height_ = height;
432 last_set_bitrate_kbps_ = kbps;
433 last_set_fps_ = fps;
434 yuv_size_ = width_ * height_ * 3 / 2;
435 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000436 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000437 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000438 frames_in_queue_ = 0;
439 current_timestamp_us_ = 0;
440 start_time_ms_ = GetCurrentTimeMs();
441 current_frames_ = 0;
442 current_bytes_ = 0;
443 current_encoding_time_ms_ = 0;
444 last_input_timestamp_ms_ = -1;
445 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000446 output_timestamp_ = 0;
447 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000448 timestamps_.clear();
449 render_times_ms_.clear();
450 frame_rtc_times_ms_.clear();
451 drop_next_input_frame_ = false;
452 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
453 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000454 jobject j_video_codec_enum = JavaEnumFromIndex(
455 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000456 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
457 jni->CallObjectMethod(*j_media_codec_video_encoder_,
perkj12f68022015-10-16 13:31:45 +0200458 j_init_encode_method_,
459 j_video_codec_enum,
460 width_,
461 height_,
462 kbps,
463 fps));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000464 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000465 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000466 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000467 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000468
perkj12f68022015-10-16 13:31:45 +0200469 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000470 switch (GetIntField(jni, *j_media_codec_video_encoder_,
471 j_color_format_field_)) {
472 case COLOR_FormatYUV420Planar:
473 encoder_fourcc_ = libyuv::FOURCC_YU12;
474 break;
475 case COLOR_FormatYUV420SemiPlanar:
476 case COLOR_QCOM_FormatYUV420SemiPlanar:
477 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
478 encoder_fourcc_ = libyuv::FOURCC_NV12;
479 break;
480 default:
481 LOG(LS_ERROR) << "Wrong color format.";
482 return WEBRTC_VIDEO_CODEC_ERROR;
483 }
484 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
henrikg91d6ede2015-09-17 00:24:34 -0700485 RTC_CHECK(input_buffers_.empty())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000486 << "Unexpected double InitEncode without Release";
487 input_buffers_.resize(num_input_buffers);
488 for (size_t i = 0; i < num_input_buffers; ++i) {
489 input_buffers_[i] =
490 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
Peter Boström0c4e06b2015-10-07 12:23:21 +0200491 int64_t yuv_buffer_capacity =
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000492 jni->GetDirectBufferCapacity(input_buffers_[i]);
493 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700494 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000495 }
496 CHECK_EXCEPTION(jni);
497
498 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
499 return WEBRTC_VIDEO_CODEC_OK;
500}
501
502int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700503 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000504 const std::vector<webrtc::VideoFrameType>* frame_types) {
perkj12f68022015-10-16 13:31:45 +0200505 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000506 JNIEnv* jni = AttachCurrentThreadIfNeeded();
507 ScopedLocalRefFrame local_ref_frame(jni);
508
509 if (!inited_) {
510 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
511 }
512 frames_received_++;
513 if (!DeliverPendingOutputs(jni)) {
perkj12f68022015-10-16 13:31:45 +0200514 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 // Continue as if everything's fine.
516 }
517
518 if (drop_next_input_frame_) {
perkj12f68022015-10-16 13:31:45 +0200519 ALOGV("Encoder drop frame - failed callback.");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000520 drop_next_input_frame_ = false;
521 return WEBRTC_VIDEO_CODEC_OK;
522 }
523
henrikg91d6ede2015-09-17 00:24:34 -0700524 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen6e2ce6e2015-07-13 16:26:33 -0700525 // Check framerate before spatial resolution change.
Peter Boström2bc68c72015-09-24 16:22:28 +0200526 if (scale_)
527 quality_scaler_.OnEncodeFrame(frame);
528
529 const VideoFrame& input_frame =
530 scale_ ? quality_scaler_.GetScaledFrame(frame) : frame;
jackychen61b4d512015-04-21 15:30:11 -0700531
perkj12f68022015-10-16 13:31:45 +0200532 if (input_frame.width() != width_ || input_frame.height() != height_) {
533 ALOGD << "Frame resolution change from " << width_ << " x " << height_ <<
534 " to " << input_frame.width() << " x " << input_frame.height();
535 width_ = input_frame.width();
536 height_ = input_frame.height();
537 ResetCodec();
538 return WEBRTC_VIDEO_CODEC_OK;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000539 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000540
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000541 // Check if we accumulated too many frames in encoder input buffers
542 // or the encoder latency exceeds 70 ms and drop frame if so.
543 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
544 int encoder_latency_ms = last_input_timestamp_ms_ -
545 last_output_timestamp_ms_;
546 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700547 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
548 " ms. Q size: " << frames_in_queue_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000549 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700550 // Report dropped frame to quality_scaler_.
551 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000552 return WEBRTC_VIDEO_CODEC_OK;
553 }
554 }
555
556 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
557 j_dequeue_input_buffer_method_);
558 CHECK_EXCEPTION(jni);
559 if (j_input_buffer_index == -1) {
560 // Video codec falls behind - no input buffer available.
perkj12f68022015-10-16 13:31:45 +0200561 ALOGV("Encoder drop frame - no input buffers available");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000562 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700563 // Report dropped frame to quality_scaler_.
564 OnDroppedFrame();
perkj12f68022015-10-16 13:31:45 +0200565 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000566 }
567 if (j_input_buffer_index == -2) {
perkj12f68022015-10-16 13:31:45 +0200568 ResetCodec();
569 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000570 }
571
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000572 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
573 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000574
575 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200576 uint8_t* yuv_buffer =
577 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000578 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700579 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
580 RTC_CHECK(!libyuv::ConvertFromI420(
perkj12f68022015-10-16 13:31:45 +0200581 input_frame.buffer(webrtc::kYPlane), input_frame.stride(webrtc::kYPlane),
582 input_frame.buffer(webrtc::kUPlane), input_frame.stride(webrtc::kUPlane),
583 input_frame.buffer(webrtc::kVPlane), input_frame.stride(webrtc::kVPlane),
henrikg91d6ede2015-09-17 00:24:34 -0700584 yuv_buffer, width_, width_, height_, encoder_fourcc_))
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000585 << "ConvertFromI420 failed";
perkj12f68022015-10-16 13:31:45 +0200586 last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
587 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000588
perkj12f68022015-10-16 13:31:45 +0200589 // Save input image timestamps for later output
590 timestamps_.push_back(input_frame.timestamp());
591 render_times_ms_.push_back(input_frame.render_time_ms());
592 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000593
perkj12f68022015-10-16 13:31:45 +0200594 bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000595 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj12f68022015-10-16 13:31:45 +0200596 j_encode_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000597 key_frame,
598 j_input_buffer_index,
599 yuv_size_,
600 current_timestamp_us_);
601 CHECK_EXCEPTION(jni);
perkj12f68022015-10-16 13:31:45 +0200602 current_timestamp_us_ += 1000000 / last_set_fps_;
603
604 if (!encode_status || !DeliverPendingOutputs(jni)) {
605 ResetCodec();
606 return WEBRTC_VIDEO_CODEC_ERROR;
607 }
608
609 return WEBRTC_VIDEO_CODEC_OK;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000610}
611
612int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
613 webrtc::EncodedImageCallback* callback) {
perkj12f68022015-10-16 13:31:45 +0200614 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000615 JNIEnv* jni = AttachCurrentThreadIfNeeded();
616 ScopedLocalRefFrame local_ref_frame(jni);
617 callback_ = callback;
618 return WEBRTC_VIDEO_CODEC_OK;
619}
620
621int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
622 if (!inited_) {
623 return WEBRTC_VIDEO_CODEC_OK;
624 }
perkj12f68022015-10-16 13:31:45 +0200625 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000626 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700627 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
628 frames_received_ << ". Encoded: " << frames_encoded_ <<
629 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000630 ScopedLocalRefFrame local_ref_frame(jni);
631 for (size_t i = 0; i < input_buffers_.size(); ++i)
632 jni->DeleteGlobalRef(input_buffers_[i]);
633 input_buffers_.clear();
634 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
635 CHECK_EXCEPTION(jni);
636 rtc::MessageQueueManager::Clear(this);
637 inited_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700638 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000639 return WEBRTC_VIDEO_CODEC_OK;
640}
641
642int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
643 uint32_t frame_rate) {
perkj12f68022015-10-16 13:31:45 +0200644 CheckOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000645 if (last_set_bitrate_kbps_ == new_bit_rate &&
646 last_set_fps_ == frame_rate) {
647 return WEBRTC_VIDEO_CODEC_OK;
648 }
649 JNIEnv* jni = AttachCurrentThreadIfNeeded();
650 ScopedLocalRefFrame local_ref_frame(jni);
651 if (new_bit_rate > 0) {
652 last_set_bitrate_kbps_ = new_bit_rate;
653 }
654 if (frame_rate > 0) {
655 last_set_fps_ = frame_rate;
656 }
657 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
658 j_set_rates_method_,
659 last_set_bitrate_kbps_,
660 last_set_fps_);
661 CHECK_EXCEPTION(jni);
662 if (!ret) {
perkj12f68022015-10-16 13:31:45 +0200663 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000664 return WEBRTC_VIDEO_CODEC_ERROR;
665 }
666 return WEBRTC_VIDEO_CODEC_OK;
667}
668
669int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
670 JNIEnv* jni,
671 jobject j_output_buffer_info) {
672 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
673}
674
675jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
676 JNIEnv* jni,
677 jobject j_output_buffer_info) {
678 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
679}
680
681bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
682 JNIEnv* jni,
683 jobject j_output_buffer_info) {
684 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
685}
686
687jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
688 JNIEnv* jni,
689 jobject j_output_buffer_info) {
690 return GetLongField(
691 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
692}
693
694bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
695 while (true) {
696 jobject j_output_buffer_info = jni->CallObjectMethod(
697 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
698 CHECK_EXCEPTION(jni);
699 if (IsNull(jni, j_output_buffer_info)) {
700 break;
701 }
702
703 int output_buffer_index =
704 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
705 if (output_buffer_index == -1) {
perkj12f68022015-10-16 13:31:45 +0200706 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000707 return false;
708 }
709
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000710 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000711 jobject j_output_buffer =
712 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
713 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000714
715 // Get frame timestamps from a queue - for non config frames only.
716 int64_t frame_encoding_time_ms = 0;
717 last_output_timestamp_ms_ =
718 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
719 1000;
720 if (frames_in_queue_ > 0) {
721 output_timestamp_ = timestamps_.front();
722 timestamps_.erase(timestamps_.begin());
723 output_render_time_ms_ = render_times_ms_.front();
724 render_times_ms_.erase(render_times_ms_.begin());
725 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
726 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
727 frames_in_queue_--;
728 }
729
730 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000731 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200732 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000733 jni->GetDirectBufferAddress(j_output_buffer));
734 CHECK_EXCEPTION(jni);
735
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000736 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
737 " Latency: %lld. EncTime: %lld",
738 frames_encoded_, key_frame, payload_size,
739 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000740 last_input_timestamp_ms_ - last_output_timestamp_ms_,
741 frame_encoding_time_ms);
742
743 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000744 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000745 current_frames_++;
746 current_bytes_ += payload_size;
747 current_encoding_time_ms_ += frame_encoding_time_ms;
748 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
749 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
750 current_frames_ > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700751 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
752 (current_bytes_ * 8 / statistic_time_ms) <<
753 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
754 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
755 << ", encTime: " <<
756 (current_encoding_time_ms_ / current_frames_) << " for last " <<
757 statistic_time_ms << " ms.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000758 start_time_ms_ = GetCurrentTimeMs();
759 current_frames_ = 0;
760 current_bytes_ = 0;
761 current_encoding_time_ms_ = 0;
762 }
763
764 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000765 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000766 if (callback_) {
767 scoped_ptr<webrtc::EncodedImage> image(
768 new webrtc::EncodedImage(payload, payload_size, payload_size));
769 image->_encodedWidth = width_;
770 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000771 image->_timeStamp = output_timestamp_;
772 image->capture_time_ms_ = output_render_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000773 image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
774 image->_completeFrame = true;
775
776 webrtc::CodecSpecificInfo info;
777 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000778 info.codecType = codecType_;
779 if (codecType_ == kVideoCodecVP8) {
780 info.codecSpecific.VP8.pictureId = picture_id_;
781 info.codecSpecific.VP8.nonReference = false;
782 info.codecSpecific.VP8.simulcastIdx = 0;
783 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
784 info.codecSpecific.VP8.layerSync = false;
785 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
786 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
787 picture_id_ = (picture_id_ + 1) & 0x7FFF;
788 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000789
790 // Generate a header describing a single fragment.
791 webrtc::RTPFragmentationHeader header;
792 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000793 if (codecType_ == kVideoCodecVP8) {
794 header.VerifyAndAllocateFragmentationHeader(1);
795 header.fragmentationOffset[0] = 0;
796 header.fragmentationLength[0] = image->_length;
797 header.fragmentationPlType[0] = 0;
798 header.fragmentationTimeDiff[0] = 0;
Peter Boström2bc68c72015-09-24 16:22:28 +0200799 if (scale_)
800 quality_scaler_.ReportQP(webrtc::vp8::GetQP(payload));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000801 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200802 if (scale_) {
803 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
804 int qp;
805 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
806 quality_scaler_.ReportQP(qp);
807 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000808 // For H.264 search for start codes.
809 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
810 int32_t scPositionsLength = 0;
811 int32_t scPosition = 0;
812 while (scPositionsLength < MAX_NALUS_PERFRAME) {
813 int32_t naluPosition = NextNaluPosition(
814 payload + scPosition, payload_size - scPosition);
815 if (naluPosition < 0) {
816 break;
817 }
818 scPosition += naluPosition;
819 scPositions[scPositionsLength++] = scPosition;
820 scPosition += H264_SC_LENGTH;
821 }
822 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700823 ALOGE << "Start code is not found!";
824 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
825 << " " << image->_buffer[2] << " " << image->_buffer[3]
826 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj12f68022015-10-16 13:31:45 +0200827 ResetCodec();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000828 return false;
829 }
830 scPositions[scPositionsLength] = payload_size;
831 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
832 for (size_t i = 0; i < scPositionsLength; i++) {
833 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
834 header.fragmentationLength[i] =
835 scPositions[i + 1] - header.fragmentationOffset[i];
836 header.fragmentationPlType[i] = 0;
837 header.fragmentationTimeDiff[i] = 0;
838 }
839 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000840
841 callback_status = callback_->Encoded(*image, &info, &header);
842 }
843
844 // Return output buffer back to the encoder.
845 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
846 j_release_output_buffer_method_,
847 output_buffer_index);
848 CHECK_EXCEPTION(jni);
849 if (!success) {
perkj12f68022015-10-16 13:31:45 +0200850 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000851 return false;
852 }
853
854 if (callback_status > 0) {
855 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000856 // Theoretically could handle callback_status<0 here, but unclear what
857 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000858 }
859 }
860
861 return true;
862}
863
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000864int32_t MediaCodecVideoEncoder::NextNaluPosition(
865 uint8_t *buffer, size_t buffer_size) {
866 if (buffer_size < H264_SC_LENGTH) {
867 return -1;
868 }
869 uint8_t *head = buffer;
870 // Set end buffer pointer to 4 bytes before actual buffer end so we can
871 // access head[1], head[2] and head[3] in a loop without buffer overrun.
872 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
873
874 while (head < end) {
875 if (head[0]) {
876 head++;
877 continue;
878 }
879 if (head[1]) { // got 00xx
880 head += 2;
881 continue;
882 }
883 if (head[2]) { // got 0000xx
884 head += 3;
885 continue;
886 }
887 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000888 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000889 continue;
890 }
891 return (int32_t)(head - buffer);
892 }
893 return -1;
894}
895
jackychen61b4d512015-04-21 15:30:11 -0700896void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200897 if (scale_)
898 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700899}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000900
jackychen6e2ce6e2015-07-13 16:26:33 -0700901int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200902 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -0700903}
904
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000905MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
906 JNIEnv* jni = AttachCurrentThreadIfNeeded();
907 ScopedLocalRefFrame local_ref_frame(jni);
908 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000909 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000910
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000911 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
912 j_encoder_class,
913 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
914 CHECK_EXCEPTION(jni);
915 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700916 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000917 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
918 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
919 }
920
921 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
922 j_encoder_class,
923 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
924 CHECK_EXCEPTION(jni);
925 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700926 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000927 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
928 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
929 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000930}
931
932MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
933
934webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000935 VideoCodecType type) {
936 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000937 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000938 }
939 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
940 it != supported_codecs_.end(); ++it) {
941 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700942 ALOGD << "Create HW video encoder for type " << (int)type <<
943 " (" << it->name << ").";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000944 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
945 }
946 }
947 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000948}
949
950const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
951MediaCodecVideoEncoderFactory::codecs() const {
952 return supported_codecs_;
953}
954
955void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
956 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700957 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000958 delete encoder;
959}
960
961} // namespace webrtc_jni
962