]> git.sesse.net Git - vlc/blob - modules/codec/omxil/android_mediacodec.c
mediacodec: fix comparison between signed and unsigned warning
[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 "../hevc_nal.h"
41 #include <OMX_Core.h>
42 #include <OMX_Component.h>
43 #include "omxil_utils.h"
44 #include "android_opaque.h"
45
46 #define INFO_OUTPUT_BUFFERS_CHANGED -3
47 #define INFO_OUTPUT_FORMAT_CHANGED  -2
48 #define INFO_TRY_AGAIN_LATER        -1
49
50 #define THREAD_NAME "android_mediacodec"
51
52 extern int jni_attach_thread(JNIEnv **env, const char *thread_name);
53 extern void jni_detach_thread();
54 /* JNI functions to get/set an Android Surface object. */
55 extern jobject jni_LockAndGetAndroidJavaSurface();
56 extern void jni_UnlockAndroidSurface();
57 extern void jni_SetAndroidSurfaceSizeEnv(JNIEnv *p_env, int width, int height, int visible_width, int visible_height, int sar_num, int sar_den);
58 extern void jni_EventHardwareAccelerationError();
59 extern bool jni_IsVideoPlayerActivityCreated();
60
61 /* Implementation of a circular buffer of timestamps with overwriting
62  * of older values. MediaCodec has only one type of timestamp, if a
63  * block has no PTS, we send the DTS instead. Some hardware decoders
64  * cannot cope with this situation and output the frames in the wrong
65  * order. As a workaround in this case, we use a FIFO of timestamps in
66  * order to remember which input packets had no PTS.  Since an
67  * hardware decoder can silently drop frames, this might cause a
68  * growing desynchronization with the actual timestamp. Thus the
69  * circular buffer has a limited size and will overwrite older values.
70  */
71 typedef struct
72 {
73     uint32_t          begin;
74     uint32_t          size;
75     uint32_t          capacity;
76     int64_t           *buffer;
77 } timestamp_fifo_t;
78
79 static timestamp_fifo_t *timestamp_FifoNew(uint32_t capacity)
80 {
81     timestamp_fifo_t *fifo = calloc(1, sizeof(*fifo));
82     if (!fifo)
83         return NULL;
84     fifo->buffer = malloc(capacity * sizeof(*fifo->buffer));
85     if (!fifo->buffer) {
86         free(fifo);
87         return NULL;
88     }
89     fifo->capacity = capacity;
90     return fifo;
91 }
92
93 static void timestamp_FifoRelease(timestamp_fifo_t *fifo)
94 {
95     free(fifo->buffer);
96     free(fifo);
97 }
98
99 static bool timestamp_FifoIsEmpty(timestamp_fifo_t *fifo)
100 {
101     return fifo->size == 0;
102 }
103
104 static bool timestamp_FifoIsFull(timestamp_fifo_t *fifo)
105 {
106     return fifo->size == fifo->capacity;
107 }
108
109 static void timestamp_FifoEmpty(timestamp_fifo_t *fifo)
110 {
111     fifo->size = 0;
112 }
113
114 static void timestamp_FifoPut(timestamp_fifo_t *fifo, int64_t ts)
115 {
116     uint32_t end = (fifo->begin + fifo->size) % fifo->capacity;
117     fifo->buffer[end] = ts;
118     if (!timestamp_FifoIsFull(fifo))
119         fifo->size += 1;
120     else
121         fifo->begin = (fifo->begin + 1) % fifo->capacity;
122 }
123
124 static int64_t timestamp_FifoGet(timestamp_fifo_t *fifo)
125 {
126     if (timestamp_FifoIsEmpty(fifo))
127         return VLC_TS_INVALID;
128
129     int64_t result = fifo->buffer[fifo->begin];
130     fifo->begin = (fifo->begin + 1) % fifo->capacity;
131     fifo->size -= 1;
132     return result;
133 }
134
135 struct decoder_sys_t
136 {
137     jclass media_codec_list_class, media_codec_class, media_format_class;
138     jclass buffer_info_class, byte_buffer_class;
139     jmethodID tostring;
140     jmethodID get_codec_count, get_codec_info_at, is_encoder, get_capabilities_for_type;
141     jfieldID profile_levels_field, profile_field, level_field;
142     jmethodID get_supported_types, get_name;
143     jmethodID create_by_codec_name, configure, start, stop, flush, release;
144     jmethodID get_output_format, get_input_buffers, get_output_buffers;
145     jmethodID dequeue_input_buffer, dequeue_output_buffer, queue_input_buffer;
146     jmethodID release_output_buffer;
147     jmethodID create_video_format, set_integer, set_bytebuffer, get_integer;
148     jmethodID buffer_info_ctor;
149     jmethodID allocate_direct, limit;
150     jfieldID size_field, offset_field, pts_field;
151
152     uint32_t nal_size;
153
154     jobject codec;
155     jobject buffer_info;
156     jobject input_buffers, output_buffers;
157     int pixel_format;
158     int stride, slice_height;
159     int crop_top, crop_left;
160     char *name;
161
162     bool allocated;
163     bool started;
164     bool decoded;
165     bool error_state;
166     bool error_event_sent;
167
168     ArchitectureSpecificCopyData architecture_specific_data;
169
170     /* Direct rendering members. */
171     bool direct_rendering;
172     int i_output_buffers; /**< number of MediaCodec output buffers */
173     picture_t** inflight_picture; /**< stores the inflight picture for each output buffer or NULL */
174
175     timestamp_fifo_t *timestamp_fifo;
176 };
177
178 enum Types
179 {
180     METHOD, STATIC_METHOD, FIELD
181 };
182
183 #define OFF(x) offsetof(struct decoder_sys_t, x)
184 struct classname
185 {
186     const char *name;
187     int offset;
188 };
189 static const struct classname classes[] = {
190     { "android/media/MediaCodecList", OFF(media_codec_list_class) },
191     { "android/media/MediaCodec", OFF(media_codec_class) },
192     { "android/media/MediaFormat", OFF(media_format_class) },
193     { "android/media/MediaFormat", OFF(media_format_class) },
194     { "android/media/MediaCodec$BufferInfo", OFF(buffer_info_class) },
195     { "java/nio/ByteBuffer", OFF(byte_buffer_class) },
196     { NULL, 0 },
197 };
198
199 struct member
200 {
201     const char *name;
202     const char *sig;
203     const char *class;
204     int offset;
205     int type;
206 };
207 static const struct member members[] = {
208     { "toString", "()Ljava/lang/String;", "java/lang/Object", OFF(tostring), METHOD },
209
210     { "getCodecCount", "()I", "android/media/MediaCodecList", OFF(get_codec_count), STATIC_METHOD },
211     { "getCodecInfoAt", "(I)Landroid/media/MediaCodecInfo;", "android/media/MediaCodecList", OFF(get_codec_info_at), STATIC_METHOD },
212
213     { "isEncoder", "()Z", "android/media/MediaCodecInfo", OFF(is_encoder), METHOD },
214     { "getSupportedTypes", "()[Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_supported_types), METHOD },
215     { "getName", "()Ljava/lang/String;", "android/media/MediaCodecInfo", OFF(get_name), METHOD },
216     { "getCapabilitiesForType", "(Ljava/lang/String;)Landroid/media/MediaCodecInfo$CodecCapabilities;", "android/media/MediaCodecInfo", OFF(get_capabilities_for_type), METHOD },
217
218     { "profileLevels", "[Landroid/media/MediaCodecInfo$CodecProfileLevel;", "android/media/MediaCodecInfo$CodecCapabilities", OFF(profile_levels_field), FIELD },
219     { "profile", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(profile_field), FIELD },
220     { "level", "I", "android/media/MediaCodecInfo$CodecProfileLevel", OFF(level_field), FIELD },
221
222     { "createByCodecName", "(Ljava/lang/String;)Landroid/media/MediaCodec;", "android/media/MediaCodec", OFF(create_by_codec_name), STATIC_METHOD },
223     { "configure", "(Landroid/media/MediaFormat;Landroid/view/Surface;Landroid/media/MediaCrypto;I)V", "android/media/MediaCodec", OFF(configure), METHOD },
224     { "start", "()V", "android/media/MediaCodec", OFF(start), METHOD },
225     { "stop", "()V", "android/media/MediaCodec", OFF(stop), METHOD },
226     { "flush", "()V", "android/media/MediaCodec", OFF(flush), METHOD },
227     { "release", "()V", "android/media/MediaCodec", OFF(release), METHOD },
228     { "getOutputFormat", "()Landroid/media/MediaFormat;", "android/media/MediaCodec", OFF(get_output_format), METHOD },
229     { "getInputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_input_buffers), METHOD },
230     { "getOutputBuffers", "()[Ljava/nio/ByteBuffer;", "android/media/MediaCodec", OFF(get_output_buffers), METHOD },
231     { "dequeueInputBuffer", "(J)I", "android/media/MediaCodec", OFF(dequeue_input_buffer), METHOD },
232     { "dequeueOutputBuffer", "(Landroid/media/MediaCodec$BufferInfo;J)I", "android/media/MediaCodec", OFF(dequeue_output_buffer), METHOD },
233     { "queueInputBuffer", "(IIIJI)V", "android/media/MediaCodec", OFF(queue_input_buffer), METHOD },
234     { "releaseOutputBuffer", "(IZ)V", "android/media/MediaCodec", OFF(release_output_buffer), METHOD },
235
236     { "createVideoFormat", "(Ljava/lang/String;II)Landroid/media/MediaFormat;", "android/media/MediaFormat", OFF(create_video_format), STATIC_METHOD },
237     { "setInteger", "(Ljava/lang/String;I)V", "android/media/MediaFormat", OFF(set_integer), METHOD },
238     { "getInteger", "(Ljava/lang/String;)I", "android/media/MediaFormat", OFF(get_integer), METHOD },
239     { "setByteBuffer", "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V", "android/media/MediaFormat", OFF(set_bytebuffer), METHOD },
240
241     { "<init>", "()V", "android/media/MediaCodec$BufferInfo", OFF(buffer_info_ctor), METHOD },
242     { "size", "I", "android/media/MediaCodec$BufferInfo", OFF(size_field), FIELD },
243     { "offset", "I", "android/media/MediaCodec$BufferInfo", OFF(offset_field), FIELD },
244     { "presentationTimeUs", "J", "android/media/MediaCodec$BufferInfo", OFF(pts_field), FIELD },
245
246     { "allocateDirect", "(I)Ljava/nio/ByteBuffer;", "java/nio/ByteBuffer", OFF(allocate_direct), STATIC_METHOD },
247     { "limit", "(I)Ljava/nio/Buffer;", "java/nio/ByteBuffer", OFF(limit), METHOD },
248
249     { NULL, NULL, NULL, 0, 0 },
250 };
251
252 #define GET_INTEGER(obj, name) (*env)->CallIntMethod(env, obj, p_sys->get_integer, (*env)->NewStringUTF(env, name))
253
254 /*****************************************************************************
255  * Local prototypes
256  *****************************************************************************/
257 static int  OpenDecoder(vlc_object_t *);
258 static void CloseDecoder(vlc_object_t *);
259
260 static picture_t *DecodeVideo(decoder_t *, block_t **);
261
262 static void InvalidateAllPictures(decoder_t *);
263
264 /*****************************************************************************
265  * Module descriptor
266  *****************************************************************************/
267 #define DIRECTRENDERING_TEXT N_("Android direct rendering")
268 #define DIRECTRENDERING_LONGTEXT N_(\
269         "Enable Android direct rendering using opaque buffers.")
270
271 #define CFG_PREFIX "mediacodec-"
272
273 vlc_module_begin ()
274     set_description( N_("Video decoder using Android MediaCodec") )
275     set_category( CAT_INPUT )
276     set_subcategory( SUBCAT_INPUT_VCODEC )
277     set_section( N_("Decoding") , NULL )
278     set_capability( "decoder", 0 ) /* Only enabled via commandline arguments */
279     add_bool(CFG_PREFIX "dr", true,
280              DIRECTRENDERING_TEXT, DIRECTRENDERING_LONGTEXT, true)
281     set_callbacks( OpenDecoder, CloseDecoder )
282 vlc_module_end ()
283
284 static int jstrcmp(JNIEnv* env, jobject str, const char* str2)
285 {
286     jsize len = (*env)->GetStringUTFLength(env, str);
287     if (len != (jsize) strlen(str2))
288         return -1;
289     const char *ptr = (*env)->GetStringUTFChars(env, str, NULL);
290     int ret = memcmp(ptr, str2, len);
291     (*env)->ReleaseStringUTFChars(env, str, ptr);
292     return ret;
293 }
294
295 /*****************************************************************************
296  * OpenDecoder: Create the decoder instance
297  *****************************************************************************/
298 static int OpenDecoder(vlc_object_t *p_this)
299 {
300     decoder_t *p_dec = (decoder_t*)p_this;
301     decoder_sys_t *p_sys;
302
303     if (p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
304         return VLC_EGENERIC;
305
306     const char *mime = NULL;
307     switch (p_dec->fmt_in.i_codec) {
308     case VLC_CODEC_HEVC: mime = "video/hevc"; break;
309     case VLC_CODEC_H264: mime = "video/avc"; break;
310     case VLC_CODEC_H263: mime = "video/3gpp"; break;
311     case VLC_CODEC_MP4V: mime = "video/mp4v-es"; break;
312     case VLC_CODEC_WMV3: mime = "video/x-ms-wmv"; break;
313     case VLC_CODEC_VC1:  mime = "video/wvc1"; break;
314     case VLC_CODEC_VP8:  mime = "video/x-vnd.on2.vp8"; break;
315     case VLC_CODEC_VP9:  mime = "video/x-vnd.on2.vp9"; break;
316     default:
317         msg_Dbg(p_dec, "codec %4.4s not supported", (char *)&p_dec->fmt_in.i_codec);
318         return VLC_EGENERIC;
319     }
320
321     size_t fmt_profile = 0;
322     if (p_dec->fmt_in.i_codec == VLC_CODEC_H264)
323         h264_get_profile_level(&p_dec->fmt_in, &fmt_profile, NULL, NULL);
324
325     /* Allocate the memory needed to store the decoder's structure */
326     if ((p_dec->p_sys = p_sys = calloc(1, sizeof(*p_sys))) == NULL)
327         return VLC_ENOMEM;
328
329     p_dec->pf_decode_video = DecodeVideo;
330
331     p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
332     p_dec->fmt_out.video = p_dec->fmt_in.video;
333     p_dec->fmt_out.audio = p_dec->fmt_in.audio;
334     p_dec->b_need_packetized = true;
335
336     JNIEnv* env = NULL;
337     jni_attach_thread(&env, THREAD_NAME);
338
339     for (int i = 0; classes[i].name; i++) {
340         *(jclass*)((uint8_t*)p_sys + classes[i].offset) =
341             (*env)->FindClass(env, classes[i].name);
342
343         if ((*env)->ExceptionOccurred(env)) {
344             msg_Warn(p_dec, "Unable to find class %s", classes[i].name);
345             (*env)->ExceptionClear(env);
346             goto error;
347         }
348     }
349
350     jclass last_class;
351     for (int i = 0; members[i].name; i++) {
352         if (i == 0 || strcmp(members[i].class, members[i - 1].class))
353             last_class = (*env)->FindClass(env, members[i].class);
354
355         if ((*env)->ExceptionOccurred(env)) {
356             msg_Warn(p_dec, "Unable to find class %s", members[i].class);
357             (*env)->ExceptionClear(env);
358             goto error;
359         }
360
361         switch (members[i].type) {
362         case METHOD:
363             *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
364                 (*env)->GetMethodID(env, last_class, members[i].name, members[i].sig);
365             break;
366         case STATIC_METHOD:
367             *(jmethodID*)((uint8_t*)p_sys + members[i].offset) =
368                 (*env)->GetStaticMethodID(env, last_class, members[i].name, members[i].sig);
369             break;
370         case FIELD:
371             *(jfieldID*)((uint8_t*)p_sys + members[i].offset) =
372                 (*env)->GetFieldID(env, last_class, members[i].name, members[i].sig);
373             break;
374         }
375         if ((*env)->ExceptionOccurred(env)) {
376             msg_Warn(p_dec, "Unable to find the member %s in %s",
377                      members[i].name, members[i].class);
378             (*env)->ExceptionClear(env);
379             goto error;
380         }
381     }
382
383     int num_codecs = (*env)->CallStaticIntMethod(env, p_sys->media_codec_list_class,
384                                                  p_sys->get_codec_count);
385     jobject codec_name = NULL;
386
387     for (int i = 0; i < num_codecs; i++) {
388         jobject info = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_list_class,
389                                                       p_sys->get_codec_info_at, i);
390         if ((*env)->CallBooleanMethod(env, info, p_sys->is_encoder)) {
391             (*env)->DeleteLocalRef(env, info);
392             continue;
393         }
394
395         jobject codec_capabilities = (*env)->CallObjectMethod(env, info, p_sys->get_capabilities_for_type,
396                                                               (*env)->NewStringUTF(env, mime));
397         jobject profile_levels = NULL;
398         int profile_levels_len = 0;
399         if ((*env)->ExceptionOccurred(env)) {
400             msg_Warn(p_dec, "Exception occurred in MediaCodecInfo.getCapabilitiesForType");
401             (*env)->ExceptionClear(env);
402             break;
403         } else if (codec_capabilities) {
404             profile_levels = (*env)->GetObjectField(env, codec_capabilities, p_sys->profile_levels_field);
405             if (profile_levels)
406                 profile_levels_len = (*env)->GetArrayLength(env, profile_levels);
407         }
408         msg_Dbg(p_dec, "Number of profile levels: %d", profile_levels_len);
409
410         jobject types = (*env)->CallObjectMethod(env, info, p_sys->get_supported_types);
411         int num_types = (*env)->GetArrayLength(env, types);
412         bool found = false;
413         for (int j = 0; j < num_types && !found; j++) {
414             jobject type = (*env)->GetObjectArrayElement(env, types, j);
415             if (!jstrcmp(env, type, mime)) {
416                 /* The mime type is matching for this component. We
417                    now check if the capabilities of the codec is
418                    matching the video format. */
419                 if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && fmt_profile) {
420                     for (int i = 0; i < profile_levels_len && !found; ++i) {
421                         jobject profile_level = (*env)->GetObjectArrayElement(env, profile_levels, i);
422
423                         int omx_profile = (*env)->GetIntField(env, profile_level, p_sys->profile_field);
424                         size_t codec_profile = convert_omx_to_profile_idc(omx_profile);
425                         if (codec_profile != fmt_profile)
426                             continue;
427                         /* Some encoders set the level too high, thus we ignore it for the moment.
428                            We could try to guess the actual profile based on the resolution. */
429                         found = true;
430                     }
431                 }
432                 else
433                     found = true;
434             }
435             (*env)->DeleteLocalRef(env, type);
436         }
437         if (found) {
438             jobject name = (*env)->CallObjectMethod(env, info, p_sys->get_name);
439             jsize name_len = (*env)->GetStringUTFLength(env, name);
440             const char *name_ptr = (*env)->GetStringUTFChars(env, name, NULL);
441             msg_Dbg(p_dec, "using %.*s", name_len, name_ptr);
442             p_sys->name = malloc(name_len + 1);
443             memcpy(p_sys->name, name_ptr, name_len);
444             p_sys->name[name_len] = '\0';
445             (*env)->ReleaseStringUTFChars(env, name, name_ptr);
446             codec_name = name;
447             break;
448         }
449         (*env)->DeleteLocalRef(env, info);
450     }
451
452     if (!codec_name) {
453         msg_Dbg(p_dec, "No suitable codec matching %s was found", mime);
454         goto error;
455     }
456
457     // This method doesn't handle errors nicely, it crashes if the codec isn't found.
458     // (The same goes for createDecoderByType.) This is fixed in latest AOSP and in 4.2,
459     // but not in 4.1 devices.
460     p_sys->codec = (*env)->CallStaticObjectMethod(env, p_sys->media_codec_class,
461                                                   p_sys->create_by_codec_name, codec_name);
462     if ((*env)->ExceptionOccurred(env)) {
463         msg_Warn(p_dec, "Exception occurred in MediaCodec.createByCodecName.");
464         (*env)->ExceptionClear(env);
465         goto error;
466     }
467     p_sys->allocated = true;
468     p_sys->codec = (*env)->NewGlobalRef(env, p_sys->codec);
469
470     jobject format = (*env)->CallStaticObjectMethod(env, p_sys->media_format_class,
471                          p_sys->create_video_format, (*env)->NewStringUTF(env, mime),
472                          p_dec->fmt_in.video.i_width, p_dec->fmt_in.video.i_height);
473
474     if (p_dec->fmt_in.i_extra) {
475         // Allocate a byte buffer via allocateDirect in java instead of NewDirectByteBuffer,
476         // since the latter doesn't allocate storage of its own, and we don't know how long
477         // the codec uses the buffer.
478         int buf_size = p_dec->fmt_in.i_extra + 20;
479         jobject bytebuf = (*env)->CallStaticObjectMethod(env, p_sys->byte_buffer_class,
480                                                          p_sys->allocate_direct, buf_size);
481         uint32_t size = p_dec->fmt_in.i_extra;
482         uint8_t *ptr = (*env)->GetDirectBufferAddress(env, bytebuf);
483         if (p_dec->fmt_in.i_codec == VLC_CODEC_H264 && ((uint8_t*)p_dec->fmt_in.p_extra)[0] == 1) {
484             convert_sps_pps(p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
485                             ptr, buf_size,
486                             &size, &p_sys->nal_size);
487         } else if (p_dec->fmt_in.i_codec == VLC_CODEC_HEVC) {
488             convert_hevc_nal_units(p_dec, p_dec->fmt_in.p_extra,
489                                    p_dec->fmt_in.i_extra, ptr, buf_size,
490                                    &size, &p_sys->nal_size);
491         } else {
492             memcpy(ptr, p_dec->fmt_in.p_extra, size);
493         }
494         (*env)->CallObjectMethod(env, bytebuf, p_sys->limit, size);
495         (*env)->CallVoidMethod(env, format, p_sys->set_bytebuffer,
496                                (*env)->NewStringUTF(env, "csd-0"), bytebuf);
497         (*env)->DeleteLocalRef(env, bytebuf);
498     }
499
500     /* If the VideoPlayerActivity is not started, MediaCodec opaque
501        direct rendering should be disabled since no surface will be
502        attached to the JNI. */
503     p_sys->direct_rendering = jni_IsVideoPlayerActivityCreated() && var_InheritBool(p_dec, CFG_PREFIX "dr");
504     if (p_sys->direct_rendering) {
505         jobject surf = jni_LockAndGetAndroidJavaSurface();
506         if (surf) {
507             // Configure MediaCodec with the Android surface.
508             (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, surf, NULL, 0);
509             if ((*env)->ExceptionOccurred(env)) {
510                 msg_Warn(p_dec, "Exception occurred in MediaCodec.configure with an output surface.");
511                 (*env)->ExceptionClear(env);
512                 jni_UnlockAndroidSurface();
513                 goto error;
514             }
515             p_dec->fmt_out.i_codec = VLC_CODEC_ANDROID_OPAQUE;
516         } else {
517             msg_Warn(p_dec, "Failed to get the Android Surface, disabling direct rendering.");
518             p_sys->direct_rendering = false;
519         }
520         jni_UnlockAndroidSurface();
521     }
522     if (!p_sys->direct_rendering) {
523         (*env)->CallVoidMethod(env, p_sys->codec, p_sys->configure, format, NULL, NULL, 0);
524         if ((*env)->ExceptionOccurred(env)) {
525             msg_Warn(p_dec, "Exception occurred in MediaCodec.configure");
526             (*env)->ExceptionClear(env);
527             goto error;
528         }
529     }
530
531     (*env)->CallVoidMethod(env, p_sys->codec, p_sys->start);
532     if ((*env)->ExceptionOccurred(env)) {
533         msg_Warn(p_dec, "Exception occurred in MediaCodec.start");
534         (*env)->ExceptionClear(env);
535         goto error;
536     }
537     p_sys->started = true;
538
539     p_sys->input_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffers);
540     p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_buffers);
541     p_sys->buffer_info = (*env)->NewObject(env, p_sys->buffer_info_class, p_sys->buffer_info_ctor);
542     p_sys->input_buffers = (*env)->NewGlobalRef(env, p_sys->input_buffers);
543     p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
544     p_sys->buffer_info = (*env)->NewGlobalRef(env, p_sys->buffer_info);
545     p_sys->i_output_buffers = (*env)->GetArrayLength(env, p_sys->output_buffers);
546     p_sys->inflight_picture = calloc(1, sizeof(picture_t*) * p_sys->i_output_buffers);
547     if (!p_sys->inflight_picture)
548         goto error;
549     (*env)->DeleteLocalRef(env, format);
550
551     jni_detach_thread();
552
553     const int timestamp_fifo_size = 32;
554     p_sys->timestamp_fifo = timestamp_FifoNew(timestamp_fifo_size);
555     if (!p_sys->timestamp_fifo)
556         goto error;
557
558     return VLC_SUCCESS;
559
560  error:
561     jni_detach_thread();
562     CloseDecoder(p_this);
563     return VLC_EGENERIC;
564 }
565
566 static void CloseDecoder(vlc_object_t *p_this)
567 {
568     decoder_t *p_dec = (decoder_t *)p_this;
569     decoder_sys_t *p_sys = p_dec->p_sys;
570     JNIEnv *env = NULL;
571
572     if (!p_sys)
573         return;
574
575     /* Invalidate all pictures that are currently in flight in order
576      * to prevent the vout from using destroyed output buffers. */
577     if (p_sys->direct_rendering)
578         InvalidateAllPictures(p_dec);
579     jni_attach_thread(&env, THREAD_NAME);
580     if (p_sys->input_buffers)
581         (*env)->DeleteGlobalRef(env, p_sys->input_buffers);
582     if (p_sys->output_buffers)
583         (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
584     if (p_sys->codec) {
585         if (p_sys->started)
586         {
587             (*env)->CallVoidMethod(env, p_sys->codec, p_sys->stop);
588             if ((*env)->ExceptionOccurred(env)) {
589                 msg_Err(p_dec, "Exception in MediaCodec.stop");
590                 (*env)->ExceptionClear(env);
591             }
592         }
593         if (p_sys->allocated)
594         {
595             (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release);
596             if ((*env)->ExceptionOccurred(env)) {
597                 msg_Err(p_dec, "Exception in MediaCodec.release");
598                 (*env)->ExceptionClear(env);
599             }
600         }
601         (*env)->DeleteGlobalRef(env, p_sys->codec);
602     }
603     if (p_sys->buffer_info)
604         (*env)->DeleteGlobalRef(env, p_sys->buffer_info);
605     jni_detach_thread();
606
607     free(p_sys->name);
608     ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
609     free(p_sys->inflight_picture);
610     if (p_sys->timestamp_fifo)
611         timestamp_FifoRelease(p_sys->timestamp_fifo);
612     free(p_sys);
613 }
614
615 /*****************************************************************************
616  * vout callbacks
617  *****************************************************************************/
618 static void DisplayBuffer(picture_sys_t* p_picsys, bool b_render)
619 {
620     decoder_t *p_dec = p_picsys->p_dec;
621     decoder_sys_t *p_sys = p_dec->p_sys;
622
623     if (!p_picsys->b_valid)
624         return;
625
626     vlc_mutex_lock(get_android_opaque_mutex());
627
628     /* Picture might have been invalidated while waiting on the mutex. */
629     if (!p_picsys->b_valid) {
630         vlc_mutex_unlock(get_android_opaque_mutex());
631         return;
632     }
633
634     uint32_t i_index = p_picsys->i_index;
635     p_sys->inflight_picture[i_index] = NULL;
636
637     /* Release the MediaCodec buffer. */
638     JNIEnv *env = NULL;
639     jni_attach_thread(&env, THREAD_NAME);
640     (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_index, b_render);
641     if ((*env)->ExceptionOccurred(env)) {
642         msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (DisplayBuffer)");
643         (*env)->ExceptionClear(env);
644     }
645
646     jni_detach_thread();
647     p_picsys->b_valid = false;
648
649     vlc_mutex_unlock(get_android_opaque_mutex());
650 }
651
652 static void UnlockCallback(picture_sys_t* p_picsys)
653 {
654     DisplayBuffer(p_picsys, false);
655 }
656
657 static void DisplayCallback(picture_sys_t* p_picsys)
658 {
659     DisplayBuffer(p_picsys, true);
660 }
661
662 static void InvalidateAllPictures(decoder_t *p_dec)
663 {
664     decoder_sys_t *p_sys = p_dec->p_sys;
665
666     vlc_mutex_lock(get_android_opaque_mutex());
667     for (int i = 0; i < p_sys->i_output_buffers; ++i) {
668         picture_t *p_pic = p_sys->inflight_picture[i];
669         if (p_pic) {
670             p_pic->p_sys->b_valid = false;
671             p_sys->inflight_picture[i] = NULL;
672         }
673     }
674     vlc_mutex_unlock(get_android_opaque_mutex());
675 }
676
677 static void GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
678 {
679     decoder_sys_t *p_sys = p_dec->p_sys;
680     while (1) {
681         int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_output_buffer,
682                                           p_sys->buffer_info, timeout);
683         if ((*env)->ExceptionOccurred(env)) {
684             msg_Err(p_dec, "Exception in MediaCodec.dequeueOutputBuffer (GetOutput)");
685             (*env)->ExceptionClear(env);
686             p_sys->error_state = true;
687             return;
688         }
689
690         if (index >= 0) {
691             if (!p_sys->pixel_format) {
692                 msg_Warn(p_dec, "Buffers returned before output format is set, dropping frame");
693                 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
694                 if ((*env)->ExceptionOccurred(env)) {
695                     msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer");
696                     (*env)->ExceptionClear(env);
697                     p_sys->error_state = true;
698                     return;
699                 }
700                 continue;
701             }
702
703             if (!*pp_pic) {
704                 *pp_pic = decoder_NewPicture(p_dec);
705             } else if (p_sys->direct_rendering) {
706                 picture_t *p_pic = *pp_pic;
707                 picture_sys_t *p_picsys = p_pic->p_sys;
708                 int i_prev_index = p_picsys->i_index;
709                 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_prev_index, false);
710                 if ((*env)->ExceptionOccurred(env)) {
711                     msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer " \
712                             "(GetOutput, overwriting previous picture)");
713                     (*env)->ExceptionClear(env);
714                     p_sys->error_state = true;
715                     return;
716                 }
717
718                 // No need to lock here since the previous picture was not sent.
719                 p_sys->inflight_picture[i_prev_index] = NULL;
720             }
721             if (*pp_pic) {
722
723                 picture_t *p_pic = *pp_pic;
724                 // TODO: Use crop_top/crop_left as well? Or is that already taken into account?
725                 // On OMX_TI_COLOR_FormatYUV420PackedSemiPlanar the offset already incldues
726                 // the cropping, so the top/left cropping params should just be ignored.
727
728                 /* If the oldest input block had no PTS, the timestamp
729                  * of the frame returned by MediaCodec might be wrong
730                  * so we overwrite it with the corresponding dts. */
731                 int64_t forced_ts = timestamp_FifoGet(p_sys->timestamp_fifo);
732                 if (forced_ts == VLC_TS_INVALID)
733                     p_pic->date = (*env)->GetLongField(env, p_sys->buffer_info, p_sys->pts_field);
734                 else
735                     p_pic->date = forced_ts;
736
737                 if (p_sys->direct_rendering) {
738                     picture_sys_t *p_picsys = p_pic->p_sys;
739                     p_picsys->pf_display_callback = DisplayCallback;
740                     p_picsys->pf_unlock_callback = UnlockCallback;
741                     p_picsys->p_dec = p_dec;
742                     p_picsys->i_index = index;
743                     p_picsys->b_valid = true;
744
745                     p_sys->inflight_picture[index] = p_pic;
746                 } else {
747                     jobject buf = (*env)->GetObjectArrayElement(env, p_sys->output_buffers, index);
748                     //jsize buf_size = (*env)->GetDirectBufferCapacity(env, buf);
749                     uint8_t *ptr = (*env)->GetDirectBufferAddress(env, buf);
750
751                     //int size = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->size_field);
752                     int offset = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->offset_field);
753                     ptr += offset; // Check the size parameter as well
754
755                     unsigned int chroma_div;
756                     GetVlcChromaSizes(p_dec->fmt_out.i_codec, p_dec->fmt_out.video.i_width,
757                                       p_dec->fmt_out.video.i_height, NULL, NULL, &chroma_div);
758                     CopyOmxPicture(p_sys->pixel_format, p_pic, p_sys->slice_height, p_sys->stride,
759                                    ptr, chroma_div, &p_sys->architecture_specific_data);
760                     (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
761
762                     jthrowable exception = (*env)->ExceptionOccurred(env);
763                     if (exception != NULL) {
764                         jclass illegalStateException = (*env)->FindClass(env, "java/lang/IllegalStateException");
765                         if((*env)->IsInstanceOf(env, exception, illegalStateException)) {
766                             msg_Err(p_dec, "Codec error (IllegalStateException) in MediaCodec.releaseOutputBuffer");
767                             (*env)->ExceptionClear(env);
768                             (*env)->DeleteLocalRef(env, illegalStateException);
769                             p_sys->error_state = true;
770                         }
771                     }
772                     (*env)->DeleteLocalRef(env, buf);
773                 }
774             } else {
775                 msg_Warn(p_dec, "NewPicture failed");
776                 (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
777                 if ((*env)->ExceptionOccurred(env)) {
778                     msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (GetOutput)");
779                     (*env)->ExceptionClear(env);
780                     p_sys->error_state = true;
781                 }
782             }
783             return;
784
785         } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
786             msg_Dbg(p_dec, "output buffers changed");
787             (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
788
789             p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec,
790                                                              p_sys->get_output_buffers);
791             if ((*env)->ExceptionOccurred(env)) {
792                 msg_Err(p_dec, "Exception in MediaCodec.getOutputBuffer (GetOutput)");
793                 (*env)->ExceptionClear(env);
794                 p_sys->output_buffers = NULL;
795                 p_sys->error_state = true;
796                 return;
797             }
798
799             p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
800
801             vlc_mutex_lock(get_android_opaque_mutex());
802             free(p_sys->inflight_picture);
803             p_sys->i_output_buffers = (*env)->GetArrayLength(env, p_sys->output_buffers);
804             p_sys->inflight_picture = calloc(1, sizeof(picture_t*) * p_sys->i_output_buffers);
805             vlc_mutex_unlock(get_android_opaque_mutex());
806
807         } else if (index == INFO_OUTPUT_FORMAT_CHANGED) {
808             jobject format = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_format);
809             if ((*env)->ExceptionOccurred(env)) {
810                 msg_Err(p_dec, "Exception in MediaCodec.getOutputFormat (GetOutput)");
811                 (*env)->ExceptionClear(env);
812                 p_sys->error_state = true;
813                 return;
814             }
815
816             jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
817
818             jsize format_len = (*env)->GetStringUTFLength(env, format_string);
819             const char *format_ptr = (*env)->GetStringUTFChars(env, format_string, NULL);
820             msg_Dbg(p_dec, "output format changed: %.*s", format_len, format_ptr);
821             (*env)->ReleaseStringUTFChars(env, format_string, format_ptr);
822
823             ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
824
825             int width           = GET_INTEGER(format, "width");
826             int height          = GET_INTEGER(format, "height");
827             p_sys->stride       = GET_INTEGER(format, "stride");
828             p_sys->slice_height = GET_INTEGER(format, "slice-height");
829             p_sys->pixel_format = GET_INTEGER(format, "color-format");
830             p_sys->crop_left    = GET_INTEGER(format, "crop-left");
831             p_sys->crop_top     = GET_INTEGER(format, "crop-top");
832             int crop_right      = GET_INTEGER(format, "crop-right");
833             int crop_bottom     = GET_INTEGER(format, "crop-bottom");
834
835             const char *name = "unknown";
836             if (p_sys->direct_rendering) {
837                 int sar_num = 1, sar_den = 1;
838                 if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
839                     sar_num = p_dec->fmt_in.video.i_sar_num;
840                     sar_den = p_dec->fmt_in.video.i_sar_den;
841                 }
842                 jni_SetAndroidSurfaceSizeEnv(env, width, height, width, height, sar_num, sar_den);
843             } else
844                 GetVlcChromaFormat(p_sys->pixel_format, &p_dec->fmt_out.i_codec, &name);
845
846             msg_Dbg(p_dec, "output: %d %s, %dx%d stride %d %d, crop %d %d %d %d",
847                     p_sys->pixel_format, name, width, height, p_sys->stride, p_sys->slice_height,
848                     p_sys->crop_left, p_sys->crop_top, crop_right, crop_bottom);
849
850             p_dec->fmt_out.video.i_width = crop_right + 1 - p_sys->crop_left;
851             p_dec->fmt_out.video.i_height = crop_bottom + 1 - p_sys->crop_top;
852             if (p_sys->stride <= 0)
853                 p_sys->stride = width;
854             if (p_sys->slice_height <= 0)
855                 p_sys->slice_height = height;
856             if ((*env)->ExceptionOccurred(env))
857                 (*env)->ExceptionClear(env);
858
859             ArchitectureSpecificCopyHooks(p_dec, p_sys->pixel_format, p_sys->slice_height,
860                                           p_sys->stride, &p_sys->architecture_specific_data);
861             if (p_sys->pixel_format == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) {
862                 p_sys->slice_height -= p_sys->crop_top/2;
863                 /* Reset crop top/left here, since the offset parameter already includes this.
864                  * If we'd ignore the offset parameter in the BufferInfo, we could just keep
865                  * the original slice height and apply the top/left cropping instead. */
866                 p_sys->crop_top = 0;
867                 p_sys->crop_left = 0;
868             }
869             if (IgnoreOmxDecoderPadding(p_sys->name)) {
870                 p_sys->slice_height = 0;
871                 p_sys->stride = p_dec->fmt_out.video.i_width;
872             }
873
874         } else {
875             return;
876         }
877     }
878 }
879
880 static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
881 {
882     decoder_sys_t *p_sys = p_dec->p_sys;
883     picture_t *p_pic = NULL;
884     JNIEnv *env = NULL;
885     struct H264ConvertState convert_state = { 0, 0 };
886
887     if (!pp_block || !*pp_block)
888         return NULL;
889
890     block_t *p_block = *pp_block;
891
892     if (p_sys->error_state) {
893         block_Release(p_block);
894         if (!p_sys->error_event_sent) {
895             /* Signal the error to the Java. */
896             jni_EventHardwareAccelerationError();
897             p_sys->error_event_sent = true;
898         }
899         return NULL;
900     }
901
902     jni_attach_thread(&env, THREAD_NAME);
903
904     if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED)) {
905         block_Release(p_block);
906         timestamp_FifoEmpty(p_sys->timestamp_fifo);
907         if (p_sys->decoded) {
908             /* Invalidate all pictures that are currently in flight
909              * since flushing make all previous indices returned by
910              * MediaCodec invalid. */
911             if (p_sys->direct_rendering)
912                 InvalidateAllPictures(p_dec);
913
914             (*env)->CallVoidMethod(env, p_sys->codec, p_sys->flush);
915             if ((*env)->ExceptionOccurred(env)) {
916                 msg_Warn(p_dec, "Exception occurred in MediaCodec.flush");
917                 (*env)->ExceptionClear(env);
918                 p_sys->error_state = true;
919             }
920         }
921         p_sys->decoded = false;
922         jni_detach_thread();
923         return NULL;
924     }
925
926     /* Use the aspect ratio provided by the input (ie read from packetizer).
927      * Don't check the current value of the aspect ratio in fmt_out, since we
928      * want to allow changes in it to propagate. */
929     if (p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) {
930         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
931         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
932     }
933
934     jlong timeout = 0;
935     const int max_polling_attempts = 50;
936     int attempts = 0;
937     while (true) {
938         int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_input_buffer, (jlong) 0);
939         if ((*env)->ExceptionOccurred(env)) {
940             msg_Err(p_dec, "Exception occurred in MediaCodec.dequeueInputBuffer");
941             (*env)->ExceptionClear(env);
942             p_sys->error_state = true;
943             break;
944         }
945
946         if (index < 0) {
947             GetOutput(p_dec, env, &p_pic, timeout);
948             if (p_pic) {
949                 /* If we couldn't get an available input buffer but a
950                  * decoded frame is available, we return the frame
951                  * without assigning NULL to *pp_block. The next call
952                  * to DecodeVideo will try to send the input packet again.
953                  */
954                 jni_detach_thread();
955                 return p_pic;
956             }
957             timeout = 30 * 1000;
958             ++attempts;
959             /* With opaque DR the output buffers are released by the
960                vout therefore we implement a timeout for polling in
961                order to avoid being indefinitely stalled in this loop. */
962             if (p_sys->direct_rendering && attempts == max_polling_attempts) {
963                 picture_t *invalid_picture = decoder_NewPicture(p_dec);
964                 if (invalid_picture) {
965                     invalid_picture->date = VLC_TS_INVALID;
966                     picture_sys_t *p_picsys = invalid_picture->p_sys;
967                     p_picsys->pf_display_callback = NULL;
968                     p_picsys->pf_unlock_callback = NULL;
969                     p_picsys->p_dec = NULL;
970                     p_picsys->i_index = -1;
971                     p_picsys->b_valid = false;
972                 }
973                 else {
974                     /* If we cannot return a picture we must free the
975                        block since the decoder will proceed with the
976                        next block. */
977                     block_Release(p_block);
978                     *pp_block = NULL;
979                 }
980                 jni_detach_thread();
981                 return invalid_picture;
982             }
983             continue;
984         }
985
986         jobject buf = (*env)->GetObjectArrayElement(env, p_sys->input_buffers, index);
987         jsize size = (*env)->GetDirectBufferCapacity(env, buf);
988         uint8_t *bufptr = (*env)->GetDirectBufferAddress(env, buf);
989         if (size < 0) {
990             msg_Err(p_dec, "Java buffer has invalid size");
991             p_sys->error_state = true;
992             break;
993         }
994         if ((size_t) size > p_block->i_buffer)
995             size = p_block->i_buffer;
996         memcpy(bufptr, p_block->p_buffer, size);
997
998         convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
999
1000         int64_t ts = p_block->i_pts;
1001         if (!ts && p_block->i_dts)
1002             ts = p_block->i_dts;
1003         timestamp_FifoPut(p_sys->timestamp_fifo, p_block->i_pts ? VLC_TS_INVALID : p_block->i_dts);
1004         (*env)->CallVoidMethod(env, p_sys->codec, p_sys->queue_input_buffer, index, 0, size, ts, 0);
1005         (*env)->DeleteLocalRef(env, buf);
1006         if ((*env)->ExceptionOccurred(env)) {
1007             msg_Err(p_dec, "Exception in MediaCodec.queueInputBuffer");
1008             (*env)->ExceptionClear(env);
1009             p_sys->error_state = true;
1010             break;
1011         }
1012         p_sys->decoded = true;
1013         break;
1014     }
1015     if (!p_pic)
1016         GetOutput(p_dec, env, &p_pic, 0);
1017     jni_detach_thread();
1018
1019     block_Release(p_block);
1020     *pp_block = NULL;
1021
1022     return p_pic;
1023 }