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