blob: 17b52b56bfc1d98fede494e3767e4bad81b2d109 [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
74
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000075// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
76// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
77// HW-backed video encode. This C++ class is implemented as a very thin shim,
78// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
79// MediaCodecVideoEncoder is created, operated, and destroyed on a single
80// thread, currently the libjingle Worker thread.
81class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
82 public rtc::MessageHandler {
83 public:
84 virtual ~MediaCodecVideoEncoder();
perkj9576e542015-11-12 06:43:16 -080085 MediaCodecVideoEncoder(JNIEnv* jni,
perkj30e91822015-11-20 01:31:25 -080086 VideoCodecType codecType,
87 jobject egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000088
89 // webrtc::VideoEncoder implementation. Everything trampolines to
90 // |codec_thread_| for execution.
91 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
92 int32_t /* number_of_cores */,
93 size_t /* max_payload_size */) override;
pbos22993e12015-10-19 02:39:06 -070094 int32_t Encode(const webrtc::VideoFrame& input_image,
95 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
96 const std::vector<webrtc::FrameType>* frame_types) override;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000097 int32_t RegisterEncodeCompleteCallback(
98 webrtc::EncodedImageCallback* callback) override;
99 int32_t Release() override;
100 int32_t SetChannelParameters(uint32_t /* packet_loss */,
101 int64_t /* rtt */) override;
102 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
103
104 // rtc::MessageHandler implementation.
105 void OnMessage(rtc::Message* msg) override;
106
jackychen61b4d512015-04-21 15:30:11 -0700107 void OnDroppedFrame() override;
108
jackychen6e2ce6e2015-07-13 16:26:33 -0700109 int GetTargetFramerate() override;
110
perkj30e91822015-11-20 01:31:25 -0800111 bool SupportsNativeHandle() const override { return true; }
112
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000113 private:
perkj9576e542015-11-12 06:43:16 -0800114 // ResetCodecOnCodecThread() calls ReleaseOnCodecThread() and
115 // InitEncodeOnCodecThread() in an attempt to restore the codec to an
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000116 // operable state. Necessary after all manner of OMX-layer errors.
perkj9576e542015-11-12 06:43:16 -0800117 bool ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000118
119 // Implementation of webrtc::VideoEncoder methods above, all running on the
120 // codec thread exclusively.
121 //
122 // If width==0 then this is assumed to be a re-initialization and the
123 // previously-current values are reused instead of the passed parameters
124 // (makes it easier to reason about thread-safety).
perkj30e91822015-11-20 01:31:25 -0800125 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps,
126 bool use_surface);
127 // Reconfigure to match |frame| in width, height. Also reconfigures the
128 // encoder if |frame| is a texture/byte buffer and the encoder is initialized
129 // for byte buffer/texture. Returns false if reconfiguring fails.
perkj9576e542015-11-12 06:43:16 -0800130 bool MaybeReconfigureEncoderOnCodecThread(const webrtc::VideoFrame& frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000131 int32_t EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700132 const webrtc::VideoFrame& input_image,
pbos22993e12015-10-19 02:39:06 -0700133 const std::vector<webrtc::FrameType>* frame_types);
perkj9576e542015-11-12 06:43:16 -0800134 bool EncodeByteBufferOnCodecThread(JNIEnv* jni,
135 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index);
perkj30e91822015-11-20 01:31:25 -0800136 bool EncodeTextureOnCodecThread(JNIEnv* jni,
137 bool key_frame, const webrtc::VideoFrame& frame);
perkj9576e542015-11-12 06:43:16 -0800138
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000139 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
140 webrtc::EncodedImageCallback* callback);
141 int32_t ReleaseOnCodecThread();
142 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
143
144 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
145 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
146 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
147 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
148 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000149 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000150
151 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
152 // true on success.
153 bool DeliverPendingOutputs(JNIEnv* jni);
154
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000155 // Search for H.264 start codes.
156 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
157
158 // Type of video codec.
159 VideoCodecType codecType_;
160
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000161 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
162 // |codec_thread_| synchronously.
163 webrtc::EncodedImageCallback* callback_;
164
165 // State that is constant for the lifetime of this object once the ctor
166 // returns.
167 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
perkj9576e542015-11-12 06:43:16 -0800168 rtc::ThreadChecker codec_thread_checker_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000169 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
170 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
171 jmethodID j_init_encode_method_;
perkj9576e542015-11-12 06:43:16 -0800172 jmethodID j_get_input_buffers_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000173 jmethodID j_dequeue_input_buffer_method_;
perkj9576e542015-11-12 06:43:16 -0800174 jmethodID j_encode_buffer_method_;
perkj30e91822015-11-20 01:31:25 -0800175 jmethodID j_encode_texture_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000176 jmethodID j_release_method_;
177 jmethodID j_set_rates_method_;
178 jmethodID j_dequeue_output_buffer_method_;
179 jmethodID j_release_output_buffer_method_;
180 jfieldID j_color_format_field_;
181 jfieldID j_info_index_field_;
182 jfieldID j_info_buffer_field_;
183 jfieldID j_info_is_key_frame_field_;
184 jfieldID j_info_presentation_timestamp_us_field_;
185
186 // State that is valid only between InitEncode() and the next Release().
187 // Touched only on codec_thread_ so no explicit synchronization necessary.
188 int width_; // Frame width in pixels.
189 int height_; // Frame height in pixels.
190 bool inited_;
perkj30e91822015-11-20 01:31:25 -0800191 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000192 uint16_t picture_id_;
193 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
194 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
195 int last_set_fps_; // Last-requested frame rate.
196 int64_t current_timestamp_us_; // Current frame timestamps in us.
197 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000198 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000199 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000200 int frames_in_queue_; // Number of frames in encoder queue.
201 int64_t start_time_ms_; // Start time for statistics.
202 int current_frames_; // Number of frames in the current statistics interval.
203 int current_bytes_; // Encoded bytes in the current statistics interval.
204 int current_encoding_time_ms_; // Overall encoding time in the current second
205 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
206 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
207 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
208 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
209 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
210 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000211 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
212 int64_t output_render_time_ms_; // Last output frame render time from
213 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000214 // Frame size in bytes fed to MediaCodec.
215 int yuv_size_;
216 // True only when between a callback_->Encoded() call return a positive value
217 // and the next Encode() call being ignored.
218 bool drop_next_input_frame_;
219 // Global references; must be deleted in Release().
220 std::vector<jobject> input_buffers_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200221 webrtc::QualityScaler quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700222 // Dynamic resolution change, off by default.
223 bool scale_;
Peter Boström2bc68c72015-09-24 16:22:28 +0200224
225 // H264 bitstream parser, used to extract QP from encoded bitstreams.
226 webrtc::H264BitstreamParser h264_bitstream_parser_;
Alex Glaznevad948c42015-11-18 13:06:42 -0800227
228 // VP9 variables to populate codec specific structure.
229 webrtc::GofInfoVP9 gof_; // Contains each frame's temporal information for
230 // non-flexible VP9 mode.
231 uint8_t tl0_pic_idx_;
232 size_t gof_idx_;
perkj30e91822015-11-20 01:31:25 -0800233
234 // EGL context - owned by factory, should not be allocated/destroyed
235 // by MediaCodecVideoEncoder.
236 jobject egl_context_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000237};
238
239MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
240 // Call Release() to ensure no more callbacks to us after we are deleted.
241 Release();
242}
243
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000244MediaCodecVideoEncoder::MediaCodecVideoEncoder(
perkj30e91822015-11-20 01:31:25 -0800245 JNIEnv* jni, VideoCodecType codecType, jobject egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000246 codecType_(codecType),
247 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000248 inited_(false),
perkj30e91822015-11-20 01:31:25 -0800249 use_surface_(false),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000250 picture_id_(0),
251 codec_thread_(new Thread()),
252 j_media_codec_video_encoder_class_(
253 jni,
254 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
255 j_media_codec_video_encoder_(
256 jni,
257 jni->NewObject(*j_media_codec_video_encoder_class_,
258 GetMethodID(jni,
259 *j_media_codec_video_encoder_class_,
260 "<init>",
perkj30e91822015-11-20 01:31:25 -0800261 "()V"))),
262 egl_context_(egl_context) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000263 ScopedLocalRefFrame local_ref_frame(jni);
264 // It would be nice to avoid spinning up a new thread per MediaCodec, and
265 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
266 // 2732 means that deadlocks abound. This class synchronously trampolines
267 // to |codec_thread_|, so if anything else can be coming to _us_ from
268 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
269 // in the bug, we have a problem. For now work around that with a dedicated
270 // thread.
271 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700272 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
perkj9576e542015-11-12 06:43:16 -0800273 codec_thread_checker_.DetachFromThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000274 jclass j_output_buffer_info_class =
275 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000276 j_init_encode_method_ = GetMethodID(
277 jni,
278 *j_media_codec_video_encoder_class_,
279 "initEncode",
perkj30e91822015-11-20 01:31:25 -0800280 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;"
perkj40455d62015-12-02 01:07:18 -0800281 "IIIILorg/webrtc/EglBase$Context;)Z");
perkj9576e542015-11-12 06:43:16 -0800282 j_get_input_buffers_method_ = GetMethodID(
283 jni,
284 *j_media_codec_video_encoder_class_,
285 "getInputBuffers",
286 "()[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000287 j_dequeue_input_buffer_method_ = GetMethodID(
288 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
perkj9576e542015-11-12 06:43:16 -0800289 j_encode_buffer_method_ = GetMethodID(
290 jni, *j_media_codec_video_encoder_class_, "encodeBuffer", "(ZIIJ)Z");
perkj30e91822015-11-20 01:31:25 -0800291 j_encode_texture_method_ = GetMethodID(
292 jni, *j_media_codec_video_encoder_class_, "encodeTexture",
293 "(ZI[FJ)Z");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000294 j_release_method_ =
295 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
296 j_set_rates_method_ = GetMethodID(
297 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000298 j_dequeue_output_buffer_method_ = GetMethodID(
299 jni,
300 *j_media_codec_video_encoder_class_,
301 "dequeueOutputBuffer",
302 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000303 j_release_output_buffer_method_ = GetMethodID(
304 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
305
306 j_color_format_field_ =
307 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
308 j_info_index_field_ =
309 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
310 j_info_buffer_field_ = GetFieldID(
311 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
312 j_info_is_key_frame_field_ =
313 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
314 j_info_presentation_timestamp_us_field_ = GetFieldID(
315 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
316 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
Alex Glaznevad948c42015-11-18 13:06:42 -0800317 srand(time(NULL));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000318 AllowBlockingCalls();
319}
320
321int32_t MediaCodecVideoEncoder::InitEncode(
322 const webrtc::VideoCodec* codec_settings,
323 int32_t /* number_of_cores */,
324 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700325 const int kMinWidth = 320;
326 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700327 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000328 if (codec_settings == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700329 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000330 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
331 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000332 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700333 RTC_CHECK(codec_settings->codecType == codecType_)
334 << "Unsupported codec " << codec_settings->codecType << " for "
335 << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000336
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700337 ALOGD << "InitEncode request";
Alex Glaznevad948c42015-11-18 13:06:42 -0800338 scale_ = (codecType_ != kVideoCodecVP9) && (webrtc::field_trial::FindFullName(
339 "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled");
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700340 ALOGD << "Encoder automatic resize " << (scale_ ? "enabled" : "disabled");
Peter Boström2bc68c72015-09-24 16:22:28 +0200341 if (scale_) {
342 if (codecType_ == kVideoCodecVP8) {
343 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
344 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
345 // always = 127. Note that in SW, QP is that of the user-level range [0,
346 // 63].
347 const int kMaxQp = 127;
Peter Boström17417702015-09-25 17:03:26 +0200348 // TODO(pbos): Investigate whether high-QP thresholds make sense for VP8.
349 // This effectively disables high QP as VP8 QP can't go above this
350 // threshold.
351 const int kDisabledBadQpThreshold = kMaxQp + 1;
352 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator,
353 kDisabledBadQpThreshold, true);
Peter Boström2bc68c72015-09-24 16:22:28 +0200354 } else if (codecType_ == kVideoCodecH264) {
355 // H264 QP is in the range [0, 51].
356 const int kMaxQp = 51;
Peter Boström17417702015-09-25 17:03:26 +0200357 const int kBadQpThreshold = 40;
358 quality_scaler_.Init(kMaxQp / kLowQpThresholdDenominator, kBadQpThreshold,
359 false);
Peter Boström2bc68c72015-09-24 16:22:28 +0200360 } else {
361 // When adding codec support to additional hardware codecs, also configure
362 // their QP thresholds for scaling.
363 RTC_NOTREACHED() << "Unsupported codec without configured QP thresholds.";
364 }
365 quality_scaler_.SetMinResolution(kMinWidth, kMinHeight);
366 quality_scaler_.ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700367 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000368 return codec_thread_->Invoke<int32_t>(
369 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
370 this,
371 codec_settings->width,
372 codec_settings->height,
373 codec_settings->startBitrate,
perkj30e91822015-11-20 01:31:25 -0800374 codec_settings->maxFramerate,
375 false /* use_surface */));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000376}
377
378int32_t MediaCodecVideoEncoder::Encode(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700379 const webrtc::VideoFrame& frame,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000380 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
pbos22993e12015-10-19 02:39:06 -0700381 const std::vector<webrtc::FrameType>* frame_types) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000382 return codec_thread_->Invoke<int32_t>(Bind(
383 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
384}
385
386int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
387 webrtc::EncodedImageCallback* callback) {
388 return codec_thread_->Invoke<int32_t>(
389 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
390 this,
391 callback));
392}
393
394int32_t MediaCodecVideoEncoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700395 ALOGD << "EncoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000396 return codec_thread_->Invoke<int32_t>(
397 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
398}
399
400int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
401 int64_t /* rtt */) {
402 return WEBRTC_VIDEO_CODEC_OK;
403}
404
405int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
406 uint32_t frame_rate) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200407 if (scale_)
408 quality_scaler_.ReportFramerate(frame_rate);
409
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000410 return codec_thread_->Invoke<int32_t>(
411 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
412 this,
413 new_bit_rate,
414 frame_rate));
415}
416
417void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
perkj9576e542015-11-12 06:43:16 -0800418 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000419 JNIEnv* jni = AttachCurrentThreadIfNeeded();
420 ScopedLocalRefFrame local_ref_frame(jni);
421
422 // We only ever send one message to |this| directly (not through a Bind()'d
423 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700424 RTC_CHECK(!msg->message_id) << "Unexpected message!";
425 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000426 if (!inited_) {
427 return;
428 }
429
430 // It would be nice to recover from a failure here if one happened, but it's
431 // unclear how to signal such a failure to the app, so instead we stay silent
432 // about it and let the next app-called API method reveal the borkedness.
433 DeliverPendingOutputs(jni);
434 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
435}
436
perkj9576e542015-11-12 06:43:16 -0800437bool MediaCodecVideoEncoder::ResetCodecOnCodecThread() {
438 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
439 ALOGE << "ResetOnCodecThread";
440 if (ReleaseOnCodecThread() != WEBRTC_VIDEO_CODEC_OK ||
perkj30e91822015-11-20 01:31:25 -0800441 InitEncodeOnCodecThread(width_, height_, 0, 0, false) !=
442 WEBRTC_VIDEO_CODEC_OK) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000443 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
444 // degrade to a SW encoder at this point? There isn't one AFAICT :(
445 // https://code.google.com/p/webrtc/issues/detail?id=2920
perkj9576e542015-11-12 06:43:16 -0800446 return false;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000447 }
perkj9576e542015-11-12 06:43:16 -0800448 return true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000449}
450
451int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
perkj30e91822015-11-20 01:31:25 -0800452 int width, int height, int kbps, int fps, bool use_surface) {
perkj9576e542015-11-12 06:43:16 -0800453 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800454 RTC_CHECK(!use_surface || egl_context_ != nullptr) << "EGL context not set.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000455 JNIEnv* jni = AttachCurrentThreadIfNeeded();
456 ScopedLocalRefFrame local_ref_frame(jni);
457
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700458 ALOGD << "InitEncodeOnCodecThread Type: " << (int)codecType_ << ", " <<
459 width << " x " << height << ". Bitrate: " << kbps <<
460 " kbps. Fps: " << fps;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000461 if (kbps == 0) {
462 kbps = last_set_bitrate_kbps_;
463 }
464 if (fps == 0) {
465 fps = last_set_fps_;
466 }
467
468 width_ = width;
469 height_ = height;
470 last_set_bitrate_kbps_ = kbps;
471 last_set_fps_ = fps;
472 yuv_size_ = width_ * height_ * 3 / 2;
473 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000474 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000475 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000476 frames_in_queue_ = 0;
477 current_timestamp_us_ = 0;
478 start_time_ms_ = GetCurrentTimeMs();
479 current_frames_ = 0;
480 current_bytes_ = 0;
481 current_encoding_time_ms_ = 0;
482 last_input_timestamp_ms_ = -1;
483 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000484 output_timestamp_ = 0;
485 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000486 timestamps_.clear();
487 render_times_ms_.clear();
488 frame_rtc_times_ms_.clear();
489 drop_next_input_frame_ = false;
perkj30e91822015-11-20 01:31:25 -0800490 use_surface_ = use_surface;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000491 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
Alex Glaznevad948c42015-11-18 13:06:42 -0800492 gof_.SetGofInfoVP9(webrtc::TemporalStructureMode::kTemporalStructureMode1);
493 tl0_pic_idx_ = static_cast<uint8_t>(rand());
494 gof_idx_ = 0;
perkj9576e542015-11-12 06:43:16 -0800495
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000496 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000497 jobject j_video_codec_enum = JavaEnumFromIndex(
498 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
perkj9576e542015-11-12 06:43:16 -0800499 const bool encode_status = jni->CallBooleanMethod(
500 *j_media_codec_video_encoder_, j_init_encode_method_,
perkj30e91822015-11-20 01:31:25 -0800501 j_video_codec_enum, width, height, kbps, fps,
502 (use_surface ? egl_context_ : nullptr));
perkj9576e542015-11-12 06:43:16 -0800503 if (!encode_status) {
504 ALOGE << "Failed to configure encoder.";
505 return WEBRTC_VIDEO_CODEC_ERROR;
506 }
507 CHECK_EXCEPTION(jni);
508
Per598242a2015-11-26 14:28:55 +0100509 if (!use_surface) {
perkj30e91822015-11-20 01:31:25 -0800510 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
511 jni->CallObjectMethod(*j_media_codec_video_encoder_,
512 j_get_input_buffers_method_));
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000513 CHECK_EXCEPTION(jni);
perkj30e91822015-11-20 01:31:25 -0800514 if (IsNull(jni, input_buffers)) {
515 return WEBRTC_VIDEO_CODEC_ERROR;
516 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000517
perkj30e91822015-11-20 01:31:25 -0800518 switch (GetIntField(jni, *j_media_codec_video_encoder_,
519 j_color_format_field_)) {
520 case COLOR_FormatYUV420Planar:
521 encoder_fourcc_ = libyuv::FOURCC_YU12;
522 break;
523 case COLOR_FormatYUV420SemiPlanar:
524 case COLOR_QCOM_FormatYUV420SemiPlanar:
525 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
526 encoder_fourcc_ = libyuv::FOURCC_NV12;
527 break;
528 default:
529 LOG(LS_ERROR) << "Wrong color format.";
530 return WEBRTC_VIDEO_CODEC_ERROR;
531 }
532 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
533 RTC_CHECK(input_buffers_.empty())
534 << "Unexpected double InitEncode without Release";
535 input_buffers_.resize(num_input_buffers);
536 for (size_t i = 0; i < num_input_buffers; ++i) {
537 input_buffers_[i] =
538 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
539 int64_t yuv_buffer_capacity =
540 jni->GetDirectBufferCapacity(input_buffers_[i]);
541 CHECK_EXCEPTION(jni);
542 RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
543 }
544 }
perkj9576e542015-11-12 06:43:16 -0800545
546 inited_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000547 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
548 return WEBRTC_VIDEO_CODEC_OK;
549}
550
551int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700552 const webrtc::VideoFrame& frame,
pbos22993e12015-10-19 02:39:06 -0700553 const std::vector<webrtc::FrameType>* frame_types) {
perkj9576e542015-11-12 06:43:16 -0800554 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000555 JNIEnv* jni = AttachCurrentThreadIfNeeded();
556 ScopedLocalRefFrame local_ref_frame(jni);
557
558 if (!inited_) {
559 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
560 }
perkj9576e542015-11-12 06:43:16 -0800561
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000562 frames_received_++;
563 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800564 if (!ResetCodecOnCodecThread())
565 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000566 }
567
568 if (drop_next_input_frame_) {
perkj9576e542015-11-12 06:43:16 -0800569 ALOGW << "Encoder drop frame - failed callback.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000570 drop_next_input_frame_ = false;
571 return WEBRTC_VIDEO_CODEC_OK;
572 }
573
henrikg91d6ede2015-09-17 00:24:34 -0700574 RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count";
Peter Boström2bc68c72015-09-24 16:22:28 +0200575
Per598242a2015-11-26 14:28:55 +0100576 VideoFrame input_frame = frame;
577 if (scale_) {
578 // Check framerate before spatial resolution change.
579 quality_scaler_.OnEncodeFrame(frame);
580 const webrtc::QualityScaler::Resolution scaled_resolution =
581 quality_scaler_.GetScaledResolution();
582 if (scaled_resolution.width != frame.width() ||
583 scaled_resolution.height != frame.height()) {
584 if (frame.native_handle() != nullptr) {
585 rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled_buffer(
586 static_cast<AndroidTextureBuffer*>(
Per71f5a9a2015-12-11 09:32:37 +0100587 frame.video_frame_buffer().get())->ScaleAndRotate(
Per598242a2015-11-26 14:28:55 +0100588 scaled_resolution.width,
Per71f5a9a2015-12-11 09:32:37 +0100589 scaled_resolution.height,
590 webrtc::kVideoRotation_0));
Per598242a2015-11-26 14:28:55 +0100591 input_frame.set_video_frame_buffer(scaled_buffer);
592 } else {
593 input_frame = quality_scaler_.GetScaledFrame(frame);
594 }
595 }
596 }
jackychen61b4d512015-04-21 15:30:11 -0700597
perkj9576e542015-11-12 06:43:16 -0800598 if (!MaybeReconfigureEncoderOnCodecThread(input_frame)) {
599 ALOGE << "Failed to reconfigure encoder.";
600 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000601 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000602
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000603 // Check if we accumulated too many frames in encoder input buffers
604 // or the encoder latency exceeds 70 ms and drop frame if so.
605 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
606 int encoder_latency_ms = last_input_timestamp_ms_ -
607 last_output_timestamp_ms_;
608 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700609 ALOGD << "Drop frame - encoder is behind by " << encoder_latency_ms <<
610 " ms. Q size: " << frames_in_queue_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000611 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700612 // Report dropped frame to quality_scaler_.
613 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000614 return WEBRTC_VIDEO_CODEC_OK;
615 }
616 }
617
perkj30e91822015-11-20 01:31:25 -0800618 const bool key_frame = frame_types->front() != webrtc::kVideoFrameDelta;
619 bool encode_status = true;
620 if (!input_frame.native_handle()) {
621 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
622 j_dequeue_input_buffer_method_);
623 CHECK_EXCEPTION(jni);
624 if (j_input_buffer_index == -1) {
625 // Video codec falls behind - no input buffer available.
626 ALOGW << "Encoder drop frame - no input buffers available";
627 frames_dropped_++;
628 // Report dropped frame to quality_scaler_.
629 OnDroppedFrame();
630 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
631 }
632 if (j_input_buffer_index == -2) {
633 ResetCodecOnCodecThread();
634 return WEBRTC_VIDEO_CODEC_ERROR;
635 }
636 encode_status = EncodeByteBufferOnCodecThread(jni, key_frame, input_frame,
637 j_input_buffer_index);
638 } else {
639 encode_status = EncodeTextureOnCodecThread(jni, key_frame, input_frame);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000640 }
perkj30e91822015-11-20 01:31:25 -0800641
642 if (!encode_status) {
643 ALOGE << "Failed encode frame with timestamp: " << input_frame.timestamp();
perkj9576e542015-11-12 06:43:16 -0800644 ResetCodecOnCodecThread();
perkj12f68022015-10-16 13:31:45 +0200645 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000646 }
647
perkj9576e542015-11-12 06:43:16 -0800648 last_input_timestamp_ms_ =
649 current_timestamp_us_ / rtc::kNumMicrosecsPerMillisec;
perkj12f68022015-10-16 13:31:45 +0200650 frames_in_queue_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000651
perkj12f68022015-10-16 13:31:45 +0200652 // Save input image timestamps for later output
653 timestamps_.push_back(input_frame.timestamp());
654 render_times_ms_.push_back(input_frame.render_time_ms());
655 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
perkj9576e542015-11-12 06:43:16 -0800656 current_timestamp_us_ += rtc::kNumMicrosecsPerSec / last_set_fps_;
657
perkj30e91822015-11-20 01:31:25 -0800658 if (!DeliverPendingOutputs(jni)) {
perkj9576e542015-11-12 06:43:16 -0800659 ALOGE << "Failed deliver pending outputs.";
660 ResetCodecOnCodecThread();
661 return WEBRTC_VIDEO_CODEC_ERROR;
662 }
663 return WEBRTC_VIDEO_CODEC_OK;
664}
665
666bool MediaCodecVideoEncoder::MaybeReconfigureEncoderOnCodecThread(
667 const webrtc::VideoFrame& frame) {
668 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
669
perkj30e91822015-11-20 01:31:25 -0800670 const bool is_texture_frame = frame.native_handle() != nullptr;
671 const bool reconfigure_due_to_format = is_texture_frame != use_surface_;
perkj9576e542015-11-12 06:43:16 -0800672 const bool reconfigure_due_to_size =
673 frame.width() != width_ || frame.height() != height_;
674
perkj30e91822015-11-20 01:31:25 -0800675 if (reconfigure_due_to_format) {
676 ALOGD << "Reconfigure encoder due to format change. "
677 << (use_surface_ ?
678 "Reconfiguring to encode from byte buffer." :
679 "Reconfiguring to encode from texture.");
680 }
perkj9576e542015-11-12 06:43:16 -0800681 if (reconfigure_due_to_size) {
682 ALOGD << "Reconfigure encoder due to frame resolution change from "
683 << width_ << " x " << height_ << " to " << frame.width() << " x "
684 << frame.height();
685 width_ = frame.width();
686 height_ = frame.height();
687 }
688
perkj30e91822015-11-20 01:31:25 -0800689 if (!reconfigure_due_to_format && !reconfigure_due_to_size)
perkj9576e542015-11-12 06:43:16 -0800690 return true;
691
692 ReleaseOnCodecThread();
693
perkj30e91822015-11-20 01:31:25 -0800694 return InitEncodeOnCodecThread(width_, height_, 0, 0 , is_texture_frame) ==
perkj9576e542015-11-12 06:43:16 -0800695 WEBRTC_VIDEO_CODEC_OK;
696}
697
698bool MediaCodecVideoEncoder::EncodeByteBufferOnCodecThread(JNIEnv* jni,
699 bool key_frame, const webrtc::VideoFrame& frame, int input_buffer_index) {
700 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
perkj30e91822015-11-20 01:31:25 -0800701 RTC_CHECK(!use_surface_);
perkj9576e542015-11-12 06:43:16 -0800702
703 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
704 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
705
706 jobject j_input_buffer = input_buffers_[input_buffer_index];
707 uint8_t* yuv_buffer =
708 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
709 CHECK_EXCEPTION(jni);
710 RTC_CHECK(yuv_buffer) << "Indirect buffer??";
711 RTC_CHECK(!libyuv::ConvertFromI420(
712 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
713 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
714 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
715 yuv_buffer, width_, width_, height_, encoder_fourcc_))
716 << "ConvertFromI420 failed";
717
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000718 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
perkj9576e542015-11-12 06:43:16 -0800719 j_encode_buffer_method_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000720 key_frame,
perkj9576e542015-11-12 06:43:16 -0800721 input_buffer_index,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000722 yuv_size_,
723 current_timestamp_us_);
724 CHECK_EXCEPTION(jni);
perkj9576e542015-11-12 06:43:16 -0800725 return encode_status;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000726}
727
perkj30e91822015-11-20 01:31:25 -0800728bool MediaCodecVideoEncoder::EncodeTextureOnCodecThread(JNIEnv* jni,
729 bool key_frame, const webrtc::VideoFrame& frame) {
730 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
731 RTC_CHECK(use_surface_);
732 NativeHandleImpl* handle =
733 static_cast<NativeHandleImpl*>(frame.native_handle());
734 jfloatArray sampling_matrix = jni->NewFloatArray(16);
735 jni->SetFloatArrayRegion(sampling_matrix, 0, 16, handle->sampling_matrix);
736
737 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
738 j_encode_texture_method_,
739 key_frame,
740 handle->oes_texture_id,
741 sampling_matrix,
742 current_timestamp_us_);
743 CHECK_EXCEPTION(jni);
744 return encode_status;
745}
746
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000747int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
748 webrtc::EncodedImageCallback* callback) {
perkj9576e542015-11-12 06:43:16 -0800749 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000750 JNIEnv* jni = AttachCurrentThreadIfNeeded();
751 ScopedLocalRefFrame local_ref_frame(jni);
752 callback_ = callback;
753 return WEBRTC_VIDEO_CODEC_OK;
754}
755
756int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
perkj9576e542015-11-12 06:43:16 -0800757 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000758 if (!inited_) {
759 return WEBRTC_VIDEO_CODEC_OK;
760 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000761 JNIEnv* jni = AttachCurrentThreadIfNeeded();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700762 ALOGD << "EncoderReleaseOnCodecThread: Frames received: " <<
763 frames_received_ << ". Encoded: " << frames_encoded_ <<
764 ". Dropped: " << frames_dropped_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000765 ScopedLocalRefFrame local_ref_frame(jni);
766 for (size_t i = 0; i < input_buffers_.size(); ++i)
767 jni->DeleteGlobalRef(input_buffers_[i]);
768 input_buffers_.clear();
769 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
770 CHECK_EXCEPTION(jni);
771 rtc::MessageQueueManager::Clear(this);
772 inited_ = false;
perkj30e91822015-11-20 01:31:25 -0800773 use_surface_ = false;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700774 ALOGD << "EncoderReleaseOnCodecThread done.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000775 return WEBRTC_VIDEO_CODEC_OK;
776}
777
778int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
779 uint32_t frame_rate) {
perkj9576e542015-11-12 06:43:16 -0800780 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000781 if (last_set_bitrate_kbps_ == new_bit_rate &&
782 last_set_fps_ == frame_rate) {
783 return WEBRTC_VIDEO_CODEC_OK;
784 }
785 JNIEnv* jni = AttachCurrentThreadIfNeeded();
786 ScopedLocalRefFrame local_ref_frame(jni);
787 if (new_bit_rate > 0) {
788 last_set_bitrate_kbps_ = new_bit_rate;
789 }
790 if (frame_rate > 0) {
791 last_set_fps_ = frame_rate;
792 }
793 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
794 j_set_rates_method_,
795 last_set_bitrate_kbps_,
796 last_set_fps_);
797 CHECK_EXCEPTION(jni);
798 if (!ret) {
perkj9576e542015-11-12 06:43:16 -0800799 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000800 return WEBRTC_VIDEO_CODEC_ERROR;
801 }
802 return WEBRTC_VIDEO_CODEC_OK;
803}
804
805int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
806 JNIEnv* jni,
807 jobject j_output_buffer_info) {
808 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
809}
810
811jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
812 JNIEnv* jni,
813 jobject j_output_buffer_info) {
814 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
815}
816
817bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
818 JNIEnv* jni,
819 jobject j_output_buffer_info) {
820 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
821}
822
823jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
824 JNIEnv* jni,
825 jobject j_output_buffer_info) {
826 return GetLongField(
827 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
828}
829
830bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
perkj9576e542015-11-12 06:43:16 -0800831 RTC_DCHECK(codec_thread_checker_.CalledOnValidThread());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000832 while (true) {
833 jobject j_output_buffer_info = jni->CallObjectMethod(
834 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
835 CHECK_EXCEPTION(jni);
836 if (IsNull(jni, j_output_buffer_info)) {
837 break;
838 }
839
840 int output_buffer_index =
841 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
842 if (output_buffer_index == -1) {
perkj9576e542015-11-12 06:43:16 -0800843 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000844 return false;
845 }
846
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000847 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000848 jobject j_output_buffer =
849 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
850 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000851
852 // Get frame timestamps from a queue - for non config frames only.
853 int64_t frame_encoding_time_ms = 0;
854 last_output_timestamp_ms_ =
855 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
856 1000;
857 if (frames_in_queue_ > 0) {
858 output_timestamp_ = timestamps_.front();
859 timestamps_.erase(timestamps_.begin());
860 output_render_time_ms_ = render_times_ms_.front();
861 render_times_ms_.erase(render_times_ms_.begin());
862 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
863 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
864 frames_in_queue_--;
865 }
866
867 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000868 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200869 uint8_t* payload = reinterpret_cast<uint8_t*>(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000870 jni->GetDirectBufferAddress(j_output_buffer));
871 CHECK_EXCEPTION(jni);
872
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000873 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
874 " Latency: %lld. EncTime: %lld",
875 frames_encoded_, key_frame, payload_size,
876 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000877 last_input_timestamp_ms_ - last_output_timestamp_ms_,
878 frame_encoding_time_ms);
879
880 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000881 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000882 current_frames_++;
883 current_bytes_ += payload_size;
884 current_encoding_time_ms_ += frame_encoding_time_ms;
885 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
886 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
887 current_frames_ > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700888 ALOGD << "Encoded frames: " << frames_encoded_ << ". Bitrate: " <<
889 (current_bytes_ * 8 / statistic_time_ms) <<
890 ", target: " << last_set_bitrate_kbps_ << " kbps, fps: " <<
891 ((current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms)
892 << ", encTime: " <<
893 (current_encoding_time_ms_ / current_frames_) << " for last " <<
894 statistic_time_ms << " ms.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000895 start_time_ms_ = GetCurrentTimeMs();
896 current_frames_ = 0;
897 current_bytes_ = 0;
898 current_encoding_time_ms_ = 0;
899 }
900
901 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000902 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000903 if (callback_) {
904 scoped_ptr<webrtc::EncodedImage> image(
905 new webrtc::EncodedImage(payload, payload_size, payload_size));
906 image->_encodedWidth = width_;
907 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000908 image->_timeStamp = output_timestamp_;
909 image->capture_time_ms_ = output_render_time_ms_;
Peter Boström49e196a2015-10-23 15:58:18 +0200910 image->_frameType =
911 (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000912 image->_completeFrame = true;
asapersson075fb4b2015-10-29 08:49:14 -0700913 image->adapt_reason_.quality_resolution_downscales =
914 scale_ ? quality_scaler_.downscale_shift() : -1;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000915
916 webrtc::CodecSpecificInfo info;
917 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000918 info.codecType = codecType_;
919 if (codecType_ == kVideoCodecVP8) {
920 info.codecSpecific.VP8.pictureId = picture_id_;
921 info.codecSpecific.VP8.nonReference = false;
922 info.codecSpecific.VP8.simulcastIdx = 0;
923 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
924 info.codecSpecific.VP8.layerSync = false;
925 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
926 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
Alex Glaznevad948c42015-11-18 13:06:42 -0800927 } else if (codecType_ == kVideoCodecVP9) {
928 if (key_frame) {
929 gof_idx_ = 0;
930 }
931 info.codecSpecific.VP9.picture_id = picture_id_;
932 info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true;
933 info.codecSpecific.VP9.flexible_mode = false;
934 info.codecSpecific.VP9.ss_data_available = key_frame ? true : false;
935 info.codecSpecific.VP9.tl0_pic_idx = tl0_pic_idx_++;
936 info.codecSpecific.VP9.temporal_idx = webrtc::kNoTemporalIdx;
937 info.codecSpecific.VP9.spatial_idx = webrtc::kNoSpatialIdx;
938 info.codecSpecific.VP9.temporal_up_switch = true;
939 info.codecSpecific.VP9.inter_layer_predicted = false;
940 info.codecSpecific.VP9.gof_idx =
941 static_cast<uint8_t>(gof_idx_++ % gof_.num_frames_in_gof);
942 info.codecSpecific.VP9.num_spatial_layers = 1;
943 info.codecSpecific.VP9.spatial_layer_resolution_present = false;
944 if (info.codecSpecific.VP9.ss_data_available) {
945 info.codecSpecific.VP9.spatial_layer_resolution_present = true;
946 info.codecSpecific.VP9.width[0] = width_;
947 info.codecSpecific.VP9.height[0] = height_;
948 info.codecSpecific.VP9.gof.CopyGofInfoVP9(gof_);
949 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000950 }
Alex Glaznevad948c42015-11-18 13:06:42 -0800951 picture_id_ = (picture_id_ + 1) & 0x7FFF;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000952
953 // Generate a header describing a single fragment.
954 webrtc::RTPFragmentationHeader header;
955 memset(&header, 0, sizeof(header));
Alex Glaznevad948c42015-11-18 13:06:42 -0800956 if (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecVP9) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000957 header.VerifyAndAllocateFragmentationHeader(1);
958 header.fragmentationOffset[0] = 0;
959 header.fragmentationLength[0] = image->_length;
960 header.fragmentationPlType[0] = 0;
961 header.fragmentationTimeDiff[0] = 0;
Alex Glaznevad948c42015-11-18 13:06:42 -0800962 if (codecType_ == kVideoCodecVP8 && scale_) {
asapersson86b01602015-10-20 23:55:26 -0700963 int qp;
964 if (webrtc::vp8::GetQp(payload, payload_size, &qp))
965 quality_scaler_.ReportQP(qp);
966 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000967 } else if (codecType_ == kVideoCodecH264) {
Peter Boström2bc68c72015-09-24 16:22:28 +0200968 if (scale_) {
969 h264_bitstream_parser_.ParseBitstream(payload, payload_size);
970 int qp;
971 if (h264_bitstream_parser_.GetLastSliceQp(&qp))
972 quality_scaler_.ReportQP(qp);
973 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000974 // For H.264 search for start codes.
975 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
976 int32_t scPositionsLength = 0;
977 int32_t scPosition = 0;
978 while (scPositionsLength < MAX_NALUS_PERFRAME) {
979 int32_t naluPosition = NextNaluPosition(
980 payload + scPosition, payload_size - scPosition);
981 if (naluPosition < 0) {
982 break;
983 }
984 scPosition += naluPosition;
985 scPositions[scPositionsLength++] = scPosition;
986 scPosition += H264_SC_LENGTH;
987 }
988 if (scPositionsLength == 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700989 ALOGE << "Start code is not found!";
990 ALOGE << "Data:" << image->_buffer[0] << " " << image->_buffer[1]
991 << " " << image->_buffer[2] << " " << image->_buffer[3]
992 << " " << image->_buffer[4] << " " << image->_buffer[5];
perkj9576e542015-11-12 06:43:16 -0800993 ResetCodecOnCodecThread();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000994 return false;
995 }
996 scPositions[scPositionsLength] = payload_size;
997 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
998 for (size_t i = 0; i < scPositionsLength; i++) {
999 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
1000 header.fragmentationLength[i] =
1001 scPositions[i + 1] - header.fragmentationOffset[i];
1002 header.fragmentationPlType[i] = 0;
1003 header.fragmentationTimeDiff[i] = 0;
1004 }
1005 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001006
1007 callback_status = callback_->Encoded(*image, &info, &header);
1008 }
1009
1010 // Return output buffer back to the encoder.
1011 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
1012 j_release_output_buffer_method_,
1013 output_buffer_index);
1014 CHECK_EXCEPTION(jni);
1015 if (!success) {
perkj9576e542015-11-12 06:43:16 -08001016 ResetCodecOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001017 return false;
1018 }
1019
1020 if (callback_status > 0) {
1021 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001022 // Theoretically could handle callback_status<0 here, but unclear what
1023 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001024 }
1025 }
1026
1027 return true;
1028}
1029
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001030int32_t MediaCodecVideoEncoder::NextNaluPosition(
1031 uint8_t *buffer, size_t buffer_size) {
1032 if (buffer_size < H264_SC_LENGTH) {
1033 return -1;
1034 }
1035 uint8_t *head = buffer;
1036 // Set end buffer pointer to 4 bytes before actual buffer end so we can
1037 // access head[1], head[2] and head[3] in a loop without buffer overrun.
1038 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
1039
1040 while (head < end) {
1041 if (head[0]) {
1042 head++;
1043 continue;
1044 }
1045 if (head[1]) { // got 00xx
1046 head += 2;
1047 continue;
1048 }
1049 if (head[2]) { // got 0000xx
1050 head += 3;
1051 continue;
1052 }
1053 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +00001054 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001055 continue;
1056 }
1057 return (int32_t)(head - buffer);
1058 }
1059 return -1;
1060}
1061
jackychen61b4d512015-04-21 15:30:11 -07001062void MediaCodecVideoEncoder::OnDroppedFrame() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001063 if (scale_)
1064 quality_scaler_.ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -07001065}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001066
jackychen6e2ce6e2015-07-13 16:26:33 -07001067int MediaCodecVideoEncoder::GetTargetFramerate() {
Peter Boström2bc68c72015-09-24 16:22:28 +02001068 return scale_ ? quality_scaler_.GetTargetFramerate() : -1;
jackychen6e2ce6e2015-07-13 16:26:33 -07001069}
1070
perkj30e91822015-11-20 01:31:25 -08001071MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory()
1072 : egl_context_ (nullptr) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001073 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1074 ScopedLocalRefFrame local_ref_frame(jni);
1075 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001076 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001077
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001078 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
1079 j_encoder_class,
1080 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
1081 CHECK_EXCEPTION(jni);
1082 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001083 ALOGD << "VP8 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001084 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
1085 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1086 }
1087
Alex Glaznevad948c42015-11-18 13:06:42 -08001088 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
1089 j_encoder_class,
1090 GetStaticMethodID(jni, j_encoder_class, "isVp9HwSupported", "()Z"));
1091 CHECK_EXCEPTION(jni);
1092 if (is_vp9_hw_supported) {
1093 ALOGD << "VP9 HW Encoder supported.";
1094 supported_codecs_.push_back(VideoCodec(kVideoCodecVP9, "VP9",
1095 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1096 }
1097
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001098 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
1099 j_encoder_class,
1100 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
1101 CHECK_EXCEPTION(jni);
1102 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001103 ALOGD << "H.264 HW Encoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001104 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
1105 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
1106 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001107}
1108
1109MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
1110
perkj30e91822015-11-20 01:31:25 -08001111void MediaCodecVideoEncoderFactory::SetEGLContext(
1112 JNIEnv* jni, jobject render_egl_context) {
1113 ALOGD << "MediaCodecVideoEncoderFactory::SetEGLContext";
1114 if (egl_context_) {
1115 jni->DeleteGlobalRef(egl_context_);
1116 egl_context_ = NULL;
1117 }
1118 if (!IsNull(jni, render_egl_context)) {
1119 egl_context_ = jni->NewGlobalRef(render_egl_context);
1120 if (CheckException(jni)) {
1121 ALOGE << "error calling NewGlobalRef for EGL Context.";
1122 egl_context_ = NULL;
1123 } else {
1124 jclass j_egl_context_class =
perkj40455d62015-12-02 01:07:18 -08001125 FindClass(jni, "org/webrtc/EglBase$Context");
perkj30e91822015-11-20 01:31:25 -08001126 if (!jni->IsInstanceOf(egl_context_, j_egl_context_class)) {
1127 ALOGE << "Wrong EGL Context.";
1128 jni->DeleteGlobalRef(egl_context_);
1129 egl_context_ = NULL;
1130 }
1131 }
1132 }
1133 if (egl_context_ == NULL) {
1134 ALOGW << "NULL VideoDecoder EGL context - HW surface encoding is disabled.";
1135 }
1136}
1137
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001138webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001139 VideoCodecType type) {
1140 if (supported_codecs_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -08001141 ALOGW << "No HW video encoder for type " << (int)type;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001142 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001143 }
1144 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
1145 it != supported_codecs_.end(); ++it) {
1146 if (it->type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001147 ALOGD << "Create HW video encoder for type " << (int)type <<
1148 " (" << it->name << ").";
perkj30e91822015-11-20 01:31:25 -08001149 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type,
1150 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001151 }
1152 }
Alex Glaznevad948c42015-11-18 13:06:42 -08001153 ALOGW << "Can not find HW video encoder for type " << (int)type;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +00001154 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001155}
1156
1157const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
1158MediaCodecVideoEncoderFactory::codecs() const {
1159 return supported_codecs_;
1160}
1161
1162void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
1163 webrtc::VideoEncoder* encoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -07001164 ALOGD << "Destroy video encoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001165 delete encoder;
1166}
1167
1168} // namespace webrtc_jni
1169