blob: 59747a159fca66c726ff864ddb25862b1cb898d4 [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"
perkj9576e542015-11-12 06:43:16 -080036#include "webrtc/base/thread_checker.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020037#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000038#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
jackychen61b4d512015-04-21 15:30:11 -070039#include "webrtc/modules/video_coding/utility/include/quality_scaler.h"
jackychen98d8cf52015-05-21 11:12:02 -070040#include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010041#include "webrtc/system_wrappers/include/field_trial.h"
42#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000043#include "third_party/libyuv/include/libyuv/convert.h"
44#include "third_party/libyuv/include/libyuv/convert_from.h"
45#include "third_party/libyuv/include/libyuv/video_common.h"
46
47using rtc::Bind;
48using rtc::Thread;
49using rtc::ThreadManager;
50using rtc::scoped_ptr;
51
52using webrtc::CodecSpecificInfo;
53using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070054using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000055using webrtc::RTPFragmentationHeader;
56using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000057using webrtc::VideoCodecType;
58using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000059using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080060using webrtc::kVideoCodecVP9;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000061
62namespace webrtc_jni {
63
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000064// H.264 start code length.
65#define H264_SC_LENGTH 4
66// Maximum allowed NALUs in one output frame.
67#define MAX_NALUS_PERFRAME 32
68// Maximum supported HW video encoder resolution.
69#define MAX_VIDEO_WIDTH 1280
70#define MAX_VIDEO_HEIGHT 1280
71// Maximum supported HW video encoder fps.
72#define MAX_VIDEO_FPS 30
73
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000074// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
75// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
76// HW-backed video encode. This C++ class is implemented as a very thin shim,
77// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
78// MediaCodecVideoEncoder is created, operated, and destroyed on a single
79// thread, currently the libjingle Worker thread.
80class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
81 public rtc::MessageHandler {
82 public:
83 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -080084 MediaCodecVideoEncoder(JNIEnv* jni,
85 VideoCodecType codecType);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000086
87 // webrtc::VideoEncoder implementation. Everything trampolines to
88 // |codec_thread_| for execution.
89 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
90 int32_t /* number_of_cores */,
91 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -070092 int32_t Encode(const webrtc::VideoFrame& input_image,
93 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
94 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000095 int32_t RegisterEncodeCompleteCallback(
96 webrtc::EncodedImageCallback* callback) override;
97 int32_t Release() override;
98 int32_t SetChannelParameters(uint32_t /* packet_loss */,
99 int64_t /* rtt */) override;
100 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
101
102 // rtc::MessageHandler implementation.
103 void OnMessage(rtc::Message* msg) override;
104
jackychen61b4d512015-04-21 15:30:11 -0700105 void OnDroppedFrame() override;
106
jackychen6e2ce6e2015-07-13 16:26:33 -0700107 int GetTargetFramerate() override;
108
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000109 private:
perkj9576e542015-11-12 06:43:16 -0800110 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
111 // InitEncodeOnCodecThread() 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.
perkj9576e542015-11-12 06:43:16 -0800113 bool ResetCodecOnCodecThread();
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);
perkj9576e542015-11-12 06:43:16 -0800122 // Reconfigure to match |frame| in width, height. Returns false if
123 // reconfiguring fails.
124 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000125 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700126 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700127 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800128 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
129 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
130
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000131 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
132 webrtc::EncodedImageCallback* callback);
133 int32_t ReleaseOnCodecThread();
134 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
135
136 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
137 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
138 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
139 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
140 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000141 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000142
143 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
144 // true on success.
145 bool DeliverPendingOutputs(JNIEnv* jni);
146
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000147 // Search for H.264 start codes.
148 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
149
150 // Type of video codec.
151 VideoCodecType codecType_;
152
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000153 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
154 // |codec_thread_| synchronously.
155 webrtc::EncodedImageCallback* callback_;
156
157 // State that is constant for the lifetime of this object once the ctor
158 // returns.
159 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800160 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000161 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
162 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
163 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800164 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000165 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800166 jmethodID j_encode_buffer_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000167 jmethodID j_release_method_;
168 jmethodID j_set_rates_method_;
169 jmethodID j_dequeue_output_buffer_method_;
170 jmethodID j_release_output_buffer_method_;
171 jfieldID j_color_format_field_;
172 jfieldID j_info_index_field_;
173 jfieldID j_info_buffer_field_;
174 jfieldID j_info_is_key_frame_field_;
175 jfieldID j_info_presentation_timestamp_us_field_;
176
177 // State that is valid only between InitEncode() and the next Release().
178 // Touched only on codec_thread_ so no explicit synchronization necessary.
179 int width_; // Frame width in pixels.
180 int height_; // Frame height in pixels.
181 bool inited_;
182 uint16_t picture_id_;
183 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
184 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
185 int last_set_fps_; // Last-requested frame rate.
186 int64_t current_timestamp_us_; // Current frame timestamps in us.
187 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000188 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000189 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000190 int frames_in_queue_; // Number of frames in encoder queue.
191 int64_t start_time_ms_; // Start time for statistics.
192 int current_frames_; // Number of frames in the current statistics interval.
193 int current_bytes_; // Encoded bytes in the current statistics interval.
194 int current_encoding_time_ms_; // Overall encoding time in the current second
195 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
196 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
197 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
198 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
199 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
200 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000201 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
202 int64_t output_render_time_ms_; // Last output frame render time from
203 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000204 // Frame size in bytes fed to MediaCodec.
205 int yuv_size_;
206 // True only when between a callback_->Encoded() call return a positive value
207 // and the next Encode() call being ignored.
208 bool drop_next_input_frame_;
209 // Global references; must be deleted in Release().
210 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200211 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700212 // Dynamic resolution change, off by default.
213 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200214
215 // H264 bitstream parser, used to extract QP from encoded bitstreams.
216 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800217
218 // VP9 variables to populate codec specific structure.
219 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
220 // non-flexible VP9 mode.
221 uint8_t tl0_pic_idx_;
222 size_t gof_idx_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000223};
224
225MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
226 // Call Release() to ensure no more callbacks to us after we are deleted.
227 Release();
228}
229
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000230MediaCodecVideoEncoder::MediaCodecVideoEncoder(
231 JNIEnv* jni, VideoCodecType codecType) :
232 codecType_(codecType),
233 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000234 inited_(false),
235 picture_id_(0),
236 codec_thread_(new Thread()),
237 j_media_codec_video_encoder_class_(
238 jni,
239 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
240 j_media_codec_video_encoder_(
241 jni,
242 jni->NewObject(*j_media_codec_video_encoder_class_,
243 GetMethodID(jni,
244 *j_media_codec_video_encoder_class_,
245 "<init>",
246 "()V"))) {
247 ScopedLocalRefFrame local_ref_frame(jni);
248 // It would be nice to avoid spinning up a new thread per MediaCodec, and
249 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
250 // 2732 means that deadlocks abound. This class synchronously trampolines
251 // to |codec_thread_|, so if anything else can be coming to _us_ from
252 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
253 // in the bug, we have a problem. For now work around that with a dedicated
254 // thread.
255 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700256 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800257 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000258 jclass j_output_buffer_info_class =
259 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000260 j_init_encode_method_ = GetMethodID(
261 jni,
262 *j_media_codec_video_encoder_class_,
263 "initEncode",
perkj9576e542015-11-12 06:43:16 -0800264 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)Z");
265 j_get_input_buffers_method_ = GetMethodID(
266 jni,
267 *j_media_codec_video_encoder_class_,
268 "getInputBuffers",
269 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000270 j_dequeue_input_buffer_method_ = GetMethodID(
271 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800272 j_encode_buffer_method_ = GetMethodID(
273 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000274 j_release_method_ =
275 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
276 j_set_rates_method_ = GetMethodID(
277 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000278 j_dequeue_output_buffer_method_ = GetMethodID(
279 jni,
280 *j_media_codec_video_encoder_class_,
281 "dequeueOutputBuffer",
282 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000283 j_release_output_buffer_method_ = GetMethodID(
284 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
285
286 j_color_format_field_ =
287 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
288 j_info_index_field_ =
289 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
290 j_info_buffer_field_ = GetFieldID(
291 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
292 j_info_is_key_frame_field_ =
293 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
294 j_info_presentation_timestamp_us_field_ = GetFieldID(
295 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
296 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800297 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000298 AllowBlockingCalls();
299}
300
301int32_t MediaCodecVideoEncoder::InitEncode(
302 const webrtc::VideoCodec* codec_settings,
303 int32_t /* number_of_cores */,
304 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700305 const int kMinWidth = 320;
306 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700307 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000308 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700309 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000310 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
311 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000312 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700313 RTC_CHECK(codec_settings->codecType == codecType_)
314 << "Unsupported codec " << codec_settings->codecType << " for "
315 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000316
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700317 ALOGD << "InitEncode request";
Alex Glaznevad948c42015-11-18 13:06:42 -0800318 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
319 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700320 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200321 if (scale_) {
322 if (codecType_ == kVideoCodecVP8) {
323 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
324 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
325 // always = 127. Note that in SW, QP is that of the user-level range [0,
326 // 63].
327 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200328 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
329 // This effectively disables high QP as VP8 QP can't go above this
330 // threshold.
331 const int kDisabledBadQpThreshold = kMaxQp + 1;
332 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
333 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200334 } else if (codecType_ == kVideoCodecH264) {
335 // H264 QP is in the range [0, 51].
336 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200337 const int kBadQpThreshold = 40;
338 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
339 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200340 } else {
341 // When adding codec support to additional hardware codecs, also configure
342 // their QP thresholds for scaling.
343 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
344 }
345 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
346 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700347 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000348 return codec_thread_->Invoke<int32_t>(
349 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
350 this,
351 codec_settings->width,
352 codec_settings->height,
353 codec_settings->startBitrate,
354 codec_settings->maxFramerate));
355}
356
357int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700358 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000359 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700360 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000361 return codec_thread_->Invoke<int32_t>(Bind(
362 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
363}
364
365int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
366 webrtc::EncodedImageCallback* callback) {
367 return codec_thread_->Invoke<int32_t>(
368 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
369 this,
370 callback));
371}
372
373int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700374 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000375 return codec_thread_->Invoke<int32_t>(
376 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
377}
378
379int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
380 int64_t /* rtt */) {
381 return WEBRTC_VIDEO_CODEC_OK;
382}
383
384int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
385 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200386 if (scale_)
387 quality_scaler_.ReportFramerate(frame_rate);
388
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000389 return codec_thread_->Invoke<int32_t>(
390 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
391 this,
392 new_bit_rate,
393 frame_rate));
394}
395
396void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800397 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000398 JNIEnv* jni = AttachCurrentThreadIfNeeded();
399 ScopedLocalRefFrame local_ref_frame(jni);
400
401 // We only ever send one message to |this| directly (not through a Bind()'d
402 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700403 RTC_CHECK(!msg->message_id) << "Unexpected message!";
404 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000405 if (!inited_) {
406 return;
407 }
408
409 // It would be nice to recover from a failure here if one happened, but it's
410 // unclear how to signal such a failure to the app, so instead we stay silent
411 // about it and let the next app-called API method reveal the borkedness.
412 DeliverPendingOutputs(jni);
413 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
414}
415
perkj9576e542015-11-12 06:43:16 -0800416bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
417 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
418 ALOGE << "ResetOnCodecThread";
419 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
420 InitEncodeOnCodecThread(width_, height_, 0, 0)
421 != WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000422 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
423 // degrade to a SW encoder at this point? There isn't one AFAICT :(
424 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800425 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000426 }
perkj9576e542015-11-12 06:43:16 -0800427 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000428}
429
430int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
431 int width, int height, int kbps, int fps) {
perkj9576e542015-11-12 06:43:16 -0800432 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000433 JNIEnv* jni = AttachCurrentThreadIfNeeded();
434 ScopedLocalRefFrame local_ref_frame(jni);
435
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700436 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
437 width << " x " << height << ". Bitrate: " << kbps <<
438 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000439 if (kbps == 0) {
440 kbps = last_set_bitrate_kbps_;
441 }
442 if (fps == 0) {
443 fps = last_set_fps_;
444 }
445
446 width_ = width;
447 height_ = height;
448 last_set_bitrate_kbps_ = kbps;
449 last_set_fps_ = fps;
450 yuv_size_ = width_ * height_ * 3 / 2;
451 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000452 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000453 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000454 frames_in_queue_ = 0;
455 current_timestamp_us_ = 0;
456 start_time_ms_ = GetCurrentTimeMs();
457 current_frames_ = 0;
458 current_bytes_ = 0;
459 current_encoding_time_ms_ = 0;
460 last_input_timestamp_ms_ = -1;
461 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000462 output_timestamp_ = 0;
463 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000464 timestamps_.clear();
465 render_times_ms_.clear();
466 frame_rtc_times_ms_.clear();
467 drop_next_input_frame_ = false;
468 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800469 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
470 tl0_pic_idx_ = static_cast<uint8_t>(rand());
471 gof_idx_ = 0;
perkj9576e542015-11-12 06:43:16 -0800472
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000473 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000474 jobject j_video_codec_enum = JavaEnumFromIndex(
475 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800476 const bool encode_status = jni->CallBooleanMethod(
477 *j_media_codec_video_encoder_, j_init_encode_method_,
478 j_video_codec_enum, width, height, kbps, fps);
479 if (!encode_status) {
480 ALOGE << "Failed to configure encoder.";
481 return WEBRTC_VIDEO_CODEC_ERROR;
482 }
483 CHECK_EXCEPTION(jni);
484
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
486 jni->CallObjectMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800487 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000488 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000489 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000490 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000491 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000492
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000493 switch (GetIntField(jni, *j_media_codec_video_encoder_,
494 j_color_format_field_)) {
495 case COLOR_FormatYUV420Planar:
496 encoder_fourcc_ = libyuv::FOURCC_YU12;
497 break;
498 case COLOR_FormatYUV420SemiPlanar:
499 case COLOR_QCOM_FormatYUV420SemiPlanar:
500 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
501 encoder_fourcc_ = libyuv::FOURCC_NV12;
502 break;
503 default:
504 LOG(LS_ERROR) << "Wrong color format.";
505 return WEBRTC_VIDEO_CODEC_ERROR;
506 }
507 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
henrikg91d6ede2015-09-17 00:24:34 -0700508 RTC_CHECK(input_buffers_.empty())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000509 << "Unexpected double InitEncode without Release";
510 input_buffers_.resize(num_input_buffers);
511 for (size_t i = 0; i < num_input_buffers; ++i) {
512 input_buffers_[i] =
513 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
Peter Boström0c4e06b2015-10-07 12:23:21 +0200514 int64_t yuv_buffer_capacity =
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 jni->GetDirectBufferCapacity(input_buffers_[i]);
516 CHECK_EXCEPTION(jni);
henrikg91d6ede2015-09-17 00:24:34 -0700517 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000518 }
519 CHECK_EXCEPTION(jni);
520
perkj9576e542015-11-12 06:43:16 -0800521
522 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000523 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
524 return WEBRTC_VIDEO_CODEC_OK;
525}
526
527int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700528 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700529 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800530 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000531 JNIEnv* jni = AttachCurrentThreadIfNeeded();
532 ScopedLocalRefFrame local_ref_frame(jni);
533
534 if (!inited_) {
535 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
536 }
perkj9576e542015-11-12 06:43:16 -0800537
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 frames_received_++;
539 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800540 if (!ResetCodecOnCodecThread())
541 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000542 }
543
544 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800545 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000546 drop_next_input_frame_ = false;
547 return WEBRTC_VIDEO_CODEC_OK;
548 }
549
henrikg91d6ede2015-09-17 00:24:34 -0700550 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen6e2ce6e2015-07-13 16:26:33 -0700551 // Check framerate before spatial resolution change.
Peter Boström2bc68c72015-09-24 16:22:28 +0200552 if (scale_)
553 quality_scaler_.OnEncodeFrame(frame);
554
555 const VideoFrame& input_frame =
556 scale_ ? quality_scaler_.GetScaledFrame(frame) : frame;
jackychen61b4d512015-04-21 15:30:11 -0700557
perkj9576e542015-11-12 06:43:16 -0800558 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
559 ALOGE << "Failed to reconfigure encoder.";
560 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000561 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000562
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000563 // Check if we accumulated too many frames in encoder input buffers
564 // or the encoder latency exceeds 70 ms and drop frame if so.
565 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
566 int encoder_latency_ms = last_input_timestamp_ms_ -
567 last_output_timestamp_ms_;
568 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700569 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
570 " ms. Q size: " << frames_in_queue_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000571 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700572 // Report dropped frame to quality_scaler_.
573 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000574 return WEBRTC_VIDEO_CODEC_OK;
575 }
576 }
577
578 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800579 j_dequeue_input_buffer_method_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000580 CHECK_EXCEPTION(jni);
581 if (j_input_buffer_index == -1) {
582 // Video codec falls behind - no input buffer available.
perkj9576e542015-11-12 06:43:16 -0800583 ALOGW << "Encoder drop frame - no input buffers available";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000584 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700585 // Report dropped frame to quality_scaler_.
586 OnDroppedFrame();
perkj12f68022015-10-16 13:31:45 +0200587 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000588 }
589 if (j_input_buffer_index == -2) {
perkj9576e542015-11-12 06:43:16 -0800590 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200591 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000592 }
593
perkj9576e542015-11-12 06:43:16 -0800594 last_input_timestamp_ms_ =
595 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200596 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000597
perkj12f68022015-10-16 13:31:45 +0200598 // Save input image timestamps for later output
599 timestamps_.push_back(input_frame.timestamp());
600 render_times_ms_.push_back(input_frame.render_time_ms());
601 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000602
perkj9576e542015-11-12 06:43:16 -0800603 const bool key_frame = frame_types->front() != webrtc::kVideoFrameDelta;
604 const bool encode_status =
605 EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
606 j_input_buffer_index);
607
608 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
609
610 if (!encode_status || !DeliverPendingOutputs(jni)) {
611 ALOGE << "Failed deliver pending outputs.";
612 ResetCodecOnCodecThread();
613 return WEBRTC_VIDEO_CODEC_ERROR;
614 }
615 return WEBRTC_VIDEO_CODEC_OK;
616}
617
618bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
619 const webrtc::VideoFrame& frame) {
620 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
621
622 const bool reconfigure_due_to_size =
623 frame.width() != width_ || frame.height() != height_;
624
625 if (reconfigure_due_to_size) {
626 ALOGD << "Reconfigure encoder due to frame resolution change from "
627 << width_ << " x " << height_ << " to " << frame.width() << " x "
628 << frame.height();
629 width_ = frame.width();
630 height_ = frame.height();
631 }
632
633 if (!reconfigure_due_to_size)
634 return true;
635
636 ReleaseOnCodecThread();
637
638 return InitEncodeOnCodecThread(width_, height_, 0, 0) ==
639 WEBRTC_VIDEO_CODEC_OK;
640}
641
642bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
643 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
644 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
645
646 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
647 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
648
649 jobject j_input_buffer = input_buffers_[input_buffer_index];
650 uint8_t* yuv_buffer =
651 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
652 CHECK_EXCEPTION(jni);
653 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
654 RTC_CHECK(!libyuv::ConvertFromI420(
655 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
656 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
657 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
658 yuv_buffer, width_, width_, height_, encoder_fourcc_))
659 << "ConvertFromI420 failed";
660
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000661 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800662 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000663 key_frame,
perkj9576e542015-11-12 06:43:16 -0800664 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000665 yuv_size_,
666 current_timestamp_us_);
667 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800668 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000669}
670
671int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
672 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800673 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000674 JNIEnv* jni = AttachCurrentThreadIfNeeded();
675 ScopedLocalRefFrame local_ref_frame(jni);
676 callback_ = callback;
677 return WEBRTC_VIDEO_CODEC_OK;
678}
679
680int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800681 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000682 if (!inited_) {
683 return WEBRTC_VIDEO_CODEC_OK;
684 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000685 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700686 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
687 frames_received_ << ". Encoded: " << frames_encoded_ <<
688 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000689 ScopedLocalRefFrame local_ref_frame(jni);
690 for (size_t i = 0; i < input_buffers_.size(); ++i)
691 jni->DeleteGlobalRef(input_buffers_[i]);
692 input_buffers_.clear();
693 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
694 CHECK_EXCEPTION(jni);
695 rtc::MessageQueueManager::Clear(this);
696 inited_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700697 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000698 return WEBRTC_VIDEO_CODEC_OK;
699}
700
701int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
702 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800703 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000704 if (last_set_bitrate_kbps_ == new_bit_rate &&
705 last_set_fps_ == frame_rate) {
706 return WEBRTC_VIDEO_CODEC_OK;
707 }
708 JNIEnv* jni = AttachCurrentThreadIfNeeded();
709 ScopedLocalRefFrame local_ref_frame(jni);
710 if (new_bit_rate > 0) {
711 last_set_bitrate_kbps_ = new_bit_rate;
712 }
713 if (frame_rate > 0) {
714 last_set_fps_ = frame_rate;
715 }
716 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
717 j_set_rates_method_,
718 last_set_bitrate_kbps_,
719 last_set_fps_);
720 CHECK_EXCEPTION(jni);
721 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800722 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000723 return WEBRTC_VIDEO_CODEC_ERROR;
724 }
725 return WEBRTC_VIDEO_CODEC_OK;
726}
727
728int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
729 JNIEnv* jni,
730 jobject j_output_buffer_info) {
731 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
732}
733
734jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
735 JNIEnv* jni,
736 jobject j_output_buffer_info) {
737 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
738}
739
740bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
741 JNIEnv* jni,
742 jobject j_output_buffer_info) {
743 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
744}
745
746jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
747 JNIEnv* jni,
748 jobject j_output_buffer_info) {
749 return GetLongField(
750 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
751}
752
753bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800754 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000755 while (true) {
756 jobject j_output_buffer_info = jni->CallObjectMethod(
757 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
758 CHECK_EXCEPTION(jni);
759 if (IsNull(jni, j_output_buffer_info)) {
760 break;
761 }
762
763 int output_buffer_index =
764 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
765 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800766 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000767 return false;
768 }
769
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000770 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000771 jobject j_output_buffer =
772 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
773 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000774
775 // Get frame timestamps from a queue - for non config frames only.
776 int64_t frame_encoding_time_ms = 0;
777 last_output_timestamp_ms_ =
778 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
779 1000;
780 if (frames_in_queue_ > 0) {
781 output_timestamp_ = timestamps_.front();
782 timestamps_.erase(timestamps_.begin());
783 output_render_time_ms_ = render_times_ms_.front();
784 render_times_ms_.erase(render_times_ms_.begin());
785 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
786 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
787 frames_in_queue_--;
788 }
789
790 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000791 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200792 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000793 jni->GetDirectBufferAddress(j_output_buffer));
794 CHECK_EXCEPTION(jni);
795
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000796 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
797 " Latency: %lld. EncTime: %lld",
798 frames_encoded_, key_frame, payload_size,
799 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000800 last_input_timestamp_ms_ - last_output_timestamp_ms_,
801 frame_encoding_time_ms);
802
803 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000804 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000805 current_frames_++;
806 current_bytes_ += payload_size;
807 current_encoding_time_ms_ += frame_encoding_time_ms;
808 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
809 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
810 current_frames_ > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700811 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
812 (current_bytes_ * 8 / statistic_time_ms) <<
813 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
814 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
815 << ", encTime: " <<
816 (current_encoding_time_ms_ / current_frames_) << " for last " <<
817 statistic_time_ms << " ms.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000818 start_time_ms_ = GetCurrentTimeMs();
819 current_frames_ = 0;
820 current_bytes_ = 0;
821 current_encoding_time_ms_ = 0;
822 }
823
824 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000825 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000826 if (callback_) {
827 scoped_ptr<webrtc::EncodedImage> image(
828 new webrtc::EncodedImage(payload, payload_size, payload_size));
829 image->_encodedWidth = width_;
830 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000831 image->_timeStamp = output_timestamp_;
832 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200833 image->_frameType =
834 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000835 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700836 image->adapt_reason_.quality_resolution_downscales =
837 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000838
839 webrtc::CodecSpecificInfo info;
840 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000841 info.codecType = codecType_;
842 if (codecType_ == kVideoCodecVP8) {
843 info.codecSpecific.VP8.pictureId = picture_id_;
844 info.codecSpecific.VP8.nonReference = false;
845 info.codecSpecific.VP8.simulcastIdx = 0;
846 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
847 info.codecSpecific.VP8.layerSync = false;
848 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
849 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800850 } else if (codecType_ == kVideoCodecVP9) {
851 if (key_frame) {
852 gof_idx_ = 0;
853 }
854 info.codecSpecific.VP9.picture_id = picture_id_;
855 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
856 info.codecSpecific.VP9.flexible_mode = false;
857 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
858 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
859 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
860 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
861 info.codecSpecific.VP9.temporal_up_switch = true;
862 info.codecSpecific.VP9.inter_layer_predicted = false;
863 info.codecSpecific.VP9.gof_idx =
864 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
865 info.codecSpecific.VP9.num_spatial_layers = 1;
866 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
867 if (info.codecSpecific.VP9.ss_data_available) {
868 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
869 info.codecSpecific.VP9.width[0] = width_;
870 info.codecSpecific.VP9.height[0] = height_;
871 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
872 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000873 }
Alex Glaznevad948c42015-11-18 13:06:42 -0800874 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000875
876 // Generate a header describing a single fragment.
877 webrtc::RTPFragmentationHeader header;
878 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -0800879 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000880 header.VerifyAndAllocateFragmentationHeader(1);
881 header.fragmentationOffset[0] = 0;
882 header.fragmentationLength[0] = image->_length;
883 header.fragmentationPlType[0] = 0;
884 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -0800885 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -0700886 int qp;
887 if (webrtc::vp8::GetQp(payload, payload_size, &qp))
888 quality_scaler_.ReportQP(qp);
889 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000890 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200891 if (scale_) {
892 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
893 int qp;
894 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
895 quality_scaler_.ReportQP(qp);
896 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000897 // For H.264 search for start codes.
898 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
899 int32_t scPositionsLength = 0;
900 int32_t scPosition = 0;
901 while (scPositionsLength < MAX_NALUS_PERFRAME) {
902 int32_t naluPosition = NextNaluPosition(
903 payload + scPosition, payload_size - scPosition);
904 if (naluPosition < 0) {
905 break;
906 }
907 scPosition += naluPosition;
908 scPositions[scPositionsLength++] = scPosition;
909 scPosition += H264_SC_LENGTH;
910 }
911 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700912 ALOGE << "Start code is not found!";
913 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
914 << " " << image->_buffer[2] << " " << image->_buffer[3]
915 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -0800916 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000917 return false;
918 }
919 scPositions[scPositionsLength] = payload_size;
920 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
921 for (size_t i = 0; i < scPositionsLength; i++) {
922 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
923 header.fragmentationLength[i] =
924 scPositions[i + 1] - header.fragmentationOffset[i];
925 header.fragmentationPlType[i] = 0;
926 header.fragmentationTimeDiff[i] = 0;
927 }
928 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000929
930 callback_status = callback_->Encoded(*image, &info, &header);
931 }
932
933 // Return output buffer back to the encoder.
934 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
935 j_release_output_buffer_method_,
936 output_buffer_index);
937 CHECK_EXCEPTION(jni);
938 if (!success) {
perkj9576e542015-11-12 06:43:16 -0800939 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000940 return false;
941 }
942
943 if (callback_status > 0) {
944 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000945 // Theoretically could handle callback_status<0 here, but unclear what
946 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000947 }
948 }
949
950 return true;
951}
952
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000953int32_t MediaCodecVideoEncoder::NextNaluPosition(
954 uint8_t *buffer, size_t buffer_size) {
955 if (buffer_size < H264_SC_LENGTH) {
956 return -1;
957 }
958 uint8_t *head = buffer;
959 // Set end buffer pointer to 4 bytes before actual buffer end so we can
960 // access head[1], head[2] and head[3] in a loop without buffer overrun.
961 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
962
963 while (head < end) {
964 if (head[0]) {
965 head++;
966 continue;
967 }
968 if (head[1]) { // got 00xx
969 head += 2;
970 continue;
971 }
972 if (head[2]) { // got 0000xx
973 head += 3;
974 continue;
975 }
976 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000977 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000978 continue;
979 }
980 return (int32_t)(head - buffer);
981 }
982 return -1;
983}
984
jackychen61b4d512015-04-21 15:30:11 -0700985void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200986 if (scale_)
987 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700988}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000989
jackychen6e2ce6e2015-07-13 16:26:33 -0700990int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +0200991 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -0700992}
993
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000994MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
995 JNIEnv* jni = AttachCurrentThreadIfNeeded();
996 ScopedLocalRefFrame local_ref_frame(jni);
997 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000998 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000999
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001000 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1001 j_encoder_class,
1002 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1003 CHECK_EXCEPTION(jni);
1004 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001005 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001006 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1007 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1008 }
1009
Alex Glaznevad948c42015-11-18 13:06:42 -08001010 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1011 j_encoder_class,
1012 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1013 CHECK_EXCEPTION(jni);
1014 if (is_vp9_hw_supported) {
1015 ALOGD << "VP9 HW Encoder supported.";
1016 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1017 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1018 }
1019
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001020 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1021 j_encoder_class,
1022 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1023 CHECK_EXCEPTION(jni);
1024 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001025 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001026 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1027 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1028 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001029}
1030
1031MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
1032
1033webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001034 VideoCodecType type) {
1035 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001036 ALOGW << "No HW video encoder for type " << (int)type;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001037 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001038 }
1039 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1040 it != supported_codecs_.end(); ++it) {
1041 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001042 ALOGD << "Create HW video encoder for type " << (int)type <<
1043 " (" << it->name << ").";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001044 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
1045 }
1046 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001047 ALOGW << "Can not find HW video encoder for type " << (int)type;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001048 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001049}
1050
1051const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1052MediaCodecVideoEncoderFactory::codecs() const {
1053 return supported_codecs_;
1054}
1055
1056void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1057 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001058 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001059 delete encoder;
1060}
1061
1062} // namespace webrtc_jni
1063