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