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