]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
omxil: Update the explanation of the OMX.SEC quirk/workaround
[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
527         if(!GetVlcVideoFormat( def->format.video.eCompressionFormat,
528                                &p_fmt->i_codec, 0 ) )
529         {
530             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
531                                      &p_fmt->i_codec, 0 ) )
532             {
533                 omx_error = OMX_ErrorNotImplemented;
534                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
535                             (int)def->format.video.eColorFormat );
536             }
537             GetVlcChromaSizes( p_fmt->i_codec,
538                                def->format.video.nFrameWidth,
539                                def->format.video.nFrameHeight,
540                                &p_port->i_frame_size, &p_port->i_frame_stride,
541                                &p_port->i_frame_stride_chroma_div );
542         }
543         if(p_port->i_frame_size > def->nBufferSize)
544             def->nBufferSize = p_port->i_frame_size;
545         p_port->i_frame_size = def->nBufferSize;
546 #if 0
547         if((int)p_port->i_frame_stride > def->format.video.nStride)
548             def->format.video.nStride = p_port->i_frame_stride;
549 #endif
550         p_port->i_frame_stride = def->format.video.nStride;
551         break;
552
553     case AUDIO_ES:
554         if( !OmxToVlcAudioFormat( def->format.audio.eEncoding,
555                                 &p_fmt->i_codec, 0 ) )
556         {
557             omx_error = OMX_ErrorNotImplemented;
558             CHECK_ERROR(omx_error, "OMX audio format %i not supported",
559                         (int)def->format.audio.eEncoding );
560         }
561
562         omx_error = GetAudioParameters(p_port->omx_handle,
563                                        &p_port->format_param, def->nPortIndex,
564                                        def->format.audio.eEncoding,
565                                        &p_fmt->audio.i_channels,
566                                        &p_fmt->audio.i_rate,
567                                        &p_fmt->i_bitrate,
568                                        &p_fmt->audio.i_bitspersample,
569                                        &p_fmt->audio.i_blockalign);
570         CHECK_ERROR(omx_error, "GetAudioParameters failed (%x : %s)",
571                     omx_error, ErrorToString(omx_error));
572
573         if(p_fmt->audio.i_channels < 9)
574         {
575             static const int pi_channels_maps[9] =
576             {
577                 0, AOUT_CHAN_CENTER, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
578                 AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
579                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
580                 | AOUT_CHAN_REARRIGHT,
581                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
582                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
583                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
584                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
585                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
586                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT
587                 | AOUT_CHAN_MIDDLERIGHT,
588                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
589                 | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
590                 | AOUT_CHAN_LFE
591             };
592             p_fmt->audio.i_physical_channels =
593                 p_fmt->audio.i_original_channels =
594                     pi_channels_maps[p_fmt->audio.i_channels];
595         }
596
597         date_Init( &p_dec->p_sys->end_date, p_fmt->audio.i_rate, 1 );
598
599         break;
600
601     default: return OMX_ErrorNotImplemented;
602     }
603
604  error:
605     return omx_error;
606 }
607
608 /*****************************************************************************
609  * DeinitialiseComponent: Deinitialise and unload an OMX component
610  *****************************************************************************/
611 static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
612                                            OMX_HANDLETYPE omx_handle)
613 {
614     decoder_sys_t *p_sys = p_dec->p_sys;
615     OMX_ERRORTYPE omx_error;
616     OMX_STATETYPE state;
617     unsigned int i, j;
618
619     if(!omx_handle) return OMX_ErrorNone;
620
621     omx_error = OMX_GetState(omx_handle, &state);
622     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
623
624     if(state == OMX_StateExecuting)
625     {
626         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
627                                      OMX_StateIdle, 0 );
628         CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
629         omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
630         CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
631     }
632
633     omx_error = OMX_GetState(omx_handle, &state);
634     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
635
636     if(state == OMX_StateIdle)
637     {
638         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
639                                      OMX_StateLoaded, 0 );
640         CHECK_ERROR(omx_error, "OMX_CommandStateSet Loaded failed (%x)", omx_error );
641
642         for(i = 0; i < p_sys->ports; i++)
643         {
644             OmxPort *p_port = &p_sys->p_ports[i];
645             OMX_BUFFERHEADERTYPE *p_buffer;
646
647             for(j = 0; j < p_port->i_buffers; j++)
648             {
649                 OMX_FIFO_GET(&p_port->fifo, p_buffer);
650                 if (p_buffer->nFlags & SENTINEL_FLAG) {
651                     free(p_buffer);
652                     j--;
653                     continue;
654                 }
655                 omx_error = OMX_FreeBuffer( omx_handle,
656                                             p_port->i_port_index, p_buffer );
657
658                 if(omx_error != OMX_ErrorNone) break;
659             }
660             CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
661                         omx_error, (int)p_port->i_port_index, j );
662             while (1) {
663                 OMX_FIFO_PEEK(&p_port->fifo, p_buffer);
664                 if (!p_buffer) break;
665
666                 OMX_FIFO_GET(&p_port->fifo, p_buffer);
667                 if (p_buffer->nFlags & SENTINEL_FLAG) {
668                     free(p_buffer);
669                     continue;
670                 }
671                 msg_Warn( p_dec, "Stray buffer left in fifo, %p", p_buffer );
672             }
673         }
674
675         omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
676         CHECK_ERROR(omx_error, "Wait for Loaded failed (%x)", omx_error );
677     }
678
679  error:
680     for(i = 0; i < p_sys->ports; i++)
681     {
682         OmxPort *p_port = &p_sys->p_ports[i];
683         free(p_port->pp_buffers);
684         p_port->pp_buffers = 0;
685     }
686     omx_error = pf_free_handle( omx_handle );
687     return omx_error;
688 }
689
690 /*****************************************************************************
691  * InitialiseComponent: Load and initialise an OMX component
692  *****************************************************************************/
693 static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
694     OMX_STRING psz_component, OMX_HANDLETYPE *p_handle)
695 {
696     static OMX_CALLBACKTYPE callbacks =
697         { OmxEventHandler, OmxEmptyBufferDone, OmxFillBufferDone };
698     decoder_sys_t *p_sys = p_dec->p_sys;
699     OMX_HANDLETYPE omx_handle;
700     OMX_ERRORTYPE omx_error;
701     unsigned int i;
702     OMX_U8 psz_role[OMX_MAX_STRINGNAME_SIZE];
703     OMX_PARAM_COMPONENTROLETYPE role;
704     OMX_PARAM_PORTDEFINITIONTYPE definition;
705     OMX_PORT_PARAM_TYPE param;
706
707     /* Load component */
708     omx_error = pf_get_handle( &omx_handle, psz_component, p_dec, &callbacks );
709     if(omx_error != OMX_ErrorNone)
710     {
711         msg_Warn( p_dec, "OMX_GetHandle(%s) failed (%x: %s)", psz_component,
712                   omx_error, ErrorToString(omx_error) );
713         return omx_error;
714     }
715     strncpy(p_sys->psz_component, psz_component, OMX_MAX_STRINGNAME_SIZE-1);
716
717     omx_error = OMX_ComponentRoleEnum(omx_handle, psz_role, 0);
718     if(omx_error == OMX_ErrorNone)
719         msg_Dbg(p_dec, "loaded component %s of role %s", psz_component, psz_role);
720     else
721         msg_Dbg(p_dec, "loaded component %s", psz_component);
722     PrintOmx(p_dec, omx_handle, OMX_ALL);
723
724     /* Set component role */
725     OMX_INIT_STRUCTURE(role);
726     strcpy((char*)role.cRole,
727            GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec : p_dec->fmt_in.i_codec,
728                       p_dec->fmt_in.i_cat, p_sys->b_enc));
729
730     omx_error = OMX_SetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
731                                  &role);
732     omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
733                                  &role);
734     if(omx_error == OMX_ErrorNone)
735         msg_Dbg(p_dec, "component standard role set to %s", role.cRole);
736
737     /* Find the input / output ports */
738     OMX_INIT_STRUCTURE(param);
739     OMX_INIT_STRUCTURE(definition);
740     omx_error = OMX_GetParameter(omx_handle, p_dec->fmt_in.i_cat == VIDEO_ES ?
741                                  OMX_IndexParamVideoInit : OMX_IndexParamAudioInit, &param);
742     if(omx_error != OMX_ErrorNone) param.nPorts = 0;
743
744     for(i = 0; i < param.nPorts; i++)
745     {
746         OmxPort *p_port;
747
748         /* Get port definition */
749         definition.nPortIndex = param.nStartPortNumber + i;
750         omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamPortDefinition,
751                                      &definition);
752         if(omx_error != OMX_ErrorNone) continue;
753
754         if(definition.eDir == OMX_DirInput) p_port = &p_sys->in;
755         else  p_port = &p_sys->out;
756
757         p_port->b_valid = true;
758         p_port->i_port_index = definition.nPortIndex;
759         p_port->definition = definition;
760         p_port->omx_handle = omx_handle;
761     }
762
763     if(!p_sys->in.b_valid || !p_sys->out.b_valid)
764     {
765         omx_error = OMX_ErrorInvalidComponent;
766         CHECK_ERROR(omx_error, "couldn't find an input and output port");
767     }
768
769     if(!strncmp(p_sys->psz_component, "OMX.SEC.", 8))
770     {
771         OMX_INDEXTYPE index;
772         omx_error = OMX_GetExtensionIndex(omx_handle, (OMX_STRING) "OMX.SEC.index.ThumbnailMode", &index);
773         if(omx_error == OMX_ErrorNone)
774         {
775             OMX_BOOL enable = OMX_TRUE;
776             omx_error = OMX_SetConfig(omx_handle, index, &enable);
777             CHECK_ERROR(omx_error, "Unable to set ThumbnailMode");
778         } else {
779             OMX_BOOL enable = OMX_TRUE;
780             /* Needed on Samsung Galaxy S II */
781             omx_error = OMX_SetConfig(omx_handle, OMX_IndexVendorSetYUV420pMode, &enable);
782             if (omx_error == OMX_ErrorNone)
783                 msg_Dbg(p_dec, "Set OMX_IndexVendorSetYUV420pMode successfully");
784             else
785                 msg_Dbg(p_dec, "Unable to set OMX_IndexVendorSetYUV420pMode: %x", omx_error);
786         }
787     }
788
789     /* Set port definitions */
790     for(i = 0; i < p_sys->ports; i++)
791     {
792         omx_error = SetPortDefinition(p_dec, &p_sys->p_ports[i],
793                                       p_sys->p_ports[i].p_fmt);
794         if(omx_error != OMX_ErrorNone) goto error;
795     }
796
797     /* Allocate our array for the omx buffers and enable ports */
798     for(i = 0; i < p_sys->ports; i++)
799     {
800         OmxPort *p_port = &p_sys->p_ports[i];
801
802         p_port->pp_buffers =
803             malloc(p_port->definition.nBufferCountActual *
804                    sizeof(OMX_BUFFERHEADERTYPE*));
805         if(!p_port->pp_buffers)
806         {
807           omx_error = OMX_ErrorInsufficientResources;
808           CHECK_ERROR(omx_error, "memory allocation failed");
809         }
810         p_port->i_buffers = p_port->definition.nBufferCountActual;
811
812         /* Enable port */
813         if(!p_port->definition.bEnabled)
814         {
815             omx_error = OMX_SendCommand( omx_handle, OMX_CommandPortEnable,
816                                          p_port->i_port_index, NULL);
817             CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
818                         (int)p_port->i_port_index, omx_error );
819             omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
820             CHECK_ERROR(omx_error, "Wait for PortEnable on %i failed (%x)",
821                         (int)p_port->i_port_index, omx_error );
822         }
823     }
824
825     *p_handle = omx_handle;
826     return OMX_ErrorNone;
827
828  error:
829     DeinitialiseComponent(p_dec, omx_handle);
830     *p_handle = 0;
831     return omx_error;
832 }
833
834 /*****************************************************************************
835  * OpenDecoder: Create the decoder instance
836  *****************************************************************************/
837 static int OpenDecoder( vlc_object_t *p_this )
838 {
839     decoder_t *p_dec = (decoder_t*)p_this;
840     int status;
841
842     if( 0 || !GetOmxRole(p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat, false) )
843         return VLC_EGENERIC;
844
845 #ifdef HAVE_MAEMO
846     if( p_dec->fmt_in.i_cat != VIDEO_ES && !p_dec->b_force)
847         return VLC_EGENERIC;
848 #endif
849
850     status = OpenGeneric( p_this, false );
851     if(status != VLC_SUCCESS) return status;
852
853     p_dec->pf_decode_video = DecodeVideo;
854     p_dec->pf_decode_audio = DecodeAudio;
855
856     return VLC_SUCCESS;
857 }
858
859 /*****************************************************************************
860  * OpenEncoder: Create the encoder instance
861  *****************************************************************************/
862 static int OpenEncoder( vlc_object_t *p_this )
863 {
864     encoder_t *p_enc = (encoder_t*)p_this;
865     int status;
866
867     if( !GetOmxRole(p_enc->fmt_out.i_codec, p_enc->fmt_in.i_cat, true) )
868         return VLC_EGENERIC;
869
870     status = OpenGeneric( p_this, true );
871     if(status != VLC_SUCCESS) return status;
872
873     p_enc->pf_encode_video = EncodeVideo;
874
875     return VLC_SUCCESS;
876 }
877
878 /*****************************************************************************
879  * OpenGeneric: Create the generic decoder/encoder instance
880  *****************************************************************************/
881 static int OpenGeneric( vlc_object_t *p_this, bool b_encode )
882 {
883     decoder_t *p_dec = (decoder_t*)p_this;
884     decoder_sys_t *p_sys;
885     OMX_ERRORTYPE omx_error;
886     OMX_BUFFERHEADERTYPE *p_header;
887     unsigned int i, j;
888
889     vlc_mutex_lock( &omx_core_mutex );
890     if( omx_refcount > 0 )
891         goto loaded;
892
893     /* Load the OMX core */
894     for( i = 0; ppsz_dll_list[i]; i++ )
895     {
896         dll_handle = dll_open( ppsz_dll_list[i] );
897         if( dll_handle ) break;
898     }
899     if( !dll_handle )
900     {
901         vlc_mutex_unlock( &omx_core_mutex );
902         return VLC_EGENERIC;
903     }
904
905     pf_init = dlsym( dll_handle, "OMX_Init" );
906     pf_deinit = dlsym( dll_handle, "OMX_Deinit" );
907     pf_get_handle = dlsym( dll_handle, "OMX_GetHandle" );
908     pf_free_handle = dlsym( dll_handle, "OMX_FreeHandle" );
909     pf_component_enum = dlsym( dll_handle, "OMX_ComponentNameEnum" );
910     pf_get_roles_of_component = dlsym( dll_handle, "OMX_GetRolesOfComponent" );
911     if( !pf_init || !pf_deinit || !pf_get_handle || !pf_free_handle ||
912         !pf_component_enum || !pf_get_roles_of_component )
913     {
914         msg_Warn( p_this, "cannot find OMX_* symbols in `%s' (%s)",
915                   ppsz_dll_list[i], dlerror() );
916         dll_close(dll_handle);
917         vlc_mutex_unlock( &omx_core_mutex );
918         return VLC_EGENERIC;
919     }
920
921 loaded:
922     /* Allocate the memory needed to store the decoder's structure */
923     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(*p_sys)) ) == NULL )
924     {
925         if( omx_refcount == 0 )
926             dll_close(dll_handle);
927         vlc_mutex_unlock( &omx_core_mutex );
928         return VLC_ENOMEM;
929     }
930
931     /* Initialise the thread properties */
932     if(!b_encode)
933     {
934         p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
935         p_dec->fmt_out.video = p_dec->fmt_in.video;
936         p_dec->fmt_out.audio = p_dec->fmt_in.audio;
937         p_dec->fmt_out.i_codec = 0;
938     }
939     p_sys->b_enc = b_encode;
940     p_sys->pp_last_event = &p_sys->p_events;
941     vlc_mutex_init (&p_sys->mutex);
942     vlc_cond_init (&p_sys->cond);
943     vlc_mutex_init (&p_sys->lock);
944     vlc_mutex_init (&p_sys->in.fifo.lock);
945     vlc_cond_init (&p_sys->in.fifo.wait);
946     p_sys->in.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pOutputPortPrivate) / sizeof(void *);
947     p_sys->in.fifo.pp_last = &p_sys->in.fifo.p_first;
948     p_sys->in.b_direct = false;
949     p_sys->in.b_flushed = true;
950     p_sys->in.p_fmt = &p_dec->fmt_in;
951     vlc_mutex_init (&p_sys->out.fifo.lock);
952     vlc_cond_init (&p_sys->out.fifo.wait);
953     p_sys->out.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pInputPortPrivate) / sizeof(void *);
954     p_sys->out.fifo.pp_last = &p_sys->out.fifo.p_first;
955     p_sys->out.b_direct = true;
956     p_sys->out.b_flushed = true;
957     p_sys->out.p_fmt = &p_dec->fmt_out;
958     p_sys->ports = 2;
959     p_sys->p_ports = &p_sys->in;
960     p_sys->b_use_pts = 0;
961
962     msg_Dbg(p_dec, "fmt in:%4.4s, out: %4.4s", (char *)&p_dec->fmt_in.i_codec,
963             (char *)&p_dec->fmt_out.i_codec);
964
965     /* Initialise the OMX core */
966     omx_error = omx_refcount > 0 ? OMX_ErrorNone : pf_init();
967     omx_refcount++;
968     if(omx_error != OMX_ErrorNone)
969     {
970         msg_Warn( p_this, "OMX_Init failed (%x: %s)", omx_error,
971                   ErrorToString(omx_error) );
972         vlc_mutex_unlock( &omx_core_mutex );
973         CloseGeneric(p_this);
974         return VLC_EGENERIC;
975     }
976     p_sys->b_init = true;
977     vlc_mutex_unlock( &omx_core_mutex );
978
979     /* Enumerate components and build a list of the one we want to try */
980     if( !CreateComponentsList(p_dec,
981              GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec :
982                         p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat,
983                         p_sys->b_enc)) )
984     {
985         msg_Warn( p_this, "couldn't find an omx component for codec %4.4s",
986                   (char *)&p_dec->fmt_in.i_codec );
987         CloseGeneric(p_this);
988         return VLC_EGENERIC;
989     }
990
991     /* Try to load and initialise a component */
992     omx_error = OMX_ErrorUndefined;
993     for(i = 0; i < p_sys->components; i++)
994     {
995 #ifdef __ANDROID__
996         /* ignore OpenCore software codecs */
997         if (!strncmp(p_sys->ppsz_components[i], "OMX.PV.", 7))
998             continue;
999         /* The same sw codecs, renamed in ICS (perhaps also in honeycomb) */
1000         if (!strncmp(p_sys->ppsz_components[i], "OMX.google.", 11))
1001             continue;
1002         /* This one has been seen on HTC One V - it behaves like it works,
1003          * but FillBufferDone returns buffers filled with 0 bytes. The One V
1004          * has got a working OMX.qcom.video.decoder.avc instead though. */
1005         if (!strncmp(p_sys->ppsz_components[i], "OMX.ARICENT.", 12))
1006             continue;
1007         /* Some nVidia codec with DRM */
1008         if (!strncmp(p_sys->ppsz_components[i], "OMX.Nvidia.h264.decode.secure", 29))
1009             continue;
1010 #endif
1011         omx_error = InitialiseComponent(p_dec, p_sys->ppsz_components[i],
1012                                         &p_sys->omx_handle);
1013         if(omx_error == OMX_ErrorNone) break;
1014     }
1015     CHECK_ERROR(omx_error, "no component could be initialised" );
1016
1017     /* Move component to Idle then Executing state */
1018     OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0 );
1019     CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
1020
1021     /* Allocate omx buffers */
1022     for(i = 0; i < p_sys->ports; i++)
1023     {
1024         OmxPort *p_port = &p_sys->p_ports[i];
1025
1026         for(j = 0; j < p_port->i_buffers; j++)
1027         {
1028 #if 0
1029 #define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
1030             char *p_buf = malloc(p_port->definition.nBufferSize +
1031                                  p_port->definition.nBufferAlignment);
1032             p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
1033 #endif
1034
1035             if(0 && p_port->b_direct)
1036                 omx_error =
1037                     OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
1038                                    p_port->i_port_index, 0,
1039                                    p_port->definition.nBufferSize, (void*)1);
1040             else
1041                 omx_error =
1042                     OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
1043                                         p_port->i_port_index, 0,
1044                                         p_port->definition.nBufferSize);
1045
1046             if(omx_error != OMX_ErrorNone) break;
1047             OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[j]);
1048         }
1049         p_port->i_buffers = j;
1050         CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
1051                     omx_error, (int)p_port->i_port_index, j );
1052     }
1053
1054     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1055     CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
1056
1057     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet,
1058                                  OMX_StateExecuting, 0);
1059     CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x)", omx_error );
1060     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1061     CHECK_ERROR(omx_error, "Wait for Executing failed (%x)", omx_error );
1062
1063     /* Send codec configuration data */
1064     if( p_dec->fmt_in.i_extra )
1065     {
1066         OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1067         p_header->nFilledLen = p_dec->fmt_in.i_extra;
1068
1069         /* Convert H.264 NAL format to annex b */
1070         if( p_sys->i_nal_size_length && !p_sys->in.b_direct )
1071         {
1072             p_header->nFilledLen = 0;
1073             convert_sps_pps( p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
1074                              p_header->pBuffer, p_header->nAllocLen,
1075                              (uint32_t*) &p_header->nFilledLen, NULL );
1076         }
1077         else if(p_sys->in.b_direct)
1078         {
1079             p_header->pOutputPortPrivate = p_header->pBuffer;
1080             p_header->pBuffer = p_dec->fmt_in.p_extra;
1081         }
1082         else
1083         {
1084             if(p_header->nFilledLen > p_header->nAllocLen)
1085             {
1086                 msg_Dbg(p_dec, "buffer too small (%i,%i)", (int)p_header->nFilledLen,
1087                         (int)p_header->nAllocLen);
1088                 p_header->nFilledLen = p_header->nAllocLen;
1089             }
1090             memcpy(p_header->pBuffer, p_dec->fmt_in.p_extra, p_header->nFilledLen);
1091         }
1092
1093         p_header->nOffset = 0;
1094         p_header->nFlags = OMX_BUFFERFLAG_CODECCONFIG | OMX_BUFFERFLAG_ENDOFFRAME;
1095         msg_Dbg(p_dec, "sending codec config data %p, %p, %i", p_header,
1096                 p_header->pBuffer, (int)p_header->nFilledLen);
1097         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1098     }
1099
1100     /* Get back output port definition */
1101     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1102     if(omx_error != OMX_ErrorNone) goto error;
1103
1104     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1105     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1106
1107     if(p_sys->b_error) goto error;
1108
1109     p_dec->b_need_packetized = true;
1110     if (!strcmp(p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER"))
1111         p_sys->b_use_pts = 1;
1112
1113     if (!strcmp(p_sys->psz_component, "OMX.STM.Video.Decoder"))
1114         p_sys->b_use_pts = 1;
1115
1116     if (p_sys->b_use_pts)
1117         msg_Dbg( p_dec, "using pts timestamp mode for %s", p_sys->psz_component);
1118
1119     return VLC_SUCCESS;
1120
1121  error:
1122     CloseGeneric(p_this);
1123     return VLC_EGENERIC;
1124 }
1125
1126 /*****************************************************************************
1127  * PortReconfigure
1128  *****************************************************************************/
1129 static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
1130 {
1131     decoder_sys_t *p_sys = p_dec->p_sys;
1132     OMX_PARAM_PORTDEFINITIONTYPE definition;
1133     OMX_BUFFERHEADERTYPE *p_buffer;
1134     OMX_ERRORTYPE omx_error;
1135     unsigned int i;
1136
1137     /* Sanity checking */
1138     OMX_INIT_STRUCTURE(definition);
1139     definition.nPortIndex = p_port->i_port_index;
1140     omx_error = OMX_GetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1141                                  &definition);
1142     if(omx_error != OMX_ErrorNone || (p_dec->fmt_in.i_cat == VIDEO_ES &&
1143        (!definition.format.video.nFrameWidth ||
1144        !definition.format.video.nFrameHeight)) )
1145         return OMX_ErrorUndefined;
1146
1147     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortDisable,
1148                                  p_port->i_port_index, NULL);
1149     CHECK_ERROR(omx_error, "OMX_CommandPortDisable on %i failed (%x)",
1150                 (int)p_port->i_port_index, omx_error );
1151
1152     for(i = 0; i < p_port->i_buffers; i++)
1153     {
1154         OMX_FIFO_GET(&p_port->fifo, p_buffer);
1155         if (p_buffer->nFlags & SENTINEL_FLAG) {
1156             free(p_buffer);
1157             i--;
1158             continue;
1159         }
1160         omx_error = OMX_FreeBuffer( p_sys->omx_handle,
1161                                     p_port->i_port_index, p_buffer );
1162
1163         if(omx_error != OMX_ErrorNone) break;
1164     }
1165     CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
1166                 omx_error, (int)p_port->i_port_index, i );
1167
1168     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1169     CHECK_ERROR(omx_error, "Wait for PortDisable failed (%x)", omx_error );
1170
1171     /* Get the new port definition */
1172     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1173     if(omx_error != OMX_ErrorNone) goto error;
1174
1175     if( p_dec->fmt_in.i_cat != AUDIO_ES )
1176     {
1177         /* Don't explicitly set the new parameters that we got with
1178          * OMX_GetParameter above when using audio codecs.
1179          * That struct hasn't been changed since, so there should be
1180          * no need to set it here, unless some codec expects the
1181          * SetParameter call as a trigger event for some part of
1182          * the reconfiguration.
1183          * This fixes using audio decoders on Samsung Galaxy S II,
1184          *
1185          * Only skipping this for audio codecs, to minimize the
1186          * change for current working configurations for video.
1187          */
1188         omx_error = OMX_SetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1189                                      &definition);
1190         CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
1191                     omx_error, ErrorToString(omx_error));
1192     }
1193
1194     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortEnable,
1195                                  p_port->i_port_index, NULL);
1196     CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
1197                 (int)p_port->i_port_index, omx_error );
1198
1199     if (p_port->definition.nBufferCountActual > p_port->i_buffers) {
1200         free(p_port->pp_buffers);
1201         p_port->pp_buffers = malloc(p_port->definition.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE*));
1202         if(!p_port->pp_buffers)
1203         {
1204             omx_error = OMX_ErrorInsufficientResources;
1205             CHECK_ERROR(omx_error, "memory allocation failed");
1206         }
1207     }
1208     p_port->i_buffers = p_port->definition.nBufferCountActual;
1209     for(i = 0; i < p_port->i_buffers; i++)
1210     {
1211         if(0 && p_port->b_direct)
1212             omx_error =
1213                 OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1214                                p_port->i_port_index, 0,
1215                                p_port->definition.nBufferSize, (void*)1);
1216         else
1217             omx_error =
1218                 OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1219                                     p_port->i_port_index, 0,
1220                                     p_port->definition.nBufferSize);
1221
1222         if(omx_error != OMX_ErrorNone) break;
1223         OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
1224     }
1225     p_port->i_buffers = i;
1226     CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
1227                 omx_error, (int)p_port->i_port_index, i );
1228
1229     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1230     CHECK_ERROR(omx_error, "Wait for PortEnable failed (%x)", omx_error );
1231
1232     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1233     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1234
1235  error:
1236     return omx_error;
1237 }
1238
1239 /*****************************************************************************
1240  * DecodeVideo: Called to decode one frame
1241  *****************************************************************************/
1242 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
1243 {
1244     decoder_sys_t *p_sys = p_dec->p_sys;
1245     picture_t *p_pic = NULL, *p_next_pic;
1246     OMX_ERRORTYPE omx_error;
1247     unsigned int i;
1248
1249     OMX_BUFFERHEADERTYPE *p_header;
1250     block_t *p_block;
1251
1252     if( !pp_block || !*pp_block )
1253         return NULL;
1254
1255     p_block = *pp_block;
1256
1257     /* Check for errors from codec */
1258     if(p_sys->b_error)
1259     {
1260         msg_Dbg(p_dec, "error during decoding");
1261         block_Release( p_block );
1262         return 0;
1263     }
1264
1265     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1266     {
1267         block_Release( p_block );
1268         if(!p_sys->in.b_flushed)
1269         {
1270             msg_Dbg(p_dec, "flushing");
1271             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1272                              p_sys->in.definition.nPortIndex, 0 );
1273         }
1274         p_sys->in.b_flushed = true;
1275         return NULL;
1276     }
1277
1278     /* Take care of decoded frames first */
1279     while(!p_pic)
1280     {
1281         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1282         if(!p_header) break; /* No frame available */
1283
1284         if(p_sys->out.b_update_def)
1285         {
1286             omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1287             p_sys->out.b_update_def = 0;
1288         }
1289
1290         if(p_header->nFilledLen)
1291         {
1292             p_pic = p_header->pAppPrivate;
1293             if(!p_pic)
1294             {
1295                 /* We're not in direct rendering mode.
1296                  * Get a new picture and copy the content */
1297                 p_pic = decoder_NewPicture( p_dec );
1298
1299                 if (p_pic)
1300                     CopyOmxPicture(p_sys->out.definition.format.video.eColorFormat,
1301                                    p_pic, p_sys->out.definition.format.video.nSliceHeight,
1302                                    p_sys->out.i_frame_stride,
1303                                    p_header->pBuffer + p_header->nOffset,
1304                                    p_sys->out.i_frame_stride_chroma_div);
1305             }
1306
1307             if (p_pic)
1308                 p_pic->date = p_header->nTimeStamp;
1309             p_header->nFilledLen = 0;
1310             p_header->pAppPrivate = 0;
1311         }
1312
1313         /* Get a new picture */
1314         if(p_sys->in.b_direct && !p_header->pAppPrivate)
1315         {
1316             p_next_pic = decoder_NewPicture( p_dec );
1317             if(!p_next_pic) break;
1318
1319             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1320             p_header->pAppPrivate = p_next_pic;
1321             p_header->pInputPortPrivate = p_header->pBuffer;
1322             p_header->pBuffer = p_next_pic->p[0].p_pixels;
1323         }
1324         else
1325         {
1326             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1327         }
1328
1329 #ifdef OMXIL_EXTRA_DEBUG
1330         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1331 #endif
1332         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1333     }
1334
1335     /* Send the input buffer to the component */
1336     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1337
1338     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1339         free(p_header);
1340         goto reconfig;
1341     }
1342
1343     if(p_header)
1344     {
1345         p_header->nFilledLen = p_block->i_buffer;
1346         p_header->nOffset = 0;
1347         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1348         if (p_sys->b_use_pts && p_block->i_pts)
1349             p_header->nTimeStamp = p_block->i_pts;
1350         else
1351             p_header->nTimeStamp = p_block->i_dts;
1352
1353         /* In direct mode we pass the input pointer as is.
1354          * Otherwise we memcopy the data */
1355         if(p_sys->in.b_direct)
1356         {
1357             p_header->pOutputPortPrivate = p_header->pBuffer;
1358             p_header->pBuffer = p_block->p_buffer;
1359             p_header->pAppPrivate = p_block;
1360         }
1361         else
1362         {
1363             if(p_header->nFilledLen > p_header->nAllocLen)
1364             {
1365                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1366                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1367                 p_header->nFilledLen = p_header->nAllocLen;
1368             }
1369             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1370             block_Release(p_block);
1371         }
1372
1373         /* Convert H.264 NAL format to annex b. Doesn't do anything if
1374          * i_nal_size_length == 0, which is the case for codecs other
1375          * than H.264 */
1376         convert_h264_to_annexb( p_header->pBuffer, p_header->nFilledLen,
1377                                 p_sys->i_nal_size_length );
1378 #ifdef OMXIL_EXTRA_DEBUG
1379         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1380                  (int)p_header->nFilledLen );
1381 #endif
1382         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1383         p_sys->in.b_flushed = false;
1384         *pp_block = NULL; /* Avoid being fed the same packet again */
1385     }
1386
1387 reconfig:
1388     /* Handle the PortSettingsChanged events */
1389     for(i = 0; i < p_sys->ports; i++)
1390     {
1391         OmxPort *p_port = &p_sys->p_ports[i];
1392         if(p_port->b_reconfigure)
1393         {
1394             omx_error = PortReconfigure(p_dec, p_port);
1395             p_port->b_reconfigure = 0;
1396         }
1397         if(p_port->b_update_def)
1398         {
1399             omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1400             p_port->b_update_def = 0;
1401         }
1402     }
1403
1404     return p_pic;
1405 }
1406
1407 /*****************************************************************************
1408  * DecodeAudio: Called to decode one frame
1409  *****************************************************************************/
1410 block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1411 {
1412     decoder_sys_t *p_sys = p_dec->p_sys;
1413     block_t *p_buffer = NULL;
1414     OMX_BUFFERHEADERTYPE *p_header;
1415     OMX_ERRORTYPE omx_error;
1416     block_t *p_block;
1417     unsigned int i;
1418
1419     if( !pp_block || !*pp_block ) return NULL;
1420
1421     p_block = *pp_block;
1422
1423     /* Check for errors from codec */
1424     if(p_sys->b_error)
1425     {
1426         msg_Dbg(p_dec, "error during decoding");
1427         block_Release( p_block );
1428         return 0;
1429     }
1430
1431     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1432     {
1433         block_Release( p_block );
1434         date_Set( &p_sys->end_date, 0 );
1435         if(!p_sys->in.b_flushed)
1436         {
1437             msg_Dbg(p_dec, "flushing");
1438             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1439                              p_sys->in.definition.nPortIndex, 0 );
1440         }
1441         p_sys->in.b_flushed = true;
1442         return NULL;
1443     }
1444
1445     if( !date_Get( &p_sys->end_date ) )
1446     {
1447         if( !p_block->i_pts )
1448         {
1449             /* We've just started the stream, wait for the first PTS. */
1450             block_Release( p_block );
1451             return NULL;
1452         }
1453         date_Set( &p_sys->end_date, p_block->i_pts );
1454     }
1455
1456     /* Take care of decoded frames first */
1457     while(!p_buffer)
1458     {
1459         unsigned int i_samples;
1460
1461         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1462         if(!p_header) break; /* No frame available */
1463
1464         i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1465         if(i_samples)
1466         {
1467             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1468             if( !p_buffer ) break; /* No audio buffer available */
1469
1470             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1471             p_header->nFilledLen = 0;
1472
1473             if( p_header->nTimeStamp != 0 &&
1474                 p_header->nTimeStamp != date_Get( &p_sys->end_date ) )
1475                 date_Set( &p_sys->end_date, p_header->nTimeStamp );
1476
1477             p_buffer->i_pts = date_Get( &p_sys->end_date );
1478             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1479                 p_buffer->i_pts;
1480         }
1481
1482 #ifdef OMXIL_EXTRA_DEBUG
1483         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1484 #endif
1485         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1486         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1487     }
1488
1489
1490     /* Send the input buffer to the component */
1491     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1492
1493     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1494         free(p_header);
1495         goto reconfig;
1496     }
1497
1498     if(p_header)
1499     {
1500         p_header->nFilledLen = p_block->i_buffer;
1501         p_header->nOffset = 0;
1502         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1503         p_header->nTimeStamp = p_block->i_dts;
1504
1505         /* In direct mode we pass the input pointer as is.
1506          * Otherwise we memcopy the data */
1507         if(p_sys->in.b_direct)
1508         {
1509             p_header->pOutputPortPrivate = p_header->pBuffer;
1510             p_header->pBuffer = p_block->p_buffer;
1511             p_header->pAppPrivate = p_block;
1512         }
1513         else
1514         {
1515             if(p_header->nFilledLen > p_header->nAllocLen)
1516             {
1517                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1518                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1519                 p_header->nFilledLen = p_header->nAllocLen;
1520             }
1521             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1522             block_Release(p_block);
1523         }
1524
1525 #ifdef OMXIL_EXTRA_DEBUG
1526         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1527                  (int)p_header->nFilledLen );
1528 #endif
1529         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1530         p_sys->in.b_flushed = false;
1531         *pp_block = NULL; /* Avoid being fed the same packet again */
1532     }
1533
1534 reconfig:
1535     /* Handle the PortSettingsChanged events */
1536     for(i = 0; i < p_sys->ports; i++)
1537     {
1538         OmxPort *p_port = &p_sys->p_ports[i];
1539         if(!p_port->b_reconfigure) continue;
1540         p_port->b_reconfigure = 0;
1541         omx_error = PortReconfigure(p_dec, p_port);
1542     }
1543
1544     return p_buffer;
1545 }
1546
1547 /*****************************************************************************
1548  * EncodeVideo: Called to encode one frame
1549  *****************************************************************************/
1550 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1551 {
1552     decoder_t *p_dec = ( decoder_t *)p_enc;
1553     decoder_sys_t *p_sys = p_dec->p_sys;
1554     OMX_ERRORTYPE omx_error;
1555     unsigned int i;
1556
1557     OMX_BUFFERHEADERTYPE *p_header;
1558     block_t *p_block = 0;
1559
1560     if( !p_pic ) return NULL;
1561
1562     /* Check for errors from codec */
1563     if(p_sys->b_error)
1564     {
1565         msg_Dbg(p_dec, "error during encoding");
1566         return NULL;
1567     }
1568
1569     /* Send the input buffer to the component */
1570     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1571     if(p_header)
1572     {
1573         /* In direct mode we pass the input pointer as is.
1574          * Otherwise we memcopy the data */
1575         if(p_sys->in.b_direct)
1576         {
1577             p_header->pOutputPortPrivate = p_header->pBuffer;
1578             p_header->pBuffer = p_pic->p[0].p_pixels;
1579         }
1580         else
1581         {
1582             CopyVlcPicture(p_dec, p_header, p_pic);
1583         }
1584
1585         p_header->nFilledLen = p_sys->in.i_frame_size;
1586         p_header->nOffset = 0;
1587         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1588         p_header->nTimeStamp = p_pic->date;
1589 #ifdef OMXIL_EXTRA_DEBUG
1590         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1591                  (int)p_header->nFilledLen );
1592 #endif
1593         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1594         p_sys->in.b_flushed = false;
1595     }
1596
1597     /* Handle the PortSettingsChanged events */
1598     for(i = 0; i < p_sys->ports; i++)
1599     {
1600         OmxPort *p_port = &p_sys->p_ports[i];
1601         if(!p_port->b_reconfigure) continue;
1602         p_port->b_reconfigure = 0;
1603         omx_error = PortReconfigure(p_dec, p_port);
1604     }
1605
1606     /* Wait for the decoded frame */
1607     while(!p_block)
1608     {
1609         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1610
1611         if(p_header->nFilledLen)
1612         {
1613             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1614             {
1615                 /* TODO: need to store codec config */
1616                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1617             }
1618
1619             p_block = p_header->pAppPrivate;
1620             if(!p_block)
1621             {
1622                 /* We're not in direct rendering mode.
1623                  * Get a new block and copy the content */
1624                 p_block = block_Alloc( p_header->nFilledLen );
1625                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1626             }
1627
1628             p_block->i_buffer = p_header->nFilledLen;
1629             p_block->i_pts = p_block->i_dts = p_header->nTimeStamp;
1630             p_header->nFilledLen = 0;
1631             p_header->pAppPrivate = 0;
1632         }
1633
1634 #ifdef OMXIL_EXTRA_DEBUG
1635         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1636 #endif
1637         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1638     }
1639
1640     msg_Dbg(p_dec, "done");
1641     return p_block;
1642 }
1643
1644 /*****************************************************************************
1645  * CloseGeneric: omxil decoder destruction
1646  *****************************************************************************/
1647 static void CloseGeneric( vlc_object_t *p_this )
1648 {
1649     decoder_t *p_dec = (decoder_t *)p_this;
1650     decoder_sys_t *p_sys = p_dec->p_sys;
1651
1652     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1653     vlc_mutex_lock( &omx_core_mutex );
1654     omx_refcount--;
1655     if( omx_refcount == 0 )
1656     {
1657         if( p_sys->b_init ) pf_deinit();
1658         dll_close( dll_handle );
1659     }
1660     vlc_mutex_unlock( &omx_core_mutex );
1661
1662     vlc_mutex_destroy (&p_sys->mutex);
1663     vlc_cond_destroy (&p_sys->cond);
1664     vlc_mutex_destroy (&p_sys->in.fifo.lock);
1665     vlc_cond_destroy (&p_sys->in.fifo.wait);
1666     vlc_mutex_destroy (&p_sys->out.fifo.lock);
1667     vlc_cond_destroy (&p_sys->out.fifo.wait);
1668
1669     free( p_sys );
1670 }
1671
1672 /*****************************************************************************
1673  * OmxEventHandler: 
1674  *****************************************************************************/
1675 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1676     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1677     OMX_U32 data_2, OMX_PTR event_data )
1678 {
1679     decoder_t *p_dec = (decoder_t *)app_data;
1680     decoder_sys_t *p_sys = p_dec->p_sys;
1681     unsigned int i;
1682     (void)omx_handle;
1683
1684     switch (event)
1685     {
1686     case OMX_EventCmdComplete:
1687         switch ((OMX_STATETYPE)data_1)
1688         {
1689         case OMX_CommandStateSet:
1690             msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %s)", EventToString(event),
1691                      CommandToString(data_1), StateToString(data_2) );
1692             break;
1693
1694         default:
1695             msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u)", EventToString(event),
1696                      CommandToString(data_1), (unsigned int)data_2 );
1697             break;
1698         }
1699         break;
1700
1701     case OMX_EventError:
1702         msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u, %s)", EventToString(event),
1703                  ErrorToString((OMX_ERRORTYPE)data_1), (unsigned int)data_2,
1704                  (const char *)event_data);
1705         //p_sys->b_error = true;
1706         break;
1707
1708     case OMX_EventPortSettingsChanged:
1709         msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
1710                  (unsigned int)data_1, (unsigned int)data_2 );
1711         if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition )
1712         {
1713             OMX_BUFFERHEADERTYPE *sentinel;
1714             for(i = 0; i < p_sys->ports; i++)
1715                 if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1716                     p_sys->p_ports[i].b_reconfigure = true;
1717             sentinel = calloc(1, sizeof(*sentinel));
1718             if (sentinel) {
1719                 sentinel->nFlags = SENTINEL_FLAG;
1720                 OMX_FIFO_PUT(&p_sys->in.fifo, sentinel);
1721             }
1722         }
1723         else if( data_2 == OMX_IndexConfigCommonOutputCrop )
1724         {
1725             for(i = 0; i < p_sys->ports; i++)
1726                 if(p_sys->p_ports[i].definition.nPortIndex == data_1)
1727                     p_sys->p_ports[i].b_update_def = true;
1728         }
1729         else
1730         {
1731             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
1732         }
1733         break;
1734
1735     default:
1736         msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
1737                  (unsigned int)data_1, (unsigned int)data_2 );
1738         break;
1739     }
1740
1741     PostOmxEvent(p_dec, event, data_1, data_2, event_data);
1742     return OMX_ErrorNone;
1743 }
1744
1745 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1746     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1747 {
1748     decoder_t *p_dec = (decoder_t *)app_data;
1749     decoder_sys_t *p_sys = p_dec->p_sys;
1750     (void)omx_handle;
1751
1752 #ifdef OMXIL_EXTRA_DEBUG
1753     msg_Dbg( p_dec, "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1754 #endif
1755
1756     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1757     {
1758         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1759         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1760         if(p_block) block_Release(p_block);
1761         omx_header->pAppPrivate = 0;
1762     }
1763     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1764
1765     return OMX_ErrorNone;
1766 }
1767
1768 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1769     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1770 {
1771     decoder_t *p_dec = (decoder_t *)app_data;
1772     decoder_sys_t *p_sys = p_dec->p_sys;
1773     (void)omx_handle;
1774
1775 #ifdef OMXIL_EXTRA_DEBUG
1776     msg_Dbg( p_dec, "OmxFillBufferDone %p, %p, %i", omx_header, omx_header->pBuffer,
1777              (int)omx_header->nFilledLen );
1778 #endif
1779
1780     if(omx_header->pInputPortPrivate)
1781     {
1782         omx_header->pBuffer = omx_header->pInputPortPrivate;
1783     }
1784     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1785
1786     return OMX_ErrorNone;
1787 }