]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
omxil: factorize FreeBuffers and AllocateBuffers
[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  * DecodeVideo: Called to decode one frame
1200  *****************************************************************************/
1201 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
1202 {
1203     decoder_sys_t *p_sys = p_dec->p_sys;
1204     picture_t *p_pic = NULL, *p_next_pic;
1205     OMX_ERRORTYPE omx_error;
1206     unsigned int i;
1207
1208     OMX_BUFFERHEADERTYPE *p_header;
1209     block_t *p_block;
1210     unsigned int i_input_used = 0;
1211     struct H264ConvertState convert_state = { 0, 0 };
1212
1213     if( !pp_block || !*pp_block )
1214         return NULL;
1215
1216     p_block = *pp_block;
1217
1218     /* Check for errors from codec */
1219     if(p_sys->b_error)
1220     {
1221         msg_Dbg(p_dec, "error during decoding");
1222         block_Release( p_block );
1223         return 0;
1224     }
1225
1226     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1227     {
1228         block_Release( p_block );
1229         if(!p_sys->in.b_flushed)
1230         {
1231             msg_Dbg(p_dec, "flushing");
1232             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1233                              p_sys->in.definition.nPortIndex, 0 );
1234         }
1235         p_sys->in.b_flushed = true;
1236         return NULL;
1237     }
1238
1239     /* Use the aspect ratio provided by the input (ie read from packetizer).
1240      * In case the we get aspect ratio info from the decoder (as in the
1241      * broadcom OMX implementation on RPi), don't let the packetizer values
1242      * override what the decoder says, if anything - otherwise always update
1243      * even if it already is set (since it can change within a stream). */
1244     if((p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) &&
1245        (p_dec->fmt_out.video.i_sar_num == 0 || p_dec->fmt_out.video.i_sar_den == 0 ||
1246              !p_sys->b_aspect_ratio_handled))
1247     {
1248         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
1249         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
1250     }
1251
1252     /* Take care of decoded frames first */
1253     while(!p_pic)
1254     {
1255         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1256         if(!p_header) break; /* No frame available */
1257
1258         if(p_sys->out.b_update_def)
1259         {
1260             omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1261             p_sys->out.b_update_def = 0;
1262             CHECK_ERROR(omx_error, "GetPortDefinition failed");
1263         }
1264
1265         if(p_header->nFilledLen)
1266         {
1267             p_pic = p_header->pAppPrivate;
1268             if(!p_pic)
1269             {
1270                 /* We're not in direct rendering mode.
1271                  * Get a new picture and copy the content */
1272                 p_pic = decoder_NewPicture( p_dec );
1273
1274                 if (p_pic)
1275                     CopyOmxPicture(p_sys->out.definition.format.video.eColorFormat,
1276                                    p_pic, p_sys->out.definition.format.video.nSliceHeight,
1277                                    p_sys->out.i_frame_stride,
1278                                    p_header->pBuffer + p_header->nOffset,
1279                                    p_sys->out.i_frame_stride_chroma_div, NULL);
1280             }
1281
1282             if (p_pic)
1283                 p_pic->date = FromOmxTicks(p_header->nTimeStamp);
1284             p_header->nFilledLen = 0;
1285             p_header->pAppPrivate = 0;
1286         }
1287
1288         /* Get a new picture */
1289         if(p_sys->out.b_direct && !p_header->pAppPrivate)
1290         {
1291             p_next_pic = decoder_NewPicture( p_dec );
1292             if(!p_next_pic) break;
1293
1294             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1295             p_header->pAppPrivate = p_next_pic;
1296             p_header->pInputPortPrivate = p_header->pBuffer;
1297             p_header->pBuffer = p_next_pic->p[0].p_pixels;
1298         }
1299         else
1300         {
1301             OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1302         }
1303
1304 #ifdef OMXIL_EXTRA_DEBUG
1305         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1306 #endif
1307         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1308     }
1309
1310 more_input:
1311     /* Send the input buffer to the component */
1312     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1313
1314     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1315         free(p_header);
1316         goto reconfig;
1317     }
1318
1319     if(p_header)
1320     {
1321         bool decode_more = false;
1322         p_header->nFilledLen = p_block->i_buffer - i_input_used;
1323         p_header->nOffset = 0;
1324         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1325         if (p_sys->b_use_pts && p_block->i_pts)
1326             p_header->nTimeStamp = ToOmxTicks(p_block->i_pts);
1327         else
1328             p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1329
1330         /* In direct mode we pass the input pointer as is.
1331          * Otherwise we memcopy the data */
1332         if(p_sys->in.b_direct)
1333         {
1334             p_header->pOutputPortPrivate = p_header->pBuffer;
1335             p_header->pBuffer = p_block->p_buffer;
1336             p_header->pAppPrivate = p_block;
1337             i_input_used = p_header->nFilledLen;
1338         }
1339         else
1340         {
1341             if(p_header->nFilledLen > p_header->nAllocLen)
1342             {
1343                 p_header->nFilledLen = p_header->nAllocLen;
1344             }
1345             memcpy(p_header->pBuffer, p_block->p_buffer + i_input_used, p_header->nFilledLen);
1346             i_input_used += p_header->nFilledLen;
1347             if (i_input_used == p_block->i_buffer)
1348             {
1349                 block_Release(p_block);
1350             }
1351             else
1352             {
1353                 decode_more = true;
1354                 p_header->nFlags &= ~OMX_BUFFERFLAG_ENDOFFRAME;
1355             }
1356         }
1357
1358         /* Convert H.264 NAL format to annex b. Doesn't do anything if
1359          * i_nal_size_length == 0, which is the case for codecs other
1360          * than H.264 */
1361         convert_h264_to_annexb( p_header->pBuffer, p_header->nFilledLen,
1362                                 p_sys->i_nal_size_length, &convert_state );
1363 #ifdef OMXIL_EXTRA_DEBUG
1364         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i, %"PRId64, p_header, p_header->pBuffer,
1365                  (int)p_header->nFilledLen, FromOmxTicks(p_header->nTimeStamp) );
1366 #endif
1367         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1368         p_sys->in.b_flushed = false;
1369         if (decode_more)
1370             goto more_input;
1371         else
1372             *pp_block = NULL; /* Avoid being fed the same packet again */
1373     }
1374
1375 reconfig:
1376     /* Handle the PortSettingsChanged events */
1377     for(i = 0; i < p_sys->ports; i++)
1378     {
1379         OmxPort *p_port = &p_sys->p_ports[i];
1380         if(p_port->b_reconfigure)
1381         {
1382             omx_error = PortReconfigure(p_dec, p_port);
1383             p_port->b_reconfigure = 0;
1384             CHECK_ERROR(omx_error, "PortReconfigure failed");
1385         }
1386         if(p_port->b_update_def)
1387         {
1388             omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1389             p_port->b_update_def = 0;
1390             CHECK_ERROR(omx_error, "GetPortDefinition failed");
1391         }
1392     }
1393
1394     return p_pic;
1395 error:
1396     p_sys->b_error = true;
1397     return NULL;
1398 }
1399
1400 /*****************************************************************************
1401  * DecodeAudio: Called to decode one frame
1402  *****************************************************************************/
1403 block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1404 {
1405     decoder_sys_t *p_sys = p_dec->p_sys;
1406     block_t *p_buffer = NULL;
1407     OMX_BUFFERHEADERTYPE *p_header;
1408     OMX_ERRORTYPE omx_error;
1409     block_t *p_block;
1410     unsigned int i;
1411
1412     if( !pp_block || !*pp_block ) return NULL;
1413
1414     p_block = *pp_block;
1415
1416     /* Check for errors from codec */
1417     if(p_sys->b_error)
1418     {
1419         msg_Dbg(p_dec, "error during decoding");
1420         block_Release( p_block );
1421         return 0;
1422     }
1423
1424     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1425     {
1426         block_Release( p_block );
1427         date_Set( &p_sys->end_date, 0 );
1428         if(!p_sys->in.b_flushed)
1429         {
1430             msg_Dbg(p_dec, "flushing");
1431             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1432                              p_sys->in.definition.nPortIndex, 0 );
1433         }
1434         p_sys->in.b_flushed = true;
1435         return NULL;
1436     }
1437
1438     if( !date_Get( &p_sys->end_date ) )
1439     {
1440         if( !p_block->i_pts )
1441         {
1442             /* We've just started the stream, wait for the first PTS. */
1443             block_Release( p_block );
1444             return NULL;
1445         }
1446         date_Set( &p_sys->end_date, p_block->i_pts );
1447     }
1448
1449     /* Take care of decoded frames first */
1450     while(!p_buffer)
1451     {
1452         unsigned int i_samples = 0;
1453
1454         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1455         if(!p_header) break; /* No frame available */
1456
1457         if (p_sys->out.p_fmt->audio.i_channels)
1458             i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1459         if(i_samples)
1460         {
1461             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1462             if( !p_buffer ) break; /* No audio buffer available */
1463
1464             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1465             p_header->nFilledLen = 0;
1466
1467             int64_t timestamp = FromOmxTicks(p_header->nTimeStamp);
1468             if( timestamp != 0 &&
1469                 timestamp != date_Get( &p_sys->end_date ) )
1470                 date_Set( &p_sys->end_date, timestamp );
1471
1472             p_buffer->i_pts = date_Get( &p_sys->end_date );
1473             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1474                 p_buffer->i_pts;
1475         }
1476
1477 #ifdef OMXIL_EXTRA_DEBUG
1478         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1479 #endif
1480         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1481         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1482     }
1483
1484
1485     /* Send the input buffer to the component */
1486     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1487
1488     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1489         free(p_header);
1490         goto reconfig;
1491     }
1492
1493     if(p_header)
1494     {
1495         p_header->nFilledLen = p_block->i_buffer;
1496         p_header->nOffset = 0;
1497         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1498         p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1499
1500         /* In direct mode we pass the input pointer as is.
1501          * Otherwise we memcopy the data */
1502         if(p_sys->in.b_direct)
1503         {
1504             p_header->pOutputPortPrivate = p_header->pBuffer;
1505             p_header->pBuffer = p_block->p_buffer;
1506             p_header->pAppPrivate = p_block;
1507         }
1508         else
1509         {
1510             if(p_header->nFilledLen > p_header->nAllocLen)
1511             {
1512                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1513                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1514                 p_header->nFilledLen = p_header->nAllocLen;
1515             }
1516             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1517             block_Release(p_block);
1518         }
1519
1520 #ifdef OMXIL_EXTRA_DEBUG
1521         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1522                  (int)p_header->nFilledLen );
1523 #endif
1524         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1525         p_sys->in.b_flushed = false;
1526         *pp_block = NULL; /* Avoid being fed the same packet again */
1527     }
1528
1529 reconfig:
1530     /* Handle the PortSettingsChanged events */
1531     for(i = 0; i < p_sys->ports; i++)
1532     {
1533         OmxPort *p_port = &p_sys->p_ports[i];
1534         if(!p_port->b_reconfigure) continue;
1535         p_port->b_reconfigure = 0;
1536         omx_error = PortReconfigure(p_dec, p_port);
1537         CHECK_ERROR(omx_error, "PortReconfigure failed");
1538     }
1539
1540     return p_buffer;
1541 error:
1542     p_sys->b_error = true;
1543     return NULL;
1544 }
1545
1546 /*****************************************************************************
1547  * EncodeVideo: Called to encode one frame
1548  *****************************************************************************/
1549 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1550 {
1551     decoder_t *p_dec = ( decoder_t *)p_enc;
1552     decoder_sys_t *p_sys = p_dec->p_sys;
1553     OMX_ERRORTYPE omx_error;
1554     unsigned int i;
1555
1556     OMX_BUFFERHEADERTYPE *p_header;
1557     block_t *p_block = 0;
1558
1559     if( !p_pic ) return NULL;
1560
1561     /* Check for errors from codec */
1562     if(p_sys->b_error)
1563     {
1564         msg_Dbg(p_dec, "error during encoding");
1565         return NULL;
1566     }
1567
1568     /* Send the input buffer to the component */
1569     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1570     if(p_header)
1571     {
1572         /* In direct mode we pass the input pointer as is.
1573          * Otherwise we memcopy the data */
1574         if(p_sys->in.b_direct)
1575         {
1576             p_header->pOutputPortPrivate = p_header->pBuffer;
1577             p_header->pBuffer = p_pic->p[0].p_pixels;
1578         }
1579         else
1580         {
1581             CopyVlcPicture(p_dec, p_header, p_pic);
1582         }
1583
1584         p_header->nFilledLen = p_sys->in.i_frame_size;
1585         p_header->nOffset = 0;
1586         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1587         p_header->nTimeStamp = ToOmxTicks(p_pic->date);
1588 #ifdef OMXIL_EXTRA_DEBUG
1589         msg_Dbg( p_dec, "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1590                  (int)p_header->nFilledLen );
1591 #endif
1592         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1593         p_sys->in.b_flushed = false;
1594     }
1595
1596     /* Handle the PortSettingsChanged events */
1597     for(i = 0; i < p_sys->ports; i++)
1598     {
1599         OmxPort *p_port = &p_sys->p_ports[i];
1600         if(!p_port->b_reconfigure) continue;
1601         p_port->b_reconfigure = 0;
1602         omx_error = PortReconfigure(p_dec, p_port);
1603         CHECK_ERROR(omx_error, "PortReconfigure failed");
1604     }
1605
1606     /* Wait for the decoded frame */
1607     while(!p_block)
1608     {
1609         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1610
1611         if(p_header->nFilledLen)
1612         {
1613             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1614             {
1615                 /* TODO: need to store codec config */
1616                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1617             }
1618
1619             p_block = p_header->pAppPrivate;
1620             if(!p_block)
1621             {
1622                 /* We're not in direct rendering mode.
1623                  * Get a new block and copy the content */
1624                 p_block = block_Alloc( p_header->nFilledLen );
1625                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1626             }
1627
1628             p_block->i_buffer = p_header->nFilledLen;
1629             p_block->i_pts = p_block->i_dts = FromOmxTicks(p_header->nTimeStamp);
1630             p_header->nFilledLen = 0;
1631             p_header->pAppPrivate = 0;
1632         }
1633
1634 #ifdef OMXIL_EXTRA_DEBUG
1635         msg_Dbg( p_dec, "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1636 #endif
1637         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1638     }
1639
1640     msg_Dbg(p_dec, "done");
1641     return p_block;
1642 error:
1643     p_sys->b_error = true;
1644     return NULL;
1645 }
1646
1647 /*****************************************************************************
1648  * CloseGeneric: omxil decoder destruction
1649  *****************************************************************************/
1650 static void CloseGeneric( vlc_object_t *p_this )
1651 {
1652     decoder_t *p_dec = (decoder_t *)p_this;
1653     decoder_sys_t *p_sys = p_dec->p_sys;
1654
1655     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1656
1657     DeinitOmxCore();
1658
1659     DeinitOmxEventQueue(&p_sys->event_queue);
1660
1661     OMX_FIFO_DESTROY( &p_sys->in.fifo );
1662     OMX_FIFO_DESTROY( &p_sys->out.fifo );
1663
1664     free( p_sys );
1665 }
1666
1667 /*****************************************************************************
1668  * OmxEventHandler:
1669  *****************************************************************************/
1670 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1671     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1672     OMX_U32 data_2, OMX_PTR event_data )
1673 {
1674     decoder_t *p_dec = (decoder_t *)app_data;
1675     decoder_sys_t *p_sys = p_dec->p_sys;
1676     unsigned int i;
1677     (void)omx_handle;
1678
1679     PrintOmxEvent((vlc_object_t *) p_dec, event, data_1, data_2, event_data);
1680     switch (event)
1681     {
1682     case OMX_EventError:
1683         //p_sys->b_error = true;
1684         break;
1685
1686     case OMX_EventPortSettingsChanged:
1687         if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition ||
1688             data_2 == OMX_IndexParamAudioPcm )
1689         {
1690             OMX_BUFFERHEADERTYPE *sentinel;
1691             for(i = 0; i < p_sys->ports; i++)
1692                 if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1693                     p_sys->p_ports[i].b_reconfigure = true;
1694             sentinel = calloc(1, sizeof(*sentinel));
1695             if (sentinel) {
1696                 sentinel->nFlags = SENTINEL_FLAG;
1697                 OMX_FIFO_PUT(&p_sys->in.fifo, sentinel);
1698             }
1699         }
1700         else if( data_2 == OMX_IndexConfigCommonOutputCrop )
1701         {
1702             for(i = 0; i < p_sys->ports; i++)
1703                 if(p_sys->p_ports[i].definition.nPortIndex == data_1)
1704                     p_sys->p_ports[i].b_update_def = true;
1705         }
1706         else
1707         {
1708             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
1709         }
1710         break;
1711     case OMX_EventParamOrConfigChanged:
1712         UpdatePixelAspect(p_dec);
1713         break;
1714
1715     default:
1716         break;
1717     }
1718
1719     PostOmxEvent(&p_sys->event_queue, event, data_1, data_2, event_data);
1720     return OMX_ErrorNone;
1721 }
1722
1723 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1724     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1725 {
1726     decoder_t *p_dec = (decoder_t *)app_data;
1727     decoder_sys_t *p_sys = p_dec->p_sys;
1728     (void)omx_handle;
1729
1730 #ifdef OMXIL_EXTRA_DEBUG
1731     msg_Dbg( p_dec, "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1732 #endif
1733
1734     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1735     {
1736         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1737         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1738         if(p_block) block_Release(p_block);
1739         omx_header->pAppPrivate = 0;
1740     }
1741     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1742
1743     return OMX_ErrorNone;
1744 }
1745
1746 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1747     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1748 {
1749     decoder_t *p_dec = (decoder_t *)app_data;
1750     decoder_sys_t *p_sys = p_dec->p_sys;
1751     (void)omx_handle;
1752
1753 #ifdef OMXIL_EXTRA_DEBUG
1754     msg_Dbg( p_dec, "OmxFillBufferDone %p, %p, %i, %"PRId64, omx_header, omx_header->pBuffer,
1755              (int)omx_header->nFilledLen, FromOmxTicks(omx_header->nTimeStamp) );
1756 #endif
1757
1758     if(omx_header->pInputPortPrivate)
1759     {
1760         omx_header->pBuffer = omx_header->pInputPortPrivate;
1761     }
1762     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1763
1764     return OMX_ErrorNone;
1765 }