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