]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
omxil: Simplify the definition of SOURCES_iomx
[vlc] / modules / codec / omxil / omxil.c
1 /*****************************************************************************
2  * omxil.c: Video decoder module making use of OpenMAX IL components.
3  *****************************************************************************
4  * Copyright (C) 2010 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <dlfcn.h>
32 #if defined(USE_IOMX)
33 #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     for(i = 0; i < p_sys->components; i++)
864     {
865         omx_error = InitialiseComponent(p_dec, p_sys->ppsz_components[i],
866                                         &p_sys->omx_handle);
867         if(omx_error == OMX_ErrorNone) break;
868     }
869     CHECK_ERROR(omx_error, "no component could be initialised" );
870
871     /* Move component to Idle then Executing state */
872     OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0 );
873     CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
874
875     /* Allocate omx buffers */
876     for(i = 0; i < p_sys->ports; i++)
877     {
878         OmxPort *p_port = &p_sys->p_ports[i];
879
880         for(j = 0; j < p_port->i_buffers; j++)
881         {
882 #if 0
883 #define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
884             char *p_buf = malloc(p_port->definition.nBufferSize +
885                                  p_port->definition.nBufferAlignment);
886             p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
887 #endif
888
889             if(0 && p_port->b_direct)
890                 omx_error =
891                     OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
892                                    p_port->i_port_index, 0,
893                                    p_port->definition.nBufferSize, (void*)1);
894             else
895                 omx_error =
896                     OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
897                                         p_port->i_port_index, 0,
898                                         p_port->definition.nBufferSize);
899
900             if(omx_error != OMX_ErrorNone) break;
901             OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[j]);
902         }
903         p_port->i_buffers = j;
904         CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
905                     omx_error, (int)p_port->i_port_index, j );
906     }
907
908     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
909     CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
910
911     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet,
912                                  OMX_StateExecuting, 0);
913     CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x)", omx_error );
914     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
915     CHECK_ERROR(omx_error, "Wait for Executing failed (%x)", omx_error );
916
917     /* Send codec configuration data */
918     if( p_dec->fmt_in.i_extra )
919     {
920         OMX_FIFO_GET(&p_sys->in.fifo, p_header);
921         p_header->nFilledLen = p_dec->fmt_in.i_extra;
922
923         /* Convert H.264 NAL format to annex b */
924         if( p_sys->i_nal_size_length && !p_sys->in.b_direct )
925         {
926             p_header->nFilledLen = 0;
927             convert_sps_pps( p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
928                              p_header->pBuffer, p_header->nAllocLen,
929                              (uint32_t*) &p_header->nFilledLen, NULL );
930         }
931         else if(p_sys->in.b_direct)
932         {
933             p_header->pOutputPortPrivate = p_header->pBuffer;
934             p_header->pBuffer = p_dec->fmt_in.p_extra;
935         }
936         else
937         {
938             if(p_header->nFilledLen > p_header->nAllocLen)
939             {
940                 msg_Dbg(p_dec, "buffer too small (%i,%i)", (int)p_header->nFilledLen,
941                         (int)p_header->nAllocLen);
942                 p_header->nFilledLen = p_header->nAllocLen;
943             }
944             memcpy(p_header->pBuffer, p_dec->fmt_in.p_extra, p_header->nFilledLen);
945         }
946
947         p_header->nOffset = 0;
948         p_header->nFlags = OMX_BUFFERFLAG_CODECCONFIG;
949         msg_Dbg(p_dec, "sending codec config data %p, %p, %i", p_header,
950                 p_header->pBuffer, (int)p_header->nFilledLen);
951         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
952     }
953
954     /* Get back output port definition */
955     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
956     if(omx_error != OMX_ErrorNone) goto error;
957
958     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
959     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
960
961     if(p_sys->b_error) goto error;
962
963     p_dec->b_need_packetized = true;
964     return VLC_SUCCESS;
965
966  error:
967     CloseGeneric(p_this);
968     return VLC_EGENERIC;
969 }
970
971 /*****************************************************************************
972  * PortReconfigure
973  *****************************************************************************/
974 static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
975 {
976     decoder_sys_t *p_sys = p_dec->p_sys;
977     OMX_PARAM_PORTDEFINITIONTYPE definition;
978     OMX_BUFFERHEADERTYPE *p_buffer;
979     OMX_ERRORTYPE omx_error;
980     unsigned int i;
981
982     /* Sanity checking */
983     OMX_INIT_STRUCTURE(definition);
984     definition.nPortIndex = p_port->i_port_index;
985     omx_error = OMX_GetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
986                                  &definition);
987     if(omx_error != OMX_ErrorNone ||
988        !definition.format.video.nFrameWidth ||
989        !definition.format.video.nFrameHeight )
990         return OMX_ErrorUndefined;
991
992     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortDisable,
993                                  p_port->i_port_index, NULL);
994     CHECK_ERROR(omx_error, "OMX_CommandPortDisable on %i failed (%x)",
995                 (int)p_port->i_port_index, omx_error );
996
997     for(i = 0; i < p_port->i_buffers; i++)
998     {
999         OMX_FIFO_GET(&p_port->fifo, p_buffer);
1000         omx_error = OMX_FreeBuffer( p_sys->omx_handle,
1001                                     p_port->i_port_index, p_buffer );
1002
1003         if(omx_error != OMX_ErrorNone) break;
1004     }
1005     CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
1006                 omx_error, (int)p_port->i_port_index, i );
1007
1008     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1009     CHECK_ERROR(omx_error, "Wait for PortDisable failed (%x)", omx_error );
1010
1011     /* Get the new port definition */
1012     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1013     if(omx_error != OMX_ErrorNone) goto error;
1014     omx_error = OMX_SetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1015                                  &definition);
1016     CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
1017                 omx_error, ErrorToString(omx_error));
1018
1019     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortEnable,
1020                                  p_port->i_port_index, NULL);
1021     CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
1022                 (int)p_port->i_port_index, omx_error );
1023
1024     if (p_port->definition.nBufferCountActual > p_port->i_buffers) {
1025         free(p_port->pp_buffers);
1026         p_port->pp_buffers = malloc(p_port->definition.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE*));
1027         if(!p_port->pp_buffers)
1028         {
1029             omx_error = OMX_ErrorInsufficientResources;
1030             CHECK_ERROR(omx_error, "memory allocation failed");
1031         }
1032     }
1033     p_port->i_buffers = p_port->definition.nBufferCountActual;
1034     for(i = 0; i < p_port->i_buffers; i++)
1035     {
1036         if(0 && p_port->b_direct)
1037             omx_error =
1038                 OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1039                                p_port->i_port_index, 0,
1040                                p_port->definition.nBufferSize, (void*)1);
1041         else
1042             omx_error =
1043                 OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1044                                     p_port->i_port_index, 0,
1045                                     p_port->definition.nBufferSize);
1046
1047         if(omx_error != OMX_ErrorNone) break;
1048         OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
1049     }
1050     p_port->i_buffers = i;
1051     CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
1052                 omx_error, (int)p_port->i_port_index, i );
1053
1054     omx_error = WaitForSpecificOmxEvent(p_dec, OMX_EventCmdComplete, 0, 0, 0);
1055     CHECK_ERROR(omx_error, "Wait for PortEnable failed (%x)", omx_error );
1056
1057     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1058     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1059
1060  error:
1061     return omx_error;
1062 }
1063
1064 /*****************************************************************************
1065  * DecodeVideo: Called to decode one frame
1066  *****************************************************************************/
1067 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
1068 {
1069     decoder_sys_t *p_sys = p_dec->p_sys;
1070     picture_t *p_pic = NULL, *p_next_pic;
1071     OMX_ERRORTYPE omx_error;
1072     unsigned int i;
1073
1074     OMX_BUFFERHEADERTYPE *p_header;
1075     block_t *p_block;
1076
1077     if( !pp_block || !*pp_block )
1078         return NULL;
1079
1080     p_block = *pp_block;
1081
1082     /* Check for errors from codec */
1083     if(p_sys->b_error)
1084     {
1085         msg_Dbg(p_dec, "error during decoding");
1086         block_Release( p_block );
1087         return 0;
1088     }
1089
1090     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1091     {
1092         block_Release( p_block );
1093         if(!p_sys->in.b_flushed)
1094         {
1095             msg_Dbg(p_dec, "flushing");
1096             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1097                              p_sys->in.definition.nPortIndex, 0 );
1098         }
1099         p_sys->in.b_flushed = true;
1100         return NULL;
1101     }
1102
1103     /* Take care of decoded frames first */
1104     while(!p_pic)
1105     {
1106         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1107         if(!p_header) break; /* No frame available */
1108
1109         if(p_header->nFilledLen)
1110         {
1111             p_pic = p_header->pAppPrivate;
1112             if(!p_pic)
1113             {
1114                 /* We're not in direct rendering mode.
1115                  * Get a new picture and copy the content */
1116                 p_pic = decoder_NewPicture( p_dec );
1117                 if( !p_pic ) break; /* No picture available */
1118
1119                 CopyOmxPicture(p_dec, p_pic, p_header, p_sys->out.definition.format.video.nSliceHeight);
1120             }
1121
1122             p_pic->date = p_header->nTimeStamp;
1123             p_header->nFilledLen = 0;
1124             p_header->pAppPrivate = 0;
1125         }
1126
1127         /* Get a new picture */
1128         if(p_sys->in.b_direct && !p_header->pAppPrivate)
1129         {
1130             p_next_pic = decoder_NewPicture( p_dec );
1131             if(!p_next_pic) break;
1132
1133             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1134             p_header->pAppPrivate = p_next_pic;
1135             p_header->pInputPortPrivate = p_header->pBuffer;
1136             p_header->pBuffer = p_next_pic->p[0].p_pixels;
1137         }
1138         else
1139         {
1140             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1141         }
1142
1143 #ifdef OMXIL_EXTRA_DEBUG
1144         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1145 #endif
1146         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1147     }
1148
1149     /* Send the input buffer to the component */
1150     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1151
1152     if (p_header && p_header->nFlags & OMX_BUFFERFLAG_EOS)
1153         goto reconfig;
1154
1155     if(p_header)
1156     {
1157         p_header->nFilledLen = p_block->i_buffer;
1158         p_header->nOffset = 0;
1159         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1160         p_header->nTimeStamp = p_block->i_dts;
1161
1162         /* In direct mode we pass the input pointer as is.
1163          * Otherwise we memcopy the data */
1164         if(p_sys->in.b_direct)
1165         {
1166             p_header->pOutputPortPrivate = p_header->pBuffer;
1167             p_header->pBuffer = p_block->p_buffer;
1168             p_header->pAppPrivate = p_block;
1169         }
1170         else
1171         {
1172             if(p_header->nFilledLen > p_header->nAllocLen)
1173             {
1174                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1175                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1176                 p_header->nFilledLen = p_header->nAllocLen;
1177             }
1178             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1179             block_Release(p_block);
1180         }
1181
1182         /* Convert H.264 NAL format to annex b */
1183         if( p_sys->i_nal_size_length >= 3 && p_sys->i_nal_size_length <= 4 )
1184         {
1185             /* This only works for NAL sizes 3-4 */
1186             int i_len = p_header->nFilledLen, i;
1187             uint8_t* ptr = p_header->pBuffer;
1188             while( i_len >= p_sys->i_nal_size_length )
1189             {
1190                 uint32_t nal_len = 0;
1191                 for( i = 0; i < p_sys->i_nal_size_length; i++ ) {
1192                     nal_len = (nal_len << 8) | ptr[i];
1193                     ptr[i] = 0;
1194                 }
1195                 ptr[p_sys->i_nal_size_length - 1] = 1;
1196                 if( nal_len > INT_MAX || nal_len > (unsigned int) i_len )
1197                     break;
1198                 ptr   += nal_len + 4;
1199                 i_len -= nal_len + 4;
1200             }
1201         }
1202 #ifdef OMXIL_EXTRA_DEBUG
1203         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1204                  (int)p_header->nFilledLen );
1205 #endif
1206         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1207         p_sys->in.b_flushed = false;
1208         *pp_block = NULL; /* Avoid being fed the same packet again */
1209     }
1210
1211 reconfig:
1212     /* Handle the PortSettingsChanged events */
1213     for(i = 0; i < p_sys->ports; i++)
1214     {
1215         OmxPort *p_port = &p_sys->p_ports[i];
1216         if(!p_port->b_reconfigure) continue;
1217         p_port->b_reconfigure = 0;
1218         omx_error = PortReconfigure(p_dec, p_port);
1219     }
1220
1221     return p_pic;
1222 }
1223
1224 /*****************************************************************************
1225  * DecodeAudio: Called to decode one frame
1226  *****************************************************************************/
1227 aout_buffer_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1228 {
1229     decoder_sys_t *p_sys = p_dec->p_sys;
1230     aout_buffer_t *p_buffer = 0;
1231     OMX_BUFFERHEADERTYPE *p_header;
1232     OMX_ERRORTYPE omx_error;
1233     block_t *p_block;
1234     unsigned int i;
1235
1236     if( !pp_block || !*pp_block ) return NULL;
1237
1238     p_block = *pp_block;
1239
1240     /* Check for errors from codec */
1241     if(p_sys->b_error)
1242     {
1243         msg_Dbg(p_dec, "error during decoding");
1244         block_Release( p_block );
1245         return 0;
1246     }
1247
1248     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1249     {
1250         block_Release( p_block );
1251         date_Set( &p_sys->end_date, 0 );
1252         if(!p_sys->in.b_flushed)
1253         {
1254             msg_Dbg(p_dec, "flushing");
1255             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1256                              p_sys->in.definition.nPortIndex, 0 );
1257         }
1258         p_sys->in.b_flushed = true;
1259         return NULL;
1260     }
1261
1262     if( !date_Get( &p_sys->end_date ) )
1263     {
1264         if( !p_block->i_pts )
1265         {
1266             /* We've just started the stream, wait for the first PTS. */
1267             block_Release( p_block );
1268             return NULL;
1269         }
1270         date_Set( &p_sys->end_date, p_block->i_pts );
1271     }
1272
1273     /* Take care of decoded frames first */
1274     while(!p_buffer)
1275     {
1276         unsigned int i_samples;
1277
1278         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1279         if(!p_header) break; /* No frame available */
1280
1281         i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1282         if(i_samples)
1283         {
1284             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1285             if( !p_buffer ) break; /* No audio buffer available */
1286
1287             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1288             p_header->nFilledLen = 0;
1289
1290             if( p_header->nTimeStamp != 0 &&
1291                 p_header->nTimeStamp != date_Get( &p_sys->end_date ) )
1292                 date_Set( &p_sys->end_date, p_header->nTimeStamp );
1293
1294             p_buffer->i_pts = date_Get( &p_sys->end_date );
1295             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1296                 p_buffer->i_pts;
1297         }
1298
1299 #ifdef OMXIL_EXTRA_DEBUG
1300         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1301 #endif
1302         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1303         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1304     }
1305
1306
1307     /* Send the input buffer to the component */
1308     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1309     if(p_header)
1310     {
1311         p_header->nFilledLen = p_block->i_buffer;
1312         p_header->nOffset = 0;
1313         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1314         p_header->nTimeStamp = p_block->i_dts;
1315
1316         /* In direct mode we pass the input pointer as is.
1317          * Otherwise we memcopy the data */
1318         if(p_sys->in.b_direct)
1319         {
1320             p_header->pOutputPortPrivate = p_header->pBuffer;
1321             p_header->pBuffer = p_block->p_buffer;
1322             p_header->pAppPrivate = p_block;
1323         }
1324         else
1325         {
1326             if(p_header->nFilledLen > p_header->nAllocLen)
1327             {
1328                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1329                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1330                 p_header->nFilledLen = p_header->nAllocLen;
1331             }
1332             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1333             block_Release(p_block);
1334         }
1335
1336 #ifdef OMXIL_EXTRA_DEBUG
1337         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1338                  (int)p_header->nFilledLen );
1339 #endif
1340         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1341         p_sys->in.b_flushed = false;
1342         *pp_block = NULL; /* Avoid being fed the same packet again */
1343     }
1344
1345     /* Handle the PortSettingsChanged events */
1346     for(i = 0; i < p_sys->ports; i++)
1347     {
1348         OmxPort *p_port = &p_sys->p_ports[i];
1349         if(!p_port->b_reconfigure) continue;
1350         p_port->b_reconfigure = 0;
1351         omx_error = PortReconfigure(p_dec, p_port);
1352     }
1353
1354     return p_buffer;
1355 }
1356
1357 /*****************************************************************************
1358  * EncodeVideo: Called to encode one frame
1359  *****************************************************************************/
1360 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1361 {
1362     decoder_t *p_dec = ( decoder_t *)p_enc;
1363     decoder_sys_t *p_sys = p_dec->p_sys;
1364     OMX_ERRORTYPE omx_error;
1365     unsigned int i;
1366
1367     OMX_BUFFERHEADERTYPE *p_header;
1368     block_t *p_block = 0;
1369
1370     if( !p_pic ) return NULL;
1371
1372     /* Check for errors from codec */
1373     if(p_sys->b_error)
1374     {
1375         msg_Dbg(p_dec, "error during encoding");
1376         return NULL;
1377     }
1378
1379     /* Send the input buffer to the component */
1380     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1381     if(p_header)
1382     {
1383         /* In direct mode we pass the input pointer as is.
1384          * Otherwise we memcopy the data */
1385         if(p_sys->in.b_direct)
1386         {
1387             p_header->pOutputPortPrivate = p_header->pBuffer;
1388             p_header->pBuffer = p_pic->p[0].p_pixels;
1389         }
1390         else
1391         {
1392             CopyVlcPicture(p_dec, p_header, p_pic);
1393         }
1394
1395         p_header->nFilledLen = p_sys->in.i_frame_size;
1396         p_header->nOffset = 0;
1397         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1398         p_header->nTimeStamp = p_pic->date;
1399 #ifdef OMXIL_EXTRA_DEBUG
1400         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1401                  (int)p_header->nFilledLen );
1402 #endif
1403         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1404         p_sys->in.b_flushed = false;
1405     }
1406
1407     /* Handle the PortSettingsChanged events */
1408     for(i = 0; i < p_sys->ports; i++)
1409     {
1410         OmxPort *p_port = &p_sys->p_ports[i];
1411         if(!p_port->b_reconfigure) continue;
1412         p_port->b_reconfigure = 0;
1413         omx_error = PortReconfigure(p_dec, p_port);
1414     }
1415
1416     /* Wait for the decoded frame */
1417     while(!p_block)
1418     {
1419         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1420
1421         if(p_header->nFilledLen)
1422         {
1423             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1424             {
1425                 /* TODO: need to store codec config */
1426                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1427             }
1428
1429             p_block = p_header->pAppPrivate;
1430             if(!p_block)
1431             {
1432                 /* We're not in direct rendering mode.
1433                  * Get a new block and copy the content */
1434                 p_block = block_New( p_dec, p_header->nFilledLen );
1435                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1436             }
1437
1438             p_block->i_buffer = p_header->nFilledLen;
1439             p_block->i_pts = p_block->i_dts = p_header->nTimeStamp;
1440             p_header->nFilledLen = 0;
1441             p_header->pAppPrivate = 0;
1442         }
1443
1444 #ifdef OMXIL_EXTRA_DEBUG
1445         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1446 #endif
1447         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1448     }
1449
1450     msg_Dbg(p_dec, "done");
1451     return p_block;
1452 }
1453
1454 /*****************************************************************************
1455  * CloseGeneric: omxil decoder destruction
1456  *****************************************************************************/
1457 static void CloseGeneric( vlc_object_t *p_this )
1458 {
1459     decoder_t *p_dec = (decoder_t *)p_this;
1460     decoder_sys_t *p_sys = p_dec->p_sys;
1461
1462     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1463     if(p_sys->b_init) p_sys->pf_deinit();
1464     dll_close( p_sys->dll_handle );
1465
1466     vlc_mutex_destroy (&p_sys->mutex);
1467     vlc_cond_destroy (&p_sys->cond);
1468     vlc_mutex_destroy (&p_sys->in.fifo.lock);
1469     vlc_cond_destroy (&p_sys->in.fifo.wait);
1470     vlc_mutex_destroy (&p_sys->out.fifo.lock);
1471     vlc_cond_destroy (&p_sys->out.fifo.wait);
1472
1473     free( p_sys );
1474 }
1475
1476 /*****************************************************************************
1477  * OmxEventHandler: 
1478  *****************************************************************************/
1479 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1480     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1481     OMX_U32 data_2, OMX_PTR event_data )
1482 {
1483     decoder_t *p_dec = (decoder_t *)app_data;
1484     decoder_sys_t *p_sys = p_dec->p_sys;
1485     unsigned int i;
1486     (void)omx_handle;
1487
1488     switch (event)
1489     {
1490     case OMX_EventCmdComplete:
1491         switch ((OMX_STATETYPE)data_1)
1492         {
1493         case OMX_CommandStateSet:
1494             msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %s)", EventToString(event),
1495                      CommandToString(data_1), StateToString(data_2) );
1496             break;
1497
1498         default:
1499             msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u)", EventToString(event),
1500                      CommandToString(data_1), (unsigned int)data_2 );
1501             break;
1502         }
1503         break;
1504
1505     case OMX_EventError:
1506         msg_Dbg( p_dec, "OmxEventHandler (%s, %s, %u, %s)", EventToString(event),
1507                  ErrorToString((OMX_ERRORTYPE)data_1), (unsigned int)data_2,
1508                  (const char *)event_data);
1509         //p_sys->b_error = true;
1510         break;
1511
1512     case OMX_EventPortSettingsChanged:
1513         msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
1514                  (unsigned int)data_1, (unsigned int)data_2 );
1515         for(i = 0; i < p_sys->ports; i++)
1516             if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1517                 p_sys->p_ports[i].b_reconfigure = true;
1518         memset(&p_sys->sentinel_buffer, 0, sizeof(p_sys->sentinel_buffer));
1519         p_sys->sentinel_buffer.nFlags = OMX_BUFFERFLAG_EOS;
1520         OMX_FIFO_PUT(&p_sys->in.fifo, &p_sys->sentinel_buffer);
1521         break;
1522
1523     default:
1524         msg_Dbg( p_dec, "OmxEventHandler (%s, %u, %u)", EventToString(event),
1525                  (unsigned int)data_1, (unsigned int)data_2 );
1526         break;
1527     }
1528
1529     PostOmxEvent(p_dec, event, data_1, data_2, event_data);
1530     return OMX_ErrorNone;
1531 }
1532
1533 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1534     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1535 {
1536     decoder_t *p_dec = (decoder_t *)app_data;
1537     decoder_sys_t *p_sys = p_dec->p_sys;
1538     (void)omx_handle;
1539
1540 #ifdef OMXIL_EXTRA_DEBUG
1541     msg_Dbg( p_dec, "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1542 #endif
1543
1544     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1545     {
1546         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1547         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1548         if(p_block) block_Release(p_block);
1549         omx_header->pAppPrivate = 0;
1550     }
1551     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1552
1553     return OMX_ErrorNone;
1554 }
1555
1556 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1557     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1558 {
1559     decoder_t *p_dec = (decoder_t *)app_data;
1560     decoder_sys_t *p_sys = p_dec->p_sys;
1561     (void)omx_handle;
1562
1563 #ifdef OMXIL_EXTRA_DEBUG
1564     msg_Dbg( p_dec, "OmxFillBufferDone %p, %p, %i", omx_header, omx_header->pBuffer,
1565              (int)omx_header->nFilledLen );
1566 #endif
1567
1568     if(omx_header->pInputPortPrivate)
1569     {
1570         omx_header->pBuffer = omx_header->pInputPortPrivate;
1571     }
1572     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1573
1574     return OMX_ErrorNone;
1575 }