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_SetAndroidSurfaceSizeEnv(JNIEnv *p_env, int width, int height, int visible_width, int visible_height, int sar_num, int sar_den);
59 extern void jni_EventHardwareAccelerationError();
60 extern bool jni_IsVideoPlayerActivityCreated();
62 /* Implementation of a circular buffer of timestamps with overwriting
63 * of older values. MediaCodec has only one type of timestamp, if a
64 * block has no PTS, we send the DTS instead. Some hardware decoders
65 * cannot cope with this situation and output the frames in the wrong
66 * order. As a workaround in this case, we use a FIFO of timestamps in
67 * order to remember which input packets had no PTS. Since an
68 * hardware decoder can silently drop frames, this might cause a
69 * growing desynchronization with the actual timestamp. Thus the
70 * circular buffer has a limited size and will overwrite older values.
80 static timestamp_fifo_t *timestamp_FifoNew(uint32_t capacity)
82 timestamp_fifo_t *fifo = calloc(1, sizeof(*fifo));
85 fifo->buffer = malloc(capacity * sizeof(*fifo->buffer));
90 fifo->capacity = capacity;
94 static void timestamp_FifoRelease(timestamp_fifo_t *fifo)
100 static bool timestamp_FifoIsEmpty(timestamp_fifo_t *fifo)
102 return fifo->size == 0;
105 static bool timestamp_FifoIsFull(timestamp_fifo_t *fifo)
107 return fifo->size == fifo->capacity;
110 static void timestamp_FifoEmpty(timestamp_fifo_t *fifo)
115 static void timestamp_FifoPut(timestamp_fifo_t *fifo, int64_t ts)
117 uint32_t end = (fifo->begin + fifo->size) % fifo->capacity;
118 fifo->buffer[end] = ts;
119 if (!timestamp_FifoIsFull(fifo))
122 fifo->begin = (fifo->begin + 1) % fifo->capacity;
125 static int64_t timestamp_FifoGet(timestamp_fifo_t *fifo)
127 if (timestamp_FifoIsEmpty(fifo))
128 return VLC_TS_INVALID;
130 int64_t result = fifo->buffer[fifo->begin];
131 fifo->begin = (fifo->begin + 1) % fifo->capacity;
138 jclass media_codec_list_class, media_codec_class, media_format_class;
139 jclass buffer_info_class, byte_buffer_class;
141 jmethodID get_codec_count, get_codec_info_at, is_encoder, get_capabilities_for_type;
142 jfieldID profile_levels_field, profile_field, level_field;
143 jmethodID get_supported_types, get_name;
144 jmethodID create_by_codec_name, configure, start, stop, flush, release;
145 jmethodID get_output_format, get_input_buffers, get_output_buffers;
146 jmethodID dequeue_input_buffer, dequeue_output_buffer, queue_input_buffer;
147 jmethodID release_output_buffer;
148 jmethodID create_video_format, set_integer, set_bytebuffer, get_integer;
149 jmethodID buffer_info_ctor;
150 jmethodID allocate_direct, limit;
151 jfieldID size_field, offset_field, pts_field;
157 jobject input_buffers, output_buffers;
159 int stride, slice_height;
160 int crop_top, crop_left;
167 bool error_event_sent;
169 ArchitectureSpecificCopyData architecture_specific_data;
171 /* Direct rendering members. */
172 bool direct_rendering;
173 int i_output_buffers; /**< number of MediaCodec output buffers */
174 picture_t** inflight_picture; /**< stores the inflight picture for each output buffer or NULL */
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) },
208 static const struct member members[] = {
209 { "toString", "()Ljava/lang/String;", "java/lang/Object", OFF(tostring), METHOD },
211 { "getCodecCount", "()I", "android/media/MediaCodecList", OFF(get_codec_count), STATIC_METHOD },
212 { "getCodecInfoAt", "(I)Landroid/media/MediaCodecInfo;", "android/media/MediaCodecList", OFF(get_codec_info_at), STATIC_METHOD },
214 { "isEncoder", "()Z", "android/media/MediaCodecInfo", OFF(is_encoder), METHOD },
215 { "getSupportedTypes", "()[Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_supported_types), METHOD },
216 { "getName", "()Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_name), METHOD },
217 { "getCapabilitiesForType", "(Ljava/lang/String;)Landroid/media/MediaCodecInfo$CodecCapabilities;", "android/media/MediaCodecInfo", OFF(get_capabilities_for_type), METHOD },
219 { "profileLevels", "[Landroid/media/MediaCodecInfo$CodecProfileLevel;", "android/media/MediaCodecInfo$CodecCapabilities", OFF(profile_levels_field), FIELD },
220 { "profile", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(profile_field), FIELD },
221 { "level", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(level_field), FIELD },
223 { "createByCodecName", "(Ljava/lang/String;)Landroid/media/MediaCodec;", "android/media/MediaCodec", OFF(create_by_codec_name), STATIC_METHOD },
224 { "configure", "(Landroid/media/MediaFormat;Landroid/view/Surface;Landroid/media/MediaCrypto;I)V", "android/media/MediaCodec", OFF(configure), METHOD },
225 { "start", "()V", "android/media/MediaCodec", OFF(start), METHOD },
226 { "stop", "()V", "android/media/MediaCodec", OFF(stop), METHOD },
227 { "flush", "()V", "android/media/MediaCodec", OFF(flush), METHOD },
228 { "release", "()V", "android/media/MediaCodec", OFF(release), METHOD },
229 { "getOutputFormat", "()Landroid/media/MediaFormat;", "android/media/MediaCodec", OFF(get_output_format), METHOD },
230 { "getInputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_input_buffers), METHOD },
231 { "getOutputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_output_buffers), METHOD },
232 { "dequeueInputBuffer", "(J)I", "android/media/MediaCodec", OFF(dequeue_input_buffer), METHOD },
233 { "dequeueOutputBuffer", "(Landroid/media/MediaCodec$BufferInfo;J)I", "android/media/MediaCodec", OFF(dequeue_output_buffer), METHOD },
234 { "queueInputBuffer", "(IIIJI)V", "android/media/MediaCodec", OFF(queue_input_buffer), METHOD },
235 { "releaseOutputBuffer", "(IZ)V", "android/media/MediaCodec", OFF(release_output_buffer), METHOD },
237 { "createVideoFormat", "(Ljava/lang/String;II)Landroid/media/MediaFormat;", "android/media/MediaFormat", OFF(create_video_format), STATIC_METHOD },
238 { "setInteger", "(Ljava/lang/String;I)V", "android/media/MediaFormat", OFF(set_integer), METHOD },
239 { "getInteger", "(Ljava/lang/String;)I", "android/media/MediaFormat", OFF(get_integer), METHOD },
240 { "setByteBuffer", "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V", "android/media/MediaFormat", OFF(set_bytebuffer), METHOD },
242 { "<init>", "()V", "android/media/MediaCodec$BufferInfo", OFF(buffer_info_ctor), METHOD },
243 { "size", "I", "android/media/MediaCodec$BufferInfo", OFF(size_field), FIELD },
244 { "offset", "I", "android/media/MediaCodec$BufferInfo", OFF(offset_field), FIELD },
245 { "presentationTimeUs", "J", "android/media/MediaCodec$BufferInfo", OFF(pts_field), FIELD },
247 { "allocateDirect", "(I)Ljava/nio/ByteBuffer;", "java/nio/ByteBuffer", OFF(allocate_direct), STATIC_METHOD },
248 { "limit", "(I)Ljava/nio/Buffer;", "java/nio/ByteBuffer", OFF(limit), METHOD },
250 { NULL, NULL, NULL, 0, 0 },
253 #define GET_INTEGER(obj, name) (*env)->CallIntMethod(env, obj, p_sys->get_integer, (*env)->NewStringUTF(env, name))
255 /*****************************************************************************
257 *****************************************************************************/
258 static int OpenDecoder(vlc_object_t *);
259 static void CloseDecoder(vlc_object_t *);
261 static picture_t *DecodeVideo(decoder_t *, block_t **);
263 static void InvalidateAllPictures(decoder_t *);
265 /*****************************************************************************
267 *****************************************************************************/
268 #define DIRECTRENDERING_TEXT N_("Android direct rendering")
269 #define DIRECTRENDERING_LONGTEXT N_(\
270 "Enable Android direct rendering using opaque buffers.")
272 #define CFG_PREFIX "mediacodec-"
275 set_description( N_("Video decoder using Android MediaCodec") )
276 set_category( CAT_INPUT )
277 set_subcategory( SUBCAT_INPUT_VCODEC )
278 set_section( N_("Decoding") , NULL )
279 set_capability( "decoder", 0 ) /* Only enabled via commandline arguments */
280 add_bool(CFG_PREFIX "dr", true,
281 DIRECTRENDERING_TEXT, DIRECTRENDERING_LONGTEXT, true)
282 set_callbacks( OpenDecoder, CloseDecoder )
285 static int jstrcmp(JNIEnv* env, jobject str, const char* str2)
287 jsize len = (*env)->GetStringUTFLength(env, str);
288 if (len != (jsize) strlen(str2))
290 const char *ptr = (*env)->GetStringUTFChars(env, str, NULL);
291 int ret = memcmp(ptr, str2, len);
292 (*env)->ReleaseStringUTFChars(env, str, ptr);
296 /*****************************************************************************
297 * OpenDecoder: Create the decoder instance
298 *****************************************************************************/
299 static int OpenDecoder(vlc_object_t *p_this)
301 decoder_t *p_dec = (decoder_t*)p_this;
302 decoder_sys_t *p_sys;
304 if (p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
307 const char *mime = NULL;
308 switch (p_dec->fmt_in.i_codec) {
309 case VLC_CODEC_HEVC: mime = "video/hevc"; break;
310 case VLC_CODEC_H264: mime = "video/avc"; break;
311 case VLC_CODEC_H263: mime = "video/3gpp"; break;
312 case VLC_CODEC_MP4V: mime = "video/mp4v-es"; break;
313 case VLC_CODEC_WMV3: mime = "video/x-ms-wmv"; break;
314 case VLC_CODEC_VC1: mime = "video/wvc1"; break;
315 case VLC_CODEC_VP8: mime = "video/x-vnd.on2.vp8"; break;
316 case VLC_CODEC_VP9: mime = "video/x-vnd.on2.vp9"; break;
318 msg_Dbg(p_dec, "codec %4.4s not supported", (char *)&p_dec->fmt_in.i_codec);
322 size_t fmt_profile = 0;
323 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264)
324 h264_get_profile_level(&p_dec->fmt_in, &fmt_profile, NULL, NULL);
326 /* Allocate the memory needed to store the decoder's structure */
327 if ((p_dec->p_sys = p_sys = calloc(1, sizeof(*p_sys))) == NULL)
330 p_dec->pf_decode_video = DecodeVideo;
332 p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
333 p_dec->fmt_out.video = p_dec->fmt_in.video;
334 p_dec->fmt_out.audio = p_dec->fmt_in.audio;
335 p_dec->b_need_packetized = true;
338 jni_attach_thread(&env, THREAD_NAME);
340 for (int i = 0; classes[i].name; i++) {
341 *(jclass*)((uint8_t*)p_sys + classes[i].offset) =
342 (*env)->FindClass(env, classes[i].name);
344 if ((*env)->ExceptionOccurred(env)) {
345 msg_Warn(p_dec, "Unable to find class %s", classes[i].name);
346 (*env)->ExceptionClear(env);
352 for (int i = 0; members[i].name; i++) {
353 if (i == 0 || strcmp(members[i].class, members[i - 1].class))
354 last_class = (*env)->FindClass(env, members[i].class);
356 if ((*env)->ExceptionOccurred(env)) {
357 msg_Warn(p_dec, "Unable to find class %s", members[i].class);
358 (*env)->ExceptionClear(env);
362 switch (members[i].type) {
364 *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
365 (*env)->GetMethodID(env, last_class, members[i].name, members[i].sig);
368 *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
369 (*env)->GetStaticMethodID(env, last_class, members[i].name, members[i].sig);
372 *(jfieldID*)((uint8_t*)p_sys + members[i].offset) =
373 (*env)->GetFieldID(env, last_class, members[i].name, members[i].sig);
376 if ((*env)->ExceptionOccurred(env)) {
377 msg_Warn(p_dec, "Unable to find the member %s in %s",
378 members[i].name, members[i].class);
379 (*env)->ExceptionClear(env);
384 int num_codecs = (*env)->CallStaticIntMethod(env, p_sys->media_codec_list_class,
385 p_sys->get_codec_count);
386 jobject codec_name = NULL;
388 for (int i = 0; i < num_codecs; i++) {
389 jobject info = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_list_class,
390 p_sys->get_codec_info_at, i);
391 if ((*env)->CallBooleanMethod(env, info, p_sys->is_encoder)) {
392 (*env)->DeleteLocalRef(env, info);
396 jobject codec_capabilities = (*env)->CallObjectMethod(env, info, p_sys->get_capabilities_for_type,
397 (*env)->NewStringUTF(env, mime));
398 jobject profile_levels = NULL;
399 int profile_levels_len = 0;
400 if ((*env)->ExceptionOccurred(env)) {
401 msg_Warn(p_dec, "Exception occurred in MediaCodecInfo.getCapabilitiesForType");
402 (*env)->ExceptionClear(env);
403 (*env)->DeleteLocalRef(env, info);
405 } else if (codec_capabilities) {
406 profile_levels = (*env)->GetObjectField(env, codec_capabilities, p_sys->profile_levels_field);
408 profile_levels_len = (*env)->GetArrayLength(env, profile_levels);
410 msg_Dbg(p_dec, "Number of profile levels: %d", profile_levels_len);
412 jobject types = (*env)->CallObjectMethod(env, info, p_sys->get_supported_types);
413 int num_types = (*env)->GetArrayLength(env, types);
415 for (int j = 0; j < num_types && !found; j++) {
416 jobject type = (*env)->GetObjectArrayElement(env, types, j);
417 if (!jstrcmp(env, type, mime)) {
418 /* The mime type is matching for this component. We
419 now check if the capabilities of the codec is
420 matching the video format. */
421 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && fmt_profile) {
422 for (int i = 0; i < profile_levels_len && !found; ++i) {
423 jobject profile_level = (*env)->GetObjectArrayElement(env, profile_levels, i);
425 int omx_profile = (*env)->GetIntField(env, profile_level, p_sys->profile_field);
426 size_t codec_profile = convert_omx_to_profile_idc(omx_profile);
427 if (codec_profile != fmt_profile)
429 /* Some encoders set the level too high, thus we ignore it for the moment.
430 We could try to guess the actual profile based on the resolution. */
437 (*env)->DeleteLocalRef(env, type);
440 jobject name = (*env)->CallObjectMethod(env, info, p_sys->get_name);
441 jsize name_len = (*env)->GetStringUTFLength(env, name);
442 const char *name_ptr = (*env)->GetStringUTFChars(env, name, NULL);
443 msg_Dbg(p_dec, "using %.*s", name_len, name_ptr);
444 p_sys->name = malloc(name_len + 1);
445 memcpy(p_sys->name, name_ptr, name_len);
446 p_sys->name[name_len] = '\0';
447 (*env)->ReleaseStringUTFChars(env, name, name_ptr);
449 (*env)->DeleteLocalRef(env, info);
452 (*env)->DeleteLocalRef(env, info);
456 msg_Dbg(p_dec, "No suitable codec matching %s was found", mime);
460 // This method doesn't handle errors nicely, it crashes if the codec isn't found.
461 // (The same goes for createDecoderByType.) This is fixed in latest AOSP and in 4.2,
462 // but not in 4.1 devices.
463 p_sys->codec = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_class,
464 p_sys->create_by_codec_name, codec_name);
465 if ((*env)->ExceptionOccurred(env)) {
466 msg_Warn(p_dec, "Exception occurred in MediaCodec.createByCodecName.");
467 (*env)->ExceptionClear(env);
470 p_sys->allocated = true;
471 p_sys->codec = (*env)->NewGlobalRef(env, p_sys->codec);
473 jobject format = (*env)->CallStaticObjectMethod(env, p_sys->media_format_class,
474 p_sys->create_video_format, (*env)->NewStringUTF(env, mime),
475 p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height);
477 if (p_dec->fmt_in.i_extra) {
478 // Allocate a byte buffer via allocateDirect in java instead of NewDirectByteBuffer,
479 // since the latter doesn't allocate storage of its own, and we don't know how long
480 // the codec uses the buffer.
481 int buf_size = p_dec->fmt_in.i_extra + 20;
482 jobject bytebuf = (*env)->CallStaticObjectMethod(env, p_sys->byte_buffer_class,
483 p_sys->allocate_direct, buf_size);
484 uint32_t size = p_dec->fmt_in.i_extra;
485 uint8_t *ptr = (*env)->GetDirectBufferAddress(env, bytebuf);
486 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && ((uint8_t*)p_dec->fmt_in.p_extra)[0] == 1) {
487 convert_sps_pps(p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
489 &size, &p_sys->nal_size);
490 } else if (p_dec->fmt_in.i_codec == VLC_CODEC_HEVC) {
491 convert_hevc_nal_units(p_dec, p_dec->fmt_in.p_extra,
492 p_dec->fmt_in.i_extra, ptr, buf_size,
493 &size, &p_sys->nal_size);
495 memcpy(ptr, p_dec->fmt_in.p_extra, size);
497 (*env)->CallObjectMethod(env, bytebuf, p_sys->limit, size);
498 (*env)->CallVoidMethod(env, format, p_sys->set_bytebuffer,
499 (*env)->NewStringUTF(env, "csd-0"), bytebuf);
500 (*env)->DeleteLocalRef(env, bytebuf);
503 /* If the VideoPlayerActivity is not started, MediaCodec opaque
504 direct rendering should be disabled since no surface will be
505 attached to the JNI. */
506 p_sys->direct_rendering = jni_IsVideoPlayerActivityCreated() && var_InheritBool(p_dec, CFG_PREFIX "dr");
507 if (p_sys->direct_rendering) {
508 jobject surf = jni_LockAndGetAndroidJavaSurface();
510 // Configure MediaCodec with the Android surface.
511 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, surf, NULL, 0);
512 if ((*env)->ExceptionOccurred(env)) {
513 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure with an output surface.");
514 (*env)->ExceptionClear(env);
515 jni_UnlockAndroidSurface();
518 p_dec->fmt_out.i_codec = VLC_CODEC_ANDROID_OPAQUE;
520 msg_Warn(p_dec, "Failed to get the Android Surface, disabling direct rendering.");
521 p_sys->direct_rendering = false;
523 jni_UnlockAndroidSurface();
525 if (!p_sys->direct_rendering) {
526 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, NULL, NULL, 0);
527 if ((*env)->ExceptionOccurred(env)) {
528 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure");
529 (*env)->ExceptionClear(env);
534 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->start);
535 if ((*env)->ExceptionOccurred(env)) {
536 msg_Warn(p_dec, "Exception occurred in MediaCodec.start");
537 (*env)->ExceptionClear(env);
540 p_sys->started = true;
542 p_sys->input_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffers);
543 p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_buffers);
544 p_sys->buffer_info = (*env)->NewObject(env, p_sys->buffer_info_class, p_sys->buffer_info_ctor);
545 p_sys->input_buffers = (*env)->NewGlobalRef(env, p_sys->input_buffers);
546 p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
547 p_sys->buffer_info = (*env)->NewGlobalRef(env, p_sys->buffer_info);
548 p_sys->i_output_buffers = (*env)->GetArrayLength(env, p_sys->output_buffers);
549 p_sys->inflight_picture = calloc(1, sizeof(picture_t*) * p_sys->i_output_buffers);
550 if (!p_sys->inflight_picture)
552 (*env)->DeleteLocalRef(env, format);
556 const int timestamp_fifo_size = 32;
557 p_sys->timestamp_fifo = timestamp_FifoNew(timestamp_fifo_size);
558 if (!p_sys->timestamp_fifo)
565 CloseDecoder(p_this);
569 static void CloseDecoder(vlc_object_t *p_this)
571 decoder_t *p_dec = (decoder_t *)p_this;
572 decoder_sys_t *p_sys = p_dec->p_sys;
578 /* Invalidate all pictures that are currently in flight in order
579 * to prevent the vout from using destroyed output buffers. */
580 if (p_sys->direct_rendering)
581 InvalidateAllPictures(p_dec);
582 jni_attach_thread(&env, THREAD_NAME);
583 if (p_sys->input_buffers)
584 (*env)->DeleteGlobalRef(env, p_sys->input_buffers);
585 if (p_sys->output_buffers)
586 (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
590 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->stop);
591 if ((*env)->ExceptionOccurred(env)) {
592 msg_Err(p_dec, "Exception in MediaCodec.stop");
593 (*env)->ExceptionClear(env);
596 if (p_sys->allocated)
598 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release);
599 if ((*env)->ExceptionOccurred(env)) {
600 msg_Err(p_dec, "Exception in MediaCodec.release");
601 (*env)->ExceptionClear(env);
604 (*env)->DeleteGlobalRef(env, p_sys->codec);
606 if (p_sys->buffer_info)
607 (*env)->DeleteGlobalRef(env, p_sys->buffer_info);
611 ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
612 free(p_sys->inflight_picture);
613 if (p_sys->timestamp_fifo)
614 timestamp_FifoRelease(p_sys->timestamp_fifo);
618 /*****************************************************************************
620 *****************************************************************************/
621 static void UnlockPicture(picture_t* p_pic)
623 picture_sys_t *p_picsys = p_pic->p_sys;
624 decoder_t *p_dec = p_picsys->priv.hw.p_dec;
625 decoder_sys_t *p_sys = p_dec->p_sys;
627 if (!p_picsys->priv.hw.b_valid)
630 vlc_mutex_lock(get_android_opaque_mutex());
632 /* Picture might have been invalidated while waiting on the mutex. */
633 if (!p_picsys->priv.hw.b_valid) {
634 vlc_mutex_unlock(get_android_opaque_mutex());
638 uint32_t i_index = p_picsys->priv.hw.i_index;
639 bool b_render = p_picsys->b_render;
640 p_sys->inflight_picture[i_index] = NULL;
642 /* Release the MediaCodec buffer. */
644 jni_attach_thread(&env, THREAD_NAME);
645 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_index, b_render);
646 if ((*env)->ExceptionOccurred(env)) {
647 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (DisplayBuffer)");
648 (*env)->ExceptionClear(env);
652 p_picsys->priv.hw.b_valid = false;
654 vlc_mutex_unlock(get_android_opaque_mutex());
657 static void InvalidateAllPictures(decoder_t *p_dec)
659 decoder_sys_t *p_sys = p_dec->p_sys;
661 vlc_mutex_lock(get_android_opaque_mutex());
662 for (int i = 0; i < p_sys->i_output_buffers; ++i) {
663 picture_t *p_pic = p_sys->inflight_picture[i];
665 p_pic->p_sys->priv.hw.b_valid = false;
666 p_sys->inflight_picture[i] = NULL;
669 vlc_mutex_unlock(get_android_opaque_mutex());
672 static void GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
674 decoder_sys_t *p_sys = p_dec->p_sys;
676 int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_output_buffer,
677 p_sys->buffer_info, timeout);
678 if ((*env)->ExceptionOccurred(env)) {
679 msg_Err(p_dec, "Exception in MediaCodec.dequeueOutputBuffer (GetOutput)");
680 (*env)->ExceptionClear(env);
681 p_sys->error_state = true;
686 if (!p_sys->pixel_format) {
687 msg_Warn(p_dec, "Buffers returned before output format is set, dropping frame");
688 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
689 if ((*env)->ExceptionOccurred(env)) {
690 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer");
691 (*env)->ExceptionClear(env);
692 p_sys->error_state = true;
699 *pp_pic = decoder_NewPicture(p_dec);
700 } else if (p_sys->direct_rendering) {
701 picture_t *p_pic = *pp_pic;
702 picture_sys_t *p_picsys = p_pic->p_sys;
703 int i_prev_index = p_picsys->priv.hw.i_index;
704 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_prev_index, false);
705 if ((*env)->ExceptionOccurred(env)) {
706 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer " \
707 "(GetOutput, overwriting previous picture)");
708 (*env)->ExceptionClear(env);
709 p_sys->error_state = true;
713 // No need to lock here since the previous picture was not sent.
714 p_sys->inflight_picture[i_prev_index] = NULL;
718 picture_t *p_pic = *pp_pic;
719 // TODO: Use crop_top/crop_left as well? Or is that already taken into account?
720 // On OMX_TI_COLOR_FormatYUV420PackedSemiPlanar the offset already incldues
721 // the cropping, so the top/left cropping params should just be ignored.
723 /* If the oldest input block had no PTS, the timestamp
724 * of the frame returned by MediaCodec might be wrong
725 * so we overwrite it with the corresponding dts. */
726 int64_t forced_ts = timestamp_FifoGet(p_sys->timestamp_fifo);
727 if (forced_ts == VLC_TS_INVALID)
728 p_pic->date = (*env)->GetLongField(env, p_sys->buffer_info, p_sys->pts_field);
730 p_pic->date = forced_ts;
732 if (p_sys->direct_rendering) {
733 picture_sys_t *p_picsys = p_pic->p_sys;
734 p_picsys->pf_lock_pic = NULL;
735 p_picsys->pf_unlock_pic = UnlockPicture;
736 p_picsys->priv.hw.p_dec = p_dec;
737 p_picsys->priv.hw.i_index = index;
738 p_picsys->priv.hw.b_valid = true;
740 p_sys->inflight_picture[index] = p_pic;
742 jobject buf = (*env)->GetObjectArrayElement(env, p_sys->output_buffers, index);
743 //jsize buf_size = (*env)->GetDirectBufferCapacity(env, buf);
744 uint8_t *ptr = (*env)->GetDirectBufferAddress(env, buf);
746 //int size = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->size_field);
747 int offset = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->offset_field);
748 ptr += offset; // Check the size parameter as well
750 unsigned int chroma_div;
751 GetVlcChromaSizes(p_dec->fmt_out.i_codec, p_dec->fmt_out.video.i_width,
752 p_dec->fmt_out.video.i_height, NULL, NULL, &chroma_div);
753 CopyOmxPicture(p_sys->pixel_format, p_pic, p_sys->slice_height, p_sys->stride,
754 ptr, chroma_div, &p_sys->architecture_specific_data);
755 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
757 jthrowable exception = (*env)->ExceptionOccurred(env);
758 if (exception != NULL) {
759 jclass illegalStateException = (*env)->FindClass(env, "java/lang/IllegalStateException");
760 if((*env)->IsInstanceOf(env, exception, illegalStateException)) {
761 msg_Err(p_dec, "Codec error (IllegalStateException) in MediaCodec.releaseOutputBuffer");
762 (*env)->ExceptionClear(env);
763 (*env)->DeleteLocalRef(env, illegalStateException);
764 p_sys->error_state = true;
767 (*env)->DeleteLocalRef(env, buf);
770 msg_Warn(p_dec, "NewPicture failed");
771 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
772 if ((*env)->ExceptionOccurred(env)) {
773 msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (GetOutput)");
774 (*env)->ExceptionClear(env);
775 p_sys->error_state = true;
780 } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
781 msg_Dbg(p_dec, "output buffers changed");
782 (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
784 p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec,
785 p_sys->get_output_buffers);
786 if ((*env)->ExceptionOccurred(env)) {
787 msg_Err(p_dec, "Exception in MediaCodec.getOutputBuffer (GetOutput)");
788 (*env)->ExceptionClear(env);
789 p_sys->output_buffers = NULL;
790 p_sys->error_state = true;
794 p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
796 vlc_mutex_lock(get_android_opaque_mutex());
797 free(p_sys->inflight_picture);
798 p_sys->i_output_buffers = (*env)->GetArrayLength(env, p_sys->output_buffers);
799 p_sys->inflight_picture = calloc(1, sizeof(picture_t*) * p_sys->i_output_buffers);
800 vlc_mutex_unlock(get_android_opaque_mutex());
802 } else if (index == INFO_OUTPUT_FORMAT_CHANGED) {
803 jobject format = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_format);
804 if ((*env)->ExceptionOccurred(env)) {
805 msg_Err(p_dec, "Exception in MediaCodec.getOutputFormat (GetOutput)");
806 (*env)->ExceptionClear(env);
807 p_sys->error_state = true;
811 jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
813 jsize format_len = (*env)->GetStringUTFLength(env, format_string);
814 const char *format_ptr = (*env)->GetStringUTFChars(env, format_string, NULL);
815 msg_Dbg(p_dec, "output format changed: %.*s", format_len, format_ptr);
816 (*env)->ReleaseStringUTFChars(env, format_string, format_ptr);
818 ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
820 int width = GET_INTEGER(format, "width");
821 int height = GET_INTEGER(format, "height");
822 p_sys->stride = GET_INTEGER(format, "stride");
823 p_sys->slice_height = GET_INTEGER(format, "slice-height");
824 p_sys->pixel_format = GET_INTEGER(format, "color-format");
825 p_sys->crop_left = GET_INTEGER(format, "crop-left");
826 p_sys->crop_top = GET_INTEGER(format, "crop-top");
827 int crop_right = GET_INTEGER(format, "crop-right");
828 int crop_bottom = GET_INTEGER(format, "crop-bottom");
830 const char *name = "unknown";
831 if (p_sys->direct_rendering) {
832 int sar_num = 1, sar_den = 1;
833 if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
834 sar_num = p_dec->fmt_in.video.i_sar_num;
835 sar_den = p_dec->fmt_in.video.i_sar_den;
837 jni_SetAndroidSurfaceSizeEnv(env, width, height, width, height, sar_num, sar_den);
839 if (!GetVlcChromaFormat(p_sys->pixel_format,
840 &p_dec->fmt_out.i_codec, &name)) {
841 msg_Err(p_dec, "color-format not recognized");
842 p_sys->error_state = true;
847 msg_Dbg(p_dec, "output: %d %s, %dx%d stride %d %d, crop %d %d %d %d",
848 p_sys->pixel_format, name, width, height, p_sys->stride, p_sys->slice_height,
849 p_sys->crop_left, p_sys->crop_top, crop_right, crop_bottom);
851 p_dec->fmt_out.video.i_width = crop_right + 1 - p_sys->crop_left;
852 p_dec->fmt_out.video.i_height = crop_bottom + 1 - p_sys->crop_top;
853 if (p_sys->stride <= 0)
854 p_sys->stride = width;
855 if (p_sys->slice_height <= 0)
856 p_sys->slice_height = height;
857 if ((*env)->ExceptionOccurred(env))
858 (*env)->ExceptionClear(env);
860 ArchitectureSpecificCopyHooks(p_dec, p_sys->pixel_format, p_sys->slice_height,
861 p_sys->stride, &p_sys->architecture_specific_data);
862 if (p_sys->pixel_format == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) {
863 p_sys->slice_height -= p_sys->crop_top/2;
864 /* Reset crop top/left here, since the offset parameter already includes this.
865 * If we'd ignore the offset parameter in the BufferInfo, we could just keep
866 * the original slice height and apply the top/left cropping instead. */
868 p_sys->crop_left = 0;
870 if (IgnoreOmxDecoderPadding(p_sys->name)) {
871 p_sys->slice_height = 0;
872 p_sys->stride = p_dec->fmt_out.video.i_width;
881 static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
883 decoder_sys_t *p_sys = p_dec->p_sys;
884 picture_t *p_pic = NULL;
886 struct H264ConvertState convert_state = { 0, 0 };
888 if (!pp_block || !*pp_block)
891 block_t *p_block = *pp_block;
893 if (p_sys->error_state) {
894 block_Release(p_block);
895 if (!p_sys->error_event_sent) {
896 /* Signal the error to the Java. */
897 jni_EventHardwareAccelerationError();
898 p_sys->error_event_sent = true;
903 jni_attach_thread(&env, THREAD_NAME);
905 if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED)) {
906 block_Release(p_block);
907 timestamp_FifoEmpty(p_sys->timestamp_fifo);
908 if (p_sys->decoded) {
909 /* Invalidate all pictures that are currently in flight
910 * since flushing make all previous indices returned by
911 * MediaCodec invalid. */
912 if (p_sys->direct_rendering)
913 InvalidateAllPictures(p_dec);
915 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->flush);
916 if ((*env)->ExceptionOccurred(env)) {
917 msg_Warn(p_dec, "Exception occurred in MediaCodec.flush");
918 (*env)->ExceptionClear(env);
919 p_sys->error_state = true;
922 p_sys->decoded = false;
927 /* Use the aspect ratio provided by the input (ie read from packetizer).
928 * Don't check the current value of the aspect ratio in fmt_out, since we
929 * want to allow changes in it to propagate. */
930 if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
931 p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
932 p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
936 const int max_polling_attempts = 50;
939 int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_input_buffer, (jlong) 0);
940 if ((*env)->ExceptionOccurred(env)) {
941 msg_Err(p_dec, "Exception occurred in MediaCodec.dequeueInputBuffer");
942 (*env)->ExceptionClear(env);
943 p_sys->error_state = true;
948 GetOutput(p_dec, env, &p_pic, timeout);
949 if (p_sys->error_state)
952 /* If we couldn't get an available input buffer but a
953 * decoded frame is available, we return the frame
954 * without assigning NULL to *pp_block. The next call
955 * to DecodeVideo will try to send the input packet again.
962 /* With opaque DR the output buffers are released by the
963 vout therefore we implement a timeout for polling in
964 order to avoid being indefinitely stalled in this loop. */
965 if (p_sys->direct_rendering && attempts == max_polling_attempts) {
966 picture_t *invalid_picture = decoder_NewPicture(p_dec);
967 if (invalid_picture) {
968 invalid_picture->date = VLC_TS_INVALID;
969 picture_sys_t *p_picsys = invalid_picture->p_sys;
970 p_picsys->pf_lock_pic = NULL;
971 p_picsys->pf_unlock_pic = NULL;
972 p_picsys->priv.hw.p_dec = NULL;
973 p_picsys->priv.hw.i_index = -1;
974 p_picsys->priv.hw.b_valid = false;
977 /* If we cannot return a picture we must free the
978 block since the decoder will proceed with the
980 block_Release(p_block);
984 return invalid_picture;
989 jobject buf = (*env)->GetObjectArrayElement(env, p_sys->input_buffers, index);
990 jsize size = (*env)->GetDirectBufferCapacity(env, buf);
991 uint8_t *bufptr = (*env)->GetDirectBufferAddress(env, buf);
993 msg_Err(p_dec, "Java buffer has invalid size");
994 p_sys->error_state = true;
997 if ((size_t) size > p_block->i_buffer)
998 size = p_block->i_buffer;
999 memcpy(bufptr, p_block->p_buffer, size);
1001 convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
1003 int64_t ts = p_block->i_pts;
1004 if (!ts && p_block->i_dts)
1005 ts = p_block->i_dts;
1006 timestamp_FifoPut(p_sys->timestamp_fifo, p_block->i_pts ? VLC_TS_INVALID : p_block->i_dts);
1007 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->queue_input_buffer, index, 0, size, ts, 0);
1008 (*env)->DeleteLocalRef(env, buf);
1009 if ((*env)->ExceptionOccurred(env)) {
1010 msg_Err(p_dec, "Exception in MediaCodec.queueInputBuffer");
1011 (*env)->ExceptionClear(env);
1012 p_sys->error_state = true;
1015 p_sys->decoded = true;
1018 if (p_sys->error_state) {
1020 picture_Release(p_pic);
1021 jni_detach_thread();
1025 GetOutput(p_dec, env, &p_pic, 0);
1026 jni_detach_thread();
1028 block_Release(p_block);