blob: 831b68d512c0292f68db001cac7b624fcd3c18ac [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"
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000035
36using rtc::Bind;
37using rtc::Thread;
38using rtc::ThreadManager;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000039
40using webrtc::CodecSpecificInfo;
41using webrtc::DecodedImageCallback;
42using webrtc::EncodedImage;
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -070043using webrtc::VideoFrame;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000044using webrtc::RTPFragmentationHeader;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000045using webrtc::VideoCodec;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +000046using webrtc::VideoCodecType;
47using webrtc::kVideoCodecH264;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000048using webrtc::kVideoCodecVP8;
Alex Glaznev69a7fd52015-11-10 10:25:40 -080049using webrtc::kVideoCodecVP9;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000050
51namespace webrtc_jni {
52
glaznevf4decb52016-01-15 13:49:22 -080053// Logging macros.
54#define TAG_DECODER "MediaCodecVideoDecoder"
55#ifdef TRACK_BUFFER_TIMING
56#define ALOGV(...)
57 __android_log_print(ANDROID_LOG_VERBOSE, TAG_DECODER, __VA_ARGS__)
58#else
59#define ALOGV(...)
60#endif
61#define ALOGD LOG_TAG(rtc::LS_INFO, TAG_DECODER)
62#define ALOGW LOG_TAG(rtc::LS_WARNING, TAG_DECODER)
63#define ALOGE LOG_TAG(rtc::LS_ERROR, TAG_DECODER)
64
glaznevae95ff32016-02-04 11:47:12 -080065enum { kMaxWarningLogFrames = 2 };
66
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000067class MediaCodecVideoDecoder : public webrtc::VideoDecoder,
68 public rtc::MessageHandler {
69 public:
Alex Glaznev4d2f4d12015-09-01 15:04:13 -070070 explicit MediaCodecVideoDecoder(
71 JNIEnv* jni, VideoCodecType codecType, jobject render_egl_context);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000072 virtual ~MediaCodecVideoDecoder();
73
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000074 int32_t InitDecode(const VideoCodec* codecSettings, int32_t numberOfCores)
75 override;
76
77 int32_t Decode(
78 const EncodedImage& inputImage, bool missingFrames,
79 const RTPFragmentationHeader* fragmentation,
80 const CodecSpecificInfo* codecSpecificInfo = NULL,
81 int64_t renderTimeMs = -1) override;
82
83 int32_t RegisterDecodeCompleteCallback(DecodedImageCallback* callback)
84 override;
85
86 int32_t Release() override;
87
perkj796cfaf2015-12-10 09:27:38 -080088 bool PrefersLateDecoding() const override { return true; }
89
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000090 // rtc::MessageHandler implementation.
91 void OnMessage(rtc::Message* msg) override;
92
Peter Boströmb7d9a972015-12-18 16:01:11 +010093 const char* ImplementationName() const override;
94
glaznev@webrtc.org18c92472015-02-18 18:42:55 +000095 private:
96 // CHECK-fail if not running on |codec_thread_|.
97 void CheckOnCodecThread();
98
99 int32_t InitDecodeOnCodecThread();
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800100 int32_t ResetDecodeOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000101 int32_t ReleaseOnCodecThread();
102 int32_t DecodeOnCodecThread(const EncodedImage& inputImage);
103 // Deliver any outputs pending in the MediaCodec to our |callback_| and return
104 // true on success.
105 bool DeliverPendingOutputs(JNIEnv* jni, int dequeue_timeout_us);
Alex Glaznev782671f2015-06-12 16:40:44 -0700106 int32_t ProcessHWErrorOnCodecThread();
glaznevae95ff32016-02-04 11:47:12 -0800107 void EnableFrameLogOnWarning();
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800108 void ResetVariables();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000109
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000110 // Type of video codec.
111 VideoCodecType codecType_;
112
kjellander60ca31b2016-01-04 10:15:53 -0800113 // Render EGL context - owned by factory, should not be allocated/destroyed
114 // by VideoDecoder.
115 jobject render_egl_context_;
116
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000117 bool key_frame_required_;
118 bool inited_;
Alex Glaznev782671f2015-06-12 16:40:44 -0700119 bool sw_fallback_required_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000120 bool use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000121 VideoCodec codec_;
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200122 webrtc::I420BufferPool decoded_frame_pool_;
Per488e75f2015-11-19 10:43:36 +0100123 rtc::scoped_refptr<SurfaceTextureHelper> surface_texture_helper_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000124 DecodedImageCallback* callback_;
125 int frames_received_; // Number of frames received by decoder.
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000126 int frames_decoded_; // Number of frames decoded by decoder.
glaznevae95ff32016-02-04 11:47:12 -0800127 // Number of decoded frames for which log information is displayed.
128 int frames_decoded_logged_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000129 int64_t start_time_ms_; // Start time for statistics.
130 int current_frames_; // Number of frames in the current statistics interval.
131 int current_bytes_; // Encoded bytes in the current statistics interval.
132 int current_decoding_time_ms_; // Overall decoding time in the current second
glaznevfd6706a2016-02-05 14:05:08 -0800133 int current_delay_time_ms_; // Overall delay time in the current second.
134 uint32_t max_pending_frames_; // Maximum number of pending input frames.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000135
136 // State that is constant for the lifetime of this object once the ctor
137 // returns.
kwibergd1fe2812016-04-27 06:47:29 -0700138 std::unique_ptr<Thread>
139 codec_thread_; // Thread on which to operate MediaCodec.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000140 ScopedGlobalRef<jclass> j_media_codec_video_decoder_class_;
141 ScopedGlobalRef<jobject> j_media_codec_video_decoder_;
142 jmethodID j_init_decode_method_;
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800143 jmethodID j_reset_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000144 jmethodID j_release_method_;
145 jmethodID j_dequeue_input_buffer_method_;
146 jmethodID j_queue_input_buffer_method_;
Per488e75f2015-11-19 10:43:36 +0100147 jmethodID j_dequeue_byte_buffer_method_;
148 jmethodID j_dequeue_texture_buffer_method_;
magjed44bf6f52015-10-03 02:08:00 -0700149 jmethodID j_return_decoded_byte_buffer_method_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000150 // MediaCodecVideoDecoder fields.
151 jfieldID j_input_buffers_field_;
152 jfieldID j_output_buffers_field_;
153 jfieldID j_color_format_field_;
154 jfieldID j_width_field_;
155 jfieldID j_height_field_;
156 jfieldID j_stride_field_;
157 jfieldID j_slice_height_field_;
magjed44bf6f52015-10-03 02:08:00 -0700158 // MediaCodecVideoDecoder.DecodedTextureBuffer fields.
Per488e75f2015-11-19 10:43:36 +0100159 jfieldID j_texture_id_field_;
160 jfieldID j_transform_matrix_field_;
glaznev94291482016-02-01 13:17:18 -0800161 jfieldID j_texture_presentation_timestamp_ms_field_;
Per488e75f2015-11-19 10:43:36 +0100162 jfieldID j_texture_timestamp_ms_field_;
163 jfieldID j_texture_ntp_timestamp_ms_field_;
164 jfieldID j_texture_decode_time_ms_field_;
165 jfieldID j_texture_frame_delay_ms_field_;
166 // MediaCodecVideoDecoder.DecodedOutputBuffer fields.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000167 jfieldID j_info_index_field_;
168 jfieldID j_info_offset_field_;
169 jfieldID j_info_size_field_;
glaznev94291482016-02-01 13:17:18 -0800170 jfieldID j_presentation_timestamp_ms_field_;
171 jfieldID j_timestamp_ms_field_;
172 jfieldID j_ntp_timestamp_ms_field_;
Per488e75f2015-11-19 10:43:36 +0100173 jfieldID j_byte_buffer_decode_time_ms_field_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000174
175 // Global references; must be deleted in Release().
176 std::vector<jobject> input_buffers_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000177};
178
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000179MediaCodecVideoDecoder::MediaCodecVideoDecoder(
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700180 JNIEnv* jni, VideoCodecType codecType, jobject render_egl_context) :
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000181 codecType_(codecType),
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700182 render_egl_context_(render_egl_context),
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000183 key_frame_required_(true),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000184 inited_(false),
Alex Glaznev782671f2015-06-12 16:40:44 -0700185 sw_fallback_required_(false),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000186 codec_thread_(new Thread()),
187 j_media_codec_video_decoder_class_(
188 jni,
189 FindClass(jni, "org/webrtc/MediaCodecVideoDecoder")),
190 j_media_codec_video_decoder_(
191 jni,
192 jni->NewObject(*j_media_codec_video_decoder_class_,
193 GetMethodID(jni,
194 *j_media_codec_video_decoder_class_,
195 "<init>",
196 "()V"))) {
197 ScopedLocalRefFrame local_ref_frame(jni);
198 codec_thread_->SetName("MediaCodecVideoDecoder", NULL);
henrikg91d6ede2015-09-17 00:24:34 -0700199 RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoDecoder";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000200
201 j_init_decode_method_ = GetMethodID(
202 jni, *j_media_codec_video_decoder_class_, "initDecode",
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000203 "(Lorg/webrtc/MediaCodecVideoDecoder$VideoCodecType;"
Per488e75f2015-11-19 10:43:36 +0100204 "IILorg/webrtc/SurfaceTextureHelper;)Z");
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800205 j_reset_method_ =
206 GetMethodID(jni, *j_media_codec_video_decoder_class_, "reset", "(II)V");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000207 j_release_method_ =
208 GetMethodID(jni, *j_media_codec_video_decoder_class_, "release", "()V");
209 j_dequeue_input_buffer_method_ = GetMethodID(
210 jni, *j_media_codec_video_decoder_class_, "dequeueInputBuffer", "()I");
211 j_queue_input_buffer_method_ = GetMethodID(
Per488e75f2015-11-19 10:43:36 +0100212 jni, *j_media_codec_video_decoder_class_, "queueInputBuffer", "(IIJJJ)Z");
213 j_dequeue_byte_buffer_method_ = GetMethodID(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000214 jni, *j_media_codec_video_decoder_class_, "dequeueOutputBuffer",
Per488e75f2015-11-19 10:43:36 +0100215 "(I)Lorg/webrtc/MediaCodecVideoDecoder$DecodedOutputBuffer;");
216 j_dequeue_texture_buffer_method_ = GetMethodID(
217 jni, *j_media_codec_video_decoder_class_, "dequeueTextureBuffer",
218 "(I)Lorg/webrtc/MediaCodecVideoDecoder$DecodedTextureBuffer;");
magjed44bf6f52015-10-03 02:08:00 -0700219 j_return_decoded_byte_buffer_method_ =
220 GetMethodID(jni, *j_media_codec_video_decoder_class_,
Per488e75f2015-11-19 10:43:36 +0100221 "returnDecodedOutputBuffer", "(I)V");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000222
223 j_input_buffers_field_ = GetFieldID(
224 jni, *j_media_codec_video_decoder_class_,
225 "inputBuffers", "[Ljava/nio/ByteBuffer;");
226 j_output_buffers_field_ = GetFieldID(
227 jni, *j_media_codec_video_decoder_class_,
228 "outputBuffers", "[Ljava/nio/ByteBuffer;");
229 j_color_format_field_ = GetFieldID(
230 jni, *j_media_codec_video_decoder_class_, "colorFormat", "I");
231 j_width_field_ = GetFieldID(
232 jni, *j_media_codec_video_decoder_class_, "width", "I");
233 j_height_field_ = GetFieldID(
234 jni, *j_media_codec_video_decoder_class_, "height", "I");
235 j_stride_field_ = GetFieldID(
236 jni, *j_media_codec_video_decoder_class_, "stride", "I");
237 j_slice_height_field_ = GetFieldID(
238 jni, *j_media_codec_video_decoder_class_, "sliceHeight", "I");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000239
Per488e75f2015-11-19 10:43:36 +0100240 jclass j_decoded_texture_buffer_class = FindClass(jni,
magjed44bf6f52015-10-03 02:08:00 -0700241 "org/webrtc/MediaCodecVideoDecoder$DecodedTextureBuffer");
Per488e75f2015-11-19 10:43:36 +0100242 j_texture_id_field_ = GetFieldID(
243 jni, j_decoded_texture_buffer_class, "textureID", "I");
244 j_transform_matrix_field_ = GetFieldID(
245 jni, j_decoded_texture_buffer_class, "transformMatrix", "[F");
glaznev94291482016-02-01 13:17:18 -0800246 j_texture_presentation_timestamp_ms_field_ = GetFieldID(
247 jni, j_decoded_texture_buffer_class, "presentationTimeStampMs", "J");
Per488e75f2015-11-19 10:43:36 +0100248 j_texture_timestamp_ms_field_ = GetFieldID(
249 jni, j_decoded_texture_buffer_class, "timeStampMs", "J");
250 j_texture_ntp_timestamp_ms_field_ = GetFieldID(
251 jni, j_decoded_texture_buffer_class, "ntpTimeStampMs", "J");
252 j_texture_decode_time_ms_field_ = GetFieldID(
253 jni, j_decoded_texture_buffer_class, "decodeTimeMs", "J");
254 j_texture_frame_delay_ms_field_ = GetFieldID(
255 jni, j_decoded_texture_buffer_class, "frameDelayMs", "J");
magjed44bf6f52015-10-03 02:08:00 -0700256
Per488e75f2015-11-19 10:43:36 +0100257 jclass j_decoded_output_buffer_class = FindClass(jni,
258 "org/webrtc/MediaCodecVideoDecoder$DecodedOutputBuffer");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000259 j_info_index_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100260 jni, j_decoded_output_buffer_class, "index", "I");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000261 j_info_offset_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100262 jni, j_decoded_output_buffer_class, "offset", "I");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000263 j_info_size_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100264 jni, j_decoded_output_buffer_class, "size", "I");
glaznev94291482016-02-01 13:17:18 -0800265 j_presentation_timestamp_ms_field_ = GetFieldID(
266 jni, j_decoded_output_buffer_class, "presentationTimeStampMs", "J");
267 j_timestamp_ms_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100268 jni, j_decoded_output_buffer_class, "timeStampMs", "J");
glaznev94291482016-02-01 13:17:18 -0800269 j_ntp_timestamp_ms_field_ = GetFieldID(
Per488e75f2015-11-19 10:43:36 +0100270 jni, j_decoded_output_buffer_class, "ntpTimeStampMs", "J");
271 j_byte_buffer_decode_time_ms_field_ = GetFieldID(
272 jni, j_decoded_output_buffer_class, "decodeTimeMs", "J");
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000273
274 CHECK_EXCEPTION(jni) << "MediaCodecVideoDecoder ctor failed";
Magnus Jedvert207370f2015-09-16 12:32:21 +0200275 use_surface_ = (render_egl_context_ != NULL);
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700276 ALOGD << "MediaCodecVideoDecoder ctor. Use surface: " << use_surface_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000277 memset(&codec_, 0, sizeof(codec_));
278 AllowBlockingCalls();
279}
280
281MediaCodecVideoDecoder::~MediaCodecVideoDecoder() {
282 // Call Release() to ensure no more callbacks to us after we are deleted.
283 Release();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000284}
285
286int32_t MediaCodecVideoDecoder::InitDecode(const VideoCodec* inst,
287 int32_t numberOfCores) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700288 ALOGD << "InitDecode.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000289 if (inst == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700290 ALOGE << "NULL VideoCodec instance";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000291 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
292 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000293 // Factory should guard against other codecs being used with us.
henrikg91d6ede2015-09-17 00:24:34 -0700294 RTC_CHECK(inst->codecType == codecType_)
295 << "Unsupported codec " << inst->codecType << " for " << codecType_;
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000296
Alex Glaznev782671f2015-06-12 16:40:44 -0700297 if (sw_fallback_required_) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700298 ALOGE << "InitDecode() - fallback to SW decoder";
Alex Glaznev782671f2015-06-12 16:40:44 -0700299 return WEBRTC_VIDEO_CODEC_OK;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000300 }
301 // Save VideoCodec instance for later.
302 if (&codec_ != inst) {
303 codec_ = *inst;
304 }
glazneve55c42c2015-10-28 10:30:32 -0700305 // If maxFramerate is not set then assume 30 fps.
306 codec_.maxFramerate = (codec_.maxFramerate >= 1) ? codec_.maxFramerate : 30;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000307
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000308 // Call Java init.
309 return codec_thread_->Invoke<int32_t>(
310 Bind(&MediaCodecVideoDecoder::InitDecodeOnCodecThread, this));
311}
312
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800313void MediaCodecVideoDecoder::ResetVariables() {
314 CheckOnCodecThread();
315
316 key_frame_required_ = true;
317 frames_received_ = 0;
318 frames_decoded_ = 0;
319 frames_decoded_logged_ = kMaxDecodedLogFrames;
Niels Möllerd28db7f2016-05-10 16:31:47 +0200320 start_time_ms_ = rtc::TimeMillis();
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800321 current_frames_ = 0;
322 current_bytes_ = 0;
323 current_decoding_time_ms_ = 0;
324 current_delay_time_ms_ = 0;
325}
326
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000327int32_t MediaCodecVideoDecoder::InitDecodeOnCodecThread() {
328 CheckOnCodecThread();
329 JNIEnv* jni = AttachCurrentThreadIfNeeded();
330 ScopedLocalRefFrame local_ref_frame(jni);
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700331 ALOGD << "InitDecodeOnCodecThread Type: " << (int)codecType_ << ". "
332 << codec_.width << " x " << codec_.height << ". Fps: " <<
333 (int)codec_.maxFramerate;
Alex Glaznev782671f2015-06-12 16:40:44 -0700334
335 // Release previous codec first if it was allocated before.
336 int ret_val = ReleaseOnCodecThread();
337 if (ret_val < 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700338 ALOGE << "Release failure: " << ret_val << " - fallback to SW codec";
Alex Glaznev782671f2015-06-12 16:40:44 -0700339 sw_fallback_required_ = true;
340 return WEBRTC_VIDEO_CODEC_ERROR;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000341 }
342
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800343 ResetVariables();
Alex Glaznev782671f2015-06-12 16:40:44 -0700344
Per488e75f2015-11-19 10:43:36 +0100345 if (use_surface_) {
magjed2aa84262016-05-09 08:28:45 -0700346 surface_texture_helper_ = SurfaceTextureHelper::create(
magjed82b750b2016-03-31 00:54:15 -0700347 jni, "Decoder SurfaceTextureHelper", render_egl_context_);
magjed2aa84262016-05-09 08:28:45 -0700348 if (!surface_texture_helper_) {
349 ALOGE << "Couldn't create SurfaceTextureHelper - fallback to SW codec";
350 sw_fallback_required_ = true;
351 return WEBRTC_VIDEO_CODEC_ERROR;
352 }
Per488e75f2015-11-19 10:43:36 +0100353 }
354
Perec2922f2016-01-27 15:25:46 +0100355 jobject j_video_codec_enum = JavaEnumFromIndexAndClassName(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000356 jni, "MediaCodecVideoDecoder$VideoCodecType", codecType_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000357 bool success = jni->CallBooleanMethod(
358 *j_media_codec_video_decoder_,
359 j_init_decode_method_,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000360 j_video_codec_enum,
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000361 codec_.width,
362 codec_.height,
magjed0dc23162016-03-14 03:59:38 -0700363 use_surface_ ? surface_texture_helper_->GetJavaSurfaceTextureHelper()
364 : nullptr);
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800365
Alex Glaznev782671f2015-06-12 16:40:44 -0700366 if (CheckException(jni) || !success) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700367 ALOGE << "Codec initialization error - fallback to SW codec.";
Alex Glaznev782671f2015-06-12 16:40:44 -0700368 sw_fallback_required_ = true;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000369 return WEBRTC_VIDEO_CODEC_ERROR;
370 }
371 inited_ = true;
372
glaznev@webrtc.orga4623d22015-02-25 00:02:50 +0000373 switch (codecType_) {
374 case kVideoCodecVP8:
375 max_pending_frames_ = kMaxPendingFramesVp8;
376 break;
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800377 case kVideoCodecVP9:
378 max_pending_frames_ = kMaxPendingFramesVp9;
379 break;
glaznev@webrtc.orga4623d22015-02-25 00:02:50 +0000380 case kVideoCodecH264:
381 max_pending_frames_ = kMaxPendingFramesH264;
382 break;
383 default:
384 max_pending_frames_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000385 }
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800386 ALOGD << "Maximum amount of pending frames: " << max_pending_frames_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000387
388 jobjectArray input_buffers = (jobjectArray)GetObjectField(
389 jni, *j_media_codec_video_decoder_, j_input_buffers_field_);
390 size_t num_input_buffers = jni->GetArrayLength(input_buffers);
391 input_buffers_.resize(num_input_buffers);
392 for (size_t i = 0; i < num_input_buffers; ++i) {
393 input_buffers_[i] =
394 jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
Alex Glaznev782671f2015-06-12 16:40:44 -0700395 if (CheckException(jni)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700396 ALOGE << "NewGlobalRef error - fallback to SW codec.";
Alex Glaznev782671f2015-06-12 16:40:44 -0700397 sw_fallback_required_ = true;
398 return WEBRTC_VIDEO_CODEC_ERROR;
399 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000400 }
401
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000402 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
403
404 return WEBRTC_VIDEO_CODEC_OK;
405}
406
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800407int32_t MediaCodecVideoDecoder::ResetDecodeOnCodecThread() {
408 CheckOnCodecThread();
409 JNIEnv* jni = AttachCurrentThreadIfNeeded();
410 ScopedLocalRefFrame local_ref_frame(jni);
411 ALOGD << "ResetDecodeOnCodecThread Type: " << (int)codecType_ << ". "
412 << codec_.width << " x " << codec_.height;
413 ALOGD << " Frames received: " << frames_received_ <<
414 ". Frames decoded: " << frames_decoded_;
415
416 inited_ = false;
417 rtc::MessageQueueManager::Clear(this);
418 ResetVariables();
419
420 jni->CallVoidMethod(
421 *j_media_codec_video_decoder_,
422 j_reset_method_,
423 codec_.width,
424 codec_.height);
425
426 if (CheckException(jni)) {
427 ALOGE << "Soft reset error - fallback to SW codec.";
428 sw_fallback_required_ = true;
429 return WEBRTC_VIDEO_CODEC_ERROR;
430 }
431 inited_ = true;
432
433 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
434
435 return WEBRTC_VIDEO_CODEC_OK;
436}
437
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000438int32_t MediaCodecVideoDecoder::Release() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700439 ALOGD << "DecoderRelease request";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000440 return codec_thread_->Invoke<int32_t>(
441 Bind(&MediaCodecVideoDecoder::ReleaseOnCodecThread, this));
442}
443
444int32_t MediaCodecVideoDecoder::ReleaseOnCodecThread() {
445 if (!inited_) {
446 return WEBRTC_VIDEO_CODEC_OK;
447 }
448 CheckOnCodecThread();
449 JNIEnv* jni = AttachCurrentThreadIfNeeded();
glazneve55c42c2015-10-28 10:30:32 -0700450 ALOGD << "DecoderReleaseOnCodecThread: Frames received: " <<
451 frames_received_ << ". Frames decoded: " << frames_decoded_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000452 ScopedLocalRefFrame local_ref_frame(jni);
453 for (size_t i = 0; i < input_buffers_.size(); i++) {
454 jni->DeleteGlobalRef(input_buffers_[i]);
455 }
456 input_buffers_.clear();
457 jni->CallVoidMethod(*j_media_codec_video_decoder_, j_release_method_);
Per488e75f2015-11-19 10:43:36 +0100458 surface_texture_helper_ = nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000459 inited_ = false;
Alex Glaznev782671f2015-06-12 16:40:44 -0700460 rtc::MessageQueueManager::Clear(this);
461 if (CheckException(jni)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700462 ALOGE << "Decoder release exception";
Alex Glaznev782671f2015-06-12 16:40:44 -0700463 return WEBRTC_VIDEO_CODEC_ERROR;
464 }
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700465 ALOGD << "DecoderReleaseOnCodecThread done";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000466 return WEBRTC_VIDEO_CODEC_OK;
467}
468
469void MediaCodecVideoDecoder::CheckOnCodecThread() {
kwiberg9708e9c2016-03-29 10:17:42 -0700470 RTC_CHECK(codec_thread_.get() == ThreadManager::Instance()->CurrentThread())
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000471 << "Running on wrong thread!";
472}
473
glaznevae95ff32016-02-04 11:47:12 -0800474void MediaCodecVideoDecoder::EnableFrameLogOnWarning() {
475 // Log next 2 output frames.
476 frames_decoded_logged_ = std::max(
477 frames_decoded_logged_, frames_decoded_ + kMaxWarningLogFrames);
478}
479
Alex Glaznev782671f2015-06-12 16:40:44 -0700480int32_t MediaCodecVideoDecoder::ProcessHWErrorOnCodecThread() {
481 CheckOnCodecThread();
482 int ret_val = ReleaseOnCodecThread();
483 if (ret_val < 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700484 ALOGE << "ProcessHWError: Release failure";
Alex Glaznev782671f2015-06-12 16:40:44 -0700485 }
486 if (codecType_ == kVideoCodecH264) {
487 // For now there is no SW H.264 which can be used as fallback codec.
488 // So try to restart hw codec for now.
489 ret_val = InitDecodeOnCodecThread();
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700490 ALOGE << "Reset H.264 codec done. Status: " << ret_val;
Alex Glaznev782671f2015-06-12 16:40:44 -0700491 if (ret_val == WEBRTC_VIDEO_CODEC_OK) {
492 // H.264 codec was succesfully reset - return regular error code.
493 return WEBRTC_VIDEO_CODEC_ERROR;
494 } else {
495 // Fail to restart H.264 codec - return error code which should stop the
496 // call.
497 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
498 }
499 } else {
500 sw_fallback_required_ = true;
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700501 ALOGE << "Return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE";
Alex Glaznev782671f2015-06-12 16:40:44 -0700502 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
503 }
504}
505
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000506int32_t MediaCodecVideoDecoder::Decode(
507 const EncodedImage& inputImage,
508 bool missingFrames,
509 const RTPFragmentationHeader* fragmentation,
510 const CodecSpecificInfo* codecSpecificInfo,
511 int64_t renderTimeMs) {
Alex Glaznev782671f2015-06-12 16:40:44 -0700512 if (sw_fallback_required_) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700513 ALOGE << "Decode() - fallback to SW codec";
Alex Glaznev782671f2015-06-12 16:40:44 -0700514 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000515 }
516 if (callback_ == NULL) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700517 ALOGE << "Decode() - callback_ is NULL";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000518 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
519 }
520 if (inputImage._buffer == NULL && inputImage._length > 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700521 ALOGE << "Decode() - inputImage is incorrect";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000522 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
523 }
Alex Glaznev782671f2015-06-12 16:40:44 -0700524 if (!inited_) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700525 ALOGE << "Decode() - decoder is not initialized";
Alex Glaznev782671f2015-06-12 16:40:44 -0700526 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
527 }
528
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000529 // Check if encoded frame dimension has changed.
530 if ((inputImage._encodedWidth * inputImage._encodedHeight > 0) &&
531 (inputImage._encodedWidth != codec_.width ||
532 inputImage._encodedHeight != codec_.height)) {
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800533 ALOGW << "Input resolution changed from " <<
534 codec_.width << " x " << codec_.height << " to " <<
535 inputImage._encodedWidth << " x " << inputImage._encodedHeight;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000536 codec_.width = inputImage._encodedWidth;
537 codec_.height = inputImage._encodedHeight;
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800538 int32_t ret;
Alex Glaznev79299af2016-04-12 16:39:39 -0700539 if (use_surface_ &&
540 (codecType_ == kVideoCodecVP8 || codecType_ == kVideoCodecH264)) {
541 // Soft codec reset - only for surface decoding.
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800542 ret = codec_thread_->Invoke<int32_t>(Bind(
543 &MediaCodecVideoDecoder::ResetDecodeOnCodecThread, this));
544 } else {
545 // Hard codec reset.
546 ret = InitDecode(&codec_, 1);
547 }
Alex Glaznev782671f2015-06-12 16:40:44 -0700548 if (ret < 0) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700549 ALOGE << "InitDecode failure: " << ret << " - fallback to SW codec";
Alex Glaznev782671f2015-06-12 16:40:44 -0700550 sw_fallback_required_ = true;
551 return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
552 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000553 }
554
555 // Always start with a complete key frame.
556 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200557 if (inputImage._frameType != webrtc::kVideoFrameKey) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700558 ALOGE << "Decode() - key frame is required";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000559 return WEBRTC_VIDEO_CODEC_ERROR;
560 }
561 if (!inputImage._completeFrame) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700562 ALOGE << "Decode() - complete frame is required";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000563 return WEBRTC_VIDEO_CODEC_ERROR;
564 }
565 key_frame_required_ = false;
566 }
567 if (inputImage._length == 0) {
568 return WEBRTC_VIDEO_CODEC_ERROR;
569 }
570
571 return codec_thread_->Invoke<int32_t>(Bind(
572 &MediaCodecVideoDecoder::DecodeOnCodecThread, this, inputImage));
573}
574
575int32_t MediaCodecVideoDecoder::DecodeOnCodecThread(
576 const EncodedImage& inputImage) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000577 CheckOnCodecThread();
578 JNIEnv* jni = AttachCurrentThreadIfNeeded();
579 ScopedLocalRefFrame local_ref_frame(jni);
580
581 // Try to drain the decoder and wait until output is not too
582 // much behind the input.
Alex Glaznev6a4a03c2016-03-04 14:10:50 -0800583 if (codecType_ == kVideoCodecH264 &&
584 frames_received_ > frames_decoded_ + max_pending_frames_) {
585 // Print warning for H.264 only - for VP8/VP9 one frame delay is ok.
glaznevae95ff32016-02-04 11:47:12 -0800586 ALOGW << "Decoder is too far behind. Try to drain. Received: " <<
587 frames_received_ << ". Decoded: " << frames_decoded_;
588 EnableFrameLogOnWarning();
589 }
Niels Möllerd28db7f2016-05-10 16:31:47 +0200590 const int64 drain_start = rtc::TimeMillis();
Per488e75f2015-11-19 10:43:36 +0100591 while ((frames_received_ > frames_decoded_ + max_pending_frames_) &&
Niels Möllerd28db7f2016-05-10 16:31:47 +0200592 (rtc::TimeMillis() - drain_start) < kMediaCodecTimeoutMs) {
Per488e75f2015-11-19 10:43:36 +0100593 if (!DeliverPendingOutputs(jni, kMediaCodecPollMs)) {
glazneve55c42c2015-10-28 10:30:32 -0700594 ALOGE << "DeliverPendingOutputs error. Frames received: " <<
595 frames_received_ << ". Frames decoded: " << frames_decoded_;
Alex Glaznev782671f2015-06-12 16:40:44 -0700596 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000597 }
Per488e75f2015-11-19 10:43:36 +0100598 }
599 if (frames_received_ > frames_decoded_ + max_pending_frames_) {
600 ALOGE << "Output buffer dequeue timeout. Frames received: " <<
601 frames_received_ << ". Frames decoded: " << frames_decoded_;
602 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000603 }
604
605 // Get input buffer.
glaznevae95ff32016-02-04 11:47:12 -0800606 int j_input_buffer_index = jni->CallIntMethod(
607 *j_media_codec_video_decoder_, j_dequeue_input_buffer_method_);
Alex Glaznev782671f2015-06-12 16:40:44 -0700608 if (CheckException(jni) || j_input_buffer_index < 0) {
glaznevae95ff32016-02-04 11:47:12 -0800609 ALOGE << "dequeueInputBuffer error: " << j_input_buffer_index <<
610 ". Retry DeliverPendingOutputs.";
611 EnableFrameLogOnWarning();
612 // Try to drain the decoder.
613 if (!DeliverPendingOutputs(jni, kMediaCodecPollMs)) {
614 ALOGE << "DeliverPendingOutputs error. Frames received: " <<
615 frames_received_ << ". Frames decoded: " << frames_decoded_;
616 return ProcessHWErrorOnCodecThread();
617 }
618 // Try dequeue input buffer one last time.
619 j_input_buffer_index = jni->CallIntMethod(
620 *j_media_codec_video_decoder_, j_dequeue_input_buffer_method_);
621 if (CheckException(jni) || j_input_buffer_index < 0) {
622 ALOGE << "dequeueInputBuffer critical error: " << j_input_buffer_index;
623 return ProcessHWErrorOnCodecThread();
624 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000625 }
626
627 // Copy encoded data to Java ByteBuffer.
628 jobject j_input_buffer = input_buffers_[j_input_buffer_index];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200629 uint8_t* buffer =
630 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_input_buffer));
henrikg91d6ede2015-09-17 00:24:34 -0700631 RTC_CHECK(buffer) << "Indirect buffer??";
Peter Boström0c4e06b2015-10-07 12:23:21 +0200632 int64_t buffer_capacity = jni->GetDirectBufferCapacity(j_input_buffer);
Alex Glaznev782671f2015-06-12 16:40:44 -0700633 if (CheckException(jni) || buffer_capacity < inputImage._length) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700634 ALOGE << "Input frame size "<< inputImage._length <<
635 " is bigger than buffer size " << buffer_capacity;
Alex Glaznev782671f2015-06-12 16:40:44 -0700636 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000637 }
glaznevae95ff32016-02-04 11:47:12 -0800638 jlong presentation_timestamp_us = static_cast<jlong>(
639 static_cast<int64_t>(frames_received_) * 1000000 / codec_.maxFramerate);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000640 memcpy(buffer, inputImage._buffer, inputImage._length);
641
glaznevae95ff32016-02-04 11:47:12 -0800642 if (frames_decoded_ < frames_decoded_logged_) {
glaznev94291482016-02-01 13:17:18 -0800643 ALOGD << "Decoder frame in # " << frames_received_ <<
644 ". Type: " << inputImage._frameType <<
645 ". Buffer # " << j_input_buffer_index <<
glaznevae95ff32016-02-04 11:47:12 -0800646 ". TS: " << presentation_timestamp_us / 1000 <<
glaznev94291482016-02-01 13:17:18 -0800647 ". Size: " << inputImage._length;
648 }
649
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000650 // Save input image timestamps for later output.
651 frames_received_++;
652 current_bytes_ += inputImage._length;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000653
654 // Feed input to decoder.
Per488e75f2015-11-19 10:43:36 +0100655 bool success = jni->CallBooleanMethod(
656 *j_media_codec_video_decoder_,
657 j_queue_input_buffer_method_,
658 j_input_buffer_index,
659 inputImage._length,
660 presentation_timestamp_us,
661 static_cast<int64_t> (inputImage._timeStamp),
662 inputImage.ntp_time_ms_);
Alex Glaznev782671f2015-06-12 16:40:44 -0700663 if (CheckException(jni) || !success) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700664 ALOGE << "queueInputBuffer error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700665 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000666 }
667
668 // Try to drain the decoder
669 if (!DeliverPendingOutputs(jni, 0)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700670 ALOGE << "DeliverPendingOutputs error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700671 return ProcessHWErrorOnCodecThread();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000672 }
673
674 return WEBRTC_VIDEO_CODEC_OK;
675}
676
677bool MediaCodecVideoDecoder::DeliverPendingOutputs(
Per488e75f2015-11-19 10:43:36 +0100678 JNIEnv* jni, int dequeue_timeout_ms) {
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000679 if (frames_received_ <= frames_decoded_) {
680 // No need to query for output buffers - decoder is drained.
681 return true;
682 }
683 // Get decoder output.
Per488e75f2015-11-19 10:43:36 +0100684 jobject j_decoder_output_buffer =
685 jni->CallObjectMethod(*j_media_codec_video_decoder_,
686 use_surface_ ? j_dequeue_texture_buffer_method_
687 : j_dequeue_byte_buffer_method_,
688 dequeue_timeout_ms);
689
Alex Glaznev782671f2015-06-12 16:40:44 -0700690 if (CheckException(jni)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700691 ALOGE << "dequeueOutputBuffer() error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700692 return false;
693 }
magjed44bf6f52015-10-03 02:08:00 -0700694 if (IsNull(jni, j_decoder_output_buffer)) {
695 // No decoded frame ready.
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000696 return true;
697 }
698
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000699 // Get decoded video frame properties.
700 int color_format = GetIntField(jni, *j_media_codec_video_decoder_,
701 j_color_format_field_);
702 int width = GetIntField(jni, *j_media_codec_video_decoder_, j_width_field_);
703 int height = GetIntField(jni, *j_media_codec_video_decoder_, j_height_field_);
704 int stride = GetIntField(jni, *j_media_codec_video_decoder_, j_stride_field_);
705 int slice_height = GetIntField(jni, *j_media_codec_video_decoder_,
706 j_slice_height_field_);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000707
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200708 rtc::scoped_refptr<webrtc::VideoFrameBuffer> frame_buffer;
glaznev94291482016-02-01 13:17:18 -0800709 int64_t presentation_timestamps_ms = 0;
Per488e75f2015-11-19 10:43:36 +0100710 int64_t output_timestamps_ms = 0;
711 int64_t output_ntp_timestamps_ms = 0;
712 int decode_time_ms = 0;
713 int64_t frame_delayed_ms = 0;
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200714 if (use_surface_) {
magjed44bf6f52015-10-03 02:08:00 -0700715 // Extract data from Java DecodedTextureBuffer.
glaznevae95ff32016-02-04 11:47:12 -0800716 presentation_timestamps_ms = GetLongField(
717 jni, j_decoder_output_buffer,
718 j_texture_presentation_timestamp_ms_field_);
719 output_timestamps_ms = GetLongField(
720 jni, j_decoder_output_buffer, j_texture_timestamp_ms_field_);
721 output_ntp_timestamps_ms = GetLongField(
722 jni, j_decoder_output_buffer, j_texture_ntp_timestamp_ms_field_);
723 decode_time_ms = GetLongField(
724 jni, j_decoder_output_buffer, j_texture_decode_time_ms_field_);
725
magjed44bf6f52015-10-03 02:08:00 -0700726 const int texture_id =
Per488e75f2015-11-19 10:43:36 +0100727 GetIntField(jni, j_decoder_output_buffer, j_texture_id_field_);
728 if (texture_id != 0) { // |texture_id| == 0 represents a dropped frame.
729 const jfloatArray j_transform_matrix =
730 reinterpret_cast<jfloatArray>(GetObjectField(
731 jni, j_decoder_output_buffer, j_transform_matrix_field_));
glaznev94291482016-02-01 13:17:18 -0800732 frame_delayed_ms = GetLongField(
733 jni, j_decoder_output_buffer, j_texture_frame_delay_ms_field_);
Per488e75f2015-11-19 10:43:36 +0100734
735 // Create webrtc::VideoFrameBuffer with native texture handle.
736 frame_buffer = surface_texture_helper_->CreateTextureFrame(
737 width, height, NativeHandleImpl(jni, texture_id, j_transform_matrix));
glaznevae95ff32016-02-04 11:47:12 -0800738 } else {
739 EnableFrameLogOnWarning();
Per488e75f2015-11-19 10:43:36 +0100740 }
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200741 } else {
742 // Extract data from Java ByteBuffer and create output yuv420 frame -
743 // for non surface decoding only.
glaznev94291482016-02-01 13:17:18 -0800744 const int output_buffer_index = GetIntField(
745 jni, j_decoder_output_buffer, j_info_index_field_);
746 const int output_buffer_offset = GetIntField(
747 jni, j_decoder_output_buffer, j_info_offset_field_);
748 const int output_buffer_size = GetIntField(
749 jni, j_decoder_output_buffer, j_info_size_field_);
750 presentation_timestamps_ms = GetLongField(
751 jni, j_decoder_output_buffer, j_presentation_timestamp_ms_field_);
752 output_timestamps_ms = GetLongField(
753 jni, j_decoder_output_buffer, j_timestamp_ms_field_);
754 output_ntp_timestamps_ms = GetLongField(
755 jni, j_decoder_output_buffer, j_ntp_timestamp_ms_field_);
Per488e75f2015-11-19 10:43:36 +0100756
757 decode_time_ms = GetLongField(jni, j_decoder_output_buffer,
758 j_byte_buffer_decode_time_ms_field_);
magjed44bf6f52015-10-03 02:08:00 -0700759
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000760 if (output_buffer_size < width * height * 3 / 2) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700761 ALOGE << "Insufficient output buffer size: " << output_buffer_size;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000762 return false;
763 }
glaznev3816bfd2016-03-08 10:35:33 -0800764 if (output_buffer_size < stride * height * 3 / 2 &&
765 slice_height == height && stride > width) {
766 // Some codecs (Exynos) incorrectly report stride information for
767 // output byte buffer, so actual stride value need to be corrected.
768 stride = output_buffer_size * 2 / (height * 3);
769 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000770 jobjectArray output_buffers = reinterpret_cast<jobjectArray>(GetObjectField(
771 jni, *j_media_codec_video_decoder_, j_output_buffers_field_));
772 jobject output_buffer =
773 jni->GetObjectArrayElement(output_buffers, output_buffer_index);
774 uint8_t* payload = reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(
775 output_buffer));
Alex Glaznev782671f2015-06-12 16:40:44 -0700776 if (CheckException(jni)) {
777 return false;
778 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000779 payload += output_buffer_offset;
780
781 // Create yuv420 frame.
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200782 frame_buffer = decoded_frame_pool_.CreateBuffer(width, height);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000783 if (color_format == COLOR_FormatYUV420Planar) {
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200784 RTC_CHECK_EQ(0, stride % 2);
785 RTC_CHECK_EQ(0, slice_height % 2);
786 const int uv_stride = stride / 2;
787 const int u_slice_height = slice_height / 2;
788 const uint8_t* y_ptr = payload;
789 const uint8_t* u_ptr = y_ptr + stride * slice_height;
790 const uint8_t* v_ptr = u_ptr + uv_stride * u_slice_height;
791 libyuv::I420Copy(y_ptr, stride,
792 u_ptr, uv_stride,
793 v_ptr, uv_stride,
794 frame_buffer->MutableData(webrtc::kYPlane),
795 frame_buffer->stride(webrtc::kYPlane),
796 frame_buffer->MutableData(webrtc::kUPlane),
797 frame_buffer->stride(webrtc::kUPlane),
798 frame_buffer->MutableData(webrtc::kVPlane),
799 frame_buffer->stride(webrtc::kVPlane),
800 width, height);
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000801 } else {
802 // All other supported formats are nv12.
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200803 const uint8_t* y_ptr = payload;
804 const uint8_t* uv_ptr = y_ptr + stride * slice_height;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000805 libyuv::NV12ToI420(
Magnus Jedvertbbda54e2015-09-30 16:06:37 +0200806 y_ptr, stride,
807 uv_ptr, stride,
808 frame_buffer->MutableData(webrtc::kYPlane),
809 frame_buffer->stride(webrtc::kYPlane),
810 frame_buffer->MutableData(webrtc::kUPlane),
811 frame_buffer->stride(webrtc::kUPlane),
812 frame_buffer->MutableData(webrtc::kVPlane),
813 frame_buffer->stride(webrtc::kVPlane),
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000814 width, height);
815 }
magjed44bf6f52015-10-03 02:08:00 -0700816 // Return output byte buffer back to codec.
817 jni->CallVoidMethod(
818 *j_media_codec_video_decoder_,
819 j_return_decoded_byte_buffer_method_,
820 output_buffer_index);
821 if (CheckException(jni)) {
Per488e75f2015-11-19 10:43:36 +0100822 ALOGE << "returnDecodedOutputBuffer error";
magjed44bf6f52015-10-03 02:08:00 -0700823 return false;
824 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000825 }
glaznevae95ff32016-02-04 11:47:12 -0800826 if (frames_decoded_ < frames_decoded_logged_) {
glaznev94291482016-02-01 13:17:18 -0800827 ALOGD << "Decoder frame out # " << frames_decoded_ <<
828 ". " << width << " x " << height <<
829 ". " << stride << " x " << slice_height <<
830 ". Color: " << color_format <<
831 ". TS: " << presentation_timestamps_ms <<
Per488e75f2015-11-19 10:43:36 +0100832 ". DecTime: " << (int)decode_time_ms <<
833 ". DelayTime: " << (int)frame_delayed_ms;
glazneve55c42c2015-10-28 10:30:32 -0700834 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000835
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000836 // Calculate and print decoding statistics - every 3 seconds.
837 frames_decoded_++;
838 current_frames_++;
Per488e75f2015-11-19 10:43:36 +0100839 current_decoding_time_ms_ += decode_time_ms;
glaznevfd6706a2016-02-05 14:05:08 -0800840 current_delay_time_ms_ += frame_delayed_ms;
Niels Möllerd28db7f2016-05-10 16:31:47 +0200841 int statistic_time_ms = rtc::TimeMillis() - start_time_ms_;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000842 if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
843 current_frames_ > 0) {
glaznev94291482016-02-01 13:17:18 -0800844 int current_bitrate = current_bytes_ * 8 / statistic_time_ms;
845 int current_fps =
846 (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms;
glaznevfd6706a2016-02-05 14:05:08 -0800847 ALOGD << "Frames decoded: " << frames_decoded_ <<
848 ". Received: " << frames_received_ <<
glaznev94291482016-02-01 13:17:18 -0800849 ". Bitrate: " << current_bitrate << " kbps" <<
850 ". Fps: " << current_fps <<
851 ". DecTime: " << (current_decoding_time_ms_ / current_frames_) <<
glaznevfd6706a2016-02-05 14:05:08 -0800852 ". DelayTime: " << (current_delay_time_ms_ / current_frames_) <<
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700853 " for last " << statistic_time_ms << " ms.";
Niels Möllerd28db7f2016-05-10 16:31:47 +0200854 start_time_ms_ = rtc::TimeMillis();
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000855 current_frames_ = 0;
856 current_bytes_ = 0;
857 current_decoding_time_ms_ = 0;
glaznevfd6706a2016-02-05 14:05:08 -0800858 current_delay_time_ms_ = 0;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000859 }
860
nisse94cd3fa2016-05-23 23:35:54 -0700861 // If the frame was dropped, frame_buffer is left as nullptr.
862 if (frame_buffer) {
863 VideoFrame decoded_frame(frame_buffer, 0, 0, webrtc::kVideoRotation_0);
864 decoded_frame.set_timestamp(output_timestamps_ms);
865 decoded_frame.set_ntp_time_ms(output_ntp_timestamps_ms);
866
Per488e75f2015-11-19 10:43:36 +0100867 const int32_t callback_status =
868 callback_->Decoded(decoded_frame, decode_time_ms);
869 if (callback_status > 0) {
870 ALOGE << "callback error";
871 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000872 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000873 return true;
874}
875
876int32_t MediaCodecVideoDecoder::RegisterDecodeCompleteCallback(
877 DecodedImageCallback* callback) {
878 callback_ = callback;
879 return WEBRTC_VIDEO_CODEC_OK;
880}
881
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000882void MediaCodecVideoDecoder::OnMessage(rtc::Message* msg) {
883 JNIEnv* jni = AttachCurrentThreadIfNeeded();
884 ScopedLocalRefFrame local_ref_frame(jni);
885 if (!inited_) {
886 return;
887 }
888 // We only ever send one message to |this| directly (not through a Bind()'d
889 // functor), so expect no ID/data.
henrikg91d6ede2015-09-17 00:24:34 -0700890 RTC_CHECK(!msg->message_id) << "Unexpected message!";
891 RTC_CHECK(!msg->pdata) << "Unexpected message!";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000892 CheckOnCodecThread();
893
894 if (!DeliverPendingOutputs(jni, 0)) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700895 ALOGE << "OnMessage: DeliverPendingOutputs error";
Alex Glaznev782671f2015-06-12 16:40:44 -0700896 ProcessHWErrorOnCodecThread();
897 return;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000898 }
899 codec_thread_->PostDelayed(kMediaCodecPollMs, this);
900}
901
perkj461121c2016-02-15 06:28:36 -0800902MediaCodecVideoDecoderFactory::MediaCodecVideoDecoderFactory()
903 : egl_context_(nullptr) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700904 ALOGD << "MediaCodecVideoDecoderFactory ctor";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000905 JNIEnv* jni = AttachCurrentThreadIfNeeded();
906 ScopedLocalRefFrame local_ref_frame(jni);
907 jclass j_decoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoDecoder");
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000908 supported_codec_types_.clear();
909
910 bool is_vp8_hw_supported = jni->CallStaticBooleanMethod(
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000911 j_decoder_class,
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000912 GetStaticMethodID(jni, j_decoder_class, "isVp8HwSupported", "()Z"));
Alex Glaznev782671f2015-06-12 16:40:44 -0700913 if (CheckException(jni)) {
914 is_vp8_hw_supported = false;
915 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000916 if (is_vp8_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700917 ALOGD << "VP8 HW Decoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000918 supported_codec_types_.push_back(kVideoCodecVP8);
919 }
920
Alex Glaznev69a7fd52015-11-10 10:25:40 -0800921 bool is_vp9_hw_supported = jni->CallStaticBooleanMethod(
922 j_decoder_class,
923 GetStaticMethodID(jni, j_decoder_class, "isVp9HwSupported", "()Z"));
924 if (CheckException(jni)) {
925 is_vp9_hw_supported = false;
926 }
927 if (is_vp9_hw_supported) {
928 ALOGD << "VP9 HW Decoder supported.";
929 supported_codec_types_.push_back(kVideoCodecVP9);
930 }
931
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000932 bool is_h264_hw_supported = jni->CallStaticBooleanMethod(
933 j_decoder_class,
934 GetStaticMethodID(jni, j_decoder_class, "isH264HwSupported", "()Z"));
Alex Glaznev782671f2015-06-12 16:40:44 -0700935 if (CheckException(jni)) {
936 is_h264_hw_supported = false;
937 }
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000938 if (is_h264_hw_supported) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700939 ALOGD << "H264 HW Decoder supported.";
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000940 supported_codec_types_.push_back(kVideoCodecH264);
941 }
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000942}
943
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700944MediaCodecVideoDecoderFactory::~MediaCodecVideoDecoderFactory() {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700945 ALOGD << "MediaCodecVideoDecoderFactory dtor";
perkj461121c2016-02-15 06:28:36 -0800946 if (egl_context_) {
947 JNIEnv* jni = AttachCurrentThreadIfNeeded();
948 jni->DeleteGlobalRef(egl_context_);
949 }
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700950}
951
952void MediaCodecVideoDecoderFactory::SetEGLContext(
perkj461121c2016-02-15 06:28:36 -0800953 JNIEnv* jni, jobject egl_context) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700954 ALOGD << "MediaCodecVideoDecoderFactory::SetEGLContext";
Perfd22e6c2016-02-18 11:35:48 +0100955 if (egl_context_) {
956 jni->DeleteGlobalRef(egl_context_);
957 egl_context_ = nullptr;
958 }
perkj461121c2016-02-15 06:28:36 -0800959 egl_context_ = jni->NewGlobalRef(egl_context);
960 if (CheckException(jni)) {
961 ALOGE << "error calling NewGlobalRef for EGL Context.";
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700962 }
963}
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000964
965webrtc::VideoDecoder* MediaCodecVideoDecoderFactory::CreateVideoDecoder(
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000966 VideoCodecType type) {
967 if (supported_codec_types_.empty()) {
Alex Glaznevad948c42015-11-18 13:06:42 -0800968 ALOGW << "No HW video decoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +0100969 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000970 }
Alex Glaznev4d2f4d12015-09-01 15:04:13 -0700971 for (VideoCodecType codec_type : supported_codec_types_) {
972 if (codec_type == type) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700973 ALOGD << "Create HW video decoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +0100974 return new MediaCodecVideoDecoder(AttachCurrentThreadIfNeeded(), type,
perkj461121c2016-02-15 06:28:36 -0800975 egl_context_);
glaznev@webrtc.orgb28474c2015-02-23 17:44:27 +0000976 }
977 }
Alex Glaznevad948c42015-11-18 13:06:42 -0800978 ALOGW << "Can not find HW video decoder for type " << (int)type;
Perec2922f2016-01-27 15:25:46 +0100979 return nullptr;
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000980}
981
982void MediaCodecVideoDecoderFactory::DestroyVideoDecoder(
983 webrtc::VideoDecoder* decoder) {
Alex Glaznevfddf6e52015-10-07 16:51:02 -0700984 ALOGD << "Destroy video decoder.";
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000985 delete decoder;
986}
987
Peter Boströmb7d9a972015-12-18 16:01:11 +0100988const char* MediaCodecVideoDecoder::ImplementationName() const {
989 return "MediaCodec";
990}
991
glaznev@webrtc.org18c92472015-02-18 18:42:55 +0000992} // namespace webrtc_jni