]> git.sesse.net Git - vlc/blob - modules/codec/omxil/android_mediacodec.c
7c27e958408de2b70e563090035418d447135a86
[vlc] / modules / codec / omxil / android_mediacodec.c
1 /*****************************************************************************
2  * android_mediacodec.c: Video decoder module using the Android MediaCodec API
3  *****************************************************************************
4  * Copyright (C) 2012 Martin Storsjo
5  *
6  * Authors: Martin Storsjo <martin@martin.st>
7  *
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.
12  *
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.
17  *
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  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <jni.h>
31 #include <stdint.h>
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_codec.h>
36 #include <vlc_block_helper.h>
37 #include <vlc_cpu.h>
38
39 #include "../h264_nal.h"
40 #include <OMX_Core.h>
41 #include <OMX_Component.h>
42 #include "omxil_utils.h"
43 #include "android_opaque.h"
44
45 #define INFO_OUTPUT_BUFFERS_CHANGED -3
46 #define INFO_OUTPUT_FORMAT_CHANGED  -2
47 #define INFO_TRY_AGAIN_LATER        -1
48
49 extern JavaVM *myVm;
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();
56
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.
66  */
67 typedef struct
68 {
69     uint32_t          begin;
70     uint32_t          size;
71     uint32_t          capacity;
72     int64_t           *buffer;
73 } timestamp_fifo_t;
74
75 static timestamp_fifo_t *timestamp_FifoNew(uint32_t capacity)
76 {
77     timestamp_fifo_t *fifo = calloc(1, sizeof(*fifo));
78     if (!fifo)
79         return NULL;
80     fifo->buffer = malloc(capacity * sizeof(*fifo->buffer));
81     if (!fifo->buffer) {
82         free(fifo);
83         return NULL;
84     }
85     fifo->capacity = capacity;
86     return fifo;
87 }
88
89 static void timestamp_FifoRelease(timestamp_fifo_t *fifo)
90 {
91     free(fifo->buffer);
92     free(fifo);
93 }
94
95 static bool timestamp_FifoIsEmpty(timestamp_fifo_t *fifo)
96 {
97     return fifo->size == 0;
98 }
99
100 static bool timestamp_FifoIsFull(timestamp_fifo_t *fifo)
101 {
102     return fifo->size == fifo->capacity;
103 }
104
105 static void timestamp_FifoEmpty(timestamp_fifo_t *fifo)
106 {
107     fifo->size = 0;
108 }
109
110 static void timestamp_FifoPut(timestamp_fifo_t *fifo, int64_t ts)
111 {
112     uint32_t end = (fifo->begin + fifo->size) % fifo->capacity;
113     fifo->buffer[end] = ts;
114     if (!timestamp_FifoIsFull(fifo))
115         fifo->size += 1;
116     else
117         fifo->begin = (fifo->begin + 1) % fifo->capacity;
118 }
119
120 static int64_t timestamp_FifoGet(timestamp_fifo_t *fifo)
121 {
122     if (timestamp_FifoIsEmpty(fifo))
123         return VLC_TS_INVALID;
124
125     int64_t result = fifo->buffer[fifo->begin];
126     fifo->begin = (fifo->begin + 1) % fifo->capacity;
127     fifo->size -= 1;
128     return result;
129 }
130
131 struct decoder_sys_t
132 {
133     jclass media_codec_list_class, media_codec_class, media_format_class;
134     jclass buffer_info_class, byte_buffer_class;
135     jmethodID tostring;
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;
147
148     uint32_t nal_size;
149
150     jobject codec;
151     jobject buffer_info;
152     jobject input_buffers, output_buffers;
153     int pixel_format;
154     int stride, slice_height;
155     int crop_top, crop_left;
156     char *name;
157
158     bool allocated;
159     bool started;
160     bool decoded;
161     bool error_state;
162     bool error_event_sent;
163
164     ArchitectureSpecificCopyData architecture_specific_data;
165
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 */
170
171     timestamp_fifo_t *timestamp_fifo;
172 };
173
174 enum Types
175 {
176     METHOD, STATIC_METHOD, FIELD
177 };
178
179 #define OFF(x) offsetof(struct decoder_sys_t, x)
180 struct classname
181 {
182     const char *name;
183     int offset;
184 };
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) },
192     { NULL, 0 },
193 };
194
195 struct member
196 {
197     const char *name;
198     const char *sig;
199     const char *class;
200     int offset;
201     int type;
202 };
203 static const struct member members[] = {
204     { "toString", "()Ljava/lang/String;", "java/lang/Object", OFF(tostring), METHOD },
205
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 },
208
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 },
213
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 },
217
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 },
231
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 },
236
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 },
241
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 },
244
245     { NULL, NULL, NULL, 0, 0 },
246 };
247
248 #define GET_INTEGER(obj, name) (*env)->CallIntMethod(env, obj, p_sys->get_integer, (*env)->NewStringUTF(env, name))
249
250 /*****************************************************************************
251  * Local prototypes
252  *****************************************************************************/
253 static int  OpenDecoder(vlc_object_t *);
254 static void CloseDecoder(vlc_object_t *);
255
256 static picture_t *DecodeVideo(decoder_t *, block_t **);
257
258 static void InvalidateAllPictures(decoder_t *);
259
260 /*****************************************************************************
261  * Module descriptor
262  *****************************************************************************/
263 #define DIRECTRENDERING_TEXT N_("Android direct rendering")
264 #define DIRECTRENDERING_LONGTEXT N_(\
265         "Enable Android direct rendering using opaque buffers.")
266
267 #define CFG_PREFIX "mediacodec-"
268
269 vlc_module_begin ()
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 )
278 vlc_module_end ()
279
280 static int jstrcmp(JNIEnv* env, jobject str, const char* str2)
281 {
282     jsize len = (*env)->GetStringUTFLength(env, str);
283     if (len != (jsize) strlen(str2))
284         return -1;
285     const char *ptr = (*env)->GetStringUTFChars(env, str, NULL);
286     int ret = memcmp(ptr, str2, len);
287     (*env)->ReleaseStringUTFChars(env, str, ptr);
288     return ret;
289 }
290
291 /*****************************************************************************
292  * OpenDecoder: Create the decoder instance
293  *****************************************************************************/
294 static int OpenDecoder(vlc_object_t *p_this)
295 {
296     decoder_t *p_dec = (decoder_t*)p_this;
297     decoder_sys_t *p_sys;
298
299     if (p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
300         return VLC_EGENERIC;
301
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;
311     default:
312         msg_Dbg(p_dec, "codec %4.4s not supported", (char *)&p_dec->fmt_in.i_codec);
313         return VLC_EGENERIC;
314     }
315
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);
319
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)
322         return VLC_ENOMEM;
323
324     p_dec->pf_decode_video = DecodeVideo;
325
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;
330
331     JNIEnv* env = NULL;
332     (*myVm)->AttachCurrentThread(myVm, &env, NULL);
333
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);
337
338         if ((*env)->ExceptionOccurred(env)) {
339             msg_Warn(p_dec, "Unable to find class %s", classes[i].name);
340             (*env)->ExceptionClear(env);
341             goto error;
342         }
343     }
344
345     jclass last_class;
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);
349
350         if ((*env)->ExceptionOccurred(env)) {
351             msg_Warn(p_dec, "Unable to find class %s", members[i].class);
352             (*env)->ExceptionClear(env);
353             goto error;
354         }
355
356         switch (members[i].type) {
357         case METHOD:
358             *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
359                 (*env)->GetMethodID(env, last_class, members[i].name, members[i].sig);
360             break;
361         case STATIC_METHOD:
362             *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
363                 (*env)->GetStaticMethodID(env, last_class, members[i].name, members[i].sig);
364             break;
365         case FIELD:
366             *(jfieldID*)((uint8_t*)p_sys + members[i].offset) =
367                 (*env)->GetFieldID(env, last_class, members[i].name, members[i].sig);
368             break;
369         }
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);
374             goto error;
375         }
376     }
377
378     int num_codecs = (*env)->CallStaticIntMethod(env, p_sys->media_codec_list_class,
379                                                  p_sys->get_codec_count);
380     jobject codec_name = NULL;
381
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);
387             continue;
388         }
389
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);
397             break;
398         } else if (codec_capabilities) {
399             profile_levels = (*env)->GetObjectField(env, codec_capabilities, p_sys->profile_levels_field);
400             if (profile_levels)
401                 profile_levels_len = (*env)->GetArrayLength(env, profile_levels);
402         }
403         msg_Dbg(p_dec, "Number of profile levels: %d", profile_levels_len);
404
405         jobject types = (*env)->CallObjectMethod(env, info, p_sys->get_supported_types);
406         int num_types = (*env)->GetArrayLength(env, types);
407         bool found = false;
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);
417
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)
421                             continue;
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. */
424                         found = true;
425                     }
426                 }
427                 else
428                     found = true;
429             }
430             (*env)->DeleteLocalRef(env, type);
431         }
432         if (found) {
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);
441             codec_name = name;
442             break;
443         }
444         (*env)->DeleteLocalRef(env, info);
445     }
446
447     if (!codec_name) {
448         msg_Dbg(p_dec, "No suitable codec matching %s was found", mime);
449         goto error;
450     }
451
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);
460         goto error;
461     }
462     p_sys->allocated = true;
463     p_sys->codec = (*env)->NewGlobalRef(env, p_sys->codec);
464
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);
468
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,
480                             ptr, buf_size,
481                             &size, &p_sys->nal_size);
482         } else {
483             memcpy(ptr, p_dec->fmt_in.p_extra, size);
484         }
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);
489     }
490
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();
497         if (surf) {
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();
504                 goto error;
505             }
506             p_dec->fmt_out.i_codec = VLC_CODEC_ANDROID_OPAQUE;
507         } else {
508             msg_Warn(p_dec, "Failed to get the Android Surface, disabling direct rendering.");
509             p_sys->direct_rendering = false;
510         }
511         jni_UnlockAndroidSurface();
512     }
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);
518             goto error;
519         }
520     }
521
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);
526         goto error;
527     }
528     p_sys->started = true;
529
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)
539         goto error;
540     (*env)->DeleteLocalRef(env, format);
541
542     (*myVm)->DetachCurrentThread(myVm);
543
544     const int timestamp_fifo_size = 32;
545     p_sys->timestamp_fifo = timestamp_FifoNew(timestamp_fifo_size);
546     if (!p_sys->timestamp_fifo)
547         goto error;
548
549     return VLC_SUCCESS;
550
551  error:
552     (*myVm)->DetachCurrentThread(myVm);
553     CloseDecoder(p_this);
554     return VLC_EGENERIC;
555 }
556
557 static void CloseDecoder(vlc_object_t *p_this)
558 {
559     decoder_t *p_dec = (decoder_t *)p_this;
560     decoder_sys_t *p_sys = p_dec->p_sys;
561     JNIEnv *env = NULL;
562
563     if (!p_sys)
564         return;
565
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);
575     if (p_sys->codec) {
576         if (p_sys->started)
577         {
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);
582             }
583         }
584         if (p_sys->allocated)
585         {
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);
590             }
591         }
592         (*env)->DeleteGlobalRef(env, p_sys->codec);
593     }
594     if (p_sys->buffer_info)
595         (*env)->DeleteGlobalRef(env, p_sys->buffer_info);
596     (*myVm)->DetachCurrentThread(myVm);
597
598     free(p_sys->name);
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);
603     free(p_sys);
604 }
605
606 /*****************************************************************************
607  * vout callbacks
608  *****************************************************************************/
609 static void DisplayBuffer(picture_sys_t* p_picsys, bool b_render)
610 {
611     decoder_t *p_dec = p_picsys->p_dec;
612     decoder_sys_t *p_sys = p_dec->p_sys;
613
614     if (!p_picsys->b_valid)
615         return;
616
617     vlc_mutex_lock(get_android_opaque_mutex());
618
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());
622         return;
623     }
624
625     uint32_t i_index = p_picsys->i_index;
626     p_sys->inflight_picture[i_index] = NULL;
627
628     /* Release the MediaCodec buffer. */
629     JNIEnv *env = NULL;
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);
635     }
636
637     (*myVm)->DetachCurrentThread(myVm);
638     p_picsys->b_valid = false;
639
640     vlc_mutex_unlock(get_android_opaque_mutex());
641 }
642
643 static void UnlockCallback(picture_sys_t* p_picsys)
644 {
645     DisplayBuffer(p_picsys, false);
646 }
647
648 static void DisplayCallback(picture_sys_t* p_picsys)
649 {
650     DisplayBuffer(p_picsys, true);
651 }
652
653 static void InvalidateAllPictures(decoder_t *p_dec)
654 {
655     decoder_sys_t *p_sys = p_dec->p_sys;
656
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];
660         if (p_pic) {
661             p_pic->p_sys->b_valid = false;
662             p_sys->inflight_picture[i] = NULL;
663         }
664     }
665     vlc_mutex_unlock(get_android_opaque_mutex());
666 }
667
668 static void GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
669 {
670     decoder_sys_t *p_sys = p_dec->p_sys;
671     while (1) {
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;
678             return;
679         }
680
681         if (index >= 0) {
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;
689                     return;
690                 }
691                 continue;
692             }
693
694             if (!*pp_pic) {
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;
706                     return;
707                 }
708
709                 // No need to lock here since the previous picture was not sent.
710                 p_sys->inflight_picture[i_prev_index] = NULL;
711             }
712             if (*pp_pic) {
713
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.
718
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);
725                 else
726                     p_pic->date = forced_ts;
727
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;
735
736                     p_sys->inflight_picture[index] = p_pic;
737                 } else {
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);
741
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
745
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);
752
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;
761                         }
762                     }
763                     (*env)->DeleteLocalRef(env, buf);
764                 }
765             } else {
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;
772                 }
773             }
774             return;
775
776         } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
777             msg_Dbg(p_dec, "output buffers changed");
778             (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
779
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;
787                 return;
788             }
789
790             p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
791
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());
797
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;
804                 return;
805             }
806
807             jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
808
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);
813
814             ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
815
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");
825
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;
832                 }
833                 jni_SetAndroidSurfaceSizeEnv(env, width, height, width, height, sar_num, sar_den);
834             } else
835                 GetVlcChromaFormat(p_sys->pixel_format, &p_dec->fmt_out.i_codec, &name);
836
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);
840
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);
849
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. */
857                 p_sys->crop_top = 0;
858                 p_sys->crop_left = 0;
859             }
860             if (IgnoreOmxDecoderPadding(p_sys->name)) {
861                 p_sys->slice_height = 0;
862                 p_sys->stride = p_dec->fmt_out.video.i_width;
863             }
864
865         } else {
866             return;
867         }
868     }
869 }
870
871 static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
872 {
873     decoder_sys_t *p_sys = p_dec->p_sys;
874     picture_t *p_pic = NULL;
875     JNIEnv *env = NULL;
876     struct H264ConvertState convert_state = { 0, 0 };
877
878     if (!pp_block || !*pp_block)
879         return NULL;
880
881     block_t *p_block = *pp_block;
882
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;
889         }
890         return NULL;
891     }
892
893     (*myVm)->AttachCurrentThread(myVm, &env, NULL);
894
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);
904
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;
910             }
911         }
912         p_sys->decoded = false;
913         (*myVm)->DetachCurrentThread(myVm);
914         return NULL;
915     }
916
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;
923     }
924
925     jlong timeout = 0;
926     const int max_polling_attempts = 50;
927     int attempts = 0;
928     while (true) {
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;
934             break;
935         }
936
937         if (index < 0) {
938             GetOutput(p_dec, env, &p_pic, timeout);
939             if (p_pic) {
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.
944                  */
945                 (*myVm)->DetachCurrentThread(myVm);
946                 return p_pic;
947             }
948             timeout = 30 * 1000;
949             ++attempts;
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;
963                 }
964                 else {
965                     /* If we cannot return a picture we must free the
966                        block since the decoder will proceed with the
967                        next block. */
968                     block_Release(p_block);
969                     *pp_block = NULL;
970                 }
971                 (*myVm)->DetachCurrentThread(myVm);
972                 return invalid_picture;
973             }
974             continue;
975         }
976
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);
983
984         convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
985
986         int64_t ts = p_block->i_pts;
987         if (!ts && p_block->i_dts)
988             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;
996             break;
997         }
998         p_sys->decoded = true;
999         break;
1000     }
1001     if (!p_pic)
1002         GetOutput(p_dec, env, &p_pic, 0);
1003     (*myVm)->DetachCurrentThread(myVm);
1004
1005     block_Release(p_block);
1006     *pp_block = NULL;
1007
1008     return p_pic;
1009 }