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