blob: 8b5933f940fd7a009cc969fd5b6987014add2ef5 [file] [log] [blame]
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001/*
2 * libjingle
3 * Copyright 2015 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 *
27 */
28
29#include "talk/app/webrtc/java/jni/androidmediaencoder_jni.h"
30#include "talk/app/webrtc/java/jni/classreferenceholder.h"
31#include "talk/app/webrtc/java/jni/androidmediacodeccommon.h"
perkj30e91822015-11-20 01:31:25 -080032#include "talk/app/webrtc/java/jni/native_handle_impl.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000033#include "webrtc/base/bind.h"
34#include "webrtc/base/checks.h"
35#include "webrtc/base/logging.h"
36#include "webrtc/base/thread.h"
perkj9576e542015-11-12 06:43:16 -080037#include "webrtc/base/thread_checker.h"
asapersson1d61a512016-01-20 01:13:46 -080038#include "webrtc/common_types.h"
Peter Boström2bc68c72015-09-24 16:22:28 +020039#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080040#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010041#include "webrtc/modules/video_coding/utility/quality_scaler.h"
42#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/field_trial.h"
44#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000045#include "third_party/libyuv/include/libyuv/convert.h"
46#include "third_party/libyuv/include/libyuv/convert_from.h"
47#include "third_party/libyuv/include/libyuv/video_common.h"
48
49using rtc::Bind;
50using rtc::Thread;
51using rtc::ThreadManager;
52using rtc::scoped_ptr;
53
54using webrtc::CodecSpecificInfo;
55using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070056using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000057using webrtc::RTPFragmentationHeader;
58using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000059using webrtc::VideoCodecType;
60using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000061using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080062using webrtc::kVideoCodecVP9;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000063
64namespace webrtc_jni {
65
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000066// H.264 start code length.
67#define H264_SC_LENGTH 4
68// Maximum allowed NALUs in one output frame.
69#define MAX_NALUS_PERFRAME 32
70// Maximum supported HW video encoder resolution.
71#define MAX_VIDEO_WIDTH 1280
72#define MAX_VIDEO_HEIGHT 1280
73// Maximum supported HW video encoder fps.
74#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080075// Maximum allowed fps value in SetRates() call.
76#define MAX_ALLOWED_VIDEO_FPS 60
77// Maximum allowed frames in encoder input queue.
78#define MAX_ENCODER_Q_SIZE 2
79// Maximum allowed latency in ms.
80#define MAX_ENCODER_LATENCY_MS 70
glaznev919ff752016-01-27 15:01:03 -080081// Maximum amount of dropped frames caused by full encoder queue - exceeding
82// this threshold means that encoder probably got stuck and need to be reset.
83#define ENCODER_STALL_FRAMEDROP_THRESHOLD 60
glaznevf4decb52016-01-15 13:49:22 -080084
85// Logging macros.
86#define TAG_ENCODER "MediaCodecVideoEncoder"
87#ifdef TRACK_BUFFER_TIMING
88#define ALOGV(...)
89 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
90#else
91#define ALOGV(...)
92#endif
93#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
94#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
95#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000096
asapersson1d61a512016-01-20 01:13:46 -080097namespace {
98// Maximum time limit between incoming frames before requesting a key frame.
99const size_t kFrameDiffThresholdMs = 1100;
100const int kMinKeyFrameInterval = 2;
101} // namespace
102
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000103// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
104// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
105// HW-backed video encode. This C++ class is implemented as a very thin shim,
106// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
107// MediaCodecVideoEncoder is created, operated, and destroyed on a single
108// thread, currently the libjingle Worker thread.
109class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
110 public rtc::MessageHandler {
111 public:
112 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -0800113 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800114 VideoCodecType codecType,
115 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000116
117 // webrtc::VideoEncoder implementation. Everything trampolines to
118 // |codec_thread_| for execution.
119 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
120 int32_t /* number_of_cores */,
121 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700122 int32_t Encode(const webrtc::VideoFrame& input_image,
123 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
124 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000125 int32_t RegisterEncodeCompleteCallback(
126 webrtc::EncodedImageCallback* callback) override;
127 int32_t Release() override;
128 int32_t SetChannelParameters(uint32_t /* packet_loss */,
129 int64_t /* rtt */) override;
130 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
131
132 // rtc::MessageHandler implementation.
133 void OnMessage(rtc::Message* msg) override;
134
jackychen61b4d512015-04-21 15:30:11 -0700135 void OnDroppedFrame() override;
136
jackychen6e2ce6e2015-07-13 16:26:33 -0700137 int GetTargetFramerate() override;
138
Perec2922f2016-01-27 15:25:46 +0100139 bool SupportsNativeHandle() const override { return egl_context_ != nullptr; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100140 const char* ImplementationName() const override;
141
142 private:
143 // CHECK-fail if not running on |codec_thread_|.
144 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800145
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000146 private:
perkj9576e542015-11-12 06:43:16 -0800147 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
148 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000149 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800150 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000151
152 // Implementation of webrtc::VideoEncoder methods above, all running on the
153 // codec thread exclusively.
154 //
155 // If width==0 then this is assumed to be a re-initialization and the
156 // previously-current values are reused instead of the passed parameters
157 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800158 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
159 bool use_surface);
160 // Reconfigure to match |frame| in width, height. Also reconfigures the
161 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
162 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800163 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000164 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700165 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700166 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800167 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
168 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800169 bool EncodeTextureOnCodecThread(JNIEnv* jni,
170 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800171
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000172 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
173 webrtc::EncodedImageCallback* callback);
174 int32_t ReleaseOnCodecThread();
175 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
176
177 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
178 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
179 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
180 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
181 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000182 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000183
184 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
185 // true on success.
186 bool DeliverPendingOutputs(JNIEnv* jni);
187
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000188 // Search for H.264 start codes.
189 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
190
glaznev94291482016-02-01 13:17:18 -0800191 // Displays encoder statistics.
192 void LogStatistics(bool force_log);
193
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000194 // Type of video codec.
195 VideoCodecType codecType_;
196
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000197 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
198 // |codec_thread_| synchronously.
199 webrtc::EncodedImageCallback* callback_;
200
201 // State that is constant for the lifetime of this object once the ctor
202 // returns.
203 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800204 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000205 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
206 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
207 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800208 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000209 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800210 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800211 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000212 jmethodID j_release_method_;
213 jmethodID j_set_rates_method_;
214 jmethodID j_dequeue_output_buffer_method_;
215 jmethodID j_release_output_buffer_method_;
216 jfieldID j_color_format_field_;
217 jfieldID j_info_index_field_;
218 jfieldID j_info_buffer_field_;
219 jfieldID j_info_is_key_frame_field_;
220 jfieldID j_info_presentation_timestamp_us_field_;
221
222 // State that is valid only between InitEncode() and the next Release().
223 // Touched only on codec_thread_ so no explicit synchronization necessary.
224 int width_; // Frame width in pixels.
225 int height_; // Frame height in pixels.
226 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800227 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000228 uint16_t picture_id_;
229 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
230 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
231 int last_set_fps_; // Last-requested frame rate.
232 int64_t current_timestamp_us_; // Current frame timestamps in us.
233 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000234 int frames_encoded_; // Number of frames encoded by encoder.
glaznev919ff752016-01-27 15:01:03 -0800235 int frames_dropped_media_encoder_; // Number of frames dropped by encoder.
236 // Number of dropped frames caused by full queue.
237 int consecutive_full_queue_frame_drops_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000238 int frames_in_queue_; // Number of frames in encoder queue.
glaznev94291482016-02-01 13:17:18 -0800239 int64_t stat_start_time_ms_; // Start time for statistics.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000240 int current_frames_; // Number of frames in the current statistics interval.
241 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800242 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000243 int current_encoding_time_ms_; // Overall encoding time in the current second
244 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
245 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
246 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
247 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
248 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
249 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000250 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
251 int64_t output_render_time_ms_; // Last output frame render time from
252 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000253 // Frame size in bytes fed to MediaCodec.
254 int yuv_size_;
255 // True only when between a callback_->Encoded() call return a positive value
256 // and the next Encode() call being ignored.
257 bool drop_next_input_frame_;
258 // Global references; must be deleted in Release().
259 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200260 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700261 // Dynamic resolution change, off by default.
262 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200263
264 // H264 bitstream parser, used to extract QP from encoded bitstreams.
265 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800266
267 // VP9 variables to populate codec specific structure.
268 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
269 // non-flexible VP9 mode.
270 uint8_t tl0_pic_idx_;
271 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800272
273 // EGL context - owned by factory, should not be allocated/destroyed
274 // by MediaCodecVideoEncoder.
275 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800276
277 // Temporary fix for VP8.
278 // Sends a key frame if frames are largely spaced apart (possibly
279 // corresponding to a large image change).
280 int64_t last_frame_received_ms_;
281 int frames_received_since_last_key_;
282 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000283};
284
285MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
286 // Call Release() to ensure no more callbacks to us after we are deleted.
287 Release();
288}
289
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000290MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800291 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000292 codecType_(codecType),
293 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000294 codec_thread_(new Thread()),
295 j_media_codec_video_encoder_class_(
296 jni,
297 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
298 j_media_codec_video_encoder_(
299 jni,
300 jni->NewObject(*j_media_codec_video_encoder_class_,
301 GetMethodID(jni,
302 *j_media_codec_video_encoder_class_,
303 "<init>",
perkj30e91822015-11-20 01:31:25 -0800304 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800305 inited_(false),
306 use_surface_(false),
307 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800308 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000309 ScopedLocalRefFrame local_ref_frame(jni);
310 // It would be nice to avoid spinning up a new thread per MediaCodec, and
311 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
312 // 2732 means that deadlocks abound. This class synchronously trampolines
313 // to |codec_thread_|, so if anything else can be coming to _us_ from
314 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
315 // in the bug, we have a problem. For now work around that with a dedicated
316 // thread.
317 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700318 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800319 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000320 jclass j_output_buffer_info_class =
321 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000322 j_init_encode_method_ = GetMethodID(
323 jni,
324 *j_media_codec_video_encoder_class_,
325 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800326 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800327 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800328 j_get_input_buffers_method_ = GetMethodID(
329 jni,
330 *j_media_codec_video_encoder_class_,
331 "getInputBuffers",
332 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000333 j_dequeue_input_buffer_method_ = GetMethodID(
334 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800335 j_encode_buffer_method_ = GetMethodID(
336 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800337 j_encode_texture_method_ = GetMethodID(
338 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
339 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000340 j_release_method_ =
341 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
342 j_set_rates_method_ = GetMethodID(
343 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000344 j_dequeue_output_buffer_method_ = GetMethodID(
345 jni,
346 *j_media_codec_video_encoder_class_,
347 "dequeueOutputBuffer",
348 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000349 j_release_output_buffer_method_ = GetMethodID(
350 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
351
352 j_color_format_field_ =
353 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
354 j_info_index_field_ =
355 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
356 j_info_buffer_field_ = GetFieldID(
357 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
358 j_info_is_key_frame_field_ =
359 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
360 j_info_presentation_timestamp_us_field_ = GetFieldID(
361 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
362 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800363 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000364 AllowBlockingCalls();
365}
366
367int32_t MediaCodecVideoEncoder::InitEncode(
368 const webrtc::VideoCodec* codec_settings,
369 int32_t /* number_of_cores */,
370 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700371 const int kMinWidth = 320;
372 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700373 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000374 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700375 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000376 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
377 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000378 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700379 RTC_CHECK(codec_settings->codecType == codecType_)
380 << "Unsupported codec " << codec_settings->codecType << " for "
381 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000382
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700383 ALOGD << "InitEncode request";
asapersson1d61a512016-01-20 01:13:46 -0800384 codec_mode_ = codec_settings->mode;
Alex Glaznevad948c42015-11-18 13:06:42 -0800385 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
386 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700387 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200388 if (scale_) {
389 if (codecType_ == kVideoCodecVP8) {
390 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
391 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
392 // always = 127. Note that in SW, QP is that of the user-level range [0,
393 // 63].
394 const int kMaxQp = 127;
glaznev919ff752016-01-27 15:01:03 -0800395 const int kBadQpThreshold = 95;
396 quality_scaler_.Init(
397 kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold, false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200398 } else if (codecType_ == kVideoCodecH264) {
399 // H264 QP is in the range [0, 51].
400 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200401 const int kBadQpThreshold = 40;
glaznev919ff752016-01-27 15:01:03 -0800402 quality_scaler_.Init(
403 kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold, false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200404 } else {
405 // When adding codec support to additional hardware codecs, also configure
406 // their QP thresholds for scaling.
407 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
408 }
409 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
410 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700411 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000412 return codec_thread_->Invoke<int32_t>(
413 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
414 this,
415 codec_settings->width,
416 codec_settings->height,
417 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800418 codec_settings->maxFramerate,
419 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000420}
421
422int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700423 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000424 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700425 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000426 return codec_thread_->Invoke<int32_t>(Bind(
427 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
428}
429
430int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
431 webrtc::EncodedImageCallback* callback) {
432 return codec_thread_->Invoke<int32_t>(
433 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
434 this,
435 callback));
436}
437
438int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700439 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000440 return codec_thread_->Invoke<int32_t>(
441 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
442}
443
444int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
445 int64_t /* rtt */) {
446 return WEBRTC_VIDEO_CODEC_OK;
447}
448
449int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
450 uint32_t frame_rate) {
451 return codec_thread_->Invoke<int32_t>(
452 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
453 this,
454 new_bit_rate,
455 frame_rate));
456}
457
458void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800459 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000460 JNIEnv* jni = AttachCurrentThreadIfNeeded();
461 ScopedLocalRefFrame local_ref_frame(jni);
462
463 // We only ever send one message to |this| directly (not through a Bind()'d
464 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700465 RTC_CHECK(!msg->message_id) << "Unexpected message!";
466 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000467 if (!inited_) {
468 return;
469 }
470
471 // It would be nice to recover from a failure here if one happened, but it's
472 // unclear how to signal such a failure to the app, so instead we stay silent
473 // about it and let the next app-called API method reveal the borkedness.
474 DeliverPendingOutputs(jni);
475 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
476}
477
perkj9576e542015-11-12 06:43:16 -0800478bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
479 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
480 ALOGE << "ResetOnCodecThread";
481 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800482 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
483 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000484 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
485 // degrade to a SW encoder at this point? There isn't one AFAICT :(
486 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800487 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000488 }
perkj9576e542015-11-12 06:43:16 -0800489 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000490}
491
492int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800493 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800494 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800495 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000496 JNIEnv* jni = AttachCurrentThreadIfNeeded();
497 ScopedLocalRefFrame local_ref_frame(jni);
498
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700499 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
500 width << " x " << height << ". Bitrate: " << kbps <<
501 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000502 if (kbps == 0) {
503 kbps = last_set_bitrate_kbps_;
504 }
505 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800506 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000507 }
508
509 width_ = width;
510 height_ = height;
511 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800512 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000513 yuv_size_ = width_ * height_ * 3 / 2;
514 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000515 frames_encoded_ = 0;
glaznev919ff752016-01-27 15:01:03 -0800516 frames_dropped_media_encoder_ = 0;
517 consecutive_full_queue_frame_drops_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000518 frames_in_queue_ = 0;
519 current_timestamp_us_ = 0;
glaznev94291482016-02-01 13:17:18 -0800520 stat_start_time_ms_ = GetCurrentTimeMs();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000521 current_frames_ = 0;
522 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800523 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000524 current_encoding_time_ms_ = 0;
525 last_input_timestamp_ms_ = -1;
526 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000527 output_timestamp_ = 0;
528 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000529 timestamps_.clear();
530 render_times_ms_.clear();
531 frame_rtc_times_ms_.clear();
532 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800533 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000534 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800535 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
536 tl0_pic_idx_ = static_cast<uint8_t>(rand());
537 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800538 last_frame_received_ms_ = -1;
539 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800540
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000541 // We enforce no extra stride/padding in the format creation step.
Perec2922f2016-01-27 15:25:46 +0100542 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000543 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800544 const bool encode_status = jni->CallBooleanMethod(
545 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800546 j_video_codec_enum, width, height, kbps, fps,
547 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800548 if (!encode_status) {
549 ALOGE << "Failed to configure encoder.";
550 return WEBRTC_VIDEO_CODEC_ERROR;
551 }
552 CHECK_EXCEPTION(jni);
553
Per598242a2015-11-26 14:28:55 +0100554 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800555 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
556 jni->CallObjectMethod(*j_media_codec_video_encoder_,
557 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000558 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800559 if (IsNull(jni, input_buffers)) {
560 return WEBRTC_VIDEO_CODEC_ERROR;
561 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000562
perkj30e91822015-11-20 01:31:25 -0800563 switch (GetIntField(jni, *j_media_codec_video_encoder_,
564 j_color_format_field_)) {
565 case COLOR_FormatYUV420Planar:
566 encoder_fourcc_ = libyuv::FOURCC_YU12;
567 break;
568 case COLOR_FormatYUV420SemiPlanar:
569 case COLOR_QCOM_FormatYUV420SemiPlanar:
570 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
571 encoder_fourcc_ = libyuv::FOURCC_NV12;
572 break;
573 default:
574 LOG(LS_ERROR) << "Wrong color format.";
575 return WEBRTC_VIDEO_CODEC_ERROR;
576 }
577 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
578 RTC_CHECK(input_buffers_.empty())
579 << "Unexpected double InitEncode without Release";
580 input_buffers_.resize(num_input_buffers);
581 for (size_t i = 0; i < num_input_buffers; ++i) {
582 input_buffers_[i] =
583 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
584 int64_t yuv_buffer_capacity =
585 jni->GetDirectBufferCapacity(input_buffers_[i]);
586 CHECK_EXCEPTION(jni);
587 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
588 }
589 }
perkj9576e542015-11-12 06:43:16 -0800590
591 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000592 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
593 return WEBRTC_VIDEO_CODEC_OK;
594}
595
596int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700597 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700598 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800599 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000600 JNIEnv* jni = AttachCurrentThreadIfNeeded();
601 ScopedLocalRefFrame local_ref_frame(jni);
602
603 if (!inited_) {
604 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
605 }
perkj9576e542015-11-12 06:43:16 -0800606
asapersson1d61a512016-01-20 01:13:46 -0800607 bool send_key_frame = false;
glaznev94291482016-02-01 13:17:18 -0800608 if (codec_mode_ == webrtc::kRealtimeVideo) {
asapersson1d61a512016-01-20 01:13:46 -0800609 ++frames_received_since_last_key_;
610 int64_t now_ms = GetCurrentTimeMs();
611 if (last_frame_received_ms_ != -1 &&
612 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
613 // Add limit to prevent triggering a key for every frame for very low
614 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
615 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
616 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
617 send_key_frame = true;
618 }
619 frames_received_since_last_key_ = 0;
620 }
621 last_frame_received_ms_ = now_ms;
622 }
623
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000624 frames_received_++;
625 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800626 if (!ResetCodecOnCodecThread())
627 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000628 }
glaznevf4decb52016-01-15 13:49:22 -0800629 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800630 ALOGD << "Encoder frame in # " << (frames_received_ - 1) <<
631 ". TS: " << (int)(current_timestamp_us_ / 1000) <<
632 ". Q: " << frames_in_queue_ <<
633 ". Fps: " << last_set_fps_ <<
634 ". Kbps: " << last_set_bitrate_kbps_;
glaznevf4decb52016-01-15 13:49:22 -0800635 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000636
637 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800638 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000639 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800640 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800641 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800642 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000643 return WEBRTC_VIDEO_CODEC_OK;
644 }
645
henrikg91d6ede2015-09-17 00:24:34 -0700646 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200647
glaznevf4decb52016-01-15 13:49:22 -0800648 // Check if we accumulated too many frames in encoder input buffers
649 // or the encoder latency exceeds 70 ms and drop frame if so.
650 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
651 int encoder_latency_ms = last_input_timestamp_ms_ -
652 last_output_timestamp_ms_;
653 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE ||
654 encoder_latency_ms > MAX_ENCODER_LATENCY_MS) {
655 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
glaznev94291482016-02-01 13:17:18 -0800656 " ms. Q size: " << frames_in_queue_ << ". TS: " <<
657 (int)(current_timestamp_us_ / 1000) << ". Fps: " << last_set_fps_ <<
658 ". Consecutive drops: " << consecutive_full_queue_frame_drops_ ;
glaznevf4decb52016-01-15 13:49:22 -0800659 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
glaznev919ff752016-01-27 15:01:03 -0800660 consecutive_full_queue_frame_drops_++;
661 if (consecutive_full_queue_frame_drops_ >=
662 ENCODER_STALL_FRAMEDROP_THRESHOLD) {
663 ALOGE << "Encoder got stuck. Reset.";
664 ResetCodecOnCodecThread();
665 return WEBRTC_VIDEO_CODEC_ERROR;
666 }
667 frames_dropped_media_encoder_++;
glaznevf4decb52016-01-15 13:49:22 -0800668 OnDroppedFrame();
669 return WEBRTC_VIDEO_CODEC_OK;
670 }
671 }
glaznev919ff752016-01-27 15:01:03 -0800672 consecutive_full_queue_frame_drops_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800673
Per598242a2015-11-26 14:28:55 +0100674 VideoFrame input_frame = frame;
675 if (scale_) {
676 // Check framerate before spatial resolution change.
677 quality_scaler_.OnEncodeFrame(frame);
678 const webrtc::QualityScaler::Resolution scaled_resolution =
679 quality_scaler_.GetScaledResolution();
680 if (scaled_resolution.width != frame.width() ||
681 scaled_resolution.height != frame.height()) {
682 if (frame.native_handle() != nullptr) {
683 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
684 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100685 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100686 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100687 scaled_resolution.height,
688 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100689 input_frame.set_video_frame_buffer(scaled_buffer);
690 } else {
691 input_frame = quality_scaler_.GetScaledFrame(frame);
692 }
693 }
694 }
jackychen61b4d512015-04-21 15:30:11 -0700695
perkj9576e542015-11-12 06:43:16 -0800696 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
697 ALOGE << "Failed to reconfigure encoder.";
698 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000699 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000700
glaznevf4decb52016-01-15 13:49:22 -0800701 // Save time when input frame is sent to the encoder input.
702 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000703
asapersson1d61a512016-01-20 01:13:46 -0800704 const bool key_frame =
705 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800706 bool encode_status = true;
707 if (!input_frame.native_handle()) {
708 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
709 j_dequeue_input_buffer_method_);
710 CHECK_EXCEPTION(jni);
711 if (j_input_buffer_index == -1) {
712 // Video codec falls behind - no input buffer available.
713 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800714 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
glaznev919ff752016-01-27 15:01:03 -0800715 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
716 frames_dropped_media_encoder_++;
717 OnDroppedFrame();
perkj30e91822015-11-20 01:31:25 -0800718 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
719 }
720 if (j_input_buffer_index == -2) {
721 ResetCodecOnCodecThread();
722 return WEBRTC_VIDEO_CODEC_ERROR;
723 }
724 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
725 j_input_buffer_index);
726 } else {
727 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000728 }
perkj30e91822015-11-20 01:31:25 -0800729
730 if (!encode_status) {
731 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800732 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200733 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000734 }
735
perkj9576e542015-11-12 06:43:16 -0800736 last_input_timestamp_ms_ =
737 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200738 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000739
perkj12f68022015-10-16 13:31:45 +0200740 // Save input image timestamps for later output
741 timestamps_.push_back(input_frame.timestamp());
742 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800743 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
744
perkj30e91822015-11-20 01:31:25 -0800745 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800746 ALOGE << "Failed deliver pending outputs.";
747 ResetCodecOnCodecThread();
748 return WEBRTC_VIDEO_CODEC_ERROR;
749 }
750 return WEBRTC_VIDEO_CODEC_OK;
751}
752
753bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
754 const webrtc::VideoFrame& frame) {
755 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
756
perkj30e91822015-11-20 01:31:25 -0800757 const bool is_texture_frame = frame.native_handle() != nullptr;
758 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800759 const bool reconfigure_due_to_size =
760 frame.width() != width_ || frame.height() != height_;
761
perkj30e91822015-11-20 01:31:25 -0800762 if (reconfigure_due_to_format) {
763 ALOGD << "Reconfigure encoder due to format change. "
764 << (use_surface_ ?
765 "Reconfiguring to encode from byte buffer." :
766 "Reconfiguring to encode from texture.");
glaznev94291482016-02-01 13:17:18 -0800767 LogStatistics(true);
perkj30e91822015-11-20 01:31:25 -0800768 }
perkj9576e542015-11-12 06:43:16 -0800769 if (reconfigure_due_to_size) {
glaznev94291482016-02-01 13:17:18 -0800770 ALOGW << "Reconfigure encoder due to frame resolution change from "
perkj9576e542015-11-12 06:43:16 -0800771 << width_ << " x " << height_ << " to " << frame.width() << " x "
772 << frame.height();
glaznev94291482016-02-01 13:17:18 -0800773 LogStatistics(true);
perkj9576e542015-11-12 06:43:16 -0800774 width_ = frame.width();
775 height_ = frame.height();
776 }
777
perkj30e91822015-11-20 01:31:25 -0800778 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800779 return true;
780
781 ReleaseOnCodecThread();
782
perkj30e91822015-11-20 01:31:25 -0800783 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800784 WEBRTC_VIDEO_CODEC_OK;
785}
786
787bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
788 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
789 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800790 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800791
perkj9576e542015-11-12 06:43:16 -0800792 jobject j_input_buffer = input_buffers_[input_buffer_index];
793 uint8_t* yuv_buffer =
794 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
795 CHECK_EXCEPTION(jni);
796 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
797 RTC_CHECK(!libyuv::ConvertFromI420(
798 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
799 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
800 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
801 yuv_buffer, width_, width_, height_, encoder_fourcc_))
802 << "ConvertFromI420 failed";
803
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000804 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800805 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000806 key_frame,
perkj9576e542015-11-12 06:43:16 -0800807 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000808 yuv_size_,
809 current_timestamp_us_);
810 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800811 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000812}
813
perkj30e91822015-11-20 01:31:25 -0800814bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
815 bool key_frame, const webrtc::VideoFrame& frame) {
816 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
817 RTC_CHECK(use_surface_);
818 NativeHandleImpl* handle =
819 static_cast<NativeHandleImpl*>(frame.native_handle());
820 jfloatArray sampling_matrix = jni->NewFloatArray(16);
821 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
822
823 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
824 j_encode_texture_method_,
825 key_frame,
826 handle->oes_texture_id,
827 sampling_matrix,
828 current_timestamp_us_);
829 CHECK_EXCEPTION(jni);
830 return encode_status;
831}
832
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000833int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
834 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800835 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000836 JNIEnv* jni = AttachCurrentThreadIfNeeded();
837 ScopedLocalRefFrame local_ref_frame(jni);
838 callback_ = callback;
839 return WEBRTC_VIDEO_CODEC_OK;
840}
841
842int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800843 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000844 if (!inited_) {
845 return WEBRTC_VIDEO_CODEC_OK;
846 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000847 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700848 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
849 frames_received_ << ". Encoded: " << frames_encoded_ <<
glaznev919ff752016-01-27 15:01:03 -0800850 ". Dropped: " << frames_dropped_media_encoder_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000851 ScopedLocalRefFrame local_ref_frame(jni);
852 for (size_t i = 0; i < input_buffers_.size(); ++i)
853 jni->DeleteGlobalRef(input_buffers_[i]);
854 input_buffers_.clear();
855 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
856 CHECK_EXCEPTION(jni);
857 rtc::MessageQueueManager::Clear(this);
858 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800859 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700860 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000861 return WEBRTC_VIDEO_CODEC_OK;
862}
863
864int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
865 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800866 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800867 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
868 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000869 if (last_set_bitrate_kbps_ == new_bit_rate &&
870 last_set_fps_ == frame_rate) {
871 return WEBRTC_VIDEO_CODEC_OK;
872 }
glaznev919ff752016-01-27 15:01:03 -0800873 if (scale_) {
874 quality_scaler_.ReportFramerate(frame_rate);
875 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000876 JNIEnv* jni = AttachCurrentThreadIfNeeded();
877 ScopedLocalRefFrame local_ref_frame(jni);
878 if (new_bit_rate > 0) {
879 last_set_bitrate_kbps_ = new_bit_rate;
880 }
881 if (frame_rate > 0) {
882 last_set_fps_ = frame_rate;
883 }
884 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
885 j_set_rates_method_,
886 last_set_bitrate_kbps_,
887 last_set_fps_);
888 CHECK_EXCEPTION(jni);
889 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800890 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000891 return WEBRTC_VIDEO_CODEC_ERROR;
892 }
893 return WEBRTC_VIDEO_CODEC_OK;
894}
895
896int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
897 JNIEnv* jni,
898 jobject j_output_buffer_info) {
899 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
900}
901
902jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
903 JNIEnv* jni,
904 jobject j_output_buffer_info) {
905 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
906}
907
908bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
909 JNIEnv* jni,
910 jobject j_output_buffer_info) {
911 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
912}
913
914jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
915 JNIEnv* jni,
916 jobject j_output_buffer_info) {
917 return GetLongField(
918 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
919}
920
921bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800922 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000923 while (true) {
924 jobject j_output_buffer_info = jni->CallObjectMethod(
925 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
926 CHECK_EXCEPTION(jni);
927 if (IsNull(jni, j_output_buffer_info)) {
928 break;
929 }
930
931 int output_buffer_index =
932 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
933 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800934 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000935 return false;
936 }
937
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000938 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000939 jobject j_output_buffer =
940 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
941 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000942
943 // Get frame timestamps from a queue - for non config frames only.
944 int64_t frame_encoding_time_ms = 0;
945 last_output_timestamp_ms_ =
946 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
947 1000;
948 if (frames_in_queue_ > 0) {
949 output_timestamp_ = timestamps_.front();
950 timestamps_.erase(timestamps_.begin());
951 output_render_time_ms_ = render_times_ms_.front();
952 render_times_ms_.erase(render_times_ms_.begin());
953 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
954 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
955 frames_in_queue_--;
956 }
957
958 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000959 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200960 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000961 jni->GetDirectBufferAddress(j_output_buffer));
962 CHECK_EXCEPTION(jni);
963
glaznevf4decb52016-01-15 13:49:22 -0800964 if (frames_encoded_ < kMaxEncodedLogFrames) {
glaznev94291482016-02-01 13:17:18 -0800965 int current_latency =
966 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_);
967 ALOGD << "Encoder frame out # " << frames_encoded_ <<
968 ". Key: " << key_frame <<
969 ". Size: " << payload_size <<
970 ". TS: " << (int)last_output_timestamp_ms_ <<
971 ". Latency: " << current_latency <<
glaznevf4decb52016-01-15 13:49:22 -0800972 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000973 }
974
975 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000976 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000977 if (callback_) {
978 scoped_ptr<webrtc::EncodedImage> image(
979 new webrtc::EncodedImage(payload, payload_size, payload_size));
980 image->_encodedWidth = width_;
981 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000982 image->_timeStamp = output_timestamp_;
983 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200984 image->_frameType =
985 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000986 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700987 image->adapt_reason_.quality_resolution_downscales =
988 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000989
990 webrtc::CodecSpecificInfo info;
991 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000992 info.codecType = codecType_;
993 if (codecType_ == kVideoCodecVP8) {
994 info.codecSpecific.VP8.pictureId = picture_id_;
995 info.codecSpecific.VP8.nonReference = false;
996 info.codecSpecific.VP8.simulcastIdx = 0;
997 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
998 info.codecSpecific.VP8.layerSync = false;
999 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
1000 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -08001001 } else if (codecType_ == kVideoCodecVP9) {
1002 if (key_frame) {
1003 gof_idx_ = 0;
1004 }
1005 info.codecSpecific.VP9.picture_id = picture_id_;
1006 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
1007 info.codecSpecific.VP9.flexible_mode = false;
1008 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
1009 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
1010 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
1011 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
1012 info.codecSpecific.VP9.temporal_up_switch = true;
1013 info.codecSpecific.VP9.inter_layer_predicted = false;
1014 info.codecSpecific.VP9.gof_idx =
1015 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
1016 info.codecSpecific.VP9.num_spatial_layers = 1;
1017 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
1018 if (info.codecSpecific.VP9.ss_data_available) {
1019 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
1020 info.codecSpecific.VP9.width[0] = width_;
1021 info.codecSpecific.VP9.height[0] = height_;
1022 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
1023 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001024 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001025 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001026
1027 // Generate a header describing a single fragment.
1028 webrtc::RTPFragmentationHeader header;
1029 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001030 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001031 header.VerifyAndAllocateFragmentationHeader(1);
1032 header.fragmentationOffset[0] = 0;
1033 header.fragmentationLength[0] = image->_length;
1034 header.fragmentationPlType[0] = 0;
1035 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001036 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001037 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001038 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1039 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001040 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001041 }
asapersson86b01602015-10-20 23:55:26 -07001042 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001043 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001044 if (scale_) {
1045 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1046 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001047 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1048 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001049 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001050 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001051 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001052 // For H.264 search for start codes.
1053 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1054 int32_t scPositionsLength = 0;
1055 int32_t scPosition = 0;
1056 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1057 int32_t naluPosition = NextNaluPosition(
1058 payload + scPosition, payload_size - scPosition);
1059 if (naluPosition < 0) {
1060 break;
1061 }
1062 scPosition += naluPosition;
1063 scPositions[scPositionsLength++] = scPosition;
1064 scPosition += H264_SC_LENGTH;
1065 }
1066 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001067 ALOGE << "Start code is not found!";
1068 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1069 << " " << image->_buffer[2] << " " << image->_buffer[3]
1070 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001071 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001072 return false;
1073 }
1074 scPositions[scPositionsLength] = payload_size;
1075 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1076 for (size_t i = 0; i < scPositionsLength; i++) {
1077 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1078 header.fragmentationLength[i] =
1079 scPositions[i + 1] - header.fragmentationOffset[i];
1080 header.fragmentationPlType[i] = 0;
1081 header.fragmentationTimeDiff[i] = 0;
1082 }
1083 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001084
1085 callback_status = callback_->Encoded(*image, &info, &header);
1086 }
1087
1088 // Return output buffer back to the encoder.
1089 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1090 j_release_output_buffer_method_,
1091 output_buffer_index);
1092 CHECK_EXCEPTION(jni);
1093 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001094 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001095 return false;
1096 }
1097
glaznevf4decb52016-01-15 13:49:22 -08001098 // Calculate and print encoding statistics - every 3 seconds.
1099 frames_encoded_++;
1100 current_frames_++;
1101 current_bytes_ += payload_size;
1102 current_encoding_time_ms_ += frame_encoding_time_ms;
glaznev94291482016-02-01 13:17:18 -08001103 LogStatistics(false);
glaznevf4decb52016-01-15 13:49:22 -08001104
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001105 if (callback_status > 0) {
1106 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001107 // Theoretically could handle callback_status<0 here, but unclear what
1108 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001109 }
1110 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001111 return true;
1112}
1113
glaznev94291482016-02-01 13:17:18 -08001114void MediaCodecVideoEncoder::LogStatistics(bool force_log) {
1115 int statistic_time_ms = GetCurrentTimeMs() - stat_start_time_ms_;
1116 if ((statistic_time_ms >= kMediaCodecStatisticsIntervalMs || force_log) &&
1117 current_frames_ > 0 && statistic_time_ms > 0) {
1118 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
1119 int current_fps =
1120 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
1121 ALOGD << "Encoded frames: " << frames_encoded_ <<
1122 ". Bitrate: " << current_bitrate <<
1123 ", target: " << last_set_bitrate_kbps_ << " kbps" <<
1124 ", fps: " << current_fps <<
1125 ", encTime: " << (current_encoding_time_ms_ / current_frames_) <<
1126 ". QP: " << (current_acc_qp_ / current_frames_) <<
1127 " for last " << statistic_time_ms << " ms.";
1128 stat_start_time_ms_ = GetCurrentTimeMs();
1129 current_frames_ = 0;
1130 current_bytes_ = 0;
1131 current_acc_qp_ = 0;
1132 current_encoding_time_ms_ = 0;
1133 }
1134}
1135
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001136int32_t MediaCodecVideoEncoder::NextNaluPosition(
1137 uint8_t *buffer, size_t buffer_size) {
1138 if (buffer_size < H264_SC_LENGTH) {
1139 return -1;
1140 }
1141 uint8_t *head = buffer;
1142 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1143 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1144 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1145
1146 while (head < end) {
1147 if (head[0]) {
1148 head++;
1149 continue;
1150 }
1151 if (head[1]) { // got 00xx
1152 head += 2;
1153 continue;
1154 }
1155 if (head[2]) { // got 0000xx
1156 head += 3;
1157 continue;
1158 }
1159 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001160 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001161 continue;
1162 }
1163 return (int32_t)(head - buffer);
1164 }
1165 return -1;
1166}
1167
jackychen61b4d512015-04-21 15:30:11 -07001168void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001169 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001170 if (scale_)
1171 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001172}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001173
jackychen6e2ce6e2015-07-13 16:26:33 -07001174int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001175 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001176}
1177
Peter Boströmb7d9a972015-12-18 16:01:11 +01001178const char* MediaCodecVideoEncoder::ImplementationName() const {
1179 return "MediaCodec";
1180}
1181
Perec2922f2016-01-27 15:25:46 +01001182MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001183 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1184 ScopedLocalRefFrame local_ref_frame(jni);
1185 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001186 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001187
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001188 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1189 j_encoder_class,
1190 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1191 CHECK_EXCEPTION(jni);
1192 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001193 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001194 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1195 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1196 }
1197
Alex Glaznevad948c42015-11-18 13:06:42 -08001198 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1199 j_encoder_class,
1200 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1201 CHECK_EXCEPTION(jni);
1202 if (is_vp9_hw_supported) {
1203 ALOGD << "VP9 HW Encoder supported.";
1204 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1205 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1206 }
1207
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001208 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1209 j_encoder_class,
1210 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1211 CHECK_EXCEPTION(jni);
1212 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001213 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001214 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1215 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1216 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001217}
1218
Perec2922f2016-01-27 15:25:46 +01001219MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {
1220 ALOGD << "MediaCodecVideoEncoderFactory dtor";
1221}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001222
perkj30e91822015-11-20 01:31:25 -08001223void MediaCodecVideoEncoderFactory::SetEGLContext(
1224 JNIEnv* jni, jobject render_egl_context) {
1225 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
Perec2922f2016-01-27 15:25:46 +01001226 if (!egl_base_.CreateEglBase(jni, render_egl_context)) {
1227 ALOGW << "Invalid EGL context - HW surface encoding is disabled.";
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,
Perec2922f2016-01-27 15:25:46 +01001243 egl_base_.egl_base_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