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