]> git.sesse.net Git - vlc/blobdiff - modules/codec/omxil/omxil.c
nativewindowpriv: split setup into setUsage and setBuffersGeometry
[vlc] / modules / codec / omxil / omxil.c
index a3f0af3e2bb7973468d59961e6376341bddf28fb..9bdedc5b0e79b24eeae4fe5196e6e3673eb06a31 100644 (file)
 # include "config.h"
 #endif
 
-#include <dlfcn.h>
-#if defined(USE_IOMX)
-/* On dll_open, just check that the OMX_Init symbol already is loaded */
-# define dll_open(name) dlsym(RTLD_DEFAULT, "OMX_Init")
-# define dll_close(handle) do { } while (0)
-# define dlsym(handle, name) dlsym(RTLD_DEFAULT, "I" name)
-#else
-# define dll_open(name) dlopen( name, RTLD_NOW )
-# define dll_close(handle) dlclose(handle)
-#endif
-
 #include <limits.h>
 
 #include <vlc_common.h>
 #include <vlc_block_helper.h>
 #include <vlc_cpu.h>
 #include "../h264_nal.h"
+#include "../hevc_nal.h"
 
 #include "omxil.h"
+#include "omxil_core.h"
+#include "OMX_Broadcom.h"
+
+#if defined(USE_IOMX)
+#include <dlfcn.h>
+#include <jni.h>
+#include "android_opaque.h"
+#include "../../video_output/android/android_window.h"
+#endif
 
 #ifndef NDEBUG
-# define OMXIL_EXTRA_DEBUG
+# define OMX_DBG(...) msg_Dbg( p_dec, __VA_ARGS__ )
+#else
+# define OMX_DBG(...)
 #endif
 
 #define SENTINEL_FLAG 0x10000
 
-/*****************************************************************************
- * List of OpenMAX IL core we will try in order
- *****************************************************************************/
-static const char *ppsz_dll_list[] =
-{
+/* Defined in the broadcom version of OMX_Index.h */
+#define OMX_IndexConfigRequestCallback 0x7f000063
+#define OMX_IndexParamBrcmPixelAspectRatio 0x7f00004d
+#define OMX_IndexParamBrcmVideoDecodeErrorConcealment 0x7f000080
+
+/* Defined in the broadcom version of OMX_Core.h */
+#define OMX_EventParamOrConfigChanged 0x7F000001
+
 #if defined(USE_IOMX)
-    "libiomx.so", /* Not used when using IOMX, the lib should already be loaded */
-#else
-    "libOMX_Core.so", /* TI OMAP IL core */
-    "libOmxCore.so", /* Qualcomm IL core */
-    "libomxil-bellagio.so",  /* Bellagio IL core */
+/* JNI functions to get/set an Android Surface object. */
+#define THREAD_NAME "omxil"
+extern int jni_attach_thread(JNIEnv **env, const char *thread_name);
+extern void jni_detach_thread();
+extern jobject jni_LockAndGetAndroidJavaSurface();
+extern void jni_UnlockAndroidSurface();
+extern bool jni_IsVideoPlayerActivityCreated();
 #endif
-    0
-};
-
-/*****************************************************************************
- * Global OMX Core instance, shared between module instances
- *****************************************************************************/
-static vlc_mutex_t omx_core_mutex = VLC_STATIC_MUTEX;
-static unsigned int omx_refcount = 0;
-static void *dll_handle;
-static OMX_ERRORTYPE (*pf_init) (void);
-static OMX_ERRORTYPE (*pf_deinit) (void);
-static OMX_ERRORTYPE (*pf_get_handle) (OMX_HANDLETYPE *, OMX_STRING,
-                                       OMX_PTR, OMX_CALLBACKTYPE *);
-static OMX_ERRORTYPE (*pf_free_handle) (OMX_HANDLETYPE);
-static OMX_ERRORTYPE (*pf_component_enum)(OMX_STRING, OMX_U32, OMX_U32);
-static OMX_ERRORTYPE (*pf_get_roles_of_component)(OMX_STRING, OMX_U32 *, OMX_U8 **);
 
 /*****************************************************************************
  * Local prototypes
@@ -104,9 +94,58 @@ static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE, OMX_PTR,
 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE, OMX_PTR,
                                         OMX_BUFFERHEADERTYPE * );
 
+#if defined(USE_IOMX)
+static void *DequeueThread( void *data );
+static void UnlockPicture( picture_t* p_pic, bool b_render );
+static void HwBuffer_Init( decoder_t *p_dec, OmxPort *p_port );
+static void HwBuffer_Destroy( decoder_t *p_dec, OmxPort *p_port );
+static int  HwBuffer_AllocateBuffers( decoder_t *p_dec, OmxPort *p_port );
+static int  HwBuffer_FreeBuffers( decoder_t *p_dec, OmxPort *p_port );
+static int  HwBuffer_Start( decoder_t *p_dec, OmxPort *p_port );
+static int  HwBuffer_Stop( decoder_t *p_dec, OmxPort *p_port );
+static int  HwBuffer_Join( decoder_t *p_dec, OmxPort *p_port );
+static int  HwBuffer_GetPic( decoder_t *p_dec, OmxPort *p_port,
+                             picture_t **pp_pic );
+static void HwBuffer_SetCrop( decoder_t *p_dec, OmxPort *p_port,
+                              OMX_CONFIG_RECTTYPE *p_rect );
+static void HwBuffer_ChangeState( decoder_t *p_dec, OmxPort *p_port,
+                                  int i_index, int i_state );
+
+#define HWBUFFER_LOCK() vlc_mutex_lock( get_android_opaque_mutex() )
+#define HWBUFFER_UNLOCK() vlc_mutex_unlock( get_android_opaque_mutex() )
+#define HWBUFFER_WAIT(p_port) vlc_cond_wait( &(p_port)->p_hwbuf->wait, \
+                                              get_android_opaque_mutex() )
+#define HWBUFFER_BROADCAST(p_port) vlc_cond_broadcast( &(p_port)->p_hwbuf->wait )
+
+#else
+static inline int HwBuffer_dummy( )
+{
+    return 0;
+}
+#define HwBuffer_Init(p_dec, p_port) do { } while (0)
+#define HwBuffer_Destroy(p_dec, p_port) do { } while (0)
+#define HwBuffer_AllocateBuffers(p_dec, p_port) HwBuffer_dummy()
+#define HwBuffer_FreeBuffers(p_dec, p_port) HwBuffer_dummy()
+#define HwBuffer_Start(p_dec, p_port) HwBuffer_dummy()
+#define HwBuffer_Stop(p_dec, p_port) HwBuffer_dummy()
+#define HwBuffer_Join(p_dec, p_port) HwBuffer_dummy()
+#define HwBuffer_GetPic(p_dec, p_port, pp_pic) HwBuffer_dummy()
+#define HwBuffer_SetCrop(p_dec, p_port, p_rect) do { } while (0)
+
+#define HWBUFFER_LOCK() do { } while (0)
+#define HWBUFFER_UNLOCK() do { } while (0)
+#define HWBUFFER_WAIT(p_port) do { } while (0)
+#define HWBUFFER_BROADCAST(p_port) do { } while (0)
+#endif
+
 /*****************************************************************************
  * Module descriptor
  *****************************************************************************/
+#define DIRECTRENDERING_TEXT N_("OMX direct rendering")
+#define DIRECTRENDERING_LONGTEXT N_(\
+        "Enable OMX direct rendering.")
+
+#define CFG_PREFIX "omxil-"
 vlc_module_begin ()
     set_description( N_("Audio/Video decoder (using OpenMAX IL)") )
     set_category( CAT_INPUT )
@@ -117,6 +156,8 @@ vlc_module_begin ()
      * enable it only via the --codec iomx command line parameter when
      * wanted. */
     set_capability( "decoder", 0 )
+    add_bool(CFG_PREFIX "dr", true,
+             DIRECTRENDERING_TEXT, DIRECTRENDERING_LONGTEXT, true)
 #else
     set_capability( "decoder", 80 )
 #endif
@@ -129,73 +170,6 @@ vlc_module_begin ()
     set_callbacks( OpenEncoder, CloseGeneric )
 vlc_module_end ()
 
-/*****************************************************************************
- * CreateComponentsList: creates a list of components matching the given role
- *****************************************************************************/
-static int CreateComponentsList(decoder_t *p_dec, const char *psz_role)
-{
-    decoder_sys_t *p_sys = p_dec->p_sys;
-    char psz_name[OMX_MAX_STRINGNAME_SIZE];
-    OMX_ERRORTYPE omx_error;
-    OMX_U32 roles = 0;
-    OMX_U8 **ppsz_roles = 0;
-    unsigned int i, j, len;
-
-    if(!psz_role) goto end;
-    len = strlen(psz_role);
-
-    for( i = 0; ; i++ )
-    {
-        bool b_found = false;
-
-        omx_error = pf_component_enum(psz_name, OMX_MAX_STRINGNAME_SIZE, i);
-        if(omx_error != OMX_ErrorNone) break;
-
-        msg_Dbg(p_dec, "component %s", psz_name);
-
-        omx_error = pf_get_roles_of_component(psz_name, &roles, 0);
-        if(omx_error != OMX_ErrorNone || !roles) continue;
-
-        ppsz_roles = malloc(roles * (sizeof(OMX_U8*) + OMX_MAX_STRINGNAME_SIZE));
-        if(!ppsz_roles) continue;
-
-        for( j = 0; j < roles; j++ )
-            ppsz_roles[j] = ((OMX_U8 *)(&ppsz_roles[roles])) +
-                j * OMX_MAX_STRINGNAME_SIZE;
-
-        omx_error = pf_get_roles_of_component(psz_name, &roles, ppsz_roles);
-        if(omx_error != OMX_ErrorNone) roles = 0;
-
-        for(j = 0; j < roles; j++)
-        {
-            msg_Dbg(p_dec, "  - role: %s", ppsz_roles[j]);
-            if(!strncmp((char *)ppsz_roles[j], psz_role, len)) b_found = true;
-        }
-
-        free(ppsz_roles);
-
-        if(!b_found) continue;
-
-        if(p_sys->components >= MAX_COMPONENTS_LIST_SIZE)
-        {
-            msg_Dbg(p_dec, "too many matching components");
-            continue;
-        }
-
-        strncpy(p_sys->ppsz_components[p_sys->components], psz_name,
-                OMX_MAX_STRINGNAME_SIZE-1);
-        p_sys->components++;
-    }
-
- end:
-    msg_Dbg(p_dec, "found %i matching components for role %s",
-            p_sys->components, psz_role);
-    for( i = 0; i < p_sys->components; i++ )
-        msg_Dbg(p_dec, "- %s", p_sys->ppsz_components[i]);
-
-    return p_sys->components;
-}
-
 /*****************************************************************************
  * ImplementationSpecificWorkarounds: place-holder for implementation
  * specific workarounds
@@ -205,39 +179,12 @@ static OMX_ERRORTYPE ImplementationSpecificWorkarounds(decoder_t *p_dec,
 {
     decoder_sys_t *p_sys = p_dec->p_sys;
     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
-    int i_profile = 0xFFFF, i_level = 0xFFFF;
+    size_t i_profile = 0xFFFF, i_level = 0xFFFF;
 
     /* Try to find out the profile of the video */
