blob: dba71acac93b7aba41483ba364b663ddfd6be2d8 [file] [log] [blame]
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2015 The WebRTC project authors. All Rights Reserved.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00009 */
10
kjellandera96e2d72016-02-04 23:52:28 -080011// NOTICE: androidmediaencoder_jni.h must be included before
12// androidmediacodeccommon.h to avoid build errors.
Henrik Kjellander15583c12016-02-10 10:53:12 +010013#include "webrtc/api/java/jni/androidmediaencoder_jni.h"
14
kjellandera96e2d72016-02-04 23:52:28 -080015#include "third_party/libyuv/include/libyuv/convert.h"
16#include "third_party/libyuv/include/libyuv/convert_from.h"
17#include "third_party/libyuv/include/libyuv/video_common.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/java/jni/androidmediacodeccommon.h"
19#include "webrtc/api/java/jni/classreferenceholder.h"
20#include "webrtc/api/java/jni/native_handle_impl.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000021#include "webrtc/base/bind.h"
22#include "webrtc/base/checks.h"
23#include "webrtc/base/logging.h"
24#include "webrtc/base/thread.h"
perkj9576e542015-11-12 06:43:16 -080025#include "webrtc/base/thread_checker.h"
asapersson1d61a512016-01-20 01:13:46 -080026#include "webrtc/common_types.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020027#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080028#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010029#include "webrtc/modules/video_coding/utility/quality_scaler.h"
30#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010031#include "webrtc/system_wrappers/include/field_trial.h"
32#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000033
34using rtc::Bind;
35using rtc::Thread;
36using rtc::ThreadManager;
37using rtc::scoped_ptr;
38
39using webrtc::CodecSpecificInfo;
40using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070041using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000042using webrtc::RTPFragmentationHeader;
43using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000044using webrtc::VideoCodecType;
45using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000046using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080047using webrtc::kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -080048using webrtc::QualityScaler;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000049
50namespace webrtc_jni {
51
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000052// H.264 start code length.
53#define H264_SC_LENGTH 4
54// Maximum allowed NALUs in one output frame.
55#define MAX_NALUS_PERFRAME 32
56// Maximum supported HW video encoder resolution.
57#define MAX_VIDEO_WIDTH 1280
58#define MAX_VIDEO_HEIGHT 1280
59// Maximum supported HW video encoder fps.
60#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080061// Maximum allowed fps value in SetRates() call.
62#define MAX_ALLOWED_VIDEO_FPS 60
63// Maximum allowed frames in encoder input queue.
64#define MAX_ENCODER_Q_SIZE 2
glaznev919ff752016-01-27 15:01:03 -080065// Maximum amount of dropped frames caused by full encoder queue - exceeding
66// this threshold means that encoder probably got stuck and need to be reset.
67#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080068
69// Logging macros.
70#define TAG_ENCODER "MediaCodecVideoEncoder"
71#ifdef TRACK_BUFFER_TIMING
72#define ALOGV(...)
73 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
74#else
75#define ALOGV(...)
76#endif
77#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
78#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
79#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000080
asapersson1d61a512016-01-20 01:13:46 -080081namespace {
82// Maximum time limit between incoming frames before requesting a key frame.
83const size_t kFrameDiffThresholdMs = 1100;
84const int kMinKeyFrameInterval = 2;
85} // namespace
86
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000087// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
88// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
89// HW-backed video encode. This C++ class is implemented as a very thin shim,
90// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
91// MediaCodecVideoEncoder is created, operated, and destroyed on a single
92// thread, currently the libjingle Worker thread.
93class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
94 public rtc::MessageHandler {
95 public:
96 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -080097 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -080098 VideoCodecType codecType,
99 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000100
101 // webrtc::VideoEncoder implementation. Everything trampolines to
102 // |codec_thread_| for execution.
103 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
104 int32_t /* number_of_cores */,
105 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700106 int32_t Encode(const webrtc::VideoFrame& input_image,
107 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
108 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000109 int32_t RegisterEncodeCompleteCallback(
110 webrtc::EncodedImageCallback* callback) override;
111 int32_t Release() override;
112 int32_t SetChannelParameters(uint32_t /* packet_loss */,
113 int64_t /* rtt */) override;
114 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
115
116 // rtc::MessageHandler implementation.
117 void OnMessage(rtc::Message* msg) override;
118
jackychen61b4d512015-04-21 15:30:11 -0700119 void OnDroppedFrame() override;
120
jackychen6e2ce6e2015-07-13 16:26:33 -0700121 int GetTargetFramerate() override;
122
Perec2922f2016-01-27 15:25:46 +0100123 bool SupportsNativeHandle() const override { return egl_context_ != nullptr; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100124 const char* ImplementationName() const override;
125
126 private:
127 // CHECK-fail if not running on |codec_thread_|.
128 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800129
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000130 private:
perkj9576e542015-11-12 06:43:16 -0800131 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
132 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000133 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800134 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000135
136 // Implementation of webrtc::VideoEncoder methods above, all running on the
137 // codec thread exclusively.
138 //
139 // If width==0 then this is assumed to be a re-initialization and the
140 // previously-current values are reused instead of the passed parameters
141 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800142 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
143 bool use_surface);
144 // Reconfigure to match |frame| in width, height. Also reconfigures the
145 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
146 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800147 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000148 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700149 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700150 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800151 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
152 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800153 bool EncodeTextureOnCodecThread(JNIEnv* jni,
154 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800155
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000156 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
157 webrtc::EncodedImageCallback* callback);
158 int32_t ReleaseOnCodecThread();
159 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
160
161 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
162 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
163 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
164 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
165 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000166 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000167
168 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
169 // true on success.
170 bool DeliverPendingOutputs(JNIEnv* jni);
171
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000172 // Search for H.264 start codes.
173 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
174
glaznev94291482016-02-01 13:17:18 -0800175 // Displays encoder statistics.
176 void LogStatistics(bool force_log);
177
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000178 // Type of video codec.
179 VideoCodecType codecType_;
180
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000181 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
182 // |codec_thread_| synchronously.
183 webrtc::EncodedImageCallback* callback_;
184
185 // State that is constant for the lifetime of this object once the ctor
186 // returns.
187 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800188 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000189 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
190 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
191 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800192 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000193 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800194 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800195 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000196 jmethodID j_release_method_;
197 jmethodID j_set_rates_method_;
198 jmethodID j_dequeue_output_buffer_method_;
199 jmethodID j_release_output_buffer_method_;
200 jfieldID j_color_format_field_;
201 jfieldID j_info_index_field_;
202 jfieldID j_info_buffer_field_;
203 jfieldID j_info_is_key_frame_field_;
204 jfieldID j_info_presentation_timestamp_us_field_;
205
206 // State that is valid only between InitEncode() and the next Release().
207 // Touched only on codec_thread_ so no explicit synchronization necessary.
208 int width_; // Frame width in pixels.
209 int height_; // Frame height in pixels.
210 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800211 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000212 uint16_t picture_id_;
213 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
214 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
215 int last_set_fps_; // Last-requested frame rate.
216 int64_t current_timestamp_us_; // Current frame timestamps in us.
217 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000218 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800219 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
220 // Number of dropped frames caused by full queue.
221 int consecutive_full_queue_frame_drops_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000222 int frames_in_queue_; // Number of frames in encoder queue.
glaznev94291482016-02-01 13:17:18 -0800223 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000224 int current_frames_; // Number of frames in the current statistics interval.
225 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800226 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000227 int current_encoding_time_ms_; // Overall encoding time in the current second
228 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
229 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
230 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
231 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
232 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
233 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000234 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
235 int64_t output_render_time_ms_; // Last output frame render time from
236 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000237 // Frame size in bytes fed to MediaCodec.
238 int yuv_size_;
239 // True only when between a callback_->Encoded() call return a positive value
240 // and the next Encode() call being ignored.
241 bool drop_next_input_frame_;
242 // Global references; must be deleted in Release().
243 std::vector<jobject> input_buffers_;
Alex Glazneva9d08922016-02-19 15:24:06 -0800244 QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700245 // Dynamic resolution change, off by default.
246 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200247
248 // H264 bitstream parser, used to extract QP from encoded bitstreams.
249 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800250
251 // VP9 variables to populate codec specific structure.
252 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
253 // non-flexible VP9 mode.
254 uint8_t tl0_pic_idx_;
255 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800256
257 // EGL context - owned by factory, should not be allocated/destroyed
258 // by MediaCodecVideoEncoder.
259 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800260
261 // Temporary fix for VP8.
262 // Sends a key frame if frames are largely spaced apart (possibly
263 // corresponding to a large image change).
264 int64_t last_frame_received_ms_;
265 int frames_received_since_last_key_;
266 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000267};
268
269MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
270 // Call Release() to ensure no more callbacks to us after we are deleted.
271 Release();
272}
273
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000274MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800275 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000276 codecType_(codecType),
277 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000278 codec_thread_(new Thread()),
279 j_media_codec_video_encoder_class_(
280 jni,
281 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
282 j_media_codec_video_encoder_(
283 jni,
284 jni->NewObject(*j_media_codec_video_encoder_class_,
285 GetMethodID(jni,
286 *j_media_codec_video_encoder_class_,
287 "<init>",
perkj30e91822015-11-20 01:31:25 -0800288 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800289 inited_(false),
290 use_surface_(false),
291 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800292 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000293 ScopedLocalRefFrame local_ref_frame(jni);
294 // It would be nice to avoid spinning up a new thread per MediaCodec, and
295 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
296 // 2732 means that deadlocks abound. This class synchronously trampolines
297 // to |codec_thread_|, so if anything else can be coming to _us_ from
298 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
299 // in the bug, we have a problem. For now work around that with a dedicated
300 // thread.
301 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700302 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800303 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000304 jclass j_output_buffer_info_class =
305 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000306 j_init_encode_method_ = GetMethodID(
307 jni,
308 *j_media_codec_video_encoder_class_,
309 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800310 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800311 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800312 j_get_input_buffers_method_ = GetMethodID(
313 jni,
314 *j_media_codec_video_encoder_class_,
315 "getInputBuffers",
316 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000317 j_dequeue_input_buffer_method_ = GetMethodID(
318 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800319 j_encode_buffer_method_ = GetMethodID(
320 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800321 j_encode_texture_method_ = GetMethodID(
322 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
323 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000324 j_release_method_ =
325 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
326 j_set_rates_method_ = GetMethodID(
327 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000328 j_dequeue_output_buffer_method_ = GetMethodID(
329 jni,
330 *j_media_codec_video_encoder_class_,
331 "dequeueOutputBuffer",
332 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000333 j_release_output_buffer_method_ = GetMethodID(
334 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
335
336 j_color_format_field_ =
337 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
338 j_info_index_field_ =
339 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
340 j_info_buffer_field_ = GetFieldID(
341 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
342 j_info_is_key_frame_field_ =
343 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
344 j_info_presentation_timestamp_us_field_ = GetFieldID(
345 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
346 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800347 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000348 AllowBlockingCalls();
349}
350
351int32_t MediaCodecVideoEncoder::InitEncode(
352 const webrtc::VideoCodec* codec_settings,
353 int32_t /* number_of_cores */,
354 size_t /* max_payload_size */) {
Peter Boström01bcbd02016-03-22 21:44:29 +0100355 const int kMinDimension = 180;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000356 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700357 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000358 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
359 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000360 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700361 RTC_CHECK(codec_settings->codecType == codecType_)
362 << "Unsupported codec " << codec_settings->codecType << " for "
363 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000364
asapersson1d61a512016-01-20 01:13:46 -0800365 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800366 int init_width = codec_settings->width;
367 int init_height = codec_settings->height;
Alex Glaznevad948c42015-11-18 13:06:42 -0800368 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
369 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800370
371 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700372 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800373
Peter Boström2bc68c72015-09-24 16:22:28 +0200374 if (scale_) {
375 if (codecType_ == kVideoCodecVP8) {
376 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
377 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
378 // always = 127. Note that in SW, QP is that of the user-level range [0,
379 // 63].
Alex Glazneva9d08922016-02-19 15:24:06 -0800380 const int kLowQpThreshold = 32;
381 const int kBadQpThreshold = 92;
382 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
phoglund19b4fec2016-04-12 09:05:58 -0700383 codec_settings->startBitrate,
384 codec_settings->width, codec_settings->height);
Peter Boström2bc68c72015-09-24 16:22:28 +0200385 } else if (codecType_ == kVideoCodecH264) {
386 // H264 QP is in the range [0, 51].
Alex Glaznev67b81f92016-02-22 15:05:15 -0800387 const int kLowQpThreshold = 21;
388 const int kBadQpThreshold = 36;
Alex Glazneva9d08922016-02-19 15:24:06 -0800389 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
phoglund19b4fec2016-04-12 09:05:58 -0700390 codec_settings->startBitrate,
391 codec_settings->width, codec_settings->height);
Peter Boström2bc68c72015-09-24 16:22:28 +0200392 } else {
393 // When adding codec support to additional hardware codecs, also configure
394 // their QP thresholds for scaling.
395 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800396 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200397 }
Peter Boström01bcbd02016-03-22 21:44:29 +0100398 quality_scaler_.SetMinResolution(kMinDimension, kMinDimension);
phoglund19b4fec2016-04-12 09:05:58 -0700399 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
Alex Glazneva9d08922016-02-19 15:24:06 -0800400 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström01bcbd02016-03-22 21:44:29 +0100401 init_width = std::max(res.width, kMinDimension);
402 init_height = std::max(res.height, kMinDimension);
Alex Glazneva9d08922016-02-19 15:24:06 -0800403 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700404 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800405
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000406 return codec_thread_->Invoke<int32_t>(
407 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
408 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800409 init_width,
410 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000411 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800412 codec_settings->maxFramerate,
413 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000414}
415
416int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700417 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000418 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700419 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000420 return codec_thread_->Invoke<int32_t>(Bind(
421 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
422}
423
424int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
425 webrtc::EncodedImageCallback* callback) {
426 return codec_thread_->Invoke<int32_t>(
427 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
428 this,
429 callback));
430}
431
432int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700433 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000434 return codec_thread_->Invoke<int32_t>(
435 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
436}
437
438int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
439 int64_t /* rtt */) {
440 return WEBRTC_VIDEO_CODEC_OK;
441}
442
443int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
444 uint32_t frame_rate) {
445 return codec_thread_->Invoke<int32_t>(
446 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
447 this,
448 new_bit_rate,
449 frame_rate));
450}
451
452void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800453 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000454 JNIEnv* jni = AttachCurrentThreadIfNeeded();
455 ScopedLocalRefFrame local_ref_frame(jni);
456
457 // We only ever send one message to |this| directly (not through a Bind()'d
458 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700459 RTC_CHECK(!msg->message_id) << "Unexpected message!";
460 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000461 if (!inited_) {
462 return;
463 }
464
465 // It would be nice to recover from a failure here if one happened, but it's
466 // unclear how to signal such a failure to the app, so instead we stay silent
467 // about it and let the next app-called API method reveal the borkedness.
468 DeliverPendingOutputs(jni);
469 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
470}
471
perkj9576e542015-11-12 06:43:16 -0800472bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
473 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
474 ALOGE << "ResetOnCodecThread";
475 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800476 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
477 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000478 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
479 // degrade to a SW encoder at this point? There isn't one AFAICT :(
480 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800481 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000482 }
perkj9576e542015-11-12 06:43:16 -0800483 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000484}
485
486int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800487 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800488 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800489 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000490 JNIEnv* jni = AttachCurrentThreadIfNeeded();
491 ScopedLocalRefFrame local_ref_frame(jni);
492
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700493 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
494 width << " x " << height << ". Bitrate: " << kbps <<
495 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000496 if (kbps == 0) {
497 kbps = last_set_bitrate_kbps_;
498 }
499 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800500 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000501 }
502
503 width_ = width;
504 height_ = height;
505 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800506 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000507 yuv_size_ = width_ * height_ * 3 / 2;
508 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000509 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800510 frames_dropped_media_encoder_ = 0;
511 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000512 frames_in_queue_ = 0;
513 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800514 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 current_frames_ = 0;
516 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800517 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000518 current_encoding_time_ms_ = 0;
519 last_input_timestamp_ms_ = -1;
520 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000521 output_timestamp_ = 0;
522 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000523 timestamps_.clear();
524 render_times_ms_.clear();
525 frame_rtc_times_ms_.clear();
526 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800527 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000528 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800529 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
530 tl0_pic_idx_ = static_cast<uint8_t>(rand());
531 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800532 last_frame_received_ms_ = -1;
533 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800534
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000535 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100536 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000537 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800538 const bool encode_status = jni->CallBooleanMethod(
539 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800540 j_video_codec_enum, width, height, kbps, fps,
541 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800542 if (!encode_status) {
543 ALOGE << "Failed to configure encoder.";
544 return WEBRTC_VIDEO_CODEC_ERROR;
545 }
546 CHECK_EXCEPTION(jni);
547
Per598242a2015-11-26 14:28:55 +0100548 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800549 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
550 jni->CallObjectMethod(*j_media_codec_video_encoder_,
551 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000552 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800553 if (IsNull(jni, input_buffers)) {
554 return WEBRTC_VIDEO_CODEC_ERROR;
555 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000556
perkj30e91822015-11-20 01:31:25 -0800557 switch (GetIntField(jni, *j_media_codec_video_encoder_,
558 j_color_format_field_)) {
559 case COLOR_FormatYUV420Planar:
560 encoder_fourcc_ = libyuv::FOURCC_YU12;
561 break;
562 case COLOR_FormatYUV420SemiPlanar:
563 case COLOR_QCOM_FormatYUV420SemiPlanar:
564 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
565 encoder_fourcc_ = libyuv::FOURCC_NV12;
566 break;
567 default:
568 LOG(LS_ERROR) << "Wrong color format.";
569 return WEBRTC_VIDEO_CODEC_ERROR;
570 }
571 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
572 RTC_CHECK(input_buffers_.empty())
573 << "Unexpected double InitEncode without Release";
574 input_buffers_.resize(num_input_buffers);
575 for (size_t i = 0; i < num_input_buffers; ++i) {
576 input_buffers_[i] =
577 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
578 int64_t yuv_buffer_capacity =
579 jni->GetDirectBufferCapacity(input_buffers_[i]);
580 CHECK_EXCEPTION(jni);
581 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
582 }
583 }
perkj9576e542015-11-12 06:43:16 -0800584
585 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000586 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
587 return WEBRTC_VIDEO_CODEC_OK;
588}
589
590int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700591 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700592 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800593 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000594 JNIEnv* jni = AttachCurrentThreadIfNeeded();
595 ScopedLocalRefFrame local_ref_frame(jni);
596
597 if (!inited_) {
598 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
599 }
perkj9576e542015-11-12 06:43:16 -0800600
asapersson1d61a512016-01-20 01:13:46 -0800601 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800602 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800603 ++frames_received_since_last_key_;
604 int64_t now_ms = GetCurrentTimeMs();
605 if (last_frame_received_ms_ != -1 &&
606 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
607 // Add limit to prevent triggering a key for every frame for very low
608 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
609 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
610 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
611 send_key_frame = true;
612 }
613 frames_received_since_last_key_ = 0;
614 }
615 last_frame_received_ms_ = now_ms;
616 }
617
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000618 frames_received_++;
619 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800620 if (!ResetCodecOnCodecThread())
621 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000622 }
glaznevf4decb52016-01-15 13:49:22 -0800623 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800624 ALOGD << "Encoder frame in # " << (frames_received_ - 1) <<
625 ". TS: " << (int)(current_timestamp_us_ / 1000) <<
626 ". Q: " << frames_in_queue_ <<
627 ". Fps: " << last_set_fps_ <<
628 ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800629 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000630
631 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800632 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000633 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800634 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800635 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800636 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000637 return WEBRTC_VIDEO_CODEC_OK;
638 }
639
henrikg91d6ede2015-09-17 00:24:34 -0700640 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200641
Peter Boströmf7704d12016-04-11 16:42:40 +0200642 // Check if we accumulated too many frames in encoder input buffers and drop
643 // frame if so.
644 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE) {
645 ALOGD << "Already " << frames_in_queue_ << " frames in the queue, dropping"
646 << ". TS: " << (int)(current_timestamp_us_ / 1000)
647 << ". Fps: " << last_set_fps_
648 << ". Consecutive drops: " << consecutive_full_queue_frame_drops_;
649 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
650 consecutive_full_queue_frame_drops_++;
651 if (consecutive_full_queue_frame_drops_ >=
652 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
653 ALOGE << "Encoder got stuck. Reset.";
654 ResetCodecOnCodecThread();
655 return WEBRTC_VIDEO_CODEC_ERROR;
glaznevf4decb52016-01-15 13:49:22 -0800656 }
Peter Boströmf7704d12016-04-11 16:42:40 +0200657 frames_dropped_media_encoder_++;
658 OnDroppedFrame();
659 return WEBRTC_VIDEO_CODEC_OK;
glaznevf4decb52016-01-15 13:49:22 -0800660 }
glaznev919ff752016-01-27 15:01:03 -0800661 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800662
Per598242a2015-11-26 14:28:55 +0100663 VideoFrame input_frame = frame;
664 if (scale_) {
665 // Check framerate before spatial resolution change.
666 quality_scaler_.OnEncodeFrame(frame);
667 const webrtc::QualityScaler::Resolution scaled_resolution =
668 quality_scaler_.GetScaledResolution();
669 if (scaled_resolution.width != frame.width() ||
670 scaled_resolution.height != frame.height()) {
671 if (frame.native_handle() != nullptr) {
672 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
673 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100674 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100675 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100676 scaled_resolution.height,
677 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100678 input_frame.set_video_frame_buffer(scaled_buffer);
679 } else {
680 input_frame = quality_scaler_.GetScaledFrame(frame);
681 }
682 }
683 }
jackychen61b4d512015-04-21 15:30:11 -0700684
perkj9576e542015-11-12 06:43:16 -0800685 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
686 ALOGE << "Failed to reconfigure encoder.";
687 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000688 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000689
glaznevf4decb52016-01-15 13:49:22 -0800690 // Save time when input frame is sent to the encoder input.
691 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000692
asapersson1d61a512016-01-20 01:13:46 -0800693 const bool key_frame =
694 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800695 bool encode_status = true;
696 if (!input_frame.native_handle()) {
697 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
698 j_dequeue_input_buffer_method_);
699 CHECK_EXCEPTION(jni);
700 if (j_input_buffer_index == -1) {
701 // Video codec falls behind - no input buffer available.
702 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800703 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800704 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
705 frames_dropped_media_encoder_++;
706 OnDroppedFrame();
perkj30e91822015-11-20 01:31:25 -0800707 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
708 }
709 if (j_input_buffer_index == -2) {
710 ResetCodecOnCodecThread();
711 return WEBRTC_VIDEO_CODEC_ERROR;
712 }
713 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
714 j_input_buffer_index);
715 } else {
716 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000717 }
perkj30e91822015-11-20 01:31:25 -0800718
719 if (!encode_status) {
720 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800721 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200722 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000723 }
724
perkj9576e542015-11-12 06:43:16 -0800725 last_input_timestamp_ms_ =
726 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200727 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000728
perkj12f68022015-10-16 13:31:45 +0200729 // Save input image timestamps for later output
730 timestamps_.push_back(input_frame.timestamp());
731 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800732 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
733
perkj30e91822015-11-20 01:31:25 -0800734 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800735 ALOGE << "Failed deliver pending outputs.";
736 ResetCodecOnCodecThread();
737 return WEBRTC_VIDEO_CODEC_ERROR;
738 }
739 return WEBRTC_VIDEO_CODEC_OK;
740}
741
742bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
743 const webrtc::VideoFrame& frame) {
744 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
745
perkj30e91822015-11-20 01:31:25 -0800746 const bool is_texture_frame = frame.native_handle() != nullptr;
747 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800748 const bool reconfigure_due_to_size =
749 frame.width() != width_ || frame.height() != height_;
750
perkj30e91822015-11-20 01:31:25 -0800751 if (reconfigure_due_to_format) {
752 ALOGD << "Reconfigure encoder due to format change. "
753 << (use_surface_ ?
754 "Reconfiguring to encode from byte buffer." :
755 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800756 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800757 }
perkj9576e542015-11-12 06:43:16 -0800758 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800759 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800760 << width_ << " x " << height_ << " to " << frame.width() << " x "
761 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800762 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800763 width_ = frame.width();
764 height_ = frame.height();
765 }
766
perkj30e91822015-11-20 01:31:25 -0800767 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800768 return true;
769
770 ReleaseOnCodecThread();
771
perkj30e91822015-11-20 01:31:25 -0800772 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800773 WEBRTC_VIDEO_CODEC_OK;
774}
775
776bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
777 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
778 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800779 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800780
perkj9576e542015-11-12 06:43:16 -0800781 jobject j_input_buffer = input_buffers_[input_buffer_index];
782 uint8_t* yuv_buffer =
783 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
784 CHECK_EXCEPTION(jni);
785 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
786 RTC_CHECK(!libyuv::ConvertFromI420(
787 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
788 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
789 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
790 yuv_buffer, width_, width_, height_, encoder_fourcc_))
791 << "ConvertFromI420 failed";
792
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000793 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800794 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000795 key_frame,
perkj9576e542015-11-12 06:43:16 -0800796 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000797 yuv_size_,
798 current_timestamp_us_);
799 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800800 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000801}
802
perkj30e91822015-11-20 01:31:25 -0800803bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
804 bool key_frame, const webrtc::VideoFrame& frame) {
805 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
806 RTC_CHECK(use_surface_);
807 NativeHandleImpl* handle =
808 static_cast<NativeHandleImpl*>(frame.native_handle());
809 jfloatArray sampling_matrix = jni->NewFloatArray(16);
810 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
811
812 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
813 j_encode_texture_method_,
814 key_frame,
815 handle->oes_texture_id,
816 sampling_matrix,
817 current_timestamp_us_);
818 CHECK_EXCEPTION(jni);
819 return encode_status;
820}
821
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000822int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
823 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800824 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000825 JNIEnv* jni = AttachCurrentThreadIfNeeded();
826 ScopedLocalRefFrame local_ref_frame(jni);
827 callback_ = callback;
828 return WEBRTC_VIDEO_CODEC_OK;
829}
830
831int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800832 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000833 if (!inited_) {
834 return WEBRTC_VIDEO_CODEC_OK;
835 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000836 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700837 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
838 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800839 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000840 ScopedLocalRefFrame local_ref_frame(jni);
841 for (size_t i = 0; i < input_buffers_.size(); ++i)
842 jni->DeleteGlobalRef(input_buffers_[i]);
843 input_buffers_.clear();
844 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
845 CHECK_EXCEPTION(jni);
846 rtc::MessageQueueManager::Clear(this);
847 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800848 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700849 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000850 return WEBRTC_VIDEO_CODEC_OK;
851}
852
853int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
854 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800855 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800856 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
857 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000858 if (last_set_bitrate_kbps_ == new_bit_rate &&
859 last_set_fps_ == frame_rate) {
860 return WEBRTC_VIDEO_CODEC_OK;
861 }
glaznev919ff752016-01-27 15:01:03 -0800862 if (scale_) {
863 quality_scaler_.ReportFramerate(frame_rate);
864 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000865 JNIEnv* jni = AttachCurrentThreadIfNeeded();
866 ScopedLocalRefFrame local_ref_frame(jni);
867 if (new_bit_rate > 0) {
868 last_set_bitrate_kbps_ = new_bit_rate;
869 }
870 if (frame_rate > 0) {
871 last_set_fps_ = frame_rate;
872 }
873 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
874 j_set_rates_method_,
875 last_set_bitrate_kbps_,
876 last_set_fps_);
877 CHECK_EXCEPTION(jni);
878 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800879 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000880 return WEBRTC_VIDEO_CODEC_ERROR;
881 }
882 return WEBRTC_VIDEO_CODEC_OK;
883}
884
885int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
886 JNIEnv* jni,
887 jobject j_output_buffer_info) {
888 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
889}
890
891jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
892 JNIEnv* jni,
893 jobject j_output_buffer_info) {
894 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
895}
896
897bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
898 JNIEnv* jni,
899 jobject j_output_buffer_info) {
900 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
901}
902
903jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
904 JNIEnv* jni,
905 jobject j_output_buffer_info) {
906 return GetLongField(
907 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
908}
909
910bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800911 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000912 while (true) {
913 jobject j_output_buffer_info = jni->CallObjectMethod(
914 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
915 CHECK_EXCEPTION(jni);
916 if (IsNull(jni, j_output_buffer_info)) {
917 break;
918 }
919
920 int output_buffer_index =
921 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
922 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800923 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000924 return false;
925 }
926
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000927 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000928 jobject j_output_buffer =
929 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
930 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000931
932 // Get frame timestamps from a queue - for non config frames only.
933 int64_t frame_encoding_time_ms = 0;
934 last_output_timestamp_ms_ =
935 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
936 1000;
937 if (frames_in_queue_ > 0) {
938 output_timestamp_ = timestamps_.front();
939 timestamps_.erase(timestamps_.begin());
940 output_render_time_ms_ = render_times_ms_.front();
941 render_times_ms_.erase(render_times_ms_.begin());
942 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
943 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
944 frames_in_queue_--;
945 }
946
947 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000948 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200949 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000950 jni->GetDirectBufferAddress(j_output_buffer));
951 CHECK_EXCEPTION(jni);
952
glaznevf4decb52016-01-15 13:49:22 -0800953 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800954 int current_latency =
955 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
956 ALOGD << "Encoder frame out # " << frames_encoded_ <<
957 ". Key: " << key_frame <<
958 ". Size: " << payload_size <<
959 ". TS: " << (int)last_output_timestamp_ms_ <<
960 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800961 ". 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;
glaznev94291482016-02-01 13:17:18 -08001092 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001093
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001094 if (callback_status > 0) {
1095 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001096 // Theoretically could handle callback_status<0 here, but unclear what
1097 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001098 }
1099 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001100 return true;
1101}
1102
glaznev94291482016-02-01 13:17:18 -08001103void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1104 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1105 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1106 current_frames_ > 0 && statistic_time_ms > 0) {
1107 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1108 int current_fps =
1109 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1110 ALOGD << "Encoded frames: " << frames_encoded_ <<
1111 ". Bitrate: " << current_bitrate <<
1112 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1113 ", fps: " << current_fps <<
1114 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1115 ". QP: " << (current_acc_qp_ / current_frames_) <<
1116 " for last " << statistic_time_ms << " ms.";
1117 stat_start_time_ms_ = GetCurrentTimeMs();
1118 current_frames_ = 0;
1119 current_bytes_ = 0;
1120 current_acc_qp_ = 0;
1121 current_encoding_time_ms_ = 0;
1122 }
1123}
1124
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001125int32_t MediaCodecVideoEncoder::NextNaluPosition(
1126 uint8_t *buffer, size_t buffer_size) {
1127 if (buffer_size < H264_SC_LENGTH) {
1128 return -1;
1129 }
1130 uint8_t *head = buffer;
1131 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1132 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1133 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1134
1135 while (head < end) {
1136 if (head[0]) {
1137 head++;
1138 continue;
1139 }
1140 if (head[1]) { // got 00xx
1141 head += 2;
1142 continue;
1143 }
1144 if (head[2]) { // got 0000xx
1145 head += 3;
1146 continue;
1147 }
1148 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001149 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001150 continue;
1151 }
1152 return (int32_t)(head - buffer);
1153 }
1154 return -1;
1155}
1156
jackychen61b4d512015-04-21 15:30:11 -07001157void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001158 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001159 if (scale_)
1160 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001161}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001162
jackychen6e2ce6e2015-07-13 16:26:33 -07001163int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001164 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001165}
1166
Peter Boströmb7d9a972015-12-18 16:01:11 +01001167const char* MediaCodecVideoEncoder::ImplementationName() const {
1168 return "MediaCodec";
1169}
1170
perkj461121c2016-02-15 06:28:36 -08001171MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1172 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001173 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1174 ScopedLocalRefFrame local_ref_frame(jni);
1175 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001176 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001177
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001178 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1179 j_encoder_class,
1180 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1181 CHECK_EXCEPTION(jni);
1182 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001183 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001184 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1185 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1186 }
1187
Alex Glaznevad948c42015-11-18 13:06:42 -08001188 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1189 j_encoder_class,
1190 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1191 CHECK_EXCEPTION(jni);
1192 if (is_vp9_hw_supported) {
1193 ALOGD << "VP9 HW Encoder supported.";
1194 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1195 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1196 }
1197
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001198 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1199 j_encoder_class,
1200 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1201 CHECK_EXCEPTION(jni);
1202 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001203 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001204 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1205 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1206 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001207}
1208
Perec2922f2016-01-27 15:25:46 +01001209MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1210 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001211 if (egl_context_) {
1212 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1213 jni->DeleteGlobalRef(egl_context_);
1214 }
Perec2922f2016-01-27 15:25:46 +01001215}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001216
perkj30e91822015-11-20 01:31:25 -08001217void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001218 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001219 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001220 if (egl_context_) {
1221 jni->DeleteGlobalRef(egl_context_);
1222 egl_context_ = nullptr;
1223 }
perkj461121c2016-02-15 06:28:36 -08001224 egl_context_ = jni->NewGlobalRef(egl_context);
1225 if (CheckException(jni)) {
1226 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001227 }
1228}
1229
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001230webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001231 VideoCodecType type) {
1232 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001233 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001234 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001235 }
1236 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1237 it != supported_codecs_.end(); ++it) {
1238 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001239 ALOGD << "Create HW video encoder for type " << (int)type <<
1240 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001241 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001242 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001243 }
1244 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001245 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001246 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001247}
1248
1249const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1250MediaCodecVideoEncoderFactory::codecs() const {
1251 return supported_codecs_;
1252}
1253
1254void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1255 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001256 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001257 delete encoder;
1258}
1259
1260} // namespace webrtc_jni
1261