1 /*****************************************************************************
2 * android_mediacodec.c: Video decoder module using the Android MediaCodec API
3 *****************************************************************************
4 * Copyright (C) 2012 Martin Storsjo
6 * Authors: Martin Storsjo <martin@martin.st>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21 *****************************************************************************/
23 /*****************************************************************************
25 *****************************************************************************/
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_codec.h>
36 #include <vlc_block_helper.h>
39 #include "../h264_nal.h"
40 #include "../hevc_nal.h"
42 #include <OMX_Component.h>
43 #include "omxil_utils.h"
44 #include "android_opaque.h"
45 #include "../../video_output/android/android_window.h"
47 #define INFO_OUTPUT_BUFFERS_CHANGED -3
48 #define INFO_OUTPUT_FORMAT_CHANGED -2
49 #define INFO_TRY_AGAIN_LATER -1
51 #define THREAD_NAME "android_mediacodec"
53 extern int jni_attach_thread(JNIEnv **env, const char *thread_name);
54 extern void jni_detach_thread();
55 /* JNI functions to get/set an Android Surface object. */
56 extern jobject jni_LockAndGetAndroidJavaSurface();
57 extern void jni_UnlockAndroidSurface();
58 extern void jni_EventHardwareAccelerationError();
59 extern bool jni_IsVideoPlayerActivityCreated();
61 /* Implementation of a circular buffer of timestamps with overwriting
62 * of older values. MediaCodec has only one type of timestamp, if a
63 * block has no PTS, we send the DTS instead. Some hardware decoders
64 * cannot cope with this situation and output the frames in the wrong
65 * order. As a workaround in this case, we use a FIFO of timestamps in
66 * order to remember which input packets had no PTS. Since an
67 * hardware decoder can silently drop frames, this might cause a
68 * growing desynchronization with the actual timestamp. Thus the
69 * circular buffer has a limited size and will overwrite older values.
79 static timestamp_fifo_t *timestamp_FifoNew(uint32_t capacity)
81 timestamp_fifo_t *fifo = calloc(1, sizeof(*fifo));
84 fifo->buffer = malloc(capacity * sizeof(*fifo->buffer));
89 fifo->capacity = capacity;
93 static void timestamp_FifoRelease(timestamp_fifo_t *fifo)
99 static bool timestamp_FifoIsEmpty(timestamp_fifo_t *fifo)
101 return fifo->size == 0;
104 static bool timestamp_FifoIsFull(timestamp_fifo_t *fifo)
106 return fifo->size == fifo->capacity;
109 static void timestamp_FifoEmpty(timestamp_fifo_t *fifo)
114 static void timestamp_FifoPut(timestamp_fifo_t *fifo, int64_t ts)
116 uint32_t end = (fifo->begin + fifo->size) % fifo->capacity;
117 fifo->buffer[end] = ts;
118 if (!timestamp_FifoIsFull(fifo))
121 fifo->begin = (fifo->begin + 1) % fifo->capacity;
124 static int64_t timestamp_FifoGet(timestamp_fifo_t *fifo)
126 if (timestamp_FifoIsEmpty(fifo))
127 return VLC_TS_INVALID;
129 int64_t result = fifo->buffer[fifo->begin];
130 fifo->begin = (fifo->begin + 1) % fifo->capacity;
137 jclass media_codec_list_class, media_codec_class, media_format_class;
138 jclass buffer_info_class, byte_buffer_class;
140 jmethodID get_codec_count, get_codec_info_at, is_encoder, get_capabilities_for_type;
141 jfieldID profile_levels_field, profile_field, level_field;
142 jmethodID get_supported_types, get_name;
143 jmethodID create_by_codec_name, configure, start, stop, flush, release;
144 jmethodID get_output_format;
145 jmethodID get_input_buffers, get_input_buffer;
146 jmethodID get_output_buffers, get_output_buffer;
147 jmethodID dequeue_input_buffer, dequeue_output_buffer, queue_input_buffer;
148 jmethodID release_output_buffer;
149 jmethodID create_video_format, set_integer, set_bytebuffer, get_integer;
150 jmethodID buffer_info_ctor;
151 jmethodID allocate_direct, limit;
152 jfieldID size_field, offset_field, pts_field;
158 jobject input_buffers, output_buffers;
160 int stride, slice_height;
167 bool error_event_sent;
169 ArchitectureSpecificCopyData architecture_specific_data;
171 /* Direct rendering members. */
172 bool direct_rendering;
173 picture_t** pp_inflight_pictures; /**< stores the inflight picture for each output buffer or NULL */
174 unsigned int i_inflight_pictures;
176 timestamp_fifo_t *timestamp_fifo;
181 METHOD, STATIC_METHOD, FIELD
184 #define OFF(x) offsetof(struct decoder_sys_t, x)
190 static const struct classname classes[] = {
191 { "android/media/MediaCodecList", OFF(media_codec_list_class) },
192 { "android/media/MediaCodec", OFF(media_codec_class) },
193 { "android/media/MediaFormat", OFF(media_format_class) },
194 { "android/media/MediaFormat", OFF(media_format_class) },
195 { "android/media/MediaCodec$BufferInfo", OFF(buffer_info_class) },
196 { "java/nio/ByteBuffer", OFF(byte_buffer_class) },
209 static const struct member members[] = {
210 { "toString", "()Ljava/lang/String;", "java/lang/Object", OFF(tostring), METHOD, true },
212 { "getCodecCount", "()I", "android/media/MediaCodecList", OFF(get_codec_count), STATIC_METHOD, true },
213 { "getCodecInfoAt", "(I)Landroid/media/MediaCodecInfo;", "android/media/MediaCodecList", OFF(get_codec_info_at), STATIC_METHOD, true },
215 { "isEncoder", "()Z", "android/media/MediaCodecInfo", OFF(is_encoder), METHOD, true },
216 { "getSupportedTypes", "()[Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_supported_types), METHOD, true },
217 { "getName", "()Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_name), METHOD, true },
218 { "getCapabilitiesForType", "(Ljava/lang/String;)Landroid/media/MediaCodecInfo$CodecCapabilities;", "android/media/MediaCodecInfo", OFF(get_capabilities_for_type), METHOD, true },
220 { "profileLevels", "[Landroid/media/MediaCodecInfo$CodecProfileLevel;", "android/media/MediaCodecInfo$CodecCapabilities", OFF(profile_levels_field), FIELD, true },
221 { "profile", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(profile_field), FIELD, true },
222 { "level", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(level_field), FIELD, true },
224 { "createByCodecName", "(Ljava/lang/String;)Landroid/media/MediaCodec;", "android/media/MediaCodec", OFF(create_by_codec_name), STATIC_METHOD, true },
225 { "configure", "(Landroid/media/MediaFormat;Landroid/view/Surface;Landroid/media/MediaCrypto;I)V", "android/media/MediaCodec", OFF(configure), METHOD, true },
226 { "start", "()V", "android/media/MediaCodec", OFF(start), METHOD, true },
227 { "stop", "()V", "android/media/MediaCodec", OFF(stop), METHOD, true },
228 { "flush", "()V", "android/media/MediaCodec", OFF(flush), METHOD, true },
229 { "release", "()V", "android/media/MediaCodec", OFF(release), METHOD, true },
230 { "getOutputFormat", "()Landroid/media/MediaFormat;", "android/media/MediaCodec", OFF(get_output_format), METHOD, true },
231 { "getInputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_input_buffers), METHOD, false },
232 { "getInputBuffer", "(I)Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_input_buffer), METHOD, false },
233 { "getOutputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_output_buffers), METHOD, false },
234 { "getOutputBuffer", "(I)Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_output_buffer), METHOD, false },
235 { "dequeueInputBuffer", "(J)I", "android/media/MediaCodec", OFF(dequeue_input_buffer), METHOD, true },
236 { "dequeueOutputBuffer", "(Landroid/media/MediaCodec$BufferInfo;J)I", "android/media/MediaCodec", OFF(dequeue_output_buffer), METHOD, true },
237 { "queueInputBuffer", "(IIIJI)V", "android/media/MediaCodec", OFF(queue_input_buffer), METHOD, true },
238 { "releaseOutputBuffer", "(IZ)V", "android/media/MediaCodec", OFF(release_output_buffer), METHOD, true },
240 { "createVideoFormat", "(Ljava/lang/String;II)Landroid/media/MediaFormat;", "android/media/MediaFormat", OFF(create_video_format), STATIC_METHOD, true },
241 { "setInteger", "(Ljava/lang/String;I)V", "android/media/MediaFormat", OFF(set_integer), METHOD, true },
242 { "getInteger", "(Ljava/lang/String;)I", "android/media/MediaFormat", OFF(get_integer), METHOD, true },
243 { "setByteBuffer", "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V", "android/media/MediaFormat", OFF(set_bytebuffer), METHOD, true },
245 { "<init>", "()V", "android/media/MediaCodec$BufferInfo", OFF(buffer_info_ctor), METHOD, true },
246 { "size", "I", "android/media/MediaCodec$BufferInfo", OFF(size_field), FIELD, true },
247 { "offset", "I", "android/media/MediaCodec$BufferInfo", OFF(offset_field), FIELD, true },
248 { "presentationTimeUs", "J", "android/media/MediaCodec$BufferInfo", OFF(pts_field), FIELD, true },
250 { "allocateDirect", "(I)Ljava/nio/ByteBuffer;", "java/nio/ByteBuffer", OFF(allocate_direct), STATIC_METHOD, true },
251 { "limit", "(I)Ljava/nio/Buffer;", "java/nio/ByteBuffer", OFF(limit), METHOD, true },
253 { NULL, NULL, NULL, 0, 0, false },
256 #define GET_INTEGER(obj, name) (*env)->CallIntMethod(env, obj, p_sys->get_integer, (*env)->NewStringUTF(env, name))
258 /*****************************************************************************
260 *****************************************************************************/
261 static int OpenDecoder(vlc_object_t *);
262 static void CloseDecoder(vlc_object_t *);
264 static picture_t *DecodeVideo(decoder_t *, block_t **);
266 static void InvalidateAllPictures(decoder_t *);
267 static int InsertInflightPicture(decoder_t *, picture_t *, unsigned int );
269 /*****************************************************************************
271 *****************************************************************************/
272 #define DIRECTRENDERING_TEXT N_("Android direct rendering")
273 #define DIRECTRENDERING_LONGTEXT N_(\
274 "Enable Android direct rendering using opaque buffers.")
276 #define CFG_PREFIX "mediacodec-"
279 set_description( N_("Video decoder using Android MediaCodec") )
280 set_category( CAT_INPUT )
281 set_subcategory( SUBCAT_INPUT_VCODEC )
282 set_section( N_("Decoding") , NULL )
283 set_capability( "decoder", 0 ) /* Only enabled via commandline arguments */
284 add_bool(CFG_PREFIX "dr", true,
285 DIRECTRENDERING_TEXT, DIRECTRENDERING_LONGTEXT, true)
286 set_callbacks( OpenDecoder, CloseDecoder )
289 static int jstrcmp(JNIEnv* env, jobject str, const char* str2)
291 jsize len = (*env)->GetStringUTFLength(env, str);
292 if (len != (jsize) strlen(str2))
294 const char *ptr = (*env)->GetStringUTFChars(env, str, NULL);
295 int ret = memcmp(ptr, str2, len);
296 (*env)->ReleaseStringUTFChars(env, str, ptr);
300 /*****************************************************************************
301 * OpenDecoder: Create the decoder instance
302 *****************************************************************************/
303 static int OpenDecoder(vlc_object_t *p_this)
305 decoder_t *p_dec = (decoder_t*)p_this;
306 decoder_sys_t *p_sys;
308 if (p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
311 const char *mime = NULL;
312 switch (p_dec->fmt_in.i_codec) {
313 case VLC_CODEC_HEVC: mime = "video/hevc"; break;
314 case VLC_CODEC_H264: mime = "video/avc"; break;
315 case VLC_CODEC_H263: mime = "video/3gpp"; break;
316 case VLC_CODEC_MP4V: mime = "video/mp4v-es"; break;
317 case VLC_CODEC_WMV3: mime = "video/x-ms-wmv"; break;
318 case VLC_CODEC_VC1: mime = "video/wvc1"; break;
319 case VLC_CODEC_VP8: mime = "video/x-vnd.on2.vp8"; break;
320 case VLC_CODEC_VP9: mime = "video/x-vnd.on2.vp9"; break;
322 msg_Dbg(p_dec, "codec %4.4s not supported", (char *)&p_dec->fmt_in.i_codec);
326 size_t fmt_profile = 0;
327 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264)
328 h264_get_profile_level(&p_dec->fmt_in, &fmt_profile, NULL, NULL);
330 /* Allocate the memory needed to store the decoder's structure */
331 if ((p_dec->p_sys = p_sys = calloc(1, sizeof(*p_sys))) == NULL)
334 p_dec->pf_decode_video = DecodeVideo;
336 p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
337 p_dec->fmt_out.video = p_dec->fmt_in.video;
338 p_dec->fmt_out.audio = p_dec->fmt_in.audio;
339 p_dec->b_need_packetized = true;
342 jni_attach_thread(&env, THREAD_NAME);
344 for (int i = 0; classes[i].name; i++) {
345 *(jclass*)((uint8_t*)p_sys + classes[i].offset) =
346 (*env)->FindClass(env, classes[i].name);
348 if ((*env)->ExceptionOccurred(env)) {
349 msg_Warn(p_dec, "Unable to find class %s", classes[i].name);
350 (*env)->ExceptionClear(env);
356 for (int i = 0; members[i].name; i++) {
357 if (i == 0 || strcmp(members[i].class, members[i - 1].class))
358 last_class = (*env)->FindClass(env, members[i].class);
360 if ((*env)->ExceptionOccurred(env)) {
361 msg_Warn(p_dec, "Unable to find class %s", members[i].class);
362 (*env)->ExceptionClear(env);
366 switch (members[i].type) {
368 *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
369 (*env)->GetMethodID(env, last_class, members[i].name, members[i].sig);
372 *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
373 (*env)->GetStaticMethodID(env, last_class, members[i].name, members[i].sig);
376 *(jfieldID*)((uint8_t*)p_sys + members[i].offset) =
377 (*env)->GetFieldID(env, last_class, members[i].name, members[i].sig);
380 if ((*env)->ExceptionOccurred(env)) {
381 msg_Warn(p_dec, "Unable to find the member %s in %s",
382 members[i].name, members[i].class);
383 (*env)->ExceptionClear(env);
384 if (members[i].critical)
388 /* getInputBuffers and getOutputBuffers are deprecated if API >= 21
389 * use getInputBuffer and getOutputBuffer instead. */
390 if (p_sys->get_input_buffer && p_sys->get_output_buffer) {
391 p_sys->get_output_buffers =
392 p_sys->get_input_buffers = NULL;
393 } else if (!p_sys->get_output_buffers && !p_sys->get_input_buffers) {
394 msg_Warn(p_dec, "Unable to find get Output/Input Buffer/Buffers");
398 int num_codecs = (*env)->CallStaticIntMethod(env, p_sys->media_codec_list_class,
399 p_sys->get_codec_count);
400 jobject codec_name = NULL;
402 for (int i = 0; i < num_codecs; i++) {
403 jobject codec_capabilities = NULL;
404 jobject profile_levels = NULL;
407 jobject types = NULL;
409 int profile_levels_len = 0, num_types = 0;
410 const char *name_ptr = NULL;
413 info = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_list_class,
414 p_sys->get_codec_info_at, i);
415 if ((*env)->CallBooleanMethod(env, info, p_sys->is_encoder))
418 codec_capabilities = (*env)->CallObjectMethod(env, info, p_sys->get_capabilities_for_type,
419 (*env)->NewStringUTF(env, mime));
420 if ((*env)->ExceptionOccurred(env)) {
421 msg_Warn(p_dec, "Exception occurred in MediaCodecInfo.getCapabilitiesForType");
422 (*env)->ExceptionClear(env);
424 } else if (codec_capabilities) {
425 profile_levels = (*env)->GetObjectField(env, codec_capabilities, p_sys->profile_levels_field);
427 profile_levels_len = (*env)->GetArrayLength(env, profile_levels);
429 msg_Dbg(p_dec, "Number of profile levels: %d", profile_levels_len);
431 types = (*env)->CallObjectMethod(env, info, p_sys->get_supported_types);
432 num_types = (*env)->GetArrayLength(env, types);
433 name = (*env)->CallObjectMethod(env, info, p_sys->get_name);
434 name_len = (*env)->GetStringUTFLength(env, name);
435 name_ptr = (*env)->GetStringUTFChars(env, name, NULL);
438 if (!strncmp(name_ptr, "OMX.google.", __MIN(11, name_len)))
440 for (int j = 0; j < num_types && !found; j++) {
441 jobject type = (*env)->GetObjectArrayElement(env, types, j);
442 if (!jstrcmp(env, type, mime)) {
443 /* The mime type is matching for this component. We
444 now check if the capabilities of the codec is
445 matching the video format. */
446 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && fmt_profile) {
447 for (int i = 0; i < profile_levels_len && !found; ++i) {
448 jobject profile_level = (*env)->GetObjectArrayElement(env, profile_levels, i);
450 int omx_profile = (*env)->GetIntField(env, profile_level, p_sys->profile_field);
451 size_t codec_profile = convert_omx_to_profile_idc(omx_profile);
452 (*env)->DeleteLocalRef(env, profile_level);
453 if (codec_profile != fmt_profile)
455 /* Some encoders set the level too high, thus we ignore it for the moment.
456 We could try to guess the actual profile based on the resolution. */
463 (*env)->DeleteLocalRef(env, type);
466 msg_Dbg(p_dec, "using %.*s", name_len, name_ptr);
467 p_sys->name = malloc(name_len + 1);
468 memcpy(p_sys->name, name_ptr, name_len);
469 p_sys->name[name_len] = '\0';
474 (*env)->ReleaseStringUTFChars(env, name, name_ptr);
476 (*env)->DeleteLocalRef(env, profile_levels);
478 (*env)->DeleteLocalRef(env, types);
479 if (codec_capabilities)
480 (*env)->DeleteLocalRef(env, codec_capabilities);
482 (*env)->DeleteLocalRef(env, info);
488 msg_Dbg(p_dec, "No suitable codec matching %s was found", mime);
492 // This method doesn't handle errors nicely, it crashes if the codec isn't found.
493 // (The same goes for createDecoderByType.) This is fixed in latest AOSP and in 4.2,
494 // but not in 4.1 devices.
495 p_sys->codec = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_class,
496 p_sys->create_by_codec_name, codec_name);
497 if ((*env)->ExceptionOccurred(env)) {
498 msg_Warn(p_dec, "Exception occurred in MediaCodec.createByCodecName.");
499 (*env)->ExceptionClear(env);
502 p_sys->allocated = true;
503 p_sys->codec = (*env)->NewGlobalRef(env, p_sys->codec);
505 jobject format = (*env)->CallStaticObjectMethod(env, p_sys->media_format_class,
506 p_sys->create_video_format, (*env)->NewStringUTF(env, mime),
507 p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height);
509 if (p_dec->fmt_in.i_extra) {
510 // Allocate a byte buffer via allocateDirect in java instead of NewDirectByteBuffer,
511 // since the latter doesn't allocate storage of its own, and we don't know how long
512 // the codec uses the buffer.
513 int buf_size = p_dec->fmt_in.i_extra + 20;
514 jobject bytebuf = (*env)->CallStaticObjectMethod(env, p_sys->byte_buffer_class,
515 p_sys->allocate_direct, buf_size);
516 uint32_t size = p_dec->fmt_in.i_extra;
517 uint8_t *ptr = (*env)->GetDirectBufferAddress(env, bytebuf);
518 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && ((uint8_t*)p_dec->fmt_in.p_extra)[0] == 1) {
519 convert_sps_pps(p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
521 &size, &p_sys->nal_size);
522 } else if (p_dec->fmt_in.i_codec == VLC_CODEC_HEVC) {
523 convert_hevc_nal_units(p_dec, p_dec->fmt_in.p_extra,
524 p_dec->fmt_in.i_extra, ptr, buf_size,
525 &size, &p_sys->nal_size);
527 memcpy(ptr, p_dec->fmt_in.p_extra, size);
529 (*env)->CallObjectMethod(env, bytebuf, p_sys->limit, size);
530 (*env)->CallVoidMethod(env, format, p_sys->set_bytebuffer,
531 (*env)->NewStringUTF(env, "csd-0"), bytebuf);
532 (*env)->DeleteLocalRef(env, bytebuf);
535 /* If the VideoPlayerActivity is not started, MediaCodec opaque
536 direct rendering should be disabled since no surface will be
537 attached to the JNI. */
538 p_sys->direct_rendering = jni_IsVideoPlayerActivityCreated() && var_InheritBool(p_dec, CFG_PREFIX "dr");
539 if (p_sys->direct_rendering) {
540 if (p_dec->fmt_in.video.orientation != ORIENT_NORMAL) {
543 switch (p_dec->fmt_in.video.orientation) {
544 case ORIENT_ROTATED_90:
547 case ORIENT_ROTATED_180:
550 case ORIENT_ROTATED_270:
556 (*env)->CallVoidMethod(env, format, p_sys->set_integer,
557 (*env)->NewStringUTF(env, "rotation-degrees"),
561 jobject surf = jni_LockAndGetAndroidJavaSurface();
563 // Configure MediaCodec with the Android surface.
564 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, surf, NULL, 0);
565 if ((*env)->ExceptionOccurred(env)) {
566 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure with an output surface.");
567 (*env)->ExceptionClear(env);
568 jni_UnlockAndroidSurface();
571 p_dec->fmt_out.i_codec = VLC_CODEC_ANDROID_OPAQUE;
573 msg_Warn(p_dec, "Failed to get the Android Surface, disabling direct rendering.");
574 p_sys->direct_rendering = false;
576 jni_UnlockAndroidSurface();
578 if (!p_sys->direct_rendering) {
579 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, NULL, NULL, 0);
580 if ((*env)->ExceptionOccurred(env)) {
581 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure");
582 (*env)->ExceptionClear(env);
587 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->start);
588 if ((*env)->ExceptionOccurred(env)) {
589 msg_Warn(p_dec, "Exception occurred in MediaCodec.start");
590 (*env)->ExceptionClear(env);
593 p_sys->started = true;
595 if (p_sys->get_input_buffers && p_sys->get_output_buffers) {
596 p_sys->input_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffers);
597 p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_buffers);
598 p_sys->input_buffers = (*env)->NewGlobalRef(env, p_sys->input_buffers);
599 p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
601 p_sys->buffer_info = (*env)->NewObject(env, p_sys->buffer_info_class, p_sys->buffer_info_ctor);
602 p_sys->buffer_info = (*env)->NewGlobalRef(env, p_sys->buffer_info);
603 (*env)->DeleteLocalRef(env, format);
607 const int timestamp_fifo_size = 32;
608 p_sys->timestamp_fifo = timestamp_FifoNew(timestamp_fifo_size);
609 if (!p_sys->timestamp_fifo)
616 CloseDecoder(p_this);
620 static void CloseDecoder(vlc_object_t *p_this)
622 decoder_t *p_dec = (decoder_t *)p_this;
623 decoder_sys_t *p_sys = p_dec->p_sys;
629 /* Invalidate all pictures that are currently in flight in order
630 * to prevent the vout from using destroyed output buffers. */
631 if (p_sys->direct_rendering)
632 InvalidateAllPictures(p_dec);
633 jni_attach_thread(&env, THREAD_NAME);
634 if (p_sys->input_buffers)
635 (*env)->DeleteGlobalRef(env, p_sys->input_buffers);
636 if (p_sys->output_buffers)
637 (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
641 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->stop);
642 if ((*env)->ExceptionOccurred(env)) {
643 msg_Err(p_dec, "Exception in MediaCodec.stop");
644 (*env)->ExceptionClear(env);
647 if (p_sys->allocated)
649 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release);
650 if ((*env)->ExceptionOccurred(env)) {
651 msg_Err(p_dec, "Exception in MediaCodec.release");
652 (*env)->ExceptionClear(env);
655 (*env)->DeleteGlobalRef(env, p_sys->codec);
657 if (p_sys->buffer_info)
658 (*env)->DeleteGlobalRef(env, p_sys->buffer_info);
662 ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
663 free(p_sys->pp_inflight_pictures);
664 if (p_sys->timestamp_fifo)
665 timestamp_FifoRelease(p_sys->timestamp_fifo);
669 /*****************************************************************************
671 *****************************************************************************/
672 static void UnlockPicture(picture_t* p_pic, bool b_render)
674 picture_sys_t *p_picsys = p_pic->p_sys;
675 decoder_t *p_dec = p_picsys->priv.hw.p_dec;
676 decoder_sys_t *p_sys = p_dec->p_sys;
678 if (!p_picsys->priv.hw.b_valid)
681 vlc_mutex_lock(get_android_opaque_mutex());
683 /* Picture might have been invalidated while waiting on the mutex. */
684 if (!p_picsys->priv.hw.b_valid) {
685 vlc_mutex_unlock(get_android_opaque_mutex());
689 uint32_t i_index = p_picsys->priv.hw.i_index;
690 InsertInflightPicture(p_dec, NULL, i_index);
692 /* Release the MediaCodec buffer. */
694 jni_attach_thread(&env, THREAD_NAME);
695 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_index, b_render);
696 if ((*env)->ExceptionOccurred(env)) {
697 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (DisplayBuffer)");
698 (*env)->ExceptionClear(env);
702 p_picsys->priv.hw.b_valid = false;
704 vlc_mutex_unlock(get_android_opaque_mutex());
707 static void InvalidateAllPictures(decoder_t *p_dec)
709 decoder_sys_t *p_sys = p_dec->p_sys;
711 vlc_mutex_lock(get_android_opaque_mutex());
713 for (unsigned int i = 0; i < p_sys->i_inflight_pictures; ++i) {
714 picture_t *p_pic = p_sys->pp_inflight_pictures[i];
716 p_pic->p_sys->priv.hw.b_valid = false;
717 p_sys->pp_inflight_pictures[i] = NULL;
720 vlc_mutex_unlock(get_android_opaque_mutex());
723 static int InsertInflightPicture(decoder_t *p_dec, picture_t *p_pic,
724 unsigned int i_index)
726 decoder_sys_t *p_sys = p_dec->p_sys;
728 if (i_index >= p_sys->i_inflight_pictures) {
729 picture_t **pp_pics = realloc(p_sys->pp_inflight_pictures,
730 (i_index + 1) * sizeof (picture_t *));
733 if (i_index - p_sys->i_inflight_pictures > 0)
734 memset(&pp_pics[p_sys->i_inflight_pictures], 0,
735 (i_index - p_sys->i_inflight_pictures) * sizeof (picture_t *));
736 p_sys->pp_inflight_pictures = pp_pics;
737 p_sys->i_inflight_pictures = i_index + 1;
739 p_sys->pp_inflight_pictures[i_index] = p_pic;
743 static void GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
745 decoder_sys_t *p_sys = p_dec->p_sys;
747 int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_output_buffer,
748 p_sys->buffer_info, timeout);
749 if ((*env)->ExceptionOccurred(env)) {
750 msg_Err(p_dec, "Exception in MediaCodec.dequeueOutputBuffer (GetOutput)");
751 (*env)->ExceptionClear(env);
752 p_sys->error_state = true;
757 if (!p_sys->pixel_format) {
758 msg_Warn(p_dec, "Buffers returned before output format is set, dropping frame");
759 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
760 if ((*env)->ExceptionOccurred(env)) {
761 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer");
762 (*env)->ExceptionClear(env);
763 p_sys->error_state = true;
770 *pp_pic = decoder_NewPicture(p_dec);
771 } else if (p_sys->direct_rendering) {
772 picture_t *p_pic = *pp_pic;
773 picture_sys_t *p_picsys = p_pic->p_sys;
774 int i_prev_index = p_picsys->priv.hw.i_index;
775 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_prev_index, false);
776 if ((*env)->ExceptionOccurred(env)) {
777 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer " \
778 "(GetOutput, overwriting previous picture)");
779 (*env)->ExceptionClear(env);
780 p_sys->error_state = true;
784 // No need to lock here since the previous picture was not sent.
785 InsertInflightPicture(p_dec, NULL, i_prev_index);
789 picture_t *p_pic = *pp_pic;
790 /* If the oldest input block had no PTS, the timestamp
791 * of the frame returned by MediaCodec might be wrong
792 * so we overwrite it with the corresponding dts. */
793 int64_t forced_ts = timestamp_FifoGet(p_sys->timestamp_fifo);
794 if (forced_ts == VLC_TS_INVALID)
795 p_pic->date = (*env)->GetLongField(env, p_sys->buffer_info, p_sys->pts_field);
797 p_pic->date = forced_ts;
799 if (p_sys->direct_rendering) {
800 picture_sys_t *p_picsys = p_pic->p_sys;
801 p_picsys->pf_lock_pic = NULL;
802 p_picsys->pf_unlock_pic = UnlockPicture;
803 p_picsys->priv.hw.p_dec = p_dec;
804 p_picsys->priv.hw.i_index = index;
805 p_picsys->priv.hw.b_valid = true;
807 vlc_mutex_lock(get_android_opaque_mutex());
808 InsertInflightPicture(p_dec, p_pic, index);
809 vlc_mutex_unlock(get_android_opaque_mutex());
812 if (p_sys->get_output_buffers)
813 buf = (*env)->GetObjectArrayElement(env, p_sys->output_buffers, index);
815 buf = (*env)->CallObjectMethod(env, p_sys->codec,
816 p_sys->get_output_buffer, index);
817 //jsize buf_size = (*env)->GetDirectBufferCapacity(env, buf);
818 uint8_t *ptr = (*env)->GetDirectBufferAddress(env, buf);
820 //int size = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->size_field);
821 int offset = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->offset_field);
822 ptr += offset; // Check the size parameter as well
824 unsigned int chroma_div;
825 GetVlcChromaSizes(p_dec->fmt_out.i_codec, p_dec->fmt_out.video.i_width,
826 p_dec->fmt_out.video.i_height, NULL, NULL, &chroma_div);
827 CopyOmxPicture(p_sys->pixel_format, p_pic, p_sys->slice_height, p_sys->stride,
828 ptr, chroma_div, &p_sys->architecture_specific_data);
829 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
831 jthrowable exception = (*env)->ExceptionOccurred(env);
832 if (exception != NULL) {
833 jclass illegalStateException = (*env)->FindClass(env, "java/lang/IllegalStateException");
834 if((*env)->IsInstanceOf(env, exception, illegalStateException)) {
835 msg_Err(p_dec, "Codec error (IllegalStateException) in MediaCodec.releaseOutputBuffer");
836 (*env)->ExceptionClear(env);
837 (*env)->DeleteLocalRef(env, illegalStateException);
838 p_sys->error_state = true;
841 (*env)->DeleteLocalRef(env, buf);
844 msg_Warn(p_dec, "NewPicture failed");
845 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
846 if ((*env)->ExceptionOccurred(env)) {
847 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (GetOutput)");
848 (*env)->ExceptionClear(env);
849 p_sys->error_state = true;
854 } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
855 msg_Dbg(p_dec, "output buffers changed");
856 if (!p_sys->get_output_buffers)
858 (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
860 p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec,
861 p_sys->get_output_buffers);
862 if ((*env)->ExceptionOccurred(env)) {
863 msg_Err(p_dec, "Exception in MediaCodec.getOutputBuffer (GetOutput)");
864 (*env)->ExceptionClear(env);
865 p_sys->output_buffers = NULL;
866 p_sys->error_state = true;
870 p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
871 } else if (index == INFO_OUTPUT_FORMAT_CHANGED) {
872 jobject format = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_format);
873 if ((*env)->ExceptionOccurred(env)) {
874 msg_Err(p_dec, "Exception in MediaCodec.getOutputFormat (GetOutput)");
875 (*env)->ExceptionClear(env);
876 p_sys->error_state = true;
880 jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
882 jsize format_len = (*env)->GetStringUTFLength(env, format_string);
883 const char *format_ptr = (*env)->GetStringUTFChars(env, format_string, NULL);
884 msg_Dbg(p_dec, "output format changed: %.*s", format_len, format_ptr);
885 (*env)->ReleaseStringUTFChars(env, format_string, format_ptr);
887 ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
889 int width = GET_INTEGER(format, "width");
890 int height = GET_INTEGER(format, "height");
891 p_sys->stride = GET_INTEGER(format, "stride");
892 p_sys->slice_height = GET_INTEGER(format, "slice-height");
893 p_sys->pixel_format = GET_INTEGER(format, "color-format");
894 int crop_left = GET_INTEGER(format, "crop-left");
895 int crop_top = GET_INTEGER(format, "crop-top");
896 int crop_right = GET_INTEGER(format, "crop-right");
897 int crop_bottom = GET_INTEGER(format, "crop-bottom");
899 const char *name = "unknown";
900 if (!p_sys->direct_rendering) {
901 if (!GetVlcChromaFormat(p_sys->pixel_format,
902 &p_dec->fmt_out.i_codec, &name)) {
903 msg_Err(p_dec, "color-format not recognized");
904 p_sys->error_state = true;
909 msg_Err(p_dec, "output: %d %s, %dx%d stride %d %d, crop %d %d %d %d",
910 p_sys->pixel_format, name, width, height, p_sys->stride, p_sys->slice_height,
911 crop_left, crop_top, crop_right, crop_bottom);
913 p_dec->fmt_out.video.i_width = crop_right + 1 - crop_left;
914 p_dec->fmt_out.video.i_height = crop_bottom + 1 - crop_top;
915 if (p_dec->fmt_out.video.i_width <= 1
916 || p_dec->fmt_out.video.i_height <= 1) {
917 p_dec->fmt_out.video.i_width = width;
918 p_dec->fmt_out.video.i_height = height;
920 p_dec->fmt_out.video.i_visible_width = p_dec->fmt_out.video.i_width;
921 p_dec->fmt_out.video.i_visible_height = p_dec->fmt_out.video.i_height;
923 if (p_sys->stride <= 0)
924 p_sys->stride = width;
925 if (p_sys->slice_height <= 0)
926 p_sys->slice_height = height;
927 if ((*env)->ExceptionOccurred(env))
928 (*env)->ExceptionClear(env);
930 ArchitectureSpecificCopyHooks(p_dec, p_sys->pixel_format, p_sys->slice_height,
931 p_sys->stride, &p_sys->architecture_specific_data);
932 if (p_sys->pixel_format == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
933 p_sys->slice_height -= crop_top/2;
934 if (IgnoreOmxDecoderPadding(p_sys->name)) {
935 p_sys->slice_height = 0;
936 p_sys->stride = p_dec->fmt_out.video.i_width;
945 static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
947 decoder_sys_t *p_sys = p_dec->p_sys;
948 picture_t *p_pic = NULL;
950 struct H264ConvertState convert_state = { 0, 0 };
952 if (!pp_block || !*pp_block)
955 block_t *p_block = *pp_block;
957 if (p_sys->error_state) {
958 block_Release(p_block);
959 if (!p_sys->error_event_sent) {
960 /* Signal the error to the Java. */
961 jni_EventHardwareAccelerationError();
962 p_sys->error_event_sent = true;
967 jni_attach_thread(&env, THREAD_NAME);
969 if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED)) {
970 block_Release(p_block);
971 timestamp_FifoEmpty(p_sys->timestamp_fifo);
972 if (p_sys->decoded) {
973 /* Invalidate all pictures that are currently in flight
974 * since flushing make all previous indices returned by
975 * MediaCodec invalid. */
976 if (p_sys->direct_rendering)
977 InvalidateAllPictures(p_dec);
979 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->flush);
980 if ((*env)->ExceptionOccurred(env)) {
981 msg_Warn(p_dec, "Exception occurred in MediaCodec.flush");
982 (*env)->ExceptionClear(env);
983 p_sys->error_state = true;
986 p_sys->decoded = false;
991 /* Use the aspect ratio provided by the input (ie read from packetizer).
992 * Don't check the current value of the aspect ratio in fmt_out, since we
993 * want to allow changes in it to propagate. */
994 if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
995 p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
996 p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
1000 const int max_polling_attempts = 50;
1003 int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_input_buffer, (jlong) 0);
1004 if ((*env)->ExceptionOccurred(env)) {
1005 msg_Err(p_dec, "Exception occurred in MediaCodec.dequeueInputBuffer");
1006 (*env)->ExceptionClear(env);
1007 p_sys->error_state = true;
1012 GetOutput(p_dec, env, &p_pic, timeout);
1013 if (p_sys->error_state)
1016 /* If we couldn't get an available input buffer but a
1017 * decoded frame is available, we return the frame
1018 * without assigning NULL to *pp_block. The next call
1019 * to DecodeVideo will try to send the input packet again.
1021 jni_detach_thread();
1024 timeout = 30 * 1000;
1026 /* With opaque DR the output buffers are released by the
1027 vout therefore we implement a timeout for polling in
1028 order to avoid being indefinitely stalled in this loop. */
1029 if (p_sys->direct_rendering && attempts == max_polling_attempts) {
1030 picture_t *invalid_picture = decoder_NewPicture(p_dec);
1031 if (invalid_picture) {
1032 invalid_picture->date = VLC_TS_INVALID;
1033 picture_sys_t *p_picsys = invalid_picture->p_sys;
1034 p_picsys->pf_lock_pic = NULL;
1035 p_picsys->pf_unlock_pic = NULL;
1036 p_picsys->priv.hw.p_dec = NULL;
1037 p_picsys->priv.hw.i_index = -1;
1038 p_picsys->priv.hw.b_valid = false;
1041 /* If we cannot return a picture we must free the
1042 block since the decoder will proceed with the
1044 block_Release(p_block);
1047 jni_detach_thread();
1048 return invalid_picture;
1054 if (p_sys->get_input_buffers)
1055 buf = (*env)->GetObjectArrayElement(env, p_sys->input_buffers, index);
1057 buf = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffer, index);
1058 jsize size = (*env)->GetDirectBufferCapacity(env, buf);
1059 uint8_t *bufptr = (*env)->GetDirectBufferAddress(env, buf);
1061 msg_Err(p_dec, "Java buffer has invalid size");
1062 p_sys->error_state = true;
1065 if ((size_t) size > p_block->i_buffer)
1066 size = p_block->i_buffer;
1067 memcpy(bufptr, p_block->p_buffer, size);
1069 convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
1071 int64_t ts = p_block->i_pts;
1072 if (!ts && p_block->i_dts)
1073 ts = p_block->i_dts;
1074 timestamp_FifoPut(p_sys->timestamp_fifo, p_block->i_pts ? VLC_TS_INVALID : p_block->i_dts);
1075 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->queue_input_buffer, index, 0, size, ts, 0);
1076 (*env)->DeleteLocalRef(env, buf);
1077 if ((*env)->ExceptionOccurred(env)) {
1078 msg_Err(p_dec, "Exception in MediaCodec.queueInputBuffer");
1079 (*env)->ExceptionClear(env);
1080 p_sys->error_state = true;
1083 p_sys->decoded = true;
1086 if (p_sys->error_state) {
1088 picture_Release(p_pic);
1089 jni_detach_thread();
1093 GetOutput(p_dec, env, &p_pic, 0);
1094 jni_detach_thread();
1096 block_Release(p_block);