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