-    while(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
-          p_fmt->i_codec == VLC_CODEC_H264)
-    {
-        uint8_t *p = (uint8_t*)p_dec->fmt_in.p_extra;
-        if(!p || !p_dec->fmt_in.p_extra) break;
-
-        /* Check the profile / level */
-        if(p_dec->fmt_in.i_original_fourcc == VLC_FOURCC('a','v','c','1') &&
-           p[0] == 1)
-        {
-            if(p_dec->fmt_in.i_extra < 12) break;
-            p_sys->i_nal_size_length = 1 + (p[4]&0x03);
-            if( !(p[5]&0x1f) ) break;
-            p += 8;
-        }
-        else
-        {
-            if(p_dec->fmt_in.i_extra < 8) break;
-            if(!p[0] && !p[1] && !p[2] && p[3] == 1) p += 4;
-            else if(!p[0] && !p[1] && p[2] == 1) p += 3;
-            else break;
-        }
-
-        if( ((*p++)&0x1f) != 7) break;
-
-        /* Get profile/level out of first SPS */
-        i_profile = p[0];
-        i_level = p[2];
-        break;
-    }
+    if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
+            p_fmt->i_codec == VLC_CODEC_H264)
+        h264_get_profile_level(&p_dec->fmt_in, &i_profile, &i_level, &p_sys->i_nal_size_length);
 
     if(!strcmp(p_sys->psz_component, "OMX.TI.Video.Decoder"))
     {
@@ -286,6 +233,15 @@ static OMX_ERRORTYPE ImplementationSpecificWorkarounds(decoder_t *p_dec,
         }
     }
 #endif
+#ifdef RPI_OMX
+    else if (!strcmp(p_sys->psz_component, "OMX.broadcom.video_decode"))
+    {
+        /* Clear these fields before setting parameters, to allow the codec
+         * fill in what it wants (instead of rejecting whatever happened to
+         * be there. */
+        def->format.video.nStride = def->format.video.nSliceHeight = 0;
+    }
+#endif
 
     return OMX_ErrorNone;
 }
@@ -344,6 +300,12 @@ static OMX_ERRORTYPE SetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
         }
         else
         {
+            if( p_port->p_hwbuf )
+            {
+                p_fmt->i_codec = VLC_CODEC_ANDROID_OPAQUE;
+                break;
+            }
+
             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
                                      &p_fmt->i_codec, 0 ) )
             {
@@ -413,16 +375,23 @@ static OMX_ERRORTYPE SetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
         omx_error = SetAudioParameters(p_port->omx_handle,
                                        &p_port->format_param, def->nPortIndex,
                                        def->format.audio.eEncoding,
+                                       p_fmt->i_codec,
                                        p_fmt->audio.i_channels,
                                        p_fmt->audio.i_rate,
                                        p_fmt->i_bitrate,
                                        p_fmt->audio.i_bitspersample,
                                        p_fmt->audio.i_blockalign);
-        CHECK_ERROR(omx_error, "SetAudioParameters failed (%x : %s)",
-                    omx_error, ErrorToString(omx_error));
+        if (def->eDir == OMX_DirInput) {
+            CHECK_ERROR(omx_error, "SetAudioParameters failed (%x : %s)",
+                        omx_error, ErrorToString(omx_error));
+        } else if (omx_error != OMX_ErrorNone) {
+            msg_Warn(p_dec, "SetAudioParameters failed (%x : %s) on output port",
+                     omx_error, ErrorToString(omx_error));
+            omx_error = OMX_ErrorNone;
+        }
     }
     if (!strcmp(p_dec->p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER") &&
-                def->eDir == OMX_DirOutput)
+                def->eDir == OMX_DirOutput && !p_port->p_hwbuf)
     {
         /* When setting the output buffer size above, the decoder actually
          * sets the buffer size to a lower value than what was chosen. If
@@ -431,28 +400,179 @@ static OMX_ERRORTYPE SetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
         def->nBufferSize *= 2;
     }
 
-    if (def->format.video.eCompressionFormat == OMX_VIDEO_CodingWMV) {
-        OMX_VIDEO_PARAM_WMVTYPE wmvtype = { 0 };
-        OMX_INIT_STRUCTURE(wmvtype);
-        wmvtype.nPortIndex = def->nPortIndex;
-        switch (p_dec->fmt_in.i_codec) {
-        case VLC_CODEC_WMV1:
-            wmvtype.eFormat = OMX_VIDEO_WMVFormat7;
-            break;
-        case VLC_CODEC_WMV2:
-            wmvtype.eFormat = OMX_VIDEO_WMVFormat8;
-            break;
-        case VLC_CODEC_WMV3:
-        case VLC_CODEC_VC1:
-            wmvtype.eFormat = OMX_VIDEO_WMVFormat9;
+ error:
+    return omx_error;
+}
+
+
+/*****************************************************************************
+ * UpdatePixelAspect: Update vlc pixel aspect based on the aspect reported on
+ * the omx port - NOTE: Broadcom specific
+ *****************************************************************************/
+static OMX_ERRORTYPE UpdatePixelAspect(decoder_t *p_dec)
+{
+    decoder_sys_t *p_sys = p_dec->p_sys;
+    OMX_CONFIG_POINTTYPE pixel_aspect;
+    OMX_INIT_STRUCTURE(pixel_aspect);
+    OMX_ERRORTYPE omx_err;
+
+    if (strncmp(p_sys->psz_component, "OMX.broadcom.", 13))
+        return OMX_ErrorNotImplemented;
+
+    pixel_aspect.nPortIndex = p_sys->out.i_port_index;
+    omx_err = OMX_GetParameter(p_sys->omx_handle,
+            OMX_IndexParamBrcmPixelAspectRatio, &pixel_aspect);
+    if (omx_err != OMX_ErrorNone) {
+        msg_Warn(p_dec, "Failed to retrieve aspect ratio");
+    } else {
+        p_dec->fmt_out.video.i_sar_num = pixel_aspect.nX;
+        p_dec->fmt_out.video.i_sar_den = pixel_aspect.nY;
+    }
+
+    return omx_err;
+}
+
+/*****************************************************************************
+ * AllocateBuffers: Allocate Omx buffers
+ *****************************************************************************/
+static OMX_ERRORTYPE AllocateBuffers(decoder_t *p_dec, OmxPort *p_port)
+{
+    decoder_sys_t *p_sys = p_dec->p_sys;
+    OMX_ERRORTYPE omx_error = OMX_ErrorUndefined;
+    OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
+    unsigned int i = 0;
+
+    OMX_DBG( "AllocateBuffers(%d)", def->eDir );
+
+    p_port->i_buffers = p_port->definition.nBufferCountActual;
+
+    p_port->pp_buffers = calloc(p_port->i_buffers, sizeof(OMX_BUFFERHEADERTYPE*));
+    if( !p_port->pp_buffers )
+    {
+        p_port->i_buffers = 0;
+        return OMX_ErrorInsufficientResources;
+    }
+
+    for(i = 0; i < p_port->i_buffers; i++)
+    {
+#if 0
+#define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
+        char *p_buf = malloc(p_port->definition.nBufferSize +
+                             p_port->definition.nBufferAlignment);
+        p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
+#endif
+
+        if( p_port->p_hwbuf )
+        {
+            omx_error =
+                OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
+                               p_port->i_port_index, 0,
+                               p_port->definition.nBufferSize,
+                               p_port->p_hwbuf->pp_handles[i] );
+            OMX_DBG( "OMX_UseBuffer(%d) %p, %p", def->eDir,
+                     p_port->pp_buffers[i], p_port->p_hwbuf->pp_handles[i] );
+        }
+        else if( p_port->b_direct )
+        {
+            omx_error =
+                OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
+                               p_port->i_port_index, 0,
+                               p_port->definition.nBufferSize, (void*)1);
+            OMX_DBG( "OMX_UseBuffer(%d) %p, %p", def->eDir,
+                     p_port->pp_buffers[i], p_port->pp_buffers[i] ?
+                     p_port->pp_buffers[i]->pBuffer : NULL );
+        }
+        else
+        {
+            omx_error =
+                OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
+                                    p_port->i_port_index, 0,
+                                    p_port->definition.nBufferSize);
+            OMX_DBG( "OMX_AllocateBuffer(%d) %p, %p", def->eDir,
+                     p_port->pp_buffers[i], p_port->pp_buffers[i] ? 
+                     p_port->pp_buffers[i]->pBuffer : NULL );
+        }
+
+        if(omx_error != OMX_ErrorNone)
+        {
+            p_port->i_buffers = i;
             break;
         }
-        omx_error = OMX_SetParameter(p_port->omx_handle, OMX_IndexParamVideoWmv, &wmvtype);
-        CHECK_ERROR(omx_error, "OMX_SetParameter OMX_IndexParamVideoWmv failed (%x : %s)",
-                    omx_error, ErrorToString(omx_error));
+        if( !p_port->p_hwbuf )
+            OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
     }
 
- error:
+    CHECK_ERROR(omx_error, "AllocateBuffers failed (%x, %i)",
+                omx_error, (int)p_port->i_port_index );
+
+
+    OMX_DBG( "AllocateBuffers(%d)::done", def->eDir );
+error:
+    return omx_error;
+}
+
+/*****************************************************************************
+ * FreeBuffers: Free Omx buffers
+ *****************************************************************************/
+static OMX_ERRORTYPE FreeBuffers(decoder_t *p_dec, OmxPort *p_port)
+{
+    OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
+    OMX_ERRORTYPE omx_error = OMX_ErrorNone;
+    OMX_BUFFERHEADERTYPE *p_buffer;
+    unsigned int i, i_wait_buffers;
+
+    /* Normally, all buffers are in the port fifo, or given to the codec that
+     * will return them when disabling the port or changing state, therefore we
+     * normally wait for all buffers. For IOMX direct rendering (HwBuffer),
+     * only a few buffers are given to the codec at a time, thus we can only
+     * wait for that many buffers. And after that, we can still free all OMX
+     * buffers since we either got some of them returned via OMX_FIFO_GET, or
+     * never passed them to the codec at all. */
+    if( p_port->p_hwbuf )
+        i_wait_buffers = p_port->p_hwbuf->i_owned;
+    else
+        i_wait_buffers = p_port->i_buffers;
+
+    OMX_DBG( "FreeBuffers(%d), waiting for %u buffers", def->eDir,
+             i_wait_buffers);
+
+    for(i = 0; i < i_wait_buffers; i++)
+    {
+        OMX_FIFO_GET(&p_port->fifo, p_buffer);
+        if (p_buffer->nFlags & SENTINEL_FLAG) {
+            free(p_buffer);
+            i--;
+            continue;
+        }
+    }
+
+    for(i = 0; i < p_port->i_buffers; i++)
+    {
+        p_buffer = p_port->pp_buffers[i];
+        if( p_buffer )
+        {
+            if (p_buffer->pAppPrivate != NULL)
+                picture_Release( p_buffer->pAppPrivate );
+
+            omx_error = OMX_FreeBuffer( p_port->omx_handle,
+                                        p_port->i_port_index, p_buffer );
+            OMX_DBG( "OMX_FreeBuffer(%d) %p, %p", def->eDir,
+                     p_buffer, p_buffer->pBuffer );
+
+            if(omx_error != OMX_ErrorNone) break;
+        }
+    }
+
+    if( omx_error != OMX_ErrorNone )
+       msg_Err( p_dec, "OMX_FreeBuffer failed (%x, %i, %i)",
+                omx_error, (int)p_port->i_port_index, i );
+
+    p_port->i_buffers = 0;
+    free( p_port->pp_buffers );
+    p_port->pp_buffers = NULL;
+
+    OMX_DBG( "FreeBuffers(%d)::done", def->eDir );
+
     return omx_error;
 }
 
@@ -497,6 +617,9 @@ static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
             p_fmt->video.i_visible_height = crop_rect.nHeight;
             if (def->format.video.eColorFormat == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
                 def->format.video.nSliceHeight -= crop_rect.nTop/2;
+
+            if( p_port->p_hwbuf )
+                HwBuffer_SetCrop( p_dec, p_port, &crop_rect );
         }
         else
         {
@@ -504,6 +627,11 @@ static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
             omx_error = OMX_ErrorNone;
         }
 
+        if( p_port->p_hwbuf )
+        {
+            UpdatePixelAspect(p_dec);
+            break;
+        }
         /* Hack: Nexus One (stock firmware with binary OMX driver blob)
          * claims to output 420Planar even though it in in practice is
          * NV21. */
