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