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