@@ -512,17 +640,10 @@ static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
                     strlen("OMX.qcom.video.decoder")))
             def->format.video.eColorFormat = OMX_QCOM_COLOR_FormatYVU420SemiPlanar;
 
-        /* Hack: Galaxy S II (stock firmware) gives a slice height larger
-         * than the video height, but this doesn't imply padding between
-         * the video planes. Nexus S also has a slice height larger than
-         * the video height, but there it actually is real padding, thus
-         * Galaxy S II is the buggy one. The Galaxy S II decoder is
-         * named OMX.SEC.avcdec while the one on Nexus S is
-         * OMX.SEC.AVC.Decoder. Thus do this for any OMX.SEC. that don't
-         * contain the string ".Decoder". */
-        if(!strncmp(p_sys->psz_component, "OMX.SEC.", strlen("OMX.SEC.")) &&
-           !strstr(p_sys->psz_component, ".Decoder"))
+        if (IgnoreOmxDecoderPadding(p_sys->psz_component)) {
             def->format.video.nSliceHeight = 0;
+            def->format.video.nStride = p_fmt->video.i_width;
+        }
 
         if(!GetVlcVideoFormat( def->format.video.eCompressionFormat,
                                &p_fmt->i_codec, 0 ) )
@@ -548,6 +669,7 @@ static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
             def->format.video.nStride = p_port->i_frame_stride;
 #endif
         p_port->i_frame_stride = def->format.video.nStride;
+        UpdatePixelAspect(p_dec);
         break;
 
     case AUDIO_ES:
@@ -612,22 +734,33 @@ static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
                                            OMX_HANDLETYPE omx_handle)
 {
     decoder_sys_t *p_sys = p_dec->p_sys;
+    OMX_BUFFERHEADERTYPE *p_buffer;
     OMX_ERRORTYPE omx_error;
     OMX_STATETYPE state;
-    unsigned int i, j;
+    unsigned int i;
 
     if(!omx_handle) return OMX_ErrorNone;
 
     omx_error = OMX_GetState(omx_handle, &state);
     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
 
+    if( p_sys->out.p_hwbuf && HwBuffer_Stop( p_dec, &p_sys->out ) != 0 )
+        msg_Warn( p_dec, "HwBuffer_Stop failed" );
+
     if(state == OMX_StateExecuting)
     {
         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
                                      OMX_StateIdle, 0 );
         CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
-        omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
-        CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
+        while (1) {
+            OMX_U32 cmd, state;
+            omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, &cmd, &state, 0);
+            CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
+            // The event queue can contain other OMX_EventCmdComplete items,
+            // such as for OMX_CommandFlush
+            if (cmd == OMX_CommandStateSet && state == OMX_StateIdle)
+                break;
+        }
     }
 
     omx_error = OMX_GetState(omx_handle, &state);
@@ -642,37 +775,18 @@ static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
         for(i = 0; i < p_sys->ports; i++)
         {
             OmxPort *p_port = &p_sys->p_ports[i];
-            OMX_BUFFERHEADERTYPE *p_buffer;
 
-            for(j = 0; j < p_port->i_buffers; j++)
+            omx_error = FreeBuffers( p_dec, p_port );
+            CHECK_ERROR(omx_error, "FreeBuffers failed (%x, %i)",
+                        omx_error, (int)p_port->i_port_index );
+            if( p_port->p_hwbuf )
             {
-                OMX_FIFO_GET(&p_port->fifo, p_buffer);
-                if (p_buffer->nFlags & SENTINEL_FLAG) {
-                    free(p_buffer);
-                    j--;
-                    continue;
-                }
-                omx_error = OMX_FreeBuffer( omx_handle,
-                                            p_port->i_port_index, p_buffer );
-
-                if(omx_error != OMX_ErrorNone) break;
-            }
-            CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
-                        omx_error, (int)p_port->i_port_index, j );
-            while (1) {
-                OMX_FIFO_PEEK(&p_port->fifo, p_buffer);
-                if (!p_buffer) break;
-
-                OMX_FIFO_GET(&p_port->fifo, p_buffer);
-                if (p_buffer->nFlags & SENTINEL_FLAG) {
-                    free(p_buffer);
-                    continue;
-                }
-                msg_Warn( p_dec, "Stray buffer left in fifo, %p", p_buffer );
+                HwBuffer_FreeBuffers( p_dec, p_port );
+                HwBuffer_Join( p_dec, p_port );
             }
         }
 
-        omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
+        omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
         CHECK_ERROR(omx_error, "Wait for Loaded failed (%x)", omx_error );
     }
 
@@ -682,6 +796,19 @@ static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
         OmxPort *p_port = &p_sys->p_ports[i];
         free(p_port->pp_buffers);
         p_port->pp_buffers = 0;
+
+        while (1) {
+            OMX_FIFO_PEEK(&p_port->fifo, p_buffer);
+            if (!p_buffer) break;
+
+            OMX_FIFO_GET(&p_port->fifo, p_buffer);
+            if (p_buffer->nFlags & SENTINEL_FLAG) {
+                free(p_buffer);
+                continue;
+            }
+            msg_Warn( p_dec, "Stray buffer left in fifo, %p", p_buffer );
+        }
+        HwBuffer_Destroy( p_dec, p_port );
     }
     omx_error = pf_free_handle( omx_handle );
     return omx_error;
@@ -739,7 +866,14 @@ static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
     OMX_INIT_STRUCTURE(definition);
     omx_error = OMX_GetParameter(omx_handle, p_dec->fmt_in.i_cat == VIDEO_ES ?
                                  OMX_IndexParamVideoInit : OMX_IndexParamAudioInit, &param);
-    if(omx_error != OMX_ErrorNone) param.nPorts = 0;
+    if(omx_error != OMX_ErrorNone) {
+#ifdef __ANDROID__
+        param.nPorts = 2;
+        param.nStartPortNumber = 0;
+#else
+        param.nPorts = 0;
+#endif
+    }
 
     for(i = 0; i < param.nPorts; i++)
     {
@@ -758,6 +892,7 @@ static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
         p_port->i_port_index = definition.nPortIndex;
         p_port->definition = definition;
         p_port->omx_handle = omx_handle;
+        HwBuffer_Init( p_dec, p_port );
     }
 
     if(!p_sys->in.b_valid || !p_sys->out.b_valid)
@@ -766,7 +901,8 @@ static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
         CHECK_ERROR(omx_error, "couldn't find an input and output port");
     }
 
-    if(!strncmp(p_sys->psz_component, "OMX.SEC.", 8))
+    if( !p_sys->out.p_hwbuf && !strncmp(p_sys->psz_component, "OMX.SEC.", 8) &&
+       p_dec->fmt_in.i_cat == VIDEO_ES )
     {
         OMX_INDEXTYPE index;
         omx_error = OMX_GetExtensionIndex(omx_handle, (OMX_STRING) "OMX.SEC.index.ThumbnailMode", &index);
@@ -786,6 +922,24 @@ static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
         }
     }
 
+    if(!strncmp(p_sys->psz_component, "OMX.broadcom.", 13))
+    {
+        OMX_CONFIG_REQUESTCALLBACKTYPE notifications;
+        OMX_INIT_STRUCTURE(notifications);
+
+        notifications.nPortIndex = p_sys->out.i_port_index;
+        notifications.nIndex = OMX_IndexParamBrcmPixelAspectRatio;
+        notifications.bEnable = OMX_TRUE;
+
+        omx_error = OMX_SetParameter(omx_handle,
+                OMX_IndexConfigRequestCallback, &notifications);
+        if (omx_error == OMX_ErrorNone) {
+            msg_Dbg(p_dec, "Enabled aspect ratio notifications");
+            p_sys->b_aspect_ratio_handled = true;
+        } else
+            msg_Dbg(p_dec, "Could not enable aspect ratio notifications");
+    }
+
     /* Set port definitions */
     for(i = 0; i < p_sys->ports; i++)
     {
@@ -794,21 +948,26 @@ static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
         if(omx_error != OMX_ErrorNone) goto error;
     }
 
+    if(!strncmp(p_sys->psz_component, "OMX.broadcom.", 13) &&
+        p_sys->in.p_fmt->i_codec == VLC_CODEC_H264)
+    {
+        OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE concanParam;
+        OMX_INIT_STRUCTURE(concanParam);
+        concanParam.bStartWithValidFrame = OMX_FALSE;
+
+        omx_error = OMX_SetParameter(omx_handle,
+                OMX_IndexParamBrcmVideoDecodeErrorConcealment, &concanParam);
+        if (omx_error == OMX_ErrorNone)
+            msg_Dbg(p_dec, "StartWithValidFrame disabled.");
+        else
+            msg_Dbg(p_dec, "Could not disable StartWithValidFrame.");
+    }
+
     /* Allocate our array for the omx buffers and enable ports */
     for(i = 0; i < p_sys->ports; i++)
     {
         OmxPort *p_port = &p_sys->p_ports[i];
 
-        p_port->pp_buffers =
-            malloc(p_port->definition.nBufferCountActual *
-                   sizeof(OMX_BUFFERHEADERTYPE*));
-        if(!p_port->pp_buffers)
-        {
-          omx_error = OMX_ErrorInsufficientResources;
-          CHECK_ERROR(omx_error, "memory allocation failed");
-        }
-        p_port->i_buffers = p_port->definition.nBufferCountActual;
-
         /* Enable port */
         if(!p_port->definition.bEnabled)
         {
@@ -816,7 +975,7 @@ static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
                                          p_port->i_port_index, NULL);
             CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
                         (int)p_port->i_port_index, omx_error );
-            omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
+            omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
             CHECK_ERROR(omx_error, "Wait for PortEnable on %i failed (%x)",
                         (int)p_port->i_port_index, omx_error );
         }
@@ -839,13 +998,13 @@ static int OpenDecoder( vlc_object_t *p_this )
     decoder_t *p_dec = (decoder_t*)p_this;
     int status;
 
-    if( 0 || !GetOmxRole(p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat, false) )
+#ifdef __ANDROID__
+    if( p_dec->fmt_in.i_cat == AUDIO_ES )
         return VLC_EGENERIC;
+#endif
 
-#ifdef HAVE_MAEMO
-    if( p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
+    if( 0 || !GetOmxRole(p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat, false) )
         return VLC_EGENERIC;
-#endif
 
     status = OpenGeneric( p_this, false );
     if(status != VLC_SUCCESS) return status;
@@ -884,47 +1043,16 @@ static int OpenGeneric( vlc_object_t *p_this, bool b_encode )
     decoder_sys_t *p_sys;
     OMX_ERRORTYPE omx_error;
     OMX_BUFFERHEADERTYPE *p_header;
-    unsigned int i, j;
-
-    vlc_mutex_lock( &omx_core_mutex );
-    if( omx_refcount > 0 )
-        goto loaded;
-
-    /* Load the OMX core */
-    for( i = 0; ppsz_dll_list[i]; i++ )
-    {
-        dll_handle = dll_open( ppsz_dll_list[i] );
-        if( dll_handle ) break;
-    }
-    if( !dll_handle )
-    {
-        vlc_mutex_unlock( &omx_core_mutex );
-        return VLC_EGENERIC;
-    }
+    unsigned int i;
 
-    pf_init = dlsym( dll_handle, "OMX_Init" );
-    pf_deinit = dlsym( dll_handle, "OMX_Deinit" );
-    pf_get_handle = dlsym( dll_handle, "OMX_GetHandle" );
-    pf_free_handle = dlsym( dll_handle, "OMX_FreeHandle" );
-    pf_component_enum = dlsym( dll_handle, "OMX_ComponentNameEnum" );
-    pf_get_roles_of_component = dlsym( dll_handle, "OMX_GetRolesOfComponent" );
-    if( !pf_init || !pf_deinit || !pf_get_handle || !pf_free_handle ||
-        !pf_component_enum || !pf_get_roles_of_component )
-    {
-        msg_Warn( p_this, "cannot find OMX_* symbols in `%s' (%s)",
-                  ppsz_dll_list[i], dlerror() );
-        dll_close(dll_handle);
-        vlc_mutex_unlock( &omx_core_mutex );
+    if (InitOmxCore(p_this) != VLC_SUCCESS) {
         return VLC_EGENERIC;
     }
 
-loaded:
     /* Allocate the memory needed to store the decoder's structure */
     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(*p_sys)) ) == NULL )
     {
-        if( omx_refcount == 0 )
-            dll_close(dll_handle);
-        vlc_mutex_unlock( &omx_core_mutex );
+        DeinitOmxCore();
         return VLC_ENOMEM;
     }
 
