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