blob: 7f558c0551b07e657d2163df58167a4734ecf06d [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"
Peter Boström2bc68c72015-09-24 16:22:28 +020038#include "webrtc/modules/rtp_rtcp/source/h264_bitstream_parser.h"
perkj30e91822015-11-20 01:31:25 -080039#include "webrtc/modules/video_coding/include/video_codec_interface.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010040#include "webrtc/modules/video_coding/utility/quality_scaler.h"
41#include "webrtc/modules/video_coding/utility/vp8_header_parser.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010042#include "webrtc/system_wrappers/include/field_trial.h"
43#include "webrtc/system_wrappers/include/logcat_trace_context.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000044#include "third_party/libyuv/include/libyuv/convert.h"
45#include "third_party/libyuv/include/libyuv/convert_from.h"
46#include "third_party/libyuv/include/libyuv/video_common.h"
47
48using rtc::Bind;
49using rtc::Thread;
50using rtc::ThreadManager;
51using rtc::scoped_ptr;
52
53using webrtc::CodecSpecificInfo;
54using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070055using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000056using webrtc::RTPFragmentationHeader;
57using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000058using webrtc::VideoCodecType;
59using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000060using webrtc::kVideoCodecVP8;
Alex Glaznevad948c42015-11-18 13:06:42 -080061using webrtc::kVideoCodecVP9;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000062
63namespace webrtc_jni {
64
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000065// H.264 start code length.
66#define H264_SC_LENGTH 4
67// Maximum allowed NALUs in one output frame.
68#define MAX_NALUS_PERFRAME 32
69// Maximum supported HW video encoder resolution.
70#define MAX_VIDEO_WIDTH 1280
71#define MAX_VIDEO_HEIGHT 1280
72// Maximum supported HW video encoder fps.
73#define MAX_VIDEO_FPS 30
glaznevf4decb52016-01-15 13:49:22 -080074// Maximum allowed fps value in SetRates() call.
75#define MAX_ALLOWED_VIDEO_FPS 60
76// Maximum allowed frames in encoder input queue.
77#define MAX_ENCODER_Q_SIZE 2
78// Maximum allowed latency in ms.
79#define MAX_ENCODER_LATENCY_MS 70
80
81
82// Logging macros.
83#define TAG_ENCODER "MediaCodecVideoEncoder"
84#ifdef TRACK_BUFFER_TIMING
85#define ALOGV(...)
86 __android_log_print(ANDROID_LOG_VERBOSE, TAG_ENCODER, __VA_ARGS__)
87#else
88#define ALOGV(...)
89#endif
90#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_ENCODER)
91#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_ENCODER)
92#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_ENCODER)
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000093
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000094// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
95// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
96// HW-backed video encode. This C++ class is implemented as a very thin shim,
97// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
98// MediaCodecVideoEncoder is created, operated, and destroyed on a single
99// thread, currently the libjingle Worker thread.
100class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
101 public rtc::MessageHandler {
102 public:
103 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -0800104 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -0800105 VideoCodecType codecType,
106 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000107
108 // webrtc::VideoEncoder implementation. Everything trampolines to
109 // |codec_thread_| for execution.
110 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
111 int32_t /* number_of_cores */,
112 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -0700113 int32_t Encode(const webrtc::VideoFrame& input_image,
114 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
115 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000116 int32_t RegisterEncodeCompleteCallback(
117 webrtc::EncodedImageCallback* callback) override;
118 int32_t Release() override;
119 int32_t SetChannelParameters(uint32_t /* packet_loss */,
120 int64_t /* rtt */) override;
121 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
122
123 // rtc::MessageHandler implementation.
124 void OnMessage(rtc::Message* msg) override;
125
jackychen61b4d512015-04-21 15:30:11 -0700126 void OnDroppedFrame() override;
127
jackychen6e2ce6e2015-07-13 16:26:33 -0700128 int GetTargetFramerate() override;
129
perkj30e91822015-11-20 01:31:25 -0800130 bool SupportsNativeHandle() const override { return true; }
Peter Boströmb7d9a972015-12-18 16:01:11 +0100131 const char* ImplementationName() const override;
132
133 private:
134 // CHECK-fail if not running on |codec_thread_|.
135 void CheckOnCodecThread();
perkj30e91822015-11-20 01:31:25 -0800136
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000137 private:
perkj9576e542015-11-12 06:43:16 -0800138 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
139 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000140 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800141 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000142
143 // Implementation of webrtc::VideoEncoder methods above, all running on the
144 // codec thread exclusively.
145 //
146 // If width==0 then this is assumed to be a re-initialization and the
147 // previously-current values are reused instead of the passed parameters
148 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800149 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
150 bool use_surface);
151 // Reconfigure to match |frame| in width, height. Also reconfigures the
152 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
153 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800154 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000155 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700156 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700157 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800158 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
159 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800160 bool EncodeTextureOnCodecThread(JNIEnv* jni,
161 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800162
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000163 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
164 webrtc::EncodedImageCallback* callback);
165 int32_t ReleaseOnCodecThread();
166 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
167
168 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
169 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
170 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
171 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
172 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000173 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000174
175 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
176 // true on success.
177 bool DeliverPendingOutputs(JNIEnv* jni);
178
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000179 // Search for H.264 start codes.
180 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
181
182 // Type of video codec.
183 VideoCodecType codecType_;
184
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000185 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
186 // |codec_thread_| synchronously.
187 webrtc::EncodedImageCallback* callback_;
188
189 // State that is constant for the lifetime of this object once the ctor
190 // returns.
191 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800192 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000193 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
194 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
195 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800196 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000197 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800198 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800199 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000200 jmethodID j_release_method_;
201 jmethodID j_set_rates_method_;
202 jmethodID j_dequeue_output_buffer_method_;
203 jmethodID j_release_output_buffer_method_;
204 jfieldID j_color_format_field_;
205 jfieldID j_info_index_field_;
206 jfieldID j_info_buffer_field_;
207 jfieldID j_info_is_key_frame_field_;
208 jfieldID j_info_presentation_timestamp_us_field_;
209
210 // State that is valid only between InitEncode() and the next Release().
211 // Touched only on codec_thread_ so no explicit synchronization necessary.
212 int width_; // Frame width in pixels.
213 int height_; // Frame height in pixels.
214 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800215 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000216 uint16_t picture_id_;
217 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
218 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
219 int last_set_fps_; // Last-requested frame rate.
220 int64_t current_timestamp_us_; // Current frame timestamps in us.
221 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000222 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000223 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000224 int frames_in_queue_; // Number of frames in encoder queue.
225 int64_t start_time_ms_; // Start time for statistics.
226 int current_frames_; // Number of frames in the current statistics interval.
227 int current_bytes_; // Encoded bytes in the current statistics interval.
glaznevf4decb52016-01-15 13:49:22 -0800228 int current_acc_qp_; // Accumulated QP in the current statistics interval.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000229 int current_encoding_time_ms_; // Overall encoding time in the current second
230 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
231 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
232 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
233 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
234 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
235 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000236 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
237 int64_t output_render_time_ms_; // Last output frame render time from
238 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000239 // Frame size in bytes fed to MediaCodec.
240 int yuv_size_;
241 // True only when between a callback_->Encoded() call return a positive value
242 // and the next Encode() call being ignored.
243 bool drop_next_input_frame_;
244 // Global references; must be deleted in Release().
245 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200246 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700247 // Dynamic resolution change, off by default.
248 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200249
250 // H264 bitstream parser, used to extract QP from encoded bitstreams.
251 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800252
253 // VP9 variables to populate codec specific structure.
254 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
255 // non-flexible VP9 mode.
256 uint8_t tl0_pic_idx_;
257 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800258
259 // EGL context - owned by factory, should not be allocated/destroyed
260 // by MediaCodecVideoEncoder.
261 jobject egl_context_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000262};
263
264MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
265 // Call Release() to ensure no more callbacks to us after we are deleted.
266 Release();
267}
268
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000269MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800270 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000271 codecType_(codecType),
272 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000273 codec_thread_(new Thread()),
274 j_media_codec_video_encoder_class_(
275 jni,
276 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
277 j_media_codec_video_encoder_(
278 jni,
279 jni->NewObject(*j_media_codec_video_encoder_class_,
280 GetMethodID(jni,
281 *j_media_codec_video_encoder_class_,
282 "<init>",
perkj30e91822015-11-20 01:31:25 -0800283 "()V"))),
kjellander60ca31b2016-01-04 10:15:53 -0800284 inited_(false),
285 use_surface_(false),
286 picture_id_(0),
perkj30e91822015-11-20 01:31:25 -0800287 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000288 ScopedLocalRefFrame local_ref_frame(jni);
289 // It would be nice to avoid spinning up a new thread per MediaCodec, and
290 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
291 // 2732 means that deadlocks abound. This class synchronously trampolines
292 // to |codec_thread_|, so if anything else can be coming to _us_ from
293 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
294 // in the bug, we have a problem. For now work around that with a dedicated
295 // thread.
296 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700297 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800298 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000299 jclass j_output_buffer_info_class =
300 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000301 j_init_encode_method_ = GetMethodID(
302 jni,
303 *j_media_codec_video_encoder_class_,
304 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800305 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj48477c12015-12-18 00:34:37 -0800306 "IIIILorg/webrtc/EglBase14$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800307 j_get_input_buffers_method_ = GetMethodID(
308 jni,
309 *j_media_codec_video_encoder_class_,
310 "getInputBuffers",
311 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000312 j_dequeue_input_buffer_method_ = GetMethodID(
313 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800314 j_encode_buffer_method_ = GetMethodID(
315 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800316 j_encode_texture_method_ = GetMethodID(
317 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
318 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000319 j_release_method_ =
320 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
321 j_set_rates_method_ = GetMethodID(
322 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000323 j_dequeue_output_buffer_method_ = GetMethodID(
324 jni,
325 *j_media_codec_video_encoder_class_,
326 "dequeueOutputBuffer",
327 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000328 j_release_output_buffer_method_ = GetMethodID(
329 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
330
331 j_color_format_field_ =
332 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
333 j_info_index_field_ =
334 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
335 j_info_buffer_field_ = GetFieldID(
336 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
337 j_info_is_key_frame_field_ =
338 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
339 j_info_presentation_timestamp_us_field_ = GetFieldID(
340 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
341 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800342 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000343 AllowBlockingCalls();
344}
345
346int32_t MediaCodecVideoEncoder::InitEncode(
347 const webrtc::VideoCodec* codec_settings,
348 int32_t /* number_of_cores */,
349 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700350 const int kMinWidth = 320;
351 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700352 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000353 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700354 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000355 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
356 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000357 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700358 RTC_CHECK(codec_settings->codecType == codecType_)
359 << "Unsupported codec " << codec_settings->codecType << " for "
360 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000361
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700362 ALOGD << "InitEncode request";
Alex Glaznevad948c42015-11-18 13:06:42 -0800363 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
364 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700365 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200366 if (scale_) {
367 if (codecType_ == kVideoCodecVP8) {
368 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
369 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
370 // always = 127. Note that in SW, QP is that of the user-level range [0,
371 // 63].
372 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200373 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
374 // This effectively disables high QP as VP8 QP can't go above this
375 // threshold.
376 const int kDisabledBadQpThreshold = kMaxQp + 1;
377 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
378 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200379 } else if (codecType_ == kVideoCodecH264) {
380 // H264 QP is in the range [0, 51].
381 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200382 const int kBadQpThreshold = 40;
383 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
384 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200385 } else {
386 // When adding codec support to additional hardware codecs, also configure
387 // their QP thresholds for scaling.
388 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
389 }
390 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
391 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700392 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000393 return codec_thread_->Invoke<int32_t>(
394 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
395 this,
396 codec_settings->width,
397 codec_settings->height,
398 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800399 codec_settings->maxFramerate,
400 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000401}
402
403int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700404 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000405 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700406 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000407 return codec_thread_->Invoke<int32_t>(Bind(
408 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
409}
410
411int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
412 webrtc::EncodedImageCallback* callback) {
413 return codec_thread_->Invoke<int32_t>(
414 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
415 this,
416 callback));
417}
418
419int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700420 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000421 return codec_thread_->Invoke<int32_t>(
422 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
423}
424
425int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
426 int64_t /* rtt */) {
427 return WEBRTC_VIDEO_CODEC_OK;
428}
429
430int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
431 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200432 if (scale_)
433 quality_scaler_.ReportFramerate(frame_rate);
434
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000435 return codec_thread_->Invoke<int32_t>(
436 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
437 this,
438 new_bit_rate,
439 frame_rate));
440}
441
442void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800443 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000444 JNIEnv* jni = AttachCurrentThreadIfNeeded();
445 ScopedLocalRefFrame local_ref_frame(jni);
446
447 // We only ever send one message to |this| directly (not through a Bind()'d
448 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700449 RTC_CHECK(!msg->message_id) << "Unexpected message!";
450 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000451 if (!inited_) {
452 return;
453 }
454
455 // It would be nice to recover from a failure here if one happened, but it's
456 // unclear how to signal such a failure to the app, so instead we stay silent
457 // about it and let the next app-called API method reveal the borkedness.
458 DeliverPendingOutputs(jni);
459 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
460}
461
perkj9576e542015-11-12 06:43:16 -0800462bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
463 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
464 ALOGE << "ResetOnCodecThread";
465 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800466 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
467 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000468 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
469 // degrade to a SW encoder at this point? There isn't one AFAICT :(
470 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800471 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000472 }
perkj9576e542015-11-12 06:43:16 -0800473 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000474}
475
476int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800477 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800478 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800479 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000480 JNIEnv* jni = AttachCurrentThreadIfNeeded();
481 ScopedLocalRefFrame local_ref_frame(jni);
482
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700483 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
484 width << " x " << height << ". Bitrate: " << kbps <<
485 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000486 if (kbps == 0) {
487 kbps = last_set_bitrate_kbps_;
488 }
489 if (fps == 0) {
glaznevf4decb52016-01-15 13:49:22 -0800490 fps = MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000491 }
492
493 width_ = width;
494 height_ = height;
495 last_set_bitrate_kbps_ = kbps;
glaznevf4decb52016-01-15 13:49:22 -0800496 last_set_fps_ = (fps < MAX_VIDEO_FPS) ? fps : MAX_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000497 yuv_size_ = width_ * height_ * 3 / 2;
498 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000499 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000500 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000501 frames_in_queue_ = 0;
502 current_timestamp_us_ = 0;
503 start_time_ms_ = GetCurrentTimeMs();
504 current_frames_ = 0;
505 current_bytes_ = 0;
glaznevf4decb52016-01-15 13:49:22 -0800506 current_acc_qp_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000507 current_encoding_time_ms_ = 0;
508 last_input_timestamp_ms_ = -1;
509 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000510 output_timestamp_ = 0;
511 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000512 timestamps_.clear();
513 render_times_ms_.clear();
514 frame_rtc_times_ms_.clear();
515 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800516 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000517 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800518 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
519 tl0_pic_idx_ = static_cast<uint8_t>(rand());
520 gof_idx_ = 0;
perkj9576e542015-11-12 06:43:16 -0800521
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000522 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000523 jobject j_video_codec_enum = JavaEnumFromIndex(
524 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800525 const bool encode_status = jni->CallBooleanMethod(
526 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800527 j_video_codec_enum, width, height, kbps, fps,
528 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800529 if (!encode_status) {
530 ALOGE << "Failed to configure encoder.";
531 return WEBRTC_VIDEO_CODEC_ERROR;
532 }
533 CHECK_EXCEPTION(jni);
534
Per598242a2015-11-26 14:28:55 +0100535 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800536 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
537 jni->CallObjectMethod(*j_media_codec_video_encoder_,
538 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000539 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800540 if (IsNull(jni, input_buffers)) {
541 return WEBRTC_VIDEO_CODEC_ERROR;
542 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000543
perkj30e91822015-11-20 01:31:25 -0800544 switch (GetIntField(jni, *j_media_codec_video_encoder_,
545 j_color_format_field_)) {
546 case COLOR_FormatYUV420Planar:
547 encoder_fourcc_ = libyuv::FOURCC_YU12;
548 break;
549 case COLOR_FormatYUV420SemiPlanar:
550 case COLOR_QCOM_FormatYUV420SemiPlanar:
551 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
552 encoder_fourcc_ = libyuv::FOURCC_NV12;
553 break;
554 default:
555 LOG(LS_ERROR) << "Wrong color format.";
556 return WEBRTC_VIDEO_CODEC_ERROR;
557 }
558 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
559 RTC_CHECK(input_buffers_.empty())
560 << "Unexpected double InitEncode without Release";
561 input_buffers_.resize(num_input_buffers);
562 for (size_t i = 0; i < num_input_buffers; ++i) {
563 input_buffers_[i] =
564 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
565 int64_t yuv_buffer_capacity =
566 jni->GetDirectBufferCapacity(input_buffers_[i]);
567 CHECK_EXCEPTION(jni);
568 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
569 }
570 }
perkj9576e542015-11-12 06:43:16 -0800571
572 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000573 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
574 return WEBRTC_VIDEO_CODEC_OK;
575}
576
577int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700578 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700579 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800580 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000581 JNIEnv* jni = AttachCurrentThreadIfNeeded();
582 ScopedLocalRefFrame local_ref_frame(jni);
583
584 if (!inited_) {
585 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
586 }
perkj9576e542015-11-12 06:43:16 -0800587
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000588 frames_received_++;
589 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800590 if (!ResetCodecOnCodecThread())
591 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000592 }
glaznevf4decb52016-01-15 13:49:22 -0800593 if (frames_encoded_ < kMaxEncodedLogFrames) {
594 ALOGD << "Encoder frame in # " << (frames_received_ - 1) << ". TS: " <<
595 (int)(current_timestamp_us_ / 1000) << ". Q: " << frames_in_queue_ <<
596 ". Fps: " << last_set_fps_ << ". Kbps: " << last_set_bitrate_kbps_;
597 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000598
599 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800600 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000601 drop_next_input_frame_ = false;
glaznevf4decb52016-01-15 13:49:22 -0800602 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
603 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000604 return WEBRTC_VIDEO_CODEC_OK;
605 }
606
henrikg91d6ede2015-09-17 00:24:34 -0700607 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200608
glaznevf4decb52016-01-15 13:49:22 -0800609 // Check if we accumulated too many frames in encoder input buffers
610 // or the encoder latency exceeds 70 ms and drop frame if so.
611 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
612 int encoder_latency_ms = last_input_timestamp_ms_ -
613 last_output_timestamp_ms_;
614 if (frames_in_queue_ > MAX_ENCODER_Q_SIZE ||
615 encoder_latency_ms > MAX_ENCODER_LATENCY_MS) {
616 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
617 " ms. Q size: " << frames_in_queue_;
618 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
619 OnDroppedFrame();
620 return WEBRTC_VIDEO_CODEC_OK;
621 }
622 }
623
Per598242a2015-11-26 14:28:55 +0100624 VideoFrame input_frame = frame;
625 if (scale_) {
626 // Check framerate before spatial resolution change.
627 quality_scaler_.OnEncodeFrame(frame);
628 const webrtc::QualityScaler::Resolution scaled_resolution =
629 quality_scaler_.GetScaledResolution();
630 if (scaled_resolution.width != frame.width() ||
631 scaled_resolution.height != frame.height()) {
632 if (frame.native_handle() != nullptr) {
633 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
634 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100635 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100636 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100637 scaled_resolution.height,
638 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100639 input_frame.set_video_frame_buffer(scaled_buffer);
640 } else {
641 input_frame = quality_scaler_.GetScaledFrame(frame);
642 }
643 }
644 }
jackychen61b4d512015-04-21 15:30:11 -0700645
perkj9576e542015-11-12 06:43:16 -0800646 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
647 ALOGE << "Failed to reconfigure encoder.";
648 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000649 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000650
glaznevf4decb52016-01-15 13:49:22 -0800651 // Save time when input frame is sent to the encoder input.
652 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000653
perkj30e91822015-11-20 01:31:25 -0800654 const bool key_frame = frame_types->front() != webrtc::kVideoFrameDelta;
655 bool encode_status = true;
656 if (!input_frame.native_handle()) {
657 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
658 j_dequeue_input_buffer_method_);
659 CHECK_EXCEPTION(jni);
660 if (j_input_buffer_index == -1) {
661 // Video codec falls behind - no input buffer available.
662 ALOGW << "Encoder drop frame - no input buffers available";
glaznevf4decb52016-01-15 13:49:22 -0800663 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
664 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
perkj30e91822015-11-20 01:31:25 -0800665 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
666 }
667 if (j_input_buffer_index == -2) {
668 ResetCodecOnCodecThread();
669 return WEBRTC_VIDEO_CODEC_ERROR;
670 }
671 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
672 j_input_buffer_index);
673 } else {
674 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000675 }
perkj30e91822015-11-20 01:31:25 -0800676
677 if (!encode_status) {
678 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800679 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200680 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000681 }
682
perkj9576e542015-11-12 06:43:16 -0800683 last_input_timestamp_ms_ =
684 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200685 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000686
perkj12f68022015-10-16 13:31:45 +0200687 // Save input image timestamps for later output
688 timestamps_.push_back(input_frame.timestamp());
689 render_times_ms_.push_back(input_frame.render_time_ms());
perkj9576e542015-11-12 06:43:16 -0800690 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
691
perkj30e91822015-11-20 01:31:25 -0800692 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800693 ALOGE << "Failed deliver pending outputs.";
694 ResetCodecOnCodecThread();
695 return WEBRTC_VIDEO_CODEC_ERROR;
696 }
697 return WEBRTC_VIDEO_CODEC_OK;
698}
699
700bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
701 const webrtc::VideoFrame& frame) {
702 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
703
perkj30e91822015-11-20 01:31:25 -0800704 const bool is_texture_frame = frame.native_handle() != nullptr;
705 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800706 const bool reconfigure_due_to_size =
707 frame.width() != width_ || frame.height() != height_;
708
perkj30e91822015-11-20 01:31:25 -0800709 if (reconfigure_due_to_format) {
710 ALOGD << "Reconfigure encoder due to format change. "
711 << (use_surface_ ?
712 "Reconfiguring to encode from byte buffer." :
713 "Reconfiguring to encode from texture.");
714 }
perkj9576e542015-11-12 06:43:16 -0800715 if (reconfigure_due_to_size) {
716 ALOGD << "Reconfigure encoder due to frame resolution change from "
717 << width_ << " x " << height_ << " to " << frame.width() << " x "
718 << frame.height();
719 width_ = frame.width();
720 height_ = frame.height();
721 }
722
perkj30e91822015-11-20 01:31:25 -0800723 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800724 return true;
725
726 ReleaseOnCodecThread();
727
perkj30e91822015-11-20 01:31:25 -0800728 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800729 WEBRTC_VIDEO_CODEC_OK;
730}
731
732bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
733 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
734 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800735 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800736
perkj9576e542015-11-12 06:43:16 -0800737 jobject j_input_buffer = input_buffers_[input_buffer_index];
738 uint8_t* yuv_buffer =
739 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
740 CHECK_EXCEPTION(jni);
741 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
742 RTC_CHECK(!libyuv::ConvertFromI420(
743 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
744 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
745 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
746 yuv_buffer, width_, width_, height_, encoder_fourcc_))
747 << "ConvertFromI420 failed";
748
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000749 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800750 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000751 key_frame,
perkj9576e542015-11-12 06:43:16 -0800752 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000753 yuv_size_,
754 current_timestamp_us_);
755 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800756 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000757}
758
perkj30e91822015-11-20 01:31:25 -0800759bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
760 bool key_frame, const webrtc::VideoFrame& frame) {
761 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
762 RTC_CHECK(use_surface_);
763 NativeHandleImpl* handle =
764 static_cast<NativeHandleImpl*>(frame.native_handle());
765 jfloatArray sampling_matrix = jni->NewFloatArray(16);
766 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
767
768 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
769 j_encode_texture_method_,
770 key_frame,
771 handle->oes_texture_id,
772 sampling_matrix,
773 current_timestamp_us_);
774 CHECK_EXCEPTION(jni);
775 return encode_status;
776}
777
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000778int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
779 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800780 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000781 JNIEnv* jni = AttachCurrentThreadIfNeeded();
782 ScopedLocalRefFrame local_ref_frame(jni);
783 callback_ = callback;
784 return WEBRTC_VIDEO_CODEC_OK;
785}
786
787int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800788 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000789 if (!inited_) {
790 return WEBRTC_VIDEO_CODEC_OK;
791 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000792 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700793 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
794 frames_received_ << ". Encoded: " << frames_encoded_ <<
795 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000796 ScopedLocalRefFrame local_ref_frame(jni);
797 for (size_t i = 0; i < input_buffers_.size(); ++i)
798 jni->DeleteGlobalRef(input_buffers_[i]);
799 input_buffers_.clear();
800 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
801 CHECK_EXCEPTION(jni);
802 rtc::MessageQueueManager::Clear(this);
803 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800804 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700805 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000806 return WEBRTC_VIDEO_CODEC_OK;
807}
808
809int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
810 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800811 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznevf4decb52016-01-15 13:49:22 -0800812 frame_rate = (frame_rate < MAX_ALLOWED_VIDEO_FPS) ?
813 frame_rate : MAX_ALLOWED_VIDEO_FPS;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000814 if (last_set_bitrate_kbps_ == new_bit_rate &&
815 last_set_fps_ == frame_rate) {
816 return WEBRTC_VIDEO_CODEC_OK;
817 }
818 JNIEnv* jni = AttachCurrentThreadIfNeeded();
819 ScopedLocalRefFrame local_ref_frame(jni);
820 if (new_bit_rate > 0) {
821 last_set_bitrate_kbps_ = new_bit_rate;
822 }
823 if (frame_rate > 0) {
824 last_set_fps_ = frame_rate;
825 }
826 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
827 j_set_rates_method_,
828 last_set_bitrate_kbps_,
829 last_set_fps_);
830 CHECK_EXCEPTION(jni);
831 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800832 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000833 return WEBRTC_VIDEO_CODEC_ERROR;
834 }
835 return WEBRTC_VIDEO_CODEC_OK;
836}
837
838int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
839 JNIEnv* jni,
840 jobject j_output_buffer_info) {
841 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
842}
843
844jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
845 JNIEnv* jni,
846 jobject j_output_buffer_info) {
847 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
848}
849
850bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
851 JNIEnv* jni,
852 jobject j_output_buffer_info) {
853 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
854}
855
856jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
857 JNIEnv* jni,
858 jobject j_output_buffer_info) {
859 return GetLongField(
860 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
861}
862
863bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800864 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000865 while (true) {
866 jobject j_output_buffer_info = jni->CallObjectMethod(
867 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
868 CHECK_EXCEPTION(jni);
869 if (IsNull(jni, j_output_buffer_info)) {
870 break;
871 }
872
873 int output_buffer_index =
874 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
875 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800876 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000877 return false;
878 }
879
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000880 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000881 jobject j_output_buffer =
882 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
883 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000884
885 // Get frame timestamps from a queue - for non config frames only.
886 int64_t frame_encoding_time_ms = 0;
887 last_output_timestamp_ms_ =
888 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
889 1000;
890 if (frames_in_queue_ > 0) {
891 output_timestamp_ = timestamps_.front();
892 timestamps_.erase(timestamps_.begin());
893 output_render_time_ms_ = render_times_ms_.front();
894 render_times_ms_.erase(render_times_ms_.begin());
895 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
896 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
897 frames_in_queue_--;
898 }
899
900 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000901 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200902 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000903 jni->GetDirectBufferAddress(j_output_buffer));
904 CHECK_EXCEPTION(jni);
905
glaznevf4decb52016-01-15 13:49:22 -0800906 if (frames_encoded_ < kMaxEncodedLogFrames) {
907 ALOGD << "Encoder frame out # " << frames_encoded_ << ". Key: " <<
908 key_frame << ". Size: " << payload_size << ". TS: " <<
909 (int)last_output_timestamp_ms_ << ". Latency: " <<
910 (int)(last_input_timestamp_ms_ - last_output_timestamp_ms_) <<
911 ". EncTime: " << frame_encoding_time_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000912 }
913
914 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000915 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000916 if (callback_) {
917 scoped_ptr<webrtc::EncodedImage> image(
918 new webrtc::EncodedImage(payload, payload_size, payload_size));
919 image->_encodedWidth = width_;
920 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000921 image->_timeStamp = output_timestamp_;
922 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200923 image->_frameType =
924 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000925 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700926 image->adapt_reason_.quality_resolution_downscales =
927 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000928
929 webrtc::CodecSpecificInfo info;
930 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000931 info.codecType = codecType_;
932 if (codecType_ == kVideoCodecVP8) {
933 info.codecSpecific.VP8.pictureId = picture_id_;
934 info.codecSpecific.VP8.nonReference = false;
935 info.codecSpecific.VP8.simulcastIdx = 0;
936 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
937 info.codecSpecific.VP8.layerSync = false;
938 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
939 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800940 } else if (codecType_ == kVideoCodecVP9) {
941 if (key_frame) {
942 gof_idx_ = 0;
943 }
944 info.codecSpecific.VP9.picture_id = picture_id_;
945 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
946 info.codecSpecific.VP9.flexible_mode = false;
947 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
948 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
949 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
950 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
951 info.codecSpecific.VP9.temporal_up_switch = true;
952 info.codecSpecific.VP9.inter_layer_predicted = false;
953 info.codecSpecific.VP9.gof_idx =
954 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
955 info.codecSpecific.VP9.num_spatial_layers = 1;
956 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
957 if (info.codecSpecific.VP9.ss_data_available) {
958 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
959 info.codecSpecific.VP9.width[0] = width_;
960 info.codecSpecific.VP9.height[0] = height_;
961 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
962 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000963 }
Alex Glaznevad948c42015-11-18 13:06:42 -0800964 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000965
966 // Generate a header describing a single fragment.
967 webrtc::RTPFragmentationHeader header;
968 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -0800969 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000970 header.VerifyAndAllocateFragmentationHeader(1);
971 header.fragmentationOffset[0] = 0;
972 header.fragmentationLength[0] = image->_length;
973 header.fragmentationPlType[0] = 0;
974 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -0800975 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -0700976 int qp;
glaznevf4decb52016-01-15 13:49:22 -0800977 if (webrtc::vp8::GetQp(payload, payload_size, &qp)) {
978 current_acc_qp_ += qp;
asapersson86b01602015-10-20 23:55:26 -0700979 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -0800980 }
asapersson86b01602015-10-20 23:55:26 -0700981 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000982 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200983 if (scale_) {
984 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
985 int qp;
glaznevf4decb52016-01-15 13:49:22 -0800986 if (h264_bitstream_parser_.GetLastSliceQp(&qp)) {
987 current_acc_qp_ += qp;
Peter Boström2bc68c72015-09-24 16:22:28 +0200988 quality_scaler_.ReportQP(qp);
glaznevf4decb52016-01-15 13:49:22 -0800989 }
Peter Boström2bc68c72015-09-24 16:22:28 +0200990 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000991 // For H.264 search for start codes.
992 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
993 int32_t scPositionsLength = 0;
994 int32_t scPosition = 0;
995 while (scPositionsLength < MAX_NALUS_PERFRAME) {
996 int32_t naluPosition = NextNaluPosition(
997 payload + scPosition, payload_size - scPosition);
998 if (naluPosition < 0) {
999 break;
1000 }
1001 scPosition += naluPosition;
1002 scPositions[scPositionsLength++] = scPosition;
1003 scPosition += H264_SC_LENGTH;
1004 }
1005 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001006 ALOGE << "Start code is not found!";
1007 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
1008 << " " << image->_buffer[2] << " " << image->_buffer[3]
1009 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -08001010 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001011 return false;
1012 }
1013 scPositions[scPositionsLength] = payload_size;
1014 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
1015 for (size_t i = 0; i < scPositionsLength; i++) {
1016 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1017 header.fragmentationLength[i] =
1018 scPositions[i + 1] - header.fragmentationOffset[i];
1019 header.fragmentationPlType[i] = 0;
1020 header.fragmentationTimeDiff[i] = 0;
1021 }
1022 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001023
1024 callback_status = callback_->Encoded(*image, &info, &header);
1025 }
1026
1027 // Return output buffer back to the encoder.
1028 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1029 j_release_output_buffer_method_,
1030 output_buffer_index);
1031 CHECK_EXCEPTION(jni);
1032 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001033 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001034 return false;
1035 }
1036
glaznevf4decb52016-01-15 13:49:22 -08001037 // Calculate and print encoding statistics - every 3 seconds.
1038 frames_encoded_++;
1039 current_frames_++;
1040 current_bytes_ += payload_size;
1041 current_encoding_time_ms_ += frame_encoding_time_ms;
1042 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
1043 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
1044 current_frames_ > 0) {
1045 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
1046 (current_bytes_ * 8 / statistic_time_ms) <<
1047 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
1048 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
1049 << ", encTime: " <<
1050 (current_encoding_time_ms_ / current_frames_) << ". QP: " <<
1051 (current_acc_qp_ / current_frames_) << " for last " <<
1052 statistic_time_ms << " ms.";
1053 start_time_ms_ = GetCurrentTimeMs();
1054 current_frames_ = 0;
1055 current_bytes_ = 0;
1056 current_acc_qp_ = 0;
1057 current_encoding_time_ms_ = 0;
1058 }
1059
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001060 if (callback_status > 0) {
1061 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001062 // Theoretically could handle callback_status<0 here, but unclear what
1063 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001064 }
1065 }
1066
1067 return true;
1068}
1069
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001070int32_t MediaCodecVideoEncoder::NextNaluPosition(
1071 uint8_t *buffer, size_t buffer_size) {
1072 if (buffer_size < H264_SC_LENGTH) {
1073 return -1;
1074 }
1075 uint8_t *head = buffer;
1076 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1077 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1078 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1079
1080 while (head < end) {
1081 if (head[0]) {
1082 head++;
1083 continue;
1084 }
1085 if (head[1]) { // got 00xx
1086 head += 2;
1087 continue;
1088 }
1089 if (head[2]) { // got 0000xx
1090 head += 3;
1091 continue;
1092 }
1093 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001094 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001095 continue;
1096 }
1097 return (int32_t)(head - buffer);
1098 }
1099 return -1;
1100}
1101
jackychen61b4d512015-04-21 15:30:11 -07001102void MediaCodecVideoEncoder::OnDroppedFrame() {
glaznevf4decb52016-01-15 13:49:22 -08001103 frames_dropped_++;
1104 // Report dropped frame to quality_scaler_.
Peter Boström2bc68c72015-09-24 16:22:28 +02001105 if (scale_)
1106 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001107}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001108
jackychen6e2ce6e2015-07-13 16:26:33 -07001109int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001110 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001111}
1112
Peter Boströmb7d9a972015-12-18 16:01:11 +01001113const char* MediaCodecVideoEncoder::ImplementationName() const {
1114 return "MediaCodec";
1115}
1116
perkj30e91822015-11-20 01:31:25 -08001117MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
Peter Boströmb7d9a972015-12-18 16:01:11 +01001118 : egl_context_(nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001119 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1120 ScopedLocalRefFrame local_ref_frame(jni);
1121 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001122 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001123
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001124 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1125 j_encoder_class,
1126 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1127 CHECK_EXCEPTION(jni);
1128 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001129 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001130 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1131 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1132 }
1133
Alex Glaznevad948c42015-11-18 13:06:42 -08001134 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1135 j_encoder_class,
1136 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1137 CHECK_EXCEPTION(jni);
1138 if (is_vp9_hw_supported) {
1139 ALOGD << "VP9 HW Encoder supported.";
1140 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1141 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1142 }
1143
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001144 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1145 j_encoder_class,
1146 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1147 CHECK_EXCEPTION(jni);
1148 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001149 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001150 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1151 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1152 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001153}
1154
1155MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
1156
perkj30e91822015-11-20 01:31:25 -08001157void MediaCodecVideoEncoderFactory::SetEGLContext(
1158 JNIEnv* jni, jobject render_egl_context) {
1159 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
1160 if (egl_context_) {
1161 jni->DeleteGlobalRef(egl_context_);
1162 egl_context_ = NULL;
1163 }
1164 if (!IsNull(jni, render_egl_context)) {
1165 egl_context_ = jni->NewGlobalRef(render_egl_context);
1166 if (CheckException(jni)) {
1167 ALOGE << "error calling NewGlobalRef for EGL Context.";
1168 egl_context_ = NULL;
1169 } else {
1170 jclass j_egl_context_class =
perkj48477c12015-12-18 00:34:37 -08001171 FindClass(jni, "org/webrtc/EglBase14$Context");
perkj30e91822015-11-20 01:31:25 -08001172 if (!jni->IsInstanceOf(egl_context_, j_egl_context_class)) {
1173 ALOGE << "Wrong EGL Context.";
1174 jni->DeleteGlobalRef(egl_context_);
1175 egl_context_ = NULL;
1176 }
1177 }
1178 }
1179 if (egl_context_ == NULL) {
1180 ALOGW << "NULL VideoDecoder EGL context - HW surface encoding is disabled.";
1181 }
1182}
1183
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001184webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001185 VideoCodecType type) {
1186 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001187 ALOGW << "No HW video encoder for type " << (int)type;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001188 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001189 }
1190 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1191 it != supported_codecs_.end(); ++it) {
1192 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001193 ALOGD << "Create HW video encoder for type " << (int)type <<
1194 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001195 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
1196 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001197 }
1198 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001199 ALOGW << "Can not find HW video encoder for type " << (int)type;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001200 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001201}
1202
1203const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1204MediaCodecVideoEncoderFactory::codecs() const {
1205 return supported_codecs_;
1206}
1207
1208void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1209 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001210 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001211 delete encoder;
1212}
1213
1214} // namespace webrtc_jni
1215