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