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