blob: e87abaf5a5d5a74ce6063aba938b6af6214ac9c2 [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
81
82
83// Logging macros.
84#define TAG_ENCODER "MediaCodecVideoEncoder"
85#ifdef TRACK_BUFFER_TIMING
86#define ALOGV(...)
87 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
88#else
89#define ALOGV(...)
90#endif
91#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
92#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
93#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000094
asapersson1d61a512016-01-20 01:13:46 -080095namespace {
96// Maximum time limit between incoming frames before requesting a key frame.
97const size_t kFrameDiffThresholdMs = 1100;
98const int kMinKeyFrameInterval = 2;
99} // namespace
100
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000101// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
102// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
103// HW-backed video encode. This C++ class is implemented as a very thin shim,
104// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
105// MediaCodecVideoEncoder is created, operated, and destroyed on a single
106// thread, currently the libjingle Worker thread.
107class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
108 public rtc::MessageHandler {
109 public:
110 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -0800111 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800112 VideoCodecType codecType,
113 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000114
115 // webrtc::VideoEncoder implementation. Everything trampolines to
116 // |codec_thread_| for execution.
117 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
118 int32_t /* number_of_cores */,
119 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700120 int32_t Encode(const webrtc::VideoFrame& input_image,
121 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
122 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000123 int32_t RegisterEncodeCompleteCallback(
124 webrtc::EncodedImageCallback* callback) override;
125 int32_t Release() override;
126 int32_t SetChannelParameters(uint32_t /* packet_loss */,
127 int64_t /* rtt */) override;
128 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
129
130 // rtc::MessageHandler implementation.
131 void OnMessage(rtc::Message* msg) override;
132
jackychen61b4d512015-04-21 15:30:11 -0700133 void OnDroppedFrame() override;
134
jackychen6e2ce6e2015-07-13 16:26:33 -0700135 int GetTargetFramerate() override;
136
perkj30e91822015-11-20 01:31:25 -0800137 bool SupportsNativeHandle() const override { return true; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100138 const char* ImplementationName() const override;
139
140 private:
141 // CHECK-fail if not running on |codec_thread_|.
142 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800143
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000144 private:
perkj9576e542015-11-12 06:43:16 -0800145 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
146 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000147 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800148 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000149
150 // Implementation of webrtc::VideoEncoder methods above, all running on the
151 // codec thread exclusively.
152 //
153 // If width==0 then this is assumed to be a re-initialization and the
154 // previously-current values are reused instead of the passed parameters
155 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800156 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
157 bool use_surface);
158 // Reconfigure to match |frame| in width, height. Also reconfigures the
159 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
160 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800161 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000162 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700163 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700164 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800165 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
166 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800167 bool EncodeTextureOnCodecThread(JNIEnv* jni,
168 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800169
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000170 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
171 webrtc::EncodedImageCallback* callback);
172 int32_t ReleaseOnCodecThread();
173 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
174
175 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
176 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
177 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
178 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
179 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000180 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000181
182 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
183 // true on success.
184 bool DeliverPendingOutputs(JNIEnv* jni);
185
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000186 // Search for H.264 start codes.
187 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
188
189 // Type of video codec.
190 VideoCodecType codecType_;
191
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000192 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
193 // |codec_thread_| synchronously.
194 webrtc::EncodedImageCallback* callback_;
195
196 // State that is constant for the lifetime of this object once the ctor
197 // returns.
198 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800199 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000200 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
201 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
202 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800203 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000204 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800205 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800206 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000207 jmethodID j_release_method_;
208 jmethodID j_set_rates_method_;
209 jmethodID j_dequeue_output_buffer_method_;
210 jmethodID j_release_output_buffer_method_;
211 jfieldID j_color_format_field_;
212 jfieldID j_info_index_field_;
213 jfieldID j_info_buffer_field_;
214 jfieldID j_info_is_key_frame_field_;
215 jfieldID j_info_presentation_timestamp_us_field_;
216
217 // State that is valid only between InitEncode() and the next Release().
218 // Touched only on codec_thread_ so no explicit synchronization necessary.
219 int width_; // Frame width in pixels.
220 int height_; // Frame height in pixels.
221 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800222 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000223 uint16_t picture_id_;
224 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
225 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
226 int last_set_fps_; // Last-requested frame rate.
227 int64_t current_timestamp_us_; // Current frame timestamps in us.
228 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000229 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000230 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000231 int frames_in_queue_; // Number of frames in encoder queue.
232 int64_t start_time_ms_; // Start time for statistics.
233 int current_frames_; // Number of frames in the current statistics interval.
234 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800235 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000236 int current_encoding_time_ms_; // Overall encoding time in the current second
237 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
238 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
239 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
240 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
241 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
242 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000243 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
244 int64_t output_render_time_ms_; // Last output frame render time from
245 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000246 // Frame size in bytes fed to MediaCodec.
247 int yuv_size_;
248 // True only when between a callback_->Encoded() call return a positive value
249 // and the next Encode() call being ignored.
250 bool drop_next_input_frame_;
251 // Global references; must be deleted in Release().
252 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200253 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700254 // Dynamic resolution change, off by default.
255 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200256
257 // H264 bitstream parser, used to extract QP from encoded bitstreams.
258 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800259
260 // VP9 variables to populate codec specific structure.
261 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
262 // non-flexible VP9 mode.
263 uint8_t tl0_pic_idx_;
264 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800265
266 // EGL context - owned by factory, should not be allocated/destroyed
267 // by MediaCodecVideoEncoder.
268 jobject egl_context_;
asapersson1d61a512016-01-20 01:13:46 -0800269
270 // Temporary fix for VP8.
271 // Sends a key frame if frames are largely spaced apart (possibly
272 // corresponding to a large image change).
273 int64_t last_frame_received_ms_;
274 int frames_received_since_last_key_;
275 webrtc::VideoCodecMode codec_mode_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000276};
277
278MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
279 // Call Release() to ensure no more callbacks to us after we are deleted.
280 Release();
281}
282
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000283MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800284 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000285 codecType_(codecType),
286 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000287 codec_thread_(new Thread()),
288 j_media_codec_video_encoder_class_(
289 jni,
290 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
291 j_media_codec_video_encoder_(
292 jni,
293 jni->NewObject(*j_media_codec_video_encoder_class_,
294 GetMethodID(jni,
295 *j_media_codec_video_encoder_class_,
296 "<init>",
perkj30e91822015-11-20 01:31:25 -0800297 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800298 inited_(false),
299 use_surface_(false),
300 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800301 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000302 ScopedLocalRefFrame local_ref_frame(jni);
303 // It would be nice to avoid spinning up a new thread per MediaCodec, and
304 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
305 // 2732 means that deadlocks abound. This class synchronously trampolines
306 // to |codec_thread_|, so if anything else can be coming to _us_ from
307 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
308 // in the bug, we have a problem. For now work around that with a dedicated
309 // thread.
310 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700311 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800312 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000313 jclass j_output_buffer_info_class =
314 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000315 j_init_encode_method_ = GetMethodID(
316 jni,
317 *j_media_codec_video_encoder_class_,
318 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800319 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800320 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800321 j_get_input_buffers_method_ = GetMethodID(
322 jni,
323 *j_media_codec_video_encoder_class_,
324 "getInputBuffers",
325 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000326 j_dequeue_input_buffer_method_ = GetMethodID(
327 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800328 j_encode_buffer_method_ = GetMethodID(
329 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800330 j_encode_texture_method_ = GetMethodID(
331 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
332 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000333 j_release_method_ =
334 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
335 j_set_rates_method_ = GetMethodID(
336 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000337 j_dequeue_output_buffer_method_ = GetMethodID(
338 jni,
339 *j_media_codec_video_encoder_class_,
340 "dequeueOutputBuffer",
341 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000342 j_release_output_buffer_method_ = GetMethodID(
343 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
344
345 j_color_format_field_ =
346 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
347 j_info_index_field_ =
348 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
349 j_info_buffer_field_ = GetFieldID(
350 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
351 j_info_is_key_frame_field_ =
352 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
353 j_info_presentation_timestamp_us_field_ = GetFieldID(
354 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
355 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800356 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000357 AllowBlockingCalls();
358}
359
360int32_t MediaCodecVideoEncoder::InitEncode(
361 const webrtc::VideoCodec* codec_settings,
362 int32_t /* number_of_cores */,
363 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700364 const int kMinWidth = 320;
365 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700366 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000367 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700368 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000369 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
370 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000371 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700372 RTC_CHECK(codec_settings->codecType == codecType_)
373 << "Unsupported codec " << codec_settings->codecType << " for "
374 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000375
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700376 ALOGD << "InitEncode request";
asapersson1d61a512016-01-20 01:13:46 -0800377 codec_mode_ = codec_settings->mode;
Alex Glaznevad948c42015-11-18 13:06:42 -0800378 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
379 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700380 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200381 if (scale_) {
382 if (codecType_ == kVideoCodecVP8) {
383 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
384 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
385 // always = 127. Note that in SW, QP is that of the user-level range [0,
386 // 63].
387 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200388 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
389 // This effectively disables high QP as VP8 QP can't go above this
390 // threshold.
391 const int kDisabledBadQpThreshold = kMaxQp + 1;
392 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
393 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200394 } else if (codecType_ == kVideoCodecH264) {
395 // H264 QP is in the range [0, 51].
396 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200397 const int kBadQpThreshold = 40;
398 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
399 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200400 } else {
401 // When adding codec support to additional hardware codecs, also configure
402 // their QP thresholds for scaling.
403 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
404 }
405 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
406 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700407 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000408 return codec_thread_->Invoke<int32_t>(
409 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
410 this,
411 codec_settings->width,
412 codec_settings->height,
413 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800414 codec_settings->maxFramerate,
415 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000416}
417
418int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700419 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000420 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700421 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000422 return codec_thread_->Invoke<int32_t>(Bind(
423 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
424}
425
426int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
427 webrtc::EncodedImageCallback* callback) {
428 return codec_thread_->Invoke<int32_t>(
429 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
430 this,
431 callback));
432}
433
434int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700435 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000436 return codec_thread_->Invoke<int32_t>(
437 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
438}
439
440int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
441 int64_t /* rtt */) {
442 return WEBRTC_VIDEO_CODEC_OK;
443}
444
445int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
446 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200447 if (scale_)
448 quality_scaler_.ReportFramerate(frame_rate);
449
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000450 return codec_thread_->Invoke<int32_t>(
451 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
452 this,
453 new_bit_rate,
454 frame_rate));
455}
456
457void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800458 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000459 JNIEnv* jni = AttachCurrentThreadIfNeeded();
460 ScopedLocalRefFrame local_ref_frame(jni);
461
462 // We only ever send one message to |this| directly (not through a Bind()'d
463 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700464 RTC_CHECK(!msg->message_id) << "Unexpected message!";
465 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000466 if (!inited_) {
467 return;
468 }
469
470 // It would be nice to recover from a failure here if one happened, but it's
471 // unclear how to signal such a failure to the app, so instead we stay silent
472 // about it and let the next app-called API method reveal the borkedness.
473 DeliverPendingOutputs(jni);
474 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
475}
476
perkj9576e542015-11-12 06:43:16 -0800477bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
478 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
479 ALOGE << "ResetOnCodecThread";
480 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800481 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
482 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000483 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
484 // degrade to a SW encoder at this point? There isn't one AFAICT :(
485 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800486 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000487 }
perkj9576e542015-11-12 06:43:16 -0800488 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000489}
490
491int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800492 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800493 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800494 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000495 JNIEnv* jni = AttachCurrentThreadIfNeeded();
496 ScopedLocalRefFrame local_ref_frame(jni);
497
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700498 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
499 width << " x " << height << ". Bitrate: " << kbps <<
500 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000501 if (kbps == 0) {
502 kbps = last_set_bitrate_kbps_;
503 }
504 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800505 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000506 }
507
508 width_ = width;
509 height_ = height;
510 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800511 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000512 yuv_size_ = width_ * height_ * 3 / 2;
513 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000514 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000516 frames_in_queue_ = 0;
517 current_timestamp_us_ = 0;
518 start_time_ms_ = GetCurrentTimeMs();
519 current_frames_ = 0;
520 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800521 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000522 current_encoding_time_ms_ = 0;
523 last_input_timestamp_ms_ = -1;
524 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000525 output_timestamp_ = 0;
526 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000527 timestamps_.clear();
528 render_times_ms_.clear();
529 frame_rtc_times_ms_.clear();
530 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800531 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000532 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800533 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
534 tl0_pic_idx_ = static_cast<uint8_t>(rand());
535 gof_idx_ = 0;
asapersson1d61a512016-01-20 01:13:46 -0800536 last_frame_received_ms_ = -1;
537 frames_received_since_last_key_ = kMinKeyFrameInterval;
perkj9576e542015-11-12 06:43:16 -0800538
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000539 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000540 jobject j_video_codec_enum = JavaEnumFromIndex(
541 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800542 const bool encode_status = jni->CallBooleanMethod(
543 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800544 j_video_codec_enum, width, height, kbps, fps,
545 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800546 if (!encode_status) {
547 ALOGE << "Failed to configure encoder.";
548 return WEBRTC_VIDEO_CODEC_ERROR;
549 }
550 CHECK_EXCEPTION(jni);
551
Per598242a2015-11-26 14:28:55 +0100552 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800553 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
554 jni->CallObjectMethod(*j_media_codec_video_encoder_,
555 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000556 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800557 if (IsNull(jni, input_buffers)) {
558 return WEBRTC_VIDEO_CODEC_ERROR;
559 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000560
perkj30e91822015-11-20 01:31:25 -0800561 switch (GetIntField(jni, *j_media_codec_video_encoder_,
562 j_color_format_field_)) {
563 case COLOR_FormatYUV420Planar:
564 encoder_fourcc_ = libyuv::FOURCC_YU12;
565 break;
566 case COLOR_FormatYUV420SemiPlanar:
567 case COLOR_QCOM_FormatYUV420SemiPlanar:
568 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
569 encoder_fourcc_ = libyuv::FOURCC_NV12;
570 break;
571 default:
572 LOG(LS_ERROR) << "Wrong color format.";
573 return WEBRTC_VIDEO_CODEC_ERROR;
574 }
575 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
576 RTC_CHECK(input_buffers_.empty())
577 << "Unexpected double InitEncode without Release";
578 input_buffers_.resize(num_input_buffers);
579 for (size_t i = 0; i < num_input_buffers; ++i) {
580 input_buffers_[i] =
581 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
582 int64_t yuv_buffer_capacity =
583 jni->GetDirectBufferCapacity(input_buffers_[i]);
584 CHECK_EXCEPTION(jni);
585 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
586 }
587 }
perkj9576e542015-11-12 06:43:16 -0800588
589 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000590 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
591 return WEBRTC_VIDEO_CODEC_OK;
592}
593
594int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700595 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700596 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800597 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000598 JNIEnv* jni = AttachCurrentThreadIfNeeded();
599 ScopedLocalRefFrame local_ref_frame(jni);
600
601 if (!inited_) {
602 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
603 }
perkj9576e542015-11-12 06:43:16 -0800604
asapersson1d61a512016-01-20 01:13:46 -0800605 bool send_key_frame = false;
606 if (codecType_ == kVideoCodecVP8 && codec_mode_ == webrtc::kRealtimeVideo) {
607 ++frames_received_since_last_key_;
608 int64_t now_ms = GetCurrentTimeMs();
609 if (last_frame_received_ms_ != -1 &&
610 (now_ms - last_frame_received_ms_) > kFrameDiffThresholdMs) {
611 // Add limit to prevent triggering a key for every frame for very low
612 // framerates (e.g. if frame diff > kFrameDiffThresholdMs).
613 if (frames_received_since_last_key_ > kMinKeyFrameInterval) {
614 ALOGD << "Send key, frame diff: " << (now_ms - last_frame_received_ms_);
615 send_key_frame = true;
616 }
617 frames_received_since_last_key_ = 0;
618 }
619 last_frame_received_ms_ = now_ms;
620 }
621
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000622 frames_received_++;
623 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800624 if (!ResetCodecOnCodecThread())
625 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000626 }
glaznevf4decb52016-01-15 13:49:22 -0800627 if (frames_encoded_ < kMaxEncodedLogFrames) {
628 ALOGD << "Encoder frame in # " << (frames_received_ - 1) << ". TS: " <<
629 (int)(current_timestamp_us_ / 1000) << ". Q: " << frames_in_queue_ <<
630 ". Fps: " << last_set_fps_ << ". Kbps: " << last_set_bitrate_kbps_;
631 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000632
633 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800634 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000635 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800636 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
637 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000638 return WEBRTC_VIDEO_CODEC_OK;
639 }
640
henrikg91d6ede2015-09-17 00:24:34 -0700641 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200642
glaznevf4decb52016-01-15 13:49:22 -0800643 // Check if we accumulated too many frames in encoder input buffers
644 // or the encoder latency exceeds 70 ms and drop frame if so.
645 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
646 int encoder_latency_ms = last_input_timestamp_ms_ -
647 last_output_timestamp_ms_;
648 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE ||
649 encoder_latency_ms > MAX_ENCODER_LATENCY_MS) {
650 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
651 " ms. Q size: " << frames_in_queue_;
652 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
653 OnDroppedFrame();
654 return WEBRTC_VIDEO_CODEC_OK;
655 }
656 }
657
Per598242a2015-11-26 14:28:55 +0100658 VideoFrame input_frame = frame;
659 if (scale_) {
660 // Check framerate before spatial resolution change.
661 quality_scaler_.OnEncodeFrame(frame);
662 const webrtc::QualityScaler::Resolution scaled_resolution =
663 quality_scaler_.GetScaledResolution();
664 if (scaled_resolution.width != frame.width() ||
665 scaled_resolution.height != frame.height()) {
666 if (frame.native_handle() != nullptr) {
667 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
668 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100669 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100670 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100671 scaled_resolution.height,
672 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100673 input_frame.set_video_frame_buffer(scaled_buffer);
674 } else {
675 input_frame = quality_scaler_.GetScaledFrame(frame);
676 }
677 }
678 }
jackychen61b4d512015-04-21 15:30:11 -0700679
perkj9576e542015-11-12 06:43:16 -0800680 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
681 ALOGE << "Failed to reconfigure encoder.";
682 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000683 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000684
glaznevf4decb52016-01-15 13:49:22 -0800685 // Save time when input frame is sent to the encoder input.
686 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000687
asapersson1d61a512016-01-20 01:13:46 -0800688 const bool key_frame =
689 frame_types->front() != webrtc::kVideoFrameDelta || send_key_frame;
perkj30e91822015-11-20 01:31:25 -0800690 bool encode_status = true;
691 if (!input_frame.native_handle()) {
692 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
693 j_dequeue_input_buffer_method_);
694 CHECK_EXCEPTION(jni);
695 if (j_input_buffer_index == -1) {
696 // Video codec falls behind - no input buffer available.
697 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800698 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
699 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
perkj30e91822015-11-20 01:31:25 -0800700 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
701 }
702 if (j_input_buffer_index == -2) {
703 ResetCodecOnCodecThread();
704 return WEBRTC_VIDEO_CODEC_ERROR;
705 }
706 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
707 j_input_buffer_index);
708 } else {
709 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000710 }
perkj30e91822015-11-20 01:31:25 -0800711
712 if (!encode_status) {
713 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800714 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200715 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000716 }
717
perkj9576e542015-11-12 06:43:16 -0800718 last_input_timestamp_ms_ =
719 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200720 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000721
perkj12f68022015-10-16 13:31:45 +0200722 // Save input image timestamps for later output
723 timestamps_.push_back(input_frame.timestamp());
724 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800725 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
726
perkj30e91822015-11-20 01:31:25 -0800727 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800728 ALOGE << "Failed deliver pending outputs.";
729 ResetCodecOnCodecThread();
730 return WEBRTC_VIDEO_CODEC_ERROR;
731 }
732 return WEBRTC_VIDEO_CODEC_OK;
733}
734
735bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
736 const webrtc::VideoFrame& frame) {
737 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
738
perkj30e91822015-11-20 01:31:25 -0800739 const bool is_texture_frame = frame.native_handle() != nullptr;
740 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800741 const bool reconfigure_due_to_size =
742 frame.width() != width_ || frame.height() != height_;
743
perkj30e91822015-11-20 01:31:25 -0800744 if (reconfigure_due_to_format) {
745 ALOGD << "Reconfigure encoder due to format change. "
746 << (use_surface_ ?
747 "Reconfiguring to encode from byte buffer." :
748 "Reconfiguring to encode from texture.");
749 }
perkj9576e542015-11-12 06:43:16 -0800750 if (reconfigure_due_to_size) {
751 ALOGD << "Reconfigure encoder due to frame resolution change from "
752 << width_ << " x " << height_ << " to " << frame.width() << " x "
753 << frame.height();
754 width_ = frame.width();
755 height_ = frame.height();
756 }
757
perkj30e91822015-11-20 01:31:25 -0800758 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800759 return true;
760
761 ReleaseOnCodecThread();
762
perkj30e91822015-11-20 01:31:25 -0800763 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800764 WEBRTC_VIDEO_CODEC_OK;
765}
766
767bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
768 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
769 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800770 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800771
perkj9576e542015-11-12 06:43:16 -0800772 jobject j_input_buffer = input_buffers_[input_buffer_index];
773 uint8_t* yuv_buffer =
774 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
775 CHECK_EXCEPTION(jni);
776 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
777 RTC_CHECK(!libyuv::ConvertFromI420(
778 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
779 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
780 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
781 yuv_buffer, width_, width_, height_, encoder_fourcc_))
782 << "ConvertFromI420 failed";
783
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000784 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800785 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000786 key_frame,
perkj9576e542015-11-12 06:43:16 -0800787 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000788 yuv_size_,
789 current_timestamp_us_);
790 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800791 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000792}
793
perkj30e91822015-11-20 01:31:25 -0800794bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
795 bool key_frame, const webrtc::VideoFrame& frame) {
796 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
797 RTC_CHECK(use_surface_);
798 NativeHandleImpl* handle =
799 static_cast<NativeHandleImpl*>(frame.native_handle());
800 jfloatArray sampling_matrix = jni->NewFloatArray(16);
801 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
802
803 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
804 j_encode_texture_method_,
805 key_frame,
806 handle->oes_texture_id,
807 sampling_matrix,
808 current_timestamp_us_);
809 CHECK_EXCEPTION(jni);
810 return encode_status;
811}
812
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000813int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
814 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800815 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000816 JNIEnv* jni = AttachCurrentThreadIfNeeded();
817 ScopedLocalRefFrame local_ref_frame(jni);
818 callback_ = callback;
819 return WEBRTC_VIDEO_CODEC_OK;
820}
821
822int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800823 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000824 if (!inited_) {
825 return WEBRTC_VIDEO_CODEC_OK;
826 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000827 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700828 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
829 frames_received_ << ". Encoded: " << frames_encoded_ <<
830 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000831 ScopedLocalRefFrame local_ref_frame(jni);
832 for (size_t i = 0; i < input_buffers_.size(); ++i)
833 jni->DeleteGlobalRef(input_buffers_[i]);
834 input_buffers_.clear();
835 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
836 CHECK_EXCEPTION(jni);
837 rtc::MessageQueueManager::Clear(this);
838 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800839 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700840 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000841 return WEBRTC_VIDEO_CODEC_OK;
842}
843
844int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
845 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800846 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800847 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
848 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000849 if (last_set_bitrate_kbps_ == new_bit_rate &&
850 last_set_fps_ == frame_rate) {
851 return WEBRTC_VIDEO_CODEC_OK;
852 }
853 JNIEnv* jni = AttachCurrentThreadIfNeeded();
854 ScopedLocalRefFrame local_ref_frame(jni);
855 if (new_bit_rate > 0) {
856 last_set_bitrate_kbps_ = new_bit_rate;
857 }
858 if (frame_rate > 0) {
859 last_set_fps_ = frame_rate;
860 }
861 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
862 j_set_rates_method_,
863 last_set_bitrate_kbps_,
864 last_set_fps_);
865 CHECK_EXCEPTION(jni);
866 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800867 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000868 return WEBRTC_VIDEO_CODEC_ERROR;
869 }
870 return WEBRTC_VIDEO_CODEC_OK;
871}
872
873int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
874 JNIEnv* jni,
875 jobject j_output_buffer_info) {
876 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
877}
878
879jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
880 JNIEnv* jni,
881 jobject j_output_buffer_info) {
882 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
883}
884
885bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
886 JNIEnv* jni,
887 jobject j_output_buffer_info) {
888 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
889}
890
891jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
892 JNIEnv* jni,
893 jobject j_output_buffer_info) {
894 return GetLongField(
895 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
896}
897
898bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800899 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000900 while (true) {
901 jobject j_output_buffer_info = jni->CallObjectMethod(
902 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
903 CHECK_EXCEPTION(jni);
904 if (IsNull(jni, j_output_buffer_info)) {
905 break;
906 }
907
908 int output_buffer_index =
909 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
910 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800911 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000912 return false;
913 }
914
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000915 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000916 jobject j_output_buffer =
917 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
918 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000919
920 // Get frame timestamps from a queue - for non config frames only.
921 int64_t frame_encoding_time_ms = 0;
922 last_output_timestamp_ms_ =
923 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
924 1000;
925 if (frames_in_queue_ > 0) {
926 output_timestamp_ = timestamps_.front();
927 timestamps_.erase(timestamps_.begin());
928 output_render_time_ms_ = render_times_ms_.front();
929 render_times_ms_.erase(render_times_ms_.begin());
930 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
931 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
932 frames_in_queue_--;
933 }
934
935 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000936 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200937 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000938 jni->GetDirectBufferAddress(j_output_buffer));
939 CHECK_EXCEPTION(jni);
940
glaznevf4decb52016-01-15 13:49:22 -0800941 if (frames_encoded_ < kMaxEncodedLogFrames) {
942 ALOGD << "Encoder frame out # " << frames_encoded_ << ". Key: " <<
943 key_frame << ". Size: " << payload_size << ". TS: " <<
944 (int)last_output_timestamp_ms_ << ". Latency: " <<
945 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_) <<
946 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000947 }
948
949 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000950 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000951 if (callback_) {
952 scoped_ptr<webrtc::EncodedImage> image(
953 new webrtc::EncodedImage(payload, payload_size, payload_size));
954 image->_encodedWidth = width_;
955 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000956 image->_timeStamp = output_timestamp_;
957 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200958 image->_frameType =
959 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000960 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700961 image->adapt_reason_.quality_resolution_downscales =
962 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000963
964 webrtc::CodecSpecificInfo info;
965 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000966 info.codecType = codecType_;
967 if (codecType_ == kVideoCodecVP8) {
968 info.codecSpecific.VP8.pictureId = picture_id_;
969 info.codecSpecific.VP8.nonReference = false;
970 info.codecSpecific.VP8.simulcastIdx = 0;
971 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
972 info.codecSpecific.VP8.layerSync = false;
973 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
974 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800975 } else if (codecType_ == kVideoCodecVP9) {
976 if (key_frame) {
977 gof_idx_ = 0;
978 }
979 info.codecSpecific.VP9.picture_id = picture_id_;
980 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
981 info.codecSpecific.VP9.flexible_mode = false;
982 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
983 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
984 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
985 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
986 info.codecSpecific.VP9.temporal_up_switch = true;
987 info.codecSpecific.VP9.inter_layer_predicted = false;
988 info.codecSpecific.VP9.gof_idx =
989 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
990 info.codecSpecific.VP9.num_spatial_layers = 1;
991 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
992 if (info.codecSpecific.VP9.ss_data_available) {
993 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
994 info.codecSpecific.VP9.width[0] = width_;
995 info.codecSpecific.VP9.height[0] = height_;
996 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
997 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000998 }
Alex Glaznevad948c42015-11-18 13:06:42 -0800999 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001000
1001 // Generate a header describing a single fragment.
1002 webrtc::RTPFragmentationHeader header;
1003 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -08001004 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001005 header.VerifyAndAllocateFragmentationHeader(1);
1006 header.fragmentationOffset[0] = 0;
1007 header.fragmentationLength[0] = image->_length;
1008 header.fragmentationPlType[0] = 0;
1009 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -08001010 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -07001011 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001012 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
1013 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -07001014 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001015 }
asapersson86b01602015-10-20 23:55:26 -07001016 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001017 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +02001018 if (scale_) {
1019 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
1020 int qp;
glaznevf4decb52016-01-15 13:49:22 -08001021 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
1022 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +02001023 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -08001024 }
Peter Boström2bc68c72015-09-24 16:22:28 +02001025 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001026 // For H.264 search for start codes.
1027 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
1028 int32_t scPositionsLength = 0;
1029 int32_t scPosition = 0;
1030 while (scPositionsLength < MAX_NALUS_PERFRAME) {
1031 int32_t naluPosition = NextNaluPosition(
1032 payload + scPosition, payload_size - scPosition);
1033 if (naluPosition < 0) {
1034 break;
1035 }
1036 scPosition += naluPosition;
1037 scPositions[scPositionsLength++] = scPosition;
1038 scPosition += H264_SC_LENGTH;
1039 }
1040 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001041 ALOGE << "Start code is not found!";
1042 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1043 << " " << image->_buffer[2] << " " << image->_buffer[3]
1044 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001045 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001046 return false;
1047 }
1048 scPositions[scPositionsLength] = payload_size;
1049 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1050 for (size_t i = 0; i < scPositionsLength; i++) {
1051 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1052 header.fragmentationLength[i] =
1053 scPositions[i + 1] - header.fragmentationOffset[i];
1054 header.fragmentationPlType[i] = 0;
1055 header.fragmentationTimeDiff[i] = 0;
1056 }
1057 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001058
1059 callback_status = callback_->Encoded(*image, &info, &header);
1060 }
1061
1062 // Return output buffer back to the encoder.
1063 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1064 j_release_output_buffer_method_,
1065 output_buffer_index);
1066 CHECK_EXCEPTION(jni);
1067 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001068 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001069 return false;
1070 }
1071
glaznevf4decb52016-01-15 13:49:22 -08001072 // Calculate and print encoding statistics - every 3 seconds.
1073 frames_encoded_++;
1074 current_frames_++;
1075 current_bytes_ += payload_size;
1076 current_encoding_time_ms_ += frame_encoding_time_ms;
1077 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
1078 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
1079 current_frames_ > 0) {
1080 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
1081 (current_bytes_ * 8 / statistic_time_ms) <<
1082 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
1083 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
1084 << ", encTime: " <<
1085 (current_encoding_time_ms_ / current_frames_) << ". QP: " <<
1086 (current_acc_qp_ / current_frames_) << " for last " <<
1087 statistic_time_ms << " ms.";
1088 start_time_ms_ = GetCurrentTimeMs();
1089 current_frames_ = 0;
1090 current_bytes_ = 0;
1091 current_acc_qp_ = 0;
1092 current_encoding_time_ms_ = 0;
1093 }
1094
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001095 if (callback_status > 0) {
1096 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001097 // Theoretically could handle callback_status<0 here, but unclear what
1098 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001099 }
1100 }
1101
1102 return true;
1103}
1104
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001105int32_t MediaCodecVideoEncoder::NextNaluPosition(
1106 uint8_t *buffer, size_t buffer_size) {
1107 if (buffer_size < H264_SC_LENGTH) {
1108 return -1;
1109 }
1110 uint8_t *head = buffer;
1111 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1112 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1113 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1114
1115 while (head < end) {
1116 if (head[0]) {
1117 head++;
1118 continue;
1119 }
1120 if (head[1]) { // got 00xx
1121 head += 2;
1122 continue;
1123 }
1124 if (head[2]) { // got 0000xx
1125 head += 3;
1126 continue;
1127 }
1128 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001129 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001130 continue;
1131 }
1132 return (int32_t)(head - buffer);
1133 }
1134 return -1;
1135}
1136
jackychen61b4d512015-04-21 15:30:11 -07001137void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001138 frames_dropped_++;
1139 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001140 if (scale_)
1141 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001142}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001143
jackychen6e2ce6e2015-07-13 16:26:33 -07001144int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001145 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001146}
1147
Peter Boströmb7d9a972015-12-18 16:01:11 +01001148const char* MediaCodecVideoEncoder::ImplementationName() const {
1149 return "MediaCodec";
1150}
1151
perkj30e91822015-11-20 01:31:25 -08001152MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
Peter Boströmb7d9a972015-12-18 16:01:11 +01001153 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001154 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1155 ScopedLocalRefFrame local_ref_frame(jni);
1156 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001157 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001158
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001159 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1160 j_encoder_class,
1161 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1162 CHECK_EXCEPTION(jni);
1163 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001164 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001165 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1166 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1167 }
1168
Alex Glaznevad948c42015-11-18 13:06:42 -08001169 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1170 j_encoder_class,
1171 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1172 CHECK_EXCEPTION(jni);
1173 if (is_vp9_hw_supported) {
1174 ALOGD << "VP9 HW Encoder supported.";
1175 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1176 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1177 }
1178
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001179 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1180 j_encoder_class,
1181 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1182 CHECK_EXCEPTION(jni);
1183 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001184 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001185 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1186 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1187 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001188}
1189
1190MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
1191
perkj30e91822015-11-20 01:31:25 -08001192void MediaCodecVideoEncoderFactory::SetEGLContext(
1193 JNIEnv* jni, jobject render_egl_context) {
1194 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
1195 if (egl_context_) {
1196 jni->DeleteGlobalRef(egl_context_);
1197 egl_context_ = NULL;
1198 }
1199 if (!IsNull(jni, render_egl_context)) {
1200 egl_context_ = jni->NewGlobalRef(render_egl_context);
1201 if (CheckException(jni)) {
1202 ALOGE << "error calling NewGlobalRef for EGL Context.";
1203 egl_context_ = NULL;
1204 } else {
1205 jclass j_egl_context_class =
perkj48477c12015-12-18 00:34:37 -08001206 FindClass(jni, "org/webrtc/EglBase14$Context");
perkj30e91822015-11-20 01:31:25 -08001207 if (!jni->IsInstanceOf(egl_context_, j_egl_context_class)) {
1208 ALOGE << "Wrong EGL Context.";
1209 jni->DeleteGlobalRef(egl_context_);
1210 egl_context_ = NULL;
1211 }
1212 }
1213 }
1214 if (egl_context_ == NULL) {
1215 ALOGW << "NULL VideoDecoder EGL context - HW surface encoding is disabled.";
1216 }
1217}
1218
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001219webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001220 VideoCodecType type) {
1221 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001222 ALOGW << "No HW video encoder for type " << (int)type;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001223 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001224 }
1225 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1226 it != supported_codecs_.end(); ++it) {
1227 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001228 ALOGD << "Create HW video encoder for type " << (int)type <<
1229 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001230 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
1231 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001232 }
1233 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001234 ALOGW << "Can not find HW video encoder for type " << (int)type;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001235 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001236}
1237
1238const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1239MediaCodecVideoEncoderFactory::codecs() const {
1240 return supported_codecs_;
1241}
1242
1243void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1244 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001245 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001246 delete encoder;
1247}
1248
1249} // namespace webrtc_jni
1250