]> git.sesse.net Git - vlc/blobdiff - modules/codec/omxil/android_mediacodec.c
mediacodec: skip prerolled frames
[vlc] / modules / codec / omxil / android_mediacodec.c
index 114b648243625f4461b4bce398cca66d7c3660dd..93481cd470632e435b6b2c710349e5bee0270da8 100644 (file)
@@ -174,6 +174,8 @@ struct decoder_sys_t
     unsigned int i_inflight_pictures;
 
     timestamp_fifo_t *timestamp_fifo;
+
+    int64_t i_preroll_end;
 };
 
 enum Types
@@ -308,6 +310,26 @@ static inline bool check_exception( JNIEnv *env )
 }
 #define CHECK_EXCEPTION() check_exception( env )
 
+static bool codec_is_blacklisted( const char *p_name, int i_name_len )
+{
+     static const char *blacklisted_codecs[] = {
+        /* software decoders */
+        "OMX.google.",
+        /* crashes mediaserver */
+        "OMX.MTK.VIDEO.DECODER.MPEG4",
+        NULL,
+     };
+
+     for( const char **pp_bl_codecs = blacklisted_codecs; *pp_bl_codecs != NULL;
+          pp_bl_codecs++ )
+     {
+        if( !strncmp( p_name, *pp_bl_codecs,
+            __MIN( strlen(*pp_bl_codecs), i_name_len ) ) )
+            return true;
+     }
+     return false;
+}
+
 /*****************************************************************************
  * OpenDecoder: Create the decoder instance
  *****************************************************************************/
@@ -442,7 +464,7 @@ static int OpenDecoder(vlc_object_t *p_this)
         name_ptr = (*env)->GetStringUTFChars(env, name, NULL);
         found = false;
 
-        if (!strncmp(name_ptr, "OMX.google.", __MIN(11, name_len)))
+        if (codec_is_blacklisted( name_ptr, name_len))
             goto loopclean;
         for (int j = 0; j < num_types && !found; j++) {
             jobject type = (*env)->GetObjectArrayElement(env, types, j);
@@ -689,6 +711,23 @@ static void CloseDecoder(vlc_object_t *p_this)
     free(p_sys);
 }
 
+/*****************************************************************************
+ * ReleaseOutputBuffer
+ *****************************************************************************/
+static int ReleaseOutputBuffer(decoder_t *p_dec, JNIEnv *env, int i_index,
+                               bool b_render)
+{
+    decoder_sys_t *p_sys = p_dec->p_sys;
+
+    (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer,
+                           i_index, b_render);
+    if (CHECK_EXCEPTION()) {
+        msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer");
+        return -1;
+    }
+    return 0;
+}
+
 /*****************************************************************************
  * vout callbacks
  *****************************************************************************/
