]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
omxil: Convert from/to OMX_TICKS via helper functions
[vlc] / modules / codec / omxil / omxil.c
1 /*****************************************************************************
2  * omxil.c: Video decoder module making use of OpenMAX IL components.
3  *****************************************************************************
4  * Copyright (C) 2010 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <dlfcn.h>
32 #if defined(USE_IOMX)
33 /* On dll_open, just check that the OMX_Init symbol already is loaded */
34 # define dll_open(name) dlsym(RTLD_DEFAULT, "OMX_Init")
35 # define dll_close(handle) do { } while (0)
36 # define dlsym(handle, name) dlsym(RTLD_DEFAULT, "I" name)
37 #else
38 # define dll_open(name) dlopen( name, RTLD_NOW )
39 # define dll_close(handle) dlclose(handle)
40 #endif
41
42 #include <limits.h>
43
44 #include <vlc_common.h>
45 #include <vlc_plugin.h>
46 #include <vlc_codec.h>
47 #include <vlc_block_helper.h>
48 #include <vlc_cpu.h>
49 #include "../h264_nal.h"
50
51 #include "omxil.h"
52
53 #ifndef NDEBUG
54 # define OMXIL_EXTRA_DEBUG
55 #endif
56
57 #define SENTINEL_FLAG 0x10000
58
59 /*****************************************************************************
60  * List of OpenMAX IL core we will try in order
61  *****************************************************************************/
62 static const char *ppsz_dll_list[] =
63 {
64 #if defined(USE_IOMX)
65     "libiomx.so", /* Not used when using IOMX, the lib should already be loaded */
66 #else
67     "libOMX_Core.so", /* TI OMAP IL core */
68     "libOmxCore.so", /* Qualcomm IL core */
69     "libomxil-bellagio.so",  /* Bellagio IL core */
70 #endif
71     0
72 };
73
74 /*****************************************************************************
75  * Global OMX Core instance, shared between module instances
76  *****************************************************************************/
77 static vlc_mutex_t omx_core_mutex = VLC_STATIC_MUTEX;
78 static unsigned int omx_refcount = 0;
79 static void *dll_handle;
80 static OMX_ERRORTYPE (*pf_init) (void);
81 static OMX_ERRORTYPE (*pf_deinit) (void);
82 static OMX_ERRORTYPE (*pf_get_handle) (OMX_HANDLETYPE *, OMX_STRING,
83                                        OMX_PTR, OMX_CALLBACKTYPE *);
84 static OMX_ERRORTYPE (*pf_free_handle) (OMX_HANDLETYPE);
85 static OMX_ERRORTYPE (*pf_component_enum)(OMX_STRING, OMX_U32, OMX_U32);
86 static OMX_ERRORTYPE (*pf_get_roles_of_component)(OMX_STRING, OMX_U32 *, OMX_U8 **);
87
88 /*****************************************************************************
89  * Local prototypes
90  *****************************************************************************/
91 static int  OpenDecoder( vlc_object_t * );
92 static int  OpenEncoder( vlc_object_t * );
93 static int  OpenGeneric( vlc_object_t *, bool b_encode );
94 static void CloseGeneric( vlc_object_t * );
95
96 static picture_t *DecodeVideo( decoder_t *, block_t ** );
97 static block_t *DecodeAudio ( decoder_t *, block_t ** );
98 static block_t *EncodeVideo( encoder_t *, picture_t * );
99
100 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE, OMX_PTR, OMX_EVENTTYPE,
101                                       OMX_U32, OMX_U32, OMX_PTR );
102 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE, OMX_PTR,
103                                          OMX_BUFFERHEADERTYPE * );
104 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE, OMX_PTR,
105                                         OMX_BUFFERHEADERTYPE * );
106
107 /*****************************************************************************
108  * Module descriptor
109  *****************************************************************************/
110 vlc_module_begin ()
111     set_description( N_("Audio/Video decoder (using OpenMAX IL)") )
112     set_category( CAT_INPUT )
113     set_subcategory( SUBCAT_INPUT_VCODEC )
114     set_section( N_("Decoding") , NULL )
115 #if defined(USE_IOMX)
116     /* For IOMX, don't enable it automatically via priorities,
117      * enable it only via the --codec iomx command line parameter when
118      * wanted. */
119     set_capability( "decoder", 0 )
120 #else
121     set_capability( "decoder", 80 )
122 #endif
123     set_callbacks( OpenDecoder, CloseGeneric )
124
125     add_submodule ()
126     set_section( N_("Encoding") , NULL )
127     set_description( N_("Video encoder (using OpenMAX IL)") )
128     set_capability( "encoder", 0 )
129     set_callbacks( OpenEncoder, CloseGeneric )
130 vlc_module_end ()
131
132 /*****************************************************************************
133  * CreateComponentsList: creates a list of components matching the given role
134  *****************************************************************************/
135 static int CreateComponentsList(decoder_t *p_dec, const char *psz_role)
136 {
137     decoder_sys_t *p_sys = p_dec->p_sys;
138     char psz_name[OMX_MAX_STRINGNAME_SIZE];
139     OMX_ERRORTYPE omx_error;
140     OMX_U32 roles = 0;
141     OMX_U8 **ppsz_roles = 0;
142     unsigned int i, j;
143
144     if(!psz_role) goto end;
145
146     for( i = 0; ; i++ )
147     {
148         bool b_found = false;
149
150         omx_error = pf_component_enum(psz_name, OMX_MAX_STRINGNAME_SIZE, i);
151         if(omx_error != OMX_ErrorNone) break;
152
153         msg_Dbg(p_dec, "component %s", psz_name);
154
155         omx_error = pf_get_roles_of_component(psz_name, &roles, 0);
156         if(omx_error != OMX_ErrorNone || !roles) continue;
157
158         ppsz_roles = malloc(roles * (sizeof(OMX_U8*) + OMX_MAX_STRINGNAME_SIZE));
159         if(!ppsz_roles) continue;
160
161         for( j = 0; j < roles; j++ )
162             ppsz_roles[j] = ((OMX_U8 *)(&ppsz_roles[roles])) +
163                 j * OMX_MAX_STRINGNAME_SIZE;
164
165         omx_error = pf_get_roles_of_component(psz_name, &roles, ppsz_roles);
166         if(omx_error != OMX_ErrorNone) roles = 0;
167
168         for(j = 0; j < roles; j++)
169         {
170             msg_Dbg(p_dec, "  - role: %s", ppsz_roles[j]);
171             if(!strcmp((char *)ppsz_roles[j], psz_role)) b_found = true;
172         }
173
174         free(ppsz_roles);
175
176         if(!b_found) continue;
177
178         if(p_sys->components >= MAX_COMPONENTS_LIST_SIZE)
179         {
180             msg_Dbg(p_dec, "too many matching components");
181             continue;
182         }
183
184         strncpy(p_sys->ppsz_components[p_sys->components], psz_name,
185                 OMX_MAX_STRINGNAME_SIZE-1);
186         p_sys->components++;
187     }
188
189  end:
190     msg_Dbg(p_dec, "found %i matching components for role %s",
191             p_sys->components, psz_role);
192     for( i = 0; i < p_sys->components; i++ )
193         msg_Dbg(p_dec, "- %s", p_sys->ppsz_components[i]);
194
195     return p_sys->components;
196 }
197
198 /*****************************************************************************
199  * ImplementationSpecificWorkarounds: place-holder for implementation
200  * specific workarounds
201  *****************************************************************************/
202 static OMX_ERRORTYPE ImplementationSpecificWorkarounds(decoder_t *p_dec,
203     OmxPort *p_port, es_format_t *p_fmt)
204 {
205     decoder_sys_t *p_sys = p_dec->p_sys;
206     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
207     int i_profile = 0xFFFF, i_level = 0xFFFF;
208
209     /* Try to find out the profile of the video */
210     while(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
211           p_fmt->i_codec == VLC_CODEC_H264)
212     {
213         uint8_t *p = (uint8_t*)p_dec->fmt_in.p_extra;
214         if(!p || !p_dec->fmt_in.p_extra) break;
215
216         /* Check the profile / level */
217         if(p_dec->fmt_in.i_original_fourcc == VLC_FOURCC('a','v','c','1') &&
218            p[0] == 1)
219         {
220             if(p_dec->fmt_in.i_extra < 12) break;
221             p_sys->i_nal_size_length = 1 + (p[4]&0x03);
222             if( !(p[5]&0x1f) ) break;
223             p += 8;
224         }
225         else
226         {
227             if(p_dec->fmt_in.i_extra < 8) break;
228             if(!p[0] && !p[1] && !p[2] && p[3] == 1) p += 4;
229             else if(!p[0] && !p[1] && p[2] == 1) p += 3;
230             else break;
231         }
232
233         if( ((*p++)&0x1f) != 7) break;
234
235         /* Get profile/level out of first SPS */
236         i_profile = p[0];
237         i_level = p[2];
238         break;
239     }
240
241     if(!strcmp(p_sys->psz_component, "OMX.TI.Video.Decoder"))
242     {
243         if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
244            p_fmt->i_codec == VLC_CODEC_H264 &&
245            (i_profile != 66 || i_level > 30))
246         {
247             msg_Dbg(p_dec, "h264 profile/level not supported (0x%x, 0x%x)",
248                     i_profile, i_level);
249             return OMX_ErrorNotImplemented;
250         }
251
252         if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirOutput &&
253            p_fmt->i_codec == VLC_CODEC_I420)
254         {
255             /* I420 xvideo is slow on OMAP */
256             def->format.video.eColorFormat = OMX_COLOR_FormatCbYCrY;
257             GetVlcChromaFormat( def->format.video.eColorFormat,
258                                 &p_fmt->i_codec, 0 );
259             GetVlcChromaSizes( p_fmt->i_codec,
260                                def->format.video.nFrameWidth,
261                                def->format.video.nFrameHeight,
262                                &p_port->i_frame_size, &p_port->i_frame_stride,
263                                &p_port->i_frame_stride_chroma_div );
264             def->format.video.nStride = p_port->i_frame_stride;
265             def->nBufferSize = p_port->i_frame_size;
266         }
267     }
268     else if(!strcmp(p_sys->psz_component, "OMX.st.video_encoder"))
269     {
270         if(p_fmt->i_cat == VIDEO_ES)
271         {
272             /* Bellagio's encoder doesn't encode the framerate in Q16 */
273             def->format.video.xFramerate >>= 16;
274         }
275     }
276 #if 0 /* FIXME: doesn't apply for HP Touchpad */
277     else if (!strncmp(p_sys->psz_component, "OMX.qcom.video.decoder.",
278                       strlen("OMX.qcom.video.decoder")))
279     {
280         /* qdsp6 refuses buffer size larger than 450K on input port */
281         if (def->nBufferSize > 450 * 1024)
282         {
283             def->nBufferSize = 450 * 1024;
284             p_port->i_frame_size = def->nBufferSize;
285         }
286     }
287 #endif
288
289     return OMX_ErrorNone;
290 }
291
292 /*****************************************************************************
293  * SetPortDefinition: set definition of the omx port based on the vlc format
294  *****************************************************************************/
295 static OMX_ERRORTYPE SetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
296                                        es_format_t *p_fmt)
297 {
298     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
299     OMX_ERRORTYPE omx_error;
300
301     omx_error = OMX_GetParameter(p_port->omx_handle,
302                                  OMX_IndexParamPortDefinition, def);
303     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
304                 omx_error, ErrorToString(omx_error));
305
306     switch(p_fmt->i_cat)
307     {
308     case VIDEO_ES:
309         def->format.video.nFrameWidth = p_fmt->video.i_width;
310         def->format.video.nFrameHeight = p_fmt->video.i_height;
311         if(def->format.video.eCompressionFormat == OMX_VIDEO_CodingUnused)
312             def->format.video.nStride = def->format.video.nFrameWidth;
313         if( p_fmt->video.i_frame_rate > 0 &&
314             p_fmt->video.i_frame_rate_base > 0 )
315             def->format.video.xFramerate = (p_fmt->video.i_frame_rate << 16) /
316                 p_fmt->video.i_frame_rate_base;
317
318         if(def->eDir == OMX_DirInput || p_dec->p_sys->b_enc)
319         {
320             if (def->eDir == OMX_DirInput && p_dec->p_sys->b_enc)
321                 def->nBufferSize = def->format.video.nFrameWidth *
322                   def->format.video.nFrameHeight * 2;
323             p_port->i_frame_size = def->nBufferSize;
324
325             if(!GetOmxVideoFormat(p_fmt->i_codec,
326                                   &def->format.video.eCompressionFormat, 0) )
327             {
328                 if(!GetOmxChromaFormat(p_fmt->i_codec,
329                                        &def->format.video.eColorFormat, 0) )
330                 {
331                     omx_error = OMX_ErrorNotImplemented;
332                     CHECK_ERROR(omx_error, "codec %4.4s doesn't match any OMX format",
333                                 (char *)&p_fmt->i_codec );
334                 }
335                 GetVlcChromaSizes( p_fmt->i_codec,
336                                    def->format.video.nFrameWidth,
337                                    def->format.video.nFrameHeight,
338                                    &p_port->i_frame_size, &p_port->i_frame_stride,
339                                    &p_port->i_frame_stride_chroma_div );
340                 def->format.video.nStride = p_port->i_frame_stride;
341                 def->nBufferSize = p_port->i_frame_size;
342             }
343         }
344         else
345         {
346             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
347                                      &p_fmt->i_codec, 0 ) )
348             {
349                 omx_error = OMX_ErrorNotImplemented;
350                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
351                             (int)def->format.video.eColorFormat );
352             }
353             GetVlcChromaSizes( p_fmt->i_codec,
354                                def->format.video.nFrameWidth,
355                                def->format.video.nFrameHeight,
356                                &p_port->i_frame_size, &p_port->i_frame_stride,
357                                &p_port->i_frame_stride_chroma_div );
358             def->format.video.nStride = p_port->i_frame_stride;
359             if (p_port->i_frame_size > def->nBufferSize)
360                 def->nBufferSize = p_port->i_frame_size;
361         }
362         break;
363
364     case AUDIO_ES:
365         p_port->i_frame_size = def->nBufferSize;
366         if(def->eDir == OMX_DirInput)
367         {
368             if(!GetOmxAudioFormat(p_fmt->i_codec,
369                                   &def->format.audio.eEncoding, 0) )
370             {
371                 omx_error = OMX_ErrorNotImplemented;
372                 CHECK_ERROR(omx_error, "codec %4.4s doesn't match any OMX format",
373                             (char *)&p_fmt->i_codec );
374             }
375         }
376         else
377         {
378             if( !OmxToVlcAudioFormat(def->format.audio.eEncoding,
379                                    &p_fmt->i_codec, 0 ) )
380             {
381                 omx_error = OMX_ErrorNotImplemented;
382                 CHECK_ERROR(omx_error, "OMX audio encoding %i not supported",
383                             (int)def->format.audio.eEncoding );
384             }
385         }
386         break;
387
388     default: return OMX_ErrorNotImplemented;
389     }
390
391     omx_error = ImplementationSpecificWorkarounds(p_dec, p_port, p_fmt);
392     CHECK_ERROR(omx_error, "ImplementationSpecificWorkarounds failed (%x : %s)",
393                 omx_error, ErrorToString(omx_error));
394
395     omx_error = OMX_SetParameter(p_port->omx_handle,
396                                  OMX_IndexParamPortDefinition, def);
397     CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
398                 omx_error, ErrorToString(omx_error));
399
400     omx_error = OMX_GetParameter(p_port->omx_handle,
401                                  OMX_IndexParamPortDefinition, def);
402     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
403                 omx_error, ErrorToString(omx_error));
404
405     if(p_port->i_frame_size > def->nBufferSize)
406         def->nBufferSize = p_port->i_frame_size;
407     p_port->i_frame_size = def->nBufferSize;
408
409     /* Deal with audio params */
410     if(p_fmt->i_cat == AUDIO_ES)
411     {
412         omx_error = SetAudioParameters(p_port->omx_handle,
413                                        &p_port->format_param, def->nPortIndex,
414                                        def->format.audio.eEncoding,
415                                        p_fmt->i_codec,
416                                        p_fmt->audio.i_channels,
417                                        p_fmt->audio.i_rate,
418                                        p_fmt->i_bitrate,
419                                        p_fmt->audio.i_bitspersample,
420                                        p_fmt->audio.i_blockalign);
421         if (def->eDir == OMX_DirInput) {
422             CHECK_ERROR(omx_error, "SetAudioParameters failed (%x : %s)",
423                         omx_error, ErrorToString(omx_error));
424         } else if (omx_error != OMX_ErrorNone) {
425             msg_Warn(p_dec, "SetAudioParameters failed (%x : %s) on output port",
426                      omx_error, ErrorToString(omx_error));
427             omx_error = OMX_ErrorNone;
428         }
429     }
430     if (!strcmp(p_dec->p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER") &&
431                 def->eDir == OMX_DirOutput)
432     {
433         /* When setting the output buffer size above, the decoder actually
434          * sets the buffer size to a lower value than what was chosen. If
435          * we try to allocate buffers of this size, it fails. Thus, forcibly
436          * use a larger buffer size. */
437         def->nBufferSize *= 2;
438     }
439
440  error:
441     return omx_error;
442 }
443
444 /*****************************************************************************
445  * GetPortDefinition: set vlc format based on the definition of the omx port
446  *****************************************************************************/
447 static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
448                                        es_format_t *p_fmt)
449 {
450     decoder_sys_t *p_sys = p_dec->p_sys;
451     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
452     OMX_ERRORTYPE omx_error;
453     OMX_CONFIG_RECTTYPE crop_rect;
454
455     omx_error = OMX_GetParameter(p_port->omx_handle,
456                                  OMX_IndexParamPortDefinition, def);
457     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
458                 omx_error, ErrorToString(omx_error));
459
460     switch(p_fmt->i_cat)
461     {
462     case VIDEO_ES:
463         p_fmt->video.i_width = def->format.video.nFrameWidth;
464         p_fmt->video.i_visible_width = def->format.video.nFrameWidth;
465         p_fmt->video.i_height = def->format.video.nFrameHeight;
466         p_fmt->video.i_visible_height = def->format.video.nFrameHeight;
467         p_fmt->video.i_frame_rate = p_dec->fmt_in.video.i_frame_rate;
468         p_fmt->video.i_frame_rate_base = p_dec->fmt_in.video.i_frame_rate_base;
469
470         OMX_INIT_STRUCTURE(crop_rect);
471         crop_rect.nPortIndex = def->nPortIndex;
472         omx_error = OMX_GetConfig(p_port->omx_handle, OMX_IndexConfigCommonOutputCrop, &crop_rect);
473         if (omx_error == OMX_ErrorNone)
474         {
475             if (!def->format.video.nSliceHeight)
476                 def->format.video.nSliceHeight = def->format.video.nFrameHeight;
477             if (!def->format.video.nStride)
478                 def->format.video.nStride = def->format.video.nFrameWidth;
479             p_fmt->video.i_width = crop_rect.nWidth;
480             p_fmt->video.i_visible_width = crop_rect.nWidth;
481             p_fmt->video.i_height = crop_rect.nHeight;
482             p_fmt->video.i_visible_height = crop_rect.nHeight;
483             if (def->format.video.eColorFormat == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
484                 def->format.video.nSliceHeight -= crop_rect.nTop/2;
485         }
486         else
487         {
488             /* Don't pass the error back to the caller, this isn't mandatory */
489             omx_error = OMX_ErrorNone;
490         }
491
492         /* Hack: Nexus One (stock firmware with binary OMX driver blob)
493          * claims to output 420Planar even though it in in practice is
494          * NV21. */
495         if(def->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar &&
496            !strncmp(p_sys->psz_component, "OMX.qcom.video.decoder",
497                     strlen("OMX.qcom.video.decoder")))
498             def->format.video.eColorFormat = OMX_QCOM_COLOR_FormatYVU420SemiPlanar;
499
500         if (IgnoreOmxDecoderPadding(p_sys->psz_component)) {
501             def->format.video.nSliceHeight = 0;
502             def->format.video.nStride = p_fmt->video.i_width;
503         }
504
505         if(!GetVlcVideoFormat( def->format.video.eCompressionFormat,
506                                &p_fmt->i_codec, 0 ) )
507         {
508             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
509                                      &p_fmt->i_codec, 0 ) )
510             {
511                 omx_error = OMX_ErrorNotImplemented;
512                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
513                             (int)def->format.video.eColorFormat );
514             }
515             GetVlcChromaSizes( p_fmt->i_codec,
516                                def->format.video.nFrameWidth,
517                                def->format.video.nFrameHeight,
518                                &p_port->i_frame_size, &p_port->i_frame_stride,
519                                &p_port->i_frame_stride_chroma_div );
520         }
521         if(p_port->i_frame_size > def->nBufferSize)
522             def->nBufferSize = p_port->i_frame_size;
523         p_port->i_frame_size = def->nBufferSize;
524 #if 0
525         if((int)p_port->i_frame_stride > def->format.video.nStride)
526             def->format.video.nStride = p_port->i_frame_stride;
527 #endif
528         p_port->i_frame_stride = def->format.video.nStride;
529         break;
530
531     case AUDIO_ES:
532         if( !OmxToVlcAudioFormat( def->format.audio.eEncoding,
533                                 &p_fmt->i_codec, 0 ) )
534         {
535             omx_error = OMX_ErrorNotImplemented;
536             CHECK_ERROR(omx_error, "OMX audio format %i not supported",
537                         (int)def->format.audio.eEncoding );
538         }
539
540         omx_error = GetAudioParameters(p_port->omx_handle,
541                                        &p_port->format_param, def->nPortIndex,
542                                        def->format.audio.eEncoding,
543                                        &p_fmt->audio.i_channels,
544                                        &p_fmt->audio.i_rate,
545                                        &p_fmt->i_bitrate,
546                                        &p_fmt->audio.i_bitspersample,
547                                        &p_fmt->audio.i_blockalign);
548         CHECK_ERROR(omx_error, "GetAudioParameters failed (%x : %s)",
549                     omx_error, ErrorToString(omx_error));
550
551         if(p_fmt->audio.i_channels < 9)
552         {
553             static const int pi_channels_maps[9] =
554             {
555                 0, AOUT_CHAN_CENTER, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
556                 AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
557                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
558                 | AOUT_CHAN_REARRIGHT,
559                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
560                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
561                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
562                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
563                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
564                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT
565                 | AOUT_CHAN_MIDDLERIGHT,
566                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
567                 | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
568                 | AOUT_CHAN_LFE
569             };
570             p_fmt->audio.i_physical_channels =
571                 p_fmt->audio.i_original_channels =
572                     pi_channels_maps[p_fmt->audio.i_channels];
573         }
574
575         date_Init( &p_dec->p_sys->end_date, p_fmt->audio.i_rate, 1 );
576
577         break;
578
579     default: return OMX_ErrorNotImplemented;
580     }
581
582  error:
583     return omx_error;
584 }
585
586 /*****************************************************************************
587  * DeinitialiseComponent: Deinitialise and unload an OMX component
588  *****************************************************************************/
589 static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
590                                            OMX_HANDLETYPE omx_handle)
591 {
592     decoder_sys_t *p_sys = p_dec->p_sys;
593     OMX_ERRORTYPE omx_error;
594     OMX_STATETYPE state;
595     unsigned int i, j;
596
597     if(!omx_handle) return OMX_ErrorNone;
598
599     omx_error = OMX_GetState(omx_handle, &state);
600     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
601
602     if(state == OMX_StateExecuting)
603     {
604         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
605                                      OMX_StateIdle, 0 );
606         CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
607         while (1) {
608             OMX_U32 cmd, state;
609             omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, &cmd, &state, 0);
610             CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
611             // The event queue can contain other OMX_EventCmdComplete items,
612             // such as for OMX_CommandFlush
613             if (cmd == OMX_CommandStateSet && state == OMX_StateIdle)
614                 break;
615         }
616     }
617
618     omx_error = OMX_GetState(omx_handle, &state);
619     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
620
621     if(state == OMX_StateIdle)
622     {
623         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
624                                      OMX_StateLoaded, 0 );
625         CHECK_ERROR(omx_error, "OMX_CommandStateSet Loaded failed (%x)", omx_error );
626
627         for(i = 0; i < p_sys->ports; i++)
628         {
629             OmxPort *p_port = &p_sys->p_ports[i];
630             OMX_BUFFERHEADERTYPE *p_buffer;
631
632             for(j = 0; j < p_port->i_buffers; j++)
633             {
634                 OMX_FIFO_GET(&p_port->fifo, p_buffer);
635                 if (p_buffer->nFlags & SENTINEL_FLAG) {
636                     free(p_buffer);
637                     j--;
638                     continue;
639                 }
640                 omx_error = OMX_FreeBuffer( omx_handle,
641                                             p_port->i_port_index, p_buffer );
642
643                 if(omx_error != OMX_ErrorNone) break;
644             }
645             CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
646                         omx_error, (int)p_port->i_port_index, j );
647             while (1) {
648                 OMX_FIFO_PEEK(&p_port->fifo, p_buffer);
649                 if (!p_buffer) break;
650
651                 OMX_FIFO_GET(&p_port->fifo, p_buffer);
652                 if (p_buffer->nFlags & SENTINEL_FLAG) {
653                     free(p_buffer);
654                     continue;
655                 }
656                 msg_Warn( p_dec, "Stray buffer left in fifo, %p", p_buffer );
657             }
658         }
659
660         omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
661         CHECK_ERROR(omx_error, "Wait for Loaded failed (%x)", omx_error );
662     }
663
664  error:
665     for(i = 0; i < p_sys->ports; i++)
666     {
667         OmxPort *p_port = &p_sys->p_ports[i];
668         free(p_port->pp_buffers);
669         p_port->pp_buffers = 0;
670     }
671     omx_error = pf_free_handle( omx_handle );
672     return omx_error;
673 }
674
675 /*****************************************************************************
676  * InitialiseComponent: Load and initialise an OMX component
677  *****************************************************************************/
678 static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
679     OMX_STRING psz_component, OMX_HANDLETYPE *p_handle)
680 {
681     static OMX_CALLBACKTYPE callbacks =
682         { OmxEventHandler, OmxEmptyBufferDone, OmxFillBufferDone };
683     decoder_sys_t *p_sys = p_dec->p_sys;
684     OMX_HANDLETYPE omx_handle;
685     OMX_ERRORTYPE omx_error;
686     unsigned int i;
687     OMX_U8 psz_role[OMX_MAX_STRINGNAME_SIZE];
688     OMX_PARAM_COMPONENTROLETYPE role;
689     OMX_PARAM_PORTDEFINITIONTYPE definition;
690     OMX_PORT_PARAM_TYPE param;
691
692     /* Load component */
693     omx_error = pf_get_handle( &omx_handle, psz_component, p_dec, &callbacks );
694     if(omx_error != OMX_ErrorNone)
695     {
696         msg_Warn( p_dec, "OMX_GetHandle(%s) failed (%x: %s)", psz_component,
697                   omx_error, ErrorToString(omx_error) );
698         return omx_error;
699     }
700     strncpy(p_sys->psz_component, psz_component, OMX_MAX_STRINGNAME_SIZE-1);
701
702     omx_error = OMX_ComponentRoleEnum(omx_handle, psz_role, 0);
703     if(omx_error == OMX_ErrorNone)
704         msg_Dbg(p_dec, "loaded component %s of role %s", psz_component, psz_role);
705     else
706         msg_Dbg(p_dec, "loaded component %s", psz_component);
707     PrintOmx(p_dec, omx_handle, OMX_ALL);
708
709     /* Set component role */
710     OMX_INIT_STRUCTURE(role);
711     strcpy((char*)role.cRole,
712            GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec : p_dec->fmt_in.i_codec,
713                       p_dec->fmt_in.i_cat, p_sys->b_enc));
714
715     omx_error = OMX_SetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
716                                  &role);
717     omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
718                                  &role);
719     if(omx_error == OMX_ErrorNone)
720         msg_Dbg(p_dec, "component standard role set to %s", role.cRole);
721
722     /* Find the input / output ports */
723     OMX_INIT_STRUCTURE(param);
724     OMX_INIT_STRUCTURE(definition);
725     omx_error = OMX_GetParameter(omx_handle, p_dec->fmt_in.i_cat == VIDEO_ES ?
726                                  OMX_IndexParamVideoInit : OMX_IndexParamAudioInit, &param);
727     if(omx_error != OMX_ErrorNone) {
728 #ifdef __ANDROID__
729         param.nPorts = 2;
730         param.nStartPortNumber = 0;
731 #else
732         param.nPorts = 0;
733 #endif
734     }
735
736     for(i = 0; i < param.nPorts; i++)
737     {
738         OmxPort *p_port;
739
740         /* Get port definition */
741         definition.nPortIndex = param.nStartPortNumber + i;
742         omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamPortDefinition,
743                                      &definition);
744         if(omx_error != OMX_ErrorNone) continue;
745
746         if(definition.eDir == OMX_DirInput) p_port = &p_sys->in;
747         else  p_port = &p_sys->out;
748
749         p_port->b_valid = true;
750         p_port->i_port_index = definition.nPortIndex;
751         p_port->definition = definition;
752         p_port->omx_handle = omx_handle;
753     }
754
755     if(!p_sys->in.b_valid || !p_sys->out.b_valid)
756     {
757         omx_error = OMX_ErrorInvalidComponent;
758         CHECK_ERROR(omx_error, "couldn't find an input and output port");
759     }
760
761     if(!strncmp(p_sys->psz_component, "OMX.SEC.", 8) &&
762        p_dec->fmt_in.i_cat == VIDEO_ES)
763     {
764         OMX_INDEXTYPE index;
765         omx_error = OMX_GetExtensionIndex(omx_handle, (OMX_STRING) "OMX.SEC.index.ThumbnailMode", &index);
766         if(omx_error == OMX_ErrorNone)
767         {
768             OMX_BOOL enable = OMX_TRUE;
769             omx_error = OMX_SetConfig(omx_handle, index, &enable);
770             CHECK_ERROR(omx_error, "Unable to set ThumbnailMode");
771         } else {
772             OMX_BOOL enable = OMX_TRUE;
773             /* Needed on Samsung Galaxy S II */
774             omx_error = OMX_SetConfig(omx_handle, OMX_IndexVendorSetYUV420pMode, &enable);
775             if (omx_error == OMX_ErrorNone)
776                 msg_Dbg(p_dec, "Set OMX_IndexVendorSetYUV420pMode successfully");
777             else
778                 msg_Dbg(p_dec, "Unable to set OMX_IndexVendorSetYUV420pMode: %x", omx_error);
779         }
780     }
781
782     /* Set port definitions */
783     for(i = 0; i < p_sys->ports; i++)
784     {
785         omx_error = SetPortDefinition(p_dec, &p_sys->p_ports[i],
786                                       p_sys->p_ports[i].p_fmt);
787         if(omx_error != OMX_ErrorNone) goto error;
788     }
789
790     /* Allocate our array for the omx buffers and enable ports */
791     for(i = 0; i < p_sys->ports; i++)
792     {
793         OmxPort *p_port = &p_sys->p_ports[i];
794
795         p_port->pp_buffers =
796             malloc(p_port->definition.nBufferCountActual *
797                    sizeof(OMX_BUFFERHEADERTYPE*));
798         if(!p_port->pp_buffers)
799         {
800           omx_error = OMX_ErrorInsufficientResources;
801           CHECK_ERROR(omx_error, "memory allocation failed");
802         }
803         p_port->i_buffers = p_port->definition.nBufferCountActual;
804
805         /* Enable port */
806         if(!p_port->definition.bEnabled)
807         {
808             omx_error = OMX_SendCommand( omx_handle, OMX_CommandPortEnable,
809                                          p_port->i_port_index, NULL);
810             CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
811                         (int)p_port->i_port_index, omx_error );
812             omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
813             CHECK_ERROR(omx_error, "Wait for PortEnable on %i failed (%x)",
814                         (int)p_port->i_port_index, omx_error );
815         }
816     }
817
818     *p_handle = omx_handle;
819     return OMX_ErrorNone;
820
821  error:
822     DeinitialiseComponent(p_dec, omx_handle);
823     *p_handle = 0;
824     return omx_error;
825 }
826
827 /*****************************************************************************
828  * OpenDecoder: Create the decoder instance
829  *****************************************************************************/
830 static int OpenDecoder( vlc_object_t *p_this )
831 {
832     decoder_t *p_dec = (decoder_t*)p_this;
833     int status;
834
835     if( 0 || !GetOmxRole(p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat, false) )
836         return VLC_EGENERIC;
837
838     status = OpenGeneric( p_this, false );
839     if(status != VLC_SUCCESS) return status;
840
841     p_dec->pf_decode_video = DecodeVideo;
842     p_dec->pf_decode_audio = DecodeAudio;
843
844     return VLC_SUCCESS;
845 }
846
847 /*****************************************************************************
848  * OpenEncoder: Create the encoder instance
849  *****************************************************************************/
850 static int OpenEncoder( vlc_object_t *p_this )
851 {
852     encoder_t *p_enc = (encoder_t*)p_this;
853     int status;
854
855     if( !GetOmxRole(p_enc->fmt_out.i_codec, p_enc->fmt_in.i_cat, true) )
856         return VLC_EGENERIC;
857
858     status = OpenGeneric( p_this, true );
859     if(status != VLC_SUCCESS) return status;
860
861     p_enc->pf_encode_video = EncodeVideo;
862
863     return VLC_SUCCESS;
864 }
865
866 /*****************************************************************************
867  * OpenGeneric: Create the generic decoder/encoder instance
868  *****************************************************************************/
869 static int OpenGeneric( vlc_object_t *p_this, bool b_encode )
870 {
871     decoder_t *p_dec = (decoder_t*)p_this;
872     decoder_sys_t *p_sys;
873     OMX_ERRORTYPE omx_error;
874     OMX_BUFFERHEADERTYPE *p_header;
875     unsigned int i, j;
876
877     vlc_mutex_lock( &omx_core_mutex );
878     if( omx_refcount > 0 )
879         goto loaded;
880
881     /* Load the OMX core */
882     for( i = 0; ppsz_dll_list[i]; i++ )
883     {
884         dll_handle = dll_open( ppsz_dll_list[i] );
885         if( dll_handle ) break;
886     }
887     if( !dll_handle )
888     {
889         vlc_mutex_unlock( &omx_core_mutex );
890         return VLC_EGENERIC;
891     }
892
893     pf_init = dlsym( dll_handle, "OMX_Init" );
894     pf_deinit = dlsym( dll_handle, "OMX_Deinit" );
895     pf_get_handle = dlsym( dll_handle, "OMX_GetHandle" );
896     pf_free_handle = dlsym( dll_handle, "OMX_FreeHandle" );
897     pf_component_enum = dlsym( dll_handle, "OMX_ComponentNameEnum" );
898     pf_get_roles_of_component = dlsym( dll_handle, "OMX_GetRolesOfComponent" );
899     if( !pf_init || !pf_deinit || !pf_get_handle || !pf_free_handle ||
900         !pf_component_enum || !pf_get_roles_of_component )
901     {
902         msg_Warn( p_this, "cannot find OMX_* symbols in `%s' (%s)",
903                   ppsz_dll_list[i], dlerror() );
904         dll_close(dll_handle);
905         vlc_mutex_unlock( &omx_core_mutex );
906         return VLC_EGENERIC;
907     }
908
909 loaded:
910     /* Allocate the memory needed to store the decoder's structure */
911     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(*p_sys)) ) == NULL )
912     {
913         if( omx_refcount == 0 )
914             dll_close(dll_handle);
915         vlc_mutex_unlock( &omx_core_mutex );
916         return VLC_ENOMEM;
917     }
918
919     /* Initialise the thread properties */
920     if(!b_encode)
921     {
922         p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
923         p_dec->fmt_out.video = p_dec->fmt_in.video;
924         p_dec->fmt_out.audio = p_dec->fmt_in.audio;
925         p_dec->fmt_out.i_codec = 0;
926     }
927     p_sys->b_enc = b_encode;
928     p_sys->pp_last_event = &p_sys->p_events;
929     vlc_mutex_init (&p_sys->mutex);
930     vlc_cond_init (&p_sys->cond);
931     vlc_mutex_init (&p_sys->in.fifo.lock);
932     vlc_cond_init (&p_sys->in.fifo.wait);
933     p_sys->in.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pOutputPortPrivate) / sizeof(void *);
934     p_sys->in.fifo.pp_last = &p_sys->in.fifo.p_first;
935     p_sys->in.b_direct = false;
936     p_sys->in.b_flushed = true;
937     p_sys->in.p_fmt = &p_dec->fmt_in;
938     vlc_mutex_init (&p_sys->out.fifo.lock);
939     vlc_cond_init (&p_sys->out.fifo.wait);
940     p_sys->out.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pInputPortPrivate) / sizeof(void *);
941     p_sys->out.fifo.pp_last = &p_sys->out.fifo.p_first;
942     p_sys->out.b_direct = false;
943     p_sys->out.b_flushed = true;
944     p_sys->out.p_fmt = &p_dec->fmt_out;
945     p_sys->ports = 2;
946     p_sys->p_ports = &p_sys->in;
947     p_sys->b_use_pts = 0;
948
949     msg_Dbg(p_dec, "fmt in:%4.4s, out: %4.4s", (char *)&p_dec->fmt_in.i_codec,
950             (char *)&p_dec->fmt_out.i_codec);
951
952     /* Initialise the OMX core */
953     omx_error = omx_refcount > 0 ? OMX_ErrorNone : pf_init();
954     omx_refcount++;
955     if(omx_error != OMX_ErrorNone)
956     {
957         msg_Warn( p_this, "OMX_Init failed (%x: %s)", omx_error,
958                   ErrorToString(omx_error) );
959         vlc_mutex_unlock( &omx_core_mutex );
960         CloseGeneric(p_this);
961         return VLC_EGENERIC;
962     }
963     p_sys->b_init = true;
964     vlc_mutex_unlock( &omx_core_mutex );
965
966     /* Enumerate components and build a list of the one we want to try */
967     if( !CreateComponentsList(p_dec,
968              GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec :
969                         p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat,
970                         p_sys->b_enc)) )
971     {
972         msg_Warn( p_this, "couldn't find an omx component for codec %4.4s",
973                   (char *)&p_dec->fmt_in.i_codec );
974         CloseGeneric(p_this);
975         return VLC_EGENERIC;
976     }
977
978     /* Try to load and initialise a component */
979     omx_error = OMX_ErrorUndefined;
980     for(i = 0; i < p_sys->components; i++)
981     {
982 #ifdef __ANDROID__
983         /* ignore OpenCore software codecs */
984         if (!strncmp(p_sys->ppsz_components[i], "OMX.PV.", 7))
985             continue;
986         /* The same sw codecs, renamed in ICS (perhaps also in honeycomb) */
987         if (!strncmp(p_sys->ppsz_components[i], "OMX.google.", 11))
988             continue;
989         /* This one has been seen on HTC One V - it behaves like it works,
990          * but FillBufferDone returns buffers filled with 0 bytes. The One V
991          * has got a working OMX.qcom.video.decoder.avc instead though. */
992         if (!strncmp(p_sys->ppsz_components[i], "OMX.ARICENT.", 12))
993             continue;
994         /* Codecs with DRM, that don't output plain YUV data but only
995          * support direct rendering where the output can't be intercepted. */
996         if (strstr(p_sys->ppsz_components[i], ".secure"))
997             continue;
998         /* Use VC1 decoder for WMV3 for now */
999         if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.WMV.Decoder"))
1000             continue;
1001         /* This decoder does work, but has an insane latency (leading to errors
1002          * about "main audio output playback way too late" and dropped frames).
1003          * At least Samsung Galaxy S III (where this decoder is present) has
1004          * got another one, OMX.SEC.mp3.dec, that works well and has a
1005          * sensible latency. (Also, even if that one isn't found, in general,
1006          * using SW codecs is usually more than fast enough for MP3.) */
1007         if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.MP3.Decoder"))
1008             continue;
1009         /* This codec should be able to handle both VC1 and WMV3, but
1010          * for VC1 it doesn't output any buffers at all (in the way we use
1011          * it) and for WMV3 it outputs plain black buffers. Thus ignore
1012          * it until we can make it work properly. */
1013         if (!strcmp(p_sys->ppsz_components[i], "OMX.Nvidia.vc1.decode"))
1014             continue;
1015 #endif
1016         omx_error = InitialiseComponent(p_dec, p_sys->ppsz_components[i],
1017                                         &p_sys->omx_handle);
1018         if(omx_error == OMX_ErrorNone) break;
1019     }
1020     CHECK_ERROR(omx_error, "no component could be initialised" );
1021
1022     /* Move component to Idle then Executing state */
1023     OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0 );
1024     CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
1025
1026     /* Allocate omx buffers */
1027     for(i = 0; i < p_sys->ports; i++)
1028     {
1029         OmxPort *p_port = &p_sys->p_ports[i];
1030
1031         for(j = 0; j < p_port->i_buffers; j++)
1032         {
1033 #if 0
1034 #define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
1035             char *p_buf = malloc(p_port->definition.nBufferSize +
1036                                  p_port->definition.nBufferAlignment);
1037             p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
1038 #endif
1039
1040             if(p_port->b_direct)
1041                 omx_error =
1042                     OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
1043                                    p_port->i_port_index, 0,
1044                                    p_port->definition.nBufferSize, (void*)1);
1045             else
1046                 omx_error =
1047                     OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
1048                                         p_port->i_port_index, 0,
1049                                         p_port->definition.nBufferSize);
1050
1051             if(omx_error != OMX_ErrorNone) break;
1052             OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[j]);
1053         }
1054         p_port->i_buffers = j;
1055         CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
1056                     omx_error, (int)p_port->i_port_index, j );
1057     }
1058
1059     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1060     CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
1061
1062     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet,
1063                                  OMX_StateExecuting, 0);
1064     CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x)", omx_error );
1065     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1066     CHECK_ERROR(omx_error, "Wait for Executing failed (%x)", omx_error );
1067
1068     /* Send codec configuration data */
1069     if( p_dec->fmt_in.i_extra )
1070     {
1071         OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1072         p_header->nFilledLen = p_dec->fmt_in.i_extra;
1073
1074         /* Convert H.264 NAL format to annex b */
1075         if( p_sys->i_nal_size_length && !p_sys->in.b_direct )
1076         {
1077             p_header->nFilledLen = 0;
1078             convert_sps_pps( p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
1079                              p_header->pBuffer, p_header->nAllocLen,
1080                              (uint32_t*) &p_header->nFilledLen, NULL );
1081         }
1082         else if(p_sys->in.b_direct)
1083         {
1084             p_header->pOutputPortPrivate = p_header->pBuffer;
1085             p_header->pBuffer = p_dec->fmt_in.p_extra;
1086         }
1087         else if (p_dec->fmt_in.i_codec == VLC_CODEC_WMV3 &&
1088                  p_dec->fmt_in.i_extra >= 4 &&
1089                  p_header->nAllocLen >= 36)
1090         {
1091             int profile;
1092             // According to OMX IL 1.2.0 spec (4.3.33.2), the codec config
1093             // data for VC-1 Main/Simple (aka WMV3) is according to table 265
1094             // in the VC-1 spec. Most of the fields are just set with placeholders
1095             // (like framerate, hrd_buffer/rate).
1096             static const uint8_t wmv3seq[] = {
1097                 0xff, 0xff, 0xff, 0xc5, // numframes=ffffff, marker byte
1098                 0x04, 0x00, 0x00, 0x00, // marker byte
1099                 0x00, 0x00, 0x00, 0x00, // struct C, almost equal to p_extra
1100                 0x00, 0x00, 0x00, 0x00, // struct A, vert size
1101                 0x00, 0x00, 0x00, 0x00, // struct A, horiz size
1102                 0x0c, 0x00, 0x00, 0x00, // marker byte
1103                 0xff, 0xff, 0x00, 0x80, // struct B, level=4, cbr=0, hrd_buffer=ffff
1104                 0xff, 0xff, 0x00, 0x00, // struct B, hrd_rate=ffff
1105                 0xff, 0xff, 0xff, 0xff, // struct B, framerate=ffffffff
1106             };
1107             p_header->nFilledLen = sizeof(wmv3seq);
1108             memcpy(p_header->pBuffer, wmv3seq, p_header->nFilledLen);
1109             // Struct C - almost equal to the extradata
1110             memcpy(&p_header->pBuffer[8], p_dec->fmt_in.p_extra, 4);
1111             // Expand profile from the highest 2 bits to the highest 4 bits
1112             profile = p_header->pBuffer[8] >> 6;
1113             p_header->pBuffer[8] = (p_header->pBuffer[8] & 0x0f) | (profile << 4);
1114             // Fill in the height/width for struct A
1115             SetDWLE(&p_header->pBuffer[12], p_dec->fmt_in.video.i_height);
1116             SetDWLE(&p_header->pBuffer[16], p_dec->fmt_in.video.i_width);
1117         }
1118         else
1119         {
1120             if(p_header->nFilledLen > p_header->nAllocLen)
1121             {
1122                 msg_Dbg(p_dec, "buffer too small (%i,%i)", (int)p_header->nFilledLen,
1123                         (int)p_header->nAllocLen);
1124                 p_header->nFilledLen = p_header->nAllocLen;
1125             }
1126             memcpy(p_header->pBuffer, p_dec->fmt_in.p_extra, p_header->nFilledLen);
1127         }
1128
1129         p_header->nOffset = 0;
1130         p_header->nFlags = OMX_BUFFERFLAG_CODECCONFIG | OMX_BUFFERFLAG_ENDOFFRAME;
1131         msg_Dbg(p_dec, "sending codec config data %p, %p, %i", p_header,
1132                 p_header->pBuffer, (int)p_header->nFilledLen);
1133         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1134     }
1135
1136     /* Get back output port definition */
1137     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1138     if(omx_error != OMX_ErrorNone) goto error;
1139
1140     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1141     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1142
1143     if(p_sys->b_error) goto error;
1144
1145     p_dec->b_need_packetized = true;
1146     if (!strcmp(p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER"))
1147         p_sys->b_use_pts = 1;
1148
1149     if (!strcmp(p_sys->psz_component, "OMX.STM.Video.Decoder"))
1150         p_sys->b_use_pts = 1;
1151
1152     if (p_sys->b_use_pts)
1153         msg_Dbg( p_dec, "using pts timestamp mode for %s", p_sys->psz_component);
1154
1155     return VLC_SUCCESS;
1156
1157  error:
1158     CloseGeneric(p_this);
1159     return VLC_EGENERIC;
1160 }
1161
1162 /*****************************************************************************
1163  * PortReconfigure
1164  *****************************************************************************/
1165 static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
1166 {
1167     decoder_sys_t *p_sys = p_dec->p_sys;
1168     OMX_PARAM_PORTDEFINITIONTYPE definition;
1169     OMX_BUFFERHEADERTYPE *p_buffer;
1170     OMX_ERRORTYPE omx_error;
1171     unsigned int i;
1172
1173     /* Sanity checking */
1174     OMX_INIT_STRUCTURE(definition);
1175     definition.nPortIndex = p_port->i_port_index;
1176     omx_error = OMX_GetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1177                                  &definition);
1178     if(omx_error != OMX_ErrorNone || (p_dec->fmt_in.i_cat == VIDEO_ES &&
1179        (!definition.format.video.nFrameWidth ||
1180        !definition.format.video.nFrameHeight)) )
1181         return OMX_ErrorUndefined;
1182
1183     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortDisable,
1184                                  p_port->i_port_index, NULL);
1185     CHECK_ERROR(omx_error, "OMX_CommandPortDisable on %i failed (%x)",
1186                 (int)p_port->i_port_index, omx_error );
1187
1188     for(i = 0; i < p_port->i_buffers; i++)
1189     {
1190         OMX_FIFO_GET(&p_port->fifo, p_buffer);
1191         if (p_buffer->nFlags & SENTINEL_FLAG) {
1192             free(p_buffer);
1193             i--;
1194             continue;
1195         }
1196         omx_error = OMX_FreeBuffer( p_sys->omx_handle,
1197                                     p_port->i_port_index, p_buffer );
1198
1199         if(omx_error != OMX_ErrorNone) break;
1200     }
1201     CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
1202                 omx_error, (int)p_port->i_port_index, i );
1203
1204     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1205     CHECK_ERROR(omx_error, "Wait for PortDisable failed (%x)", omx_error );
1206
1207     /* Get the new port definition */
1208     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1209     if(omx_error != OMX_ErrorNone) goto error;
1210
1211     if( p_dec->fmt_in.i_cat != AUDIO_ES )
1212     {
1213         /* Don't explicitly set the new parameters that we got with
1214          * OMX_GetParameter above when using audio codecs.
1215          * That struct hasn't been changed since, so there should be
1216          * no need to set it here, unless some codec expects the
1217          * SetParameter call as a trigger event for some part of
1218          * the reconfiguration.
1219          * This fixes using audio decoders on Samsung Galaxy S II,
1220          *
1221          * Only skipping this for audio codecs, to minimize the
1222          * change for current working configurations for video.
1223          */
1224         omx_error = OMX_SetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1225                                      &definition);
1226         CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
1227                     omx_error, ErrorToString(omx_error));
1228     }
1229
1230     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortEnable,
1231                                  p_port->i_port_index, NULL);
1232     CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
1233                 (int)p_port->i_port_index, omx_error );
1234
1235     if (p_port->definition.nBufferCountActual > p_port->i_buffers) {
1236         free(p_port->pp_buffers);
1237         p_port->pp_buffers = malloc(p_port->definition.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE*));
1238         if(!p_port->pp_buffers)
1239         {
1240             omx_error = OMX_ErrorInsufficientResources;
1241             CHECK_ERROR(omx_error, "memory allocation failed");
1242         }
1243     }
1244     p_port->i_buffers = p_port->definition.nBufferCountActual;
1245     for(i = 0; i < p_port->i_buffers; i++)
1246     {
1247         if(p_port->b_direct)
1248             omx_error =
1249                 OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1250                                p_port->i_port_index, 0,
1251                                p_port->definition.nBufferSize, (void*)1);
1252         else
1253             omx_error =
1254                 OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1255                                     p_port->i_port_index, 0,
1256                                     p_port->definition.nBufferSize);
1257
1258         if(omx_error != OMX_ErrorNone) break;
1259         OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
1260     }
1261     p_port->i_buffers = i;
1262     CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
1263                 omx_error, (int)p_port->i_port_index, i );
1264
1265     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1266     CHECK_ERROR(omx_error, "Wait for PortEnable failed (%x)", omx_error );
1267
1268     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1269     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1270
1271  error:
1272     return omx_error;
1273 }
1274
1275 /*****************************************************************************
1276  * DecodeVideo: Called to decode one frame
1277  *****************************************************************************/
1278 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
1279 {
1280     decoder_sys_t *p_sys = p_dec->p_sys;
1281     picture_t *p_pic = NULL, *p_next_pic;
1282     OMX_ERRORTYPE omx_error;
1283     unsigned int i;
1284
1285     OMX_BUFFERHEADERTYPE *p_header;
1286     block_t *p_block;
1287
1288     if( !pp_block || !*pp_block )
1289         return NULL;
1290
1291     p_block = *pp_block;
1292
1293     /* Check for errors from codec */
1294     if(p_sys->b_error)
1295     {
1296         msg_Dbg(p_dec, "error during decoding");
1297         block_Release( p_block );
1298         return 0;
1299     }
1300
1301     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1302     {
1303         block_Release( p_block );
1304         if(!p_sys->in.b_flushed)
1305         {
1306             msg_Dbg(p_dec, "flushing");
1307             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1308                              p_sys->in.definition.nPortIndex, 0 );
1309         }
1310         p_sys->in.b_flushed = true;
1311         return NULL;
1312     }
1313
1314     /* Take care of decoded frames first */
1315     while(!p_pic)
1316     {
1317         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1318         if(!p_header) break; /* No frame available */
1319
1320         if(p_sys->out.b_update_def)
1321         {
1322             omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1323             p_sys->out.b_update_def = 0;
1324         }
1325
1326         if(p_header->nFilledLen)
1327         {
1328             p_pic = p_header->pAppPrivate;
1329             if(!p_pic)
1330             {
1331                 /* We're not in direct rendering mode.
1332                  * Get a new picture and copy the content */
1333                 p_pic = decoder_NewPicture( p_dec );
1334
1335                 if (p_pic)
1336                     CopyOmxPicture(p_sys->out.definition.format.video.eColorFormat,
1337                                    p_pic, p_sys->out.definition.format.video.nSliceHeight,
1338                                    p_sys->out.i_frame_stride,
1339                                    p_header->pBuffer + p_header->nOffset,
1340                                    p_sys->out.i_frame_stride_chroma_div);
1341             }
1342
1343             if (p_pic)
1344                 p_pic->date = FromOmxTicks(p_header->nTimeStamp);
1345             p_header->nFilledLen = 0;
1346             p_header->pAppPrivate = 0;
1347         }
1348
1349         /* Get a new picture */
1350         if(p_sys->out.b_direct && !p_header->pAppPrivate)
1351         {
1352             p_next_pic = decoder_NewPicture( p_dec );
1353             if(!p_next_pic) break;
1354
1355             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1356             p_header->pAppPrivate = p_next_pic;
1357             p_header->pInputPortPrivate = p_header->pBuffer;
1358             p_header->pBuffer = p_next_pic->p[0].p_pixels;
1359         }
1360         else
1361         {
1362             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1363         }
1364
1365 #ifdef OMXIL_EXTRA_DEBUG
1366         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1367 #endif
1368         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1369     }
1370
1371     /* Send the input buffer to the component */
1372     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1373
1374     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1375         free(p_header);
1376         goto reconfig;
1377     }
1378
1379     if(p_header)
1380     {
1381         p_header->nFilledLen = p_block->i_buffer;
1382         p_header->nOffset = 0;
1383         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1384         if (p_sys->b_use_pts && p_block->i_pts)
1385             p_header->nTimeStamp = ToOmxTicks(p_block->i_pts);
1386         else
1387             p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1388
1389         /* In direct mode we pass the input pointer as is.
1390          * Otherwise we memcopy the data */
1391         if(p_sys->in.b_direct)
1392         {
1393             p_header->pOutputPortPrivate = p_header->pBuffer;
1394             p_header->pBuffer = p_block->p_buffer;
1395             p_header->pAppPrivate = p_block;
1396         }
1397         else
1398         {
1399             if(p_header->nFilledLen > p_header->nAllocLen)
1400             {
1401                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1402                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1403                 p_header->nFilledLen = p_header->nAllocLen;
1404             }
1405             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1406             block_Release(p_block);
1407         }
1408
1409         /* Convert H.264 NAL format to annex b. Doesn't do anything if
1410          * i_nal_size_length == 0, which is the case for codecs other
1411          * than H.264 */
1412         convert_h264_to_annexb( p_header->pBuffer, p_header->nFilledLen,
1413                                 p_sys->i_nal_size_length );
1414 #ifdef OMXIL_EXTRA_DEBUG
1415         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1416                  (int)p_header->nFilledLen );
1417 #endif
1418         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1419         p_sys->in.b_flushed = false;
1420         *pp_block = NULL; /* Avoid being fed the same packet again */
1421     }
1422
1423 reconfig:
1424     /* Handle the PortSettingsChanged events */
1425     for(i = 0; i < p_sys->ports; i++)
1426     {
1427         OmxPort *p_port = &p_sys->p_ports[i];
1428         if(p_port->b_reconfigure)
1429         {
1430             omx_error = PortReconfigure(p_dec, p_port);
1431             p_port->b_reconfigure = 0;
1432         }
1433         if(p_port->b_update_def)
1434         {
1435             omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1436             p_port->b_update_def = 0;
1437         }
1438     }
1439
1440     return p_pic;
1441 }
1442
1443 /*****************************************************************************
1444  * DecodeAudio: Called to decode one frame
1445  *****************************************************************************/
1446 block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1447 {
1448     decoder_sys_t *p_sys = p_dec->p_sys;
1449     block_t *p_buffer = NULL;
1450     OMX_BUFFERHEADERTYPE *p_header;
1451     OMX_ERRORTYPE omx_error;
1452     block_t *p_block;
1453     unsigned int i;
1454
1455     if( !pp_block || !*pp_block ) return NULL;
1456
1457     p_block = *pp_block;
1458
1459     /* Check for errors from codec */
1460     if(p_sys->b_error)
1461     {
1462         msg_Dbg(p_dec, "error during decoding");
1463         block_Release( p_block );
1464         return 0;
1465     }
1466
1467     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1468     {
1469         block_Release( p_block );
1470         date_Set( &p_sys->end_date, 0 );
1471         if(!p_sys->in.b_flushed)
1472         {
1473             msg_Dbg(p_dec, "flushing");
1474             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1475                              p_sys->in.definition.nPortIndex, 0 );
1476         }
1477         p_sys->in.b_flushed = true;
1478         return NULL;
1479     }
1480
1481     if( !date_Get( &p_sys->end_date ) )
1482     {
1483         if( !p_block->i_pts )
1484         {
1485             /* We've just started the stream, wait for the first PTS. */
1486             block_Release( p_block );
1487             return NULL;
1488         }
1489         date_Set( &p_sys->end_date, p_block->i_pts );
1490     }
1491
1492     /* Take care of decoded frames first */
1493     while(!p_buffer)
1494     {
1495         unsigned int i_samples = 0;
1496
1497         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1498         if(!p_header) break; /* No frame available */
1499
1500         if (p_sys->out.p_fmt->audio.i_channels)
1501             i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1502         if(i_samples)
1503         {
1504             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1505             if( !p_buffer ) break; /* No audio buffer available */
1506
1507             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1508             p_header->nFilledLen = 0;
1509
1510             int64_t timestamp = FromOmxTicks(p_header->nTimeStamp);
1511             if( timestamp != 0 &&
1512                 timestamp != date_Get( &p_sys->end_date ) )
1513                 date_Set( &p_sys->end_date, timestamp );
1514
1515             p_buffer->i_pts = date_Get( &p_sys->end_date );
1516             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1517                 p_buffer->i_pts;
1518         }
1519
1520 #ifdef OMXIL_EXTRA_DEBUG
1521         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1522 #endif
1523         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1524         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1525     }
1526
1527
1528     /* Send the input buffer to the component */
1529     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1530
1531     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1532         free(p_header);
1533         goto reconfig;
1534     }
1535
1536     if(p_header)
1537     {
1538         p_header->nFilledLen = p_block->i_buffer;
1539         p_header->nOffset = 0;
1540         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1541         p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1542
1543         /* In direct mode we pass the input pointer as is.
1544          * Otherwise we memcopy the data */
1545         if(p_sys->in.b_direct)
1546         {
1547             p_header->pOutputPortPrivate = p_header->pBuffer;
1548             p_header->pBuffer = p_block->p_buffer;
1549             p_header->pAppPrivate = p_block;
1550         }
1551         else
1552         {
1553             if(p_header->nFilledLen > p_header->nAllocLen)
1554             {
1555                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1556                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1557                 p_header->nFilledLen = p_header->nAllocLen;
1558             }
1559             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1560             block_Release(p_block);
1561         }
1562
1563 #ifdef OMXIL_EXTRA_DEBUG
1564         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1565                  (int)p_header->nFilledLen );
1566 #endif
1567         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1568         p_sys->in.b_flushed = false;
1569         *pp_block = NULL; /* Avoid being fed the same packet again */
1570     }
1571
1572 reconfig:
1573     /* Handle the PortSettingsChanged events */
1574     for(i = 0; i < p_sys->ports; i++)
1575     {
1576         OmxPort *p_port = &p_sys->p_ports[i];
1577         if(!p_port->b_reconfigure) continue;
1578         p_port->b_reconfigure = 0;
1579         omx_error = PortReconfigure(p_dec, p_port);
1580     }
1581
1582     return p_buffer;
1583 }
1584
1585 /*****************************************************************************
1586  * EncodeVideo: Called to encode one frame
1587  *****************************************************************************/
1588 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1589 {
1590     decoder_t *p_dec = ( decoder_t *)p_enc;
1591     decoder_sys_t *p_sys = p_dec->p_sys;
1592     OMX_ERRORTYPE omx_error;
1593     unsigned int i;
1594
1595     OMX_BUFFERHEADERTYPE *p_header;
1596     block_t *p_block = 0;
1597
1598     if( !p_pic ) return NULL;
1599
1600     /* Check for errors from codec */
1601     if(p_sys->b_error)
1602     {
1603         msg_Dbg(p_dec, "error during encoding");
1604         return NULL;
1605     }
1606
1607     /* Send the input buffer to the component */
1608     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1609     if(p_header)
1610     {
1611         /* In direct mode we pass the input pointer as is.
1612          * Otherwise we memcopy the data */
1613         if(p_sys->in.b_direct)
1614         {
1615             p_header->pOutputPortPrivate = p_header->pBuffer;
1616             p_header->pBuffer = p_pic->p[0].p_pixels;
1617         }
1618         else
1619         {
1620             CopyVlcPicture(p_dec, p_header, p_pic);
1621         }
1622
1623         p_header->nFilledLen = p_sys->in.i_frame_size;
1624         p_header->nOffset = 0;
1625         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1626         p_header->nTimeStamp = ToOmxTicks(p_pic->date);
1627 #ifdef OMXIL_EXTRA_DEBUG
1628         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1629                  (int)p_header->nFilledLen );
1630 #endif
1631         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1632         p_sys->in.b_flushed = false;
1633     }
1634
1635     /* Handle the PortSettingsChanged events */
1636     for(i = 0; i < p_sys->ports; i++)
1637     {
1638         OmxPort *p_port = &p_sys->p_ports[i];
1639         if(!p_port->b_reconfigure) continue;
1640         p_port->b_reconfigure = 0;
1641         omx_error = PortReconfigure(p_dec, p_port);
1642     }
1643
1644     /* Wait for the decoded frame */
1645     while(!p_block)
1646     {
1647         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1648
1649         if(p_header->nFilledLen)
1650         {
1651             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1652             {
1653                 /* TODO: need to store codec config */
1654                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1655             }
1656
1657             p_block = p_header->pAppPrivate;
1658             if(!p_block)
1659             {
1660                 /* We're not in direct rendering mode.
1661                  * Get a new block and copy the content */
1662                 p_block = block_Alloc( p_header->nFilledLen );
1663                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1664             }
1665
1666             p_block->i_buffer = p_header->nFilledLen;
1667             p_block->i_pts = p_block->i_dts = FromOmxTicks(p_header->nTimeStamp);
1668             p_header->nFilledLen = 0;
1669             p_header->pAppPrivate = 0;
1670         }
1671
1672 #ifdef OMXIL_EXTRA_DEBUG
1673         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1674 #endif
1675         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1676     }
1677
1678     msg_Dbg(p_dec, "done");
1679     return p_block;
1680 }
1681
1682 /*****************************************************************************
1683  * CloseGeneric: omxil decoder destruction
1684  *****************************************************************************/
1685 static void CloseGeneric( vlc_object_t *p_this )
1686 {
1687     decoder_t *p_dec = (decoder_t *)p_this;
1688     decoder_sys_t *p_sys = p_dec->p_sys;
1689
1690     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1691     vlc_mutex_lock( &omx_core_mutex );
1692     omx_refcount--;
1693     if( omx_refcount == 0 )
1694     {
1695         if( p_sys->b_init ) pf_deinit();
1696         dll_close( dll_handle );
1697     }
1698     vlc_mutex_unlock( &omx_core_mutex );
1699
1700     vlc_mutex_destroy (&p_sys->mutex);
1701     vlc_cond_destroy (&p_sys->cond);
1702     vlc_mutex_destroy (&p_sys->in.fifo.lock);
1703     vlc_cond_destroy (&p_sys->in.fifo.wait);
1704     vlc_mutex_destroy (&p_sys->out.fifo.lock);
1705     vlc_cond_destroy (&p_sys->out.fifo.wait);
1706
1707     free( p_sys );
1708 }
1709
1710 /*****************************************************************************
1711  * OmxEventHandler: 
1712  *****************************************************************************/
1713 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1714     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1715     OMX_U32 data_2, OMX_PTR event_data )
1716 {
1717     decoder_t *p_dec = (decoder_t *)app_data;
1718     decoder_sys_t *p_sys = p_dec->p_sys;
1719     unsigned int i;
1720     (void)omx_handle;
1721
1722     switch (event)
1723     {
1724     case OMX_EventCmdComplete:
1725         switch ((OMX_STATETYPE)data_1)
1726         {
1727         case OMX_CommandStateSet:
1728             msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %s)", EventToString(event),
1729                      CommandToString(data_1), StateToString(data_2) );
1730             break;
1731
1732         default:
1733             msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u)", EventToString(event),
1734                      CommandToString(data_1), (unsigned int)data_2 );
1735             break;
1736         }
1737         break;
1738
1739     case OMX_EventError:
1740         msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u, %s)", EventToString(event),
1741                  ErrorToString((OMX_ERRORTYPE)data_1), (unsigned int)data_2,
1742                  (const char *)event_data);
1743         //p_sys->b_error = true;
1744         break;
1745
1746     case OMX_EventPortSettingsChanged:
1747         msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
1748                  (unsigned int)data_1, (unsigned int)data_2 );
1749         if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition )
1750         {
1751             OMX_BUFFERHEADERTYPE *sentinel;
1752             for(i = 0; i < p_sys->ports; i++)
1753                 if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1754                     p_sys->p_ports[i].b_reconfigure = true;
1755             sentinel = calloc(1, sizeof(*sentinel));
1756             if (sentinel) {
1757                 sentinel->nFlags = SENTINEL_FLAG;
1758                 OMX_FIFO_PUT(&p_sys->in.fifo, sentinel);
1759             }
1760         }
1761         else if( data_2 == OMX_IndexConfigCommonOutputCrop )
1762         {
1763             for(i = 0; i < p_sys->ports; i++)
1764                 if(p_sys->p_ports[i].definition.nPortIndex == data_1)
1765                     p_sys->p_ports[i].b_update_def = true;
1766         }
1767         else
1768         {
1769             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
1770         }
1771         break;
1772
1773     default:
1774         msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
1775                  (unsigned int)data_1, (unsigned int)data_2 );
1776         break;
1777     }
1778
1779     PostOmxEvent(p_dec, event, data_1, data_2, event_data);
1780     return OMX_ErrorNone;
1781 }
1782
1783 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1784     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1785 {
1786     decoder_t *p_dec = (decoder_t *)app_data;
1787     decoder_sys_t *p_sys = p_dec->p_sys;
1788     (void)omx_handle;
1789
1790 #ifdef OMXIL_EXTRA_DEBUG
1791     msg_Dbg( p_dec, "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1792 #endif
1793
1794     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1795     {
1796         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1797         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1798         if(p_block) block_Release(p_block);
1799         omx_header->pAppPrivate = 0;
1800     }
1801     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1802
1803     return OMX_ErrorNone;
1804 }
1805
1806 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1807     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1808 {
1809     decoder_t *p_dec = (decoder_t *)app_data;
1810     decoder_sys_t *p_sys = p_dec->p_sys;
1811     (void)omx_handle;
1812
1813 #ifdef OMXIL_EXTRA_DEBUG
1814     msg_Dbg( p_dec, "OmxFillBufferDone %p, %p, %i", omx_header, omx_header->pBuffer,
1815              (int)omx_header->nFilledLen );
1816 #endif
1817
1818     if(omx_header->pInputPortPrivate)
1819     {
1820         omx_header->pBuffer = omx_header->pInputPortPrivate;
1821     }
1822     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1823
1824     return OMX_ErrorNone;
1825 }