blob: 69060f8508f448f8494f5c6157884a1b26564fd2 [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 */) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000355 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700356 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000357 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
358 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000359 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700360 RTC_CHECK(codec_settings->codecType == codecType_)
361 << "Unsupported codec " << codec_settings->codecType << " for "
362 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000363
asapersson1d61a512016-01-20 01:13:46 -0800364 codec_mode_ = codec_settings->mode;
Alex Glazneva9d08922016-02-19 15:24:06 -0800365 int init_width = codec_settings->width;
366 int init_height = codec_settings->height;
Peter Boström7ace4882016-04-14 00:54:56 +0200367 scale_ = codecType_ != kVideoCodecVP9;
Alex Glazneva9d08922016-02-19 15:24:06 -0800368
369 ALOGD << "InitEncode request: " << init_width << " x " << init_height;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700370 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Alex Glazneva9d08922016-02-19 15:24:06 -0800371
Peter Boström2bc68c72015-09-24 16:22:28 +0200372 if (scale_) {
373 if (codecType_ == kVideoCodecVP8) {
374 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
375 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
376 // always = 127. Note that in SW, QP is that of the user-level range [0,
377 // 63].
Alex Glaznev79299af2016-04-12 16:39:39 -0700378 const int kLowQpThreshold = 29;
Peter Boström2c8a2962016-04-18 12:58:02 +0200379 const int kBadQpThreshold = 100;
Alex Glazneva9d08922016-02-19 15:24:06 -0800380 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
pboscbac40d2016-04-13 02:51:02 -0700381 codec_settings->startBitrate, codec_settings->width,
382 codec_settings->height,
383 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200384 } else if (codecType_ == kVideoCodecH264) {
385 // H264 QP is in the range [0, 51].
Peter Boström2c8a2962016-04-18 12:58:02 +0200386 const int kLowQpThreshold = 24;
387 const int kBadQpThreshold = 39;
Alex Glazneva9d08922016-02-19 15:24:06 -0800388 quality_scaler_.Init(kLowQpThreshold, kBadQpThreshold, false,
pboscbac40d2016-04-13 02:51:02 -0700389 codec_settings->startBitrate, codec_settings->width,
390 codec_settings->height,
391 codec_settings->maxFramerate);
Peter Boström2bc68c72015-09-24 16:22:28 +0200392 } else {
393 // When adding codec support to additional hardware codecs, also configure
394 // their QP thresholds for scaling.
395 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
Alex Glazneva9d08922016-02-19 15:24:06 -0800396 scale_ = false;
Peter Boström2bc68c72015-09-24 16:22:28 +0200397 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800398 QualityScaler::Resolution res = quality_scaler_.GetScaledResolution();
Peter Boström926dfcd2016-04-14 14:48:10 +0200399 init_width = res.width;
400 init_height = res.height;
Alex Glazneva9d08922016-02-19 15:24:06 -0800401 ALOGD << "Scaled resolution: " << init_width << " x " << init_height;
jackychen61b4d512015-04-21 15:30:11 -0700402 }
Alex Glazneva9d08922016-02-19 15:24:06 -0800403
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000404 return codec_thread_->Invoke<int32_t>(
405 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
406 this,
Alex Glazneva9d08922016-02-19 15:24:06 -0800407 init_width,
408 init_height,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000409 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800410 codec_settings->maxFramerate,
411 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000412}
413
414int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700415 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000416 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700417 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000418 return codec_thread_->Invoke<int32_t>(Bind(
419 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
420}
421
422int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
423 webrtc::EncodedImageCallback* callback) {
424 return codec_thread_->Invoke<int32_t>(
425 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
426 this,
427 callback));
428}
429
430int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700431 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000432 return codec_thread_->Invoke<int32_t>(
433 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
434}
435
436int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
437 int64_t /* rtt */) {
438 return WEBRTC_VIDEO_CODEC_OK;
439}
440
441int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
442 uint32_t frame_rate) {
443 return codec_thread_->Invoke<int32_t>(
444 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
445 this,
446 new_bit_rate,
447 frame_rate));
448}
449
450void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800451 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000452 JNIEnv* jni = AttachCurrentThreadIfNeeded();
453 ScopedLocalRefFrame local_ref_frame(jni);
454
455 // We only ever send one message to |this| directly (not through a Bind()'d
456 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700457 RTC_CHECK(!msg->message_id) << "Unexpected message!";
458 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000459 if (!inited_) {
460 return;
461 }
462
463 // It would be nice to recover from a failure here if one happened, but it's
464 // unclear how to signal such a failure to the app, so instead we stay silent
465 // about it and let the next app-called API method reveal the borkedness.
466 DeliverPendingOutputs(jni);
467 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
468}
469
perkj9576e542015-11-12 06:43:16 -0800470bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
471 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
472 ALOGE << "ResetOnCodecThread";
473 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800474 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
475 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000476 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
477 // degrade to a SW encoder at this point? There isn't one AFAICT :(
478 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800479 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000480 }
perkj9576e542015-11-12 06:43:16 -0800481 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000482}
483
484int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800485 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800486 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800487 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000488 JNIEnv* jni = AttachCurrentThreadIfNeeded();
489 ScopedLocalRefFrame local_ref_frame(jni);
490
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700491 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
492 width << " x " << height << ". Bitrate: " << kbps <<
493 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000494 if (kbps == 0) {
495 kbps = last_set_bitrate_kbps_;
496 }
497 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800498 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000499 }
500
501 width_ = width;
502 height_ = height;
503 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800504 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000505 yuv_size_ = width_ * height_ * 3 / 2;
506 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000507 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800508 frames_dropped_media_encoder_ = 0;
509 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000510 frames_in_queue_ = 0;
511 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800512 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000513 current_frames_ = 0;
514 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800515 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000516 current_encoding_time_ms_ = 0;
517 last_input_timestamp_ms_ = -1;
518 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000519 output_timestamp_ = 0;
520 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 timestamps_.clear();
522 render_times_ms_.clear();
523 frame_rtc_times_ms_.clear();
524 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800525 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000526 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800527 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
528 tl0_pic_idx_ = static_cast<uint8_t>(rand());
529 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800530 last_frame_received_ms_ = -1;
531 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800532
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000533 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100534 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000535 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800536 const bool encode_status = jni->CallBooleanMethod(
537 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800538 j_video_codec_enum, width, height, kbps, fps,
539 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800540 if (!encode_status) {
541 ALOGE << "Failed to configure encoder.";
542 return WEBRTC_VIDEO_CODEC_ERROR;
543 }
544 CHECK_EXCEPTION(jni);
545
Per598242a2015-11-26 14:28:55 +0100546 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800547 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
548 jni->CallObjectMethod(*j_media_codec_video_encoder_,
549 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000550 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800551 if (IsNull(jni, input_buffers)) {
552 return WEBRTC_VIDEO_CODEC_ERROR;
553 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000554
perkj30e91822015-11-20 01:31:25 -0800555 switch (GetIntField(jni, *j_media_codec_video_encoder_,
556 j_color_format_field_)) {
557 case COLOR_FormatYUV420Planar:
558 encoder_fourcc_ = libyuv::FOURCC_YU12;
559 break;
560 case COLOR_FormatYUV420SemiPlanar:
561 case COLOR_QCOM_FormatYUV420SemiPlanar:
562 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
563 encoder_fourcc_ = libyuv::FOURCC_NV12;
564 break;
565 default:
566 LOG(LS_ERROR) << "Wrong color format.";
567 return WEBRTC_VIDEO_CODEC_ERROR;
568 }
569 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
570 RTC_CHECK(input_buffers_.empty())
571 << "Unexpected double InitEncode without Release";
572 input_buffers_.resize(num_input_buffers);
573 for (size_t i = 0; i < num_input_buffers; ++i) {
574 input_buffers_[i] =
575 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
576 int64_t yuv_buffer_capacity =
577 jni->GetDirectBufferCapacity(input_buffers_[i]);
578 CHECK_EXCEPTION(jni);
579 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
580 }
581 }
perkj9576e542015-11-12 06:43:16 -0800582
583 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000584 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
585 return WEBRTC_VIDEO_CODEC_OK;
586}
587
588int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700589 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700590 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800591 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000592 JNIEnv* jni = AttachCurrentThreadIfNeeded();
593 ScopedLocalRefFrame local_ref_frame(jni);
594
595 if (!inited_) {
596 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
597 }
perkj9576e542015-11-12 06:43:16 -0800598
asapersson1d61a512016-01-20 01:13:46 -0800599 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800600 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800601 ++frames_received_since_last_key_;
602 int64_t now_ms = GetCurrentTimeMs();
603 if (last_frame_received_ms_ != -1 &&
604 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
605 // Add limit to prevent triggering a key for every frame for very low
606 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
607 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
608 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
609 send_key_frame = true;
610 }
611 frames_received_since_last_key_ = 0;
612 }
613 last_frame_received_ms_ = now_ms;
614 }
615
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000616 frames_received_++;
617 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800618 if (!ResetCodecOnCodecThread())
619 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000620 }
glaznevf4decb52016-01-15 13:49:22 -0800621 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800622 ALOGD << "Encoder frame in # " << (frames_received_ - 1) <<
623 ". TS: " << (int)(current_timestamp_us_ / 1000) <<
624 ". Q: " << frames_in_queue_ <<
625 ". Fps: " << last_set_fps_ <<
626 ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800627 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000628
629 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800630 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000631 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800632 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800633 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800634 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000635 return WEBRTC_VIDEO_CODEC_OK;
636 }
637
henrikg91d6ede2015-09-17 00:24:34 -0700638 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200639
Peter Boströmf7704d12016-04-11 16:42:40 +0200640 // Check if we accumulated too many frames in encoder input buffers and drop
641 // frame if so.
642 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE) {
643 ALOGD << "Already " << frames_in_queue_ << " frames in the queue, dropping"
644 << ". TS: " << (int)(current_timestamp_us_ / 1000)
645 << ". Fps: " << last_set_fps_
646 << ". Consecutive drops: " << consecutive_full_queue_frame_drops_;
647 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
648 consecutive_full_queue_frame_drops_++;
649 if (consecutive_full_queue_frame_drops_ >=
650 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
651 ALOGE << "Encoder got stuck. Reset.";
652 ResetCodecOnCodecThread();
653 return WEBRTC_VIDEO_CODEC_ERROR;
glaznevf4decb52016-01-15 13:49:22 -0800654 }
Peter Boströmf7704d12016-04-11 16:42:40 +0200655 frames_dropped_media_encoder_++;
656 OnDroppedFrame();
657 return WEBRTC_VIDEO_CODEC_OK;
glaznevf4decb52016-01-15 13:49:22 -0800658 }
glaznev919ff752016-01-27 15:01:03 -0800659 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800660
Per598242a2015-11-26 14:28:55 +0100661 VideoFrame input_frame = frame;
662 if (scale_) {
663 // Check framerate before spatial resolution change.
664 quality_scaler_.OnEncodeFrame(frame);
665 const webrtc::QualityScaler::Resolution scaled_resolution =
666 quality_scaler_.GetScaledResolution();
667 if (scaled_resolution.width != frame.width() ||
668 scaled_resolution.height != frame.height()) {
nisse26acec42016-04-15 03:43:39 -0700669 if (frame.video_frame_buffer()->native_handle() != nullptr) {
Per598242a2015-11-26 14:28:55 +0100670 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
671 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100672 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100673 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100674 scaled_resolution.height,
675 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100676 input_frame.set_video_frame_buffer(scaled_buffer);
677 } else {
678 input_frame = quality_scaler_.GetScaledFrame(frame);
679 }
680 }
681 }
jackychen61b4d512015-04-21 15:30:11 -0700682
perkj9576e542015-11-12 06:43:16 -0800683 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
684 ALOGE << "Failed to reconfigure encoder.";
685 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000686 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000687
glaznevf4decb52016-01-15 13:49:22 -0800688 // Save time when input frame is sent to the encoder input.
689 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000690
asapersson1d61a512016-01-20 01:13:46 -0800691 const bool key_frame =
692 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800693 bool encode_status = true;
nisse26acec42016-04-15 03:43:39 -0700694 if (!input_frame.video_frame_buffer()->native_handle()) {
perkj30e91822015-11-20 01:31:25 -0800695 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
696 j_dequeue_input_buffer_method_);
697 CHECK_EXCEPTION(jni);
698 if (j_input_buffer_index == -1) {
699 // Video codec falls behind - no input buffer available.
700 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800701 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800702 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
703 frames_dropped_media_encoder_++;
704 OnDroppedFrame();
perkj30e91822015-11-20 01:31:25 -0800705 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
706 }
707 if (j_input_buffer_index == -2) {
708 ResetCodecOnCodecThread();
709 return WEBRTC_VIDEO_CODEC_ERROR;
710 }
711 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
712 j_input_buffer_index);
713 } else {
714 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000715 }
perkj30e91822015-11-20 01:31:25 -0800716
717 if (!encode_status) {
718 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800719 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200720 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000721 }
722
perkj9576e542015-11-12 06:43:16 -0800723 last_input_timestamp_ms_ =
724 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200725 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000726
perkj12f68022015-10-16 13:31:45 +0200727 // Save input image timestamps for later output
728 timestamps_.push_back(input_frame.timestamp());
729 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800730 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
731
perkj30e91822015-11-20 01:31:25 -0800732 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800733 ALOGE << "Failed deliver pending outputs.";
734 ResetCodecOnCodecThread();
735 return WEBRTC_VIDEO_CODEC_ERROR;
736 }
737 return WEBRTC_VIDEO_CODEC_OK;
738}
739
740bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
741 const webrtc::VideoFrame& frame) {
742 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
743
nisse26acec42016-04-15 03:43:39 -0700744 const bool is_texture_frame =
745 frame.video_frame_buffer()->native_handle() != nullptr;
perkj30e91822015-11-20 01:31:25 -0800746 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800747 const bool reconfigure_due_to_size =
748 frame.width() != width_ || frame.height() != height_;
749
perkj30e91822015-11-20 01:31:25 -0800750 if (reconfigure_due_to_format) {
751 ALOGD << "Reconfigure encoder due to format change. "
752 << (use_surface_ ?
753 "Reconfiguring to encode from byte buffer." :
754 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800755 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800756 }
perkj9576e542015-11-12 06:43:16 -0800757 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800758 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800759 << width_ << " x " << height_ << " to " << frame.width() << " x "
760 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800761 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800762 width_ = frame.width();
763 height_ = frame.height();
764 }
765
perkj30e91822015-11-20 01:31:25 -0800766 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800767 return true;
768
769 ReleaseOnCodecThread();
770
perkj30e91822015-11-20 01:31:25 -0800771 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800772 WEBRTC_VIDEO_CODEC_OK;
773}
774
775bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
776 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
777 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800778 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800779
perkj9576e542015-11-12 06:43:16 -0800780 jobject j_input_buffer = input_buffers_[input_buffer_index];
781 uint8_t* yuv_buffer =
782 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
783 CHECK_EXCEPTION(jni);
784 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
785 RTC_CHECK(!libyuv::ConvertFromI420(
786 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
787 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
788 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
789 yuv_buffer, width_, width_, height_, encoder_fourcc_))
790 << "ConvertFromI420 failed";
791
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000792 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800793 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000794 key_frame,
perkj9576e542015-11-12 06:43:16 -0800795 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000796 yuv_size_,
797 current_timestamp_us_);
798 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800799 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000800}
801
perkj30e91822015-11-20 01:31:25 -0800802bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
803 bool key_frame, const webrtc::VideoFrame& frame) {
804 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
805 RTC_CHECK(use_surface_);
nisse26acec42016-04-15 03:43:39 -0700806 NativeHandleImpl* handle = static_cast<NativeHandleImpl*>(
807 frame.video_frame_buffer()->native_handle());
perkj30e91822015-11-20 01:31:25 -0800808 jfloatArray sampling_matrix = jni->NewFloatArray(16);
809 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
810
811 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
812 j_encode_texture_method_,
813 key_frame,
814 handle->oes_texture_id,
815 sampling_matrix,
816 current_timestamp_us_);
817 CHECK_EXCEPTION(jni);
818 return encode_status;
819}
820
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000821int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
822 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800823 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000824 JNIEnv* jni = AttachCurrentThreadIfNeeded();
825 ScopedLocalRefFrame local_ref_frame(jni);
826 callback_ = callback;
827 return WEBRTC_VIDEO_CODEC_OK;
828}
829
830int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800831 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000832 if (!inited_) {
833 return WEBRTC_VIDEO_CODEC_OK;
834 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000835 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700836 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
837 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800838 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000839 ScopedLocalRefFrame local_ref_frame(jni);
840 for (size_t i = 0; i < input_buffers_.size(); ++i)
841 jni->DeleteGlobalRef(input_buffers_[i]);
842 input_buffers_.clear();
843 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
844 CHECK_EXCEPTION(jni);
845 rtc::MessageQueueManager::Clear(this);
846 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800847 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700848 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000849 return WEBRTC_VIDEO_CODEC_OK;
850}
851
852int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
853 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800854 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800855 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
856 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000857 if (last_set_bitrate_kbps_ == new_bit_rate &&
858 last_set_fps_ == frame_rate) {
859 return WEBRTC_VIDEO_CODEC_OK;
860 }
glaznev919ff752016-01-27 15:01:03 -0800861 if (scale_) {
862 quality_scaler_.ReportFramerate(frame_rate);
863 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000864 JNIEnv* jni = AttachCurrentThreadIfNeeded();
865 ScopedLocalRefFrame local_ref_frame(jni);
866 if (new_bit_rate > 0) {
867 last_set_bitrate_kbps_ = new_bit_rate;
868 }
869 if (frame_rate > 0) {
870 last_set_fps_ = frame_rate;
871 }
872 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
873 j_set_rates_method_,
874 last_set_bitrate_kbps_,
875 last_set_fps_);
876 CHECK_EXCEPTION(jni);
877 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800878 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000879 return WEBRTC_VIDEO_CODEC_ERROR;
880 }
881 return WEBRTC_VIDEO_CODEC_OK;
882}
883
884int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
885 JNIEnv* jni,
886 jobject j_output_buffer_info) {
887 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
888}
889
890jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
891 JNIEnv* jni,
892 jobject j_output_buffer_info) {
893 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
894}
895
896bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
897 JNIEnv* jni,
898 jobject j_output_buffer_info) {
899 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
900}
901
902jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
903 JNIEnv* jni,
904 jobject j_output_buffer_info) {
905 return GetLongField(
906 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
907}
908
909bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800910 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000911 while (true) {
912 jobject j_output_buffer_info = jni->CallObjectMethod(
913 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
914 CHECK_EXCEPTION(jni);
915 if (IsNull(jni, j_output_buffer_info)) {
916 break;
917 }
918
919 int output_buffer_index =
920 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
921 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800922 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000923 return false;
924 }
925
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000926 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000927 jobject j_output_buffer =
928 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
929 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000930
931 // Get frame timestamps from a queue - for non config frames only.
932 int64_t frame_encoding_time_ms = 0;
933 last_output_timestamp_ms_ =
934 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
935 1000;
936 if (frames_in_queue_ > 0) {
937 output_timestamp_ = timestamps_.front();
938 timestamps_.erase(timestamps_.begin());
939 output_render_time_ms_ = render_times_ms_.front();
940 render_times_ms_.erase(render_times_ms_.begin());
941 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
942 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
943 frames_in_queue_--;
944 }
945
946 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000947 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200948 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000949 jni->GetDirectBufferAddress(j_output_buffer));
950 CHECK_EXCEPTION(jni);
951
glaznevf4decb52016-01-15 13:49:22 -0800952 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800953 int current_latency =
954 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
955 ALOGD << "Encoder frame out # " << frames_encoded_ <<
956 ". Key: " << key_frame <<
957 ". Size: " << payload_size <<
958 ". TS: " << (int)last_output_timestamp_ms_ <<
959 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800960 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000961 }
962
963 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000964 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000965 if (callback_) {
966 scoped_ptr<webrtc::EncodedImage> image(
967 new webrtc::EncodedImage(payload, payload_size, payload_size));
968 image->_encodedWidth = width_;
969 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000970 image->_timeStamp = output_timestamp_;
971 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200972 image->_frameType =
973 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000974 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700975 image->adapt_reason_.quality_resolution_downscales =
976 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000977
978 webrtc::CodecSpecificInfo info;
979 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000980 info.codecType = codecType_;
981 if (codecType_ == kVideoCodecVP8) {
982 info.codecSpecific.VP8.pictureId = picture_id_;
983 info.codecSpecific.VP8.nonReference = false;
984 info.codecSpecific.VP8.simulcastIdx = 0;
985 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
986 info.codecSpecific.VP8.layerSync = false;
987 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
988 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800989 } else if (codecType_ == kVideoCodecVP9) {
990 if (key_frame) {
991 gof_idx_ = 0;
992 }
993 info.codecSpecific.VP9.picture_id = picture_id_;
994 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
995 info.codecSpecific.VP9.flexible_mode = false;
996 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
997 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
998 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
999 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1000 info.codecSpecific.VP9.temporal_up_switch = true;
1001 info.codecSpecific.VP9.inter_layer_predicted = false;
1002 info.codecSpecific.VP9.gof_idx =
1003 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1004 info.codecSpecific.VP9.num_spatial_layers = 1;
1005 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1006 if (info.codecSpecific.VP9.ss_data_available) {
1007 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1008 info.codecSpecific.VP9.width[0] = width_;
1009 info.codecSpecific.VP9.height[0] = height_;
1010 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1011 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001012 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001013 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001014
1015 // Generate a header describing a single fragment.
1016 webrtc::RTPFragmentationHeader header;
1017 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001018 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001019 header.VerifyAndAllocateFragmentationHeader(1);
1020 header.fragmentationOffset[0] = 0;
1021 header.fragmentationLength[0] = image->_length;
1022 header.fragmentationPlType[0] = 0;
1023 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001024 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001025 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001026 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1027 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001028 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001029 }
asapersson86b01602015-10-20 23:55:26 -07001030 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001031 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001032 if (scale_) {
1033 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1034 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001035 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1036 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001037 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001038 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001039 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001040 // For H.264 search for start codes.
1041 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1042 int32_t scPositionsLength = 0;
1043 int32_t scPosition = 0;
1044 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1045 int32_t naluPosition = NextNaluPosition(
1046 payload + scPosition, payload_size - scPosition);
1047 if (naluPosition < 0) {
1048 break;
1049 }
1050 scPosition += naluPosition;
1051 scPositions[scPositionsLength++] = scPosition;
1052 scPosition += H264_SC_LENGTH;
1053 }
1054 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001055 ALOGE << "Start code is not found!";
1056 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1057 << " " << image->_buffer[2] << " " << image->_buffer[3]
1058 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001059 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001060 return false;
1061 }
1062 scPositions[scPositionsLength] = payload_size;
1063 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1064 for (size_t i = 0; i < scPositionsLength; i++) {
1065 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1066 header.fragmentationLength[i] =
1067 scPositions[i + 1] - header.fragmentationOffset[i];
1068 header.fragmentationPlType[i] = 0;
1069 header.fragmentationTimeDiff[i] = 0;
1070 }
1071 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001072
1073 callback_status = callback_->Encoded(*image, &info, &header);
1074 }
1075
1076 // Return output buffer back to the encoder.
1077 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1078 j_release_output_buffer_method_,
1079 output_buffer_index);
1080 CHECK_EXCEPTION(jni);
1081 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001082 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001083 return false;
1084 }
1085
glaznevf4decb52016-01-15 13:49:22 -08001086 // Calculate and print encoding statistics - every 3 seconds.
1087 frames_encoded_++;
1088 current_frames_++;
1089 current_bytes_ += payload_size;
1090 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001091 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001092
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001093 if (callback_status > 0) {
1094 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001095 // Theoretically could handle callback_status<0 here, but unclear what
1096 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001097 }
1098 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001099 return true;
1100}
1101
glaznev94291482016-02-01 13:17:18 -08001102void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1103 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1104 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1105 current_frames_ > 0 && statistic_time_ms > 0) {
1106 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1107 int current_fps =
1108 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1109 ALOGD << "Encoded frames: " << frames_encoded_ <<
1110 ". Bitrate: " << current_bitrate <<
1111 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1112 ", fps: " << current_fps <<
1113 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1114 ". QP: " << (current_acc_qp_ / current_frames_) <<
1115 " for last " << statistic_time_ms << " ms.";
1116 stat_start_time_ms_ = GetCurrentTimeMs();
1117 current_frames_ = 0;
1118 current_bytes_ = 0;
1119 current_acc_qp_ = 0;
1120 current_encoding_time_ms_ = 0;
1121 }
1122}
1123
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001124int32_t MediaCodecVideoEncoder::NextNaluPosition(
1125 uint8_t *buffer, size_t buffer_size) {
1126 if (buffer_size < H264_SC_LENGTH) {
1127 return -1;
1128 }
1129 uint8_t *head = buffer;
1130 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1131 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1132 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1133
1134 while (head < end) {
1135 if (head[0]) {
1136 head++;
1137 continue;
1138 }
1139 if (head[1]) { // got 00xx
1140 head += 2;
1141 continue;
1142 }
1143 if (head[2]) { // got 0000xx
1144 head += 3;
1145 continue;
1146 }
1147 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001148 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001149 continue;
1150 }
1151 return (int32_t)(head - buffer);
1152 }
1153 return -1;
1154}
1155
jackychen61b4d512015-04-21 15:30:11 -07001156void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001157 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001158 if (scale_)
1159 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001160}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001161
jackychen6e2ce6e2015-07-13 16:26:33 -07001162int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001163 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001164}
1165
Peter Boströmb7d9a972015-12-18 16:01:11 +01001166const char* MediaCodecVideoEncoder::ImplementationName() const {
1167 return "MediaCodec";
1168}
1169
perkj461121c2016-02-15 06:28:36 -08001170MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1171 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001172 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1173 ScopedLocalRefFrame local_ref_frame(jni);
1174 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001175 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001176
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001177 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1178 j_encoder_class,
1179 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1180 CHECK_EXCEPTION(jni);
1181 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001182 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001183 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1184 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1185 }
1186
Alex Glaznevad948c42015-11-18 13:06:42 -08001187 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1188 j_encoder_class,
1189 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1190 CHECK_EXCEPTION(jni);
1191 if (is_vp9_hw_supported) {
1192 ALOGD << "VP9 HW Encoder supported.";
1193 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1194 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1195 }
1196
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001197 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1198 j_encoder_class,
1199 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1200 CHECK_EXCEPTION(jni);
1201 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001202 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001203 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1204 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1205 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001206}
1207
Perec2922f2016-01-27 15:25:46 +01001208MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1209 ALOGD << "MediaCodecVideoEncoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -08001210 if (egl_context_) {
1211 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1212 jni->DeleteGlobalRef(egl_context_);
1213 }
Perec2922f2016-01-27 15:25:46 +01001214}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001215
perkj30e91822015-11-20 01:31:25 -08001216void MediaCodecVideoEncoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -08001217 JNIEnv* jni, jobject egl_context) {
perkj30e91822015-11-20 01:31:25 -08001218 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +01001219 if (egl_context_) {
1220 jni->DeleteGlobalRef(egl_context_);
1221 egl_context_ = nullptr;
1222 }
perkj461121c2016-02-15 06:28:36 -08001223 egl_context_ = jni->NewGlobalRef(egl_context);
1224 if (CheckException(jni)) {
1225 ALOGE << "error calling NewGlobalRef for EGL Context.";
perkj30e91822015-11-20 01:31:25 -08001226 }
1227}
1228
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001229webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001230 VideoCodecType type) {
1231 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001232 ALOGW << "No HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001233 return nullptr;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001234 }
1235 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1236 it != supported_codecs_.end(); ++it) {
1237 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001238 ALOGD << "Create HW video encoder for type " << (int)type <<
1239 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001240 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -08001241 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001242 }
1243 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001244 ALOGW << "Can not find HW video encoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +01001245 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001246}
1247
1248const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1249MediaCodecVideoEncoderFactory::codecs() const {
1250 return supported_codecs_;
1251}
1252
1253void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1254 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001255 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001256 delete encoder;
1257}
1258
1259} // namespace webrtc_jni