]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
omxil: fix warning
[vlc] / modules / codec / omxil / omxil.c
1 /*****************************************************************************
2  * omxil.c: Video decoder module making use of OpenMAX IL components.
3  *****************************************************************************
4  * Copyright (C) 2010 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * 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 <limits.h>
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_codec.h>
36 #include <vlc_block_helper.h>
37 #include <vlc_cpu.h>
38 #include "../h264_nal.h"
39
40 #include "omxil.h"
41 #include "omxil_core.h"
42 #include "OMX_Broadcom.h"
43
44 #ifndef NDEBUG
45 # define OMXIL_EXTRA_DEBUG
46 #endif
47
48 #define SENTINEL_FLAG 0x10000
49
50 /* Defined in the broadcom version of OMX_Index.h */
51 #define OMX_IndexConfigRequestCallback 0x7f000063
52 #define OMX_IndexParamBrcmPixelAspectRatio 0x7f00004d
53 #define OMX_IndexParamBrcmVideoDecodeErrorConcealment 0x7f000080
54
55 /* Defined in the broadcom version of OMX_Core.h */
56 #define OMX_EventParamOrConfigChanged 0x7F000001
57
58 /*****************************************************************************
59  * Local prototypes
60  *****************************************************************************/
61 static int  OpenDecoder( vlc_object_t * );
62 static int  OpenEncoder( vlc_object_t * );
63 static int  OpenGeneric( vlc_object_t *, bool b_encode );
64 static void CloseGeneric( vlc_object_t * );
65
66 static picture_t *DecodeVideo( decoder_t *, block_t ** );
67 static block_t *DecodeAudio ( decoder_t *, block_t ** );
68 static block_t *EncodeVideo( encoder_t *, picture_t * );
69
70 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE, OMX_PTR, OMX_EVENTTYPE,
71                                       OMX_U32, OMX_U32, OMX_PTR );
72 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE, OMX_PTR,
73                                          OMX_BUFFERHEADERTYPE * );
74 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE, OMX_PTR,
75                                         OMX_BUFFERHEADERTYPE * );
76
77 /*****************************************************************************
78  * Module descriptor
79  *****************************************************************************/
80 vlc_module_begin ()
81     set_description( N_("Audio/Video decoder (using OpenMAX IL)") )
82     set_category( CAT_INPUT )
83     set_subcategory( SUBCAT_INPUT_VCODEC )
84     set_section( N_("Decoding") , NULL )
85 #if defined(USE_IOMX)
86     /* For IOMX, don't enable it automatically via priorities,
87      * enable it only via the --codec iomx command line parameter when
88      * wanted. */
89     set_capability( "decoder", 0 )
90 #else
91     set_capability( "decoder", 80 )
92 #endif
93     set_callbacks( OpenDecoder, CloseGeneric )
94
95     add_submodule ()
96     set_section( N_("Encoding") , NULL )
97     set_description( N_("Video encoder (using OpenMAX IL)") )
98     set_capability( "encoder", 0 )
99     set_callbacks( OpenEncoder, CloseGeneric )
100 vlc_module_end ()
101
102 /*****************************************************************************
103  * ImplementationSpecificWorkarounds: place-holder for implementation
104  * specific workarounds
105  *****************************************************************************/
106 static OMX_ERRORTYPE ImplementationSpecificWorkarounds(decoder_t *p_dec,
107     OmxPort *p_port, es_format_t *p_fmt)
108 {
109     decoder_sys_t *p_sys = p_dec->p_sys;
110     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
111     size_t i_profile = 0xFFFF, i_level = 0xFFFF;
112
113     /* Try to find out the profile of the video */
114     if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
115             p_fmt->i_codec == VLC_CODEC_H264)
116         h264_get_profile_level(&p_dec->fmt_in, &i_profile, &i_level, &p_sys->i_nal_size_length);
117
118     if(!strcmp(p_sys->psz_component, "OMX.TI.Video.Decoder"))
119     {
120         if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
121            p_fmt->i_codec == VLC_CODEC_H264 &&
122            (i_profile != 66 || i_level > 30))
123         {
124             msg_Dbg(p_dec, "h264 profile/level not supported (0x%x, 0x%x)",
125                     i_profile, i_level);
126             return OMX_ErrorNotImplemented;
127         }
128
129         if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirOutput &&
130            p_fmt->i_codec == VLC_CODEC_I420)
131         {
132             /* I420 xvideo is slow on OMAP */
133             def->format.video.eColorFormat = OMX_COLOR_FormatCbYCrY;
134             GetVlcChromaFormat( def->format.video.eColorFormat,
135                                 &p_fmt->i_codec, 0 );
136             GetVlcChromaSizes( p_fmt->i_codec,
137                                def->format.video.nFrameWidth,
138                                def->format.video.nFrameHeight,
139                                &p_port->i_frame_size, &p_port->i_frame_stride,
140                                &p_port->i_frame_stride_chroma_div );
141             def->format.video.nStride = p_port->i_frame_stride;
142             def->nBufferSize = p_port->i_frame_size;
143         }
144     }
145     else if(!strcmp(p_sys->psz_component, "OMX.st.video_encoder"))
146     {
147         if(p_fmt->i_cat == VIDEO_ES)
148         {
149             /* Bellagio's encoder doesn't encode the framerate in Q16 */
150             def->format.video.xFramerate >>= 16;
151         }
152     }
153 #if 0 /* FIXME: doesn't apply for HP Touchpad */
154     else if (!strncmp(p_sys->psz_component, "OMX.qcom.video.decoder.",
155                       strlen("OMX.qcom.video.decoder")))
156     {
157         /* qdsp6 refuses buffer size larger than 450K on input port */
158         if (def->nBufferSize > 450 * 1024)
159         {
160             def->nBufferSize = 450 * 1024;
161             p_port->i_frame_size = def->nBufferSize;
162         }
163     }
164 #endif
165 #ifdef RPI_OMX
166     else if (!strcmp(p_sys->psz_component, "OMX.broadcom.video_decode"))
167     {
168         /* Clear these fields before setting parameters, to allow the codec
169          * fill in what it wants (instead of rejecting whatever happened to
170          * be there. */
171         def->format.video.nStride = def->format.video.nSliceHeight = 0;
172     }
173 #endif
174
175     return OMX_ErrorNone;
176 }
177
178 /*****************************************************************************
179  * SetPortDefinition: set definition of the omx port based on the vlc format
180  *****************************************************************************/
181 static OMX_ERRORTYPE SetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
182                                        es_format_t *p_fmt)
183 {
184     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
185     OMX_ERRORTYPE omx_error;
186
187     omx_error = OMX_GetParameter(p_port->omx_handle,
188                                  OMX_IndexParamPortDefinition, def);
189     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
190                 omx_error, ErrorToString(omx_error));
191
192     switch(p_fmt->i_cat)
193     {
194     case VIDEO_ES:
195         def->format.video.nFrameWidth = p_fmt->video.i_width;
196         def->format.video.nFrameHeight = p_fmt->video.i_height;
197         if(def->format.video.eCompressionFormat == OMX_VIDEO_CodingUnused)
198             def->format.video.nStride = def->format.video.nFrameWidth;
199         if( p_fmt->video.i_frame_rate > 0 &&
200             p_fmt->video.i_frame_rate_base > 0 )
201             def->format.video.xFramerate = (p_fmt->video.i_frame_rate << 16) /
202                 p_fmt->video.i_frame_rate_base;
203
204         if(def->eDir == OMX_DirInput || p_dec->p_sys->b_enc)
205         {
206             if (def->eDir == OMX_DirInput && p_dec->p_sys->b_enc)
207                 def->nBufferSize = def->format.video.nFrameWidth *
208                   def->format.video.nFrameHeight * 2;
209             p_port->i_frame_size = def->nBufferSize;
210
211             if(!GetOmxVideoFormat(p_fmt->i_codec,
212                                   &def->format.video.eCompressionFormat, 0) )
213             {
214                 if(!GetOmxChromaFormat(p_fmt->i_codec,
215                                        &def->format.video.eColorFormat, 0) )
216                 {
217                     omx_error = OMX_ErrorNotImplemented;
218                     CHECK_ERROR(omx_error, "codec %4.4s doesn't match any OMX format",
219                                 (char *)&p_fmt->i_codec );
220                 }
221                 GetVlcChromaSizes( p_fmt->i_codec,
222                                    def->format.video.nFrameWidth,
223                                    def->format.video.nFrameHeight,
224                                    &p_port->i_frame_size, &p_port->i_frame_stride,
225                                    &p_port->i_frame_stride_chroma_div );
226                 def->format.video.nStride = p_port->i_frame_stride;
227                 def->nBufferSize = p_port->i_frame_size;
228             }
229         }
230         else
231         {
232             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
233                                      &p_fmt->i_codec, 0 ) )
234             {
235                 omx_error = OMX_ErrorNotImplemented;
236                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
237                             (int)def->format.video.eColorFormat );
238             }
239             GetVlcChromaSizes( p_fmt->i_codec,
240                                def->format.video.nFrameWidth,
241                                def->format.video.nFrameHeight,
242                                &p_port->i_frame_size, &p_port->i_frame_stride,
243                                &p_port->i_frame_stride_chroma_div );
244             def->format.video.nStride = p_port->i_frame_stride;
245             if (p_port->i_frame_size > def->nBufferSize)
246                 def->nBufferSize = p_port->i_frame_size;
247         }
248         break;
249
250     case AUDIO_ES:
251         p_port->i_frame_size = def->nBufferSize;
252         if(def->eDir == OMX_DirInput)
253         {
254             if(!GetOmxAudioFormat(p_fmt->i_codec,
255                                   &def->format.audio.eEncoding, 0) )
256             {
257                 omx_error = OMX_ErrorNotImplemented;
258                 CHECK_ERROR(omx_error, "codec %4.4s doesn't match any OMX format",
259                             (char *)&p_fmt->i_codec );
260             }
261         }
262         else
263         {
264             if( !OmxToVlcAudioFormat(def->format.audio.eEncoding,
265                                    &p_fmt->i_codec, 0 ) )
266             {
267                 omx_error = OMX_ErrorNotImplemented;
268                 CHECK_ERROR(omx_error, "OMX audio encoding %i not supported",
269                             (int)def->format.audio.eEncoding );
270             }
271         }
272         break;
273
274     default: return OMX_ErrorNotImplemented;
275     }
276
277     omx_error = ImplementationSpecificWorkarounds(p_dec, p_port, p_fmt);
278     CHECK_ERROR(omx_error, "ImplementationSpecificWorkarounds failed (%x : %s)",
279                 omx_error, ErrorToString(omx_error));
280
281     omx_error = OMX_SetParameter(p_port->omx_handle,
282                                  OMX_IndexParamPortDefinition, def);
283     CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
284                 omx_error, ErrorToString(omx_error));
285
286     omx_error = OMX_GetParameter(p_port->omx_handle,
287                                  OMX_IndexParamPortDefinition, def);
288     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
289                 omx_error, ErrorToString(omx_error));
290
291     if(p_port->i_frame_size > def->nBufferSize)
292         def->nBufferSize = p_port->i_frame_size;
293     p_port->i_frame_size = def->nBufferSize;
294
295     /* Deal with audio params */
296     if(p_fmt->i_cat == AUDIO_ES)
297     {
298         omx_error = SetAudioParameters(p_port->omx_handle,
299                                        &p_port->format_param, def->nPortIndex,
300                                        def->format.audio.eEncoding,
301                                        p_fmt->i_codec,
302                                        p_fmt->audio.i_channels,
303                                        p_fmt->audio.i_rate,
304                                        p_fmt->i_bitrate,
305                                        p_fmt->audio.i_bitspersample,
306                                        p_fmt->audio.i_blockalign);
307         if (def->eDir == OMX_DirInput) {
308             CHECK_ERROR(omx_error, "SetAudioParameters failed (%x : %s)",
309                         omx_error, ErrorToString(omx_error));
310         } else if (omx_error != OMX_ErrorNone) {
311             msg_Warn(p_dec, "SetAudioParameters failed (%x : %s) on output port",
312                      omx_error, ErrorToString(omx_error));
313             omx_error = OMX_ErrorNone;
314         }
315     }
316     if (!strcmp(p_dec->p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER") &&
317                 def->eDir == OMX_DirOutput)
318     {
319         /* When setting the output buffer size above, the decoder actually
320          * sets the buffer size to a lower value than what was chosen. If
321          * we try to allocate buffers of this size, it fails. Thus, forcibly
322          * use a larger buffer size. */
323         def->nBufferSize *= 2;
324     }
325
326  error:
327     return omx_error;
328 }
329
330
331 /*****************************************************************************
332  * UpdatePixelAspect: Update vlc pixel aspect based on the aspect reported on
333  * the omx port - NOTE: Broadcom specific
334  *****************************************************************************/
335 static OMX_ERRORTYPE UpdatePixelAspect(decoder_t *p_dec)
336 {
337     decoder_sys_t *p_sys = p_dec->p_sys;
338     OMX_CONFIG_POINTTYPE pixel_aspect;
339     OMX_INIT_STRUCTURE(pixel_aspect);
340     OMX_ERRORTYPE omx_err;
341
342     if (strncmp(p_sys->psz_component, "OMX.broadcom.", 13))
343         return OMX_ErrorNotImplemented;
344
345     pixel_aspect.nPortIndex = p_sys->out.i_port_index;
346     omx_err = OMX_GetParameter(p_sys->omx_handle,
347             OMX_IndexParamBrcmPixelAspectRatio, &pixel_aspect);
348     if (omx_err != OMX_ErrorNone) {
349         msg_Warn(p_dec, "Failed to retrieve aspect ratio");
350     } else {
351         p_dec->fmt_out.video.i_sar_num = pixel_aspect.nX;
352         p_dec->fmt_out.video.i_sar_den = pixel_aspect.nY;
353     }
354
355     return omx_err;
356 }
357
358 /*****************************************************************************
359  * GetPortDefinition: set vlc format based on the definition of the omx port
360  *****************************************************************************/
361 static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
362                                        es_format_t *p_fmt)
363 {
364     decoder_sys_t *p_sys = p_dec->p_sys;
365     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
366     OMX_ERRORTYPE omx_error;
367     OMX_CONFIG_RECTTYPE crop_rect;
368
369     omx_error = OMX_GetParameter(p_port->omx_handle,
370                                  OMX_IndexParamPortDefinition, def);
371     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
372                 omx_error, ErrorToString(omx_error));
373
374     switch(p_fmt->i_cat)
375     {
376     case VIDEO_ES:
377         p_fmt->video.i_width = def->format.video.nFrameWidth;
378         p_fmt->video.i_visible_width = def->format.video.nFrameWidth;
379         p_fmt->video.i_height = def->format.video.nFrameHeight;
380         p_fmt->video.i_visible_height = def->format.video.nFrameHeight;
381         p_fmt->video.i_frame_rate = p_dec->fmt_in.video.i_frame_rate;
382         p_fmt->video.i_frame_rate_base = p_dec->fmt_in.video.i_frame_rate_base;
383
384         OMX_INIT_STRUCTURE(crop_rect);
385         crop_rect.nPortIndex = def->nPortIndex;
386         omx_error = OMX_GetConfig(p_port->omx_handle, OMX_IndexConfigCommonOutputCrop, &crop_rect);
387         if (omx_error == OMX_ErrorNone)
388         {
389             if (!def->format.video.nSliceHeight)
390                 def->format.video.nSliceHeight = def->format.video.nFrameHeight;
391             if (!def->format.video.nStride)
392                 def->format.video.nStride = def->format.video.nFrameWidth;
393             p_fmt->video.i_width = crop_rect.nWidth;
394             p_fmt->video.i_visible_width = crop_rect.nWidth;
395             p_fmt->video.i_height = crop_rect.nHeight;
396             p_fmt->video.i_visible_height = crop_rect.nHeight;
397             if (def->format.video.eColorFormat == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
398                 def->format.video.nSliceHeight -= crop_rect.nTop/2;
399         }
400         else
401         {
402             /* Don't pass the error back to the caller, this isn't mandatory */
403             omx_error = OMX_ErrorNone;
404         }
405
406         /* Hack: Nexus One (stock firmware with binary OMX driver blob)
407          * claims to output 420Planar even though it in in practice is
408          * NV21. */
409         if(def->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar &&
410            !strncmp(p_sys->psz_component, "OMX.qcom.video.decoder",
411                     strlen("OMX.qcom.video.decoder")))
412             def->format.video.eColorFormat = OMX_QCOM_COLOR_FormatYVU420SemiPlanar;
413
414         if (IgnoreOmxDecoderPadding(p_sys->psz_component)) {
415             def->format.video.nSliceHeight = 0;
416             def->format.video.nStride = p_fmt->video.i_width;
417         }
418
419         if(!GetVlcVideoFormat( def->format.video.eCompressionFormat,
420                                &p_fmt->i_codec, 0 ) )
421         {
422             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
423                                      &p_fmt->i_codec, 0 ) )
424             {
425                 omx_error = OMX_ErrorNotImplemented;
426                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
427                             (int)def->format.video.eColorFormat );
428             }
429             GetVlcChromaSizes( p_fmt->i_codec,
430                                def->format.video.nFrameWidth,
431                                def->format.video.nFrameHeight,
432                                &p_port->i_frame_size, &p_port->i_frame_stride,
433                                &p_port->i_frame_stride_chroma_div );
434         }
435         if(p_port->i_frame_size > def->nBufferSize)
436             def->nBufferSize = p_port->i_frame_size;
437         p_port->i_frame_size = def->nBufferSize;
438 #if 0
439         if((int)p_port->i_frame_stride > def->format.video.nStride)
440             def->format.video.nStride = p_port->i_frame_stride;
441 #endif
442         p_port->i_frame_stride = def->format.video.nStride;
443         UpdatePixelAspect(p_dec);
444         break;
445
446     case AUDIO_ES:
447         if( !OmxToVlcAudioFormat( def->format.audio.eEncoding,
448                                 &p_fmt->i_codec, 0 ) )
449         {
450             omx_error = OMX_ErrorNotImplemented;
451             CHECK_ERROR(omx_error, "OMX audio format %i not supported",
452                         (int)def->format.audio.eEncoding );
453         }
454
455         omx_error = GetAudioParameters(p_port->omx_handle,
456                                        &p_port->format_param, def->nPortIndex,
457                                        def->format.audio.eEncoding,
458                                        &p_fmt->audio.i_channels,
459                                        &p_fmt->audio.i_rate,
460                                        &p_fmt->i_bitrate,
461                                        &p_fmt->audio.i_bitspersample,
462                                        &p_fmt->audio.i_blockalign);
463         CHECK_ERROR(omx_error, "GetAudioParameters failed (%x : %s)",
464                     omx_error, ErrorToString(omx_error));
465
466         if(p_fmt->audio.i_channels < 9)
467         {
468             static const int pi_channels_maps[9] =
469             {
470                 0, AOUT_CHAN_CENTER, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
471                 AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
472                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
473                 | AOUT_CHAN_REARRIGHT,
474                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
475                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
476                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
477                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
478                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
479                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT
480                 | AOUT_CHAN_MIDDLERIGHT,
481                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
482                 | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
483                 | AOUT_CHAN_LFE
484             };
485             p_fmt->audio.i_physical_channels =
486                 p_fmt->audio.i_original_channels =
487                     pi_channels_maps[p_fmt->audio.i_channels];
488         }
489
490         date_Init( &p_dec->p_sys->end_date, p_fmt->audio.i_rate, 1 );
491
492         break;
493
494     default: return OMX_ErrorNotImplemented;
495     }
496
497  error:
498     return omx_error;
499 }
500
501 /*****************************************************************************
502  * DeinitialiseComponent: Deinitialise and unload an OMX component
503  *****************************************************************************/
504 static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
505                                            OMX_HANDLETYPE omx_handle)
506 {
507     decoder_sys_t *p_sys = p_dec->p_sys;
508     OMX_ERRORTYPE omx_error;
509     OMX_STATETYPE state;
510     unsigned int i, j;
511
512     if(!omx_handle) return OMX_ErrorNone;
513
514     omx_error = OMX_GetState(omx_handle, &state);
515     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
516
517     if(state == OMX_StateExecuting)
518     {
519         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
520                                      OMX_StateIdle, 0 );
521         CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
522         while (1) {
523             OMX_U32 cmd, state;
524             omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, &cmd, &state, 0);
525             CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
526             // The event queue can contain other OMX_EventCmdComplete items,
527             // such as for OMX_CommandFlush
528             if (cmd == OMX_CommandStateSet && state == OMX_StateIdle)
529                 break;
530         }
531     }
532
533     omx_error = OMX_GetState(omx_handle, &state);
534     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
535
536     if(state == OMX_StateIdle)
537     {
538         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
539                                      OMX_StateLoaded, 0 );
540         CHECK_ERROR(omx_error, "OMX_CommandStateSet Loaded failed (%x)", omx_error );
541
542         for(i = 0; i < p_sys->ports; i++)
543         {
544             OmxPort *p_port = &p_sys->p_ports[i];
545             OMX_BUFFERHEADERTYPE *p_buffer;
546
547             for(j = 0; j < p_port->i_buffers; j++)
548             {
549                 OMX_FIFO_GET(&p_port->fifo, p_buffer);
550                 if (p_buffer->nFlags & SENTINEL_FLAG) {
551                     free(p_buffer);
552                     j--;
553                     continue;
554                 }
555                 omx_error = OMX_FreeBuffer( omx_handle,
556                                             p_port->i_port_index, p_buffer );
557
558                 if(omx_error != OMX_ErrorNone) break;
559             }
560             CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
561                         omx_error, (int)p_port->i_port_index, j );
562             while (1) {
563                 OMX_FIFO_PEEK(&p_port->fifo, p_buffer);
564                 if (!p_buffer) break;
565
566                 OMX_FIFO_GET(&p_port->fifo, p_buffer);
567                 if (p_buffer->nFlags & SENTINEL_FLAG) {
568                     free(p_buffer);
569                     continue;
570                 }
571                 msg_Warn( p_dec, "Stray buffer left in fifo, %p", p_buffer );
572             }
573         }
574
575         omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
576         CHECK_ERROR(omx_error, "Wait for Loaded failed (%x)", omx_error );
577     }
578
579  error:
580     for(i = 0; i < p_sys->ports; i++)
581     {
582         OmxPort *p_port = &p_sys->p_ports[i];
583         free(p_port->pp_buffers);
584         p_port->pp_buffers = 0;
585     }
586     omx_error = pf_free_handle( omx_handle );
587     return omx_error;
588 }
589
590 /*****************************************************************************
591  * InitialiseComponent: Load and initialise an OMX component
592  *****************************************************************************/
593 static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
594     OMX_STRING psz_component, OMX_HANDLETYPE *p_handle)
595 {
596     static OMX_CALLBACKTYPE callbacks =
597         { OmxEventHandler, OmxEmptyBufferDone, OmxFillBufferDone };
598     decoder_sys_t *p_sys = p_dec->p_sys;
599     OMX_HANDLETYPE omx_handle;
600     OMX_ERRORTYPE omx_error;
601     unsigned int i;
602     OMX_U8 psz_role[OMX_MAX_STRINGNAME_SIZE];
603     OMX_PARAM_COMPONENTROLETYPE role;
604     OMX_PARAM_PORTDEFINITIONTYPE definition;
605     OMX_PORT_PARAM_TYPE param;
606
607     /* Load component */
608     omx_error = pf_get_handle( &omx_handle, psz_component, p_dec, &callbacks );
609     if(omx_error != OMX_ErrorNone)
610     {
611         msg_Warn( p_dec, "OMX_GetHandle(%s) failed (%x: %s)", psz_component,
612                   omx_error, ErrorToString(omx_error) );
613         return omx_error;
614     }
615     strncpy(p_sys->psz_component, psz_component, OMX_MAX_STRINGNAME_SIZE-1);
616
617     omx_error = OMX_ComponentRoleEnum(omx_handle, psz_role, 0);
618     if(omx_error == OMX_ErrorNone)
619         msg_Dbg(p_dec, "loaded component %s of role %s", psz_component, psz_role);
620     else
621         msg_Dbg(p_dec, "loaded component %s", psz_component);
622     PrintOmx(p_dec, omx_handle, OMX_ALL);
623
624     /* Set component role */
625     OMX_INIT_STRUCTURE(role);
626     strcpy((char*)role.cRole,
627            GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec : p_dec->fmt_in.i_codec,
628                       p_dec->fmt_in.i_cat, p_sys->b_enc));
629
630     omx_error = OMX_SetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
631                                  &role);
632     omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
633                                  &role);
634     if(omx_error == OMX_ErrorNone)
635         msg_Dbg(p_dec, "component standard role set to %s", role.cRole);
636
637     /* Find the input / output ports */
638     OMX_INIT_STRUCTURE(param);
639     OMX_INIT_STRUCTURE(definition);
640     omx_error = OMX_GetParameter(omx_handle, p_dec->fmt_in.i_cat == VIDEO_ES ?
641                                  OMX_IndexParamVideoInit : OMX_IndexParamAudioInit, &param);
642     if(omx_error != OMX_ErrorNone) {
643 #ifdef __ANDROID__
644         param.nPorts = 2;
645         param.nStartPortNumber = 0;
646 #else
647         param.nPorts = 0;
648 #endif
649     }
650
651     for(i = 0; i < param.nPorts; i++)
652     {
653         OmxPort *p_port;
654
655         /* Get port definition */
656         definition.nPortIndex = param.nStartPortNumber + i;
657         omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamPortDefinition,
658                                      &definition);
659         if(omx_error != OMX_ErrorNone) continue;
660
661         if(definition.eDir == OMX_DirInput) p_port = &p_sys->in;
662         else  p_port = &p_sys->out;
663
664         p_port->b_valid = true;
665         p_port->i_port_index = definition.nPortIndex;
666         p_port->definition = definition;
667         p_port->omx_handle = omx_handle;
668     }
669
670     if(!p_sys->in.b_valid || !p_sys->out.b_valid)
671     {
672         omx_error = OMX_ErrorInvalidComponent;
673         CHECK_ERROR(omx_error, "couldn't find an input and output port");
674     }
675
676     if(!strncmp(p_sys->psz_component, "OMX.SEC.", 8) &&
677        p_dec->fmt_in.i_cat == VIDEO_ES)
678     {
679         OMX_INDEXTYPE index;
680         omx_error = OMX_GetExtensionIndex(omx_handle, (OMX_STRING) "OMX.SEC.index.ThumbnailMode", &index);
681         if(omx_error == OMX_ErrorNone)
682         {
683             OMX_BOOL enable = OMX_TRUE;
684             omx_error = OMX_SetConfig(omx_handle, index, &enable);
685             CHECK_ERROR(omx_error, "Unable to set ThumbnailMode");
686         } else {
687             OMX_BOOL enable = OMX_TRUE;
688             /* Needed on Samsung Galaxy S II */
689             omx_error = OMX_SetConfig(omx_handle, OMX_IndexVendorSetYUV420pMode, &enable);
690             if (omx_error == OMX_ErrorNone)
691                 msg_Dbg(p_dec, "Set OMX_IndexVendorSetYUV420pMode successfully");
692             else
693                 msg_Dbg(p_dec, "Unable to set OMX_IndexVendorSetYUV420pMode: %x", omx_error);
694         }
695     }
696
697     if(!strncmp(p_sys->psz_component, "OMX.broadcom.", 13))
698     {
699         OMX_CONFIG_REQUESTCALLBACKTYPE notifications;
700         OMX_INIT_STRUCTURE(notifications);
701
702         notifications.nPortIndex = p_sys->out.i_port_index;
703         notifications.nIndex = OMX_IndexParamBrcmPixelAspectRatio;
704         notifications.bEnable = OMX_TRUE;
705
706         omx_error = OMX_SetParameter(omx_handle,
707                 OMX_IndexConfigRequestCallback, &notifications);
708         if (omx_error == OMX_ErrorNone) {
709             msg_Dbg(p_dec, "Enabled aspect ratio notifications");
710             p_sys->b_aspect_ratio_handled = true;
711         } else
712             msg_Dbg(p_dec, "Could not enable aspect ratio notifications");
713     }
714
715     /* Set port definitions */
716     for(i = 0; i < p_sys->ports; i++)
717     {
718         omx_error = SetPortDefinition(p_dec, &p_sys->p_ports[i],
719                                       p_sys->p_ports[i].p_fmt);
720         if(omx_error != OMX_ErrorNone) goto error;
721     }
722
723     if(!strncmp(p_sys->psz_component, "OMX.broadcom.", 13) &&
724         p_sys->in.p_fmt->i_codec == VLC_CODEC_H264)
725     {
726         OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE concanParam;
727         OMX_INIT_STRUCTURE(concanParam);
728         concanParam.bStartWithValidFrame = OMX_FALSE;
729
730         omx_error = OMX_SetParameter(omx_handle,
731                 OMX_IndexParamBrcmVideoDecodeErrorConcealment, &concanParam);
732         if (omx_error == OMX_ErrorNone)
733             msg_Dbg(p_dec, "StartWithValidFrame disabled.");
734         else
735             msg_Dbg(p_dec, "Could not disable StartWithValidFrame.");
736     }
737
738     /* Allocate our array for the omx buffers and enable ports */
739     for(i = 0; i < p_sys->ports; i++)
740     {
741         OmxPort *p_port = &p_sys->p_ports[i];
742
743         p_port->pp_buffers =
744             malloc(p_port->definition.nBufferCountActual *
745                    sizeof(OMX_BUFFERHEADERTYPE*));
746         if(!p_port->pp_buffers)
747         {
748           omx_error = OMX_ErrorInsufficientResources;
749           CHECK_ERROR(omx_error, "memory allocation failed");
750         }
751         p_port->i_buffers = p_port->definition.nBufferCountActual;
752
753         /* Enable port */
754         if(!p_port->definition.bEnabled)
755         {
756             omx_error = OMX_SendCommand( omx_handle, OMX_CommandPortEnable,
757                                          p_port->i_port_index, NULL);
758             CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
759                         (int)p_port->i_port_index, omx_error );
760             omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
761             CHECK_ERROR(omx_error, "Wait for PortEnable on %i failed (%x)",
762                         (int)p_port->i_port_index, omx_error );
763         }
764     }
765
766     *p_handle = omx_handle;
767     return OMX_ErrorNone;
768
769  error:
770     DeinitialiseComponent(p_dec, omx_handle);
771     *p_handle = 0;
772     return omx_error;
773 }
774
775 /*****************************************************************************
776  * OpenDecoder: Create the decoder instance
777  *****************************************************************************/
778 static int OpenDecoder( vlc_object_t *p_this )
779 {
780     decoder_t *p_dec = (decoder_t*)p_this;
781     int status;
782
783 #ifdef __ANDROID__
784     if( p_dec->fmt_in.i_cat == AUDIO_ES )
785         return VLC_EGENERIC;
786 #endif
787
788     if( 0 || !GetOmxRole(p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat, false) )
789         return VLC_EGENERIC;
790
791     status = OpenGeneric( p_this, false );
792     if(status != VLC_SUCCESS) return status;
793
794     p_dec->pf_decode_video = DecodeVideo;
795     p_dec->pf_decode_audio = DecodeAudio;
796
797     return VLC_SUCCESS;
798 }
799
800 /*****************************************************************************
801  * OpenEncoder: Create the encoder instance
802  *****************************************************************************/
803 static int OpenEncoder( vlc_object_t *p_this )
804 {
805     encoder_t *p_enc = (encoder_t*)p_this;
806     int status;
807
808     if( !GetOmxRole(p_enc->fmt_out.i_codec, p_enc->fmt_in.i_cat, true) )
809         return VLC_EGENERIC;
810
811     status = OpenGeneric( p_this, true );
812     if(status != VLC_SUCCESS) return status;
813
814     p_enc->pf_encode_video = EncodeVideo;
815
816     return VLC_SUCCESS;
817 }
818
819 /*****************************************************************************
820  * OpenGeneric: Create the generic decoder/encoder instance
821  *****************************************************************************/
822 static int OpenGeneric( vlc_object_t *p_this, bool b_encode )
823 {
824     decoder_t *p_dec = (decoder_t*)p_this;
825     decoder_sys_t *p_sys;
826     OMX_ERRORTYPE omx_error;
827     OMX_BUFFERHEADERTYPE *p_header;
828     unsigned int i, j;
829
830     if (InitOmxCore(p_this) != VLC_SUCCESS) {
831         return VLC_EGENERIC;
832     }
833
834     /* Allocate the memory needed to store the decoder's structure */
835     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(*p_sys)) ) == NULL )
836     {
837         DeinitOmxCore();
838         return VLC_ENOMEM;
839     }
840
841     /* Initialise the thread properties */
842     if(!b_encode)
843     {
844         p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
845         p_dec->fmt_out.video = p_dec->fmt_in.video;
846         p_dec->fmt_out.audio = p_dec->fmt_in.audio;
847         p_dec->fmt_out.i_codec = 0;
848
849         /* set default aspect of 1, if parser did not set it */
850         if (p_dec->fmt_out.video.i_sar_num == 0)
851             p_dec->fmt_out.video.i_sar_num = 1;
852         if (p_dec->fmt_out.video.i_sar_den == 0)
853             p_dec->fmt_out.video.i_sar_den = 1;
854     }
855     p_sys->b_enc = b_encode;
856     InitOmxEventQueue(&p_sys->event_queue);
857     vlc_mutex_init (&p_sys->in.fifo.lock);
858     vlc_cond_init (&p_sys->in.fifo.wait);
859     p_sys->in.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pOutputPortPrivate) / sizeof(void *);
860     p_sys->in.fifo.pp_last = &p_sys->in.fifo.p_first;
861     p_sys->in.b_direct = false;
862     p_sys->in.b_flushed = true;
863     p_sys->in.p_fmt = &p_dec->fmt_in;
864     vlc_mutex_init (&p_sys->out.fifo.lock);
865     vlc_cond_init (&p_sys->out.fifo.wait);
866     p_sys->out.fifo.offset = offsetof(OMX_BUFFERHEADERTYPE, pInputPortPrivate) / sizeof(void *);
867     p_sys->out.fifo.pp_last = &p_sys->out.fifo.p_first;
868     p_sys->out.b_direct = false;
869     p_sys->out.b_flushed = true;
870     p_sys->out.p_fmt = &p_dec->fmt_out;
871     p_sys->ports = 2;
872     p_sys->p_ports = &p_sys->in;
873     p_sys->b_use_pts = 1;
874
875     msg_Dbg(p_dec, "fmt in:%4.4s, out: %4.4s", (char *)&p_dec->fmt_in.i_codec,
876             (char *)&p_dec->fmt_out.i_codec);
877
878     /* Enumerate components and build a list of the one we want to try */
879     p_sys->components =
880         CreateComponentsList(p_this,
881              GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec :
882                         p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat,
883                         p_sys->b_enc), p_sys->ppsz_components);
884     if( !p_sys->components )
885     {
886         msg_Warn( p_this, "couldn't find an omx component for codec %4.4s",
887                   (char *)&p_dec->fmt_in.i_codec );
888         CloseGeneric(p_this);
889         return VLC_EGENERIC;
890     }
891
892     /* Try to load and initialise a component */
893     omx_error = OMX_ErrorUndefined;
894     for(i = 0; i < p_sys->components; i++)
895     {
896 #ifdef __ANDROID__
897         /* ignore OpenCore software codecs */
898         if (!strncmp(p_sys->ppsz_components[i], "OMX.PV.", 7))
899             continue;
900         /* The same sw codecs, renamed in ICS (perhaps also in honeycomb) */
901         if (!strncmp(p_sys->ppsz_components[i], "OMX.google.", 11))
902             continue;
903         /* This one has been seen on HTC One V - it behaves like it works,
904          * but FillBufferDone returns buffers filled with 0 bytes. The One V
905          * has got a working OMX.qcom.video.decoder.avc instead though. */
906         if (!strncmp(p_sys->ppsz_components[i], "OMX.ARICENT.", 12))
907             continue;
908         /* Codecs with DRM, that don't output plain YUV data but only
909          * support direct rendering where the output can't be intercepted. */
910         if (strstr(p_sys->ppsz_components[i], ".secure"))
911             continue;
912         /* Use VC1 decoder for WMV3 for now */
913         if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.WMV.Decoder"))
914             continue;
915         /* This decoder does work, but has an insane latency (leading to errors
916          * about "main audio output playback way too late" and dropped frames).
917          * At least Samsung Galaxy S III (where this decoder is present) has
918          * got another one, OMX.SEC.mp3.dec, that works well and has a
919          * sensible latency. (Also, even if that one isn't found, in general,
920          * using SW codecs is usually more than fast enough for MP3.) */
921         if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.MP3.Decoder"))
922             continue;
923         /* This codec should be able to handle both VC1 and WMV3, but
924          * for VC1 it doesn't output any buffers at all (in the way we use
925          * it) and for WMV3 it outputs plain black buffers. Thus ignore
926          * it until we can make it work properly. */
927         if (!strcmp(p_sys->ppsz_components[i], "OMX.Nvidia.vc1.decode"))
928             continue;
929 #endif
930         omx_error = InitialiseComponent(p_dec, p_sys->ppsz_components[i],
931                                         &p_sys->omx_handle);
932         if(omx_error == OMX_ErrorNone) break;
933     }
934     CHECK_ERROR(omx_error, "no component could be initialised" );
935
936     /* Move component to Idle then Executing state */
937     OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0 );
938     CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
939
940     /* Allocate omx buffers */
941     for(i = 0; i < p_sys->ports; i++)
942     {
943         OmxPort *p_port = &p_sys->p_ports[i];
944
945         for(j = 0; j < p_port->i_buffers; j++)
946         {
947 #if 0
948 #define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
949             char *p_buf = malloc(p_port->definition.nBufferSize +
950                                  p_port->definition.nBufferAlignment);
951             p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
952 #endif
953
954             if(p_port->b_direct)
955                 omx_error =
956                     OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
957                                    p_port->i_port_index, 0,
958                                    p_port->definition.nBufferSize, (void*)1);
959             else
960                 omx_error =
961                     OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[j],
962                                         p_port->i_port_index, 0,
963                                         p_port->definition.nBufferSize);
964
965             if(omx_error != OMX_ErrorNone) break;
966             OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[j]);
967         }
968         p_port->i_buffers = j;
969         CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
970                     omx_error, (int)p_port->i_port_index, j );
971     }
972
973     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
974     CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
975
976     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet,
977                                  OMX_StateExecuting, 0);
978     CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x)", omx_error );
979     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
980     CHECK_ERROR(omx_error, "Wait for Executing failed (%x)", omx_error );
981
982     /* Send codec configuration data */
983     if( p_dec->fmt_in.i_extra )
984     {
985         OMX_FIFO_GET(&p_sys->in.fifo, p_header);
986         p_header->nFilledLen = p_dec->fmt_in.i_extra;
987
988         /* Convert H.264 NAL format to annex b */
989         if( p_sys->i_nal_size_length && !p_sys->in.b_direct )
990         {
991             p_header->nFilledLen = 0;
992             convert_sps_pps( p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
993                              p_header->pBuffer, p_header->nAllocLen,
994                              (uint32_t*) &p_header->nFilledLen, NULL );
995         }
996         else if(p_sys->in.b_direct)
997         {
998             p_header->pOutputPortPrivate = p_header->pBuffer;
999             p_header->pBuffer = p_dec->fmt_in.p_extra;
1000         }
1001         else if (p_dec->fmt_in.i_codec == VLC_CODEC_WMV3 &&
1002                  p_dec->fmt_in.i_extra >= 4 &&
1003                  p_header->nAllocLen >= 36)
1004         {
1005             int profile;
1006             // According to OMX IL 1.2.0 spec (4.3.33.2), the codec config
1007             // data for VC-1 Main/Simple (aka WMV3) is according to table 265
1008             // in the VC-1 spec. Most of the fields are just set with placeholders
1009             // (like framerate, hrd_buffer/rate).
1010             static const uint8_t wmv3seq[] = {
1011                 0xff, 0xff, 0xff, 0xc5, // numframes=ffffff, marker byte
1012                 0x04, 0x00, 0x00, 0x00, // marker byte
1013                 0x00, 0x00, 0x00, 0x00, // struct C, almost equal to p_extra
1014                 0x00, 0x00, 0x00, 0x00, // struct A, vert size
1015                 0x00, 0x00, 0x00, 0x00, // struct A, horiz size
1016                 0x0c, 0x00, 0x00, 0x00, // marker byte
1017                 0xff, 0xff, 0x00, 0x80, // struct B, level=4, cbr=0, hrd_buffer=ffff
1018                 0xff, 0xff, 0x00, 0x00, // struct B, hrd_rate=ffff
1019                 0xff, 0xff, 0xff, 0xff, // struct B, framerate=ffffffff
1020             };
1021             p_header->nFilledLen = sizeof(wmv3seq);
1022             memcpy(p_header->pBuffer, wmv3seq, p_header->nFilledLen);
1023             // Struct C - almost equal to the extradata
1024             memcpy(&p_header->pBuffer[8], p_dec->fmt_in.p_extra, 4);
1025             // Expand profile from the highest 2 bits to the highest 4 bits
1026             profile = p_header->pBuffer[8] >> 6;
1027             p_header->pBuffer[8] = (p_header->pBuffer[8] & 0x0f) | (profile << 4);
1028             // Fill in the height/width for struct A
1029             SetDWLE(&p_header->pBuffer[12], p_dec->fmt_in.video.i_height);
1030             SetDWLE(&p_header->pBuffer[16], p_dec->fmt_in.video.i_width);
1031         }
1032         else
1033         {
1034             if(p_header->nFilledLen > p_header->nAllocLen)
1035             {
1036                 msg_Dbg(p_dec, "buffer too small (%i,%i)", (int)p_header->nFilledLen,
1037                         (int)p_header->nAllocLen);
1038                 p_header->nFilledLen = p_header->nAllocLen;
1039             }
1040             memcpy(p_header->pBuffer, p_dec->fmt_in.p_extra, p_header->nFilledLen);
1041         }
1042
1043         p_header->nOffset = 0;
1044         p_header->nFlags = OMX_BUFFERFLAG_CODECCONFIG | OMX_BUFFERFLAG_ENDOFFRAME;
1045         msg_Dbg(p_dec, "sending codec config data %p, %p, %i", p_header,
1046                 p_header->pBuffer, (int)p_header->nFilledLen);
1047         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1048     }
1049
1050     /* Get back output port definition */
1051     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1052     if(omx_error != OMX_ErrorNone) goto error;
1053
1054     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1055     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1056
1057     if(p_sys->b_error) goto error;
1058
1059     p_dec->b_need_packetized = true;
1060
1061     if (!p_sys->b_use_pts)
1062         msg_Dbg( p_dec, "using dts timestamp mode for %s", p_sys->psz_component);
1063
1064     return VLC_SUCCESS;
1065
1066  error:
1067     CloseGeneric(p_this);
1068     return VLC_EGENERIC;
1069 }
1070
1071 /*****************************************************************************
1072  * PortReconfigure
1073  *****************************************************************************/
1074 static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
1075 {
1076     decoder_sys_t *p_sys = p_dec->p_sys;
1077     OMX_PARAM_PORTDEFINITIONTYPE definition;
1078     OMX_BUFFERHEADERTYPE *p_buffer;
1079     OMX_ERRORTYPE omx_error;
1080     unsigned int i;
1081
1082     /* Sanity checking */
1083     OMX_INIT_STRUCTURE(definition);
1084     definition.nPortIndex = p_port->i_port_index;
1085     omx_error = OMX_GetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1086                                  &definition);
1087     if(omx_error != OMX_ErrorNone || (p_dec->fmt_in.i_cat == VIDEO_ES &&
1088        (!definition.format.video.nFrameWidth ||
1089        !definition.format.video.nFrameHeight)) )
1090         return OMX_ErrorUndefined;
1091
1092     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortDisable,
1093                                  p_port->i_port_index, NULL);
1094     CHECK_ERROR(omx_error, "OMX_CommandPortDisable on %i failed (%x)",
1095                 (int)p_port->i_port_index, omx_error );
1096
1097     for(i = 0; i < p_port->i_buffers; i++)
1098     {
1099         OMX_FIFO_GET(&p_port->fifo, p_buffer);
1100         if (p_buffer->pAppPrivate != NULL)
1101             decoder_DeletePicture( p_dec, p_buffer->pAppPrivate );
1102         if (p_buffer->nFlags & SENTINEL_FLAG) {
1103             free(p_buffer);
1104             i--;
1105             continue;
1106         }
1107         omx_error = OMX_FreeBuffer( p_sys->omx_handle,
1108                                     p_port->i_port_index, p_buffer );
1109
1110         if(omx_error != OMX_ErrorNone) break;
1111     }
1112     CHECK_ERROR(omx_error, "OMX_FreeBuffer failed (%x, %i, %i)",
1113                 omx_error, (int)p_port->i_port_index, i );
1114
1115     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
1116     CHECK_ERROR(omx_error, "Wait for PortDisable failed (%x)", omx_error );
1117
1118     /* Get the new port definition */
1119     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1120     if(omx_error != OMX_ErrorNone) goto error;
1121
1122     if( p_dec->fmt_in.i_cat != AUDIO_ES )
1123     {
1124         /* Don't explicitly set the new parameters that we got with
1125          * OMX_GetParameter above when using audio codecs.
1126          * That struct hasn't been changed since, so there should be
1127          * no need to set it here, unless some codec expects the
1128          * SetParameter call as a trigger event for some part of
1129          * the reconfiguration.
1130          * This fixes using audio decoders on Samsung Galaxy S II,
1131          *
1132          * Only skipping this for audio codecs, to minimize the
1133          * change for current working configurations for video.
1134          */
1135         omx_error = OMX_SetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1136                                      &definition);
1137         CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
1138                     omx_error, ErrorToString(omx_error));
1139     }
1140
1141     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortEnable,
1142                                  p_port->i_port_index, NULL);
1143     CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
1144                 (int)p_port->i_port_index, omx_error );
1145
1146     if (p_port->definition.nBufferCountActual > p_port->i_buffers) {
1147         free(p_port->pp_buffers);
1148         p_port->pp_buffers = malloc(p_port->definition.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE*));
1149         if(!p_port->pp_buffers)
1150         {
1151             omx_error = OMX_ErrorInsufficientResources;
1152             CHECK_ERROR(omx_error, "memory allocation failed");
1153         }
1154     }
1155     p_port->i_buffers = p_port->definition.nBufferCountActual;
1156     for(i = 0; i < p_port->i_buffers; i++)
1157     {
1158         if(p_port->b_direct)
1159             omx_error =
1160                 OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1161                                p_port->i_port_index, 0,
1162                                p_port->definition.nBufferSize, (void*)1);
1163         else
1164             omx_error =
1165                 OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
1166                                     p_port->i_port_index, 0,
1167                                     p_port->definition.nBufferSize);
1168
1169         if(omx_error != OMX_ErrorNone) break;
1170         OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
1171     }
1172     p_port->i_buffers = i;
1173     CHECK_ERROR(omx_error, "OMX_UseBuffer failed (%x, %i, %i)",
1174                 omx_error, (int)p_port->i_port_index, i );
1175
1176     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
1177     CHECK_ERROR(omx_error, "Wait for PortEnable failed (%x)", omx_error );
1178
1179     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1180     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1181
1182  error:
1183     return omx_error;
1184 }
1185
1186 /*****************************************************************************
1187  * DecodeVideo: Called to decode one frame
1188  *****************************************************************************/
1189 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
1190 {
1191     decoder_sys_t *p_sys = p_dec->p_sys;
1192     picture_t *p_pic = NULL, *p_next_pic;
1193     OMX_ERRORTYPE omx_error;
1194     unsigned int i;
1195
1196     OMX_BUFFERHEADERTYPE *p_header;
1197     block_t *p_block;
1198     unsigned int i_input_used = 0;
1199     struct H264ConvertState convert_state = { 0, 0 };
1200
1201     if( !pp_block || !*pp_block )
1202         return NULL;
1203
1204     p_block = *pp_block;
1205
1206     /* Check for errors from codec */
1207     if(p_sys->b_error)
1208     {
1209         msg_Dbg(p_dec, "error during decoding");
1210         block_Release( p_block );
1211         return 0;
1212     }
1213
1214     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1215     {
1216         block_Release( p_block );
1217         if(!p_sys->in.b_flushed)
1218         {
1219             msg_Dbg(p_dec, "flushing");
1220             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1221                              p_sys->in.definition.nPortIndex, 0 );
1222         }
1223         p_sys->in.b_flushed = true;
1224         return NULL;
1225     }
1226
1227     /* Use the aspect ratio provided by the input (ie read from packetizer).
1228      * In case the we get aspect ratio info from the decoder (as in the
1229      * broadcom OMX implementation on RPi), don't let the packetizer values
1230      * override what the decoder says, if anything - otherwise always update
1231      * even if it already is set (since it can change within a stream). */
1232     if((p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) &&
1233        (p_dec->fmt_out.video.i_sar_num == 0 || p_dec->fmt_out.video.i_sar_den == 0 ||
1234              !p_sys->b_aspect_ratio_handled))
1235     {
1236         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
1237         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
1238     }
1239
1240     /* Take care of decoded frames first */
1241     while(!p_pic)
1242     {
1243         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1244         if(!p_header) break; /* No frame available */
1245
1246         if(p_sys->out.b_update_def)
1247         {
1248             omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1249             p_sys->out.b_update_def = 0;
1250         }
1251
1252         if(p_header->nFilledLen)
1253         {
1254             p_pic = p_header->pAppPrivate;
1255             if(!p_pic)
1256             {
1257                 /* We're not in direct rendering mode.
1258                  * Get a new picture and copy the content */
1259                 p_pic = decoder_NewPicture( p_dec );
1260
1261                 if (p_pic)
1262                     CopyOmxPicture(p_sys->out.definition.format.video.eColorFormat,
1263                                    p_pic, p_sys->out.definition.format.video.nSliceHeight,
1264                                    p_sys->out.i_frame_stride,
1265                                    p_header->pBuffer + p_header->nOffset,
1266                                    p_sys->out.i_frame_stride_chroma_div, NULL);
1267             }
1268
1269             if (p_pic)
1270                 p_pic->date = FromOmxTicks(p_header->nTimeStamp);
1271             p_header->nFilledLen = 0;
1272             p_header->pAppPrivate = 0;
1273         }
1274
1275         /* Get a new picture */
1276         if(p_sys->out.b_direct && !p_header->pAppPrivate)
1277         {
1278             p_next_pic = decoder_NewPicture( p_dec );
1279             if(!p_next_pic) break;
1280
1281             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1282             p_header->pAppPrivate = p_next_pic;
1283             p_header->pInputPortPrivate = p_header->pBuffer;
1284             p_header->pBuffer = p_next_pic->p[0].p_pixels;
1285         }
1286         else
1287         {
1288             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1289         }
1290
1291 #ifdef OMXIL_EXTRA_DEBUG
1292         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1293 #endif
1294         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1295     }
1296
1297 more_input:
1298     /* Send the input buffer to the component */
1299     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1300
1301     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1302         free(p_header);
1303         goto reconfig;
1304     }
1305
1306     if(p_header)
1307     {
1308         bool decode_more = false;
1309         p_header->nFilledLen = p_block->i_buffer - i_input_used;
1310         p_header->nOffset = 0;
1311         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1312         if (p_sys->b_use_pts && p_block->i_pts)
1313             p_header->nTimeStamp = ToOmxTicks(p_block->i_pts);
1314         else
1315             p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1316
1317         /* In direct mode we pass the input pointer as is.
1318          * Otherwise we memcopy the data */
1319         if(p_sys->in.b_direct)
1320         {
1321             p_header->pOutputPortPrivate = p_header->pBuffer;
1322             p_header->pBuffer = p_block->p_buffer;
1323             p_header->pAppPrivate = p_block;
1324             i_input_used = p_header->nFilledLen;
1325         }
1326         else
1327         {
1328             if(p_header->nFilledLen > p_header->nAllocLen)
1329             {
1330                 p_header->nFilledLen = p_header->nAllocLen;
1331             }
1332             memcpy(p_header->pBuffer, p_block->p_buffer + i_input_used, p_header->nFilledLen);
1333             i_input_used += p_header->nFilledLen;
1334             if (i_input_used == p_block->i_buffer)
1335             {
1336                 block_Release(p_block);
1337             }
1338             else
1339             {
1340                 decode_more = true;
1341                 p_header->nFlags &= ~OMX_BUFFERFLAG_ENDOFFRAME;
1342             }
1343         }
1344
1345         /* Convert H.264 NAL format to annex b. Doesn't do anything if
1346          * i_nal_size_length == 0, which is the case for codecs other
1347          * than H.264 */
1348         convert_h264_to_annexb( p_header->pBuffer, p_header->nFilledLen,
1349                                 p_sys->i_nal_size_length, &convert_state );
1350 #ifdef OMXIL_EXTRA_DEBUG
1351         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i, %"PRId64, p_header, p_header->pBuffer,
1352                  (int)p_header->nFilledLen, FromOmxTicks(p_header->nTimeStamp) );
1353 #endif
1354         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1355         p_sys->in.b_flushed = false;
1356         if (decode_more)
1357             goto more_input;
1358         else
1359             *pp_block = NULL; /* Avoid being fed the same packet again */
1360     }
1361
1362 reconfig:
1363     /* Handle the PortSettingsChanged events */
1364     for(i = 0; i < p_sys->ports; i++)
1365     {
1366         OmxPort *p_port = &p_sys->p_ports[i];
1367         if(p_port->b_reconfigure)
1368         {
1369             omx_error = PortReconfigure(p_dec, p_port);
1370             p_port->b_reconfigure = 0;
1371         }
1372         if(p_port->b_update_def)
1373         {
1374             omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1375             p_port->b_update_def = 0;
1376         }
1377     }
1378
1379     return p_pic;
1380 }
1381
1382 /*****************************************************************************
1383  * DecodeAudio: Called to decode one frame
1384  *****************************************************************************/
1385 block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1386 {
1387     decoder_sys_t *p_sys = p_dec->p_sys;
1388     block_t *p_buffer = NULL;
1389     OMX_BUFFERHEADERTYPE *p_header;
1390     OMX_ERRORTYPE omx_error;
1391     block_t *p_block;
1392     unsigned int i;
1393
1394     if( !pp_block || !*pp_block ) return NULL;
1395
1396     p_block = *pp_block;
1397
1398     /* Check for errors from codec */
1399     if(p_sys->b_error)
1400     {
1401         msg_Dbg(p_dec, "error during decoding");
1402         block_Release( p_block );
1403         return 0;
1404     }
1405
1406     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1407     {
1408         block_Release( p_block );
1409         date_Set( &p_sys->end_date, 0 );
1410         if(!p_sys->in.b_flushed)
1411         {
1412             msg_Dbg(p_dec, "flushing");
1413             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1414                              p_sys->in.definition.nPortIndex, 0 );
1415         }
1416         p_sys->in.b_flushed = true;
1417         return NULL;
1418     }
1419
1420     if( !date_Get( &p_sys->end_date ) )
1421     {
1422         if( !p_block->i_pts )
1423         {
1424             /* We've just started the stream, wait for the first PTS. */
1425             block_Release( p_block );
1426             return NULL;
1427         }
1428         date_Set( &p_sys->end_date, p_block->i_pts );
1429     }
1430
1431     /* Take care of decoded frames first */
1432     while(!p_buffer)
1433     {
1434         unsigned int i_samples = 0;
1435
1436         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1437         if(!p_header) break; /* No frame available */
1438
1439         if (p_sys->out.p_fmt->audio.i_channels)
1440             i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1441         if(i_samples)
1442         {
1443             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1444             if( !p_buffer ) break; /* No audio buffer available */
1445
1446             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1447             p_header->nFilledLen = 0;
1448
1449             int64_t timestamp = FromOmxTicks(p_header->nTimeStamp);
1450             if( timestamp != 0 &&
1451                 timestamp != date_Get( &p_sys->end_date ) )
1452                 date_Set( &p_sys->end_date, timestamp );
1453
1454             p_buffer->i_pts = date_Get( &p_sys->end_date );
1455             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1456                 p_buffer->i_pts;
1457         }
1458
1459 #ifdef OMXIL_EXTRA_DEBUG
1460         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1461 #endif
1462         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1463         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1464     }
1465
1466
1467     /* Send the input buffer to the component */
1468     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1469
1470     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1471         free(p_header);
1472         goto reconfig;
1473     }
1474
1475     if(p_header)
1476     {
1477         p_header->nFilledLen = p_block->i_buffer;
1478         p_header->nOffset = 0;
1479         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1480         p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1481
1482         /* In direct mode we pass the input pointer as is.
1483          * Otherwise we memcopy the data */
1484         if(p_sys->in.b_direct)
1485         {
1486             p_header->pOutputPortPrivate = p_header->pBuffer;
1487             p_header->pBuffer = p_block->p_buffer;
1488             p_header->pAppPrivate = p_block;
1489         }
1490         else
1491         {
1492             if(p_header->nFilledLen > p_header->nAllocLen)
1493             {
1494                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1495                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1496                 p_header->nFilledLen = p_header->nAllocLen;
1497             }
1498             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1499             block_Release(p_block);
1500         }
1501
1502 #ifdef OMXIL_EXTRA_DEBUG
1503         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1504                  (int)p_header->nFilledLen );
1505 #endif
1506         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1507         p_sys->in.b_flushed = false;
1508         *pp_block = NULL; /* Avoid being fed the same packet again */
1509     }
1510
1511 reconfig:
1512     /* Handle the PortSettingsChanged events */
1513     for(i = 0; i < p_sys->ports; i++)
1514     {
1515         OmxPort *p_port = &p_sys->p_ports[i];
1516         if(!p_port->b_reconfigure) continue;
1517         p_port->b_reconfigure = 0;
1518         omx_error = PortReconfigure(p_dec, p_port);
1519     }
1520
1521     return p_buffer;
1522 }
1523
1524 /*****************************************************************************
1525  * EncodeVideo: Called to encode one frame
1526  *****************************************************************************/
1527 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1528 {
1529     decoder_t *p_dec = ( decoder_t *)p_enc;
1530     decoder_sys_t *p_sys = p_dec->p_sys;
1531     OMX_ERRORTYPE omx_error;
1532     unsigned int i;
1533
1534     OMX_BUFFERHEADERTYPE *p_header;
1535     block_t *p_block = 0;
1536
1537     if( !p_pic ) return NULL;
1538
1539     /* Check for errors from codec */
1540     if(p_sys->b_error)
1541     {
1542         msg_Dbg(p_dec, "error during encoding");
1543         return NULL;
1544     }
1545
1546     /* Send the input buffer to the component */
1547     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1548     if(p_header)
1549     {
1550         /* In direct mode we pass the input pointer as is.
1551          * Otherwise we memcopy the data */
1552         if(p_sys->in.b_direct)
1553         {
1554             p_header->pOutputPortPrivate = p_header->pBuffer;
1555             p_header->pBuffer = p_pic->p[0].p_pixels;
1556         }
1557         else
1558         {
1559             CopyVlcPicture(p_dec, p_header, p_pic);
1560         }
1561
1562         p_header->nFilledLen = p_sys->in.i_frame_size;
1563         p_header->nOffset = 0;
1564         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1565         p_header->nTimeStamp = ToOmxTicks(p_pic->date);
1566 #ifdef OMXIL_EXTRA_DEBUG
1567         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1568                  (int)p_header->nFilledLen );
1569 #endif
1570         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1571         p_sys->in.b_flushed = false;
1572     }
1573
1574     /* Handle the PortSettingsChanged events */
1575     for(i = 0; i < p_sys->ports; i++)
1576     {
1577         OmxPort *p_port = &p_sys->p_ports[i];
1578         if(!p_port->b_reconfigure) continue;
1579         p_port->b_reconfigure = 0;
1580         omx_error = PortReconfigure(p_dec, p_port);
1581     }
1582
1583     /* Wait for the decoded frame */
1584     while(!p_block)
1585     {
1586         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1587
1588         if(p_header->nFilledLen)
1589         {
1590             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1591             {
1592                 /* TODO: need to store codec config */
1593                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1594             }
1595
1596             p_block = p_header->pAppPrivate;
1597             if(!p_block)
1598             {
1599                 /* We're not in direct rendering mode.
1600                  * Get a new block and copy the content */
1601                 p_block = block_Alloc( p_header->nFilledLen );
1602                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1603             }
1604
1605             p_block->i_buffer = p_header->nFilledLen;
1606             p_block->i_pts = p_block->i_dts = FromOmxTicks(p_header->nTimeStamp);
1607             p_header->nFilledLen = 0;
1608             p_header->pAppPrivate = 0;
1609         }
1610
1611 #ifdef OMXIL_EXTRA_DEBUG
1612         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1613 #endif
1614         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1615     }
1616
1617     msg_Dbg(p_dec, "done");
1618     return p_block;
1619 }
1620
1621 /*****************************************************************************
1622  * CloseGeneric: omxil decoder destruction
1623  *****************************************************************************/
1624 static void CloseGeneric( vlc_object_t *p_this )
1625 {
1626     decoder_t *p_dec = (decoder_t *)p_this;
1627     decoder_sys_t *p_sys = p_dec->p_sys;
1628
1629     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1630
1631     DeinitOmxCore();
1632
1633     DeinitOmxEventQueue(&p_sys->event_queue);
1634     vlc_mutex_destroy (&p_sys->in.fifo.lock);
1635     vlc_cond_destroy (&p_sys->in.fifo.wait);
1636     vlc_mutex_destroy (&p_sys->out.fifo.lock);
1637     vlc_cond_destroy (&p_sys->out.fifo.wait);
1638
1639     free( p_sys );
1640 }
1641
1642 /*****************************************************************************
1643  * OmxEventHandler:
1644  *****************************************************************************/
1645 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1646     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1647     OMX_U32 data_2, OMX_PTR event_data )
1648 {
1649     decoder_t *p_dec = (decoder_t *)app_data;
1650     decoder_sys_t *p_sys = p_dec->p_sys;
1651     unsigned int i;
1652     (void)omx_handle;
1653
1654     PrintOmxEvent((vlc_object_t *) p_dec, event, data_1, data_2, event_data);
1655     switch (event)
1656     {
1657     case OMX_EventError:
1658         //p_sys->b_error = true;
1659         break;
1660
1661     case OMX_EventPortSettingsChanged:
1662         if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition ||
1663             data_2 == OMX_IndexParamAudioPcm )
1664         {
1665             OMX_BUFFERHEADERTYPE *sentinel;
1666             for(i = 0; i < p_sys->ports; i++)
1667                 if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1668                     p_sys->p_ports[i].b_reconfigure = true;
1669             sentinel = calloc(1, sizeof(*sentinel));
1670             if (sentinel) {
1671                 sentinel->nFlags = SENTINEL_FLAG;
1672                 OMX_FIFO_PUT(&p_sys->in.fifo, sentinel);
1673             }
1674         }
1675         else if( data_2 == OMX_IndexConfigCommonOutputCrop )
1676         {
1677             for(i = 0; i < p_sys->ports; i++)
1678                 if(p_sys->p_ports[i].definition.nPortIndex == data_1)
1679                     p_sys->p_ports[i].b_update_def = true;
1680         }
1681         else
1682         {
1683             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
1684         }
1685         break;
1686     case OMX_EventParamOrConfigChanged:
1687         UpdatePixelAspect(p_dec);
1688         break;
1689
1690     default:
1691         break;
1692     }
1693
1694     PostOmxEvent(&p_sys->event_queue, event, data_1, data_2, event_data);
1695     return OMX_ErrorNone;
1696 }
1697
1698 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1699     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1700 {
1701     decoder_t *p_dec = (decoder_t *)app_data;
1702     decoder_sys_t *p_sys = p_dec->p_sys;
1703     (void)omx_handle;
1704
1705 #ifdef OMXIL_EXTRA_DEBUG
1706     msg_Dbg( p_dec, "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1707 #endif
1708
1709     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1710     {
1711         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1712         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1713         if(p_block) block_Release(p_block);
1714         omx_header->pAppPrivate = 0;
1715     }
1716     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1717
1718     return OMX_ErrorNone;
1719 }
1720
1721 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1722     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1723 {
1724     decoder_t *p_dec = (decoder_t *)app_data;
1725     decoder_sys_t *p_sys = p_dec->p_sys;
1726     (void)omx_handle;
1727
1728 #ifdef OMXIL_EXTRA_DEBUG
1729     msg_Dbg( p_dec, "OmxFillBufferDone %p, %p, %i, %"PRId64, omx_header, omx_header->pBuffer,
1730              (int)omx_header->nFilledLen, FromOmxTicks(omx_header->nTimeStamp) );
1731 #endif
1732
1733     if(omx_header->pInputPortPrivate)
1734     {
1735         omx_header->pBuffer = omx_header->pInputPortPrivate;
1736     }
1737     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1738
1739     return OMX_ErrorNone;
1740 }