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