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