@@ -935,52 +1063,41 @@ loaded:
         p_dec->fmt_out.video = p_dec->fmt_in.video;
         p_dec->fmt_out.audio = p_dec->fmt_in.audio;
         p_dec->fmt_out.i_codec = 0;
+
+        /* set default aspect of 1, if parser did not set it */
+        if (p_dec->fmt_out.video.i_sar_num == 0)
+            p_dec->fmt_out.video.i_sar_num = 1;
+        if (p_dec->fmt_out.video.i_sar_den == 0)
+            p_dec->fmt_out.video.i_sar_den = 1;
     }
     p_sys->b_enc = b_encode;
-    p_sys->pp_last_event = &p_sys->p_events;
-    vlc_mutex_init (&p_sys->mutex);
-    vlc_cond_init (&p_sys->cond);
-    vlc_mutex_init (&p_sys->lock);
-    vlc_mutex_init (&p_sys->in.fifo.lock);
-    vlc_cond_init (&p_sys->in.fifo.wait);
-    p_sys->in.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pOutputPortPrivate) / sizeof(void *);
-    p_sys->in.fifo.pp_last = &p_sys->in.fifo.p_first;
+    InitOmxEventQueue(&p_sys->event_queue);
+    OMX_FIFO_INIT (&p_sys->in.fifo, pOutputPortPrivate );
     p_sys->in.b_direct = false;
     p_sys->in.b_flushed = true;
     p_sys->in.p_fmt = &p_dec->fmt_in;
-    vlc_mutex_init (&p_sys->out.fifo.lock);
-    vlc_cond_init (&p_sys->out.fifo.wait);
-    p_sys->out.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pInputPortPrivate) / sizeof(void *);
-    p_sys->out.fifo.pp_last = &p_sys->out.fifo.p_first;
-    p_sys->out.b_direct = true;
+    OMX_FIFO_INIT (&p_sys->out.fifo, pInputPortPrivate );
+#if defined(USE_IOMX)
+    p_sys->out.b_direct = jni_IsVideoPlayerActivityCreated() && var_InheritBool(p_dec, CFG_PREFIX "dr");
+#else
+    p_sys->out.b_direct = false;
+#endif
     p_sys->out.b_flushed = true;
     p_sys->out.p_fmt = &p_dec->fmt_out;
     p_sys->ports = 2;
     p_sys->p_ports = &p_sys->in;
-    p_sys->b_use_pts = 0;
+    p_sys->b_use_pts = 1;
 
     msg_Dbg(p_dec, "fmt in:%4.4s, out: %4.4s", (char *)&p_dec->fmt_in.i_codec,
             (char *)&p_dec->fmt_out.i_codec);
 
-    /* Initialise the OMX core */
-    omx_error = omx_refcount > 0 ? OMX_ErrorNone : pf_init();
-    omx_refcount++;
-    if(omx_error != OMX_ErrorNone)
-    {
-        msg_Warn( p_this, "OMX_Init failed (%x: %s)", omx_error,
-                  ErrorToString(omx_error) );
-        vlc_mutex_unlock( &omx_core_mutex );
-        CloseGeneric(p_this);
-        return VLC_EGENERIC;
-    }
-    p_sys->b_init = true;
-    vlc_mutex_unlock( &omx_core_mutex );
-
     /* Enumerate components and build a list of the one we want to try */
-    if( !CreateComponentsList(p_dec,
+    p_sys->components =
+        CreateComponentsList(p_this,
              GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec :
                         p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat,
-                        p_sys->b_enc)) )
+                        p_sys->b_enc), p_sys->ppsz_components);
+    if( !p_sys->components )
     {
         msg_Warn( p_this, "couldn't find an omx component for codec %4.4s",
                   (char *)&p_dec->fmt_in.i_codec );
@@ -1004,8 +1121,26 @@ loaded:
          * has got a working OMX.qcom.video.decoder.avc instead though. */
         if (!strncmp(p_sys->ppsz_components[i], "OMX.ARICENT.", 12))
             continue;
-        /* Some nVidia codec with DRM */
-        if (!strncmp(p_sys->ppsz_components[i], "OMX.Nvidia.h264.decode.secure", 29))
+        /* Codecs with DRM, that don't output plain YUV data but only
+         * support direct rendering where the output can't be intercepted. */
+        if (strstr(p_sys->ppsz_components[i], ".secure"))
+            continue;
+        /* Use VC1 decoder for WMV3 for now */
+        if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.WMV.Decoder"))
+            continue;
+        /* This decoder does work, but has an insane latency (leading to errors
+         * about "main audio output playback way too late" and dropped frames).
+         * At least Samsung Galaxy S III (where this decoder is present) has
+         * got another one, OMX.SEC.mp3.dec, that works well and has a
+         * sensible latency. (Also, even if that one isn't found, in general,
+         * using SW codecs is usually more than fast enough for MP3.) */
+        if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.MP3.Decoder"))
+            continue;
+        /* This codec should be able to handle both VC1 and WMV3, but
+         * for VC1 it doesn't output any buffers at all (in the way we use
+         * it) and for WMV3 it outputs plain black buffers. Thus ignore
+         * it until we can make it work properly. */
+        if (!strcmp(p_sys->ppsz_components[i], "OMX.Nvidia.vc1.decode"))
             continue;
 #endif
         omx_error = InitialiseComponent(p_dec, p_sys->ppsz_components[i],
@@ -1022,44 +1157,34 @@ loaded:
     for(i = 0; i < p_sys->ports; i++)
     {
         OmxPort *p_port = &p_sys->p_ports[i];
-
-        for(j = 0; j < p_port->i_buffers; j++)
+        if( p_port->p_hwbuf )
         {
-#if 0
-#define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
-            char *p_buf = malloc(p_port->definition.nBufferSize +
-                                 p_port->definition.nBufferAlignment);
-            p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
-#endif
-
-            if(0 && p_port->b_direct)
-                omx_error =
-                    OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
-                                   p_port->i_port_index, 0,
-                                   p_port->definition.nBufferSize, (void*)1);
-            else
-                omx_error =
-                    OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
-                                        p_port->i_port_index, 0,
-                                        p_port->definition.nBufferSize);
-
-            if(omx_error != OMX_ErrorNone) break;
-            OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[j]);
+            if( HwBuffer_AllocateBuffers( p_dec, p_port ) != 0 )
+            {
+                omx_error = OMX_ErrorInsufficientResources;
+                goto error;
+            }
         }
-        p_port->i_buffers = j;
-        CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
-                    omx_error, (int)p_port->i_port_index, j );
+        omx_error = AllocateBuffers( p_dec, p_port );
+        CHECK_ERROR(omx_error, "AllocateBuffers failed (%x, %i)",
+                    omx_error, (int)p_port->i_port_index );
     }
 
-    omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
+    omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
     CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
 
     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet,
                                  OMX_StateExecuting, 0);
     CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x)", omx_error );
-    omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
+    omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
     CHECK_ERROR(omx_error, "Wait for Executing failed (%x)", omx_error );
 
+    if( p_sys->out.p_hwbuf && HwBuffer_Start( p_dec, &p_sys->out ) != 0 )
+    {
+        omx_error = OMX_ErrorUndefined;
+        goto error;
+    }
+
     /* Send codec configuration data */
     if( p_dec->fmt_in.i_extra )
     {
@@ -1074,11 +1199,51 @@ loaded:
                              p_header->pBuffer, p_header->nAllocLen,
                              (uint32_t*) &p_header->nFilledLen, NULL );
         }
+        else if( p_dec->fmt_in.i_codec == VLC_CODEC_HEVC && !p_sys->in.b_direct )
+        {
+            p_header->nFilledLen = 0;
+            convert_hevc_nal_units( p_dec, p_dec->fmt_in.p_extra,
+                                    p_dec->fmt_in.i_extra,
+                                    p_header->pBuffer, p_header->nAllocLen,
+                                    (uint32_t*) &p_header->nFilledLen,
+                                    &p_sys->i_nal_size_length );
+        }
         else if(p_sys->in.b_direct)
         {
             p_header->pOutputPortPrivate = p_header->pBuffer;
             p_header->pBuffer = p_dec->fmt_in.p_extra;
         }
+        else if (p_dec->fmt_in.i_codec == VLC_CODEC_WMV3 &&
+                 p_dec->fmt_in.i_extra >= 4 &&
+                 p_header->nAllocLen >= 36)
+        {
+            int profile;
+            // According to OMX IL 1.2.0 spec (4.3.33.2), the codec config
+            // data for VC-1 Main/Simple (aka WMV3) is according to table 265
+            // in the VC-1 spec. Most of the fields are just set with placeholders
+            // (like framerate, hrd_buffer/rate).
+            static const uint8_t wmv3seq[] = {
+                0xff, 0xff, 0xff, 0xc5, // numframes=ffffff, marker byte
+                0x04, 0x00, 0x00, 0x00, // marker byte
+                0x00, 0x00, 0x00, 0x00, // struct C, almost equal to p_extra
+                0x00, 0x00, 0x00, 0x00, // struct A, vert size
+                0x00, 0x00, 0x00, 0x00, // struct A, horiz size
+                0x0c, 0x00, 0x00, 0x00, // marker byte
+                0xff, 0xff, 0x00, 0x80, // struct B, level=4, cbr=0, hrd_buffer=ffff
+                0xff, 0xff, 0x00, 0x00, // struct B, hrd_rate=ffff
+                0xff, 0xff, 0xff, 0xff, // struct B, framerate=ffffffff
+            };
+            p_header->nFilledLen = sizeof(wmv3seq);
+            memcpy(p_header->pBuffer, wmv3seq, p_header->nFilledLen);
+            // Struct C - almost equal to the extradata
+            memcpy(&p_header->pBuffer[8], p_dec->fmt_in.p_extra, 4);
+            // Expand profile from the highest 2 bits to the highest 4 bits
+            profile = p_header->pBuffer[8] >> 6;
+            p_header->pBuffer[8] = (p_header->pBuffer[8] & 0x0f) | (profile << 4);
+            // Fill in the height/width for struct A
+            SetDWLE(&p_header->pBuffer[12], p_dec->fmt_in.video.i_height);
+            SetDWLE(&p_header->pBuffer[16], p_dec->fmt_in.video.i_width);
+        }
         else
         {
             if(p_header->nFilledLen > p_header->nAllocLen)
@@ -1107,8 +1272,10 @@ loaded:
     if(p_sys->b_error) goto error;
 
     p_dec->b_need_packetized = true;
-    if (!strcmp(p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER"))
-        p_sys->b_use_pts = 1;
+
+    if (!p_sys->b_use_pts)
+        msg_Dbg( p_dec, "using dts timestamp mode for %s", p_sys->psz_component);
+
     return VLC_SUCCESS;
 
  error:
@@ -1123,9 +1290,9 @@ static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
 {
     decoder_sys_t *p_sys = p_dec->p_sys;
     OMX_PARAM_PORTDEFINITIONTYPE definition;
-    OMX_BUFFERHEADERTYPE *p_buffer;
     OMX_ERRORTYPE omx_error;
-    unsigned int i;
+
+    OMX_DBG( "PortReconfigure(%d)", p_port->definition.eDir );
 
     /* Sanity checking */
     OMX_INIT_STRUCTURE(definition);
@@ -1137,35 +1304,40 @@ static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
        !definition.format.video.nFrameHeight)) )
         return OMX_ErrorUndefined;
 
+    if( p_port->p_hwbuf && HwBuffer_Stop( p_dec, p_port ) != 0 )
+        msg_Warn( p_dec, "HwBuffer_Stop failed" );
+
     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortDisable,
                                  p_port->i_port_index, NULL);
     CHECK_ERROR(omx_error, "OMX_CommandPortDisable on %i failed (%x)",
                 (int)p_port->i_port_index, omx_error );
 
