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