blob: 05e81458a5a4cdd83dd534497f1d53c3ce7bcea2 [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"
perkj30e91822015-11-20 01:31:25 -080032#include "talk/app/webrtc/java/jni/native_handle_impl.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000033#include "webrtc/base/bind.h"
34#include "webrtc/base/checks.h"
35#include "webrtc/base/logging.h"
36#include "webrtc/base/thread.h"
perkj9576e542015-11-12 06:43:16 -080037#include "webrtc/base/thread_checker.h"
asapersson1d61a512016-01-20 01:13:46 -080038#include "webrtc/common_types.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020039#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080040#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010041#include "webrtc/modules/video_coding/utility/quality_scaler.h"
42#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/field_trial.h"
44#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000045#include "third_party/libyuv/include/libyuv/convert.h"
46#include "third_party/libyuv/include/libyuv/convert_from.h"
47#include "third_party/libyuv/include/libyuv/video_common.h"
48
49using rtc::Bind;
50using rtc::Thread;
51using rtc::ThreadManager;
52using rtc::scoped_ptr;
53
54using webrtc::CodecSpecificInfo;
55using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070056using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000057using webrtc::RTPFragmentationHeader;
58using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000059using webrtc::VideoCodecType;
60using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000061using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080062using webrtc::kVideoCodecVP9;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000063
64namespace webrtc_jni {
65
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000066// H.264 start code length.
67#define H264_SC_LENGTH 4
68// Maximum allowed NALUs in one output frame.
69#define MAX_NALUS_PERFRAME 32
70// Maximum supported HW video encoder resolution.
71#define MAX_VIDEO_WIDTH 1280
72#define MAX_VIDEO_HEIGHT 1280
73// Maximum supported HW video encoder fps.
74#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080075// Maximum allowed fps value in SetRates() call.
76#define MAX_ALLOWED_VIDEO_FPS 60
77// Maximum allowed frames in encoder input queue.
78#define MAX_ENCODER_Q_SIZE 2
79// Maximum allowed latency in ms.
80#define MAX_ENCODER_LATENCY_MS 70
glaznev919ff752016-01-27 15:01:03 -080081// Maximum amount of dropped frames caused by full encoder queue - exceeding
82// this threshold means that encoder probably got stuck and need to be reset.
83#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080084
85// Logging macros.
86#define TAG_ENCODER "MediaCodecVideoEncoder"
87#ifdef TRACK_BUFFER_TIMING
88#define ALOGV(...)
89 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
90#else
91#define ALOGV(...)
92#endif
93#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
94#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
95#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000096
asapersson1d61a512016-01-20 01:13:46 -080097namespace {
98// Maximum time limit between incoming frames before requesting a key frame.
99const size_t kFrameDiffThresholdMs = 1100;
100const int kMinKeyFrameInterval = 2;
101} // namespace
102
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000103// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
104// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
105// HW-backed video encode. This C++ class is implemented as a very thin shim,
106// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
107// MediaCodecVideoEncoder is created, operated, and destroyed on a single
108// thread, currently the libjingle Worker thread.
109class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
110 public rtc::MessageHandler {
111 public:
112 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -0800113 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800114 VideoCodecType codecType,
115 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000116
117 // webrtc::VideoEncoder implementation. Everything trampolines to
118 // |codec_thread_| for execution.
119 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
120 int32_t /* number_of_cores */,
121 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700122 int32_t Encode(const webrtc::VideoFrame& input_image,
123 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
124 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000125 int32_t RegisterEncodeCompleteCallback(
126 webrtc::EncodedImageCallback* callback) override;
127 int32_t Release() override;
128 int32_t SetChannelParameters(uint32_t /* packet_loss */,
129 int64_t /* rtt */) override;
130 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
131
132 // rtc::MessageHandler implementation.
133 void OnMessage(rtc::Message* msg) override;
134
jackychen61b4d512015-04-21 15:30:11 -0700135 void OnDroppedFrame() override;
136
jackychen6e2ce6e2015-07-13 16:26:33 -0700137 int GetTargetFramerate() override;
138
Perec2922f2016-01-27 15:25:46 +0100139 bool SupportsNativeHandle() const override { return egl_context_ != nullptr; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100140 const char* ImplementationName() const override;
141
142 private:
143 // CHECK-fail if not running on |codec_thread_|.
144 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800145
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000146 private:
perkj9576e542015-11-12 06:43:16 -0800147 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
148 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000149 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800150 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000151
152 // Implementation of webrtc::VideoEncoder methods above, all running on the
153 // codec thread exclusively.
154 //
155 // If width==0 then this is assumed to be a re-initialization and the
156 // previously-current values are reused instead of the passed parameters
157 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800158 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
159 bool use_surface);
160 // Reconfigure to match |frame| in width, height. Also reconfigures the
161 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
162 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800163 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000164 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700165 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700166 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800167 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
168 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800169 bool EncodeTextureOnCodecThread(JNIEnv* jni,
170 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800171
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000172 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
173 webrtc::EncodedImageCallback* callback);
174 int32_t ReleaseOnCodecThread();
175 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
176
177 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
178 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
179 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
180 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
181 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000182 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000183
184 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
185 // true on success.
186 bool DeliverPendingOutputs(JNIEnv* jni);
187
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000188 // Search for H.264 start codes.
189 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
190
191 // Type of video codec.
192 VideoCodecType codecType_;
193
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000194 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
195 // |codec_thread_| synchronously.
196 webrtc::EncodedImageCallback* callback_;
197
198 // State that is constant for the lifetime of this object once the ctor
199 // returns.
200 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800201 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000202 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
203 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
204 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800205 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000206 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800207 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800208 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000209 jmethodID j_release_method_;
210 jmethodID j_set_rates_method_;
211 jmethodID j_dequeue_output_buffer_method_;
212 jmethodID j_release_output_buffer_method_;
213 jfieldID j_color_format_field_;
214 jfieldID j_info_index_field_;
215 jfieldID j_info_buffer_field_;
216 jfieldID j_info_is_key_frame_field_;
217 jfieldID j_info_presentation_timestamp_us_field_;
218
219 // State that is valid only between InitEncode() and the next Release().
220 // Touched only on codec_thread_ so no explicit synchronization necessary.
221 int width_; // Frame width in pixels.
222 int height_; // Frame height in pixels.
223 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800224 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000225 uint16_t picture_id_;
226 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
227 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
228 int last_set_fps_; // Last-requested frame rate.
229 int64_t current_timestamp_us_; // Current frame timestamps in us.
230 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000231 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800232 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
233 // Number of dropped frames caused by full queue.
234 int consecutive_full_queue_frame_drops_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000235 int frames_in_queue_; // Number of frames in encoder queue.
236 int64_t start_time_ms_; // Start time for statistics.
237 int current_frames_; // Number of frames in the current statistics interval.
238 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800239 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000240 int current_encoding_time_ms_; // Overall encoding time in the current second
241 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
242 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
243 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
244 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
245 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
246 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000247 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
248 int64_t output_render_time_ms_; // Last output frame render time from
249 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000250 // Frame size in bytes fed to MediaCodec.
251 int yuv_size_;
252 // True only when between a callback_->Encoded() call return a positive value
253 // and the next Encode() call being ignored.
254 bool drop_next_input_frame_;
255 // Global references; must be deleted in Release().
256 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200257 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700258 // Dynamic resolution change, off by default.
259 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200260
261 // H264 bitstream parser, used to extract QP from encoded bitstreams.
262 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800263
264 // VP9 variables to populate codec specific structure.
265 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
266 // non-flexible VP9 mode.
267 uint8_t tl0_pic_idx_;
268 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800269
270 // EGL context - owned by factory, should not be allocated/destroyed
271 // by MediaCodecVideoEncoder.
272 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800273
274 // Temporary fix for VP8.
275 // Sends a key frame if frames are largely spaced apart (possibly
276 // corresponding to a large image change).
277 int64_t last_frame_received_ms_;
278 int frames_received_since_last_key_;
279 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000280};
281
282MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
283 // Call Release() to ensure no more callbacks to us after we are deleted.
284 Release();
285}
286
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000287MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800288 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000289 codecType_(codecType),
290 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000291 codec_thread_(new Thread()),
292 j_media_codec_video_encoder_class_(
293 jni,
294 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
295 j_media_codec_video_encoder_(
296 jni,
297 jni->NewObject(*j_media_codec_video_encoder_class_,
298 GetMethodID(jni,
299 *j_media_codec_video_encoder_class_,
300 "<init>",
perkj30e91822015-11-20 01:31:25 -0800301 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800302 inited_(false),
303 use_surface_(false),
304 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800305 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000306 ScopedLocalRefFrame local_ref_frame(jni);
307 // It would be nice to avoid spinning up a new thread per MediaCodec, and
308 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
309 // 2732 means that deadlocks abound. This class synchronously trampolines
310 // to |codec_thread_|, so if anything else can be coming to _us_ from
311 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
312 // in the bug, we have a problem. For now work around that with a dedicated
313 // thread.
314 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700315 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800316 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000317 jclass j_output_buffer_info_class =
318 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000319 j_init_encode_method_ = GetMethodID(
320 jni,
321 *j_media_codec_video_encoder_class_,
322 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800323 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800324 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800325 j_get_input_buffers_method_ = GetMethodID(
326 jni,
327 *j_media_codec_video_encoder_class_,
328 "getInputBuffers",
329 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000330 j_dequeue_input_buffer_method_ = GetMethodID(
331 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800332 j_encode_buffer_method_ = GetMethodID(
333 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800334 j_encode_texture_method_ = GetMethodID(
335 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
336 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000337 j_release_method_ =
338 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
339 j_set_rates_method_ = GetMethodID(
340 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000341 j_dequeue_output_buffer_method_ = GetMethodID(
342 jni,
343 *j_media_codec_video_encoder_class_,
344 "dequeueOutputBuffer",
345 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000346 j_release_output_buffer_method_ = GetMethodID(
347 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
348
349 j_color_format_field_ =
350 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
351 j_info_index_field_ =
352 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
353 j_info_buffer_field_ = GetFieldID(
354 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
355 j_info_is_key_frame_field_ =
356 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
357 j_info_presentation_timestamp_us_field_ = GetFieldID(
358 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
359 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800360 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000361 AllowBlockingCalls();
362}
363
364int32_t MediaCodecVideoEncoder::InitEncode(
365 const webrtc::VideoCodec* codec_settings,
366 int32_t /* number_of_cores */,
367 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700368 const int kMinWidth = 320;
369 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700370 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000371 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700372 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000373 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
374 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000375 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700376 RTC_CHECK(codec_settings->codecType == codecType_)
377 << "Unsupported codec " << codec_settings->codecType << " for "
378 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000379
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700380 ALOGD << "InitEncode request";
asapersson1d61a512016-01-20 01:13:46 -0800381 codec_mode_ = codec_settings->mode;
Alex Glaznevad948c42015-11-18 13:06:42 -0800382 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
383 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700384 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200385 if (scale_) {
386 if (codecType_ == kVideoCodecVP8) {
387 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
388 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
389 // always = 127. Note that in SW, QP is that of the user-level range [0,
390 // 63].
391 const int kMaxQp = 127;
glaznev919ff752016-01-27 15:01:03 -0800392 const int kBadQpThreshold = 95;
393 quality_scaler_.Init(
394 kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold, false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200395 } else if (codecType_ == kVideoCodecH264) {
396 // H264 QP is in the range [0, 51].
397 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200398 const int kBadQpThreshold = 40;
glaznev919ff752016-01-27 15:01:03 -0800399 quality_scaler_.Init(
400 kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold, false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200401 } else {
402 // When adding codec support to additional hardware codecs, also configure
403 // their QP thresholds for scaling.
404 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
405 }
406 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
407 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700408 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000409 return codec_thread_->Invoke<int32_t>(
410 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
411 this,
412 codec_settings->width,
413 codec_settings->height,
414 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800415 codec_settings->maxFramerate,
416 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000417}
418
419int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700420 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000421 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700422 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000423 return codec_thread_->Invoke<int32_t>(Bind(
424 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
425}
426
427int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
428 webrtc::EncodedImageCallback* callback) {
429 return codec_thread_->Invoke<int32_t>(
430 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
431 this,
432 callback));
433}
434
435int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700436 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000437 return codec_thread_->Invoke<int32_t>(
438 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
439}
440
441int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
442 int64_t /* rtt */) {
443 return WEBRTC_VIDEO_CODEC_OK;
444}
445
446int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
447 uint32_t frame_rate) {
448 return codec_thread_->Invoke<int32_t>(
449 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
450 this,
451 new_bit_rate,
452 frame_rate));
453}
454
455void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800456 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000457 JNIEnv* jni = AttachCurrentThreadIfNeeded();
458 ScopedLocalRefFrame local_ref_frame(jni);
459
460 // We only ever send one message to |this| directly (not through a Bind()'d
461 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700462 RTC_CHECK(!msg->message_id) << "Unexpected message!";
463 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000464 if (!inited_) {
465 return;
466 }
467
468 // It would be nice to recover from a failure here if one happened, but it's
469 // unclear how to signal such a failure to the app, so instead we stay silent
470 // about it and let the next app-called API method reveal the borkedness.
471 DeliverPendingOutputs(jni);
472 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
473}
474
perkj9576e542015-11-12 06:43:16 -0800475bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
476 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
477 ALOGE << "ResetOnCodecThread";
478 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800479 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
480 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000481 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
482 // degrade to a SW encoder at this point? There isn't one AFAICT :(
483 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800484 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485 }
perkj9576e542015-11-12 06:43:16 -0800486 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000487}
488
489int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800490 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800491 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800492 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000493 JNIEnv* jni = AttachCurrentThreadIfNeeded();
494 ScopedLocalRefFrame local_ref_frame(jni);
495
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700496 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
497 width << " x " << height << ". Bitrate: " << kbps <<
498 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000499 if (kbps == 0) {
500 kbps = last_set_bitrate_kbps_;
501 }
502 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800503 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000504 }
505
506 width_ = width;
507 height_ = height;
508 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800509 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000510 yuv_size_ = width_ * height_ * 3 / 2;
511 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000512 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800513 frames_dropped_media_encoder_ = 0;
514 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 frames_in_queue_ = 0;
516 current_timestamp_us_ = 0;
517 start_time_ms_ = GetCurrentTimeMs();
518 current_frames_ = 0;
519 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800520 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 current_encoding_time_ms_ = 0;
522 last_input_timestamp_ms_ = -1;
523 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000524 output_timestamp_ = 0;
525 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000526 timestamps_.clear();
527 render_times_ms_.clear();
528 frame_rtc_times_ms_.clear();
529 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800530 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000531 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800532 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
533 tl0_pic_idx_ = static_cast<uint8_t>(rand());
534 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800535 last_frame_received_ms_ = -1;
536 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800537
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100539 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000540 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800541 const bool encode_status = jni->CallBooleanMethod(
542 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800543 j_video_codec_enum, width, height, kbps, fps,
544 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800545 if (!encode_status) {
546 ALOGE << "Failed to configure encoder.";
547 return WEBRTC_VIDEO_CODEC_ERROR;
548 }
549 CHECK_EXCEPTION(jni);
550
Per598242a2015-11-26 14:28:55 +0100551 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800552 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
553 jni->CallObjectMethod(*j_media_codec_video_encoder_,
554 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000555 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800556 if (IsNull(jni, input_buffers)) {
557 return WEBRTC_VIDEO_CODEC_ERROR;
558 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000559
perkj30e91822015-11-20 01:31:25 -0800560 switch (GetIntField(jni, *j_media_codec_video_encoder_,
561 j_color_format_field_)) {
562 case COLOR_FormatYUV420Planar:
563 encoder_fourcc_ = libyuv::FOURCC_YU12;
564 break;
565 case COLOR_FormatYUV420SemiPlanar:
566 case COLOR_QCOM_FormatYUV420SemiPlanar:
567 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
568 encoder_fourcc_ = libyuv::FOURCC_NV12;
569 break;
570 default:
571 LOG(LS_ERROR) << "Wrong color format.";
572 return WEBRTC_VIDEO_CODEC_ERROR;
573 }
574 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
575 RTC_CHECK(input_buffers_.empty())
576 << "Unexpected double InitEncode without Release";
577 input_buffers_.resize(num_input_buffers);
578 for (size_t i = 0; i < num_input_buffers; ++i) {
579 input_buffers_[i] =
580 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
581 int64_t yuv_buffer_capacity =
582 jni->GetDirectBufferCapacity(input_buffers_[i]);
583 CHECK_EXCEPTION(jni);
584 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
585 }
586 }
perkj9576e542015-11-12 06:43:16 -0800587
588 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000589 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
590 return WEBRTC_VIDEO_CODEC_OK;
591}
592
593int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700594 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700595 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800596 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000597 JNIEnv* jni = AttachCurrentThreadIfNeeded();
598 ScopedLocalRefFrame local_ref_frame(jni);
599
600 if (!inited_) {
601 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
602 }
perkj9576e542015-11-12 06:43:16 -0800603
asapersson1d61a512016-01-20 01:13:46 -0800604 bool send_key_frame = false;
605 if (codecType_ == kVideoCodecVP8 && codec_mode_ == webrtc::kRealtimeVideo) {
606 ++frames_received_since_last_key_;
607 int64_t now_ms = GetCurrentTimeMs();
608 if (last_frame_received_ms_ != -1 &&
609 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
610 // Add limit to prevent triggering a key for every frame for very low
611 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
612 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
613 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
614 send_key_frame = true;
615 }
616 frames_received_since_last_key_ = 0;
617 }
618 last_frame_received_ms_ = now_ms;
619 }
620
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000621 frames_received_++;
622 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800623 if (!ResetCodecOnCodecThread())
624 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000625 }
glaznevf4decb52016-01-15 13:49:22 -0800626 if (frames_encoded_ < kMaxEncodedLogFrames) {
627 ALOGD << "Encoder frame in # " << (frames_received_ - 1) << ". TS: " <<
628 (int)(current_timestamp_us_ / 1000) << ". Q: " << frames_in_queue_ <<
629 ". Fps: " << last_set_fps_ << ". Kbps: " << last_set_bitrate_kbps_;
630 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000631
632 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800633 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000634 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800635 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800636 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800637 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000638 return WEBRTC_VIDEO_CODEC_OK;
639 }
640
henrikg91d6ede2015-09-17 00:24:34 -0700641 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200642
glaznevf4decb52016-01-15 13:49:22 -0800643 // Check if we accumulated too many frames in encoder input buffers
644 // or the encoder latency exceeds 70 ms and drop frame if so.
645 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
646 int encoder_latency_ms = last_input_timestamp_ms_ -
647 last_output_timestamp_ms_;
648 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE ||
649 encoder_latency_ms > MAX_ENCODER_LATENCY_MS) {
650 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
glaznev919ff752016-01-27 15:01:03 -0800651 " ms. Q size: " << frames_in_queue_ << ". Consecutive drops: " <<
652 consecutive_full_queue_frame_drops_;
glaznevf4decb52016-01-15 13:49:22 -0800653 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800654 consecutive_full_queue_frame_drops_++;
655 if (consecutive_full_queue_frame_drops_ >=
656 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
657 ALOGE << "Encoder got stuck. Reset.";
658 ResetCodecOnCodecThread();
659 return WEBRTC_VIDEO_CODEC_ERROR;
660 }
661 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800662 OnDroppedFrame();
663 return WEBRTC_VIDEO_CODEC_OK;
664 }
665 }
glaznev919ff752016-01-27 15:01:03 -0800666 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800667
Per598242a2015-11-26 14:28:55 +0100668 VideoFrame input_frame = frame;
669 if (scale_) {
670 // Check framerate before spatial resolution change.
671 quality_scaler_.OnEncodeFrame(frame);
672 const webrtc::QualityScaler::Resolution scaled_resolution =
673 quality_scaler_.GetScaledResolution();
674 if (scaled_resolution.width != frame.width() ||
675 scaled_resolution.height != frame.height()) {
676 if (frame.native_handle() != nullptr) {
677 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
678 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100679 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100680 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100681 scaled_resolution.height,
682 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100683 input_frame.set_video_frame_buffer(scaled_buffer);
684 } else {
685 input_frame = quality_scaler_.GetScaledFrame(frame);
686 }
687 }
688 }
jackychen61b4d512015-04-21 15:30:11 -0700689
perkj9576e542015-11-12 06:43:16 -0800690 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
691 ALOGE << "Failed to reconfigure encoder.";
692 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000693 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000694
glaznevf4decb52016-01-15 13:49:22 -0800695 // Save time when input frame is sent to the encoder input.
696 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000697
asapersson1d61a512016-01-20 01:13:46 -0800698 const bool key_frame =
699 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800700 bool encode_status = true;
701 if (!input_frame.native_handle()) {
702 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
703 j_dequeue_input_buffer_method_);
704 CHECK_EXCEPTION(jni);
705 if (j_input_buffer_index == -1) {
706 // Video codec falls behind - no input buffer available.
707 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800708 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800709 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
710 frames_dropped_media_encoder_++;
711 OnDroppedFrame();
perkj30e91822015-11-20 01:31:25 -0800712 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
713 }
714 if (j_input_buffer_index == -2) {
715 ResetCodecOnCodecThread();
716 return WEBRTC_VIDEO_CODEC_ERROR;
717 }
718 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
719 j_input_buffer_index);
720 } else {
721 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000722 }
perkj30e91822015-11-20 01:31:25 -0800723
724 if (!encode_status) {
725 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800726 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200727 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000728 }
729
perkj9576e542015-11-12 06:43:16 -0800730 last_input_timestamp_ms_ =
731 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200732 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000733
perkj12f68022015-10-16 13:31:45 +0200734 // Save input image timestamps for later output
735 timestamps_.push_back(input_frame.timestamp());
736 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800737 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
738
perkj30e91822015-11-20 01:31:25 -0800739 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800740 ALOGE << "Failed deliver pending outputs.";
741 ResetCodecOnCodecThread();
742 return WEBRTC_VIDEO_CODEC_ERROR;
743 }
744 return WEBRTC_VIDEO_CODEC_OK;
745}
746
747bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
748 const webrtc::VideoFrame& frame) {
749 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
750
perkj30e91822015-11-20 01:31:25 -0800751 const bool is_texture_frame = frame.native_handle() != nullptr;
752 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800753 const bool reconfigure_due_to_size =
754 frame.width() != width_ || frame.height() != height_;
755
perkj30e91822015-11-20 01:31:25 -0800756 if (reconfigure_due_to_format) {
757 ALOGD << "Reconfigure encoder due to format change. "
758 << (use_surface_ ?
759 "Reconfiguring to encode from byte buffer." :
760 "Reconfiguring to encode from texture.");
761 }
perkj9576e542015-11-12 06:43:16 -0800762 if (reconfigure_due_to_size) {
763 ALOGD << "Reconfigure encoder due to frame resolution change from "
764 << width_ << " x " << height_ << " to " << frame.width() << " x "
765 << frame.height();
766 width_ = frame.width();
767 height_ = frame.height();
768 }
769
perkj30e91822015-11-20 01:31:25 -0800770 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800771 return true;
772
773 ReleaseOnCodecThread();
774
perkj30e91822015-11-20 01:31:25 -0800775 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800776 WEBRTC_VIDEO_CODEC_OK;
777}
778
779bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
780 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
781 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800782 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800783
perkj9576e542015-11-12 06:43:16 -0800784 jobject j_input_buffer = input_buffers_[input_buffer_index];
785 uint8_t* yuv_buffer =
786 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
787 CHECK_EXCEPTION(jni);
788 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
789 RTC_CHECK(!libyuv::ConvertFromI420(
790 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
791 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
792 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
793 yuv_buffer, width_, width_, height_, encoder_fourcc_))
794 << "ConvertFromI420 failed";
795
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000796 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800797 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000798 key_frame,
perkj9576e542015-11-12 06:43:16 -0800799 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000800 yuv_size_,
801 current_timestamp_us_);
802 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800803 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000804}
805
perkj30e91822015-11-20 01:31:25 -0800806bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
807 bool key_frame, const webrtc::VideoFrame& frame) {
808 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
809 RTC_CHECK(use_surface_);
810 NativeHandleImpl* handle =
811 static_cast<NativeHandleImpl*>(frame.native_handle());
812 jfloatArray sampling_matrix = jni->NewFloatArray(16);
813 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
814
815 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
816 j_encode_texture_method_,
817 key_frame,
818 handle->oes_texture_id,
819 sampling_matrix,
820 current_timestamp_us_);
821 CHECK_EXCEPTION(jni);
822 return encode_status;
823}
824
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000825int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
826 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800827 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000828 JNIEnv* jni = AttachCurrentThreadIfNeeded();
829 ScopedLocalRefFrame local_ref_frame(jni);
830 callback_ = callback;
831 return WEBRTC_VIDEO_CODEC_OK;
832}
833
834int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800835 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000836 if (!inited_) {
837 return WEBRTC_VIDEO_CODEC_OK;
838 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000839 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700840 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
841 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800842 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000843 ScopedLocalRefFrame local_ref_frame(jni);
844 for (size_t i = 0; i < input_buffers_.size(); ++i)
845 jni->DeleteGlobalRef(input_buffers_[i]);
846 input_buffers_.clear();
847 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
848 CHECK_EXCEPTION(jni);
849 rtc::MessageQueueManager::Clear(this);
850 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800851 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700852 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000853 return WEBRTC_VIDEO_CODEC_OK;
854}
855
856int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
857 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800858 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800859 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
860 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000861 if (last_set_bitrate_kbps_ == new_bit_rate &&
862 last_set_fps_ == frame_rate) {
863 return WEBRTC_VIDEO_CODEC_OK;
864 }
glaznev919ff752016-01-27 15:01:03 -0800865 if (scale_) {
866 quality_scaler_.ReportFramerate(frame_rate);
867 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000868 JNIEnv* jni = AttachCurrentThreadIfNeeded();
869 ScopedLocalRefFrame local_ref_frame(jni);
870 if (new_bit_rate > 0) {
871 last_set_bitrate_kbps_ = new_bit_rate;
872 }
873 if (frame_rate > 0) {
874 last_set_fps_ = frame_rate;
875 }
876 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
877 j_set_rates_method_,
878 last_set_bitrate_kbps_,
879 last_set_fps_);
880 CHECK_EXCEPTION(jni);
881 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800882 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000883 return WEBRTC_VIDEO_CODEC_ERROR;
884 }
885 return WEBRTC_VIDEO_CODEC_OK;
886}
887
888int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
889 JNIEnv* jni,
890 jobject j_output_buffer_info) {
891 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
892}
893
894jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
895 JNIEnv* jni,
896 jobject j_output_buffer_info) {
897 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
898}
899
900bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
901 JNIEnv* jni,
902 jobject j_output_buffer_info) {
903 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
904}
905
906jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
907 JNIEnv* jni,
908 jobject j_output_buffer_info) {
909 return GetLongField(
910 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
911}
912
913bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800914 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000915 while (true) {
916 jobject j_output_buffer_info = jni->CallObjectMethod(
917 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
918 CHECK_EXCEPTION(jni);
919 if (IsNull(jni, j_output_buffer_info)) {
920 break;
921 }
922
923 int output_buffer_index =
924 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
925 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800926 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000927 return false;
928 }
929
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000930 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000931 jobject j_output_buffer =
932 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
933 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000934
935 // Get frame timestamps from a queue - for non config frames only.
936 int64_t frame_encoding_time_ms = 0;
937 last_output_timestamp_ms_ =
938 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
939 1000;
940 if (frames_in_queue_ > 0) {
941 output_timestamp_ = timestamps_.front();
942 timestamps_.erase(timestamps_.begin());
943 output_render_time_ms_ = render_times_ms_.front();
944 render_times_ms_.erase(render_times_ms_.begin());
945 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
946 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
947 frames_in_queue_--;
948 }
949
950 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000951 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200952 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000953 jni->GetDirectBufferAddress(j_output_buffer));
954 CHECK_EXCEPTION(jni);
955
glaznevf4decb52016-01-15 13:49:22 -0800956 if (frames_encoded_ < kMaxEncodedLogFrames) {
957 ALOGD << "Encoder frame out # " << frames_encoded_ << ". Key: " <<
958 key_frame << ". Size: " << payload_size << ". TS: " <<
959 (int)last_output_timestamp_ms_ << ". Latency: " <<
960 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_) <<
961 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000962 }
963
964 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000965 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000966 if (callback_) {
967 scoped_ptr<webrtc::EncodedImage> image(
968 new webrtc::EncodedImage(payload, payload_size, payload_size));
969 image->_encodedWidth = width_;
970 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000971 image->_timeStamp = output_timestamp_;
972 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200973 image->_frameType =
974 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000975 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700976 image->adapt_reason_.quality_resolution_downscales =
977 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000978
979 webrtc::CodecSpecificInfo info;
980 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000981 info.codecType = codecType_;
982 if (codecType_ == kVideoCodecVP8) {
983 info.codecSpecific.VP8.pictureId = picture_id_;
984 info.codecSpecific.VP8.nonReference = false;
985 info.codecSpecific.VP8.simulcastIdx = 0;
986 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
987 info.codecSpecific.VP8.layerSync = false;
988 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
989 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800990 } else if (codecType_ == kVideoCodecVP9) {
991 if (key_frame) {
992 gof_idx_ = 0;
993 }
994 info.codecSpecific.VP9.picture_id = picture_id_;
995 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
996 info.codecSpecific.VP9.flexible_mode = false;
997 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
998 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
999 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1000 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1001 info.codecSpecific.VP9.temporal_up_switch = true;
1002 info.codecSpecific.VP9.inter_layer_predicted = false;
1003 info.codecSpecific.VP9.gof_idx =
1004 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1005 info.codecSpecific.VP9.num_spatial_layers = 1;
1006 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1007 if (info.codecSpecific.VP9.ss_data_available) {
1008 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1009 info.codecSpecific.VP9.width[0] = width_;
1010 info.codecSpecific.VP9.height[0] = height_;
1011 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1012 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001013 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001014 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001015
1016 // Generate a header describing a single fragment.
1017 webrtc::RTPFragmentationHeader header;
1018 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001019 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001020 header.VerifyAndAllocateFragmentationHeader(1);
1021 header.fragmentationOffset[0] = 0;
1022 header.fragmentationLength[0] = image->_length;
1023 header.fragmentationPlType[0] = 0;
1024 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001025 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001026 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001027 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1028 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001029 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001030 }
asapersson86b01602015-10-20 23:55:26 -07001031 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001032 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001033 if (scale_) {
1034 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1035 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001036 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1037 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001038 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001039 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001040 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001041 // For H.264 search for start codes.
1042 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1043 int32_t scPositionsLength = 0;
1044 int32_t scPosition = 0;
1045 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1046 int32_t naluPosition = NextNaluPosition(
1047 payload + scPosition, payload_size - scPosition);
1048 if (naluPosition < 0) {
1049 break;
1050 }
1051 scPosition += naluPosition;
1052 scPositions[scPositionsLength++] = scPosition;
1053 scPosition += H264_SC_LENGTH;
1054 }
1055 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001056 ALOGE << "Start code is not found!";
1057 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1058 << " " << image->_buffer[2] << " " << image->_buffer[3]
1059 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001060 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001061 return false;
1062 }
1063 scPositions[scPositionsLength] = payload_size;
1064 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1065 for (size_t i = 0; i < scPositionsLength; i++) {
1066 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1067 header.fragmentationLength[i] =
1068 scPositions[i + 1] - header.fragmentationOffset[i];
1069 header.fragmentationPlType[i] = 0;
1070 header.fragmentationTimeDiff[i] = 0;
1071 }
1072 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001073
1074 callback_status = callback_->Encoded(*image, &info, &header);
1075 }
1076
1077 // Return output buffer back to the encoder.
1078 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1079 j_release_output_buffer_method_,
1080 output_buffer_index);
1081 CHECK_EXCEPTION(jni);
1082 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001083 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001084 return false;
1085 }
1086
glaznevf4decb52016-01-15 13:49:22 -08001087 // Calculate and print encoding statistics - every 3 seconds.
1088 frames_encoded_++;
1089 current_frames_++;
1090 current_bytes_ += payload_size;
1091 current_encoding_time_ms_ += frame_encoding_time_ms;
1092 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
1093 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
1094 current_frames_ > 0) {
1095 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
1096 (current_bytes_ * 8 / statistic_time_ms) <<
1097 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
1098 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
1099 << ", encTime: " <<
1100 (current_encoding_time_ms_ / current_frames_) << ". QP: " <<
1101 (current_acc_qp_ / current_frames_) << " for last " <<
1102 statistic_time_ms << " ms.";
1103 start_time_ms_ = GetCurrentTimeMs();
1104 current_frames_ = 0;
1105 current_bytes_ = 0;
1106 current_acc_qp_ = 0;
1107 current_encoding_time_ms_ = 0;
1108 }
1109
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001110 if (callback_status > 0) {
1111 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001112 // Theoretically could handle callback_status<0 here, but unclear what
1113 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001114 }
1115 }
1116
1117 return true;
1118}
1119
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001120int32_t MediaCodecVideoEncoder::NextNaluPosition(
1121 uint8_t *buffer, size_t buffer_size) {
1122 if (buffer_size < H264_SC_LENGTH) {
1123 return -1;
1124 }
1125 uint8_t *head = buffer;
1126 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1127 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1128 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1129
1130 while (head < end) {
1131 if (head[0]) {
1132 head++;
1133 continue;
1134 }
1135 if (head[1]) { // got 00xx
1136 head += 2;
1137 continue;
1138 }
1139 if (head[2]) { // got 0000xx
1140 head += 3;
1141 continue;
1142 }
1143 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001144 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001145 continue;
1146 }
1147 return (int32_t)(head - buffer);
1148 }
1149 return -1;
1150}
1151
jackychen61b4d512015-04-21 15:30:11 -07001152void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001153 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001154 if (scale_)
1155 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001156}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001157
jackychen6e2ce6e2015-07-13 16:26:33 -07001158int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001159 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001160}
1161
Peter Boströmb7d9a972015-12-18 16:01:11 +01001162const char* MediaCodecVideoEncoder::ImplementationName() const {
1163 return "MediaCodec";
1164}
1165
Perec2922f2016-01-27 15:25:46 +01001166MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001167 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1168 ScopedLocalRefFrame local_ref_frame(jni);
1169 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001170 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001171
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001172 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1173 j_encoder_class,
1174 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1175 CHECK_EXCEPTION(jni);
1176 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001177 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001178 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1179 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1180 }
1181
Alex Glaznevad948c42015-11-18 13:06:42 -08001182 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1183 j_encoder_class,
1184 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1185 CHECK_EXCEPTION(jni);
1186 if (is_vp9_hw_supported) {
1187 ALOGD << "VP9 HW Encoder supported.";
1188 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1189 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1190 }
1191
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001192 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1193 j_encoder_class,
1194 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1195 CHECK_EXCEPTION(jni);
1196 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001197 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001198 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1199 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1200 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001201}
1202
Perec2922f2016-01-27 15:25:46 +01001203MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1204 ALOGD << "MediaCodecVideoEncoderFactory dtor";
1205}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001206
perkj30e91822015-11-20 01:31:25 -08001207void MediaCodecVideoEncoderFactory::SetEGLContext(
1208 JNIEnv* jni, jobject render_egl_context) {
1209 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perec2922f2016-01-27 15:25:46 +01001210 if (!egl_base_.CreateEglBase(jni, render_egl_context)) {
1211 ALOGW << "Invalid EGL context - HW surface encoding is disabled.";
perkj30e91822015-11-20 01:31:25 -08001212 }
1213}
1214
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001215webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001216 VideoCodecType type) {
1217 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001218 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001219 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001220 }
1221 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1222 it != supported_codecs_.end(); ++it) {
1223 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001224 ALOGD << "Create HW video encoder for type " << (int)type <<
1225 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001226 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
Perec2922f2016-01-27 15:25:46 +01001227 egl_base_.egl_base_context());
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001228 }
1229 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001230 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001231 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001232}
1233
1234const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1235MediaCodecVideoEncoderFactory::codecs() const {
1236 return supported_codecs_;
1237}
1238
1239void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1240 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001241 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001242 delete encoder;
1243}
1244
1245} // namespace webrtc_jni
1246