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