blob: 7fa93de1493ad4067902dd479cc2d308ce137f9c [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;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000048
49namespace webrtc_jni {
50
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000051// H.264 start code length.
52#define H264_SC_LENGTH 4
53// Maximum allowed NALUs in one output frame.
54#define MAX_NALUS_PERFRAME 32
55// Maximum supported HW video encoder resolution.
56#define MAX_VIDEO_WIDTH 1280
57#define MAX_VIDEO_HEIGHT 1280
58// Maximum supported HW video encoder fps.
59#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080060// Maximum allowed fps value in SetRates() call.
61#define MAX_ALLOWED_VIDEO_FPS 60
62// Maximum allowed frames in encoder input queue.
63#define MAX_ENCODER_Q_SIZE 2
64// Maximum allowed latency in ms.
65#define MAX_ENCODER_LATENCY_MS 70
glaznev919ff752016-01-27 15:01:03 -080066// Maximum amount of dropped frames caused by full encoder queue - exceeding
67// this threshold means that encoder probably got stuck and need to be reset.
68#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080069
70// Logging macros.
71#define TAG_ENCODER "MediaCodecVideoEncoder"
72#ifdef TRACK_BUFFER_TIMING
73#define ALOGV(...)
74 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
75#else
76#define ALOGV(...)
77#endif
78#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
79#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
80#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000081
asapersson1d61a512016-01-20 01:13:46 -080082namespace {
83// Maximum time limit between incoming frames before requesting a key frame.
84const size_t kFrameDiffThresholdMs = 1100;
85const int kMinKeyFrameInterval = 2;
86} // namespace
87
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000088// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
89// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
90// HW-backed video encode. This C++ class is implemented as a very thin shim,
91// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
92// MediaCodecVideoEncoder is created, operated, and destroyed on a single
93// thread, currently the libjingle Worker thread.
94class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
95 public rtc::MessageHandler {
96 public:
97 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -080098 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -080099 VideoCodecType codecType,
100 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000101
102 // webrtc::VideoEncoder implementation. Everything trampolines to
103 // |codec_thread_| for execution.
104 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
105 int32_t /* number_of_cores */,
106 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700107 int32_t Encode(const webrtc::VideoFrame& input_image,
108 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
109 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000110 int32_t RegisterEncodeCompleteCallback(
111 webrtc::EncodedImageCallback* callback) override;
112 int32_t Release() override;
113 int32_t SetChannelParameters(uint32_t /* packet_loss */,
114 int64_t /* rtt */) override;
115 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
116
117 // rtc::MessageHandler implementation.
118 void OnMessage(rtc::Message* msg) override;
119
jackychen61b4d512015-04-21 15:30:11 -0700120 void OnDroppedFrame() override;
121
jackychen6e2ce6e2015-07-13 16:26:33 -0700122 int GetTargetFramerate() override;
123
Perec2922f2016-01-27 15:25:46 +0100124 bool SupportsNativeHandle() const override { return egl_context_ != nullptr; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100125 const char* ImplementationName() const override;
126
127 private:
128 // CHECK-fail if not running on |codec_thread_|.
129 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800130
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000131 private:
perkj9576e542015-11-12 06:43:16 -0800132 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
133 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000134 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800135 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000136
137 // Implementation of webrtc::VideoEncoder methods above, all running on the
138 // codec thread exclusively.
139 //
140 // If width==0 then this is assumed to be a re-initialization and the
141 // previously-current values are reused instead of the passed parameters
142 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800143 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
144 bool use_surface);
145 // Reconfigure to match |frame| in width, height. Also reconfigures the
146 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
147 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800148 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000149 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700150 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700151 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800152 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
153 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800154 bool EncodeTextureOnCodecThread(JNIEnv* jni,
155 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800156
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000157 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
158 webrtc::EncodedImageCallback* callback);
159 int32_t ReleaseOnCodecThread();
160 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
161
162 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
163 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
164 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
165 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
166 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000167 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000168
169 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
170 // true on success.
171 bool DeliverPendingOutputs(JNIEnv* jni);
172
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000173 // Search for H.264 start codes.
174 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
175
glaznev94291482016-02-01 13:17:18 -0800176 // Displays encoder statistics.
177 void LogStatistics(bool force_log);
178
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000179 // Type of video codec.
180 VideoCodecType codecType_;
181
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000182 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
183 // |codec_thread_| synchronously.
184 webrtc::EncodedImageCallback* callback_;
185
186 // State that is constant for the lifetime of this object once the ctor
187 // returns.
188 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800189 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000190 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
191 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
192 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800193 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000194 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800195 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800196 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000197 jmethodID j_release_method_;
198 jmethodID j_set_rates_method_;
199 jmethodID j_dequeue_output_buffer_method_;
200 jmethodID j_release_output_buffer_method_;
201 jfieldID j_color_format_field_;
202 jfieldID j_info_index_field_;
203 jfieldID j_info_buffer_field_;
204 jfieldID j_info_is_key_frame_field_;
205 jfieldID j_info_presentation_timestamp_us_field_;
206
207 // State that is valid only between InitEncode() and the next Release().
208 // Touched only on codec_thread_ so no explicit synchronization necessary.
209 int width_; // Frame width in pixels.
210 int height_; // Frame height in pixels.
211 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800212 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000213 uint16_t picture_id_;
214 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
215 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
216 int last_set_fps_; // Last-requested frame rate.
217 int64_t current_timestamp_us_; // Current frame timestamps in us.
218 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000219 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800220 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
221 // Number of dropped frames caused by full queue.
222 int consecutive_full_queue_frame_drops_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000223 int frames_in_queue_; // Number of frames in encoder queue.
glaznev94291482016-02-01 13:17:18 -0800224 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000225 int current_frames_; // Number of frames in the current statistics interval.
226 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800227 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000228 int current_encoding_time_ms_; // Overall encoding time in the current second
229 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
230 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
231 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
232 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
233 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
234 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000235 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
236 int64_t output_render_time_ms_; // Last output frame render time from
237 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000238 // Frame size in bytes fed to MediaCodec.
239 int yuv_size_;
240 // True only when between a callback_->Encoded() call return a positive value
241 // and the next Encode() call being ignored.
242 bool drop_next_input_frame_;
243 // Global references; must be deleted in Release().
244 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200245 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700246 // Dynamic resolution change, off by default.
247 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200248
249 // H264 bitstream parser, used to extract QP from encoded bitstreams.
250 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800251
252 // VP9 variables to populate codec specific structure.
253 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
254 // non-flexible VP9 mode.
255 uint8_t tl0_pic_idx_;
256 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800257
258 // EGL context - owned by factory, should not be allocated/destroyed
259 // by MediaCodecVideoEncoder.
260 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800261
262 // Temporary fix for VP8.
263 // Sends a key frame if frames are largely spaced apart (possibly
264 // corresponding to a large image change).
265 int64_t last_frame_received_ms_;
266 int frames_received_since_last_key_;
267 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000268};
269
270MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
271 // Call Release() to ensure no more callbacks to us after we are deleted.
272 Release();
273}
274
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000275MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800276 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000277 codecType_(codecType),
278 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000279 codec_thread_(new Thread()),
280 j_media_codec_video_encoder_class_(
281 jni,
282 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
283 j_media_codec_video_encoder_(
284 jni,
285 jni->NewObject(*j_media_codec_video_encoder_class_,
286 GetMethodID(jni,
287 *j_media_codec_video_encoder_class_,
288 "<init>",
perkj30e91822015-11-20 01:31:25 -0800289 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800290 inited_(false),
291 use_surface_(false),
292 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800293 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000294 ScopedLocalRefFrame local_ref_frame(jni);
295 // It would be nice to avoid spinning up a new thread per MediaCodec, and
296 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
297 // 2732 means that deadlocks abound. This class synchronously trampolines
298 // to |codec_thread_|, so if anything else can be coming to _us_ from
299 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
300 // in the bug, we have a problem. For now work around that with a dedicated
301 // thread.
302 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700303 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800304 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000305 jclass j_output_buffer_info_class =
306 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000307 j_init_encode_method_ = GetMethodID(
308 jni,
309 *j_media_codec_video_encoder_class_,
310 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800311 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800312 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800313 j_get_input_buffers_method_ = GetMethodID(
314 jni,
315 *j_media_codec_video_encoder_class_,
316 "getInputBuffers",
317 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000318 j_dequeue_input_buffer_method_ = GetMethodID(
319 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800320 j_encode_buffer_method_ = GetMethodID(
321 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800322 j_encode_texture_method_ = GetMethodID(
323 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
324 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000325 j_release_method_ =
326 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
327 j_set_rates_method_ = GetMethodID(
328 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000329 j_dequeue_output_buffer_method_ = GetMethodID(
330 jni,
331 *j_media_codec_video_encoder_class_,
332 "dequeueOutputBuffer",
333 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000334 j_release_output_buffer_method_ = GetMethodID(
335 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
336
337 j_color_format_field_ =
338 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
339 j_info_index_field_ =
340 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
341 j_info_buffer_field_ = GetFieldID(
342 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
343 j_info_is_key_frame_field_ =
344 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
345 j_info_presentation_timestamp_us_field_ = GetFieldID(
346 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
347 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800348 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000349 AllowBlockingCalls();
350}
351
352int32_t MediaCodecVideoEncoder::InitEncode(
353 const webrtc::VideoCodec* codec_settings,
354 int32_t /* number_of_cores */,
355 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700356 const int kMinWidth = 320;
357 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700358 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000359 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700360 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000361 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
362 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000363 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700364 RTC_CHECK(codec_settings->codecType == codecType_)
365 << "Unsupported codec " << codec_settings->codecType << " for "
366 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000367
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700368 ALOGD << "InitEncode request";
asapersson1d61a512016-01-20 01:13:46 -0800369 codec_mode_ = codec_settings->mode;
Alex Glaznevad948c42015-11-18 13:06:42 -0800370 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
371 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700372 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200373 if (scale_) {
374 if (codecType_ == kVideoCodecVP8) {
375 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
376 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
377 // always = 127. Note that in SW, QP is that of the user-level range [0,
378 // 63].
379 const int kMaxQp = 127;
glaznev919ff752016-01-27 15:01:03 -0800380 const int kBadQpThreshold = 95;
381 quality_scaler_.Init(
382 kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold, false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200383 } else if (codecType_ == kVideoCodecH264) {
384 // H264 QP is in the range [0, 51].
385 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200386 const int kBadQpThreshold = 40;
glaznev919ff752016-01-27 15:01:03 -0800387 quality_scaler_.Init(
388 kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold, false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200389 } else {
390 // When adding codec support to additional hardware codecs, also configure
391 // their QP thresholds for scaling.
392 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
393 }
394 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
395 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700396 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000397 return codec_thread_->Invoke<int32_t>(
398 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
399 this,
400 codec_settings->width,
401 codec_settings->height,
402 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800403 codec_settings->maxFramerate,
404 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000405}
406
407int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700408 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000409 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700410 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000411 return codec_thread_->Invoke<int32_t>(Bind(
412 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
413}
414
415int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
416 webrtc::EncodedImageCallback* callback) {
417 return codec_thread_->Invoke<int32_t>(
418 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
419 this,
420 callback));
421}
422
423int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700424 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000425 return codec_thread_->Invoke<int32_t>(
426 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
427}
428
429int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
430 int64_t /* rtt */) {
431 return WEBRTC_VIDEO_CODEC_OK;
432}
433
434int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
435 uint32_t frame_rate) {
436 return codec_thread_->Invoke<int32_t>(
437 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
438 this,
439 new_bit_rate,
440 frame_rate));
441}
442
443void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800444 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000445 JNIEnv* jni = AttachCurrentThreadIfNeeded();
446 ScopedLocalRefFrame local_ref_frame(jni);
447
448 // We only ever send one message to |this| directly (not through a Bind()'d
449 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700450 RTC_CHECK(!msg->message_id) << "Unexpected message!";
451 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000452 if (!inited_) {
453 return;
454 }
455
456 // It would be nice to recover from a failure here if one happened, but it's
457 // unclear how to signal such a failure to the app, so instead we stay silent
458 // about it and let the next app-called API method reveal the borkedness.
459 DeliverPendingOutputs(jni);
460 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
461}
462
perkj9576e542015-11-12 06:43:16 -0800463bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
464 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
465 ALOGE << "ResetOnCodecThread";
466 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800467 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
468 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000469 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
470 // degrade to a SW encoder at this point? There isn't one AFAICT :(
471 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800472 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000473 }
perkj9576e542015-11-12 06:43:16 -0800474 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000475}
476
477int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800478 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800479 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800480 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000481 JNIEnv* jni = AttachCurrentThreadIfNeeded();
482 ScopedLocalRefFrame local_ref_frame(jni);
483
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700484 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
485 width << " x " << height << ". Bitrate: " << kbps <<
486 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000487 if (kbps == 0) {
488 kbps = last_set_bitrate_kbps_;
489 }
490 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800491 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000492 }
493
494 width_ = width;
495 height_ = height;
496 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800497 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000498 yuv_size_ = width_ * height_ * 3 / 2;
499 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000500 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800501 frames_dropped_media_encoder_ = 0;
502 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000503 frames_in_queue_ = 0;
504 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800505 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000506 current_frames_ = 0;
507 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800508 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000509 current_encoding_time_ms_ = 0;
510 last_input_timestamp_ms_ = -1;
511 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000512 output_timestamp_ = 0;
513 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000514 timestamps_.clear();
515 render_times_ms_.clear();
516 frame_rtc_times_ms_.clear();
517 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800518 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000519 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800520 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
521 tl0_pic_idx_ = static_cast<uint8_t>(rand());
522 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800523 last_frame_received_ms_ = -1;
524 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800525
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000526 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100527 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000528 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800529 const bool encode_status = jni->CallBooleanMethod(
530 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800531 j_video_codec_enum, width, height, kbps, fps,
532 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800533 if (!encode_status) {
534 ALOGE << "Failed to configure encoder.";
535 return WEBRTC_VIDEO_CODEC_ERROR;
536 }
537 CHECK_EXCEPTION(jni);
538
Per598242a2015-11-26 14:28:55 +0100539 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800540 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
541 jni->CallObjectMethod(*j_media_codec_video_encoder_,
542 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000543 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800544 if (IsNull(jni, input_buffers)) {
545 return WEBRTC_VIDEO_CODEC_ERROR;
546 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000547
perkj30e91822015-11-20 01:31:25 -0800548 switch (GetIntField(jni, *j_media_codec_video_encoder_,
549 j_color_format_field_)) {
550 case COLOR_FormatYUV420Planar:
551 encoder_fourcc_ = libyuv::FOURCC_YU12;
552 break;
553 case COLOR_FormatYUV420SemiPlanar:
554 case COLOR_QCOM_FormatYUV420SemiPlanar:
555 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
556 encoder_fourcc_ = libyuv::FOURCC_NV12;
557 break;
558 default:
559 LOG(LS_ERROR) << "Wrong color format.";
560 return WEBRTC_VIDEO_CODEC_ERROR;
561 }
562 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
563 RTC_CHECK(input_buffers_.empty())
564 << "Unexpected double InitEncode without Release";
565 input_buffers_.resize(num_input_buffers);
566 for (size_t i = 0; i < num_input_buffers; ++i) {
567 input_buffers_[i] =
568 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
569 int64_t yuv_buffer_capacity =
570 jni->GetDirectBufferCapacity(input_buffers_[i]);
571 CHECK_EXCEPTION(jni);
572 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
573 }
574 }
perkj9576e542015-11-12 06:43:16 -0800575
576 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000577 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
578 return WEBRTC_VIDEO_CODEC_OK;
579}
580
581int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700582 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700583 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800584 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000585 JNIEnv* jni = AttachCurrentThreadIfNeeded();
586 ScopedLocalRefFrame local_ref_frame(jni);
587
588 if (!inited_) {
589 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
590 }
perkj9576e542015-11-12 06:43:16 -0800591
asapersson1d61a512016-01-20 01:13:46 -0800592 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800593 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800594 ++frames_received_since_last_key_;
595 int64_t now_ms = GetCurrentTimeMs();
596 if (last_frame_received_ms_ != -1 &&
597 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
598 // Add limit to prevent triggering a key for every frame for very low
599 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
600 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
601 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
602 send_key_frame = true;
603 }
604 frames_received_since_last_key_ = 0;
605 }
606 last_frame_received_ms_ = now_ms;
607 }
608
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000609 frames_received_++;
610 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800611 if (!ResetCodecOnCodecThread())
612 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000613 }
glaznevf4decb52016-01-15 13:49:22 -0800614 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800615 ALOGD << "Encoder frame in # " << (frames_received_ - 1) <<
616 ". TS: " << (int)(current_timestamp_us_ / 1000) <<
617 ". Q: " << frames_in_queue_ <<
618 ". Fps: " << last_set_fps_ <<
619 ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800620 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000621
622 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800623 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000624 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800625 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800626 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800627 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000628 return WEBRTC_VIDEO_CODEC_OK;
629 }
630
henrikg91d6ede2015-09-17 00:24:34 -0700631 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200632
glaznevf4decb52016-01-15 13:49:22 -0800633 // Check if we accumulated too many frames in encoder input buffers
634 // or the encoder latency exceeds 70 ms and drop frame if so.
635 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
636 int encoder_latency_ms = last_input_timestamp_ms_ -
637 last_output_timestamp_ms_;
638 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE ||
639 encoder_latency_ms > MAX_ENCODER_LATENCY_MS) {
640 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
glaznev94291482016-02-01 13:17:18 -0800641 " ms. Q size: " << frames_in_queue_ << ". TS: " <<
642 (int)(current_timestamp_us_ / 1000) << ". Fps: " << last_set_fps_ <<
643 ". Consecutive drops: " << consecutive_full_queue_frame_drops_ ;
glaznevf4decb52016-01-15 13:49:22 -0800644 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800645 consecutive_full_queue_frame_drops_++;
646 if (consecutive_full_queue_frame_drops_ >=
647 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
648 ALOGE << "Encoder got stuck. Reset.";
649 ResetCodecOnCodecThread();
650 return WEBRTC_VIDEO_CODEC_ERROR;
651 }
652 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800653 OnDroppedFrame();
654 return WEBRTC_VIDEO_CODEC_OK;
655 }
656 }
glaznev919ff752016-01-27 15:01:03 -0800657 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800658
Per598242a2015-11-26 14:28:55 +0100659 VideoFrame input_frame = frame;
660 if (scale_) {
661 // Check framerate before spatial resolution change.
662 quality_scaler_.OnEncodeFrame(frame);
663 const webrtc::QualityScaler::Resolution scaled_resolution =
664 quality_scaler_.GetScaledResolution();
665 if (scaled_resolution.width != frame.width() ||
666 scaled_resolution.height != frame.height()) {
667 if (frame.native_handle() != nullptr) {
668 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
669 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100670 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100671 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100672 scaled_resolution.height,
673 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100674 input_frame.set_video_frame_buffer(scaled_buffer);
675 } else {
676 input_frame = quality_scaler_.GetScaledFrame(frame);
677 }
678 }
679 }
jackychen61b4d512015-04-21 15:30:11 -0700680
perkj9576e542015-11-12 06:43:16 -0800681 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
682 ALOGE << "Failed to reconfigure encoder.";
683 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000684 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000685
glaznevf4decb52016-01-15 13:49:22 -0800686 // Save time when input frame is sent to the encoder input.
687 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000688
asapersson1d61a512016-01-20 01:13:46 -0800689 const bool key_frame =
690 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800691 bool encode_status = true;
692 if (!input_frame.native_handle()) {
693 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
694 j_dequeue_input_buffer_method_);
695 CHECK_EXCEPTION(jni);
696 if (j_input_buffer_index == -1) {
697 // Video codec falls behind - no input buffer available.
698 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800699 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800700 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
701 frames_dropped_media_encoder_++;
702 OnDroppedFrame();
perkj30e91822015-11-20 01:31:25 -0800703 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
704 }
705 if (j_input_buffer_index == -2) {
706 ResetCodecOnCodecThread();
707 return WEBRTC_VIDEO_CODEC_ERROR;
708 }
709 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
710 j_input_buffer_index);
711 } else {
712 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000713 }
perkj30e91822015-11-20 01:31:25 -0800714
715 if (!encode_status) {
716 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800717 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200718 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000719 }
720
perkj9576e542015-11-12 06:43:16 -0800721 last_input_timestamp_ms_ =
722 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200723 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000724
perkj12f68022015-10-16 13:31:45 +0200725 // Save input image timestamps for later output
726 timestamps_.push_back(input_frame.timestamp());
727 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800728 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
729
perkj30e91822015-11-20 01:31:25 -0800730 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800731 ALOGE << "Failed deliver pending outputs.";
732 ResetCodecOnCodecThread();
733 return WEBRTC_VIDEO_CODEC_ERROR;
734 }
735 return WEBRTC_VIDEO_CODEC_OK;
736}
737
738bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
739 const webrtc::VideoFrame& frame) {
740 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
741
perkj30e91822015-11-20 01:31:25 -0800742 const bool is_texture_frame = frame.native_handle() != nullptr;
743 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800744 const bool reconfigure_due_to_size =
745 frame.width() != width_ || frame.height() != height_;
746
perkj30e91822015-11-20 01:31:25 -0800747 if (reconfigure_due_to_format) {
748 ALOGD << "Reconfigure encoder due to format change. "
749 << (use_surface_ ?
750 "Reconfiguring to encode from byte buffer." :
751 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800752 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800753 }
perkj9576e542015-11-12 06:43:16 -0800754 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800755 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800756 << width_ << " x " << height_ << " to " << frame.width() << " x "
757 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800758 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800759 width_ = frame.width();
760 height_ = frame.height();
761 }
762
perkj30e91822015-11-20 01:31:25 -0800763 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800764 return true;
765
766 ReleaseOnCodecThread();
767
perkj30e91822015-11-20 01:31:25 -0800768 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800769 WEBRTC_VIDEO_CODEC_OK;
770}
771
772bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
773 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
774 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800775 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800776
perkj9576e542015-11-12 06:43:16 -0800777 jobject j_input_buffer = input_buffers_[input_buffer_index];
778 uint8_t* yuv_buffer =
779 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
780 CHECK_EXCEPTION(jni);
781 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
782 RTC_CHECK(!libyuv::ConvertFromI420(
783 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
784 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
785 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
786 yuv_buffer, width_, width_, height_, encoder_fourcc_))
787 << "ConvertFromI420 failed";
788
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000789 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800790 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000791 key_frame,
perkj9576e542015-11-12 06:43:16 -0800792 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000793 yuv_size_,
794 current_timestamp_us_);
795 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800796 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000797}
798
perkj30e91822015-11-20 01:31:25 -0800799bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
800 bool key_frame, const webrtc::VideoFrame& frame) {
801 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
802 RTC_CHECK(use_surface_);
803 NativeHandleImpl* handle =
804 static_cast<NativeHandleImpl*>(frame.native_handle());
805 jfloatArray sampling_matrix = jni->NewFloatArray(16);
806 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
807
808 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
809 j_encode_texture_method_,
810 key_frame,
811 handle->oes_texture_id,
812 sampling_matrix,
813 current_timestamp_us_);
814 CHECK_EXCEPTION(jni);
815 return encode_status;
816}
817
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000818int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
819 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800820 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000821 JNIEnv* jni = AttachCurrentThreadIfNeeded();
822 ScopedLocalRefFrame local_ref_frame(jni);
823 callback_ = callback;
824 return WEBRTC_VIDEO_CODEC_OK;
825}
826
827int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800828 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000829 if (!inited_) {
830 return WEBRTC_VIDEO_CODEC_OK;
831 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000832 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700833 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
834 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800835 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000836 ScopedLocalRefFrame local_ref_frame(jni);
837 for (size_t i = 0; i < input_buffers_.size(); ++i)
838 jni->DeleteGlobalRef(input_buffers_[i]);
839 input_buffers_.clear();
840 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
841 CHECK_EXCEPTION(jni);
842 rtc::MessageQueueManager::Clear(this);
843 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800844 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700845 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000846 return WEBRTC_VIDEO_CODEC_OK;
847}
848
849int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
850 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800851 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800852 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
853 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000854 if (last_set_bitrate_kbps_ == new_bit_rate &&
855 last_set_fps_ == frame_rate) {
856 return WEBRTC_VIDEO_CODEC_OK;
857 }
glaznev919ff752016-01-27 15:01:03 -0800858 if (scale_) {
859 quality_scaler_.ReportFramerate(frame_rate);
860 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000861 JNIEnv* jni = AttachCurrentThreadIfNeeded();
862 ScopedLocalRefFrame local_ref_frame(jni);
863 if (new_bit_rate > 0) {
864 last_set_bitrate_kbps_ = new_bit_rate;
865 }
866 if (frame_rate > 0) {
867 last_set_fps_ = frame_rate;
868 }
869 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
870 j_set_rates_method_,
871 last_set_bitrate_kbps_,
872 last_set_fps_);
873 CHECK_EXCEPTION(jni);
874 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800875 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000876 return WEBRTC_VIDEO_CODEC_ERROR;
877 }
878 return WEBRTC_VIDEO_CODEC_OK;
879}
880
881int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
882 JNIEnv* jni,
883 jobject j_output_buffer_info) {
884 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
885}
886
887jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
888 JNIEnv* jni,
889 jobject j_output_buffer_info) {
890 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
891}
892
893bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
894 JNIEnv* jni,
895 jobject j_output_buffer_info) {
896 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
897}
898
899jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
900 JNIEnv* jni,
901 jobject j_output_buffer_info) {
902 return GetLongField(
903 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
904}
905
906bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800907 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000908 while (true) {
909 jobject j_output_buffer_info = jni->CallObjectMethod(
910 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
911 CHECK_EXCEPTION(jni);
912 if (IsNull(jni, j_output_buffer_info)) {
913 break;
914 }
915
916 int output_buffer_index =
917 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
918 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800919 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000920 return false;
921 }
922
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000923 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000924 jobject j_output_buffer =
925 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
926 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000927
928 // Get frame timestamps from a queue - for non config frames only.
929 int64_t frame_encoding_time_ms = 0;
930 last_output_timestamp_ms_ =
931 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
932 1000;
933 if (frames_in_queue_ > 0) {
934 output_timestamp_ = timestamps_.front();
935 timestamps_.erase(timestamps_.begin());
936 output_render_time_ms_ = render_times_ms_.front();
937 render_times_ms_.erase(render_times_ms_.begin());
938 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
939 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
940 frames_in_queue_--;
941 }
942
943 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000944 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200945 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000946 jni->GetDirectBufferAddress(j_output_buffer));
947 CHECK_EXCEPTION(jni);
948
glaznevf4decb52016-01-15 13:49:22 -0800949 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800950 int current_latency =
951 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
952 ALOGD << "Encoder frame out # " << frames_encoded_ <<
953 ". Key: " << key_frame <<
954 ". Size: " << payload_size <<
955 ". TS: " << (int)last_output_timestamp_ms_ <<
956 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800957 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000958 }
959
960 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000961 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000962 if (callback_) {
963 scoped_ptr<webrtc::EncodedImage> image(
964 new webrtc::EncodedImage(payload, payload_size, payload_size));
965 image->_encodedWidth = width_;
966 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000967 image->_timeStamp = output_timestamp_;
968 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200969 image->_frameType =
970 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000971 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700972 image->adapt_reason_.quality_resolution_downscales =
973 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000974
975 webrtc::CodecSpecificInfo info;
976 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000977 info.codecType = codecType_;
978 if (codecType_ == kVideoCodecVP8) {
979 info.codecSpecific.VP8.pictureId = picture_id_;
980 info.codecSpecific.VP8.nonReference = false;
981 info.codecSpecific.VP8.simulcastIdx = 0;
982 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
983 info.codecSpecific.VP8.layerSync = false;
984 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
985 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800986 } else if (codecType_ == kVideoCodecVP9) {
987 if (key_frame) {
988 gof_idx_ = 0;
989 }
990 info.codecSpecific.VP9.picture_id = picture_id_;
991 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
992 info.codecSpecific.VP9.flexible_mode = false;
993 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
994 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
995 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
996 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
997 info.codecSpecific.VP9.temporal_up_switch = true;
998 info.codecSpecific.VP9.inter_layer_predicted = false;
999 info.codecSpecific.VP9.gof_idx =
1000 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1001 info.codecSpecific.VP9.num_spatial_layers = 1;
1002 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1003 if (info.codecSpecific.VP9.ss_data_available) {
1004 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1005 info.codecSpecific.VP9.width[0] = width_;
1006 info.codecSpecific.VP9.height[0] = height_;
1007 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1008 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001009 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001010 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001011
1012 // Generate a header describing a single fragment.
1013 webrtc::RTPFragmentationHeader header;
1014 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001015 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001016 header.VerifyAndAllocateFragmentationHeader(1);
1017 header.fragmentationOffset[0] = 0;
1018 header.fragmentationLength[0] = image->_length;
1019 header.fragmentationPlType[0] = 0;
1020 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001021 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001022 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001023 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1024 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001025 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001026 }
asapersson86b01602015-10-20 23:55:26 -07001027 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001028 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001029 if (scale_) {
1030 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1031 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001032 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1033 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001034 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001035 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001036 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001037 // For H.264 search for start codes.
1038 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1039 int32_t scPositionsLength = 0;
1040 int32_t scPosition = 0;
1041 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1042 int32_t naluPosition = NextNaluPosition(
1043 payload + scPosition, payload_size - scPosition);
1044 if (naluPosition < 0) {
1045 break;
1046 }
1047 scPosition += naluPosition;
1048 scPositions[scPositionsLength++] = scPosition;
1049 scPosition += H264_SC_LENGTH;
1050 }
1051 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001052 ALOGE << "Start code is not found!";
1053 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1054 << " " << image->_buffer[2] << " " << image->_buffer[3]
1055 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001056 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001057 return false;
1058 }
1059 scPositions[scPositionsLength] = payload_size;
1060 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1061 for (size_t i = 0; i < scPositionsLength; i++) {
1062 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1063 header.fragmentationLength[i] =
1064 scPositions[i + 1] - header.fragmentationOffset[i];
1065 header.fragmentationPlType[i] = 0;
1066 header.fragmentationTimeDiff[i] = 0;
1067 }
1068 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001069
1070 callback_status = callback_->Encoded(*image, &info, &header);
1071 }
1072
1073 // Return output buffer back to the encoder.
1074 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1075 j_release_output_buffer_method_,
1076 output_buffer_index);
1077 CHECK_EXCEPTION(jni);
1078 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001079 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001080 return false;
1081 }
1082
glaznevf4decb52016-01-15 13:49:22 -08001083 // Calculate and print encoding statistics - every 3 seconds.
1084 frames_encoded_++;
1085 current_frames_++;
1086 current_bytes_ += payload_size;
1087 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001088 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001089
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001090 if (callback_status > 0) {
1091 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001092 // Theoretically could handle callback_status<0 here, but unclear what
1093 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001094 }
1095 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001096 return true;
1097}
1098
glaznev94291482016-02-01 13:17:18 -08001099void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1100 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1101 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1102 current_frames_ > 0 && statistic_time_ms > 0) {
1103 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1104 int current_fps =
1105 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1106 ALOGD << "Encoded frames: " << frames_encoded_ <<
1107 ". Bitrate: " << current_bitrate <<
1108 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1109 ", fps: " << current_fps <<
1110 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1111 ". QP: " << (current_acc_qp_ / current_frames_) <<
1112 " for last " << statistic_time_ms << " ms.";
1113 stat_start_time_ms_ = GetCurrentTimeMs();
1114 current_frames_ = 0;
1115 current_bytes_ = 0;
1116 current_acc_qp_ = 0;
1117 current_encoding_time_ms_ = 0;
1118 }
1119}
1120
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001121int32_t MediaCodecVideoEncoder::NextNaluPosition(
1122 uint8_t *buffer, size_t buffer_size) {
1123 if (buffer_size < H264_SC_LENGTH) {
1124 return -1;
1125 }
1126 uint8_t *head = buffer;
1127 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1128 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1129 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1130
1131 while (head < end) {
1132 if (head[0]) {
1133 head++;
1134 continue;
1135 }
1136 if (head[1]) { // got 00xx
1137 head += 2;
1138 continue;
1139 }
1140 if (head[2]) { // got 0000xx
1141 head += 3;
1142 continue;
1143 }
1144 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001145 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001146 continue;
1147 }
1148 return (int32_t)(head - buffer);
1149 }
1150 return -1;
1151}
1152
jackychen61b4d512015-04-21 15:30:11 -07001153void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001154 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001155 if (scale_)
1156 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001157}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001158
jackychen6e2ce6e2015-07-13 16:26:33 -07001159int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001160 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001161}
1162
Peter Boströmb7d9a972015-12-18 16:01:11 +01001163const char* MediaCodecVideoEncoder::ImplementationName() const {
1164 return "MediaCodec";
1165}
1166
perkj461121c2016-02-15 06:28:36 -08001167MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1168 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001169 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1170 ScopedLocalRefFrame local_ref_frame(jni);
1171 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001172 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001173
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001174 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1175 j_encoder_class,
1176 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1177 CHECK_EXCEPTION(jni);
1178 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001179 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001180 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1181 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1182 }
1183
Alex Glaznevad948c42015-11-18 13:06:42 -08001184 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1185 j_encoder_class,
1186 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1187 CHECK_EXCEPTION(jni);
1188 if (is_vp9_hw_supported) {
1189 ALOGD << "VP9 HW Encoder supported.";
1190 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1191 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1192 }
1193
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001194 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1195 j_encoder_class,
1196 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1197 CHECK_EXCEPTION(jni);
1198 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001199 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001200 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1201 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1202 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001203}
1204
Perec2922f2016-01-27 15:25:46 +01001205MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1206 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001207 if (egl_context_) {
1208 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1209 jni->DeleteGlobalRef(egl_context_);
1210 }
Perec2922f2016-01-27 15:25:46 +01001211}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001212
perkj30e91822015-11-20 01:31:25 -08001213void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001214 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001215 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001216 if (egl_context_) {
1217 jni->DeleteGlobalRef(egl_context_);
1218 egl_context_ = nullptr;
1219 }
perkj461121c2016-02-15 06:28:36 -08001220 egl_context_ = jni->NewGlobalRef(egl_context);
1221 if (CheckException(jni)) {
1222 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001223 }
1224}
1225
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001226webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001227 VideoCodecType type) {
1228 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001229 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001230 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001231 }
1232 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1233 it != supported_codecs_.end(); ++it) {
1234 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001235 ALOGD << "Create HW video encoder for type " << (int)type <<
1236 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001237 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001238 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001239 }
1240 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001241 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001242 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001243}
1244
1245const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1246MediaCodecVideoEncoderFactory::codecs() const {
1247 return supported_codecs_;
1248}
1249
1250void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1251 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001252 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001253 delete encoder;
1254}
1255
1256} // namespace webrtc_jni
1257