blob: fd496f09a0f808f5948904c8d2792262c9799973 [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"
32#include "webrtc/base/bind.h"
33#include "webrtc/base/checks.h"
34#include "webrtc/base/logging.h"
35#include "webrtc/base/thread.h"
36#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
jackychen61b4d512015-04-21 15:30:11 -070037#include "webrtc/modules/video_coding/utility/include/quality_scaler.h"
jackychen98d8cf52015-05-21 11:12:02 -070038#include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000039#include "webrtc/system_wrappers/interface/logcat_trace_context.h"
40#include "third_party/libyuv/include/libyuv/convert.h"
41#include "third_party/libyuv/include/libyuv/convert_from.h"
42#include "third_party/libyuv/include/libyuv/video_common.h"
43
44using rtc::Bind;
45using rtc::Thread;
46using rtc::ThreadManager;
47using rtc::scoped_ptr;
48
49using webrtc::CodecSpecificInfo;
50using webrtc::EncodedImage;
51using webrtc::I420VideoFrame;
52using webrtc::RTPFragmentationHeader;
53using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000054using webrtc::VideoCodecType;
55using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000056using webrtc::kVideoCodecVP8;
57
58namespace webrtc_jni {
59
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000060// H.264 start code length.
61#define H264_SC_LENGTH 4
62// Maximum allowed NALUs in one output frame.
63#define MAX_NALUS_PERFRAME 32
64// Maximum supported HW video encoder resolution.
65#define MAX_VIDEO_WIDTH 1280
66#define MAX_VIDEO_HEIGHT 1280
67// Maximum supported HW video encoder fps.
68#define MAX_VIDEO_FPS 30
69
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000070// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
71// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
72// HW-backed video encode. This C++ class is implemented as a very thin shim,
73// delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder.
74// MediaCodecVideoEncoder is created, operated, and destroyed on a single
75// thread, currently the libjingle Worker thread.
76class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
77 public rtc::MessageHandler {
78 public:
79 virtual ~MediaCodecVideoEncoder();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000080 explicit MediaCodecVideoEncoder(JNIEnv* jni, VideoCodecType codecType);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000081
82 // webrtc::VideoEncoder implementation. Everything trampolines to
83 // |codec_thread_| for execution.
84 int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
85 int32_t /* number_of_cores */,
86 size_t /* max_payload_size */) override;
87 int32_t Encode(
88 const webrtc::I420VideoFrame& input_image,
89 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
90 const std::vector<webrtc::VideoFrameType>* frame_types) override;
91 int32_t RegisterEncodeCompleteCallback(
92 webrtc::EncodedImageCallback* callback) override;
93 int32_t Release() override;
94 int32_t SetChannelParameters(uint32_t /* packet_loss */,
95 int64_t /* rtt */) override;
96 int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;
97
98 // rtc::MessageHandler implementation.
99 void OnMessage(rtc::Message* msg) override;
100
jackychen61b4d512015-04-21 15:30:11 -0700101 void OnDroppedFrame() override;
102
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000103 private:
104 // CHECK-fail if not running on |codec_thread_|.
105 void CheckOnCodecThread();
106
107 // Release() and InitEncode() in an attempt to restore the codec to an
108 // operable state. Necessary after all manner of OMX-layer errors.
109 void ResetCodec();
110
111 // Implementation of webrtc::VideoEncoder methods above, all running on the
112 // codec thread exclusively.
113 //
114 // If width==0 then this is assumed to be a re-initialization and the
115 // previously-current values are reused instead of the passed parameters
116 // (makes it easier to reason about thread-safety).
117 int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps);
118 int32_t EncodeOnCodecThread(
119 const webrtc::I420VideoFrame& input_image,
120 const std::vector<webrtc::VideoFrameType>* frame_types);
121 int32_t RegisterEncodeCompleteCallbackOnCodecThread(
122 webrtc::EncodedImageCallback* callback);
123 int32_t ReleaseOnCodecThread();
124 int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
125
126 // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
127 int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
128 jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
129 bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info);
130 jlong GetOutputBufferInfoPresentationTimestampUs(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000131 JNIEnv* jni, jobject j_output_buffer_info);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000132
133 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
134 // true on success.
135 bool DeliverPendingOutputs(JNIEnv* jni);
136
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000137 // Search for H.264 start codes.
138 int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size);
139
140 // Type of video codec.
141 VideoCodecType codecType_;
142
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000143 // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to
144 // |codec_thread_| synchronously.
145 webrtc::EncodedImageCallback* callback_;
146
147 // State that is constant for the lifetime of this object once the ctor
148 // returns.
149 scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
150 ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_;
151 ScopedGlobalRef<jobject> j_media_codec_video_encoder_;
152 jmethodID j_init_encode_method_;
153 jmethodID j_dequeue_input_buffer_method_;
154 jmethodID j_encode_method_;
155 jmethodID j_release_method_;
156 jmethodID j_set_rates_method_;
157 jmethodID j_dequeue_output_buffer_method_;
158 jmethodID j_release_output_buffer_method_;
159 jfieldID j_color_format_field_;
160 jfieldID j_info_index_field_;
161 jfieldID j_info_buffer_field_;
162 jfieldID j_info_is_key_frame_field_;
163 jfieldID j_info_presentation_timestamp_us_field_;
164
165 // State that is valid only between InitEncode() and the next Release().
166 // Touched only on codec_thread_ so no explicit synchronization necessary.
167 int width_; // Frame width in pixels.
168 int height_; // Frame height in pixels.
169 bool inited_;
170 uint16_t picture_id_;
171 enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
172 int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
173 int last_set_fps_; // Last-requested frame rate.
174 int64_t current_timestamp_us_; // Current frame timestamps in us.
175 int frames_received_; // Number of frames received by encoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000176 int frames_encoded_; // Number of frames encoded by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000177 int frames_dropped_; // Number of frames dropped by encoder.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000178 int frames_in_queue_; // Number of frames in encoder queue.
179 int64_t start_time_ms_; // Start time for statistics.
180 int current_frames_; // Number of frames in the current statistics interval.
181 int current_bytes_; // Encoded bytes in the current statistics interval.
182 int current_encoding_time_ms_; // Overall encoding time in the current second
183 int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
184 int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
185 std::vector<int32_t> timestamps_; // Video frames timestamp queue.
186 std::vector<int64_t> render_times_ms_; // Video frames render time queue.
187 std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
188 // encoder input.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000189 int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q.
190 int64_t output_render_time_ms_; // Last output frame render time from
191 // render_times_ms_ queue.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000192 // Frame size in bytes fed to MediaCodec.
193 int yuv_size_;
194 // True only when between a callback_->Encoded() call return a positive value
195 // and the next Encode() call being ignored.
196 bool drop_next_input_frame_;
197 // Global references; must be deleted in Release().
198 std::vector<jobject> input_buffers_;
jackychen61b4d512015-04-21 15:30:11 -0700199 scoped_ptr<webrtc::QualityScaler> quality_scaler_;
jackychen61b4d512015-04-21 15:30:11 -0700200 // Dynamic resolution change, off by default.
201 bool scale_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000202};
203
204MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
205 // Call Release() to ensure no more callbacks to us after we are deleted.
206 Release();
207}
208
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000209MediaCodecVideoEncoder::MediaCodecVideoEncoder(
210 JNIEnv* jni, VideoCodecType codecType) :
211 codecType_(codecType),
212 callback_(NULL),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000213 inited_(false),
214 picture_id_(0),
215 codec_thread_(new Thread()),
jackychen61b4d512015-04-21 15:30:11 -0700216 quality_scaler_(new webrtc::QualityScaler()),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000217 j_media_codec_video_encoder_class_(
218 jni,
219 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
220 j_media_codec_video_encoder_(
221 jni,
222 jni->NewObject(*j_media_codec_video_encoder_class_,
223 GetMethodID(jni,
224 *j_media_codec_video_encoder_class_,
225 "<init>",
226 "()V"))) {
227 ScopedLocalRefFrame local_ref_frame(jni);
228 // It would be nice to avoid spinning up a new thread per MediaCodec, and
229 // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
230 // 2732 means that deadlocks abound. This class synchronously trampolines
231 // to |codec_thread_|, so if anything else can be coming to _us_ from
232 // |codec_thread_|, or from any thread holding the |_sendCritSect| described
233 // in the bug, we have a problem. For now work around that with a dedicated
234 // thread.
235 codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
236 CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
237
238 jclass j_output_buffer_info_class =
239 FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000240 j_init_encode_method_ = GetMethodID(
241 jni,
242 *j_media_codec_video_encoder_class_,
243 "initEncode",
244 "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)"
245 "[Ljava/nio/ByteBuffer;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000246 j_dequeue_input_buffer_method_ = GetMethodID(
247 jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I");
248 j_encode_method_ = GetMethodID(
249 jni, *j_media_codec_video_encoder_class_, "encode", "(ZIIJ)Z");
250 j_release_method_ =
251 GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V");
252 j_set_rates_method_ = GetMethodID(
253 jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000254 j_dequeue_output_buffer_method_ = GetMethodID(
255 jni,
256 *j_media_codec_video_encoder_class_,
257 "dequeueOutputBuffer",
258 "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000259 j_release_output_buffer_method_ = GetMethodID(
260 jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z");
261
262 j_color_format_field_ =
263 GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I");
264 j_info_index_field_ =
265 GetFieldID(jni, j_output_buffer_info_class, "index", "I");
266 j_info_buffer_field_ = GetFieldID(
267 jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;");
268 j_info_is_key_frame_field_ =
269 GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
270 j_info_presentation_timestamp_us_field_ = GetFieldID(
271 jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
272 CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
273 AllowBlockingCalls();
274}
275
276int32_t MediaCodecVideoEncoder::InitEncode(
277 const webrtc::VideoCodec* codec_settings,
278 int32_t /* number_of_cores */,
279 size_t /* max_payload_size */) {
jackychen61b4d512015-04-21 15:30:11 -0700280 const int kMinWidth = 320;
281 const int kMinHeight = 180;
jackychen98d8cf52015-05-21 11:12:02 -0700282 // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the
283 // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is
284 // always = 127. Note that in SW, QP is that of the user-level range [0, 63].
285 const int kMaxQP = 127;
286 const int kLowQpThresholdDenominator = 3;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000287 if (codec_settings == NULL) {
288 ALOGE("NULL VideoCodec instance");
289 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
290 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000291 // Factory should guard against other codecs being used with us.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000292 CHECK(codec_settings->codecType == codecType_) << "Unsupported codec " <<
293 codec_settings->codecType << " for " << codecType_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000294
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000295 ALOGD("InitEncode request");
jackychen61b4d512015-04-21 15:30:11 -0700296 scale_ = false;
jackychen98d8cf52015-05-21 11:12:02 -0700297 if (codecType_ == kVideoCodecVP8) {
298 quality_scaler_->Init(kMaxQP / kLowQpThresholdDenominator);
299 quality_scaler_->SetMinResolution(kMinWidth, kMinHeight);
300 quality_scaler_->ReportFramerate(codec_settings->maxFramerate);
jackychen61b4d512015-04-21 15:30:11 -0700301 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000302 return codec_thread_->Invoke<int32_t>(
303 Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
304 this,
305 codec_settings->width,
306 codec_settings->height,
307 codec_settings->startBitrate,
308 codec_settings->maxFramerate));
309}
310
311int32_t MediaCodecVideoEncoder::Encode(
312 const webrtc::I420VideoFrame& frame,
313 const webrtc::CodecSpecificInfo* /* codec_specific_info */,
314 const std::vector<webrtc::VideoFrameType>* frame_types) {
315 return codec_thread_->Invoke<int32_t>(Bind(
316 &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types));
317}
318
319int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback(
320 webrtc::EncodedImageCallback* callback) {
321 return codec_thread_->Invoke<int32_t>(
322 Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread,
323 this,
324 callback));
325}
326
327int32_t MediaCodecVideoEncoder::Release() {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000328 ALOGD("EncoderRelease request");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000329 return codec_thread_->Invoke<int32_t>(
330 Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this));
331}
332
333int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */,
334 int64_t /* rtt */) {
335 return WEBRTC_VIDEO_CODEC_OK;
336}
337
338int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate,
339 uint32_t frame_rate) {
jackychen98d8cf52015-05-21 11:12:02 -0700340 if (codecType_ == kVideoCodecVP8)
341 quality_scaler_->ReportFramerate(frame_rate);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000342 return codec_thread_->Invoke<int32_t>(
343 Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread,
344 this,
345 new_bit_rate,
346 frame_rate));
347}
348
349void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
350 JNIEnv* jni = AttachCurrentThreadIfNeeded();
351 ScopedLocalRefFrame local_ref_frame(jni);
352
353 // We only ever send one message to |this| directly (not through a Bind()'d
354 // functor), so expect no ID/data.
355 CHECK(!msg->message_id) << "Unexpected message!";
356 CHECK(!msg->pdata) << "Unexpected message!";
357 CheckOnCodecThread();
358 if (!inited_) {
359 return;
360 }
361
362 // It would be nice to recover from a failure here if one happened, but it's
363 // unclear how to signal such a failure to the app, so instead we stay silent
364 // about it and let the next app-called API method reveal the borkedness.
365 DeliverPendingOutputs(jni);
366 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
367}
368
369void MediaCodecVideoEncoder::CheckOnCodecThread() {
370 CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
371 << "Running on wrong thread!";
372}
373
374void MediaCodecVideoEncoder::ResetCodec() {
375 ALOGE("ResetCodec");
376 if (Release() != WEBRTC_VIDEO_CODEC_OK ||
377 codec_thread_->Invoke<int32_t>(Bind(
378 &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this,
379 width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) {
380 // TODO(fischman): wouldn't it be nice if there was a way to gracefully
381 // degrade to a SW encoder at this point? There isn't one AFAICT :(
382 // https://code.google.com/p/webrtc/issues/detail?id=2920
383 }
384}
385
386int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread(
387 int width, int height, int kbps, int fps) {
388 CheckOnCodecThread();
389 JNIEnv* jni = AttachCurrentThreadIfNeeded();
390 ScopedLocalRefFrame local_ref_frame(jni);
391
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000392 ALOGD("InitEncodeOnCodecThread Type: %d. %d x %d. Bitrate: %d kbps. Fps: %d",
393 (int)codecType_, width, height, kbps, fps);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000394 if (kbps == 0) {
395 kbps = last_set_bitrate_kbps_;
396 }
397 if (fps == 0) {
398 fps = last_set_fps_;
399 }
400
401 width_ = width;
402 height_ = height;
403 last_set_bitrate_kbps_ = kbps;
404 last_set_fps_ = fps;
405 yuv_size_ = width_ * height_ * 3 / 2;
406 frames_received_ = 0;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000407 frames_encoded_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000408 frames_dropped_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000409 frames_in_queue_ = 0;
410 current_timestamp_us_ = 0;
411 start_time_ms_ = GetCurrentTimeMs();
412 current_frames_ = 0;
413 current_bytes_ = 0;
414 current_encoding_time_ms_ = 0;
415 last_input_timestamp_ms_ = -1;
416 last_output_timestamp_ms_ = -1;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000417 output_timestamp_ = 0;
418 output_render_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000419 timestamps_.clear();
420 render_times_ms_.clear();
421 frame_rtc_times_ms_.clear();
422 drop_next_input_frame_ = false;
423 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
424 // We enforce no extra stride/padding in the format creation step.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000425 jobject j_video_codec_enum = JavaEnumFromIndex(
426 jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000427 jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
428 jni->CallObjectMethod(*j_media_codec_video_encoder_,
429 j_init_encode_method_,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000430 j_video_codec_enum,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000431 width_,
432 height_,
433 kbps,
434 fps));
435 CHECK_EXCEPTION(jni);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000436 if (IsNull(jni, input_buffers)) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000437 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000438 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000439
440 inited_ = true;
441 switch (GetIntField(jni, *j_media_codec_video_encoder_,
442 j_color_format_field_)) {
443 case COLOR_FormatYUV420Planar:
444 encoder_fourcc_ = libyuv::FOURCC_YU12;
445 break;
446 case COLOR_FormatYUV420SemiPlanar:
447 case COLOR_QCOM_FormatYUV420SemiPlanar:
448 case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m:
449 encoder_fourcc_ = libyuv::FOURCC_NV12;
450 break;
451 default:
452 LOG(LS_ERROR) << "Wrong color format.";
453 return WEBRTC_VIDEO_CODEC_ERROR;
454 }
455 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
456 CHECK(input_buffers_.empty())
457 << "Unexpected double InitEncode without Release";
458 input_buffers_.resize(num_input_buffers);
459 for (size_t i = 0; i < num_input_buffers; ++i) {
460 input_buffers_[i] =
461 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
462 int64 yuv_buffer_capacity =
463 jni->GetDirectBufferCapacity(input_buffers_[i]);
464 CHECK_EXCEPTION(jni);
465 CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
466 }
467 CHECK_EXCEPTION(jni);
468
469 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
470 return WEBRTC_VIDEO_CODEC_OK;
471}
472
473int32_t MediaCodecVideoEncoder::EncodeOnCodecThread(
474 const webrtc::I420VideoFrame& frame,
475 const std::vector<webrtc::VideoFrameType>* frame_types) {
476 CheckOnCodecThread();
477 JNIEnv* jni = AttachCurrentThreadIfNeeded();
478 ScopedLocalRefFrame local_ref_frame(jni);
479
480 if (!inited_) {
481 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
482 }
483 frames_received_++;
484 if (!DeliverPendingOutputs(jni)) {
485 ResetCodec();
486 // Continue as if everything's fine.
487 }
488
489 if (drop_next_input_frame_) {
490 ALOGV("Encoder drop frame - failed callback.");
491 drop_next_input_frame_ = false;
492 return WEBRTC_VIDEO_CODEC_OK;
493 }
494
495 CHECK(frame_types->size() == 1) << "Unexpected stream count";
jackychen61b4d512015-04-21 15:30:11 -0700496 const I420VideoFrame& input_frame =
497 (scale_ && codecType_ == kVideoCodecVP8) ?
498 quality_scaler_->GetScaledFrame(frame) : frame;
499
500 if (input_frame.width() != width_ || input_frame.height() != height_) {
501 ALOGD("Frame resolution change from %d x %d to %d x %d",
502 width_, height_, input_frame.width(), input_frame.height());
503 width_ = input_frame.width();
504 height_ = input_frame.height();
505 ResetCodec();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000506 return WEBRTC_VIDEO_CODEC_OK;
507 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000508
509 bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
510
511 // Check if we accumulated too many frames in encoder input buffers
512 // or the encoder latency exceeds 70 ms and drop frame if so.
513 if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
514 int encoder_latency_ms = last_input_timestamp_ms_ -
515 last_output_timestamp_ms_;
516 if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
517 ALOGD("Drop frame - encoder is behind by %d ms. Q size: %d",
518 encoder_latency_ms, frames_in_queue_);
519 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700520 // Report dropped frame to quality_scaler_.
521 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000522 return WEBRTC_VIDEO_CODEC_OK;
523 }
524 }
525
526 int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
527 j_dequeue_input_buffer_method_);
528 CHECK_EXCEPTION(jni);
529 if (j_input_buffer_index == -1) {
530 // Video codec falls behind - no input buffer available.
531 ALOGV("Encoder drop frame - no input buffers available");
532 frames_dropped_++;
jackychen61b4d512015-04-21 15:30:11 -0700533 // Report dropped frame to quality_scaler_.
534 OnDroppedFrame();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000535 return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
536 }
537 if (j_input_buffer_index == -2) {
538 ResetCodec();
539 return WEBRTC_VIDEO_CODEC_ERROR;
540 }
541
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000542 ALOGV("Encoder frame in # %d. TS: %lld. Q: %d",
543 frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000544
545 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
546 uint8* yuv_buffer =
547 reinterpret_cast<uint8*>(jni->GetDirectBufferAddress(j_input_buffer));
548 CHECK_EXCEPTION(jni);
549 CHECK(yuv_buffer) << "Indirect buffer??";
550 CHECK(!libyuv::ConvertFromI420(
jackychen61b4d512015-04-21 15:30:11 -0700551 input_frame.buffer(webrtc::kYPlane),
552 input_frame.stride(webrtc::kYPlane),
553 input_frame.buffer(webrtc::kUPlane),
554 input_frame.stride(webrtc::kUPlane),
555 input_frame.buffer(webrtc::kVPlane),
556 input_frame.stride(webrtc::kVPlane),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000557 yuv_buffer, width_,
558 width_, height_,
559 encoder_fourcc_))
560 << "ConvertFromI420 failed";
561 last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
562 frames_in_queue_++;
563
564 // Save input image timestamps for later output
jackychen61b4d512015-04-21 15:30:11 -0700565 timestamps_.push_back(input_frame.timestamp());
566 render_times_ms_.push_back(input_frame.render_time_ms());
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000567 frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
568
569 bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
570 j_encode_method_,
571 key_frame,
572 j_input_buffer_index,
573 yuv_size_,
574 current_timestamp_us_);
575 CHECK_EXCEPTION(jni);
576 current_timestamp_us_ += 1000000 / last_set_fps_;
577
578 if (!encode_status || !DeliverPendingOutputs(jni)) {
579 ResetCodec();
580 return WEBRTC_VIDEO_CODEC_ERROR;
581 }
582
583 return WEBRTC_VIDEO_CODEC_OK;
584}
585
586int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread(
587 webrtc::EncodedImageCallback* callback) {
588 CheckOnCodecThread();
589 JNIEnv* jni = AttachCurrentThreadIfNeeded();
590 ScopedLocalRefFrame local_ref_frame(jni);
591 callback_ = callback;
592 return WEBRTC_VIDEO_CODEC_OK;
593}
594
595int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
596 if (!inited_) {
597 return WEBRTC_VIDEO_CODEC_OK;
598 }
599 CheckOnCodecThread();
600 JNIEnv* jni = AttachCurrentThreadIfNeeded();
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000601 ALOGD("EncoderReleaseOnCodecThread: Frames received: %d. Encoded: %d. "
602 "Dropped: %d.", frames_received_, frames_encoded_, frames_dropped_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000603 ScopedLocalRefFrame local_ref_frame(jni);
604 for (size_t i = 0; i < input_buffers_.size(); ++i)
605 jni->DeleteGlobalRef(input_buffers_[i]);
606 input_buffers_.clear();
607 jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
608 CHECK_EXCEPTION(jni);
609 rtc::MessageQueueManager::Clear(this);
610 inited_ = false;
611 return WEBRTC_VIDEO_CODEC_OK;
612}
613
614int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate,
615 uint32_t frame_rate) {
616 CheckOnCodecThread();
617 if (last_set_bitrate_kbps_ == new_bit_rate &&
618 last_set_fps_ == frame_rate) {
619 return WEBRTC_VIDEO_CODEC_OK;
620 }
621 JNIEnv* jni = AttachCurrentThreadIfNeeded();
622 ScopedLocalRefFrame local_ref_frame(jni);
623 if (new_bit_rate > 0) {
624 last_set_bitrate_kbps_ = new_bit_rate;
625 }
626 if (frame_rate > 0) {
627 last_set_fps_ = frame_rate;
628 }
629 bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
630 j_set_rates_method_,
631 last_set_bitrate_kbps_,
632 last_set_fps_);
633 CHECK_EXCEPTION(jni);
634 if (!ret) {
635 ResetCodec();
636 return WEBRTC_VIDEO_CODEC_ERROR;
637 }
638 return WEBRTC_VIDEO_CODEC_OK;
639}
640
641int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
642 JNIEnv* jni,
643 jobject j_output_buffer_info) {
644 return GetIntField(jni, j_output_buffer_info, j_info_index_field_);
645}
646
647jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer(
648 JNIEnv* jni,
649 jobject j_output_buffer_info) {
650 return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_);
651}
652
653bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame(
654 JNIEnv* jni,
655 jobject j_output_buffer_info) {
656 return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_);
657}
658
659jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs(
660 JNIEnv* jni,
661 jobject j_output_buffer_info) {
662 return GetLongField(
663 jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_);
664}
665
666bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) {
667 while (true) {
668 jobject j_output_buffer_info = jni->CallObjectMethod(
669 *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
670 CHECK_EXCEPTION(jni);
671 if (IsNull(jni, j_output_buffer_info)) {
672 break;
673 }
674
675 int output_buffer_index =
676 GetOutputBufferInfoIndex(jni, j_output_buffer_info);
677 if (output_buffer_index == -1) {
678 ResetCodec();
679 return false;
680 }
681
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000682 // Get key and config frame flags.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000683 jobject j_output_buffer =
684 GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
685 bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000686
687 // Get frame timestamps from a queue - for non config frames only.
688 int64_t frame_encoding_time_ms = 0;
689 last_output_timestamp_ms_ =
690 GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
691 1000;
692 if (frames_in_queue_ > 0) {
693 output_timestamp_ = timestamps_.front();
694 timestamps_.erase(timestamps_.begin());
695 output_render_time_ms_ = render_times_ms_.front();
696 render_times_ms_.erase(render_times_ms_.begin());
697 frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front();
698 frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
699 frames_in_queue_--;
700 }
701
702 // Extract payload.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000703 size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
704 uint8* payload = reinterpret_cast<uint8_t*>(
705 jni->GetDirectBufferAddress(j_output_buffer));
706 CHECK_EXCEPTION(jni);
707
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000708 ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld."
709 " Latency: %lld. EncTime: %lld",
710 frames_encoded_, key_frame, payload_size,
711 last_output_timestamp_ms_,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000712 last_input_timestamp_ms_ - last_output_timestamp_ms_,
713 frame_encoding_time_ms);
714
jackychen98d8cf52015-05-21 11:12:02 -0700715 if (payload_size && codecType_ == kVideoCodecVP8)
716 quality_scaler_->ReportQP(webrtc::vp8::GetQP(payload));
jackychen61b4d512015-04-21 15:30:11 -0700717
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000718 // Calculate and print encoding statistics - every 3 seconds.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000719 frames_encoded_++;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000720 current_frames_++;
721 current_bytes_ += payload_size;
722 current_encoding_time_ms_ += frame_encoding_time_ms;
723 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
724 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
725 current_frames_ > 0) {
726 ALOGD("Encoder bitrate: %d, target: %d kbps, fps: %d,"
727 " encTime: %d for last %d ms",
728 current_bytes_ * 8 / statistic_time_ms,
729 last_set_bitrate_kbps_,
730 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms,
731 current_encoding_time_ms_ / current_frames_, statistic_time_ms);
732 start_time_ms_ = GetCurrentTimeMs();
733 current_frames_ = 0;
734 current_bytes_ = 0;
735 current_encoding_time_ms_ = 0;
736 }
737
738 // Callback - return encoded frame.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000739 int32_t callback_status = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000740 if (callback_) {
741 scoped_ptr<webrtc::EncodedImage> image(
742 new webrtc::EncodedImage(payload, payload_size, payload_size));
743 image->_encodedWidth = width_;
744 image->_encodedHeight = height_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000745 image->_timeStamp = output_timestamp_;
746 image->capture_time_ms_ = output_render_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000747 image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
748 image->_completeFrame = true;
749
750 webrtc::CodecSpecificInfo info;
751 memset(&info, 0, sizeof(info));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000752 info.codecType = codecType_;
753 if (codecType_ == kVideoCodecVP8) {
754 info.codecSpecific.VP8.pictureId = picture_id_;
755 info.codecSpecific.VP8.nonReference = false;
756 info.codecSpecific.VP8.simulcastIdx = 0;
757 info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx;
758 info.codecSpecific.VP8.layerSync = false;
759 info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx;
760 info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx;
761 picture_id_ = (picture_id_ + 1) & 0x7FFF;
762 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000763
764 // Generate a header describing a single fragment.
765 webrtc::RTPFragmentationHeader header;
766 memset(&header, 0, sizeof(header));
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000767 if (codecType_ == kVideoCodecVP8) {
768 header.VerifyAndAllocateFragmentationHeader(1);
769 header.fragmentationOffset[0] = 0;
770 header.fragmentationLength[0] = image->_length;
771 header.fragmentationPlType[0] = 0;
772 header.fragmentationTimeDiff[0] = 0;
773 } else if (codecType_ == kVideoCodecH264) {
774 // For H.264 search for start codes.
775 int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {};
776 int32_t scPositionsLength = 0;
777 int32_t scPosition = 0;
778 while (scPositionsLength < MAX_NALUS_PERFRAME) {
779 int32_t naluPosition = NextNaluPosition(
780 payload + scPosition, payload_size - scPosition);
781 if (naluPosition < 0) {
782 break;
783 }
784 scPosition += naluPosition;
785 scPositions[scPositionsLength++] = scPosition;
786 scPosition += H264_SC_LENGTH;
787 }
788 if (scPositionsLength == 0) {
789 ALOGE("Start code is not found!");
790 ALOGE("Data 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
791 image->_buffer[0], image->_buffer[1], image->_buffer[2],
792 image->_buffer[3], image->_buffer[4], image->_buffer[5]);
793 ResetCodec();
794 return false;
795 }
796 scPositions[scPositionsLength] = payload_size;
797 header.VerifyAndAllocateFragmentationHeader(scPositionsLength);
798 for (size_t i = 0; i < scPositionsLength; i++) {
799 header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH;
800 header.fragmentationLength[i] =
801 scPositions[i + 1] - header.fragmentationOffset[i];
802 header.fragmentationPlType[i] = 0;
803 header.fragmentationTimeDiff[i] = 0;
804 }
805 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000806
807 callback_status = callback_->Encoded(*image, &info, &header);
808 }
809
810 // Return output buffer back to the encoder.
811 bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
812 j_release_output_buffer_method_,
813 output_buffer_index);
814 CHECK_EXCEPTION(jni);
815 if (!success) {
816 ResetCodec();
817 return false;
818 }
819
820 if (callback_status > 0) {
821 drop_next_input_frame_ = true;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000822 // Theoretically could handle callback_status<0 here, but unclear what
823 // that would mean for us.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000824 }
825 }
826
827 return true;
828}
829
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000830int32_t MediaCodecVideoEncoder::NextNaluPosition(
831 uint8_t *buffer, size_t buffer_size) {
832 if (buffer_size < H264_SC_LENGTH) {
833 return -1;
834 }
835 uint8_t *head = buffer;
836 // Set end buffer pointer to 4 bytes before actual buffer end so we can
837 // access head[1], head[2] and head[3] in a loop without buffer overrun.
838 uint8_t *end = buffer + buffer_size - H264_SC_LENGTH;
839
840 while (head < end) {
841 if (head[0]) {
842 head++;
843 continue;
844 }
845 if (head[1]) { // got 00xx
846 head += 2;
847 continue;
848 }
849 if (head[2]) { // got 0000xx
850 head += 3;
851 continue;
852 }
853 if (head[3] != 0x01) { // got 000000xx
glaznev@webrtc.orgdc08a232015-03-06 23:32:20 +0000854 head++; // xx != 1, continue searching.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000855 continue;
856 }
857 return (int32_t)(head - buffer);
858 }
859 return -1;
860}
861
jackychen61b4d512015-04-21 15:30:11 -0700862void MediaCodecVideoEncoder::OnDroppedFrame() {
jackychen98d8cf52015-05-21 11:12:02 -0700863 if (codecType_ == kVideoCodecVP8)
864 quality_scaler_->ReportDroppedFrame();
jackychen61b4d512015-04-21 15:30:11 -0700865}
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000866
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000867MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() {
868 JNIEnv* jni = AttachCurrentThreadIfNeeded();
869 ScopedLocalRefFrame local_ref_frame(jni);
870 jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000871 supported_codecs_.clear();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000872
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000873 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
874 j_encoder_class,
875 GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z"));
876 CHECK_EXCEPTION(jni);
877 if (is_vp8_hw_supported) {
878 ALOGD("VP8 HW Encoder supported.");
879 supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8",
880 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
881 }
882
883 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
884 j_encoder_class,
885 GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z"));
886 CHECK_EXCEPTION(jni);
887 if (is_h264_hw_supported) {
888 ALOGD("H.264 HW Encoder supported.");
889 supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264",
890 MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS));
891 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000892}
893
894MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
895
896webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000897 VideoCodecType type) {
898 if (supported_codecs_.empty()) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000899 return NULL;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000900 }
901 for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin();
902 it != supported_codecs_.end(); ++it) {
903 if (it->type == type) {
904 ALOGD("Create HW video encoder for type %d (%s).",
905 (int)type, it->name.c_str());
906 return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type);
907 }
908 }
909 return NULL;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000910}
911
912const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>&
913MediaCodecVideoEncoderFactory::codecs() const {
914 return supported_codecs_;
915}
916
917void MediaCodecVideoEncoderFactory::DestroyVideoEncoder(
918 webrtc::VideoEncoder* encoder) {
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000919 ALOGD("Destroy video encoder.");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000920 delete encoder;
921}
922
923} // namespace webrtc_jni
924