-    for(i = 0; i < p_port->i_buffers; i++)
+    omx_error = FreeBuffers( p_dec, p_port );
+    CHECK_ERROR(omx_error, "FreeBuffers failed (%x, %i)",
+                omx_error, (int)p_port->i_port_index );
+
+    if( p_port->p_hwbuf )
     {
-        OMX_FIFO_GET(&p_port->fifo, p_buffer);
-        if (p_buffer->nFlags & SENTINEL_FLAG) {
-            free(p_buffer);
-            i--;
-            continue;
-        }
-        omx_error = OMX_FreeBuffer( p_sys->omx_handle,
-                                    p_port->i_port_index, p_buffer );
-
-        if(omx_error != OMX_ErrorNone) break;
+        HwBuffer_FreeBuffers( p_dec, p_port );
+        HwBuffer_Join( p_dec, p_port );
     }
-    CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
-                omx_error, (int)p_port->i_port_index, i );
 
-    omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
+    omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
     CHECK_ERROR(omx_error, "Wait for PortDisable failed (%x)", omx_error );
 
     /* Get the new port definition */
     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
     if(omx_error != OMX_ErrorNone) goto error;
 
-    if( p_dec->fmt_in.i_cat != AUDIO_ES )
+    if( p_port->p_hwbuf )
+    {
+        if( HwBuffer_AllocateBuffers( p_dec, p_port ) != 0 )
+        {
+            omx_error = OMX_ErrorInsufficientResources;
+            goto error;
+        }
+    }
+    else if( p_dec->fmt_in.i_cat != AUDIO_ES )
     {
         /* Don't explicitly set the new parameters that we got with
          * OMX_GetParameter above when using audio codecs.
@@ -1189,95 +1361,55 @@ static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
     CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
                 (int)p_port->i_port_index, omx_error );
 
-    if (p_port->definition.nBufferCountActual > p_port->i_buffers) {
-        free(p_port->pp_buffers);
-        p_port->pp_buffers = malloc(p_port->definition.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE*));
-        if(!p_port->pp_buffers)
-        {
-            omx_error = OMX_ErrorInsufficientResources;
-            CHECK_ERROR(omx_error, "memory allocation failed");
-        }
-    }
-    p_port->i_buffers = p_port->definition.nBufferCountActual;
-    for(i = 0; i < p_port->i_buffers; i++)
-    {
-        if(0 && p_port->b_direct)
-            omx_error =
-                OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
-                               p_port->i_port_index, 0,
-                               p_port->definition.nBufferSize, (void*)1);
-        else
-            omx_error =
-                OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
-                                    p_port->i_port_index, 0,
-                                    p_port->definition.nBufferSize);
-
-        if(omx_error != OMX_ErrorNone) break;
-        OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
-    }
-    p_port->i_buffers = i;
-    CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
-                omx_error, (int)p_port->i_port_index, i );
+    omx_error = AllocateBuffers( p_dec, p_port );
+    CHECK_ERROR(omx_error, "OMX_AllocateBuffers failed (%x, %i)",
+                omx_error, (int)p_port->i_port_index );
 
-    omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
+    omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
     CHECK_ERROR(omx_error, "Wait for PortEnable failed (%x)", omx_error );
 
+    if( p_port->p_hwbuf && HwBuffer_Start( p_dec, p_port ) != 0 )
+    {
+        omx_error = OMX_ErrorUndefined;
+        goto error;
+    }
+
     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
 
+    OMX_DBG( "PortReconfigure(%d)::done", p_port->definition.eDir );
  error:
     return omx_error;
 }
 
 /*****************************************************************************
- * DecodeVideo: Called to decode one frame
+ * DecodeVideoOutput
  *****************************************************************************/
-static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
+static int DecodeVideoOutput( decoder_t *p_dec, OmxPort *p_port, picture_t **pp_pic )
 {
-    decoder_sys_t *p_sys = p_dec->p_sys;
+    VLC_UNUSED( p_dec );
+    OMX_BUFFERHEADERTYPE *p_header;
     picture_t *p_pic = NULL, *p_next_pic;
     OMX_ERRORTYPE omx_error;
-    unsigned int i;
-
-    OMX_BUFFERHEADERTYPE *p_header;
-    block_t *p_block;
 
-    if( !pp_block || !*pp_block )
-        return NULL;
-
-    p_block = *pp_block;
-
-    /* Check for errors from codec */
-    if(p_sys->b_error)
+    while(!p_pic)
     {
-        msg_Dbg(p_dec, "error during decoding");
-        block_Release( p_block );
-        return 0;
-    }
+        OMX_FIFO_PEEK(&p_port->fifo, p_header);
+        if(!p_header) break; /* No frame available */
 
-    if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
-    {
-        block_Release( p_block );
-        if(!p_sys->in.b_flushed)
+        if(p_port->b_update_def)
         {
-            msg_Dbg(p_dec, "flushing");
-            OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
-                             p_sys->in.definition.nPortIndex, 0 );
+            omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
+            p_port->b_update_def = 0;
+            CHECK_ERROR(omx_error, "GetPortDefinition failed");
         }
-        p_sys->in.b_flushed = true;
-        return NULL;
-    }
 
-    /* Take care of decoded frames first */
-    while(!p_pic)
-    {
-        OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
-        if(!p_header) break; /* No frame available */
-
-        if(p_sys->out.b_update_def)
+        if( p_port->p_hwbuf )
         {
-            omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
-            p_sys->out.b_update_def = 0;
+            if( HwBuffer_GetPic( p_dec, p_port, &p_pic ) != 0 )
+                goto error;
+            else
+                continue;
         }
 
         if(p_header->nFilledLen)
@@ -1290,111 +1422,239 @@ static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
                 p_pic = decoder_NewPicture( p_dec );
 
                 if (p_pic)
-                    CopyOmxPicture(p_sys->out.definition.format.video.eColorFormat,
-                                   p_pic, p_sys->out.definition.format.video.nSliceHeight,
-                                   p_sys->out.i_frame_stride,
+                    CopyOmxPicture(p_port->definition.format.video.eColorFormat,
+                                   p_pic, p_port->definition.format.video.nSliceHeight,
+                                   p_port->i_frame_stride,
                                    p_header->pBuffer + p_header->nOffset,
-                                   p_sys->out.i_frame_stride_chroma_div);
+                                   p_port->i_frame_stride_chroma_div, NULL);
             }
 
             if (p_pic)
-                p_pic->date = p_header->nTimeStamp;
+                p_pic->date = FromOmxTicks(p_header->nTimeStamp);
             p_header->nFilledLen = 0;
             p_header->pAppPrivate = 0;
         }
 
         /* Get a new picture */
-        if(p_sys->in.b_direct && !p_header->pAppPrivate)
+        if(p_port->b_direct && !p_header->pAppPrivate)
         {
             p_next_pic = decoder_NewPicture( p_dec );
             if(!p_next_pic) break;
 
-            OMX_FIFO_GET(&p_sys->out.fifo, p_header);
+            OMX_FIFO_GET(&p_port->fifo, p_header);
             p_header->pAppPrivate = p_next_pic;
             p_header->pInputPortPrivate = p_header->pBuffer;
             p_header->pBuffer = p_next_pic->p[0].p_pixels;
         }
         else
         {
-            OMX_FIFO_GET(&p_sys->out.fifo, p_header);
+            OMX_FIFO_GET(&p_port->fifo, p_header);
         }
-
-#ifdef OMXIL_EXTRA_DEBUG
-        msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
-#endif
-        OMX_FillThisBuffer(p_sys->omx_handle, p_header);
+        OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
+        OMX_FillThisBuffer(p_port->omx_handle, p_header);
     }
 
+    *pp_pic = p_pic;
+    return 0;
+error:
+    return -1;
+}
+
+static int DecodeVideoInput( decoder_t *p_dec, OmxPort *p_port, block_t **pp_block,
+                             unsigned int i_input_used, bool *p_reconfig )
+{
+    decoder_sys_t *p_sys = p_dec->p_sys;
+    OMX_BUFFERHEADERTYPE *p_header;
+    struct H264ConvertState convert_state = { 0, 0 };
+    block_t *p_block = *pp_block;
+
     /* Send the input buffer to the component */
-    OMX_FIFO_GET(&p_sys->in.fifo, p_header);
+    OMX_FIFO_GET_TIMEOUT(&p_port->fifo, p_header, 10000);
 
     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
         free(p_header);
-        goto reconfig;
+        *p_reconfig = true;
+        return 0;
     }
+    *p_reconfig = false;
 
     if(p_header)
     {
-        p_header->nFilledLen = p_block->i_buffer;
+        bool decode_more = false;
+        p_header->nFilledLen = p_block->i_buffer - i_input_used;
         p_header->nOffset = 0;
         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
         if (p_sys->b_use_pts && p_block->i_pts)
-            p_header->nTimeStamp = p_block->i_pts;
+            p_header->nTimeStamp = ToOmxTicks(p_block->i_pts);
         else
-            p_header->nTimeStamp = p_block->i_dts;
+            p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
 
         /* In direct mode we pass the input pointer as is.
          * Otherwise we memcopy the data */
-        if(p_sys->in.b_direct)
+        if(p_port->b_direct)
         {
             p_header->pOutputPortPrivate = p_header->pBuffer;
             p_header->pBuffer = p_block->p_buffer;
             p_header->pAppPrivate = p_block;
+            i_input_used = p_header->nFilledLen;
         }
         else
         {
             if(p_header->nFilledLen > p_header->nAllocLen)
             {
-                msg_Dbg(p_dec, "buffer too small (%i,%i)",
-                        (int)p_header->nFilledLen, (int)p_header->nAllocLen);
                 p_header->nFilledLen = p_header->nAllocLen;
             }
-            memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
-            block_Release(p_block);
+            memcpy(p_header->pBuffer, p_block->p_buffer + i_input_used, p_header->nFilledLen);
+            i_input_used += p_header->nFilledLen;
+            if (i_input_used == p_block->i_buffer)
+            {
+                block_Release(p_block);
+            }
+            else
+            {
+                decode_more = true;
+                p_header->nFlags &= ~OMX_BUFFERFLAG_ENDOFFRAME;
+            }
         }
 
         /* Convert H.264 NAL format to annex b. Doesn't do anything if
          * i_nal_size_length == 0, which is the case for codecs other
          * than H.264 */
         convert_h264_to_annexb( p_header->pBuffer, p_header->nFilledLen,
-                                p_sys->i_nal_size_length );
-#ifdef OMXIL_EXTRA_DEBUG
-        msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
-                 (int)p_header->nFilledLen );
-#endif
-        OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
-        p_sys->in.b_flushed = false;
-        *pp_block = NULL; /* Avoid being fed the same packet again */
+                                p_sys->i_nal_size_length, &convert_state );
+        OMX_DBG( "EmptyThisBuffer %p, %p, %i, %"PRId64, p_header, p_header->pBuffer,
+                 (int)p_header->nFilledLen, FromOmxTicks(p_header->nTimeStamp) );
+        OMX_EmptyThisBuffer(p_port->omx_handle, p_header);
+        p_port->b_flushed = false;
+        if (decode_more)
+            return DecodeVideoInput( p_dec, p_port, pp_block, i_input_used,
+                                     p_reconfig );
+        else
+            *pp_block = NULL; /* Avoid being fed the same packet again */
     }
 
