blob: d83c4314c6c558c0937ffcc344d1d605e8197cf6 [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 Glaznev79299af2016-04-12 16:39:39 -0700380 const int kLowQpThreshold = 29;
381 const int kBadQpThreshold = 90;
Alex Glazneva9d08922016-02-19 15:24:06 -0800382 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
pboscbac40d2016-04-13 02:51:02 -0700383 codec_settings->startBitrate, codec_settings->width,
384 codec_settings->height,
385 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200386 } else if (codecType_ == kVideoCodecH264) {
387 // H264 QP is in the range [0, 51].
Alex Glaznev67b81f92016-02-22 15:05:15 -0800388 const int kLowQpThreshold = 21;
Alex Glaznev79299af2016-04-12 16:39:39 -0700389 const int kBadQpThreshold = 33;
Alex Glazneva9d08922016-02-19 15:24:06 -0800390 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
pboscbac40d2016-04-13 02:51:02 -0700391 codec_settings->startBitrate, codec_settings->width,
392 codec_settings->height,
393 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200394 } else {
395 // When adding codec support to additional hardware codecs, also configure
396 // their QP thresholds for scaling.
397 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800398 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200399 }
Peter Boström01bcbd02016-03-22 21:44:29 +0100400 quality_scaler_.SetMinResolution(kMinDimension, kMinDimension);
Alex Glazneva9d08922016-02-19 15:24:06 -0800401 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström01bcbd02016-03-22 21:44:29 +0100402 init_width = std::max(res.width, kMinDimension);
403 init_height = std::max(res.height, kMinDimension);
Alex Glazneva9d08922016-02-19 15:24:06 -0800404 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700405 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800406
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000407 return codec_thread_->Invoke<int32_t>(
408 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
409 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800410 init_width,
411 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000412 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800413 codec_settings->maxFramerate,
414 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000415}
416
417int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700418 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000419 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700420 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000421 return codec_thread_->Invoke<int32_t>(Bind(
422 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
423}
424
425int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
426 webrtc::EncodedImageCallback* callback) {
427 return codec_thread_->Invoke<int32_t>(
428 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
429 this,
430 callback));
431}
432
433int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700434 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000435 return codec_thread_->Invoke<int32_t>(
436 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
437}
438
439int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
440 int64_t /* rtt */) {
441 return WEBRTC_VIDEO_CODEC_OK;
442}
443
444int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
445 uint32_t frame_rate) {
446 return codec_thread_->Invoke<int32_t>(
447 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
448 this,
449 new_bit_rate,
450 frame_rate));
451}
452
453void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800454 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000455 JNIEnv* jni = AttachCurrentThreadIfNeeded();
456 ScopedLocalRefFrame local_ref_frame(jni);
457
458 // We only ever send one message to |this| directly (not through a Bind()'d
459 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700460 RTC_CHECK(!msg->message_id) << "Unexpected message!";
461 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000462 if (!inited_) {
463 return;
464 }
465
466 // It would be nice to recover from a failure here if one happened, but it's
467 // unclear how to signal such a failure to the app, so instead we stay silent
468 // about it and let the next app-called API method reveal the borkedness.
469 DeliverPendingOutputs(jni);
470 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
471}
472
perkj9576e542015-11-12 06:43:16 -0800473bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
474 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
475 ALOGE << "ResetOnCodecThread";
476 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800477 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
478 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000479 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
480 // degrade to a SW encoder at this point? There isn't one AFAICT :(
481 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800482 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000483 }
perkj9576e542015-11-12 06:43:16 -0800484 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000485}
486
487int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800488 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800489 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800490 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000491 JNIEnv* jni = AttachCurrentThreadIfNeeded();
492 ScopedLocalRefFrame local_ref_frame(jni);
493
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700494 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
495 width << " x " << height << ". Bitrate: " << kbps <<
496 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000497 if (kbps == 0) {
498 kbps = last_set_bitrate_kbps_;
499 }
500 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800501 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000502 }
503
504 width_ = width;
505 height_ = height;
506 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800507 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000508 yuv_size_ = width_ * height_ * 3 / 2;
509 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000510 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800511 frames_dropped_media_encoder_ = 0;
512 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000513 frames_in_queue_ = 0;
514 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800515 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000516 current_frames_ = 0;
517 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800518 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000519 current_encoding_time_ms_ = 0;
520 last_input_timestamp_ms_ = -1;
521 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000522 output_timestamp_ = 0;
523 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000524 timestamps_.clear();
525 render_times_ms_.clear();
526 frame_rtc_times_ms_.clear();
527 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800528 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000529 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800530 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
531 tl0_pic_idx_ = static_cast<uint8_t>(rand());
532 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800533 last_frame_received_ms_ = -1;
534 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800535
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000536 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100537 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000538 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800539 const bool encode_status = jni->CallBooleanMethod(
540 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800541 j_video_codec_enum, width, height, kbps, fps,
542 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800543 if (!encode_status) {
544 ALOGE << "Failed to configure encoder.";
545 return WEBRTC_VIDEO_CODEC_ERROR;
546 }
547 CHECK_EXCEPTION(jni);
548
Per598242a2015-11-26 14:28:55 +0100549 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800550 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
551 jni->CallObjectMethod(*j_media_codec_video_encoder_,
552 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000553 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800554 if (IsNull(jni, input_buffers)) {
555 return WEBRTC_VIDEO_CODEC_ERROR;
556 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000557
perkj30e91822015-11-20 01:31:25 -0800558 switch (GetIntField(jni, *j_media_codec_video_encoder_,
559 j_color_format_field_)) {
560 case COLOR_FormatYUV420Planar:
561 encoder_fourcc_ = libyuv::FOURCC_YU12;
562 break;
563 case COLOR_FormatYUV420SemiPlanar:
564 case COLOR_QCOM_FormatYUV420SemiPlanar:
565 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
566 encoder_fourcc_ = libyuv::FOURCC_NV12;
567 break;
568 default:
569 LOG(LS_ERROR) << "Wrong color format.";
570 return WEBRTC_VIDEO_CODEC_ERROR;
571 }
572 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
573 RTC_CHECK(input_buffers_.empty())
574 << "Unexpected double InitEncode without Release";
575 input_buffers_.resize(num_input_buffers);
576 for (size_t i = 0; i < num_input_buffers; ++i) {
577 input_buffers_[i] =
578 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
579 int64_t yuv_buffer_capacity =
580 jni->GetDirectBufferCapacity(input_buffers_[i]);
581 CHECK_EXCEPTION(jni);
582 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
583 }
584 }
perkj9576e542015-11-12 06:43:16 -0800585
586 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000587 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
588 return WEBRTC_VIDEO_CODEC_OK;
589}
590
591int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700592 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700593 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800594 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000595 JNIEnv* jni = AttachCurrentThreadIfNeeded();
596 ScopedLocalRefFrame local_ref_frame(jni);
597
598 if (!inited_) {
599 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
600 }
perkj9576e542015-11-12 06:43:16 -0800601
asapersson1d61a512016-01-20 01:13:46 -0800602 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800603 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800604 ++frames_received_since_last_key_;
605 int64_t now_ms = GetCurrentTimeMs();
606 if (last_frame_received_ms_ != -1 &&
607 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
608 // Add limit to prevent triggering a key for every frame for very low
609 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
610 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
611 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
612 send_key_frame = true;
613 }
614 frames_received_since_last_key_ = 0;
615 }
616 last_frame_received_ms_ = now_ms;
617 }
618
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000619 frames_received_++;
620 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800621 if (!ResetCodecOnCodecThread())
622 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000623 }
glaznevf4decb52016-01-15 13:49:22 -0800624 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800625 ALOGD << "Encoder frame in # " << (frames_received_ - 1) <<
626 ". TS: " << (int)(current_timestamp_us_ / 1000) <<
627 ". Q: " << frames_in_queue_ <<
628 ". Fps: " << last_set_fps_ <<
629 ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800630 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000631
632 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800633 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000634 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800635 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800636 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800637 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000638 return WEBRTC_VIDEO_CODEC_OK;
639 }
640
henrikg91d6ede2015-09-17 00:24:34 -0700641 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200642
Peter Boströmf7704d12016-04-11 16:42:40 +0200643 // Check if we accumulated too many frames in encoder input buffers and drop
644 // frame if so.
645 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE) {
646 ALOGD << "Already " << frames_in_queue_ << " frames in the queue, dropping"
647 << ". TS: " << (int)(current_timestamp_us_ / 1000)
648 << ". Fps: " << last_set_fps_
649 << ". Consecutive drops: " << consecutive_full_queue_frame_drops_;
650 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
651 consecutive_full_queue_frame_drops_++;
652 if (consecutive_full_queue_frame_drops_ >=
653 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
654 ALOGE << "Encoder got stuck. Reset.";
655 ResetCodecOnCodecThread();
656 return WEBRTC_VIDEO_CODEC_ERROR;
glaznevf4decb52016-01-15 13:49:22 -0800657 }
Peter Boströmf7704d12016-04-11 16:42:40 +0200658 frames_dropped_media_encoder_++;
659 OnDroppedFrame();
660 return WEBRTC_VIDEO_CODEC_OK;
glaznevf4decb52016-01-15 13:49:22 -0800661 }
glaznev919ff752016-01-27 15:01:03 -0800662 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800663
Per598242a2015-11-26 14:28:55 +0100664 VideoFrame input_frame = frame;
665 if (scale_) {
666 // Check framerate before spatial resolution change.
667 quality_scaler_.OnEncodeFrame(frame);
668 const webrtc::QualityScaler::Resolution scaled_resolution =
669 quality_scaler_.GetScaledResolution();
670 if (scaled_resolution.width != frame.width() ||
671 scaled_resolution.height != frame.height()) {
672 if (frame.native_handle() != nullptr) {
673 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
674 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100675 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100676 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100677 scaled_resolution.height,
678 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100679 input_frame.set_video_frame_buffer(scaled_buffer);
680 } else {
681 input_frame = quality_scaler_.GetScaledFrame(frame);
682 }
683 }
684 }
jackychen61b4d512015-04-21 15:30:11 -0700685
perkj9576e542015-11-12 06:43:16 -0800686 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
687 ALOGE << "Failed to reconfigure encoder.";
688 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000689 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000690
glaznevf4decb52016-01-15 13:49:22 -0800691 // Save time when input frame is sent to the encoder input.
692 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000693
asapersson1d61a512016-01-20 01:13:46 -0800694 const bool key_frame =
695 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800696 bool encode_status = true;
697 if (!input_frame.native_handle()) {
698 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
699 j_dequeue_input_buffer_method_);
700 CHECK_EXCEPTION(jni);
701 if (j_input_buffer_index == -1) {
702 // Video codec falls behind - no input buffer available.
703 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800704 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800705 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
706 frames_dropped_media_encoder_++;
707 OnDroppedFrame();
perkj30e91822015-11-20 01:31:25 -0800708 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
709 }
710 if (j_input_buffer_index == -2) {
711 ResetCodecOnCodecThread();
712 return WEBRTC_VIDEO_CODEC_ERROR;
713 }
714 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
715 j_input_buffer_index);
716 } else {
717 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000718 }
perkj30e91822015-11-20 01:31:25 -0800719
720 if (!encode_status) {
721 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800722 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200723 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000724 }
725
perkj9576e542015-11-12 06:43:16 -0800726 last_input_timestamp_ms_ =
727 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200728 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000729
perkj12f68022015-10-16 13:31:45 +0200730 // Save input image timestamps for later output
731 timestamps_.push_back(input_frame.timestamp());
732 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800733 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
734
perkj30e91822015-11-20 01:31:25 -0800735 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800736 ALOGE << "Failed deliver pending outputs.";
737 ResetCodecOnCodecThread();
738 return WEBRTC_VIDEO_CODEC_ERROR;
739 }
740 return WEBRTC_VIDEO_CODEC_OK;
741}
742
743bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
744 const webrtc::VideoFrame& frame) {
745 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
746
perkj30e91822015-11-20 01:31:25 -0800747 const bool is_texture_frame = frame.native_handle() != nullptr;
748 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800749 const bool reconfigure_due_to_size =
750 frame.width() != width_ || frame.height() != height_;
751
perkj30e91822015-11-20 01:31:25 -0800752 if (reconfigure_due_to_format) {
753 ALOGD << "Reconfigure encoder due to format change. "
754 << (use_surface_ ?
755 "Reconfiguring to encode from byte buffer." :
756 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800757 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800758 }
perkj9576e542015-11-12 06:43:16 -0800759 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800760 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800761 << width_ << " x " << height_ << " to " << frame.width() << " x "
762 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800763 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800764 width_ = frame.width();
765 height_ = frame.height();
766 }
767
perkj30e91822015-11-20 01:31:25 -0800768 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800769 return true;
770
771 ReleaseOnCodecThread();
772
perkj30e91822015-11-20 01:31:25 -0800773 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800774 WEBRTC_VIDEO_CODEC_OK;
775}
776
777bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
778 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
779 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800780 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800781
perkj9576e542015-11-12 06:43:16 -0800782 jobject j_input_buffer = input_buffers_[input_buffer_index];
783 uint8_t* yuv_buffer =
784 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
785 CHECK_EXCEPTION(jni);
786 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
787 RTC_CHECK(!libyuv::ConvertFromI420(
788 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
789 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
790 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
791 yuv_buffer, width_, width_, height_, encoder_fourcc_))
792 << "ConvertFromI420 failed";
793
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000794 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800795 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000796 key_frame,
perkj9576e542015-11-12 06:43:16 -0800797 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000798 yuv_size_,
799 current_timestamp_us_);
800 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800801 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000802}
803
perkj30e91822015-11-20 01:31:25 -0800804bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
805 bool key_frame, const webrtc::VideoFrame& frame) {
806 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
807 RTC_CHECK(use_surface_);
808 NativeHandleImpl* handle =
809 static_cast<NativeHandleImpl*>(frame.native_handle());
810 jfloatArray sampling_matrix = jni->NewFloatArray(16);
811 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
812
813 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
814 j_encode_texture_method_,
815 key_frame,
816 handle->oes_texture_id,
817 sampling_matrix,
818 current_timestamp_us_);
819 CHECK_EXCEPTION(jni);
820 return encode_status;
821}
822
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000823int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
824 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800825 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000826 JNIEnv* jni = AttachCurrentThreadIfNeeded();
827 ScopedLocalRefFrame local_ref_frame(jni);
828 callback_ = callback;
829 return WEBRTC_VIDEO_CODEC_OK;
830}
831
832int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800833 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000834 if (!inited_) {
835 return WEBRTC_VIDEO_CODEC_OK;
836 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000837 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700838 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
839 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800840 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000841 ScopedLocalRefFrame local_ref_frame(jni);
842 for (size_t i = 0; i < input_buffers_.size(); ++i)
843 jni->DeleteGlobalRef(input_buffers_[i]);
844 input_buffers_.clear();
845 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
846 CHECK_EXCEPTION(jni);
847 rtc::MessageQueueManager::Clear(this);
848 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800849 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700850 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000851 return WEBRTC_VIDEO_CODEC_OK;
852}
853
854int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
855 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800856 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800857 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
858 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000859 if (last_set_bitrate_kbps_ == new_bit_rate &&
860 last_set_fps_ == frame_rate) {
861 return WEBRTC_VIDEO_CODEC_OK;
862 }
glaznev919ff752016-01-27 15:01:03 -0800863 if (scale_) {
864 quality_scaler_.ReportFramerate(frame_rate);
865 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000866 JNIEnv* jni = AttachCurrentThreadIfNeeded();
867 ScopedLocalRefFrame local_ref_frame(jni);
868 if (new_bit_rate > 0) {
869 last_set_bitrate_kbps_ = new_bit_rate;
870 }
871 if (frame_rate > 0) {
872 last_set_fps_ = frame_rate;
873 }
874 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
875 j_set_rates_method_,
876 last_set_bitrate_kbps_,
877 last_set_fps_);
878 CHECK_EXCEPTION(jni);
879 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800880 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000881 return WEBRTC_VIDEO_CODEC_ERROR;
882 }
883 return WEBRTC_VIDEO_CODEC_OK;
884}
885
886int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
887 JNIEnv* jni,
888 jobject j_output_buffer_info) {
889 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
890}
891
892jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
893 JNIEnv* jni,
894 jobject j_output_buffer_info) {
895 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
896}
897
898bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
899 JNIEnv* jni,
900 jobject j_output_buffer_info) {
901 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
902}
903
904jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
905 JNIEnv* jni,
906 jobject j_output_buffer_info) {
907 return GetLongField(
908 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
909}
910
911bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800912 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000913 while (true) {
914 jobject j_output_buffer_info = jni->CallObjectMethod(
915 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
916 CHECK_EXCEPTION(jni);
917 if (IsNull(jni, j_output_buffer_info)) {
918 break;
919 }
920
921 int output_buffer_index =
922 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
923 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800924 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000925 return false;
926 }
927
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000928 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000929 jobject j_output_buffer =
930 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
931 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000932
933 // Get frame timestamps from a queue - for non config frames only.
934 int64_t frame_encoding_time_ms = 0;
935 last_output_timestamp_ms_ =
936 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
937 1000;
938 if (frames_in_queue_ > 0) {
939 output_timestamp_ = timestamps_.front();
940 timestamps_.erase(timestamps_.begin());
941 output_render_time_ms_ = render_times_ms_.front();
942 render_times_ms_.erase(render_times_ms_.begin());
943 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
944 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
945 frames_in_queue_--;
946 }
947
948 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000949 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200950 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000951 jni->GetDirectBufferAddress(j_output_buffer));
952 CHECK_EXCEPTION(jni);
953
glaznevf4decb52016-01-15 13:49:22 -0800954 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800955 int current_latency =
956 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
957 ALOGD << "Encoder frame out # " << frames_encoded_ <<
958 ". Key: " << key_frame <<
959 ". Size: " << payload_size <<
960 ". TS: " << (int)last_output_timestamp_ms_ <<
961 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800962 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000963 }
964
965 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000966 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000967 if (callback_) {
968 scoped_ptr<webrtc::EncodedImage> image(
969 new webrtc::EncodedImage(payload, payload_size, payload_size));
970 image->_encodedWidth = width_;
971 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000972 image->_timeStamp = output_timestamp_;
973 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200974 image->_frameType =
975 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000976 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700977 image->adapt_reason_.quality_resolution_downscales =
978 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000979
980 webrtc::CodecSpecificInfo info;
981 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000982 info.codecType = codecType_;
983 if (codecType_ == kVideoCodecVP8) {
984 info.codecSpecific.VP8.pictureId = picture_id_;
985 info.codecSpecific.VP8.nonReference = false;
986 info.codecSpecific.VP8.simulcastIdx = 0;
987 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
988 info.codecSpecific.VP8.layerSync = false;
989 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
990 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800991 } else if (codecType_ == kVideoCodecVP9) {
992 if (key_frame) {
993 gof_idx_ = 0;
994 }
995 info.codecSpecific.VP9.picture_id = picture_id_;
996 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
997 info.codecSpecific.VP9.flexible_mode = false;
998 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
999 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1000 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1001 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1002 info.codecSpecific.VP9.temporal_up_switch = true;
1003 info.codecSpecific.VP9.inter_layer_predicted = false;
1004 info.codecSpecific.VP9.gof_idx =
1005 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1006 info.codecSpecific.VP9.num_spatial_layers = 1;
1007 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1008 if (info.codecSpecific.VP9.ss_data_available) {
1009 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1010 info.codecSpecific.VP9.width[0] = width_;
1011 info.codecSpecific.VP9.height[0] = height_;
1012 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1013 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001014 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001015 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001016
1017 // Generate a header describing a single fragment.
1018 webrtc::RTPFragmentationHeader header;
1019 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001020 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001021 header.VerifyAndAllocateFragmentationHeader(1);
1022 header.fragmentationOffset[0] = 0;
1023 header.fragmentationLength[0] = image->_length;
1024 header.fragmentationPlType[0] = 0;
1025 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001026 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001027 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001028 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1029 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001030 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001031 }
asapersson86b01602015-10-20 23:55:26 -07001032 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001033 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001034 if (scale_) {
1035 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1036 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001037 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1038 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001039 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001040 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001041 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001042 // For H.264 search for start codes.
1043 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1044 int32_t scPositionsLength = 0;
1045 int32_t scPosition = 0;
1046 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1047 int32_t naluPosition = NextNaluPosition(
1048 payload + scPosition, payload_size - scPosition);
1049 if (naluPosition < 0) {
1050 break;
1051 }
1052 scPosition += naluPosition;
1053 scPositions[scPositionsLength++] = scPosition;
1054 scPosition += H264_SC_LENGTH;
1055 }
1056 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001057 ALOGE << "Start code is not found!";
1058 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1059 << " " << image->_buffer[2] << " " << image->_buffer[3]
1060 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001061 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001062 return false;
1063 }
1064 scPositions[scPositionsLength] = payload_size;
1065 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1066 for (size_t i = 0; i < scPositionsLength; i++) {
1067 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1068 header.fragmentationLength[i] =
1069 scPositions[i + 1] - header.fragmentationOffset[i];
1070 header.fragmentationPlType[i] = 0;
1071 header.fragmentationTimeDiff[i] = 0;
1072 }
1073 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001074
1075 callback_status = callback_->Encoded(*image, &info, &header);
1076 }
1077
1078 // Return output buffer back to the encoder.
1079 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1080 j_release_output_buffer_method_,
1081 output_buffer_index);
1082 CHECK_EXCEPTION(jni);
1083 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001084 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001085 return false;
1086 }
1087
glaznevf4decb52016-01-15 13:49:22 -08001088 // Calculate and print encoding statistics - every 3 seconds.
1089 frames_encoded_++;
1090 current_frames_++;
1091 current_bytes_ += payload_size;
1092 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001093 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001094
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001095 if (callback_status > 0) {
1096 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001097 // Theoretically could handle callback_status<0 here, but unclear what
1098 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001099 }
1100 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001101 return true;
1102}
1103
glaznev94291482016-02-01 13:17:18 -08001104void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1105 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1106 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1107 current_frames_ > 0 && statistic_time_ms > 0) {
1108 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1109 int current_fps =
1110 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1111 ALOGD << "Encoded frames: " << frames_encoded_ <<
1112 ". Bitrate: " << current_bitrate <<
1113 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1114 ", fps: " << current_fps <<
1115 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1116 ". QP: " << (current_acc_qp_ / current_frames_) <<
1117 " for last " << statistic_time_ms << " ms.";
1118 stat_start_time_ms_ = GetCurrentTimeMs();
1119 current_frames_ = 0;
1120 current_bytes_ = 0;
1121 current_acc_qp_ = 0;
1122 current_encoding_time_ms_ = 0;
1123 }
1124}
1125
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001126int32_t MediaCodecVideoEncoder::NextNaluPosition(
1127 uint8_t *buffer, size_t buffer_size) {
1128 if (buffer_size < H264_SC_LENGTH) {
1129 return -1;
1130 }
1131 uint8_t *head = buffer;
1132 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1133 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1134 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1135
1136 while (head < end) {
1137 if (head[0]) {
1138 head++;
1139 continue;
1140 }
1141 if (head[1]) { // got 00xx
1142 head += 2;
1143 continue;
1144 }
1145 if (head[2]) { // got 0000xx
1146 head += 3;
1147 continue;
1148 }
1149 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001150 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001151 continue;
1152 }
1153 return (int32_t)(head - buffer);
1154 }
1155 return -1;
1156}
1157
jackychen61b4d512015-04-21 15:30:11 -07001158void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001159 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001160 if (scale_)
1161 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001162}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001163
jackychen6e2ce6e2015-07-13 16:26:33 -07001164int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001165 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001166}
1167
Peter Boströmb7d9a972015-12-18 16:01:11 +01001168const char* MediaCodecVideoEncoder::ImplementationName() const {
1169 return "MediaCodec";
1170}
1171
perkj461121c2016-02-15 06:28:36 -08001172MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1173 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001174 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1175 ScopedLocalRefFrame local_ref_frame(jni);
1176 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001177 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001178
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001179 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1180 j_encoder_class,
1181 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1182 CHECK_EXCEPTION(jni);
1183 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001184 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001185 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1186 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1187 }
1188
Alex Glaznevad948c42015-11-18 13:06:42 -08001189 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1190 j_encoder_class,
1191 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1192 CHECK_EXCEPTION(jni);
1193 if (is_vp9_hw_supported) {
1194 ALOGD << "VP9 HW Encoder supported.";
1195 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1196 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1197 }
1198
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001199 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1200 j_encoder_class,
1201 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1202 CHECK_EXCEPTION(jni);
1203 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001204 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001205 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1206 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1207 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001208}
1209
Perec2922f2016-01-27 15:25:46 +01001210MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1211 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001212 if (egl_context_) {
1213 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1214 jni->DeleteGlobalRef(egl_context_);
1215 }
Perec2922f2016-01-27 15:25:46 +01001216}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001217
perkj30e91822015-11-20 01:31:25 -08001218void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001219 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001220 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001221 if (egl_context_) {
1222 jni->DeleteGlobalRef(egl_context_);
1223 egl_context_ = nullptr;
1224 }
perkj461121c2016-02-15 06:28:36 -08001225 egl_context_ = jni->NewGlobalRef(egl_context);
1226 if (CheckException(jni)) {
1227 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001228 }
1229}
1230
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001231webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001232 VideoCodecType type) {
1233 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001234 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001235 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001236 }
1237 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1238 it != supported_codecs_.end(); ++it) {
1239 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001240 ALOGD << "Create HW video encoder for type " << (int)type <<
1241 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001242 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001243 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001244 }
1245 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001246 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001247 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001248}
1249
1250const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1251MediaCodecVideoEncoderFactory::codecs() const {
1252 return supported_codecs_;
1253}
1254
1255void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1256 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001257 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001258 delete encoder;
1259}
1260
1261} // namespace webrtc_jni
1262