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"
41 #include <OMX_Component.h>
42 #include "omxil_utils.h"
43 #include "android_opaque.h"
45 #define INFO_OUTPUT_BUFFERS_CHANGED -3
46 #define INFO_OUTPUT_FORMAT_CHANGED -2
47 #define INFO_TRY_AGAIN_LATER -1
50 /* JNI functions to get/set an Android Surface object. */
51 extern jobject jni_LockAndGetAndroidJavaSurface();
52 extern void jni_UnlockAndroidSurface();
53 extern void jni_SetAndroidSurfaceSizeEnv(JNIEnv *p_env, int width, int height, int visible_width, int visible_height, int sar_num, int sar_den);
54 extern void jni_EventHardwareAccelerationError();
55 extern bool jni_IsVideoPlayerActivityCreated();
57 /* Implementation of a circular buffer of timestamps with overwriting
58 * of older values. MediaCodec has only one type of timestamp, if a
59 * block has no PTS, we send the DTS instead. Some hardware decoders
60 * cannot cope with this situation and output the frames in the wrong
61 * order. As a workaround in this case, we use a FIFO of timestamps in
62 * order to remember which input packets had no PTS. Since an
63 * hardware decoder can silently drop frames, this might cause a
64 * growing desynchronization with the actual timestamp. Thus the
65 * circular buffer has a limited size and will overwrite older values.
75 static timestamp_fifo_t *timestamp_FifoNew(uint32_t capacity)
77 timestamp_fifo_t *fifo = calloc(1, sizeof(*fifo));
80 fifo->buffer = malloc(capacity * sizeof(*fifo->buffer));
85 fifo->capacity = capacity;
89 static void timestamp_FifoRelease(timestamp_fifo_t *fifo)
95 static bool timestamp_FifoIsEmpty(timestamp_fifo_t *fifo)
97 return fifo->size == 0;
100 static bool timestamp_FifoIsFull(timestamp_fifo_t *fifo)
102 return fifo->size == fifo->capacity;
105 static void timestamp_FifoEmpty(timestamp_fifo_t *fifo)
110 static void timestamp_FifoPut(timestamp_fifo_t *fifo, int64_t ts)
112 uint32_t end = (fifo->begin + fifo->size) % fifo->capacity;
113 fifo->buffer[end] = ts;
114 if (!timestamp_FifoIsFull(fifo))
117 fifo->begin = (fifo->begin + 1) % fifo->capacity;
120 static int64_t timestamp_FifoGet(timestamp_fifo_t *fifo)
122 if (timestamp_FifoIsEmpty(fifo))
123 return VLC_TS_INVALID;
125 int64_t result = fifo->buffer[fifo->begin];
126 fifo->begin = (fifo->begin + 1) % fifo->capacity;
133 jclass media_codec_list_class, media_codec_class, media_format_class;
134 jclass buffer_info_class, byte_buffer_class;
136 jmethodID get_codec_count, get_codec_info_at, is_encoder, get_capabilities_for_type;
137 jfieldID profile_levels_field, profile_field, level_field;
138 jmethodID get_supported_types, get_name;
139 jmethodID create_by_codec_name, configure, start, stop, flush, release;
140 jmethodID get_output_format, get_input_buffers, get_output_buffers;
141 jmethodID dequeue_input_buffer, dequeue_output_buffer, queue_input_buffer;
142 jmethodID release_output_buffer;
143 jmethodID create_video_format, set_integer, set_bytebuffer, get_integer;
144 jmethodID buffer_info_ctor;
145 jmethodID allocate_direct, limit;
146 jfieldID size_field, offset_field, pts_field;
152 jobject input_buffers, output_buffers;
154 int stride, slice_height;
155 int crop_top, crop_left;
162 bool error_event_sent;
164 ArchitectureSpecificCopyData architecture_specific_data;
166 /* Direct rendering members. */
167 bool direct_rendering;
168 int i_output_buffers; /**< number of MediaCodec output buffers */
169 picture_t** inflight_picture; /**< stores the inflight picture for each output buffer or NULL */
171 timestamp_fifo_t *timestamp_fifo;
176 METHOD, STATIC_METHOD, FIELD
179 #define OFF(x) offsetof(struct decoder_sys_t, x)
185 static const struct classname classes[] = {
186 { "android/media/MediaCodecList", OFF(media_codec_list_class) },
187 { "android/media/MediaCodec", OFF(media_codec_class) },
188 { "android/media/MediaFormat", OFF(media_format_class) },
189 { "android/media/MediaFormat", OFF(media_format_class) },
190 { "android/media/MediaCodec$BufferInfo", OFF(buffer_info_class) },
191 { "java/nio/ByteBuffer", OFF(byte_buffer_class) },
203 static const struct member members[] = {
204 { "toString", "()Ljava/lang/String;", "java/lang/Object", OFF(tostring), METHOD },
206 { "getCodecCount", "()I", "android/media/MediaCodecList", OFF(get_codec_count), STATIC_METHOD },
207 { "getCodecInfoAt", "(I)Landroid/media/MediaCodecInfo;", "android/media/MediaCodecList", OFF(get_codec_info_at), STATIC_METHOD },
209 { "isEncoder", "()Z", "android/media/MediaCodecInfo", OFF(is_encoder), METHOD },
210 { "getSupportedTypes", "()[Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_supported_types), METHOD },
211 { "getName", "()Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_name), METHOD },
212 { "getCapabilitiesForType", "(Ljava/lang/String;)Landroid/media/MediaCodecInfo$CodecCapabilities;", "android/media/MediaCodecInfo", OFF(get_capabilities_for_type), METHOD },
214 { "profileLevels", "[Landroid/media/MediaCodecInfo$CodecProfileLevel;", "android/media/MediaCodecInfo$CodecCapabilities", OFF(profile_levels_field), FIELD },
215 { "profile", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(profile_field), FIELD },
216 { "level", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(level_field), FIELD },
218 { "createByCodecName", "(Ljava/lang/String;)Landroid/media/MediaCodec;", "android/media/MediaCodec", OFF(create_by_codec_name), STATIC_METHOD },
219 { "configure", "(Landroid/media/MediaFormat;Landroid/view/Surface;Landroid/media/MediaCrypto;I)V", "android/media/MediaCodec", OFF(configure), METHOD },
220 { "start", "()V", "android/media/MediaCodec", OFF(start), METHOD },
221 { "stop", "()V", "android/media/MediaCodec", OFF(stop), METHOD },
222 { "flush", "()V", "android/media/MediaCodec", OFF(flush), METHOD },
223 { "release", "()V", "android/media/MediaCodec", OFF(release), METHOD },
224 { "getOutputFormat", "()Landroid/media/MediaFormat;", "android/media/MediaCodec", OFF(get_output_format), METHOD },
225 { "getInputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_input_buffers), METHOD },
226 { "getOutputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_output_buffers), METHOD },
227 { "dequeueInputBuffer", "(J)I", "android/media/MediaCodec", OFF(dequeue_input_buffer), METHOD },
228 { "dequeueOutputBuffer", "(Landroid/media/MediaCodec$BufferInfo;J)I", "android/media/MediaCodec", OFF(dequeue_output_buffer), METHOD },
229 { "queueInputBuffer", "(IIIJI)V", "android/media/MediaCodec", OFF(queue_input_buffer), METHOD },
230 { "releaseOutputBuffer", "(IZ)V", "android/media/MediaCodec", OFF(release_output_buffer), METHOD },
232 { "createVideoFormat", "(Ljava/lang/String;II)Landroid/media/MediaFormat;", "android/media/MediaFormat", OFF(create_video_format), STATIC_METHOD },
233 { "setInteger", "(Ljava/lang/String;I)V", "android/media/MediaFormat", OFF(set_integer), METHOD },
234 { "getInteger", "(Ljava/lang/String;)I", "android/media/MediaFormat", OFF(get_integer), METHOD },
235 { "setByteBuffer", "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V", "android/media/MediaFormat", OFF(set_bytebuffer), METHOD },
237 { "<init>", "()V", "android/media/MediaCodec$BufferInfo", OFF(buffer_info_ctor), METHOD },
238 { "size", "I", "android/media/MediaCodec$BufferInfo", OFF(size_field), FIELD },
239 { "offset", "I", "android/media/MediaCodec$BufferInfo", OFF(offset_field), FIELD },
240 { "presentationTimeUs", "J", "android/media/MediaCodec$BufferInfo", OFF(pts_field), FIELD },
242 { "allocateDirect", "(I)Ljava/nio/ByteBuffer;", "java/nio/ByteBuffer", OFF(allocate_direct), STATIC_METHOD },
243 { "limit", "(I)Ljava/nio/Buffer;", "java/nio/ByteBuffer", OFF(limit), METHOD },
245 { NULL, NULL, NULL, 0, 0 },
248 #define GET_INTEGER(obj, name) (*env)->CallIntMethod(env, obj, p_sys->get_integer, (*env)->NewStringUTF(env, name))
250 /*****************************************************************************
252 *****************************************************************************/
253 static int OpenDecoder(vlc_object_t *);
254 static void CloseDecoder(vlc_object_t *);
256 static picture_t *DecodeVideo(decoder_t *, block_t **);
258 static void InvalidateAllPictures(decoder_t *);
260 /*****************************************************************************
262 *****************************************************************************/
263 #define DIRECTRENDERING_TEXT N_("Android direct rendering")
264 #define DIRECTRENDERING_LONGTEXT N_(\
265 "Enable Android direct rendering using opaque buffers.")
267 #define CFG_PREFIX "mediacodec-"
270 set_description( N_("Video decoder using Android MediaCodec") )
271 set_category( CAT_INPUT )
272 set_subcategory( SUBCAT_INPUT_VCODEC )
273 set_section( N_("Decoding") , NULL )
274 set_capability( "decoder", 0 ) /* Only enabled via commandline arguments */
275 add_bool(CFG_PREFIX "dr", true,
276 DIRECTRENDERING_TEXT, DIRECTRENDERING_LONGTEXT, true)
277 set_callbacks( OpenDecoder, CloseDecoder )
280 static int jstrcmp(JNIEnv* env, jobject str, const char* str2)
282 jsize len = (*env)->GetStringUTFLength(env, str);
283 if (len != (jsize) strlen(str2))
285 const char *ptr = (*env)->GetStringUTFChars(env, str, NULL);
286 int ret = memcmp(ptr, str2, len);
287 (*env)->ReleaseStringUTFChars(env, str, ptr);
291 /*****************************************************************************
292 * OpenDecoder: Create the decoder instance
293 *****************************************************************************/
294 static int OpenDecoder(vlc_object_t *p_this)
296 decoder_t *p_dec = (decoder_t*)p_this;
297 decoder_sys_t *p_sys;
299 if (p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
302 const char *mime = NULL;
303 switch (p_dec->fmt_in.i_codec) {
304 case VLC_CODEC_H264: mime = "video/avc"; break;
305 case VLC_CODEC_H263: mime = "video/3gpp"; break;
306 case VLC_CODEC_MP4V: mime = "video/mp4v-es"; break;
307 case VLC_CODEC_WMV3: mime = "video/x-ms-wmv"; break;
308 case VLC_CODEC_VC1: mime = "video/wvc1"; break;
309 case VLC_CODEC_VP8: mime = "video/x-vnd.on2.vp8"; break;
310 case VLC_CODEC_VP9: mime = "video/x-vnd.on2.vp9"; break;
312 msg_Dbg(p_dec, "codec %4.4s not supported", (char *)&p_dec->fmt_in.i_codec);
316 size_t fmt_profile = 0;
317 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264)
318 h264_get_profile_level(&p_dec->fmt_in, &fmt_profile, NULL, NULL);
320 /* Allocate the memory needed to store the decoder's structure */
321 if ((p_dec->p_sys = p_sys = calloc(1, sizeof(*p_sys))) == NULL)
324 p_dec->pf_decode_video = DecodeVideo;
326 p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
327 p_dec->fmt_out.video = p_dec->fmt_in.video;
328 p_dec->fmt_out.audio = p_dec->fmt_in.audio;
329 p_dec->b_need_packetized = true;
332 (*myVm)->AttachCurrentThread(myVm, &env, NULL);
334 for (int i = 0; classes[i].name; i++) {
335 *(jclass*)((uint8_t*)p_sys + classes[i].offset) =
336 (*env)->FindClass(env, classes[i].name);
338 if ((*env)->ExceptionOccurred(env)) {
339 msg_Warn(p_dec, "Unable to find class %s", classes[i].name);
340 (*env)->ExceptionClear(env);
346 for (int i = 0; members[i].name; i++) {
347 if (i == 0 || strcmp(members[i].class, members[i - 1].class))
348 last_class = (*env)->FindClass(env, members[i].class);
350 if ((*env)->ExceptionOccurred(env)) {
351 msg_Warn(p_dec, "Unable to find class %s", members[i].class);
352 (*env)->ExceptionClear(env);
356 switch (members[i].type) {
358 *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
359 (*env)->GetMethodID(env, last_class, members[i].name, members[i].sig);
362 *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
363 (*env)->GetStaticMethodID(env, last_class, members[i].name, members[i].sig);
366 *(jfieldID*)((uint8_t*)p_sys + members[i].offset) =
367 (*env)->GetFieldID(env, last_class, members[i].name, members[i].sig);
370 if ((*env)->ExceptionOccurred(env)) {
371 msg_Warn(p_dec, "Unable to find the member %s in %s",
372 members[i].name, members[i].class);
373 (*env)->ExceptionClear(env);
378 int num_codecs = (*env)->CallStaticIntMethod(env, p_sys->media_codec_list_class,
379 p_sys->get_codec_count);
380 jobject codec_name = NULL;
382 for (int i = 0; i < num_codecs; i++) {
383 jobject info = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_list_class,
384 p_sys->get_codec_info_at, i);
385 if ((*env)->CallBooleanMethod(env, info, p_sys->is_encoder)) {
386 (*env)->DeleteLocalRef(env, info);
390 jobject codec_capabilities = (*env)->CallObjectMethod(env, info, p_sys->get_capabilities_for_type,
391 (*env)->NewStringUTF(env, mime));
392 jobject profile_levels = NULL;
393 int profile_levels_len = 0;
394 if ((*env)->ExceptionOccurred(env)) {
395 msg_Warn(p_dec, "Exception occurred in MediaCodecInfo.getCapabilitiesForType");
396 (*env)->ExceptionClear(env);
398 } else if (codec_capabilities) {
399 profile_levels = (*env)->GetObjectField(env, codec_capabilities, p_sys->profile_levels_field);
401 profile_levels_len = (*env)->GetArrayLength(env, profile_levels);
403 msg_Dbg(p_dec, "Number of profile levels: %d", profile_levels_len);
405 jobject types = (*env)->CallObjectMethod(env, info, p_sys->get_supported_types);
406 int num_types = (*env)->GetArrayLength(env, types);
408 for (int j = 0; j < num_types && !found; j++) {
409 jobject type = (*env)->GetObjectArrayElement(env, types, j);
410 if (!jstrcmp(env, type, mime)) {
411 /* The mime type is matching for this component. We
412 now check if the capabilities of the codec is
413 matching the video format. */
414 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && fmt_profile) {
415 for (int i = 0; i < profile_levels_len && !found; ++i) {
416 jobject profile_level = (*env)->GetObjectArrayElement(env, profile_levels, i);
418 int omx_profile = (*env)->GetIntField(env, profile_level, p_sys->profile_field);
419 size_t codec_profile = convert_omx_to_profile_idc(omx_profile);
420 if (codec_profile != fmt_profile)
422 /* Some encoders set the level too high, thus we ignore it for the moment.
423 We could try to guess the actual profile based on the resolution. */
430 (*env)->DeleteLocalRef(env, type);
433 jobject name = (*env)->CallObjectMethod(env, info, p_sys->get_name);
434 jsize name_len = (*env)->GetStringUTFLength(env, name);
435 const char *name_ptr = (*env)->GetStringUTFChars(env, name, NULL);
436 msg_Dbg(p_dec, "using %.*s", name_len, name_ptr);
437 p_sys->name = malloc(name_len + 1);
438 memcpy(p_sys->name, name_ptr, name_len);
439 p_sys->name[name_len] = '\0';
440 (*env)->ReleaseStringUTFChars(env, name, name_ptr);
444 (*env)->DeleteLocalRef(env, info);
448 msg_Dbg(p_dec, "No suitable codec matching %s was found", mime);
452 // This method doesn't handle errors nicely, it crashes if the codec isn't found.
453 // (The same goes for createDecoderByType.) This is fixed in latest AOSP and in 4.2,
454 // but not in 4.1 devices.
455 p_sys->codec = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_class,
456 p_sys->create_by_codec_name, codec_name);
457 if ((*env)->ExceptionOccurred(env)) {
458 msg_Warn(p_dec, "Exception occurred in MediaCodec.createByCodecName.");
459 (*env)->ExceptionClear(env);
462 p_sys->allocated = true;
463 p_sys->codec = (*env)->NewGlobalRef(env, p_sys->codec);
465 jobject format = (*env)->CallStaticObjectMethod(env, p_sys->media_format_class,
466 p_sys->create_video_format, (*env)->NewStringUTF(env, mime),
467 p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height);
469 if (p_dec->fmt_in.i_extra) {
470 // Allocate a byte buffer via allocateDirect in java instead of NewDirectByteBuffer,
471 // since the latter doesn't allocate storage of its own, and we don't know how long
472 // the codec uses the buffer.
473 int buf_size = p_dec->fmt_in.i_extra + 20;
474 jobject bytebuf = (*env)->CallStaticObjectMethod(env, p_sys->byte_buffer_class,
475 p_sys->allocate_direct, buf_size);
476 uint32_t size = p_dec->fmt_in.i_extra;
477 uint8_t *ptr = (*env)->GetDirectBufferAddress(env, bytebuf);
478 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && ((uint8_t*)p_dec->fmt_in.p_extra)[0] == 1) {
479 convert_sps_pps(p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
481 &size, &p_sys->nal_size);
483 memcpy(ptr, p_dec->fmt_in.p_extra, size);
485 (*env)->CallObjectMethod(env, bytebuf, p_sys->limit, size);
486 (*env)->CallVoidMethod(env, format, p_sys->set_bytebuffer,
487 (*env)->NewStringUTF(env, "csd-0"), bytebuf);
488 (*env)->DeleteLocalRef(env, bytebuf);
491 /* If the VideoPlayerActivity is not started, MediaCodec opaque
492 direct rendering should be disabled since no surface will be
493 attached to the JNI. */
494 p_sys->direct_rendering = jni_IsVideoPlayerActivityCreated() && var_InheritBool(p_dec, CFG_PREFIX "dr");
495 if (p_sys->direct_rendering) {
496 jobject surf = jni_LockAndGetAndroidJavaSurface();
498 // Configure MediaCodec with the Android surface.
499 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, surf, NULL, 0);
500 if ((*env)->ExceptionOccurred(env)) {
501 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure with an output surface.");
502 (*env)->ExceptionClear(env);
503 jni_UnlockAndroidSurface();
506 p_dec->fmt_out.i_codec = VLC_CODEC_ANDROID_OPAQUE;
508 msg_Warn(p_dec, "Failed to get the Android Surface, disabling direct rendering.");
509 p_sys->direct_rendering = false;
511 jni_UnlockAndroidSurface();
513 if (!p_sys->direct_rendering) {
514 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, NULL, NULL, 0);
515 if ((*env)->ExceptionOccurred(env)) {
516 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure");
517 (*env)->ExceptionClear(env);
522 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->start);
523 if ((*env)->ExceptionOccurred(env)) {
524 msg_Warn(p_dec, "Exception occurred in MediaCodec.start");
525 (*env)->ExceptionClear(env);
528 p_sys->started = true;
530 p_sys->input_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffers);
531 p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_buffers);
532 p_sys->buffer_info = (*env)->NewObject(env, p_sys->buffer_info_class, p_sys->buffer_info_ctor);
533 p_sys->input_buffers = (*env)->NewGlobalRef(env, p_sys->input_buffers);
534 p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
535 p_sys->buffer_info = (*env)->NewGlobalRef(env, p_sys->buffer_info);
536 p_sys->i_output_buffers = (*env)->GetArrayLength(env, p_sys->output_buffers);
537 p_sys->inflight_picture = calloc(1, sizeof(picture_t*) * p_sys->i_output_buffers);
538 if (!p_sys->inflight_picture)
540 (*env)->DeleteLocalRef(env, format);
542 (*myVm)->DetachCurrentThread(myVm);
544 const int timestamp_fifo_size = 32;
545 p_sys->timestamp_fifo = timestamp_FifoNew(timestamp_fifo_size);
546 if (!p_sys->timestamp_fifo)
552 (*myVm)->DetachCurrentThread(myVm);
553 CloseDecoder(p_this);
557 static void CloseDecoder(vlc_object_t *p_this)
559 decoder_t *p_dec = (decoder_t *)p_this;
560 decoder_sys_t *p_sys = p_dec->p_sys;
566 /* Invalidate all pictures that are currently in flight in order
567 * to prevent the vout from using destroyed output buffers. */
568 if (p_sys->direct_rendering)
569 InvalidateAllPictures(p_dec);
570 (*myVm)->AttachCurrentThread(myVm, &env, NULL);
571 if (p_sys->input_buffers)
572 (*env)->DeleteGlobalRef(env, p_sys->input_buffers);
573 if (p_sys->output_buffers)
574 (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
578 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->stop);
579 if ((*env)->ExceptionOccurred(env)) {
580 msg_Err(p_dec, "Exception in MediaCodec.stop");
581 (*env)->ExceptionClear(env);
584 if (p_sys->allocated)
586 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release);
587 if ((*env)->ExceptionOccurred(env)) {
588 msg_Err(p_dec, "Exception in MediaCodec.release");
589 (*env)->ExceptionClear(env);
592 (*env)->DeleteGlobalRef(env, p_sys->codec);
594 if (p_sys->buffer_info)
595 (*env)->DeleteGlobalRef(env, p_sys->buffer_info);
596 (*myVm)->DetachCurrentThread(myVm);
599 ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
600 free(p_sys->inflight_picture);
601 if (p_sys->timestamp_fifo)
602 timestamp_FifoRelease(p_sys->timestamp_fifo);
606 /*****************************************************************************
608 *****************************************************************************/
609 static void DisplayBuffer(picture_sys_t* p_picsys, bool b_render)
611 decoder_t *p_dec = p_picsys->p_dec;
612 decoder_sys_t *p_sys = p_dec->p_sys;
614 if (!p_picsys->b_valid)
617 vlc_mutex_lock(get_android_opaque_mutex());
619 /* Picture might have been invalidated while waiting on the mutex. */
620 if (!p_picsys->b_valid) {
621 vlc_mutex_unlock(get_android_opaque_mutex());
625 uint32_t i_index = p_picsys->i_index;
626 p_sys->inflight_picture[i_index] = NULL;
628 /* Release the MediaCodec buffer. */
630 (*myVm)->AttachCurrentThread(myVm, &env, NULL);
631 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_index, b_render);
632 if ((*env)->ExceptionOccurred(env)) {
633 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (DisplayBuffer)");
634 (*env)->ExceptionClear(env);
637 (*myVm)->DetachCurrentThread(myVm);
638 p_picsys->b_valid = false;
640 vlc_mutex_unlock(get_android_opaque_mutex());
643 static void UnlockCallback(picture_sys_t* p_picsys)
645 DisplayBuffer(p_picsys, false);
648 static void DisplayCallback(picture_sys_t* p_picsys)
650 DisplayBuffer(p_picsys, true);
653 static void InvalidateAllPictures(decoder_t *p_dec)
655 decoder_sys_t *p_sys = p_dec->p_sys;
657 vlc_mutex_lock(get_android_opaque_mutex());
658 for (int i = 0; i < p_sys->i_output_buffers; ++i) {
659 picture_t *p_pic = p_sys->inflight_picture[i];
661 p_pic->p_sys->b_valid = false;
662 p_sys->inflight_picture[i] = NULL;
665 vlc_mutex_unlock(get_android_opaque_mutex());
668 static void GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
670 decoder_sys_t *p_sys = p_dec->p_sys;
672 int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_output_buffer,
673 p_sys->buffer_info, timeout);
674 if ((*env)->ExceptionOccurred(env)) {
675 msg_Err(p_dec, "Exception in MediaCodec.dequeueOutputBuffer (GetOutput)");
676 (*env)->ExceptionClear(env);
677 p_sys->error_state = true;
682 if (!p_sys->pixel_format) {
683 msg_Warn(p_dec, "Buffers returned before output format is set, dropping frame");
684 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
685 if ((*env)->ExceptionOccurred(env)) {
686 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer");
687 (*env)->ExceptionClear(env);
688 p_sys->error_state = true;
695 *pp_pic = decoder_NewPicture(p_dec);
696 } else if (p_sys->direct_rendering) {
697 picture_t *p_pic = *pp_pic;
698 picture_sys_t *p_picsys = p_pic->p_sys;
699 int i_prev_index = p_picsys->i_index;
700 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_prev_index, false);
701 if ((*env)->ExceptionOccurred(env)) {
702 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer " \
703 "(GetOutput, overwriting previous picture)");
704 (*env)->ExceptionClear(env);
705 p_sys->error_state = true;
709 // No need to lock here since the previous picture was not sent.
710 p_sys->inflight_picture[i_prev_index] = NULL;
714 picture_t *p_pic = *pp_pic;
715 // TODO: Use crop_top/crop_left as well? Or is that already taken into account?
716 // On OMX_TI_COLOR_FormatYUV420PackedSemiPlanar the offset already incldues
717 // the cropping, so the top/left cropping params should just be ignored.
719 /* If the oldest input block had no PTS, the timestamp
720 * of the frame returned by MediaCodec might be wrong
721 * so we overwrite it with the corresponding dts. */
722 int64_t forced_ts = timestamp_FifoGet(p_sys->timestamp_fifo);
723 if (forced_ts == VLC_TS_INVALID)
724 p_pic->date = (*env)->GetLongField(env, p_sys->buffer_info, p_sys->pts_field);
726 p_pic->date = forced_ts;
728 if (p_sys->direct_rendering) {
729 picture_sys_t *p_picsys = p_pic->p_sys;
730 p_picsys->pf_display_callback = DisplayCallback;
731 p_picsys->pf_unlock_callback = UnlockCallback;
732 p_picsys->p_dec = p_dec;
733 p_picsys->i_index = index;
734 p_picsys->b_valid = true;
736 p_sys->inflight_picture[index] = p_pic;
738 jobject buf = (*env)->GetObjectArrayElement(env, p_sys->output_buffers, index);
739 jsize buf_size = (*env)->GetDirectBufferCapacity(env, buf);
740 uint8_t *ptr = (*env)->GetDirectBufferAddress(env, buf);
742 int size = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->size_field);
743 int offset = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->offset_field);
744 ptr += offset; // Check the size parameter as well
746 unsigned int chroma_div;
747 GetVlcChromaSizes(p_dec->fmt_out.i_codec, p_dec->fmt_out.video.i_width,
748 p_dec->fmt_out.video.i_height, NULL, NULL, &chroma_div);
749 CopyOmxPicture(p_sys->pixel_format, p_pic, p_sys->slice_height, p_sys->stride,
750 ptr, chroma_div, &p_sys->architecture_specific_data);
751 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
753 jthrowable exception = (*env)->ExceptionOccurred(env);
754 if (exception != NULL) {
755 jclass illegalStateException = (*env)->FindClass(env, "java/lang/IllegalStateException");
756 if((*env)->IsInstanceOf(env, exception, illegalStateException)) {
757 msg_Err(p_dec, "Codec error (IllegalStateException) in MediaCodec.releaseOutputBuffer");
758 (*env)->ExceptionClear(env);
759 (*env)->DeleteLocalRef(env, illegalStateException);
760 p_sys->error_state = true;
763 (*env)->DeleteLocalRef(env, buf);
766 msg_Warn(p_dec, "NewPicture failed");
767 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
768 if ((*env)->ExceptionOccurred(env)) {
769 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (GetOutput)");
770 (*env)->ExceptionClear(env);
771 p_sys->error_state = true;
776 } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
777 msg_Dbg(p_dec, "output buffers changed");
778 (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
780 p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec,
781 p_sys->get_output_buffers);
782 if ((*env)->ExceptionOccurred(env)) {
783 msg_Err(p_dec, "Exception in MediaCodec.getOutputBuffer (GetOutput)");
784 (*env)->ExceptionClear(env);
785 p_sys->output_buffers = NULL;
786 p_sys->error_state = true;
790 p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
792 vlc_mutex_lock(get_android_opaque_mutex());
793 free(p_sys->inflight_picture);
794 p_sys->i_output_buffers = (*env)->GetArrayLength(env, p_sys->output_buffers);
795 p_sys->inflight_picture = calloc(1, sizeof(picture_t*) * p_sys->i_output_buffers);
796 vlc_mutex_unlock(get_android_opaque_mutex());
798 } else if (index == INFO_OUTPUT_FORMAT_CHANGED) {
799 jobject format = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_format);
800 if ((*env)->ExceptionOccurred(env)) {
801 msg_Err(p_dec, "Exception in MediaCodec.getOutputFormat (GetOutput)");
802 (*env)->ExceptionClear(env);
803 p_sys->error_state = true;
807 jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
809 jsize format_len = (*env)->GetStringUTFLength(env, format_string);
810 const char *format_ptr = (*env)->GetStringUTFChars(env, format_string, NULL);
811 msg_Dbg(p_dec, "output format changed: %.*s", format_len, format_ptr);
812 (*env)->ReleaseStringUTFChars(env, format_string, format_ptr);
814 ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
816 int width = GET_INTEGER(format, "width");
817 int height = GET_INTEGER(format, "height");
818 p_sys->stride = GET_INTEGER(format, "stride");
819 p_sys->slice_height = GET_INTEGER(format, "slice-height");
820 p_sys->pixel_format = GET_INTEGER(format, "color-format");
821 p_sys->crop_left = GET_INTEGER(format, "crop-left");
822 p_sys->crop_top = GET_INTEGER(format, "crop-top");
823 int crop_right = GET_INTEGER(format, "crop-right");
824 int crop_bottom = GET_INTEGER(format, "crop-bottom");
826 const char *name = "unknown";
827 if (p_sys->direct_rendering) {
828 int sar_num = 1, sar_den = 1;
829 if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
830 sar_num = p_dec->fmt_in.video.i_sar_num;
831 sar_den = p_dec->fmt_in.video.i_sar_den;
833 jni_SetAndroidSurfaceSizeEnv(env, width, height, width, height, sar_num, sar_den);
835 GetVlcChromaFormat(p_sys->pixel_format, &p_dec->fmt_out.i_codec, &name);
837 msg_Dbg(p_dec, "output: %d %s, %dx%d stride %d %d, crop %d %d %d %d",
838 p_sys->pixel_format, name, width, height, p_sys->stride, p_sys->slice_height,
839 p_sys->crop_left, p_sys->crop_top, crop_right, crop_bottom);
841 p_dec->fmt_out.video.i_width = crop_right + 1 - p_sys->crop_left;
842 p_dec->fmt_out.video.i_height = crop_bottom + 1 - p_sys->crop_top;
843 if (p_sys->stride <= 0)
844 p_sys->stride = width;
845 if (p_sys->slice_height <= 0)
846 p_sys->slice_height = height;
847 if ((*env)->ExceptionOccurred(env))
848 (*env)->ExceptionClear(env);
850 ArchitectureSpecificCopyHooks(p_dec, p_sys->pixel_format, p_sys->slice_height,
851 p_sys->stride, &p_sys->architecture_specific_data);
852 if (p_sys->pixel_format == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) {
853 p_sys->slice_height -= p_sys->crop_top/2;
854 /* Reset crop top/left here, since the offset parameter already includes this.
855 * If we'd ignore the offset parameter in the BufferInfo, we could just keep
856 * the original slice height and apply the top/left cropping instead. */
858 p_sys->crop_left = 0;
860 if (IgnoreOmxDecoderPadding(p_sys->name)) {
861 p_sys->slice_height = 0;
862 p_sys->stride = p_dec->fmt_out.video.i_width;
871 static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
873 decoder_sys_t *p_sys = p_dec->p_sys;
874 picture_t *p_pic = NULL;
876 struct H264ConvertState convert_state = { 0, 0 };
878 if (!pp_block || !*pp_block)
881 block_t *p_block = *pp_block;
883 if (p_sys->error_state) {
884 block_Release(p_block);
885 if (!p_sys->error_event_sent) {
886 /* Signal the error to the Java. */
887 jni_EventHardwareAccelerationError();
888 p_sys->error_event_sent = true;
893 (*myVm)->AttachCurrentThread(myVm, &env, NULL);
895 if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED)) {
896 block_Release(p_block);
897 timestamp_FifoEmpty(p_sys->timestamp_fifo);
898 if (p_sys->decoded) {
899 /* Invalidate all pictures that are currently in flight
900 * since flushing make all previous indices returned by
901 * MediaCodec invalid. */
902 if (p_sys->direct_rendering)
903 InvalidateAllPictures(p_dec);
905 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->flush);
906 if ((*env)->ExceptionOccurred(env)) {
907 msg_Warn(p_dec, "Exception occurred in MediaCodec.flush");
908 (*env)->ExceptionClear(env);
909 p_sys->error_state = true;
912 p_sys->decoded = false;
913 (*myVm)->DetachCurrentThread(myVm);
917 /* Use the aspect ratio provided by the input (ie read from packetizer).
918 * Don't check the current value of the aspect ratio in fmt_out, since we
919 * want to allow changes in it to propagate. */
920 if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
921 p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
922 p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
926 const int max_polling_attempts = 50;
929 int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_input_buffer, (jlong) 0);
930 if ((*env)->ExceptionOccurred(env)) {
931 msg_Err(p_dec, "Exception occurred in MediaCodec.dequeueInputBuffer");
932 (*env)->ExceptionClear(env);
933 p_sys->error_state = true;
938 GetOutput(p_dec, env, &p_pic, timeout);
940 /* If we couldn't get an available input buffer but a
941 * decoded frame is available, we return the frame
942 * without assigning NULL to *pp_block. The next call
943 * to DecodeVideo will try to send the input packet again.
945 (*myVm)->DetachCurrentThread(myVm);
950 /* With opaque DR the output buffers are released by the
951 vout therefore we implement a timeout for polling in
952 order to avoid being indefinitely stalled in this loop. */
953 if (p_sys->direct_rendering && attempts == max_polling_attempts) {
954 picture_t *invalid_picture = decoder_NewPicture(p_dec);
955 if (invalid_picture) {
956 invalid_picture->date = VLC_TS_INVALID;
957 picture_sys_t *p_picsys = invalid_picture->p_sys;
958 p_picsys->pf_display_callback = NULL;
959 p_picsys->pf_unlock_callback = NULL;
960 p_picsys->p_dec = NULL;
961 p_picsys->i_index = -1;
962 p_picsys->b_valid = false;
965 /* If we cannot return a picture we must free the
966 block since the decoder will proceed with the
968 block_Release(p_block);
971 (*myVm)->DetachCurrentThread(myVm);
972 return invalid_picture;
977 jobject buf = (*env)->GetObjectArrayElement(env, p_sys->input_buffers, index);
978 jsize size = (*env)->GetDirectBufferCapacity(env, buf);
979 uint8_t *bufptr = (*env)->GetDirectBufferAddress(env, buf);
980 if (size > p_block->i_buffer)
981 size = p_block->i_buffer;
982 memcpy(bufptr, p_block->p_buffer, size);
984 convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
986 int64_t ts = p_block->i_pts;
987 if (!ts && p_block->i_dts)
989 timestamp_FifoPut(p_sys->timestamp_fifo, p_block->i_pts ? VLC_TS_INVALID : p_block->i_dts);
990 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->queue_input_buffer, index, 0, size, ts, 0);
991 (*env)->DeleteLocalRef(env, buf);
992 if ((*env)->ExceptionOccurred(env)) {
993 msg_Err(p_dec, "Exception in MediaCodec.queueInputBuffer");
994 (*env)->ExceptionClear(env);
995 p_sys->error_state = true;
998 p_sys->decoded = true;
1002 GetOutput(p_dec, env, &p_pic, 0);
1003 (*myVm)->DetachCurrentThread(myVm);
1005 block_Release(p_block);