-reconfig:
-    /* Handle the PortSettingsChanged events */
-    for(i = 0; i < p_sys->ports; i++)
+    return 0;
+}
+
+/*****************************************************************************
+ * DecodeVideo: Called to decode one frame
+ *****************************************************************************/
+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;
+    OMX_ERRORTYPE omx_error;
+    unsigned int i;
+    block_t *p_block;
+
+    if( !pp_block || !*pp_block )
+        return NULL;
+
+    p_block = *pp_block;
+
+    /* Check for errors from codec */
+    if(p_sys->b_error)
     {
-        OmxPort *p_port = &p_sys->p_ports[i];
-        if(p_port->b_reconfigure)
+        msg_Dbg(p_dec, "error during decoding");
+        block_Release( p_block );
+        return 0;
+    }
+
+    if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
+    {
+        block_Release( p_block );
+        if(!p_sys->in.b_flushed)
         {
-            omx_error = PortReconfigure(p_dec, p_port);
-            p_port->b_reconfigure = 0;
+            msg_Dbg(p_dec, "flushing");
+            OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
+                             p_sys->in.definition.nPortIndex, 0 );
         }
-        if(p_port->b_update_def)
+        p_sys->in.b_flushed = true;
+        return NULL;
+    }
+
+    /* Use the aspect ratio provided by the input (ie read from packetizer).
+     * In case the we get aspect ratio info from the decoder (as in the
+     * broadcom OMX implementation on RPi), don't let the packetizer values
+     * override what the decoder says, if anything - otherwise always update
+     * even if it already is set (since it can change within a stream). */
+    if((p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) &&
+       (p_dec->fmt_out.video.i_sar_num == 0 || p_dec->fmt_out.video.i_sar_den == 0 ||
+             !p_sys->b_aspect_ratio_handled))
+    {
+        p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
+        p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
+    }
+
+    /* Take care of decoded frames first */
+    if( DecodeVideoOutput( p_dec, &p_sys->out, &p_pic ) != 0 )
+        goto error;
+
+    /* Loop as long as we haven't either got an input buffer (and cleared
+     * *pp_block) or got an output picture */
+    int max_polling_attempts = 100;
+    int attempts = 0;
+    while( *pp_block && !p_pic ) {
+        bool b_reconfig = false;
+
+        if( DecodeVideoInput( p_dec, &p_sys->in, pp_block, 0, &b_reconfig ) != 0 )
+            goto error;
+
+        /* If we don't have a p_pic from the first try. Try again */
+        if( !b_reconfig && !p_pic &&
+            DecodeVideoOutput( p_dec, &p_sys->out, &p_pic ) != 0 )
+            goto error;
+
+        /* Handle the PortSettingsChanged events */
+        for(i = 0; i < p_sys->ports; i++)
         {
-            omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
-            p_port->b_update_def = 0;
+            OmxPort *p_port = &p_sys->p_ports[i];
+            if(p_port->b_reconfigure)
+            {
+                omx_error = PortReconfigure(p_dec, p_port);
+                p_port->b_reconfigure = 0;
+                CHECK_ERROR(omx_error, "PortReconfigure failed");
+            }
+            if(p_port->b_update_def)
+            {
+                omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
+                p_port->b_update_def = 0;
+                CHECK_ERROR(omx_error, "GetPortDefinition failed");
+            }
+        }
+
+        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
+           playback is paused. */
+        if( p_sys->out.p_hwbuf && attempts == max_polling_attempts ) {
+#ifdef USE_IOMX
+            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_picsys->pf_lock_pic = NULL;
+                p_picsys->pf_unlock_pic = NULL;
+                p_picsys->priv.hw.p_dec = NULL;
+                p_picsys->priv.hw.i_index = -1;
+                p_picsys->priv.hw.b_valid = false;
+            } else {
+                /* If we cannot return a picture we must free the
+                   block since the decoder will proceed with the
+                   next block. */
+                block_Release(p_block);
+                *pp_block = NULL;
+            }
+            return invalid_picture;
+#endif
         }
     }
 
     return p_pic;
+error:
+    p_sys->b_error = true;
+    return NULL;
 }
 
 /*****************************************************************************
@@ -1449,12 +1709,13 @@ block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
     /* Take care of decoded frames first */
     while(!p_buffer)
     {
-        unsigned int i_samples;
+        unsigned int i_samples = 0;
 
         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
         if(!p_header) break; /* No frame available */
 
-        i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
+        if (p_sys->out.p_fmt->audio.i_channels)
+            i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
         if(i_samples)
         {
             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
@@ -1463,25 +1724,24 @@ block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
             p_header->nFilledLen = 0;
 
-            if( p_header->nTimeStamp != 0 &&
-                p_header->nTimeStamp != date_Get( &p_sys->end_date ) )
-                date_Set( &p_sys->end_date, p_header->nTimeStamp );
+            int64_t timestamp = FromOmxTicks(p_header->nTimeStamp);
+            if( timestamp != 0 &&
+                timestamp != date_Get( &p_sys->end_date ) )
+                date_Set( &p_sys->end_date, timestamp );
 
             p_buffer->i_pts = date_Get( &p_sys->end_date );
             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
                 p_buffer->i_pts;
         }
 
-#ifdef OMXIL_EXTRA_DEBUG
-        msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
-#endif
+        OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
     }
 
 
     /* Send the input buffer to the component */
-    OMX_FIFO_GET(&p_sys->in.fifo, p_header);
+    OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
 
     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
         free(p_header);
@@ -1493,7 +1753,7 @@ block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
         p_header->nFilledLen = p_block->i_buffer;
         p_header->nOffset = 0;
         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
-        p_header->nTimeStamp = p_block->i_dts;
+        p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
 
         /* In direct mode we pass the input pointer as is.
          * Otherwise we memcopy the data */
@@ -1515,10 +1775,8 @@ block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
             block_Release(p_block);
         }
 
-#ifdef OMXIL_EXTRA_DEBUG
-        msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
+        OMX_DBG( "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
                  (int)p_header->nFilledLen );
-#endif
         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
         p_sys->in.b_flushed = false;
         *pp_block = NULL; /* Avoid being fed the same packet again */
@@ -1532,9 +1790,13 @@ reconfig:
         if(!p_port->b_reconfigure) continue;
         p_port->b_reconfigure = 0;
         omx_error = PortReconfigure(p_dec, p_port);
+        CHECK_ERROR(omx_error, "PortReconfigure failed");
     }
 
     return p_buffer;
+error:
+    p_sys->b_error = true;
+    return NULL;
 }
 
 /*****************************************************************************
@@ -1578,11 +1840,9 @@ static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
         p_header->nFilledLen = p_sys->in.i_frame_size;
         p_header->nOffset = 0;
         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
-        p_header->nTimeStamp = p_pic->date;
-#ifdef OMXIL_EXTRA_DEBUG
-        msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
+        p_header->nTimeStamp = ToOmxTicks(p_pic->date);
+        OMX_DBG( "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
                  (int)p_header->nFilledLen );
-#endif
         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
         p_sys->in.b_flushed = false;
     }
@@ -1594,6 +1854,7 @@ static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
         if(!p_port->b_reconfigure) continue;
         p_port->b_reconfigure = 0;
         omx_error = PortReconfigure(p_dec, p_port);
+        CHECK_ERROR(omx_error, "PortReconfigure failed");
     }
 
     /* Wait for the decoded frame */
@@ -1614,24 +1875,25 @@ static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
             {
                 /* We're not in direct rendering mode.
                  * Get a new block and copy the content */
-                p_block = block_New( p_dec, p_header->nFilledLen );
+                p_block = block_Alloc( p_header->nFilledLen );
                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
             }
 
             p_block->i_buffer = p_header->nFilledLen;
-            p_block->i_pts = p_block->i_dts = p_header->nTimeStamp;
+            p_block->i_pts = p_block->i_dts = FromOmxTicks(p_header->nTimeStamp);
             p_header->nFilledLen = 0;
             p_header->pAppPrivate = 0;
         }
 
-#ifdef OMXIL_EXTRA_DEBUG
-        msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
-#endif
+        OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
     }
 
     msg_Dbg(p_dec, "done");
     return p_block;
+error:
+    p_sys->b_error = true;
+    return NULL;
 }
 
 /*****************************************************************************
@@ -1643,27 +1905,19 @@ static void CloseGeneric( vlc_object_t *p_this )
     decoder_sys_t *p_sys = p_dec->p_sys;
 
     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
-    vlc_mutex_lock( &omx_core_mutex );
-    omx_refcount--;
-    if( omx_refcount == 0 )
-    {
-        if( p_sys->b_init ) pf_deinit();
-        dll_close( dll_handle );
-    }
-    vlc_mutex_unlock( &omx_core_mutex );
 
-    vlc_mutex_destroy (&p_sys->mutex);
-    vlc_cond_destroy (&p_sys->cond);
-    vlc_mutex_destroy (&p_sys->in.fifo.lock);
-    vlc_cond_destroy (&p_sys->in.fifo.wait);
-    vlc_mutex_destroy (&p_sys->out.fifo.lock);
-    vlc_cond_destroy (&p_sys->out.fifo.wait);
+    DeinitOmxCore();
+
+    DeinitOmxEventQueue(&p_sys->event_queue);
+
+    OMX_FIFO_DESTROY( &p_sys->in.fifo );
+    OMX_FIFO_DESTROY( &p_sys->out.fifo );
 
     free( p_sys );
 }
 
 /*****************************************************************************
- * OmxEventHandler: 
+ * OmxEventHandler:
  *****************************************************************************/
 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
@@ -1674,34 +1928,16 @@ static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
     unsigned int i;
     (void)omx_handle;
 
+    PrintOmxEvent((vlc_object_t *) p_dec, event, data_1, data_2, event_data);
     switch (event)
     {
-    case OMX_EventCmdComplete:
-        switch ((OMX_STATETYPE)data_1)
-        {
-        case OMX_CommandStateSet:
-            msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %s)", EventToString(event),
-                     CommandToString(data_1), StateToString(data_2) );
-            break;
-
-        default:
-            msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u)", EventToString(event),
-                     CommandToString(data_1), (unsigned int)data_2 );
-            break;
-        }
-        break;
-
     case OMX_EventError:
-        msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u, %s)", EventToString(event),
-                 ErrorToString((OMX_ERRORTYPE)data_1), (unsigned int)data_2,
-                 (const char *)event_data);
         //p_sys->b_error = true;
         break;
 
     case OMX_EventPortSettingsChanged:
-        msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
-                 (unsigned int)data_1, (unsigned int)data_2 );
-        if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition )
+        if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition ||
+            data_2 == OMX_IndexParamAudioPcm )
         {
             OMX_BUFFERHEADERTYPE *sentinel;
             for(i = 0; i < p_sys->ports; i++)
@@ -1724,14 +1960,15 @@ static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
         }
         break;
+    case OMX_EventParamOrConfigChanged:
+        UpdatePixelAspect(p_dec);
+        break;
 
     default:
-        msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
-                 (unsigned int)data_1, (unsigned int)data_2 );
         break;
     }
 
-    PostOmxEvent(p_dec, event, data_1, data_2, event_data);
+    PostOmxEvent(&p_sys->event_queue, event, data_1, data_2, event_data);
     return OMX_ErrorNone;
 }
 
@@ -1742,9 +1979,7 @@ static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
     decoder_sys_t *p_sys = p_dec->p_sys;
     (void)omx_handle;
 
