blob: 11c8d66f20456e8ef108af41e6ed7ea966e63060 [file] [log] [blame]
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2015 The WebRTC project authors. All Rights Reserved.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +00009 */
10
magjed6d387c02015-10-14 04:02:01 -070011#include <algorithm>
kwibergd1fe2812016-04-27 06:47:29 -070012#include <memory>
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000013#include <vector>
14
kjellandera96e2d72016-02-04 23:52:28 -080015// NOTICE: androidmediadecoder_jni.h must be included before
16// androidmediacodeccommon.h to avoid build errors.
Henrik Kjellander15583c12016-02-10 10:53:12 +010017#include "webrtc/api/java/jni/androidmediadecoder_jni.h"
18
kjellandera96e2d72016-02-04 23:52:28 -080019#include "third_party/libyuv/include/libyuv/convert.h"
20#include "third_party/libyuv/include/libyuv/convert_from.h"
21#include "third_party/libyuv/include/libyuv/video_common.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010022#include "webrtc/api/java/jni/androidmediacodeccommon.h"
23#include "webrtc/api/java/jni/classreferenceholder.h"
24#include "webrtc/api/java/jni/native_handle_impl.h"
25#include "webrtc/api/java/jni/surfacetexturehelper_jni.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000026#include "webrtc/base/bind.h"
27#include "webrtc/base/checks.h"
28#include "webrtc/base/logging.h"
Magnus Jedvertbbda54e2015-09-30 16:06:37 +020029#include "webrtc/base/scoped_ref_ptr.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000030#include "webrtc/base/thread.h"
Magnus Jedvert7e319372015-10-02 15:49:38 +020031#include "webrtc/base/timeutils.h"
kjellander6f8ce062015-11-16 13:52:24 -080032#include "webrtc/common_video/include/i420_buffer_pool.h"
perkj87d58452015-11-23 01:46:27 -080033#include "webrtc/modules/video_coding/include/video_codec_interface.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010034#include "webrtc/system_wrappers/include/logcat_trace_context.h"
35#include "webrtc/system_wrappers/include/tick_util.h"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000036
37using rtc::Bind;
38using rtc::Thread;
39using rtc::ThreadManager;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000040
41using webrtc::CodecSpecificInfo;
42using webrtc::DecodedImageCallback;
43using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070044using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000045using webrtc::RTPFragmentationHeader;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000046using webrtc::TickTime;
47using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000048using webrtc::VideoCodecType;
49using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000050using webrtc::kVideoCodecVP8;
Alex Glaznev69a7fd52015-11-10 10:25:40 -080051using webrtc::kVideoCodecVP9;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000052
53namespace webrtc_jni {
54
glaznevf4decb52016-01-15 13:49:22 -080055// Logging macros.
56#define TAG_DECODER "MediaCodecVideoDecoder"
57#ifdef TRACK_BUFFER_TIMING
58#define ALOGV(...)
59 __android_log_print(ANDROID_LOG_VERBOSE, TAG_DECODER, __VA_ARGS__)
60#else
61#define ALOGV(...)
62#endif
63#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_DECODER)
64#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_DECODER)
65#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_DECODER)
66
glaznevae95ff32016-02-04 11:47:12 -080067enum { kMaxWarningLogFrames = 2 };
68
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000069class MediaCodecVideoDecoder : public webrtc::VideoDecoder,
70 public rtc::MessageHandler {
71 public:
Alex Glaznev4d2f4d12015-09-01 15:04:13 -070072 explicit MediaCodecVideoDecoder(
73 JNIEnv* jni, VideoCodecType codecType, jobject render_egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000074 virtual ~MediaCodecVideoDecoder();
75
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000076 int32_t InitDecode(const VideoCodec* codecSettings, int32_t numberOfCores)
77 override;
78
79 int32_t Decode(
80 const EncodedImage& inputImage, bool missingFrames,
81 const RTPFragmentationHeader* fragmentation,
82 const CodecSpecificInfo* codecSpecificInfo = NULL,
83 int64_t renderTimeMs = -1) override;
84
85 int32_t RegisterDecodeCompleteCallback(DecodedImageCallback* callback)
86 override;
87
88 int32_t Release() override;
89
perkj796cfaf2015-12-10 09:27:38 -080090 bool PrefersLateDecoding() const override { return true; }
91
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000092 // rtc::MessageHandler implementation.
93 void OnMessage(rtc::Message* msg) override;
94
Peter Boströmb7d9a972015-12-18 16:01:11 +010095 const char* ImplementationName() const override;
96
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000097 private:
98 // CHECK-fail if not running on |codec_thread_|.
99 void CheckOnCodecThread();
100
101 int32_t InitDecodeOnCodecThread();
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800102 int32_t ResetDecodeOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000103 int32_t ReleaseOnCodecThread();
104 int32_t DecodeOnCodecThread(const EncodedImage& inputImage);
105 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
106 // true on success.
107 bool DeliverPendingOutputs(JNIEnv* jni, int dequeue_timeout_us);
Alex Glaznev782671f2015-06-12 16:40:44 -0700108 int32_t ProcessHWErrorOnCodecThread();
glaznevae95ff32016-02-04 11:47:12 -0800109 void EnableFrameLogOnWarning();
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800110 void ResetVariables();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000111
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000112 // Type of video codec.
113 VideoCodecType codecType_;
114
kjellander60ca31b2016-01-04 10:15:53 -0800115 // Render EGL context - owned by factory, should not be allocated/destroyed
116 // by VideoDecoder.
117 jobject render_egl_context_;
118
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000119 bool key_frame_required_;
120 bool inited_;
Alex Glaznev782671f2015-06-12 16:40:44 -0700121 bool sw_fallback_required_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000122 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000123 VideoCodec codec_;
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200124 webrtc::I420BufferPool decoded_frame_pool_;
Per488e75f2015-11-19 10:43:36 +0100125 rtc::scoped_refptr<SurfaceTextureHelper> surface_texture_helper_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000126 DecodedImageCallback* callback_;
127 int frames_received_; // Number of frames received by decoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000128 int frames_decoded_; // Number of frames decoded by decoder.
glaznevae95ff32016-02-04 11:47:12 -0800129 // Number of decoded frames for which log information is displayed.
130 int frames_decoded_logged_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000131 int64_t start_time_ms_; // Start time for statistics.
132 int current_frames_; // Number of frames in the current statistics interval.
133 int current_bytes_; // Encoded bytes in the current statistics interval.
134 int current_decoding_time_ms_; // Overall decoding time in the current second
glaznevfd6706a2016-02-05 14:05:08 -0800135 int current_delay_time_ms_; // Overall delay time in the current second.
136 uint32_t max_pending_frames_; // Maximum number of pending input frames.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000137
138 // State that is constant for the lifetime of this object once the ctor
139 // returns.
kwibergd1fe2812016-04-27 06:47:29 -0700140 std::unique_ptr<Thread>
141 codec_thread_; // Thread on which to operate MediaCodec.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000142 ScopedGlobalRef<jclass> j_media_codec_video_decoder_class_;
143 ScopedGlobalRef<jobject> j_media_codec_video_decoder_;
144 jmethodID j_init_decode_method_;
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800145 jmethodID j_reset_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000146 jmethodID j_release_method_;
147 jmethodID j_dequeue_input_buffer_method_;
148 jmethodID j_queue_input_buffer_method_;
Per488e75f2015-11-19 10:43:36 +0100149 jmethodID j_dequeue_byte_buffer_method_;
150 jmethodID j_dequeue_texture_buffer_method_;
magjed44bf6f52015-10-03 02:08:00 -0700151 jmethodID j_return_decoded_byte_buffer_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000152 // MediaCodecVideoDecoder fields.
153 jfieldID j_input_buffers_field_;
154 jfieldID j_output_buffers_field_;
155 jfieldID j_color_format_field_;
156 jfieldID j_width_field_;
157 jfieldID j_height_field_;
158 jfieldID j_stride_field_;
159 jfieldID j_slice_height_field_;
magjed44bf6f52015-10-03 02:08:00 -0700160 // MediaCodecVideoDecoder.DecodedTextureBuffer fields.
Per488e75f2015-11-19 10:43:36 +0100161 jfieldID j_texture_id_field_;
162 jfieldID j_transform_matrix_field_;
glaznev94291482016-02-01 13:17:18 -0800163 jfieldID j_texture_presentation_timestamp_ms_field_;
Per488e75f2015-11-19 10:43:36 +0100164 jfieldID j_texture_timestamp_ms_field_;
165 jfieldID j_texture_ntp_timestamp_ms_field_;
166 jfieldID j_texture_decode_time_ms_field_;
167 jfieldID j_texture_frame_delay_ms_field_;
168 // MediaCodecVideoDecoder.DecodedOutputBuffer fields.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000169 jfieldID j_info_index_field_;
170 jfieldID j_info_offset_field_;
171 jfieldID j_info_size_field_;
glaznev94291482016-02-01 13:17:18 -0800172 jfieldID j_presentation_timestamp_ms_field_;
173 jfieldID j_timestamp_ms_field_;
174 jfieldID j_ntp_timestamp_ms_field_;
Per488e75f2015-11-19 10:43:36 +0100175 jfieldID j_byte_buffer_decode_time_ms_field_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000176
177 // Global references; must be deleted in Release().
178 std::vector<jobject> input_buffers_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000179};
180
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000181MediaCodecVideoDecoder::MediaCodecVideoDecoder(
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700182 JNIEnv* jni, VideoCodecType codecType, jobject render_egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000183 codecType_(codecType),
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700184 render_egl_context_(render_egl_context),
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000185 key_frame_required_(true),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000186 inited_(false),
Alex Glaznev782671f2015-06-12 16:40:44 -0700187 sw_fallback_required_(false),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000188 codec_thread_(new Thread()),
189 j_media_codec_video_decoder_class_(
190 jni,
191 FindClass(jni, "org/webrtc/MediaCodecVideoDecoder")),
192 j_media_codec_video_decoder_(
193 jni,
194 jni->NewObject(*j_media_codec_video_decoder_class_,
195 GetMethodID(jni,
196 *j_media_codec_video_decoder_class_,
197 "<init>",
198 "()V"))) {
199 ScopedLocalRefFrame local_ref_frame(jni);
200 codec_thread_->SetName("MediaCodecVideoDecoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700201 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoDecoder";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000202
203 j_init_decode_method_ = GetMethodID(
204 jni, *j_media_codec_video_decoder_class_, "initDecode",
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000205 "(Lorg/webrtc/MediaCodecVideoDecoder$VideoCodecType;"
Per488e75f2015-11-19 10:43:36 +0100206 "IILorg/webrtc/SurfaceTextureHelper;)Z");
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800207 j_reset_method_ =
208 GetMethodID(jni, *j_media_codec_video_decoder_class_, "reset", "(II)V");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000209 j_release_method_ =
210 GetMethodID(jni, *j_media_codec_video_decoder_class_, "release", "()V");
211 j_dequeue_input_buffer_method_ = GetMethodID(
212 jni, *j_media_codec_video_decoder_class_, "dequeueInputBuffer", "()I");
213 j_queue_input_buffer_method_ = GetMethodID(
Per488e75f2015-11-19 10:43:36 +0100214 jni, *j_media_codec_video_decoder_class_, "queueInputBuffer", "(IIJJJ)Z");
215 j_dequeue_byte_buffer_method_ = GetMethodID(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000216 jni, *j_media_codec_video_decoder_class_, "dequeueOutputBuffer",
Per488e75f2015-11-19 10:43:36 +0100217 "(I)Lorg/webrtc/MediaCodecVideoDecoder$DecodedOutputBuffer;");
218 j_dequeue_texture_buffer_method_ = GetMethodID(
219 jni, *j_media_codec_video_decoder_class_, "dequeueTextureBuffer",
220 "(I)Lorg/webrtc/MediaCodecVideoDecoder$DecodedTextureBuffer;");
magjed44bf6f52015-10-03 02:08:00 -0700221 j_return_decoded_byte_buffer_method_ =
222 GetMethodID(jni, *j_media_codec_video_decoder_class_,
Per488e75f2015-11-19 10:43:36 +0100223 "returnDecodedOutputBuffer", "(I)V");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000224
225 j_input_buffers_field_ = GetFieldID(
226 jni, *j_media_codec_video_decoder_class_,
227 "inputBuffers", "[Ljava/nio/ByteBuffer;");
228 j_output_buffers_field_ = GetFieldID(
229 jni, *j_media_codec_video_decoder_class_,
230 "outputBuffers", "[Ljava/nio/ByteBuffer;");
231 j_color_format_field_ = GetFieldID(
232 jni, *j_media_codec_video_decoder_class_, "colorFormat", "I");
233 j_width_field_ = GetFieldID(
234 jni, *j_media_codec_video_decoder_class_, "width", "I");
235 j_height_field_ = GetFieldID(
236 jni, *j_media_codec_video_decoder_class_, "height", "I");
237 j_stride_field_ = GetFieldID(
238 jni, *j_media_codec_video_decoder_class_, "stride", "I");
239 j_slice_height_field_ = GetFieldID(
240 jni, *j_media_codec_video_decoder_class_, "sliceHeight", "I");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000241
Per488e75f2015-11-19 10:43:36 +0100242 jclass j_decoded_texture_buffer_class = FindClass(jni,
magjed44bf6f52015-10-03 02:08:00 -0700243 "org/webrtc/MediaCodecVideoDecoder$DecodedTextureBuffer");
Per488e75f2015-11-19 10:43:36 +0100244 j_texture_id_field_ = GetFieldID(
245 jni, j_decoded_texture_buffer_class, "textureID", "I");
246 j_transform_matrix_field_ = GetFieldID(
247 jni, j_decoded_texture_buffer_class, "transformMatrix", "[F");
glaznev94291482016-02-01 13:17:18 -0800248 j_texture_presentation_timestamp_ms_field_ = GetFieldID(
249 jni, j_decoded_texture_buffer_class, "presentationTimeStampMs", "J");
Per488e75f2015-11-19 10:43:36 +0100250 j_texture_timestamp_ms_field_ = GetFieldID(
251 jni, j_decoded_texture_buffer_class, "timeStampMs", "J");
252 j_texture_ntp_timestamp_ms_field_ = GetFieldID(
253 jni, j_decoded_texture_buffer_class, "ntpTimeStampMs", "J");
254 j_texture_decode_time_ms_field_ = GetFieldID(
255 jni, j_decoded_texture_buffer_class, "decodeTimeMs", "J");
256 j_texture_frame_delay_ms_field_ = GetFieldID(
257 jni, j_decoded_texture_buffer_class, "frameDelayMs", "J");
magjed44bf6f52015-10-03 02:08:00 -0700258
Per488e75f2015-11-19 10:43:36 +0100259 jclass j_decoded_output_buffer_class = FindClass(jni,
260 "org/webrtc/MediaCodecVideoDecoder$DecodedOutputBuffer");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000261 j_info_index_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100262 jni, j_decoded_output_buffer_class, "index", "I");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000263 j_info_offset_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100264 jni, j_decoded_output_buffer_class, "offset", "I");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000265 j_info_size_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100266 jni, j_decoded_output_buffer_class, "size", "I");
glaznev94291482016-02-01 13:17:18 -0800267 j_presentation_timestamp_ms_field_ = GetFieldID(
268 jni, j_decoded_output_buffer_class, "presentationTimeStampMs", "J");
269 j_timestamp_ms_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100270 jni, j_decoded_output_buffer_class, "timeStampMs", "J");
glaznev94291482016-02-01 13:17:18 -0800271 j_ntp_timestamp_ms_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100272 jni, j_decoded_output_buffer_class, "ntpTimeStampMs", "J");
273 j_byte_buffer_decode_time_ms_field_ = GetFieldID(
274 jni, j_decoded_output_buffer_class, "decodeTimeMs", "J");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000275
276 CHECK_EXCEPTION(jni) << "MediaCodecVideoDecoder ctor failed";
Magnus Jedvert207370f2015-09-16 12:32:21 +0200277 use_surface_ = (render_egl_context_ != NULL);
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700278 ALOGD << "MediaCodecVideoDecoder ctor. Use surface: " << use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000279 memset(&codec_, 0, sizeof(codec_));
280 AllowBlockingCalls();
281}
282
283MediaCodecVideoDecoder::~MediaCodecVideoDecoder() {
284 // Call Release() to ensure no more callbacks to us after we are deleted.
285 Release();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000286}
287
288int32_t MediaCodecVideoDecoder::InitDecode(const VideoCodec* inst,
289 int32_t numberOfCores) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700290 ALOGD << "InitDecode.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000291 if (inst == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700292 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000293 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
294 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000295 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700296 RTC_CHECK(inst->codecType == codecType_)
297 << "Unsupported codec " << inst->codecType << " for " << codecType_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000298
Alex Glaznev782671f2015-06-12 16:40:44 -0700299 if (sw_fallback_required_) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700300 ALOGE << "InitDecode() - fallback to SW decoder";
Alex Glaznev782671f2015-06-12 16:40:44 -0700301 return WEBRTC_VIDEO_CODEC_OK;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000302 }
303 // Save VideoCodec instance for later.
304 if (&codec_ != inst) {
305 codec_ = *inst;
306 }
glazneve55c42c2015-10-28 10:30:32 -0700307 // If maxFramerate is not set then assume 30 fps.
308 codec_.maxFramerate = (codec_.maxFramerate >= 1) ? codec_.maxFramerate : 30;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000309
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000310 // Call Java init.
311 return codec_thread_->Invoke<int32_t>(
312 Bind(&MediaCodecVideoDecoder::InitDecodeOnCodecThread, this));
313}
314
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800315void MediaCodecVideoDecoder::ResetVariables() {
316 CheckOnCodecThread();
317
318 key_frame_required_ = true;
319 frames_received_ = 0;
320 frames_decoded_ = 0;
321 frames_decoded_logged_ = kMaxDecodedLogFrames;
322 start_time_ms_ = GetCurrentTimeMs();
323 current_frames_ = 0;
324 current_bytes_ = 0;
325 current_decoding_time_ms_ = 0;
326 current_delay_time_ms_ = 0;
327}
328
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000329int32_t MediaCodecVideoDecoder::InitDecodeOnCodecThread() {
330 CheckOnCodecThread();
331 JNIEnv* jni = AttachCurrentThreadIfNeeded();
332 ScopedLocalRefFrame local_ref_frame(jni);
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700333 ALOGD << "InitDecodeOnCodecThread Type: " << (int)codecType_ << ". "
334 << codec_.width << " x " << codec_.height << ". Fps: " <<
335 (int)codec_.maxFramerate;
Alex Glaznev782671f2015-06-12 16:40:44 -0700336
337 // Release previous codec first if it was allocated before.
338 int ret_val = ReleaseOnCodecThread();
339 if (ret_val < 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700340 ALOGE << "Release failure: " << ret_val << " - fallback to SW codec";
Alex Glaznev782671f2015-06-12 16:40:44 -0700341 sw_fallback_required_ = true;
342 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000343 }
344
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800345 ResetVariables();
Alex Glaznev782671f2015-06-12 16:40:44 -0700346
Per488e75f2015-11-19 10:43:36 +0100347 if (use_surface_) {
magjed2aa84262016-05-09 08:28:45 -0700348 surface_texture_helper_ = SurfaceTextureHelper::create(
magjed82b750b2016-03-31 00:54:15 -0700349 jni, "Decoder SurfaceTextureHelper", render_egl_context_);
magjed2aa84262016-05-09 08:28:45 -0700350 if (!surface_texture_helper_) {
351 ALOGE << "Couldn't create SurfaceTextureHelper - fallback to SW codec";
352 sw_fallback_required_ = true;
353 return WEBRTC_VIDEO_CODEC_ERROR;
354 }
Per488e75f2015-11-19 10:43:36 +0100355 }
356
Perec2922f2016-01-27 15:25:46 +0100357 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000358 jni, "MediaCodecVideoDecoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000359 bool success = jni->CallBooleanMethod(
360 *j_media_codec_video_decoder_,
361 j_init_decode_method_,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000362 j_video_codec_enum,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000363 codec_.width,
364 codec_.height,
magjed0dc23162016-03-14 03:59:38 -0700365 use_surface_ ? surface_texture_helper_->GetJavaSurfaceTextureHelper()
366 : nullptr);
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800367
Alex Glaznev782671f2015-06-12 16:40:44 -0700368 if (CheckException(jni) || !success) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700369 ALOGE << "Codec initialization error - fallback to SW codec.";
Alex Glaznev782671f2015-06-12 16:40:44 -0700370 sw_fallback_required_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000371 return WEBRTC_VIDEO_CODEC_ERROR;
372 }
373 inited_ = true;
374
glaznev@webrtc.orga4623d22015-02-25 00:02:50 +0000375 switch (codecType_) {
376 case kVideoCodecVP8:
377 max_pending_frames_ = kMaxPendingFramesVp8;
378 break;
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800379 case kVideoCodecVP9:
380 max_pending_frames_ = kMaxPendingFramesVp9;
381 break;
glaznev@webrtc.orga4623d22015-02-25 00:02:50 +0000382 case kVideoCodecH264:
383 max_pending_frames_ = kMaxPendingFramesH264;
384 break;
385 default:
386 max_pending_frames_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000387 }
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800388 ALOGD << "Maximum amount of pending frames: " << max_pending_frames_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000389
390 jobjectArray input_buffers = (jobjectArray)GetObjectField(
391 jni, *j_media_codec_video_decoder_, j_input_buffers_field_);
392 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
393 input_buffers_.resize(num_input_buffers);
394 for (size_t i = 0; i < num_input_buffers; ++i) {
395 input_buffers_[i] =
396 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
Alex Glaznev782671f2015-06-12 16:40:44 -0700397 if (CheckException(jni)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700398 ALOGE << "NewGlobalRef error - fallback to SW codec.";
Alex Glaznev782671f2015-06-12 16:40:44 -0700399 sw_fallback_required_ = true;
400 return WEBRTC_VIDEO_CODEC_ERROR;
401 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000402 }
403
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000404 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
405
406 return WEBRTC_VIDEO_CODEC_OK;
407}
408
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800409int32_t MediaCodecVideoDecoder::ResetDecodeOnCodecThread() {
410 CheckOnCodecThread();
411 JNIEnv* jni = AttachCurrentThreadIfNeeded();
412 ScopedLocalRefFrame local_ref_frame(jni);
413 ALOGD << "ResetDecodeOnCodecThread Type: " << (int)codecType_ << ". "
414 << codec_.width << " x " << codec_.height;
415 ALOGD << " Frames received: " << frames_received_ <<
416 ". Frames decoded: " << frames_decoded_;
417
418 inited_ = false;
419 rtc::MessageQueueManager::Clear(this);
420 ResetVariables();
421
422 jni->CallVoidMethod(
423 *j_media_codec_video_decoder_,
424 j_reset_method_,
425 codec_.width,
426 codec_.height);
427
428 if (CheckException(jni)) {
429 ALOGE << "Soft reset error - fallback to SW codec.";
430 sw_fallback_required_ = true;
431 return WEBRTC_VIDEO_CODEC_ERROR;
432 }
433 inited_ = true;
434
435 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
436
437 return WEBRTC_VIDEO_CODEC_OK;
438}
439
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000440int32_t MediaCodecVideoDecoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700441 ALOGD << "DecoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000442 return codec_thread_->Invoke<int32_t>(
443 Bind(&MediaCodecVideoDecoder::ReleaseOnCodecThread, this));
444}
445
446int32_t MediaCodecVideoDecoder::ReleaseOnCodecThread() {
447 if (!inited_) {
448 return WEBRTC_VIDEO_CODEC_OK;
449 }
450 CheckOnCodecThread();
451 JNIEnv* jni = AttachCurrentThreadIfNeeded();
glazneve55c42c2015-10-28 10:30:32 -0700452 ALOGD << "DecoderReleaseOnCodecThread: Frames received: " <<
453 frames_received_ << ". Frames decoded: " << frames_decoded_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000454 ScopedLocalRefFrame local_ref_frame(jni);
455 for (size_t i = 0; i < input_buffers_.size(); i++) {
456 jni->DeleteGlobalRef(input_buffers_[i]);
457 }
458 input_buffers_.clear();
459 jni->CallVoidMethod(*j_media_codec_video_decoder_, j_release_method_);
Per488e75f2015-11-19 10:43:36 +0100460 surface_texture_helper_ = nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000461 inited_ = false;
Alex Glaznev782671f2015-06-12 16:40:44 -0700462 rtc::MessageQueueManager::Clear(this);
463 if (CheckException(jni)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700464 ALOGE << "Decoder release exception";
Alex Glaznev782671f2015-06-12 16:40:44 -0700465 return WEBRTC_VIDEO_CODEC_ERROR;
466 }
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700467 ALOGD << "DecoderReleaseOnCodecThread done";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000468 return WEBRTC_VIDEO_CODEC_OK;
469}
470
471void MediaCodecVideoDecoder::CheckOnCodecThread() {
kwiberg9708e9c2016-03-29 10:17:42 -0700472 RTC_CHECK(codec_thread_.get() == ThreadManager::Instance()->CurrentThread())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000473 << "Running on wrong thread!";
474}
475
glaznevae95ff32016-02-04 11:47:12 -0800476void MediaCodecVideoDecoder::EnableFrameLogOnWarning() {
477 // Log next 2 output frames.
478 frames_decoded_logged_ = std::max(
479 frames_decoded_logged_, frames_decoded_ + kMaxWarningLogFrames);
480}
481
Alex Glaznev782671f2015-06-12 16:40:44 -0700482int32_t MediaCodecVideoDecoder::ProcessHWErrorOnCodecThread() {
483 CheckOnCodecThread();
484 int ret_val = ReleaseOnCodecThread();
485 if (ret_val < 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700486 ALOGE << "ProcessHWError: Release failure";
Alex Glaznev782671f2015-06-12 16:40:44 -0700487 }
488 if (codecType_ == kVideoCodecH264) {
489 // For now there is no SW H.264 which can be used as fallback codec.
490 // So try to restart hw codec for now.
491 ret_val = InitDecodeOnCodecThread();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700492 ALOGE << "Reset H.264 codec done. Status: " << ret_val;
Alex Glaznev782671f2015-06-12 16:40:44 -0700493 if (ret_val == WEBRTC_VIDEO_CODEC_OK) {
494 // H.264 codec was succesfully reset - return regular error code.
495 return WEBRTC_VIDEO_CODEC_ERROR;
496 } else {
497 // Fail to restart H.264 codec - return error code which should stop the
498 // call.
499 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
500 }
501 } else {
502 sw_fallback_required_ = true;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700503 ALOGE << "Return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE";
Alex Glaznev782671f2015-06-12 16:40:44 -0700504 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
505 }
506}
507
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000508int32_t MediaCodecVideoDecoder::Decode(
509 const EncodedImage& inputImage,
510 bool missingFrames,
511 const RTPFragmentationHeader* fragmentation,
512 const CodecSpecificInfo* codecSpecificInfo,
513 int64_t renderTimeMs) {
Alex Glaznev782671f2015-06-12 16:40:44 -0700514 if (sw_fallback_required_) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700515 ALOGE << "Decode() - fallback to SW codec";
Alex Glaznev782671f2015-06-12 16:40:44 -0700516 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000517 }
518 if (callback_ == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700519 ALOGE << "Decode() - callback_ is NULL";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000520 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
521 }
522 if (inputImage._buffer == NULL && inputImage._length > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700523 ALOGE << "Decode() - inputImage is incorrect";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000524 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
525 }
Alex Glaznev782671f2015-06-12 16:40:44 -0700526 if (!inited_) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700527 ALOGE << "Decode() - decoder is not initialized";
Alex Glaznev782671f2015-06-12 16:40:44 -0700528 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
529 }
530
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000531 // Check if encoded frame dimension has changed.
532 if ((inputImage._encodedWidth * inputImage._encodedHeight > 0) &&
533 (inputImage._encodedWidth != codec_.width ||
534 inputImage._encodedHeight != codec_.height)) {
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800535 ALOGW << "Input resolution changed from " <<
536 codec_.width << " x " << codec_.height << " to " <<
537 inputImage._encodedWidth << " x " << inputImage._encodedHeight;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000538 codec_.width = inputImage._encodedWidth;
539 codec_.height = inputImage._encodedHeight;
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800540 int32_t ret;
Alex Glaznev79299af2016-04-12 16:39:39 -0700541 if (use_surface_ &&
542 (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecH264)) {
543 // Soft codec reset - only for surface decoding.
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800544 ret = codec_thread_->Invoke<int32_t>(Bind(
545 &MediaCodecVideoDecoder::ResetDecodeOnCodecThread, this));
546 } else {
547 // Hard codec reset.
548 ret = InitDecode(&codec_, 1);
549 }
Alex Glaznev782671f2015-06-12 16:40:44 -0700550 if (ret < 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700551 ALOGE << "InitDecode failure: " << ret << " - fallback to SW codec";
Alex Glaznev782671f2015-06-12 16:40:44 -0700552 sw_fallback_required_ = true;
553 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
554 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000555 }
556
557 // Always start with a complete key frame.
558 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200559 if (inputImage._frameType != webrtc::kVideoFrameKey) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700560 ALOGE << "Decode() - key frame is required";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000561 return WEBRTC_VIDEO_CODEC_ERROR;
562 }
563 if (!inputImage._completeFrame) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700564 ALOGE << "Decode() - complete frame is required";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000565 return WEBRTC_VIDEO_CODEC_ERROR;
566 }
567 key_frame_required_ = false;
568 }
569 if (inputImage._length == 0) {
570 return WEBRTC_VIDEO_CODEC_ERROR;
571 }
572
573 return codec_thread_->Invoke<int32_t>(Bind(
574 &MediaCodecVideoDecoder::DecodeOnCodecThread, this, inputImage));
575}
576
577int32_t MediaCodecVideoDecoder::DecodeOnCodecThread(
578 const EncodedImage& inputImage) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000579 CheckOnCodecThread();
580 JNIEnv* jni = AttachCurrentThreadIfNeeded();
581 ScopedLocalRefFrame local_ref_frame(jni);
582
583 // Try to drain the decoder and wait until output is not too
584 // much behind the input.
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800585 if (codecType_ == kVideoCodecH264 &&
586 frames_received_ > frames_decoded_ + max_pending_frames_) {
587 // Print warning for H.264 only - for VP8/VP9 one frame delay is ok.
glaznevae95ff32016-02-04 11:47:12 -0800588 ALOGW << "Decoder is too far behind. Try to drain. Received: " <<
589 frames_received_ << ". Decoded: " << frames_decoded_;
590 EnableFrameLogOnWarning();
591 }
Per488e75f2015-11-19 10:43:36 +0100592 const int64 drain_start = GetCurrentTimeMs();
593 while ((frames_received_ > frames_decoded_ + max_pending_frames_) &&
594 (GetCurrentTimeMs() - drain_start) < kMediaCodecTimeoutMs) {
Per488e75f2015-11-19 10:43:36 +0100595 if (!DeliverPendingOutputs(jni, kMediaCodecPollMs)) {
glazneve55c42c2015-10-28 10:30:32 -0700596 ALOGE << "DeliverPendingOutputs error. Frames received: " <<
597 frames_received_ << ". Frames decoded: " << frames_decoded_;
Alex Glaznev782671f2015-06-12 16:40:44 -0700598 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000599 }
Per488e75f2015-11-19 10:43:36 +0100600 }
601 if (frames_received_ > frames_decoded_ + max_pending_frames_) {
602 ALOGE << "Output buffer dequeue timeout. Frames received: " <<
603 frames_received_ << ". Frames decoded: " << frames_decoded_;
604 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000605 }
606
607 // Get input buffer.
glaznevae95ff32016-02-04 11:47:12 -0800608 int j_input_buffer_index = jni->CallIntMethod(
609 *j_media_codec_video_decoder_, j_dequeue_input_buffer_method_);
Alex Glaznev782671f2015-06-12 16:40:44 -0700610 if (CheckException(jni) || j_input_buffer_index < 0) {
glaznevae95ff32016-02-04 11:47:12 -0800611 ALOGE << "dequeueInputBuffer error: " << j_input_buffer_index <<
612 ". Retry DeliverPendingOutputs.";
613 EnableFrameLogOnWarning();
614 // Try to drain the decoder.
615 if (!DeliverPendingOutputs(jni, kMediaCodecPollMs)) {
616 ALOGE << "DeliverPendingOutputs error. Frames received: " <<
617 frames_received_ << ". Frames decoded: " << frames_decoded_;
618 return ProcessHWErrorOnCodecThread();
619 }
620 // Try dequeue input buffer one last time.
621 j_input_buffer_index = jni->CallIntMethod(
622 *j_media_codec_video_decoder_, j_dequeue_input_buffer_method_);
623 if (CheckException(jni) || j_input_buffer_index < 0) {
624 ALOGE << "dequeueInputBuffer critical error: " << j_input_buffer_index;
625 return ProcessHWErrorOnCodecThread();
626 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000627 }
628
629 // Copy encoded data to Java ByteBuffer.
630 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200631 uint8_t* buffer =
632 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
henrikg91d6ede2015-09-17 00:24:34 -0700633 RTC_CHECK(buffer) << "Indirect buffer??";
Peter Boström0c4e06b2015-10-07 12:23:21 +0200634 int64_t buffer_capacity = jni->GetDirectBufferCapacity(j_input_buffer);
Alex Glaznev782671f2015-06-12 16:40:44 -0700635 if (CheckException(jni) || buffer_capacity < inputImage._length) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700636 ALOGE << "Input frame size "<< inputImage._length <<
637 " is bigger than buffer size " << buffer_capacity;
Alex Glaznev782671f2015-06-12 16:40:44 -0700638 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000639 }
glaznevae95ff32016-02-04 11:47:12 -0800640 jlong presentation_timestamp_us = static_cast<jlong>(
641 static_cast<int64_t>(frames_received_) * 1000000 / codec_.maxFramerate);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000642 memcpy(buffer, inputImage._buffer, inputImage._length);
643
glaznevae95ff32016-02-04 11:47:12 -0800644 if (frames_decoded_ < frames_decoded_logged_) {
glaznev94291482016-02-01 13:17:18 -0800645 ALOGD << "Decoder frame in # " << frames_received_ <<
646 ". Type: " << inputImage._frameType <<
647 ". Buffer # " << j_input_buffer_index <<
glaznevae95ff32016-02-04 11:47:12 -0800648 ". TS: " << presentation_timestamp_us / 1000 <<
glaznev94291482016-02-01 13:17:18 -0800649 ". Size: " << inputImage._length;
650 }
651
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000652 // Save input image timestamps for later output.
653 frames_received_++;
654 current_bytes_ += inputImage._length;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000655
656 // Feed input to decoder.
Per488e75f2015-11-19 10:43:36 +0100657 bool success = jni->CallBooleanMethod(
658 *j_media_codec_video_decoder_,
659 j_queue_input_buffer_method_,
660 j_input_buffer_index,
661 inputImage._length,
662 presentation_timestamp_us,
663 static_cast<int64_t> (inputImage._timeStamp),
664 inputImage.ntp_time_ms_);
Alex Glaznev782671f2015-06-12 16:40:44 -0700665 if (CheckException(jni) || !success) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700666 ALOGE << "queueInputBuffer error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700667 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000668 }
669
670 // Try to drain the decoder
671 if (!DeliverPendingOutputs(jni, 0)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700672 ALOGE << "DeliverPendingOutputs error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700673 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000674 }
675
676 return WEBRTC_VIDEO_CODEC_OK;
677}
678
679bool MediaCodecVideoDecoder::DeliverPendingOutputs(
Per488e75f2015-11-19 10:43:36 +0100680 JNIEnv* jni, int dequeue_timeout_ms) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000681 if (frames_received_ <= frames_decoded_) {
682 // No need to query for output buffers - decoder is drained.
683 return true;
684 }
685 // Get decoder output.
Per488e75f2015-11-19 10:43:36 +0100686 jobject j_decoder_output_buffer =
687 jni->CallObjectMethod(*j_media_codec_video_decoder_,
688 use_surface_ ? j_dequeue_texture_buffer_method_
689 : j_dequeue_byte_buffer_method_,
690 dequeue_timeout_ms);
691
Alex Glaznev782671f2015-06-12 16:40:44 -0700692 if (CheckException(jni)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700693 ALOGE << "dequeueOutputBuffer() error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700694 return false;
695 }
magjed44bf6f52015-10-03 02:08:00 -0700696 if (IsNull(jni, j_decoder_output_buffer)) {
697 // No decoded frame ready.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000698 return true;
699 }
700
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000701 // Get decoded video frame properties.
702 int color_format = GetIntField(jni, *j_media_codec_video_decoder_,
703 j_color_format_field_);
704 int width = GetIntField(jni, *j_media_codec_video_decoder_, j_width_field_);
705 int height = GetIntField(jni, *j_media_codec_video_decoder_, j_height_field_);
706 int stride = GetIntField(jni, *j_media_codec_video_decoder_, j_stride_field_);
707 int slice_height = GetIntField(jni, *j_media_codec_video_decoder_,
708 j_slice_height_field_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000709
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200710 rtc::scoped_refptr<webrtc::VideoFrameBuffer> frame_buffer;
glaznev94291482016-02-01 13:17:18 -0800711 int64_t presentation_timestamps_ms = 0;
Per488e75f2015-11-19 10:43:36 +0100712 int64_t output_timestamps_ms = 0;
713 int64_t output_ntp_timestamps_ms = 0;
714 int decode_time_ms = 0;
715 int64_t frame_delayed_ms = 0;
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200716 if (use_surface_) {
magjed44bf6f52015-10-03 02:08:00 -0700717 // Extract data from Java DecodedTextureBuffer.
glaznevae95ff32016-02-04 11:47:12 -0800718 presentation_timestamps_ms = GetLongField(
719 jni, j_decoder_output_buffer,
720 j_texture_presentation_timestamp_ms_field_);
721 output_timestamps_ms = GetLongField(
722 jni, j_decoder_output_buffer, j_texture_timestamp_ms_field_);
723 output_ntp_timestamps_ms = GetLongField(
724 jni, j_decoder_output_buffer, j_texture_ntp_timestamp_ms_field_);
725 decode_time_ms = GetLongField(
726 jni, j_decoder_output_buffer, j_texture_decode_time_ms_field_);
727
magjed44bf6f52015-10-03 02:08:00 -0700728 const int texture_id =
Per488e75f2015-11-19 10:43:36 +0100729 GetIntField(jni, j_decoder_output_buffer, j_texture_id_field_);
730 if (texture_id != 0) { // |texture_id| == 0 represents a dropped frame.
731 const jfloatArray j_transform_matrix =
732 reinterpret_cast<jfloatArray>(GetObjectField(
733 jni, j_decoder_output_buffer, j_transform_matrix_field_));
glaznev94291482016-02-01 13:17:18 -0800734 frame_delayed_ms = GetLongField(
735 jni, j_decoder_output_buffer, j_texture_frame_delay_ms_field_);
Per488e75f2015-11-19 10:43:36 +0100736
737 // Create webrtc::VideoFrameBuffer with native texture handle.
738 frame_buffer = surface_texture_helper_->CreateTextureFrame(
739 width, height, NativeHandleImpl(jni, texture_id, j_transform_matrix));
glaznevae95ff32016-02-04 11:47:12 -0800740 } else {
741 EnableFrameLogOnWarning();
Per488e75f2015-11-19 10:43:36 +0100742 }
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200743 } else {
744 // Extract data from Java ByteBuffer and create output yuv420 frame -
745 // for non surface decoding only.
glaznev94291482016-02-01 13:17:18 -0800746 const int output_buffer_index = GetIntField(
747 jni, j_decoder_output_buffer, j_info_index_field_);
748 const int output_buffer_offset = GetIntField(
749 jni, j_decoder_output_buffer, j_info_offset_field_);
750 const int output_buffer_size = GetIntField(
751 jni, j_decoder_output_buffer, j_info_size_field_);
752 presentation_timestamps_ms = GetLongField(
753 jni, j_decoder_output_buffer, j_presentation_timestamp_ms_field_);
754 output_timestamps_ms = GetLongField(
755 jni, j_decoder_output_buffer, j_timestamp_ms_field_);
756 output_ntp_timestamps_ms = GetLongField(
757 jni, j_decoder_output_buffer, j_ntp_timestamp_ms_field_);
Per488e75f2015-11-19 10:43:36 +0100758
759 decode_time_ms = GetLongField(jni, j_decoder_output_buffer,
760 j_byte_buffer_decode_time_ms_field_);
magjed44bf6f52015-10-03 02:08:00 -0700761
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000762 if (output_buffer_size < width * height * 3 / 2) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700763 ALOGE << "Insufficient output buffer size: " << output_buffer_size;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000764 return false;
765 }
glaznev3816bfd2016-03-08 10:35:33 -0800766 if (output_buffer_size < stride * height * 3 / 2 &&
767 slice_height == height && stride > width) {
768 // Some codecs (Exynos) incorrectly report stride information for
769 // output byte buffer, so actual stride value need to be corrected.
770 stride = output_buffer_size * 2 / (height * 3);
771 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000772 jobjectArray output_buffers = reinterpret_cast<jobjectArray>(GetObjectField(
773 jni, *j_media_codec_video_decoder_, j_output_buffers_field_));
774 jobject output_buffer =
775 jni->GetObjectArrayElement(output_buffers, output_buffer_index);
776 uint8_t* payload = reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(
777 output_buffer));
Alex Glaznev782671f2015-06-12 16:40:44 -0700778 if (CheckException(jni)) {
779 return false;
780 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000781 payload += output_buffer_offset;
782
783 // Create yuv420 frame.
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200784 frame_buffer = decoded_frame_pool_.CreateBuffer(width, height);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000785 if (color_format == COLOR_FormatYUV420Planar) {
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200786 RTC_CHECK_EQ(0, stride % 2);
787 RTC_CHECK_EQ(0, slice_height % 2);
788 const int uv_stride = stride / 2;
789 const int u_slice_height = slice_height / 2;
790 const uint8_t* y_ptr = payload;
791 const uint8_t* u_ptr = y_ptr + stride * slice_height;
792 const uint8_t* v_ptr = u_ptr + uv_stride * u_slice_height;
793 libyuv::I420Copy(y_ptr, stride,
794 u_ptr, uv_stride,
795 v_ptr, uv_stride,
796 frame_buffer->MutableData(webrtc::kYPlane),
797 frame_buffer->stride(webrtc::kYPlane),
798 frame_buffer->MutableData(webrtc::kUPlane),
799 frame_buffer->stride(webrtc::kUPlane),
800 frame_buffer->MutableData(webrtc::kVPlane),
801 frame_buffer->stride(webrtc::kVPlane),
802 width, height);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000803 } else {
804 // All other supported formats are nv12.
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200805 const uint8_t* y_ptr = payload;
806 const uint8_t* uv_ptr = y_ptr + stride * slice_height;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000807 libyuv::NV12ToI420(
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200808 y_ptr, stride,
809 uv_ptr, stride,
810 frame_buffer->MutableData(webrtc::kYPlane),
811 frame_buffer->stride(webrtc::kYPlane),
812 frame_buffer->MutableData(webrtc::kUPlane),
813 frame_buffer->stride(webrtc::kUPlane),
814 frame_buffer->MutableData(webrtc::kVPlane),
815 frame_buffer->stride(webrtc::kVPlane),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000816 width, height);
817 }
magjed44bf6f52015-10-03 02:08:00 -0700818 // Return output byte buffer back to codec.
819 jni->CallVoidMethod(
820 *j_media_codec_video_decoder_,
821 j_return_decoded_byte_buffer_method_,
822 output_buffer_index);
823 if (CheckException(jni)) {
Per488e75f2015-11-19 10:43:36 +0100824 ALOGE << "returnDecodedOutputBuffer error";
magjed44bf6f52015-10-03 02:08:00 -0700825 return false;
826 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000827 }
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200828 VideoFrame decoded_frame(frame_buffer, 0, 0, webrtc::kVideoRotation_0);
Per488e75f2015-11-19 10:43:36 +0100829 decoded_frame.set_timestamp(output_timestamps_ms);
830 decoded_frame.set_ntp_time_ms(output_ntp_timestamps_ms);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000831
glaznevae95ff32016-02-04 11:47:12 -0800832 if (frames_decoded_ < frames_decoded_logged_) {
glaznev94291482016-02-01 13:17:18 -0800833 ALOGD << "Decoder frame out # " << frames_decoded_ <<
834 ". " << width << " x " << height <<
835 ". " << stride << " x " << slice_height <<
836 ". Color: " << color_format <<
837 ". TS: " << presentation_timestamps_ms <<
Per488e75f2015-11-19 10:43:36 +0100838 ". DecTime: " << (int)decode_time_ms <<
839 ". DelayTime: " << (int)frame_delayed_ms;
glazneve55c42c2015-10-28 10:30:32 -0700840 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000841
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000842 // Calculate and print decoding statistics - every 3 seconds.
843 frames_decoded_++;
844 current_frames_++;
Per488e75f2015-11-19 10:43:36 +0100845 current_decoding_time_ms_ += decode_time_ms;
glaznevfd6706a2016-02-05 14:05:08 -0800846 current_delay_time_ms_ += frame_delayed_ms;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000847 int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
848 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
849 current_frames_ > 0) {
glaznev94291482016-02-01 13:17:18 -0800850 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
851 int current_fps =
852 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
glaznevfd6706a2016-02-05 14:05:08 -0800853 ALOGD << "Frames decoded: " << frames_decoded_ <<
854 ". Received: " << frames_received_ <<
glaznev94291482016-02-01 13:17:18 -0800855 ". Bitrate: " << current_bitrate << " kbps" <<
856 ". Fps: " << current_fps <<
857 ". DecTime: " << (current_decoding_time_ms_ / current_frames_) <<
glaznevfd6706a2016-02-05 14:05:08 -0800858 ". DelayTime: " << (current_delay_time_ms_ / current_frames_) <<
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700859 " for last " << statistic_time_ms << " ms.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000860 start_time_ms_ = GetCurrentTimeMs();
861 current_frames_ = 0;
862 current_bytes_ = 0;
863 current_decoding_time_ms_ = 0;
glaznevfd6706a2016-02-05 14:05:08 -0800864 current_delay_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000865 }
866
Per488e75f2015-11-19 10:43:36 +0100867 // |.IsZeroSize())| returns true when a frame has been dropped.
868 if (!decoded_frame.IsZeroSize()) {
869 // Callback - output decoded frame.
870 const int32_t callback_status =
871 callback_->Decoded(decoded_frame, decode_time_ms);
872 if (callback_status > 0) {
873 ALOGE << "callback error";
874 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000875 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000876 return true;
877}
878
879int32_t MediaCodecVideoDecoder::RegisterDecodeCompleteCallback(
880 DecodedImageCallback* callback) {
881 callback_ = callback;
882 return WEBRTC_VIDEO_CODEC_OK;
883}
884
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000885void MediaCodecVideoDecoder::OnMessage(rtc::Message* msg) {
886 JNIEnv* jni = AttachCurrentThreadIfNeeded();
887 ScopedLocalRefFrame local_ref_frame(jni);
888 if (!inited_) {
889 return;
890 }
891 // We only ever send one message to |this| directly (not through a Bind()'d
892 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700893 RTC_CHECK(!msg->message_id) << "Unexpected message!";
894 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000895 CheckOnCodecThread();
896
897 if (!DeliverPendingOutputs(jni, 0)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700898 ALOGE << "OnMessage: DeliverPendingOutputs error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700899 ProcessHWErrorOnCodecThread();
900 return;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000901 }
902 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
903}
904
perkj461121c2016-02-15 06:28:36 -0800905MediaCodecVideoDecoderFactory::MediaCodecVideoDecoderFactory()
906 : egl_context_(nullptr) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700907 ALOGD << "MediaCodecVideoDecoderFactory ctor";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000908 JNIEnv* jni = AttachCurrentThreadIfNeeded();
909 ScopedLocalRefFrame local_ref_frame(jni);
910 jclass j_decoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoDecoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000911 supported_codec_types_.clear();
912
913 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000914 j_decoder_class,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000915 GetStaticMethodID(jni, j_decoder_class, "isVp8HwSupported", "()Z"));
Alex Glaznev782671f2015-06-12 16:40:44 -0700916 if (CheckException(jni)) {
917 is_vp8_hw_supported = false;
918 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000919 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700920 ALOGD << "VP8 HW Decoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000921 supported_codec_types_.push_back(kVideoCodecVP8);
922 }
923
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800924 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
925 j_decoder_class,
926 GetStaticMethodID(jni, j_decoder_class, "isVp9HwSupported", "()Z"));
927 if (CheckException(jni)) {
928 is_vp9_hw_supported = false;
929 }
930 if (is_vp9_hw_supported) {
931 ALOGD << "VP9 HW Decoder supported.";
932 supported_codec_types_.push_back(kVideoCodecVP9);
933 }
934
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000935 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
936 j_decoder_class,
937 GetStaticMethodID(jni, j_decoder_class, "isH264HwSupported", "()Z"));
Alex Glaznev782671f2015-06-12 16:40:44 -0700938 if (CheckException(jni)) {
939 is_h264_hw_supported = false;
940 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000941 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700942 ALOGD << "H264 HW Decoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000943 supported_codec_types_.push_back(kVideoCodecH264);
944 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000945}
946
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700947MediaCodecVideoDecoderFactory::~MediaCodecVideoDecoderFactory() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700948 ALOGD << "MediaCodecVideoDecoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -0800949 if (egl_context_) {
950 JNIEnv* jni = AttachCurrentThreadIfNeeded();
951 jni->DeleteGlobalRef(egl_context_);
952 }
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700953}
954
955void MediaCodecVideoDecoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -0800956 JNIEnv* jni, jobject egl_context) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700957 ALOGD << "MediaCodecVideoDecoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +0100958 if (egl_context_) {
959 jni->DeleteGlobalRef(egl_context_);
960 egl_context_ = nullptr;
961 }
perkj461121c2016-02-15 06:28:36 -0800962 egl_context_ = jni->NewGlobalRef(egl_context);
963 if (CheckException(jni)) {
964 ALOGE << "error calling NewGlobalRef for EGL Context.";
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700965 }
966}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000967
968webrtc::VideoDecoder* MediaCodecVideoDecoderFactory::CreateVideoDecoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000969 VideoCodecType type) {
970 if (supported_codec_types_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -0800971 ALOGW << "No HW video decoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +0100972 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000973 }
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700974 for (VideoCodecType codec_type : supported_codec_types_) {
975 if (codec_type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700976 ALOGD << "Create HW video decoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +0100977 return new MediaCodecVideoDecoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -0800978 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000979 }
980 }
Alex Glaznevad948c42015-11-18 13:06:42 -0800981 ALOGW << "Can not find HW video decoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +0100982 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000983}
984
985void MediaCodecVideoDecoderFactory::DestroyVideoDecoder(
986 webrtc::VideoDecoder* decoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700987 ALOGD << "Destroy video decoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000988 delete decoder;
989}
990
Peter Boströmb7d9a972015-12-18 16:01:11 +0100991const char* MediaCodecVideoDecoder::ImplementationName() const {
992 return "MediaCodec";
993}
994
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000995} // namespace webrtc_jni
996