@@ -696,7 +735,6 @@ static void UnlockPicture(picture_t* p_pic, bool b_render)
 {
     picture_sys_t *p_picsys = p_pic->p_sys;
     decoder_t *p_dec = p_picsys->priv.hw.p_dec;
-    decoder_sys_t *p_sys = p_dec->p_sys;
 
     if (!p_picsys->priv.hw.b_valid)
         return;
@@ -715,10 +753,7 @@ static void UnlockPicture(picture_t* p_pic, bool b_render)
     /* Release the MediaCodec buffer. */
     JNIEnv *env = NULL;
     jni_attach_thread(&env, THREAD_NAME);
-    (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_index, b_render);
-    if (CHECK_EXCEPTION())
-        msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (DisplayBuffer)");
-
+    ReleaseOutputBuffer(p_dec, env, i_index, b_render);
     jni_detach_thread();
     p_picsys->priv.hw.b_valid = false;
 
@@ -761,199 +796,222 @@ static int InsertInflightPicture(decoder_t *p_dec, picture_t *p_pic,
     return 0;
 }
 
-static void GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
+static int PutInput(decoder_t *p_dec, JNIEnv *env, block_t **pp_block, jlong timeout)
 {
     decoder_sys_t *p_sys = p_dec->p_sys;
-    while (1) {
-        int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_output_buffer,
-                                          p_sys->buffer_info, timeout);
-        if (CHECK_EXCEPTION()) {
-            msg_Err(p_dec, "Exception in MediaCodec.dequeueOutputBuffer (GetOutput)");
-            p_sys->error_state = true;
-            return;
-        }
+    block_t *p_block = *pp_block;
+    int index;
+    jobject buf;
+    jsize size;
+    uint8_t *bufptr;
+    struct H264ConvertState convert_state = { 0, 0 };
 
-        if (index >= 0) {
-            if (!p_sys->pixel_format) {
-                msg_Warn(p_dec, "Buffers returned before output format is set, dropping frame");
-                (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
-                if (CHECK_EXCEPTION()) {
-                    msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer");
-                    p_sys->error_state = true;
-                    return;
-                }
-                continue;
-            }
+    index = (*env)->CallIntMethod(env, p_sys->codec,
+                                  p_sys->dequeue_input_buffer, timeout);
+    if (CHECK_EXCEPTION()) {
+        msg_Err(p_dec, "Exception occurred in MediaCodec.dequeueInputBuffer");
+        return -1;
+    }
+    if (index < 0)
+        return 0;
 
-            if (!*pp_pic) {
-                *pp_pic = decoder_NewPicture(p_dec);
-            } else if (p_sys->direct_rendering) {
-                picture_t *p_pic = *pp_pic;
-                picture_sys_t *p_picsys = p_pic->p_sys;
-                int i_prev_index = p_picsys->priv.hw.i_index;
-                (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, i_prev_index, false);
-                if (CHECK_EXCEPTION()) {
-                    msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer " \
-                            "(GetOutput, overwriting previous picture)");
-                    p_sys->error_state = true;
-                    return;
-                }
+    if (p_sys->get_input_buffers)
+        buf = (*env)->GetObjectArrayElement(env, p_sys->input_buffers, index);
+    else
+        buf = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffer, index);
+    size = (*env)->GetDirectBufferCapacity(env, buf);
+    bufptr = (*env)->GetDirectBufferAddress(env, buf);
+    if (size < 0) {
+        msg_Err(p_dec, "Java buffer has invalid size");
+        return -1;
+    }
+    if ((size_t) size > p_block->i_buffer)
+        size = p_block->i_buffer;
+    memcpy(bufptr, p_block->p_buffer, size);
+
+    convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
+
+    int64_t ts = p_block->i_pts;
+    if (!ts && p_block->i_dts)
+        ts = p_block->i_dts;
+    if (p_block->i_flags & BLOCK_FLAG_PREROLL )
+        p_sys->i_preroll_end = ts;
+    timestamp_FifoPut(p_sys->timestamp_fifo, p_block->i_pts ? VLC_TS_INVALID : p_block->i_dts);
+    (*env)->CallVoidMethod(env, p_sys->codec, p_sys->queue_input_buffer, index, 0, size, ts, 0);
+    (*env)->DeleteLocalRef(env, buf);
+    if (CHECK_EXCEPTION()) {
+        msg_Err(p_dec, "Exception in MediaCodec.queueInputBuffer");
+        return -1;
+    }
+    block_Release(p_block);
+    *pp_block = NULL;
+    p_sys->decoded = true;
 
-                // No need to lock here since the previous picture was not sent.
-                InsertInflightPicture(p_dec, NULL, i_prev_index);
-            }
-            if (*pp_pic) {
-
-                picture_t *p_pic = *pp_pic;
-                /* If the oldest input block had no PTS, the timestamp
-                 * of the frame returned by MediaCodec might be wrong
-                 * so we overwrite it with the corresponding dts. */
-                int64_t forced_ts = timestamp_FifoGet(p_sys->timestamp_fifo);
-                if (forced_ts == VLC_TS_INVALID)
-                    p_pic->date = (*env)->GetLongField(env, p_sys->buffer_info, p_sys->pts_field);
-                else
-                    p_pic->date = forced_ts;
+    return 0;
+}
 
-                if (p_sys->direct_rendering) {
-                    picture_sys_t *p_picsys = p_pic->p_sys;
-                    p_picsys->pf_lock_pic = NULL;
-                    p_picsys->pf_unlock_pic = UnlockPicture;
-                    p_picsys->priv.hw.p_dec = p_dec;
-                    p_picsys->priv.hw.i_index = index;
-                    p_picsys->priv.hw.b_valid = true;
-
-                    vlc_mutex_lock(get_android_opaque_mutex());
-                    InsertInflightPicture(p_dec, p_pic, index);
-                    vlc_mutex_unlock(get_android_opaque_mutex());
-                } else {
-                    jobject buf;
-                    if (p_sys->get_output_buffers)
-                        buf = (*env)->GetObjectArrayElement(env, p_sys->output_buffers, index);
-                    else
-                        buf = (*env)->CallObjectMethod(env, p_sys->codec,
-                                                       p_sys->get_output_buffer, index);
-                    //jsize buf_size = (*env)->GetDirectBufferCapacity(env, buf);
-                    uint8_t *ptr = (*env)->GetDirectBufferAddress(env, buf);
-
-                    //int size = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->size_field);
-                    int offset = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->offset_field);
-                    ptr += offset; // Check the size parameter as well
-
-                    unsigned int chroma_div;
-                    GetVlcChromaSizes(p_dec->fmt_out.i_codec, p_dec->fmt_out.video.i_width,
-                                      p_dec->fmt_out.video.i_height, NULL, NULL, &chroma_div);
-                    CopyOmxPicture(p_sys->pixel_format, p_pic, p_sys->slice_height, p_sys->stride,
-                                   ptr, chroma_div, &p_sys->architecture_specific_data);
-                    (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
-
-                    jthrowable exception = (*env)->ExceptionOccurred(env);
-                    if (exception != NULL) {
-                        jclass illegalStateException = (*env)->FindClass(env, "java/lang/IllegalStateException");
-                        if((*env)->IsInstanceOf(env, exception, illegalStateException)) {
-                            msg_Err(p_dec, "Codec error (IllegalStateException) in MediaCodec.releaseOutputBuffer");
-                            (*env)->ExceptionClear(env);
-                            (*env)->DeleteLocalRef(env, illegalStateException);
-                            p_sys->error_state = true;
-                        }
-                    }
-                    (*env)->DeleteLocalRef(env, buf);
-                }
-            } else {
-                msg_Warn(p_dec, "NewPicture failed");
-                (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
-                if (CHECK_EXCEPTION()) {
-                    msg_Err(p_dec, "Exception in MediaCodec.releaseOutputBuffer (GetOutput)");
-                    p_sys->error_state = true;
-                }
-            }
-            return;
+static int GetOutput(decoder_t *p_dec, JNIEnv *env, picture_t **pp_pic, jlong timeout)
+{
+    decoder_sys_t *p_sys = p_dec->p_sys;
+    int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_output_buffer,
+                                      p_sys->buffer_info, timeout);
+    if (CHECK_EXCEPTION()) {
+        msg_Err(p_dec, "Exception in MediaCodec.dequeueOutputBuffer (GetOutput)");
+        return -1;
+    }
 
-        } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
-            msg_Dbg(p_dec, "output buffers changed");
-            if (!p_sys->get_output_buffers)
-                continue;
-            (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
+    if (index >= 0) {
+        int64_t i_buffer_pts;
 
-            p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec,
-                                                             p_sys->get_output_buffers);
-            if (CHECK_EXCEPTION()) {
-                msg_Err(p_dec, "Exception in MediaCodec.getOutputBuffer (GetOutput)");
-                p_sys->output_buffers = NULL;
-                p_sys->error_state = true;
-                return;
-            }
+        if (!p_sys->pixel_format) {
+            msg_Warn(p_dec, "Buffers returned before output format is set, dropping frame");
+            return ReleaseOutputBuffer(p_dec, env, index, false);
+        }
 
-            p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
-        } else if (index == INFO_OUTPUT_FORMAT_CHANGED) {
-            jobject format = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_format);
-            if (CHECK_EXCEPTION()) {
-                msg_Err(p_dec, "Exception in MediaCodec.getOutputFormat (GetOutput)");
-                p_sys->error_state = true;
-                return;
-            }
+        i_buffer_pts = (*env)->GetLongField(env, p_sys->buffer_info, p_sys->pts_field);
+        if (i_buffer_pts <= p_sys->i_preroll_end)
+            return ReleaseOutputBuffer(p_dec, env, index, false);
 
-            jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
-
-            jsize format_len = (*env)->GetStringUTFLength(env, format_string);
-            const char *format_ptr = (*env)->GetStringUTFChars(env, format_string, NULL);
-            msg_Dbg(p_dec, "output format changed: %.*s", format_len, format_ptr);
-            (*env)->ReleaseStringUTFChars(env, format_string, format_ptr);
-
-            ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
-
-            int width           = GET_INTEGER(format, "width");
-            int height          = GET_INTEGER(format, "height");
-            p_sys->stride       = GET_INTEGER(format, "stride");
-            p_sys->slice_height = GET_INTEGER(format, "slice-height");
-            p_sys->pixel_format = GET_INTEGER(format, "color-format");
-            int crop_left       = GET_INTEGER(format, "crop-left");
-            int crop_top        = GET_INTEGER(format, "crop-top");
-            int crop_right      = GET_INTEGER(format, "crop-right");
-            int crop_bottom     = GET_INTEGER(format, "crop-bottom");
-
-            const char *name = "unknown";
-            if (!p_sys->direct_rendering) {
-                if (!GetVlcChromaFormat(p_sys->pixel_format,
-                                        &p_dec->fmt_out.i_codec, &name)) {
-                    msg_Err(p_dec, "color-format not recognized");
-                    p_sys->error_state = true;
-                    return;
+        *pp_pic = decoder_NewPicture(p_dec);
+        if (!*pp_pic) {
+            msg_Warn(p_dec, "NewPicture failed");
+            return ReleaseOutputBuffer(p_dec, env, index, false);
+        }
+        picture_t *p_pic = *pp_pic;
+        /* If the oldest input block had no PTS, the timestamp
+         * of the frame returned by MediaCodec might be wrong
+         * so we overwrite it with the corresponding dts. */
+        int64_t forced_ts = timestamp_FifoGet(p_sys->timestamp_fifo);
+        if (forced_ts == VLC_TS_INVALID)
+            p_pic->date = i_buffer_pts;
+        else
+            p_pic->date = forced_ts;
+
+        if (p_sys->direct_rendering) {
+            picture_sys_t *p_picsys = p_pic->p_sys;
+            p_picsys->pf_lock_pic = NULL;
+            p_picsys->pf_unlock_pic = UnlockPicture;
+            p_picsys->priv.hw.p_dec = p_dec;
+            p_picsys->priv.hw.i_index = index;
+            p_picsys->priv.hw.b_valid = true;
+
+            vlc_mutex_lock(get_android_opaque_mutex());
+            InsertInflightPicture(p_dec, p_pic, index);
+            vlc_mutex_unlock(get_android_opaque_mutex());
+        } else {
+            jobject buf;
+            if (p_sys->get_output_buffers)
+                buf = (*env)->GetObjectArrayElement(env, p_sys->output_buffers, index);
+            else
+                buf = (*env)->CallObjectMethod(env, p_sys->codec,
+                                               p_sys->get_output_buffer, index);
+            //jsize buf_size = (*env)->GetDirectBufferCapacity(env, buf);
+            uint8_t *ptr = (*env)->GetDirectBufferAddress(env, buf);
+
+            //int size = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->size_field);
+            int offset = (*env)->GetIntField(env, p_sys->buffer_info, p_sys->offset_field);
+            ptr += offset; // Check the size parameter as well
+
+            unsigned int chroma_div;
+            GetVlcChromaSizes(p_dec->fmt_out.i_codec, p_dec->fmt_out.video.i_width,
+                              p_dec->fmt_out.video.i_height, NULL, NULL, &chroma_div);
+            CopyOmxPicture(p_sys->pixel_format, p_pic, p_sys->slice_height, p_sys->stride,
+                           ptr, chroma_div, &p_sys->architecture_specific_data);
+            (*env)->CallVoidMethod(env, p_sys->codec, p_sys->release_output_buffer, index, false);
+
+            jthrowable exception = (*env)->ExceptionOccurred(env);
+            if (exception != NULL) {
+                jclass illegalStateException = (*env)->FindClass(env, "java/lang/IllegalStateException");
+                if((*env)->IsInstanceOf(env, exception, illegalStateException)) {
+                    msg_Err(p_dec, "Codec error (IllegalStateException) in MediaCodec.releaseOutputBuffer");
+                    (*env)->ExceptionClear(env);
+                    (*env)->DeleteLocalRef(env, illegalStateException);
+                    (*env)->DeleteLocalRef(env, buf);
+                    return -1;
                 }
             }
+            (*env)->DeleteLocalRef(env, buf);
+        }
+    } else if (index == INFO_OUTPUT_BUFFERS_CHANGED) {
+        msg_Dbg(p_dec, "output buffers changed");
+        if (!p_sys->get_output_buffers)
+            return 0;
+        (*env)->DeleteGlobalRef(env, p_sys->output_buffers);
 
-            msg_Err(p_dec, "output: %d %s, %dx%d stride %d %d, crop %d %d %d %d",
-                    p_sys->pixel_format, name, width, height, p_sys->stride, p_sys->slice_height,
-                    crop_left, crop_top, crop_right, crop_bottom);
+        p_sys->output_buffers = (*env)->CallObjectMethod(env, p_sys->codec,
+                                                         p_sys->get_output_buffers);
+        if (CHECK_EXCEPTION()) {
+            msg_Err(p_dec, "Exception in MediaCodec.getOutputBuffer (GetOutput)");
+            p_sys->output_buffers = NULL;
+            return -1;
+        }
 
-            p_dec->fmt_out.video.i_width = crop_right + 1 - crop_left;
-            p_dec->fmt_out.video.i_height = crop_bottom + 1 - crop_top;
-            if (p_dec->fmt_out.video.i_width <= 1
-                || p_dec->fmt_out.video.i_height <= 1) {
-                p_dec->fmt_out.video.i_width = width;
-                p_dec->fmt_out.video.i_height = height;
-            }
-            p_dec->fmt_out.video.i_visible_width = p_dec->fmt_out.video.i_width;
-            p_dec->fmt_out.video.i_visible_height = p_dec->fmt_out.video.i_height;
-
-            if (p_sys->stride <= 0)
-                p_sys->stride = width;
-            if (p_sys->slice_height <= 0)
-                p_sys->slice_height = height;
-            CHECK_EXCEPTION();
-
-            ArchitectureSpecificCopyHooks(p_dec, p_sys->pixel_format, p_sys->slice_height,
-                                          p_sys->stride, &p_sys->architecture_specific_data);
-            if (p_sys->pixel_format == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
-                p_sys->slice_height -= crop_top/2;
-            if (IgnoreOmxDecoderPadding(p_sys->name)) {
-                p_sys->slice_height = 0;
-                p_sys->stride = p_dec->fmt_out.video.i_width;
+        p_sys->output_buffers = (*env)->NewGlobalRef(env, p_sys->output_buffers);
+    } else if (index == INFO_OUTPUT_FORMAT_CHANGED) {
+        jobject format = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_output_format);
+        if (CHECK_EXCEPTION()) {
+            msg_Err(p_dec, "Exception in MediaCodec.getOutputFormat (GetOutput)");
+            return -1;
+        }
+
+        jobject format_string = (*env)->CallObjectMethod(env, format, p_sys->tostring);
+
+        jsize format_len = (*env)->GetStringUTFLength(env, format_string);
+        const char *format_ptr = (*env)->GetStringUTFChars(env, format_string, NULL);
+        msg_Dbg(p_dec, "output format changed: %.*s", format_len, format_ptr);
+        (*env)->ReleaseStringUTFChars(env, format_string, format_ptr);
+
+        ArchitectureSpecificCopyHooksDestroy(p_sys->pixel_format, &p_sys->architecture_specific_data);
+
+        int width           = GET_INTEGER(format, "width");
+        int height          = GET_INTEGER(format, "height");
+        p_sys->stride       = GET_INTEGER(format, "stride");
+        p_sys->slice_height = GET_INTEGER(format, "slice-height");
+        p_sys->pixel_format = GET_INTEGER(format, "color-format");
+        int crop_left       = GET_INTEGER(format, "crop-left");
+        int crop_top        = GET_INTEGER(format, "crop-top");
+        int crop_right      = GET_INTEGER(format, "crop-right");
+        int crop_bottom     = GET_INTEGER(format, "crop-bottom");
+
+        const char *name = "unknown";
+        if (!p_sys->direct_rendering) {
+            if (!GetVlcChromaFormat(p_sys->pixel_format,
+                                    &p_dec->fmt_out.i_codec, &name)) {
+                msg_Err(p_dec, "color-format not recognized");
+                return -1;
             }
+        }
 
-        } else {
-            return;
+        msg_Err(p_dec, "output: %d %s, %dx%d stride %d %d, crop %d %d %d %d",
+                p_sys->pixel_format, name, width, height, p_sys->stride, p_sys->slice_height,
+                crop_left, crop_top, crop_right, crop_bottom);
+
+        p_dec->fmt_out.video.i_width = crop_right + 1 - crop_left;
+        p_dec->fmt_out.video.i_height = crop_bottom + 1 - crop_top;
+        if (p_dec->fmt_out.video.i_width <= 1
+            || p_dec->fmt_out.video.i_height <= 1) {
+            p_dec->fmt_out.video.i_width = width;
+            p_dec->fmt_out.video.i_height = height;
+        }
+        p_dec->fmt_out.video.i_visible_width = p_dec->fmt_out.video.i_width;
+        p_dec->fmt_out.video.i_visible_height = p_dec->fmt_out.video.i_height;
+
+        if (p_sys->stride <= 0)
+            p_sys->stride = width;
+        if (p_sys->slice_height <= 0)
+            p_sys->slice_height = height;
+        CHECK_EXCEPTION();
+
+        ArchitectureSpecificCopyHooks(p_dec, p_sys->pixel_format, p_sys->slice_height,
+                                      p_sys->stride, &p_sys->architecture_specific_data);
+        if (p_sys->pixel_format == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
+            p_sys->slice_height -= crop_top/2;
+        if (IgnoreOmxDecoderPadding(p_sys->name)) {
+            p_sys->slice_height = 0;
+            p_sys->stride = p_dec->fmt_out.video.i_width;
         }
     }
+    return 0;
 }
 
 static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
@@ -961,27 +1019,21 @@ static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
     decoder_sys_t *p_sys = p_dec->p_sys;
     picture_t *p_pic = NULL;
     JNIEnv *env = NULL;
-    struct H264ConvertState convert_state = { 0, 0 };
 
     if (!pp_block || !*pp_block)
         return NULL;
 
-    block_t *p_block = *pp_block;
-
-    if (p_sys->error_state) {
-        block_Release(p_block);
-        if (!p_sys->error_event_sent) {
-            /* Signal the error to the Java. */
-            jni_EventHardwareAccelerationError();
-            p_sys->error_event_sent = true;
-        }
-        return NULL;
-    }
+    if (p_sys->error_state)
+        goto endclean;
 
     jni_attach_thread(&env, THREAD_NAME);
+    if (!env)
+        goto endclean;
 
-    if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED)) {
-        block_Release(p_block);
+    if ((*pp_block)->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED)) {
+        block_Release(*pp_block);
+        *pp_block = NULL;
+        p_sys->i_preroll_end = 0;
         timestamp_FifoEmpty(p_sys->timestamp_fifo);
         if (p_sys->decoded) {
             /* Invalidate all pictures that are currently in flight
@@ -997,8 +1049,7 @@ static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
             }
         }
         p_sys->decoded = false;
-        jni_detach_thread();
-        return NULL;
+        goto endclean;
     }
 
     /* Use the aspect ratio provided by the input (ie read from packetizer).
@@ -1012,37 +1063,29 @@ static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
     jlong timeout = 0;
     const int max_polling_attempts = 50;
     int attempts = 0;
-    while (true) {
-        int index = (*env)->CallIntMethod(env, p_sys->codec, p_sys->dequeue_input_buffer, (jlong) 0);
-        if (CHECK_EXCEPTION()) {
-            msg_Err(p_dec, "Exception occurred in MediaCodec.dequeueInputBuffer");
+    /* return when pp_block is processed */
+    while (*pp_block != NULL) {
+        if (*pp_block != NULL && PutInput(p_dec, env, pp_block, (jlong) 0) != 0) {
             p_sys->error_state = true;
             break;
         }
 
-        if (index < 0) {
-            GetOutput(p_dec, env, &p_pic, timeout);
-            if (p_sys->error_state)
-                break;
-            if (p_pic) {
-                /* If we couldn't get an available input buffer but a
-                 * decoded frame is available, we return the frame
-                 * without assigning NULL to *pp_block. The next call
-                 * to DecodeVideo will try to send the input packet again.
-                 */
-                jni_detach_thread();
-                return p_pic;
-            }
+        if (p_pic == NULL && GetOutput(p_dec, env, &p_pic, timeout) != 0) {
+            p_sys->error_state = true;
+            break;
+        }
+
+        if (p_pic == NULL && *pp_block != NULL) {
             timeout = 30 * 1000;
             ++attempts;
             /* With opaque DR the output buffers are released by the
                vout therefore we implement a timeout for polling in
                order to avoid being indefinitely stalled in this loop. */
             if (p_sys->direct_rendering && attempts == max_polling_attempts) {
-                picture_t *invalid_picture = decoder_NewPicture(p_dec);
-                if (invalid_picture) {
-                    invalid_picture->date = VLC_TS_INVALID;
-                    picture_sys_t *p_picsys = invalid_picture->p_sys;
+                p_pic = decoder_NewPicture(p_dec);
+                if (p_pic) {
+                    p_pic->date = VLC_TS_INVALID;
+                    picture_sys_t *p_picsys = p_pic->p_sys;
                     p_picsys->pf_lock_pic = NULL;
                     p_picsys->pf_unlock_pic = NULL;
                     p_picsys->priv.hw.p_dec = NULL;
@@ -1053,59 +1096,32 @@ static picture_t *DecodeVideo(decoder_t *p_dec, block_t **pp_block)
                     /* If we cannot return a picture we must free the
                        block since the decoder will proceed with the
                        next block. */
-                    block_Release(p_block);
+                    block_Release(*pp_block);
                     *pp_block = NULL;
                 }
-                jni_detach_thread();
-                return invalid_picture;
             }
-            continue;
-        }
-
-        jobject buf;
-        if (p_sys->get_input_buffers)
-            buf = (*env)->GetObjectArrayElement(env, p_sys->input_buffers, index);
-        else
-            buf = (*env)->CallObjectMethod(env, p_sys->codec, p_sys->get_input_buffer, index);
-        jsize size = (*env)->GetDirectBufferCapacity(env, buf);
-        uint8_t *bufptr = (*env)->GetDirectBufferAddress(env, buf);
-        if (size < 0) {
-            msg_Err(p_dec, "Java buffer has invalid size");
-            p_sys->error_state = true;
-            break;
-        }
-        if ((size_t) size > p_block->i_buffer)
-            size = p_block->i_buffer;
-        memcpy(bufptr, p_block->p_buffer, size);
-
-        convert_h264_to_annexb(bufptr, size, p_sys->nal_size, &convert_state);
-
-        int64_t ts = p_block->i_pts;
-        if (!ts && p_block->i_dts)
-            ts = p_block->i_dts;
-        timestamp_FifoPut(p_sys->timestamp_fifo, p_block->i_pts ? VLC_TS_INVALID : p_block->i_dts);
-        (*env)->CallVoidMethod(env, p_sys->codec, p_sys->queue_input_buffer, index, 0, size, ts, 0);
-        (*env)->DeleteLocalRef(env, buf);
-        if (CHECK_EXCEPTION()) {
-            msg_Err(p_dec, "Exception in MediaCodec.queueInputBuffer");
-            p_sys->error_state = true;
-            break;
         }
-        p_sys->decoded = true;
-        break;
     }
+
+endclean:
     if (p_sys->error_state) {
+        if( pp_block && *pp_block )
+        {
+            block_Release(*pp_block);
+            *pp_block = NULL;
+        }
         if (p_pic)
             picture_Release(p_pic);
-        jni_detach_thread();
-        return NULL;
-    }
-    if (!p_pic)
-        GetOutput(p_dec, env, &p_pic, 0);
-    jni_detach_thread();
+        p_pic = NULL;
 
-    block_Release(p_block);
-    *pp_block = NULL;
+        if (!p_sys->error_event_sent) {
+            /* Signal the error to the Java. */
+            jni_EventHardwareAccelerationError();
+            p_sys->error_event_sent = true;
+        }
+    }
+    if (env != NULL)
+        jni_detach_thread();
 
     return p_pic;
 }