-#ifdef OMXIL_EXTRA_DEBUG
-    msg_Dbg( p_dec, "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
-#endif
+    OMX_DBG( "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
 
     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
     {
@@ -1765,10 +2000,8 @@ static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
     decoder_sys_t *p_sys = p_dec->p_sys;
     (void)omx_handle;
 
-#ifdef OMXIL_EXTRA_DEBUG
-    msg_Dbg( p_dec, "OmxFillBufferDone %p, %p, %i", omx_header, omx_header->pBuffer,
-             (int)omx_header->nFilledLen );
-#endif
+    OMX_DBG( "OmxFillBufferDone %p, %p, %i, %"PRId64, omx_header, omx_header->pBuffer,
+             (int)omx_header->nFilledLen, FromOmxTicks(omx_header->nTimeStamp) );
 
     if(omx_header->pInputPortPrivate)
     {
@@ -1778,3 +2011,632 @@ static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
 
     return OMX_ErrorNone;
 }
+
+#if defined(USE_IOMX)
+
+/* Life cycle of buffers when using IOMX direct rendering (HwBuffer):
+ *
+ * <- android display
+ * DequeueThread owned++
+ * -> OMX_FillThisBuffer
+ * ...
+ * <- FillBufferDone OMX_FIFO_PUT
+ * ...
+ * DecodeVideoOutput OMX_FIFO_GET
+ * -> vlc core
+ * ...
+ * DisplayBuffer
+ * -> android display owned--
+ */
+
+/*****************************************************************************
+ * HwBuffer_ChangeState
+ *****************************************************************************/
+static void HwBuffer_ChangeState( decoder_t *p_dec, OmxPort *p_port,
+                                  int i_index, int i_state )
+{
+    VLC_UNUSED( p_dec );
+    p_port->p_hwbuf->i_states[i_index] = i_state;
+    if( i_state == BUF_STATE_OWNED )
+        p_port->p_hwbuf->i_owned++;
+    else
+        p_port->p_hwbuf->i_owned--;
+
+    OMX_DBG( "buffer[%d]: state -> %d, owned buffers: %u",
+             i_index, i_state, p_port->p_hwbuf->i_owned );
+}
+
+/*****************************************************************************
+ * HwBuffer_Init
+ *****************************************************************************/
+static void HwBuffer_Init( decoder_t *p_dec, OmxPort *p_port )
+{
+    VLC_UNUSED( p_dec );
+    void *surf;
+    JNIEnv *p_env;
+    OMX_ERRORTYPE omx_error;
+
+    if( !p_port->b_direct || p_port->definition.eDir != OMX_DirOutput ||
+        p_port->p_fmt->i_cat != VIDEO_ES )
+        return;
+
+    msg_Dbg( p_dec, "HwBuffer_Init");
+
+    if( !(pf_enable_graphic_buffers && pf_get_graphic_buffer_usage &&
+          pf_get_hal_format &&
+          ((OMX_COMPONENTTYPE*)p_port->omx_handle)->UseBuffer) )
+    {
+        msg_Warn( p_dec, "direct output port enabled but can't find "
+                          "extra symbols, switch back to non direct" );
+        goto error;
+    }
+
+    p_port->p_hwbuf = calloc(1, sizeof(HwBuffer));
+    if( !p_port->p_hwbuf )
+    {
+        goto error;
+    }
+    vlc_cond_init (&p_port->p_hwbuf->wait);
+    p_port->p_hwbuf->p_library = LoadNativeWindowAPI( &p_port->p_hwbuf->native_window );
+    if( !p_port->p_hwbuf->p_library )
+    {
+        msg_Warn( p_dec, "LoadNativeWindowAPI failed" );
+        goto error;
+    }
+    if( LoadNativeWindowPrivAPI( &p_port->p_hwbuf->anwpriv ) != 0 )
+    {
+        msg_Warn( p_dec, "LoadNativeWindowPrivAPI failed" );
+        goto error;
+    }
+
+    surf = jni_LockAndGetAndroidJavaSurface();
+    if( !surf ) {
+        jni_UnlockAndroidSurface();
+        msg_Warn( p_dec, "jni_LockAndGetAndroidJavaSurface failed" );
+        goto error;
+    }
+
+    jni_attach_thread( &p_env, THREAD_NAME );
+    p_port->p_hwbuf->window = p_port->p_hwbuf->native_window.winFromSurface( p_env, surf );
+    jni_detach_thread();
+
+    jni_UnlockAndroidSurface();
+    if( !p_port->p_hwbuf->window ) {
+        msg_Warn( p_dec, "winFromSurface failed" );
+        goto error;
+    }
+    p_port->p_hwbuf->window_priv =
+        p_port->p_hwbuf->anwpriv.connect( p_port->p_hwbuf->window );
+    if( !p_port->p_hwbuf->window_priv ) {
+        msg_Warn( p_dec, "connect failed" );
+        p_port->p_hwbuf->native_window.winRelease( p_port->p_hwbuf->window );
+        p_port->p_hwbuf->window = NULL;
+        goto error;
+    }
+
+    omx_error = pf_enable_graphic_buffers( p_port->omx_handle,
+                                           p_port->i_port_index, OMX_TRUE );
+    CHECK_ERROR( omx_error, "can't enable graphic buffers" );
+
+    /* PortDefinition may change after pf_enable_graphic_buffers call */
+    omx_error = OMX_GetParameter( p_port->omx_handle,
+                                  OMX_IndexParamPortDefinition,
+                                  &p_port->definition );
+    CHECK_ERROR( omx_error, "OMX_GetParameter failed (GraphicBuffers) (%x : %s)",
+                 omx_error, ErrorToString(omx_error) );
+
+
+    msg_Dbg( p_dec, "direct output port enabled" );
+    return;
+error:
+    /* if HwBuffer_Init fails, we can fall back to non direct buffers */
+    HwBuffer_Destroy( p_dec, p_port );
+}
+
+/*****************************************************************************
+ * HwBuffer_Destroy
+ *****************************************************************************/
+static void HwBuffer_Destroy( decoder_t *p_dec, OmxPort *p_port )
+{
+    if( p_port->p_hwbuf )
+    {
+        if( p_port->p_hwbuf->p_library )
+        {
+            if( p_port->p_hwbuf->window )
+            {
+                HwBuffer_Stop( p_dec, p_port );
+                HwBuffer_FreeBuffers( p_dec, p_port );
+                HwBuffer_Join( p_dec, p_port );
+                p_port->p_hwbuf->anwpriv.disconnect( p_port->p_hwbuf->window_priv );
+                pf_enable_graphic_buffers( p_port->omx_handle,
+                                           p_port->i_port_index, OMX_FALSE );
+                p_port->p_hwbuf->native_window.winRelease( p_port->p_hwbuf->window );
+            }
+            dlclose( p_port->p_hwbuf->p_library );
+        }
+
+        vlc_cond_destroy( &p_port->p_hwbuf->wait );
+        free( p_port->p_hwbuf );
+        p_port->p_hwbuf = NULL;
+    }
+    p_port->b_direct = false;
+}
+
+/*****************************************************************************
+ * HwBuffer_AllocateBuffers
+ *****************************************************************************/
+static int HwBuffer_AllocateBuffers( decoder_t *p_dec, OmxPort *p_port )
+{
+    decoder_sys_t *p_sys = p_dec->p_sys;
+    OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
+    unsigned int min_undequeued = 0;
+    unsigned int i = 0;
+    int colorFormat = def->format.video.eColorFormat;
+    OMX_ERRORTYPE omx_error;
+    OMX_U32 i_hw_usage;
+
+    if( !p_port->p_hwbuf )
+        return 0;
+
+    omx_error = pf_get_hal_format( p_sys->psz_component, &colorFormat );
+    if( omx_error != OMX_ErrorNone )
+    {
+        msg_Warn( p_dec, "pf_get_hal_format failed (Not fatal)" );
+    }
+
+    omx_error = pf_get_graphic_buffer_usage( p_port->omx_handle,
+                                             p_port->i_port_index,
+                                             &i_hw_usage );
+    if( omx_error != OMX_ErrorNone )
+    {
+        msg_Warn( p_dec, "pf_get_graphic_buffer_usage failed (Not fatal)" );
+        i_hw_usage = 0;
+    }
+
+    if( p_port->p_fmt->video.orientation != ORIENT_NORMAL )
+    {
+        int i_angle;
+
+        switch( p_port->p_fmt->video.orientation )
+        {
+            case ORIENT_ROTATED_90:
+                i_angle = 90;
+                break;
+            case ORIENT_ROTATED_180:
+                i_angle = 180;
+                break;
+            case ORIENT_ROTATED_270:
+                i_angle = 270;
+                break;
+            default:
+                i_angle = 0;
+        }
+        p_port->p_hwbuf->anwpriv.setOrientation( p_port->p_hwbuf->window_priv,
+                                                 i_angle );
+    }
+
+    if( p_port->p_hwbuf->anwpriv.setUsage( p_port->p_hwbuf->window_priv,
+                                           true, (int) i_hw_usage ) != 0 )
+    {
+        msg_Err( p_dec, "can't set usage" );
+        goto error;
+    }
+    if( p_port->p_hwbuf->anwpriv.setBuffersGeometry( p_port->p_hwbuf->window_priv,
+                                                     def->format.video.nFrameWidth,
+                                                     def->format.video.nFrameHeight,
+                                                     colorFormat ) != 0 )
+    {
+        msg_Err( p_dec, "can't set buffers geometry" );
+        goto error;
+    }
+
+    if( p_port->p_hwbuf->anwpriv.getMinUndequeued( p_port->p_hwbuf->window_priv,
+                                                   &min_undequeued ) != 0 )
+    {
+        msg_Err( p_dec, "can't get min_undequeued" );
+        goto error;
+    }
+
+    if( def->nBufferCountActual < def->nBufferCountMin + min_undequeued )
+    {
+        unsigned int new_frames_num = def->nBufferCountMin + min_undequeued;
+
+        OMX_DBG( "AllocateBuffers: video out wants more frames: %lu vs %u",
+                 p_port->definition.nBufferCountActual, new_frames_num );
+
+        p_port->definition.nBufferCountActual = new_frames_num;
+        omx_error = OMX_SetParameter( p_dec->p_sys->omx_handle,
+                                      OMX_IndexParamPortDefinition,
+                                      &p_port->definition );
+        CHECK_ERROR( omx_error, "OMX_SetParameter failed (%x : %s)",
+                     omx_error, ErrorToString(omx_error) );
+    }
+
+    if( p_port->p_hwbuf->anwpriv.setBufferCount( p_port->p_hwbuf->window_priv,
+                                                 def->nBufferCountActual ) != 0 )
+    {
+        msg_Err( p_dec, "can't set buffer_count" );
+        goto error;
+    }
+
+    p_port->p_hwbuf->i_buffers = p_port->definition.nBufferCountActual;
+    p_port->p_hwbuf->i_max_owned = p_port->p_hwbuf->i_buffers - min_undequeued;
+
+    p_port->p_hwbuf->pp_handles = calloc( p_port->p_hwbuf->i_buffers,
+                                          sizeof(void *) );
+    if( !p_port->p_hwbuf->pp_handles )
+        goto error;
+
+    p_port->p_hwbuf->i_states = calloc( p_port->p_hwbuf->i_buffers, sizeof(int) );
+    if( !p_port->p_hwbuf->i_states )
+        goto error;
+
+    p_port->p_hwbuf->inflight_picture = calloc( p_port->p_hwbuf->i_buffers,
+                                                sizeof(picture_t*) );
+    if( !p_port->p_hwbuf->inflight_picture )
+        goto error;
+
+    for(i = 0; i < p_port->p_hwbuf->i_buffers; i++)
+    {
+        void *p_handle = NULL;
+
+        if( p_port->p_hwbuf->anwpriv.dequeue( p_port->p_hwbuf->window_priv,
+                                              &p_handle ) != 0 )
+        {
+            msg_Err( p_dec, "OMXHWBuffer_dequeue Fail" );
+            goto error;
+        }
+        p_port->p_hwbuf->pp_handles[i] = p_handle;
+    }
+    for(i = 0; i < p_port->p_hwbuf->i_max_owned; i++)
+        HwBuffer_ChangeState( p_dec, p_port, i, BUF_STATE_OWNED );
+    for(; i < p_port->p_hwbuf->i_buffers; i++)
+    {
+        OMX_DBG( "canceling buffer(%d)", i );
+        p_port->p_hwbuf->anwpriv.cancel( p_port->p_hwbuf->window_priv,
+                                         p_port->p_hwbuf->pp_handles[i] );
+    }
+
+    return 0;
+
+error:
+
+    msg_Err( p_dec, "HwBuffer_AllocateBuffers(%d) failed", def->eDir );
+    return -1;
+}
+
+/*****************************************************************************
+ * HwBuffer_FreeBuffers
+ *****************************************************************************/
+static int HwBuffer_FreeBuffers( decoder_t *p_dec, OmxPort *p_port )
+{
+    msg_Dbg( p_dec, "HwBuffer_FreeBuffers");
+
+    HWBUFFER_LOCK();
+
+    p_port->p_hwbuf->b_run = false;
+
+    if( p_port->p_hwbuf->pp_handles )
+    {
+        for(unsigned int i = 0; i < p_port->p_hwbuf->i_buffers; i++)
+        {
+            void *p_handle = p_port->p_hwbuf->pp_handles[i];
+
+            if( p_handle && p_port->p_hwbuf->i_states[i] == BUF_STATE_OWNED )
+            {
+                p_port->p_hwbuf->anwpriv.cancel( p_port->p_hwbuf->window_priv, p_handle );
+                HwBuffer_ChangeState( p_dec, p_port, i, BUF_STATE_NOT_OWNED );
+            }
+        }
+    }
+    HWBUFFER_BROADCAST( p_port );
+
+    HWBUFFER_UNLOCK();
+
+    p_port->p_hwbuf->i_buffers = 0;
+
+    free( p_port->p_hwbuf->pp_handles );
+    p_port->p_hwbuf->pp_handles = NULL;
+
+    free( p_port->p_hwbuf->i_states );
+    p_port->p_hwbuf->i_states = NULL;
+
+    free( p_port->p_hwbuf->inflight_picture );
+    p_port->p_hwbuf->inflight_picture = NULL;
+
+    return 0;
+}
+
+/*****************************************************************************
+ * HwBuffer_Start
+ *****************************************************************************/
+static int HwBuffer_Start( decoder_t *p_dec, OmxPort *p_port )
+{
+    OMX_BUFFERHEADERTYPE *p_header;
+
+    msg_Dbg( p_dec, "HwBuffer_Start" );
+    HWBUFFER_LOCK();
+
+    /* fill all owned buffers dequeued by HwBuffer_AllocatesBuffers */
+    for(unsigned int i = 0; i < p_port->p_hwbuf->i_buffers; i++)
+    {
+        p_header = p_port->pp_buffers[i];
+
+        if( p_header && p_port->p_hwbuf->i_states[i] == BUF_STATE_OWNED )
+        {
+            if( p_port->p_hwbuf->anwpriv.lock( p_port->p_hwbuf->window_priv,
+                                               p_header->pBuffer ) != 0 )
+            {
+                msg_Err( p_dec, "lock failed" );
+                HWBUFFER_UNLOCK();
+                return -1;
+            }
+            OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
+            OMX_FillThisBuffer( p_port->omx_handle, p_header );
+        }
+    }
+
+    p_port->p_hwbuf->b_run = true;
+    if( vlc_clone( &p_port->p_hwbuf->dequeue_thread,
+                   DequeueThread, p_dec, VLC_THREAD_PRIORITY_LOW ) )
+    {
+        p_port->p_hwbuf->b_run = false;
+        HWBUFFER_UNLOCK();
+        return -1;
+    }
+
+    HWBUFFER_UNLOCK();
+
+    return 0;
+}
+
+/*****************************************************************************
+ * HwBuffer_Stop: stop DequeueThread and invalidate all pictures that are sent
+ * to vlc core. The thread can be stuck in dequeue, so don't
+ * join it now since it can be unblocked later by HwBuffer_FreeBuffers.
+ *****************************************************************************/
+static int HwBuffer_Stop( decoder_t *p_dec, OmxPort *p_port )
+{
+    VLC_UNUSED( p_dec );
+
+    msg_Dbg( p_dec, "HwBuffer_Stop" );
+    HWBUFFER_LOCK();
+
+    p_port->p_hwbuf->b_run = false;
+
+    /* invalidate and release all inflight pictures */
+    if( p_port->p_hwbuf->inflight_picture ) {
+        for( unsigned int i = 0; i < p_port->i_buffers; ++i ) {
+            picture_t *p_pic = p_port->p_hwbuf->inflight_picture[i];
+            if( p_pic ) {
+                picture_sys_t *p_picsys = p_pic->p_sys;
+                if( p_picsys ) {
+                    void *p_handle = p_port->pp_buffers[p_picsys->priv.hw.i_index]->pBuffer;
+                    if( p_handle )
+                    {
+                        p_port->p_hwbuf->anwpriv.cancel( p_port->p_hwbuf->window_priv, p_handle );
+                        HwBuffer_ChangeState( p_dec, p_port, p_picsys->priv.hw.i_index,
+                                              BUF_STATE_NOT_OWNED );
+                    }
+                    p_picsys->priv.hw.b_valid = false;
+                }
+                p_port->p_hwbuf->inflight_picture[i] = NULL;
+            }
+        }
+    }
+
+    HWBUFFER_BROADCAST( p_port );
+
+    HWBUFFER_UNLOCK();
+
+    return 0;
+}
+
+/*****************************************************************************
+ * HwBuffer_Join: join DequeueThread previously stopped by HwBuffer_Stop.
+ *****************************************************************************/
+static int HwBuffer_Join( decoder_t *p_dec, OmxPort *p_port )
+{
+    VLC_UNUSED( p_dec );
+
+    if( p_port->p_hwbuf->dequeue_thread )
+    {
+        vlc_join( p_port->p_hwbuf->dequeue_thread, NULL );
+        p_port->p_hwbuf->dequeue_thread = NULL;
+    }
+    return 0;
+}
+
+/*****************************************************************************
+ * HwBuffer_GetPic
+ *****************************************************************************/
+static int HwBuffer_GetPic( decoder_t *p_dec, OmxPort *p_port,
+                            picture_t **pp_pic)
+{
+    int i_index = -1;
+    picture_t *p_pic;
+    picture_sys_t *p_picsys;
+    OMX_BUFFERHEADERTYPE *p_header;
+
+    OMX_FIFO_PEEK(&p_port->fifo, p_header);
+
+    if( !p_header )
+        return 0;
+
+    for(unsigned int i = 0; i < p_port->i_buffers; i++)
+    {
+        if( p_port->pp_buffers[i] == p_header )
+        {
+            i_index = i;
+            break;
+        }
+    }
+    if( i_index == -1 )
+    {
+        msg_Err( p_dec, "output buffer not found" );
+        return -1;
+    }
+
+    p_pic = decoder_NewPicture( p_dec );
+    if(!p_pic)
+    {
+        msg_Err( p_dec, "decoder_NewPicture failed" );
+        return -1;
+    }
+    p_pic->date = FromOmxTicks( p_header->nTimeStamp );
+
+    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 = i_index;
+    p_picsys->priv.hw.b_valid = true;
+
+    HWBUFFER_LOCK();
+    p_port->p_hwbuf->inflight_picture[i_index] = p_pic;
+    HWBUFFER_UNLOCK();
+
+    *pp_pic = p_pic;
+    OMX_FIFO_GET( &p_port->fifo, p_header );
+    return 0;
+}
+
+/*****************************************************************************
+ * HwBuffer_SetCrop
+ *****************************************************************************/
+static void HwBuffer_SetCrop( decoder_t *p_dec, OmxPort *p_port,
+                              OMX_CONFIG_RECTTYPE *p_rect )
+{
+    VLC_UNUSED( p_dec );
+
+    p_port->p_hwbuf->anwpriv.setCrop( p_port->p_hwbuf->window_priv,
+                                      p_rect->nLeft, p_rect->nTop,
+                                      p_rect->nWidth, p_rect->nHeight );
+}
+
+/*****************************************************************************
+ * DequeueThread
+ *****************************************************************************/
+static void *DequeueThread( void *data )
+{
+    decoder_t *p_dec = data;
+    decoder_sys_t *p_sys = p_dec->p_sys;;
+    OmxPort *p_port = &p_sys->out;
+    unsigned int i;
+    int i_index = -1;
+    int err;
+    void *p_handle = NULL;
+    OMX_BUFFERHEADERTYPE *p_header;
+
+    msg_Dbg( p_dec, "DequeueThread running");
+    HWBUFFER_LOCK();
+    while( p_port->p_hwbuf->b_run )
+    {
+        while( p_port->p_hwbuf->b_run &&
+               p_port->p_hwbuf->i_owned >= p_port->p_hwbuf->i_max_owned )
+            HWBUFFER_WAIT( p_port );
+
+        if( !p_port->p_hwbuf->b_run ) continue;
+
+        HWBUFFER_UNLOCK();
+
+
+        /* The thread can be stuck here. It shouldn't happen since we make sure
+         * we call the dequeue function if there is at least one buffer
+         * available. */
+        err = p_port->p_hwbuf->anwpriv.dequeue( p_port->p_hwbuf->window_priv, &p_handle );
+        if( err == 0 )
+            err = p_port->p_hwbuf->anwpriv.lock( p_port->p_hwbuf->window_priv, p_handle );
+
+        HWBUFFER_LOCK();
+
+        if( err != 0 ) {
+            if( err != -EBUSY )
+                p_port->p_hwbuf->b_run = false;
+            continue;
+        }
+
+        if( !p_port->p_hwbuf->b_run )
+        {
+            p_port->p_hwbuf->anwpriv.cancel( p_port->p_hwbuf->window_priv, p_handle );
+            continue;
+        }
+
+        for(i = 0; i < p_port->i_buffers; i++)
+        {
+            if( p_port->pp_buffers[i]->pBuffer == p_handle )
+            {
+                i_index = i;
+                p_header = p_port->pp_buffers[i_index];
+                break;
+            }
+        }
+        if( i_index == -1 )
+        {
+            msg_Err( p_dec, "p_port->p_hwbuf->anwpriv.dequeue returned unknown handle" );
+            continue;
+        }
+
+        HwBuffer_ChangeState( p_dec, p_port, i_index, BUF_STATE_OWNED );
+
+        OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
+        OMX_FillThisBuffer( p_sys->omx_handle, p_header );
+
+        HWBUFFER_BROADCAST( p_port );
+    }
+    HWBUFFER_UNLOCK();
+
+    msg_Dbg( p_dec, "DequeueThread stopped");
+    return NULL;
+}
+
+/*****************************************************************************
+ * vout callbacks
+ *****************************************************************************/
+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;
+    OmxPort *p_port = &p_sys->out;
+    void *p_handle;
+
+    if( !p_picsys->priv.hw.b_valid ) return;
+
+    HWBUFFER_LOCK();
+
+    /* Picture might have been invalidated while waiting on the mutex. */
+    if (!p_picsys->priv.hw.b_valid) {
+        HWBUFFER_UNLOCK();
+        return;
+    }
+
+    p_handle = p_port->pp_buffers[p_picsys->priv.hw.i_index]->pBuffer;
+
+    OMX_DBG( "DisplayBuffer: %s %p",
+             b_render ? "render" : "cancel", p_handle );
+
+    if( !p_handle )
+    {
+        msg_Err( p_dec, "DisplayBuffer: buffer handle invalid" );
+        goto end;
+    }
+
+    if( b_render )
+        p_port->p_hwbuf->anwpriv.queue( p_port->p_hwbuf->window_priv, p_handle );
+    else
+        p_port->p_hwbuf->anwpriv.cancel( p_port->p_hwbuf->window_priv, p_handle );
+
+    HwBuffer_ChangeState( p_dec, p_port, p_picsys->priv.hw.i_index, BUF_STATE_NOT_OWNED );
+    HWBUFFER_BROADCAST( p_port );
+
+    p_port->p_hwbuf->inflight_picture[p_picsys->priv.hw.i_index] = NULL;
+
+end:
+    p_picsys->priv.hw.b_valid = false;
+    p_picsys->priv.hw.i_index = -1;
+
+    HWBUFFER_UNLOCK();
+}
+
+#endif // USE_IOMX