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