]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
iomx: Move hal_format overriding into iomx_hwbuffer
[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 #if defined(USE_IOMX)
45 #include <dlfcn.h>
46 #include <jni.h>
47 #include "android_opaque.h"
48 #endif
49
50 #ifndef NDEBUG
51 # define OMX_DBG(...) msg_Dbg( p_dec, __VA_ARGS__ )
52 #else
53 # define OMX_DBG(...)
54 #endif
55
56 #define SENTINEL_FLAG 0x10000
57
58 /* Defined in the broadcom version of OMX_Index.h */
59 #define OMX_IndexConfigRequestCallback 0x7f000063
60 #define OMX_IndexParamBrcmPixelAspectRatio 0x7f00004d
61 #define OMX_IndexParamBrcmVideoDecodeErrorConcealment 0x7f000080
62
63 /* Defined in the broadcom version of OMX_Core.h */
64 #define OMX_EventParamOrConfigChanged 0x7F000001
65
66 #if defined(USE_IOMX)
67 /* JNI functions to get/set an Android Surface object. */
68 extern JavaVM *myVm;
69 extern jobject jni_LockAndGetAndroidJavaSurface();
70 extern void jni_UnlockAndroidSurface();
71 extern void jni_SetAndroidSurfaceSize(int width, int height, int visible_width, int visible_height, int sar_num, int sar_den);
72 extern bool jni_IsVideoPlayerActivityCreated();
73 #endif
74
75 /*****************************************************************************
76  * Local prototypes
77  *****************************************************************************/
78 static int  OpenDecoder( vlc_object_t * );
79 static int  OpenEncoder( vlc_object_t * );
80 static int  OpenGeneric( vlc_object_t *, bool b_encode );
81 static void CloseGeneric( vlc_object_t * );
82
83 static picture_t *DecodeVideo( decoder_t *, block_t ** );
84 static block_t *DecodeAudio ( decoder_t *, block_t ** );
85 static block_t *EncodeVideo( encoder_t *, picture_t * );
86
87 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE, OMX_PTR, OMX_EVENTTYPE,
88                                       OMX_U32, OMX_U32, OMX_PTR );
89 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE, OMX_PTR,
90                                          OMX_BUFFERHEADERTYPE * );
91 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE, OMX_PTR,
92                                         OMX_BUFFERHEADERTYPE * );
93
94 #if defined(USE_IOMX)
95 static void *DequeueThread( void *data );
96 static void DisplayCallback( picture_sys_t* p_picsys );
97 static void UnlockCallback( picture_sys_t* p_picsys );
98 static void HwBuffer_Init( decoder_t *p_dec, OmxPort *p_port );
99 static void HwBuffer_Destroy( decoder_t *p_dec, OmxPort *p_port );
100 static int  HwBuffer_AllocateBuffers( decoder_t *p_dec, OmxPort *p_port );
101 static int  HwBuffer_FreeBuffers( decoder_t *p_dec, OmxPort *p_port );
102 static int  HwBuffer_Start( decoder_t *p_dec, OmxPort *p_port );
103 static int  HwBuffer_Stop( decoder_t *p_dec, OmxPort *p_port );
104 static int  HwBuffer_Join( decoder_t *p_dec, OmxPort *p_port );
105 static int  HwBuffer_GetPic( decoder_t *p_dec, OmxPort *p_port,
106                              picture_t **pp_pic );
107 static void HwBuffer_SetCrop( decoder_t *p_dec, OmxPort *p_port,
108                               OMX_CONFIG_RECTTYPE *p_rect );
109 static void HwBuffer_ChangeState( decoder_t *p_dec, OmxPort *p_port,
110                                   int i_index, int i_state );
111
112 #define HWBUFFER_LOCK() vlc_mutex_lock( get_android_opaque_mutex() )
113 #define HWBUFFER_UNLOCK() vlc_mutex_unlock( get_android_opaque_mutex() )
114 #define HWBUFFER_WAIT(p_port) vlc_cond_wait( &(p_port)->p_hwbuf->wait, \
115                                               get_android_opaque_mutex() )
116 #define HWBUFFER_BROADCAST(p_port) vlc_cond_broadcast( &(p_port)->p_hwbuf->wait )
117
118 #else
119 static inline int HwBuffer_dummy( )
120 {
121     return 0;
122 }
123 #define HwBuffer_Init(p_dec, p_port) do { } while (0)
124 #define HwBuffer_Destroy(p_dec, p_port) do { } while (0)
125 #define HwBuffer_AllocateBuffers(p_dec, p_port) HwBuffer_dummy()
126 #define HwBuffer_FreeBuffers(p_dec, p_port) HwBuffer_dummy()
127 #define HwBuffer_Start(p_dec, p_port) HwBuffer_dummy()
128 #define HwBuffer_Stop(p_dec, p_port) HwBuffer_dummy()
129 #define HwBuffer_Join(p_dec, p_port) HwBuffer_dummy()
130 #define HwBuffer_GetPic(p_dec, p_port, pp_pic) HwBuffer_dummy()
131 #define HwBuffer_SetCrop(p_dec, p_port, p_rect) do { } while (0)
132
133 #define HWBUFFER_LOCK() do { } while (0)
134 #define HWBUFFER_UNLOCK() do { } while (0)
135 #define HWBUFFER_WAIT(p_port) do { } while (0)
136 #define HWBUFFER_BROADCAST(p_port) do { } while (0)
137 #endif
138
139 /*****************************************************************************
140  * Module descriptor
141  *****************************************************************************/
142 #define DIRECTRENDERING_TEXT N_("OMX direct rendering")
143 #define DIRECTRENDERING_LONGTEXT N_(\
144         "Enable OMX direct rendering.")
145
146 #define CFG_PREFIX "omxil-"
147 vlc_module_begin ()
148     set_description( N_("Audio/Video decoder (using OpenMAX IL)") )
149     set_category( CAT_INPUT )
150     set_subcategory( SUBCAT_INPUT_VCODEC )
151     set_section( N_("Decoding") , NULL )
152 #if defined(USE_IOMX)
153     /* For IOMX, don't enable it automatically via priorities,
154      * enable it only via the --codec iomx command line parameter when
155      * wanted. */
156     set_capability( "decoder", 0 )
157     add_bool(CFG_PREFIX "dr", true,
158              DIRECTRENDERING_TEXT, DIRECTRENDERING_LONGTEXT, true)
159 #else
160     set_capability( "decoder", 80 )
161 #endif
162     set_callbacks( OpenDecoder, CloseGeneric )
163
164     add_submodule ()
165     set_section( N_("Encoding") , NULL )
166     set_description( N_("Video encoder (using OpenMAX IL)") )
167     set_capability( "encoder", 0 )
168     set_callbacks( OpenEncoder, CloseGeneric )
169 vlc_module_end ()
170
171 /*****************************************************************************
172  * ImplementationSpecificWorkarounds: place-holder for implementation
173  * specific workarounds
174  *****************************************************************************/
175 static OMX_ERRORTYPE ImplementationSpecificWorkarounds(decoder_t *p_dec,
176     OmxPort *p_port, es_format_t *p_fmt)
177 {
178     decoder_sys_t *p_sys = p_dec->p_sys;
179     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
180     size_t i_profile = 0xFFFF, i_level = 0xFFFF;
181
182     /* Try to find out the profile of the video */
183     if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
184             p_fmt->i_codec == VLC_CODEC_H264)
185         h264_get_profile_level(&p_dec->fmt_in, &i_profile, &i_level, &p_sys->i_nal_size_length);
186
187     if(!strcmp(p_sys->psz_component, "OMX.TI.Video.Decoder"))
188     {
189         if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirInput &&
190            p_fmt->i_codec == VLC_CODEC_H264 &&
191            (i_profile != 66 || i_level > 30))
192         {
193             msg_Dbg(p_dec, "h264 profile/level not supported (0x%x, 0x%x)",
194                     i_profile, i_level);
195             return OMX_ErrorNotImplemented;
196         }
197
198         if(p_fmt->i_cat == VIDEO_ES && def->eDir == OMX_DirOutput &&
199            p_fmt->i_codec == VLC_CODEC_I420)
200         {
201             /* I420 xvideo is slow on OMAP */
202             def->format.video.eColorFormat = OMX_COLOR_FormatCbYCrY;
203             GetVlcChromaFormat( def->format.video.eColorFormat,
204                                 &p_fmt->i_codec, 0 );
205             GetVlcChromaSizes( p_fmt->i_codec,
206                                def->format.video.nFrameWidth,
207                                def->format.video.nFrameHeight,
208                                &p_port->i_frame_size, &p_port->i_frame_stride,
209                                &p_port->i_frame_stride_chroma_div );
210             def->format.video.nStride = p_port->i_frame_stride;
211             def->nBufferSize = p_port->i_frame_size;
212         }
213     }
214     else if(!strcmp(p_sys->psz_component, "OMX.st.video_encoder"))
215     {
216         if(p_fmt->i_cat == VIDEO_ES)
217         {
218             /* Bellagio's encoder doesn't encode the framerate in Q16 */
219             def->format.video.xFramerate >>= 16;
220         }
221     }
222 #if 0 /* FIXME: doesn't apply for HP Touchpad */
223     else if (!strncmp(p_sys->psz_component, "OMX.qcom.video.decoder.",
224                       strlen("OMX.qcom.video.decoder")))
225     {
226         /* qdsp6 refuses buffer size larger than 450K on input port */
227         if (def->nBufferSize > 450 * 1024)
228         {
229             def->nBufferSize = 450 * 1024;
230             p_port->i_frame_size = def->nBufferSize;
231         }
232     }
233 #endif
234 #ifdef RPI_OMX
235     else if (!strcmp(p_sys->psz_component, "OMX.broadcom.video_decode"))
236     {
237         /* Clear these fields before setting parameters, to allow the codec
238          * fill in what it wants (instead of rejecting whatever happened to
239          * be there. */
240         def->format.video.nStride = def->format.video.nSliceHeight = 0;
241     }
242 #endif
243
244     return OMX_ErrorNone;
245 }
246
247 /*****************************************************************************
248  * SetPortDefinition: set definition of the omx port based on the vlc format
249  *****************************************************************************/
250 static OMX_ERRORTYPE SetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
251                                        es_format_t *p_fmt)
252 {
253     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
254     OMX_ERRORTYPE omx_error;
255
256     omx_error = OMX_GetParameter(p_port->omx_handle,
257                                  OMX_IndexParamPortDefinition, def);
258     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
259                 omx_error, ErrorToString(omx_error));
260
261     switch(p_fmt->i_cat)
262     {
263     case VIDEO_ES:
264         def->format.video.nFrameWidth = p_fmt->video.i_width;
265         def->format.video.nFrameHeight = p_fmt->video.i_height;
266         if(def->format.video.eCompressionFormat == OMX_VIDEO_CodingUnused)
267             def->format.video.nStride = def->format.video.nFrameWidth;
268         if( p_fmt->video.i_frame_rate > 0 &&
269             p_fmt->video.i_frame_rate_base > 0 )
270             def->format.video.xFramerate = (p_fmt->video.i_frame_rate << 16) /
271                 p_fmt->video.i_frame_rate_base;
272
273         if(def->eDir == OMX_DirInput || p_dec->p_sys->b_enc)
274         {
275             if (def->eDir == OMX_DirInput && p_dec->p_sys->b_enc)
276                 def->nBufferSize = def->format.video.nFrameWidth *
277                   def->format.video.nFrameHeight * 2;
278             p_port->i_frame_size = def->nBufferSize;
279
280             if(!GetOmxVideoFormat(p_fmt->i_codec,
281                                   &def->format.video.eCompressionFormat, 0) )
282             {
283                 if(!GetOmxChromaFormat(p_fmt->i_codec,
284                                        &def->format.video.eColorFormat, 0) )
285                 {
286                     omx_error = OMX_ErrorNotImplemented;
287                     CHECK_ERROR(omx_error, "codec %4.4s doesn't match any OMX format",
288                                 (char *)&p_fmt->i_codec );
289                 }
290                 GetVlcChromaSizes( p_fmt->i_codec,
291                                    def->format.video.nFrameWidth,
292                                    def->format.video.nFrameHeight,
293                                    &p_port->i_frame_size, &p_port->i_frame_stride,
294                                    &p_port->i_frame_stride_chroma_div );
295                 def->format.video.nStride = p_port->i_frame_stride;
296                 def->nBufferSize = p_port->i_frame_size;
297             }
298         }
299         else
300         {
301             if( p_port->p_hwbuf )
302             {
303                 p_fmt->i_codec = VLC_CODEC_ANDROID_OPAQUE;
304                 break;
305             }
306
307             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
308                                      &p_fmt->i_codec, 0 ) )
309             {
310                 omx_error = OMX_ErrorNotImplemented;
311                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
312                             (int)def->format.video.eColorFormat );
313             }
314             GetVlcChromaSizes( p_fmt->i_codec,
315                                def->format.video.nFrameWidth,
316                                def->format.video.nFrameHeight,
317                                &p_port->i_frame_size, &p_port->i_frame_stride,
318                                &p_port->i_frame_stride_chroma_div );
319             def->format.video.nStride = p_port->i_frame_stride;
320             if (p_port->i_frame_size > def->nBufferSize)
321                 def->nBufferSize = p_port->i_frame_size;
322         }
323         break;
324
325     case AUDIO_ES:
326         p_port->i_frame_size = def->nBufferSize;
327         if(def->eDir == OMX_DirInput)
328         {
329             if(!GetOmxAudioFormat(p_fmt->i_codec,
330                                   &def->format.audio.eEncoding, 0) )
331             {
332                 omx_error = OMX_ErrorNotImplemented;
333                 CHECK_ERROR(omx_error, "codec %4.4s doesn't match any OMX format",
334                             (char *)&p_fmt->i_codec );
335             }
336         }
337         else
338         {
339             if( !OmxToVlcAudioFormat(def->format.audio.eEncoding,
340                                    &p_fmt->i_codec, 0 ) )
341             {
342                 omx_error = OMX_ErrorNotImplemented;
343                 CHECK_ERROR(omx_error, "OMX audio encoding %i not supported",
344                             (int)def->format.audio.eEncoding );
345             }
346         }
347         break;
348
349     default: return OMX_ErrorNotImplemented;
350     }
351
352     omx_error = ImplementationSpecificWorkarounds(p_dec, p_port, p_fmt);
353     CHECK_ERROR(omx_error, "ImplementationSpecificWorkarounds failed (%x : %s)",
354                 omx_error, ErrorToString(omx_error));
355
356     omx_error = OMX_SetParameter(p_port->omx_handle,
357                                  OMX_IndexParamPortDefinition, def);
358     CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
359                 omx_error, ErrorToString(omx_error));
360
361     omx_error = OMX_GetParameter(p_port->omx_handle,
362                                  OMX_IndexParamPortDefinition, def);
363     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
364                 omx_error, ErrorToString(omx_error));
365
366     if(p_port->i_frame_size > def->nBufferSize)
367         def->nBufferSize = p_port->i_frame_size;
368     p_port->i_frame_size = def->nBufferSize;
369
370     /* Deal with audio params */
371     if(p_fmt->i_cat == AUDIO_ES)
372     {
373         omx_error = SetAudioParameters(p_port->omx_handle,
374                                        &p_port->format_param, def->nPortIndex,
375                                        def->format.audio.eEncoding,
376                                        p_fmt->i_codec,
377                                        p_fmt->audio.i_channels,
378                                        p_fmt->audio.i_rate,
379                                        p_fmt->i_bitrate,
380                                        p_fmt->audio.i_bitspersample,
381                                        p_fmt->audio.i_blockalign);
382         if (def->eDir == OMX_DirInput) {
383             CHECK_ERROR(omx_error, "SetAudioParameters failed (%x : %s)",
384                         omx_error, ErrorToString(omx_error));
385         } else if (omx_error != OMX_ErrorNone) {
386             msg_Warn(p_dec, "SetAudioParameters failed (%x : %s) on output port",
387                      omx_error, ErrorToString(omx_error));
388             omx_error = OMX_ErrorNone;
389         }
390     }
391     if (!strcmp(p_dec->p_sys->psz_component, "OMX.TI.DUCATI1.VIDEO.DECODER") &&
392                 def->eDir == OMX_DirOutput && !p_port->p_hwbuf)
393     {
394         /* When setting the output buffer size above, the decoder actually
395          * sets the buffer size to a lower value than what was chosen. If
396          * we try to allocate buffers of this size, it fails. Thus, forcibly
397          * use a larger buffer size. */
398         def->nBufferSize *= 2;
399     }
400
401  error:
402     return omx_error;
403 }
404
405
406 /*****************************************************************************
407  * UpdatePixelAspect: Update vlc pixel aspect based on the aspect reported on
408  * the omx port - NOTE: Broadcom specific
409  *****************************************************************************/
410 static OMX_ERRORTYPE UpdatePixelAspect(decoder_t *p_dec)
411 {
412     decoder_sys_t *p_sys = p_dec->p_sys;
413     OMX_CONFIG_POINTTYPE pixel_aspect;
414     OMX_INIT_STRUCTURE(pixel_aspect);
415     OMX_ERRORTYPE omx_err;
416
417     if (strncmp(p_sys->psz_component, "OMX.broadcom.", 13))
418         return OMX_ErrorNotImplemented;
419
420     pixel_aspect.nPortIndex = p_sys->out.i_port_index;
421     omx_err = OMX_GetParameter(p_sys->omx_handle,
422             OMX_IndexParamBrcmPixelAspectRatio, &pixel_aspect);
423     if (omx_err != OMX_ErrorNone) {
424         msg_Warn(p_dec, "Failed to retrieve aspect ratio");
425     } else {
426         p_dec->fmt_out.video.i_sar_num = pixel_aspect.nX;
427         p_dec->fmt_out.video.i_sar_den = pixel_aspect.nY;
428     }
429
430     return omx_err;
431 }
432
433 /*****************************************************************************
434  * AllocateBuffers: Allocate Omx buffers
435  *****************************************************************************/
436 static OMX_ERRORTYPE AllocateBuffers(decoder_t *p_dec, OmxPort *p_port)
437 {
438     decoder_sys_t *p_sys = p_dec->p_sys;
439     OMX_ERRORTYPE omx_error = OMX_ErrorUndefined;
440     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
441     unsigned int i = 0;
442
443     OMX_DBG( "AllocateBuffers(%d)", def->eDir );
444
445     p_port->i_buffers = p_port->definition.nBufferCountActual;
446
447     p_port->pp_buffers = calloc(p_port->i_buffers, sizeof(OMX_BUFFERHEADERTYPE*));
448     if( !p_port->pp_buffers )
449     {
450         p_port->i_buffers = 0;
451         return OMX_ErrorInsufficientResources;
452     }
453
454     for(i = 0; i < p_port->i_buffers; i++)
455     {
456 #if 0
457 #define ALIGN(x,BLOCKLIGN) (((x) + BLOCKLIGN - 1) & ~(BLOCKLIGN - 1))
458         char *p_buf = malloc(p_port->definition.nBufferSize +
459                              p_port->definition.nBufferAlignment);
460         p_port->pp_buffers[i] = (void *)ALIGN((uintptr_t)p_buf, p_port->definition.nBufferAlignment);
461 #endif
462
463         if( p_port->p_hwbuf )
464         {
465             omx_error =
466                 OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
467                                p_port->i_port_index, 0,
468                                p_port->definition.nBufferSize,
469                                p_port->p_hwbuf->pp_handles[i] );
470             OMX_DBG( "OMX_UseBuffer(%d) %p, %p", def->eDir,
471                      p_port->pp_buffers[i], p_port->p_hwbuf->pp_handles[i] );
472         }
473         else if( p_port->b_direct )
474         {
475             omx_error =
476                 OMX_UseBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
477                                p_port->i_port_index, 0,
478                                p_port->definition.nBufferSize, (void*)1);
479             OMX_DBG( "OMX_UseBuffer(%d) %p, %p", def->eDir,
480                      p_port->pp_buffers[i], p_port->pp_buffers[i]->pBuffer );
481         }
482         else
483         {
484             omx_error =
485                 OMX_AllocateBuffer( p_sys->omx_handle, &p_port->pp_buffers[i],
486                                     p_port->i_port_index, 0,
487                                     p_port->definition.nBufferSize);
488             OMX_DBG( "OMX_AllocateBuffer(%d) %p, %p", def->eDir,
489                      p_port->pp_buffers[i], p_port->pp_buffers[i]->pBuffer );
490         }
491
492         if(omx_error != OMX_ErrorNone)
493         {
494             p_port->i_buffers = i;
495             break;
496         }
497         if( !p_port->p_hwbuf )
498             OMX_FIFO_PUT(&p_port->fifo, p_port->pp_buffers[i]);
499     }
500
501     CHECK_ERROR(omx_error, "AllocateBuffers failed (%x, %i)",
502                 omx_error, (int)p_port->i_port_index );
503
504
505     OMX_DBG( "AllocateBuffers(%d)::done", def->eDir );
506 error:
507     return omx_error;
508 }
509
510 /*****************************************************************************
511  * FreeBuffers: Free Omx buffers
512  *****************************************************************************/
513 static OMX_ERRORTYPE FreeBuffers(decoder_t *p_dec, OmxPort *p_port)
514 {
515     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
516     OMX_ERRORTYPE omx_error = OMX_ErrorNone;
517     OMX_BUFFERHEADERTYPE *p_buffer;
518     unsigned int i, i_wait_buffers;
519
520     /* Normally, all buffers are in the port fifo, or given to the codec that
521      * will return them when disabling the port or changing state, therefore we
522      * normally wait for all buffers. For IOMX direct rendering (HwBuffer),
523      * only a few buffers are given to the codec at a time, thus we can only
524      * wait for that many buffers. And after that, we can still free all OMX
525      * buffers since we either got some of them returned via OMX_FIFO_GET, or
526      * never passed them to the codec at all. */
527     if( p_port->p_hwbuf )
528         i_wait_buffers = p_port->p_hwbuf->i_owned;
529     else
530         i_wait_buffers = p_port->i_buffers;
531
532     OMX_DBG( "FreeBuffers(%d), waiting for %u buffers", def->eDir,
533              i_wait_buffers);
534
535     for(i = 0; i < i_wait_buffers; i++)
536     {
537         OMX_FIFO_GET(&p_port->fifo, p_buffer);
538         if (p_buffer->nFlags & SENTINEL_FLAG) {
539             free(p_buffer);
540             i--;
541             continue;
542         }
543     }
544
545     for(i = 0; i < p_port->i_buffers; i++)
546     {
547         p_buffer = p_port->pp_buffers[i];
548         if( p_buffer )
549         {
550             if (p_buffer->pAppPrivate != NULL)
551                 decoder_DeletePicture( p_dec, p_buffer->pAppPrivate );
552
553             omx_error = OMX_FreeBuffer( p_port->omx_handle,
554                                         p_port->i_port_index, p_buffer );
555             OMX_DBG( "OMX_FreeBuffer(%d) %p, %p", def->eDir,
556                      p_buffer, p_buffer->pBuffer );
557
558             if(omx_error != OMX_ErrorNone) break;
559         }
560     }
561
562     if( omx_error != OMX_ErrorNone )
563        msg_Err( p_dec, "OMX_FreeBuffer failed (%x, %i, %i)",
564                 omx_error, (int)p_port->i_port_index, i );
565
566     p_port->i_buffers = 0;
567     free( p_port->pp_buffers );
568     p_port->pp_buffers = NULL;
569
570     OMX_DBG( "FreeBuffers(%d)::done", def->eDir );
571
572     return omx_error;
573 }
574
575 /*****************************************************************************
576  * GetPortDefinition: set vlc format based on the definition of the omx port
577  *****************************************************************************/
578 static OMX_ERRORTYPE GetPortDefinition(decoder_t *p_dec, OmxPort *p_port,
579                                        es_format_t *p_fmt)
580 {
581     decoder_sys_t *p_sys = p_dec->p_sys;
582     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
583     OMX_ERRORTYPE omx_error;
584     OMX_CONFIG_RECTTYPE crop_rect;
585
586     omx_error = OMX_GetParameter(p_port->omx_handle,
587                                  OMX_IndexParamPortDefinition, def);
588     CHECK_ERROR(omx_error, "OMX_GetParameter failed (%x : %s)",
589                 omx_error, ErrorToString(omx_error));
590
591     switch(p_fmt->i_cat)
592     {
593     case VIDEO_ES:
594         p_fmt->video.i_width = def->format.video.nFrameWidth;
595         p_fmt->video.i_visible_width = def->format.video.nFrameWidth;
596         p_fmt->video.i_height = def->format.video.nFrameHeight;
597         p_fmt->video.i_visible_height = def->format.video.nFrameHeight;
598         p_fmt->video.i_frame_rate = p_dec->fmt_in.video.i_frame_rate;
599         p_fmt->video.i_frame_rate_base = p_dec->fmt_in.video.i_frame_rate_base;
600
601         OMX_INIT_STRUCTURE(crop_rect);
602         crop_rect.nPortIndex = def->nPortIndex;
603         omx_error = OMX_GetConfig(p_port->omx_handle, OMX_IndexConfigCommonOutputCrop, &crop_rect);
604         if (omx_error == OMX_ErrorNone)
605         {
606             if (!def->format.video.nSliceHeight)
607                 def->format.video.nSliceHeight = def->format.video.nFrameHeight;
608             if (!def->format.video.nStride)
609                 def->format.video.nStride = def->format.video.nFrameWidth;
610             p_fmt->video.i_width = crop_rect.nWidth;
611             p_fmt->video.i_visible_width = crop_rect.nWidth;
612             p_fmt->video.i_height = crop_rect.nHeight;
613             p_fmt->video.i_visible_height = crop_rect.nHeight;
614             if (def->format.video.eColorFormat == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar)
615                 def->format.video.nSliceHeight -= crop_rect.nTop/2;
616
617             if( p_port->p_hwbuf )
618                 HwBuffer_SetCrop( p_dec, p_port, &crop_rect );
619         }
620         else
621         {
622             /* Don't pass the error back to the caller, this isn't mandatory */
623             omx_error = OMX_ErrorNone;
624         }
625
626         if( p_port->p_hwbuf )
627         {
628             UpdatePixelAspect(p_dec);
629             break;
630         }
631         /* Hack: Nexus One (stock firmware with binary OMX driver blob)
632          * claims to output 420Planar even though it in in practice is
633          * NV21. */
634         if(def->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar &&
635            !strncmp(p_sys->psz_component, "OMX.qcom.video.decoder",
636                     strlen("OMX.qcom.video.decoder")))
637             def->format.video.eColorFormat = OMX_QCOM_COLOR_FormatYVU420SemiPlanar;
638
639         if (IgnoreOmxDecoderPadding(p_sys->psz_component)) {
640             def->format.video.nSliceHeight = 0;
641             def->format.video.nStride = p_fmt->video.i_width;
642         }
643
644         if(!GetVlcVideoFormat( def->format.video.eCompressionFormat,
645                                &p_fmt->i_codec, 0 ) )
646         {
647             if( !GetVlcChromaFormat( def->format.video.eColorFormat,
648                                      &p_fmt->i_codec, 0 ) )
649             {
650                 omx_error = OMX_ErrorNotImplemented;
651                 CHECK_ERROR(omx_error, "OMX color format %i not supported",
652                             (int)def->format.video.eColorFormat );
653             }
654             GetVlcChromaSizes( p_fmt->i_codec,
655                                def->format.video.nFrameWidth,
656                                def->format.video.nFrameHeight,
657                                &p_port->i_frame_size, &p_port->i_frame_stride,
658                                &p_port->i_frame_stride_chroma_div );
659         }
660         if(p_port->i_frame_size > def->nBufferSize)
661             def->nBufferSize = p_port->i_frame_size;
662         p_port->i_frame_size = def->nBufferSize;
663 #if 0
664         if((int)p_port->i_frame_stride > def->format.video.nStride)
665             def->format.video.nStride = p_port->i_frame_stride;
666 #endif
667         p_port->i_frame_stride = def->format.video.nStride;
668         UpdatePixelAspect(p_dec);
669         break;
670
671     case AUDIO_ES:
672         if( !OmxToVlcAudioFormat( def->format.audio.eEncoding,
673                                 &p_fmt->i_codec, 0 ) )
674         {
675             omx_error = OMX_ErrorNotImplemented;
676             CHECK_ERROR(omx_error, "OMX audio format %i not supported",
677                         (int)def->format.audio.eEncoding );
678         }
679
680         omx_error = GetAudioParameters(p_port->omx_handle,
681                                        &p_port->format_param, def->nPortIndex,
682                                        def->format.audio.eEncoding,
683                                        &p_fmt->audio.i_channels,
684                                        &p_fmt->audio.i_rate,
685                                        &p_fmt->i_bitrate,
686                                        &p_fmt->audio.i_bitspersample,
687                                        &p_fmt->audio.i_blockalign);
688         CHECK_ERROR(omx_error, "GetAudioParameters failed (%x : %s)",
689                     omx_error, ErrorToString(omx_error));
690
691         if(p_fmt->audio.i_channels < 9)
692         {
693             static const int pi_channels_maps[9] =
694             {
695                 0, AOUT_CHAN_CENTER, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
696                 AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
697                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
698                 | AOUT_CHAN_REARRIGHT,
699                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
700                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
701                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
702                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
703                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
704                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT
705                 | AOUT_CHAN_MIDDLERIGHT,
706                 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
707                 | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
708                 | AOUT_CHAN_LFE
709             };
710             p_fmt->audio.i_physical_channels =
711                 p_fmt->audio.i_original_channels =
712                     pi_channels_maps[p_fmt->audio.i_channels];
713         }
714
715         date_Init( &p_dec->p_sys->end_date, p_fmt->audio.i_rate, 1 );
716
717         break;
718
719     default: return OMX_ErrorNotImplemented;
720     }
721
722  error:
723     return omx_error;
724 }
725
726 /*****************************************************************************
727  * DeinitialiseComponent: Deinitialise and unload an OMX component
728  *****************************************************************************/
729 static OMX_ERRORTYPE DeinitialiseComponent(decoder_t *p_dec,
730                                            OMX_HANDLETYPE omx_handle)
731 {
732     decoder_sys_t *p_sys = p_dec->p_sys;
733     OMX_BUFFERHEADERTYPE *p_buffer;
734     OMX_ERRORTYPE omx_error;
735     OMX_STATETYPE state;
736     unsigned int i;
737
738     if(!omx_handle) return OMX_ErrorNone;
739
740     omx_error = OMX_GetState(omx_handle, &state);
741     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
742
743     if( p_sys->out.p_hwbuf && HwBuffer_Stop( p_dec, &p_sys->out ) != 0 )
744         msg_Warn( p_dec, "HwBuffer_Stop failed" );
745
746     if(state == OMX_StateExecuting)
747     {
748         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
749                                      OMX_StateIdle, 0 );
750         CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
751         while (1) {
752             OMX_U32 cmd, state;
753             omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, &cmd, &state, 0);
754             CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
755             // The event queue can contain other OMX_EventCmdComplete items,
756             // such as for OMX_CommandFlush
757             if (cmd == OMX_CommandStateSet && state == OMX_StateIdle)
758                 break;
759         }
760     }
761
762     omx_error = OMX_GetState(omx_handle, &state);
763     CHECK_ERROR(omx_error, "OMX_GetState failed (%x)", omx_error );
764
765     if(state == OMX_StateIdle)
766     {
767         omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet,
768                                      OMX_StateLoaded, 0 );
769         CHECK_ERROR(omx_error, "OMX_CommandStateSet Loaded failed (%x)", omx_error );
770
771         for(i = 0; i < p_sys->ports; i++)
772         {
773             OmxPort *p_port = &p_sys->p_ports[i];
774
775             omx_error = FreeBuffers( p_dec, p_port );
776             CHECK_ERROR(omx_error, "FreeBuffers failed (%x, %i)",
777                         omx_error, (int)p_port->i_port_index );
778             if( p_port->p_hwbuf )
779             {
780                 HwBuffer_FreeBuffers( p_dec, p_port );
781                 HwBuffer_Join( p_dec, p_port );
782             }
783         }
784
785         omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
786         CHECK_ERROR(omx_error, "Wait for Loaded failed (%x)", omx_error );
787     }
788
789  error:
790     for(i = 0; i < p_sys->ports; i++)
791     {
792         OmxPort *p_port = &p_sys->p_ports[i];
793         free(p_port->pp_buffers);
794         p_port->pp_buffers = 0;
795
796         while (1) {
797             OMX_FIFO_PEEK(&p_port->fifo, p_buffer);
798             if (!p_buffer) break;
799
800             OMX_FIFO_GET(&p_port->fifo, p_buffer);
801             if (p_buffer->nFlags & SENTINEL_FLAG) {
802                 free(p_buffer);
803                 continue;
804             }
805             msg_Warn( p_dec, "Stray buffer left in fifo, %p", p_buffer );
806         }
807         HwBuffer_Destroy( p_dec, p_port );
808     }
809     omx_error = pf_free_handle( omx_handle );
810     return omx_error;
811 }
812
813 /*****************************************************************************
814  * InitialiseComponent: Load and initialise an OMX component
815  *****************************************************************************/
816 static OMX_ERRORTYPE InitialiseComponent(decoder_t *p_dec,
817     OMX_STRING psz_component, OMX_HANDLETYPE *p_handle)
818 {
819     static OMX_CALLBACKTYPE callbacks =
820         { OmxEventHandler, OmxEmptyBufferDone, OmxFillBufferDone };
821     decoder_sys_t *p_sys = p_dec->p_sys;
822     OMX_HANDLETYPE omx_handle;
823     OMX_ERRORTYPE omx_error;
824     unsigned int i;
825     OMX_U8 psz_role[OMX_MAX_STRINGNAME_SIZE];
826     OMX_PARAM_COMPONENTROLETYPE role;
827     OMX_PARAM_PORTDEFINITIONTYPE definition;
828     OMX_PORT_PARAM_TYPE param;
829
830     /* Load component */
831     omx_error = pf_get_handle( &omx_handle, psz_component, p_dec, &callbacks );
832     if(omx_error != OMX_ErrorNone)
833     {
834         msg_Warn( p_dec, "OMX_GetHandle(%s) failed (%x: %s)", psz_component,
835                   omx_error, ErrorToString(omx_error) );
836         return omx_error;
837     }
838     strncpy(p_sys->psz_component, psz_component, OMX_MAX_STRINGNAME_SIZE-1);
839
840     omx_error = OMX_ComponentRoleEnum(omx_handle, psz_role, 0);
841     if(omx_error == OMX_ErrorNone)
842         msg_Dbg(p_dec, "loaded component %s of role %s", psz_component, psz_role);
843     else
844         msg_Dbg(p_dec, "loaded component %s", psz_component);
845     PrintOmx(p_dec, omx_handle, OMX_ALL);
846
847     /* Set component role */
848     OMX_INIT_STRUCTURE(role);
849     strcpy((char*)role.cRole,
850            GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec : p_dec->fmt_in.i_codec,
851                       p_dec->fmt_in.i_cat, p_sys->b_enc));
852
853     omx_error = OMX_SetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
854                                  &role);
855     omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamStandardComponentRole,
856                                  &role);
857     if(omx_error == OMX_ErrorNone)
858         msg_Dbg(p_dec, "component standard role set to %s", role.cRole);
859
860     /* Find the input / output ports */
861     OMX_INIT_STRUCTURE(param);
862     OMX_INIT_STRUCTURE(definition);
863     omx_error = OMX_GetParameter(omx_handle, p_dec->fmt_in.i_cat == VIDEO_ES ?
864                                  OMX_IndexParamVideoInit : OMX_IndexParamAudioInit, &param);
865     if(omx_error != OMX_ErrorNone) {
866 #ifdef __ANDROID__
867         param.nPorts = 2;
868         param.nStartPortNumber = 0;
869 #else
870         param.nPorts = 0;
871 #endif
872     }
873
874     for(i = 0; i < param.nPorts; i++)
875     {
876         OmxPort *p_port;
877
878         /* Get port definition */
879         definition.nPortIndex = param.nStartPortNumber + i;
880         omx_error = OMX_GetParameter(omx_handle, OMX_IndexParamPortDefinition,
881                                      &definition);
882         if(omx_error != OMX_ErrorNone) continue;
883
884         if(definition.eDir == OMX_DirInput) p_port = &p_sys->in;
885         else  p_port = &p_sys->out;
886
887         p_port->b_valid = true;
888         p_port->i_port_index = definition.nPortIndex;
889         p_port->definition = definition;
890         p_port->omx_handle = omx_handle;
891         HwBuffer_Init( p_dec, p_port );
892     }
893
894     if(!p_sys->in.b_valid || !p_sys->out.b_valid)
895     {
896         omx_error = OMX_ErrorInvalidComponent;
897         CHECK_ERROR(omx_error, "couldn't find an input and output port");
898     }
899
900     if( !p_sys->out.p_hwbuf && !strncmp(p_sys->psz_component, "OMX.SEC.", 8) &&
901        p_dec->fmt_in.i_cat == VIDEO_ES )
902     {
903         OMX_INDEXTYPE index;
904         omx_error = OMX_GetExtensionIndex(omx_handle, (OMX_STRING) "OMX.SEC.index.ThumbnailMode", &index);
905         if(omx_error == OMX_ErrorNone)
906         {
907             OMX_BOOL enable = OMX_TRUE;
908             omx_error = OMX_SetConfig(omx_handle, index, &enable);
909             CHECK_ERROR(omx_error, "Unable to set ThumbnailMode");
910         } else {
911             OMX_BOOL enable = OMX_TRUE;
912             /* Needed on Samsung Galaxy S II */
913             omx_error = OMX_SetConfig(omx_handle, OMX_IndexVendorSetYUV420pMode, &enable);
914             if (omx_error == OMX_ErrorNone)
915                 msg_Dbg(p_dec, "Set OMX_IndexVendorSetYUV420pMode successfully");
916             else
917                 msg_Dbg(p_dec, "Unable to set OMX_IndexVendorSetYUV420pMode: %x", omx_error);
918         }
919     }
920
921     if(!strncmp(p_sys->psz_component, "OMX.broadcom.", 13))
922     {
923         OMX_CONFIG_REQUESTCALLBACKTYPE notifications;
924         OMX_INIT_STRUCTURE(notifications);
925
926         notifications.nPortIndex = p_sys->out.i_port_index;
927         notifications.nIndex = OMX_IndexParamBrcmPixelAspectRatio;
928         notifications.bEnable = OMX_TRUE;
929
930         omx_error = OMX_SetParameter(omx_handle,
931                 OMX_IndexConfigRequestCallback, &notifications);
932         if (omx_error == OMX_ErrorNone) {
933             msg_Dbg(p_dec, "Enabled aspect ratio notifications");
934             p_sys->b_aspect_ratio_handled = true;
935         } else
936             msg_Dbg(p_dec, "Could not enable aspect ratio notifications");
937     }
938
939     /* Set port definitions */
940     for(i = 0; i < p_sys->ports; i++)
941     {
942         omx_error = SetPortDefinition(p_dec, &p_sys->p_ports[i],
943                                       p_sys->p_ports[i].p_fmt);
944         if(omx_error != OMX_ErrorNone) goto error;
945     }
946
947     if(!strncmp(p_sys->psz_component, "OMX.broadcom.", 13) &&
948         p_sys->in.p_fmt->i_codec == VLC_CODEC_H264)
949     {
950         OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE concanParam;
951         OMX_INIT_STRUCTURE(concanParam);
952         concanParam.bStartWithValidFrame = OMX_FALSE;
953
954         omx_error = OMX_SetParameter(omx_handle,
955                 OMX_IndexParamBrcmVideoDecodeErrorConcealment, &concanParam);
956         if (omx_error == OMX_ErrorNone)
957             msg_Dbg(p_dec, "StartWithValidFrame disabled.");
958         else
959             msg_Dbg(p_dec, "Could not disable StartWithValidFrame.");
960     }
961
962     /* Allocate our array for the omx buffers and enable ports */
963     for(i = 0; i < p_sys->ports; i++)
964     {
965         OmxPort *p_port = &p_sys->p_ports[i];
966
967         /* Enable port */
968         if(!p_port->definition.bEnabled)
969         {
970             omx_error = OMX_SendCommand( omx_handle, OMX_CommandPortEnable,
971                                          p_port->i_port_index, NULL);
972             CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
973                         (int)p_port->i_port_index, omx_error );
974             omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
975             CHECK_ERROR(omx_error, "Wait for PortEnable on %i failed (%x)",
976                         (int)p_port->i_port_index, omx_error );
977         }
978     }
979
980     *p_handle = omx_handle;
981     return OMX_ErrorNone;
982
983  error:
984     DeinitialiseComponent(p_dec, omx_handle);
985     *p_handle = 0;
986     return omx_error;
987 }
988
989 /*****************************************************************************
990  * OpenDecoder: Create the decoder instance
991  *****************************************************************************/
992 static int OpenDecoder( vlc_object_t *p_this )
993 {
994     decoder_t *p_dec = (decoder_t*)p_this;
995     int status;
996
997 #ifdef __ANDROID__
998     if( p_dec->fmt_in.i_cat == AUDIO_ES )
999         return VLC_EGENERIC;
1000 #endif
1001
1002     if( 0 || !GetOmxRole(p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat, false) )
1003         return VLC_EGENERIC;
1004
1005     status = OpenGeneric( p_this, false );
1006     if(status != VLC_SUCCESS) return status;
1007
1008     p_dec->pf_decode_video = DecodeVideo;
1009     p_dec->pf_decode_audio = DecodeAudio;
1010
1011     return VLC_SUCCESS;
1012 }
1013
1014 /*****************************************************************************
1015  * OpenEncoder: Create the encoder instance
1016  *****************************************************************************/
1017 static int OpenEncoder( vlc_object_t *p_this )
1018 {
1019     encoder_t *p_enc = (encoder_t*)p_this;
1020     int status;
1021
1022     if( !GetOmxRole(p_enc->fmt_out.i_codec, p_enc->fmt_in.i_cat, true) )
1023         return VLC_EGENERIC;
1024
1025     status = OpenGeneric( p_this, true );
1026     if(status != VLC_SUCCESS) return status;
1027
1028     p_enc->pf_encode_video = EncodeVideo;
1029
1030     return VLC_SUCCESS;
1031 }
1032
1033 /*****************************************************************************
1034  * OpenGeneric: Create the generic decoder/encoder instance
1035  *****************************************************************************/
1036 static int OpenGeneric( vlc_object_t *p_this, bool b_encode )
1037 {
1038     decoder_t *p_dec = (decoder_t*)p_this;
1039     decoder_sys_t *p_sys;
1040     OMX_ERRORTYPE omx_error;
1041     OMX_BUFFERHEADERTYPE *p_header;
1042     unsigned int i;
1043
1044     if (InitOmxCore(p_this) != VLC_SUCCESS) {
1045         return VLC_EGENERIC;
1046     }
1047
1048     /* Allocate the memory needed to store the decoder's structure */
1049     if( ( p_dec->p_sys = p_sys = calloc( 1, sizeof(*p_sys)) ) == NULL )
1050     {
1051         DeinitOmxCore();
1052         return VLC_ENOMEM;
1053     }
1054
1055     /* Initialise the thread properties */
1056     if(!b_encode)
1057     {
1058         p_dec->fmt_out.i_cat = p_dec->fmt_in.i_cat;
1059         p_dec->fmt_out.video = p_dec->fmt_in.video;
1060         p_dec->fmt_out.audio = p_dec->fmt_in.audio;
1061         p_dec->fmt_out.i_codec = 0;
1062
1063         /* set default aspect of 1, if parser did not set it */
1064         if (p_dec->fmt_out.video.i_sar_num == 0)
1065             p_dec->fmt_out.video.i_sar_num = 1;
1066         if (p_dec->fmt_out.video.i_sar_den == 0)
1067             p_dec->fmt_out.video.i_sar_den = 1;
1068     }
1069     p_sys->b_enc = b_encode;
1070     InitOmxEventQueue(&p_sys->event_queue);
1071     OMX_FIFO_INIT (&p_sys->in.fifo, pOutputPortPrivate );
1072     p_sys->in.b_direct = false;
1073     p_sys->in.b_flushed = true;
1074     p_sys->in.p_fmt = &p_dec->fmt_in;
1075     OMX_FIFO_INIT (&p_sys->out.fifo, pInputPortPrivate );
1076 #if defined(USE_IOMX)
1077     p_sys->out.b_direct = jni_IsVideoPlayerActivityCreated() && var_InheritBool(p_dec, CFG_PREFIX "dr");
1078 #else
1079     p_sys->out.b_direct = false;
1080 #endif
1081     p_sys->out.b_flushed = true;
1082     p_sys->out.p_fmt = &p_dec->fmt_out;
1083     p_sys->ports = 2;
1084     p_sys->p_ports = &p_sys->in;
1085     p_sys->b_use_pts = 1;
1086
1087     msg_Dbg(p_dec, "fmt in:%4.4s, out: %4.4s", (char *)&p_dec->fmt_in.i_codec,
1088             (char *)&p_dec->fmt_out.i_codec);
1089
1090     /* Enumerate components and build a list of the one we want to try */
1091     p_sys->components =
1092         CreateComponentsList(p_this,
1093              GetOmxRole(p_sys->b_enc ? p_dec->fmt_out.i_codec :
1094                         p_dec->fmt_in.i_codec, p_dec->fmt_in.i_cat,
1095                         p_sys->b_enc), p_sys->ppsz_components);
1096     if( !p_sys->components )
1097     {
1098         msg_Warn( p_this, "couldn't find an omx component for codec %4.4s",
1099                   (char *)&p_dec->fmt_in.i_codec );
1100         CloseGeneric(p_this);
1101         return VLC_EGENERIC;
1102     }
1103
1104     /* Try to load and initialise a component */
1105     omx_error = OMX_ErrorUndefined;
1106     for(i = 0; i < p_sys->components; i++)
1107     {
1108 #ifdef __ANDROID__
1109         /* ignore OpenCore software codecs */
1110         if (!strncmp(p_sys->ppsz_components[i], "OMX.PV.", 7))
1111             continue;
1112         /* The same sw codecs, renamed in ICS (perhaps also in honeycomb) */
1113         if (!strncmp(p_sys->ppsz_components[i], "OMX.google.", 11))
1114             continue;
1115         /* This one has been seen on HTC One V - it behaves like it works,
1116          * but FillBufferDone returns buffers filled with 0 bytes. The One V
1117          * has got a working OMX.qcom.video.decoder.avc instead though. */
1118         if (!strncmp(p_sys->ppsz_components[i], "OMX.ARICENT.", 12))
1119             continue;
1120         /* Codecs with DRM, that don't output plain YUV data but only
1121          * support direct rendering where the output can't be intercepted. */
1122         if (strstr(p_sys->ppsz_components[i], ".secure"))
1123             continue;
1124         /* Use VC1 decoder for WMV3 for now */
1125         if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.WMV.Decoder"))
1126             continue;
1127         /* This decoder does work, but has an insane latency (leading to errors
1128          * about "main audio output playback way too late" and dropped frames).
1129          * At least Samsung Galaxy S III (where this decoder is present) has
1130          * got another one, OMX.SEC.mp3.dec, that works well and has a
1131          * sensible latency. (Also, even if that one isn't found, in general,
1132          * using SW codecs is usually more than fast enough for MP3.) */
1133         if (!strcmp(p_sys->ppsz_components[i], "OMX.SEC.MP3.Decoder"))
1134             continue;
1135         /* This codec should be able to handle both VC1 and WMV3, but
1136          * for VC1 it doesn't output any buffers at all (in the way we use
1137          * it) and for WMV3 it outputs plain black buffers. Thus ignore
1138          * it until we can make it work properly. */
1139         if (!strcmp(p_sys->ppsz_components[i], "OMX.Nvidia.vc1.decode"))
1140             continue;
1141 #endif
1142         omx_error = InitialiseComponent(p_dec, p_sys->ppsz_components[i],
1143                                         &p_sys->omx_handle);
1144         if(omx_error == OMX_ErrorNone) break;
1145     }
1146     CHECK_ERROR(omx_error, "no component could be initialised" );
1147
1148     /* Move component to Idle then Executing state */
1149     OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0 );
1150     CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x)", omx_error );
1151
1152     /* Allocate omx buffers */
1153     for(i = 0; i < p_sys->ports; i++)
1154     {
1155         OmxPort *p_port = &p_sys->p_ports[i];
1156         if( p_port->p_hwbuf )
1157         {
1158             if( HwBuffer_AllocateBuffers( p_dec, p_port ) != 0 )
1159             {
1160                 omx_error = OMX_ErrorInsufficientResources;
1161                 goto error;
1162             }
1163         }
1164         omx_error = AllocateBuffers( p_dec, p_port );
1165         CHECK_ERROR(omx_error, "AllocateBuffers failed (%x, %i)",
1166                     omx_error, (int)p_port->i_port_index );
1167     }
1168
1169     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
1170     CHECK_ERROR(omx_error, "Wait for Idle failed (%x)", omx_error );
1171
1172     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandStateSet,
1173                                  OMX_StateExecuting, 0);
1174     CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x)", omx_error );
1175     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
1176     CHECK_ERROR(omx_error, "Wait for Executing failed (%x)", omx_error );
1177
1178     if( p_sys->out.p_hwbuf && HwBuffer_Start( p_dec, &p_sys->out ) != 0 )
1179     {
1180         omx_error = OMX_ErrorUndefined;
1181         goto error;
1182     }
1183
1184     /* Send codec configuration data */
1185     if( p_dec->fmt_in.i_extra )
1186     {
1187         OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1188         p_header->nFilledLen = p_dec->fmt_in.i_extra;
1189
1190         /* Convert H.264 NAL format to annex b */
1191         if( p_sys->i_nal_size_length && !p_sys->in.b_direct )
1192         {
1193             p_header->nFilledLen = 0;
1194             convert_sps_pps( p_dec, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra,
1195                              p_header->pBuffer, p_header->nAllocLen,
1196                              (uint32_t*) &p_header->nFilledLen, NULL );
1197         }
1198         else if(p_sys->in.b_direct)
1199         {
1200             p_header->pOutputPortPrivate = p_header->pBuffer;
1201             p_header->pBuffer = p_dec->fmt_in.p_extra;
1202         }
1203         else if (p_dec->fmt_in.i_codec == VLC_CODEC_WMV3 &&
1204                  p_dec->fmt_in.i_extra >= 4 &&
1205                  p_header->nAllocLen >= 36)
1206         {
1207             int profile;
1208             // According to OMX IL 1.2.0 spec (4.3.33.2), the codec config
1209             // data for VC-1 Main/Simple (aka WMV3) is according to table 265
1210             // in the VC-1 spec. Most of the fields are just set with placeholders
1211             // (like framerate, hrd_buffer/rate).
1212             static const uint8_t wmv3seq[] = {
1213                 0xff, 0xff, 0xff, 0xc5, // numframes=ffffff, marker byte
1214                 0x04, 0x00, 0x00, 0x00, // marker byte
1215                 0x00, 0x00, 0x00, 0x00, // struct C, almost equal to p_extra
1216                 0x00, 0x00, 0x00, 0x00, // struct A, vert size
1217                 0x00, 0x00, 0x00, 0x00, // struct A, horiz size
1218                 0x0c, 0x00, 0x00, 0x00, // marker byte
1219                 0xff, 0xff, 0x00, 0x80, // struct B, level=4, cbr=0, hrd_buffer=ffff
1220                 0xff, 0xff, 0x00, 0x00, // struct B, hrd_rate=ffff
1221                 0xff, 0xff, 0xff, 0xff, // struct B, framerate=ffffffff
1222             };
1223             p_header->nFilledLen = sizeof(wmv3seq);
1224             memcpy(p_header->pBuffer, wmv3seq, p_header->nFilledLen);
1225             // Struct C - almost equal to the extradata
1226             memcpy(&p_header->pBuffer[8], p_dec->fmt_in.p_extra, 4);
1227             // Expand profile from the highest 2 bits to the highest 4 bits
1228             profile = p_header->pBuffer[8] >> 6;
1229             p_header->pBuffer[8] = (p_header->pBuffer[8] & 0x0f) | (profile << 4);
1230             // Fill in the height/width for struct A
1231             SetDWLE(&p_header->pBuffer[12], p_dec->fmt_in.video.i_height);
1232             SetDWLE(&p_header->pBuffer[16], p_dec->fmt_in.video.i_width);
1233         }
1234         else
1235         {
1236             if(p_header->nFilledLen > p_header->nAllocLen)
1237             {
1238                 msg_Dbg(p_dec, "buffer too small (%i,%i)", (int)p_header->nFilledLen,
1239                         (int)p_header->nAllocLen);
1240                 p_header->nFilledLen = p_header->nAllocLen;
1241             }
1242             memcpy(p_header->pBuffer, p_dec->fmt_in.p_extra, p_header->nFilledLen);
1243         }
1244
1245         p_header->nOffset = 0;
1246         p_header->nFlags = OMX_BUFFERFLAG_CODECCONFIG | OMX_BUFFERFLAG_ENDOFFRAME;
1247         msg_Dbg(p_dec, "sending codec config data %p, %p, %i", p_header,
1248                 p_header->pBuffer, (int)p_header->nFilledLen);
1249         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1250     }
1251
1252     /* Get back output port definition */
1253     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1254     if(omx_error != OMX_ErrorNone) goto error;
1255
1256     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1257     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1258
1259     if(p_sys->b_error) goto error;
1260
1261     p_dec->b_need_packetized = true;
1262
1263     if (!p_sys->b_use_pts)
1264         msg_Dbg( p_dec, "using dts timestamp mode for %s", p_sys->psz_component);
1265
1266     return VLC_SUCCESS;
1267
1268  error:
1269     CloseGeneric(p_this);
1270     return VLC_EGENERIC;
1271 }
1272
1273 /*****************************************************************************
1274  * PortReconfigure
1275  *****************************************************************************/
1276 static OMX_ERRORTYPE PortReconfigure(decoder_t *p_dec, OmxPort *p_port)
1277 {
1278     decoder_sys_t *p_sys = p_dec->p_sys;
1279     OMX_PARAM_PORTDEFINITIONTYPE definition;
1280     OMX_ERRORTYPE omx_error;
1281
1282     OMX_DBG( "PortReconfigure(%d)", p_port->definition.eDir );
1283
1284     /* Sanity checking */
1285     OMX_INIT_STRUCTURE(definition);
1286     definition.nPortIndex = p_port->i_port_index;
1287     omx_error = OMX_GetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1288                                  &definition);
1289     if(omx_error != OMX_ErrorNone || (p_dec->fmt_in.i_cat == VIDEO_ES &&
1290        (!definition.format.video.nFrameWidth ||
1291        !definition.format.video.nFrameHeight)) )
1292         return OMX_ErrorUndefined;
1293
1294     if( p_port->p_hwbuf && HwBuffer_Stop( p_dec, p_port ) != 0 )
1295         msg_Warn( p_dec, "HwBuffer_Stop failed" );
1296
1297     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortDisable,
1298                                  p_port->i_port_index, NULL);
1299     CHECK_ERROR(omx_error, "OMX_CommandPortDisable on %i failed (%x)",
1300                 (int)p_port->i_port_index, omx_error );
1301
1302     omx_error = FreeBuffers( p_dec, p_port );
1303     CHECK_ERROR(omx_error, "FreeBuffers failed (%x, %i)",
1304                 omx_error, (int)p_port->i_port_index );
1305
1306     if( p_port->p_hwbuf )
1307     {
1308         HwBuffer_FreeBuffers( p_dec, p_port );
1309         HwBuffer_Join( p_dec, p_port );
1310     }
1311
1312     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
1313     CHECK_ERROR(omx_error, "Wait for PortDisable failed (%x)", omx_error );
1314
1315     /* Get the new port definition */
1316     omx_error = GetPortDefinition(p_dec, &p_sys->out, p_sys->out.p_fmt);
1317     if(omx_error != OMX_ErrorNone) goto error;
1318
1319     if( p_port->p_hwbuf )
1320     {
1321         if( HwBuffer_AllocateBuffers( p_dec, p_port ) != 0 )
1322         {
1323             omx_error = OMX_ErrorInsufficientResources;
1324             goto error;
1325         }
1326     }
1327     else if( p_dec->fmt_in.i_cat != AUDIO_ES )
1328     {
1329         /* Don't explicitly set the new parameters that we got with
1330          * OMX_GetParameter above when using audio codecs.
1331          * That struct hasn't been changed since, so there should be
1332          * no need to set it here, unless some codec expects the
1333          * SetParameter call as a trigger event for some part of
1334          * the reconfiguration.
1335          * This fixes using audio decoders on Samsung Galaxy S II,
1336          *
1337          * Only skipping this for audio codecs, to minimize the
1338          * change for current working configurations for video.
1339          */
1340         omx_error = OMX_SetParameter(p_dec->p_sys->omx_handle, OMX_IndexParamPortDefinition,
1341                                      &definition);
1342         CHECK_ERROR(omx_error, "OMX_SetParameter failed (%x : %s)",
1343                     omx_error, ErrorToString(omx_error));
1344     }
1345
1346     omx_error = OMX_SendCommand( p_sys->omx_handle, OMX_CommandPortEnable,
1347                                  p_port->i_port_index, NULL);
1348     CHECK_ERROR(omx_error, "OMX_CommandPortEnable on %i failed (%x)",
1349                 (int)p_port->i_port_index, omx_error );
1350
1351     omx_error = AllocateBuffers( p_dec, p_port );
1352     CHECK_ERROR(omx_error, "OMX_AllocateBuffers failed (%x, %i)",
1353                 omx_error, (int)p_port->i_port_index );
1354
1355     omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
1356     CHECK_ERROR(omx_error, "Wait for PortEnable failed (%x)", omx_error );
1357
1358     if( p_port->p_hwbuf && HwBuffer_Start( p_dec, p_port ) != 0 )
1359     {
1360         omx_error = OMX_ErrorUndefined;
1361         goto error;
1362     }
1363
1364     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->in.i_port_index);
1365     PrintOmx(p_dec, p_sys->omx_handle, p_dec->p_sys->out.i_port_index);
1366
1367     OMX_DBG( "PortReconfigure(%d)::done", p_port->definition.eDir );
1368  error:
1369     return omx_error;
1370 }
1371
1372 /*****************************************************************************
1373  * DecodeVideoOutput
1374  *****************************************************************************/
1375 static int DecodeVideoOutput( decoder_t *p_dec, OmxPort *p_port, picture_t **pp_pic )
1376 {
1377     VLC_UNUSED( p_dec );
1378     OMX_BUFFERHEADERTYPE *p_header;
1379     picture_t *p_pic = NULL, *p_next_pic;
1380     OMX_ERRORTYPE omx_error;
1381
1382     while(!p_pic)
1383     {
1384         OMX_FIFO_PEEK(&p_port->fifo, p_header);
1385         if(!p_header) break; /* No frame available */
1386
1387         if(p_port->b_update_def)
1388         {
1389             omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1390             p_port->b_update_def = 0;
1391             CHECK_ERROR(omx_error, "GetPortDefinition failed");
1392         }
1393
1394         if( p_port->p_hwbuf )
1395         {
1396             if( HwBuffer_GetPic( p_dec, p_port, &p_pic ) != 0 )
1397                 goto error;
1398             else
1399                 continue;
1400         }
1401
1402         if(p_header->nFilledLen)
1403         {
1404             p_pic = p_header->pAppPrivate;
1405             if(!p_pic)
1406             {
1407                 /* We're not in direct rendering mode.
1408                  * Get a new picture and copy the content */
1409                 p_pic = decoder_NewPicture( p_dec );
1410
1411                 if (p_pic)
1412                     CopyOmxPicture(p_port->definition.format.video.eColorFormat,
1413                                    p_pic, p_port->definition.format.video.nSliceHeight,
1414                                    p_port->i_frame_stride,
1415                                    p_header->pBuffer + p_header->nOffset,
1416                                    p_port->i_frame_stride_chroma_div, NULL);
1417             }
1418
1419             if (p_pic)
1420                 p_pic->date = FromOmxTicks(p_header->nTimeStamp);
1421             p_header->nFilledLen = 0;
1422             p_header->pAppPrivate = 0;
1423         }
1424
1425         /* Get a new picture */
1426         if(p_port->b_direct && !p_header->pAppPrivate)
1427         {
1428             p_next_pic = decoder_NewPicture( p_dec );
1429             if(!p_next_pic) break;
1430
1431             OMX_FIFO_GET(&p_port->fifo, p_header);
1432             p_header->pAppPrivate = p_next_pic;
1433             p_header->pInputPortPrivate = p_header->pBuffer;
1434             p_header->pBuffer = p_next_pic->p[0].p_pixels;
1435         }
1436         else
1437         {
1438             OMX_FIFO_GET(&p_port->fifo, p_header);
1439         }
1440         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1441         OMX_FillThisBuffer(p_port->omx_handle, p_header);
1442     }
1443
1444     *pp_pic = p_pic;
1445     return 0;
1446 error:
1447     return -1;
1448 }
1449
1450 static int DecodeVideoInput( decoder_t *p_dec, OmxPort *p_port, block_t **pp_block,
1451                              unsigned int i_input_used, bool *p_reconfig )
1452 {
1453     decoder_sys_t *p_sys = p_dec->p_sys;
1454     OMX_BUFFERHEADERTYPE *p_header;
1455     struct H264ConvertState convert_state = { 0, 0 };
1456     block_t *p_block = *pp_block;
1457
1458     /* Send the input buffer to the component */
1459     OMX_FIFO_GET_TIMEOUT(&p_port->fifo, p_header, 10000);
1460
1461     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1462         free(p_header);
1463         *p_reconfig = true;
1464         return 0;
1465     }
1466     *p_reconfig = false;
1467
1468     if(p_header)
1469     {
1470         bool decode_more = false;
1471         p_header->nFilledLen = p_block->i_buffer - i_input_used;
1472         p_header->nOffset = 0;
1473         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1474         if (p_sys->b_use_pts && p_block->i_pts)
1475             p_header->nTimeStamp = ToOmxTicks(p_block->i_pts);
1476         else
1477             p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1478
1479         /* In direct mode we pass the input pointer as is.
1480          * Otherwise we memcopy the data */
1481         if(p_port->b_direct)
1482         {
1483             p_header->pOutputPortPrivate = p_header->pBuffer;
1484             p_header->pBuffer = p_block->p_buffer;
1485             p_header->pAppPrivate = p_block;
1486             i_input_used = p_header->nFilledLen;
1487         }
1488         else
1489         {
1490             if(p_header->nFilledLen > p_header->nAllocLen)
1491             {
1492                 p_header->nFilledLen = p_header->nAllocLen;
1493             }
1494             memcpy(p_header->pBuffer, p_block->p_buffer + i_input_used, p_header->nFilledLen);
1495             i_input_used += p_header->nFilledLen;
1496             if (i_input_used == p_block->i_buffer)
1497             {
1498                 block_Release(p_block);
1499             }
1500             else
1501             {
1502                 decode_more = true;
1503                 p_header->nFlags &= ~OMX_BUFFERFLAG_ENDOFFRAME;
1504             }
1505         }
1506
1507         /* Convert H.264 NAL format to annex b. Doesn't do anything if
1508          * i_nal_size_length == 0, which is the case for codecs other
1509          * than H.264 */
1510         convert_h264_to_annexb( p_header->pBuffer, p_header->nFilledLen,
1511                                 p_sys->i_nal_size_length, &convert_state );
1512         OMX_DBG( "EmptyThisBuffer %p, %p, %i, %"PRId64, p_header, p_header->pBuffer,
1513                  (int)p_header->nFilledLen, FromOmxTicks(p_header->nTimeStamp) );
1514         OMX_EmptyThisBuffer(p_port->omx_handle, p_header);
1515         p_port->b_flushed = false;
1516         if (decode_more)
1517             return DecodeVideoInput( p_dec, p_port, pp_block, i_input_used,
1518                                      p_reconfig );
1519         else
1520             *pp_block = NULL; /* Avoid being fed the same packet again */
1521     }
1522
1523     return 0;
1524 }
1525
1526 /*****************************************************************************
1527  * DecodeVideo: Called to decode one frame
1528  *****************************************************************************/
1529 static picture_t *DecodeVideo( decoder_t *p_dec, block_t **pp_block )
1530 {
1531     decoder_sys_t *p_sys = p_dec->p_sys;
1532     picture_t *p_pic = NULL;
1533     OMX_ERRORTYPE omx_error;
1534     unsigned int i;
1535     block_t *p_block;
1536
1537     if( !pp_block || !*pp_block )
1538         return NULL;
1539
1540     p_block = *pp_block;
1541
1542     /* Check for errors from codec */
1543     if(p_sys->b_error)
1544     {
1545         msg_Dbg(p_dec, "error during decoding");
1546         block_Release( p_block );
1547         return 0;
1548     }
1549
1550     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1551     {
1552         block_Release( p_block );
1553         if(!p_sys->in.b_flushed)
1554         {
1555             msg_Dbg(p_dec, "flushing");
1556             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1557                              p_sys->in.definition.nPortIndex, 0 );
1558         }
1559         p_sys->in.b_flushed = true;
1560         return NULL;
1561     }
1562
1563     /* Use the aspect ratio provided by the input (ie read from packetizer).
1564      * In case the we get aspect ratio info from the decoder (as in the
1565      * broadcom OMX implementation on RPi), don't let the packetizer values
1566      * override what the decoder says, if anything - otherwise always update
1567      * even if it already is set (since it can change within a stream). */
1568     if((p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) &&
1569        (p_dec->fmt_out.video.i_sar_num == 0 || p_dec->fmt_out.video.i_sar_den == 0 ||
1570              !p_sys->b_aspect_ratio_handled))
1571     {
1572         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
1573         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
1574     }
1575
1576     /* Take care of decoded frames first */
1577     if( DecodeVideoOutput( p_dec, &p_sys->out, &p_pic ) != 0 )
1578         goto error;
1579
1580     /* Loop as long as we haven't either got an input buffer (and cleared
1581      * *pp_block) or got an output picture */
1582     int max_polling_attempts = 100;
1583     int attempts = 0;
1584     while( *pp_block && !p_pic ) {
1585         bool b_reconfig = false;
1586
1587         if( DecodeVideoInput( p_dec, &p_sys->in, pp_block, 0, &b_reconfig ) != 0 )
1588             goto error;
1589
1590         /* If we don't have a p_pic from the first try. Try again */
1591         if( !b_reconfig && !p_pic &&
1592             DecodeVideoOutput( p_dec, &p_sys->out, &p_pic ) != 0 )
1593             goto error;
1594
1595         /* Handle the PortSettingsChanged events */
1596         for(i = 0; i < p_sys->ports; i++)
1597         {
1598             OmxPort *p_port = &p_sys->p_ports[i];
1599             if(p_port->b_reconfigure)
1600             {
1601                 omx_error = PortReconfigure(p_dec, p_port);
1602                 p_port->b_reconfigure = 0;
1603                 CHECK_ERROR(omx_error, "PortReconfigure failed");
1604             }
1605             if(p_port->b_update_def)
1606             {
1607                 omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1608                 p_port->b_update_def = 0;
1609                 CHECK_ERROR(omx_error, "GetPortDefinition failed");
1610             }
1611         }
1612
1613         attempts++;
1614         /* With opaque DR the output buffers are released by the
1615            vout therefore we implement a timeout for polling in
1616            order to avoid being indefinitely stalled in this loop, if
1617            playback is paused. */
1618         if( p_sys->out.p_hwbuf && attempts == max_polling_attempts ) {
1619 #ifdef USE_IOMX
1620             picture_t *invalid_picture = decoder_NewPicture(p_dec);
1621             if (invalid_picture) {
1622                 invalid_picture->date = VLC_TS_INVALID;
1623                 picture_sys_t *p_picsys = invalid_picture->p_sys;
1624                 p_picsys->pf_display_callback = NULL;
1625                 p_picsys->pf_unlock_callback = NULL;
1626                 p_picsys->p_dec = NULL;
1627                 p_picsys->i_index = -1;
1628                 p_picsys->b_valid = false;
1629             } else {
1630                 /* If we cannot return a picture we must free the
1631                    block since the decoder will proceed with the
1632                    next block. */
1633                 block_Release(p_block);
1634                 *pp_block = NULL;
1635             }
1636             return invalid_picture;
1637 #endif
1638         }
1639     }
1640
1641     return p_pic;
1642 error:
1643     p_sys->b_error = true;
1644     return NULL;
1645 }
1646
1647 /*****************************************************************************
1648  * DecodeAudio: Called to decode one frame
1649  *****************************************************************************/
1650 block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1651 {
1652     decoder_sys_t *p_sys = p_dec->p_sys;
1653     block_t *p_buffer = NULL;
1654     OMX_BUFFERHEADERTYPE *p_header;
1655     OMX_ERRORTYPE omx_error;
1656     block_t *p_block;
1657     unsigned int i;
1658
1659     if( !pp_block || !*pp_block ) return NULL;
1660
1661     p_block = *pp_block;
1662
1663     /* Check for errors from codec */
1664     if(p_sys->b_error)
1665     {
1666         msg_Dbg(p_dec, "error during decoding");
1667         block_Release( p_block );
1668         return 0;
1669     }
1670
1671     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1672     {
1673         block_Release( p_block );
1674         date_Set( &p_sys->end_date, 0 );
1675         if(!p_sys->in.b_flushed)
1676         {
1677             msg_Dbg(p_dec, "flushing");
1678             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1679                              p_sys->in.definition.nPortIndex, 0 );
1680         }
1681         p_sys->in.b_flushed = true;
1682         return NULL;
1683     }
1684
1685     if( !date_Get( &p_sys->end_date ) )
1686     {
1687         if( !p_block->i_pts )
1688         {
1689             /* We've just started the stream, wait for the first PTS. */
1690             block_Release( p_block );
1691             return NULL;
1692         }
1693         date_Set( &p_sys->end_date, p_block->i_pts );
1694     }
1695
1696     /* Take care of decoded frames first */
1697     while(!p_buffer)
1698     {
1699         unsigned int i_samples = 0;
1700
1701         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1702         if(!p_header) break; /* No frame available */
1703
1704         if (p_sys->out.p_fmt->audio.i_channels)
1705             i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1706         if(i_samples)
1707         {
1708             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1709             if( !p_buffer ) break; /* No audio buffer available */
1710
1711             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1712             p_header->nFilledLen = 0;
1713
1714             int64_t timestamp = FromOmxTicks(p_header->nTimeStamp);
1715             if( timestamp != 0 &&
1716                 timestamp != date_Get( &p_sys->end_date ) )
1717                 date_Set( &p_sys->end_date, timestamp );
1718
1719             p_buffer->i_pts = date_Get( &p_sys->end_date );
1720             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1721                 p_buffer->i_pts;
1722         }
1723
1724         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1725         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1726         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1727     }
1728
1729
1730     /* Send the input buffer to the component */
1731     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1732
1733     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1734         free(p_header);
1735         goto reconfig;
1736     }
1737
1738     if(p_header)
1739     {
1740         p_header->nFilledLen = p_block->i_buffer;
1741         p_header->nOffset = 0;
1742         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1743         p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1744
1745         /* In direct mode we pass the input pointer as is.
1746          * Otherwise we memcopy the data */
1747         if(p_sys->in.b_direct)
1748         {
1749             p_header->pOutputPortPrivate = p_header->pBuffer;
1750             p_header->pBuffer = p_block->p_buffer;
1751             p_header->pAppPrivate = p_block;
1752         }
1753         else
1754         {
1755             if(p_header->nFilledLen > p_header->nAllocLen)
1756             {
1757                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1758                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1759                 p_header->nFilledLen = p_header->nAllocLen;
1760             }
1761             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1762             block_Release(p_block);
1763         }
1764
1765         OMX_DBG( "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1766                  (int)p_header->nFilledLen );
1767         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1768         p_sys->in.b_flushed = false;
1769         *pp_block = NULL; /* Avoid being fed the same packet again */
1770     }
1771
1772 reconfig:
1773     /* Handle the PortSettingsChanged events */
1774     for(i = 0; i < p_sys->ports; i++)
1775     {
1776         OmxPort *p_port = &p_sys->p_ports[i];
1777         if(!p_port->b_reconfigure) continue;
1778         p_port->b_reconfigure = 0;
1779         omx_error = PortReconfigure(p_dec, p_port);
1780         CHECK_ERROR(omx_error, "PortReconfigure failed");
1781     }
1782
1783     return p_buffer;
1784 error:
1785     p_sys->b_error = true;
1786     return NULL;
1787 }
1788
1789 /*****************************************************************************
1790  * EncodeVideo: Called to encode one frame
1791  *****************************************************************************/
1792 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1793 {
1794     decoder_t *p_dec = ( decoder_t *)p_enc;
1795     decoder_sys_t *p_sys = p_dec->p_sys;
1796     OMX_ERRORTYPE omx_error;
1797     unsigned int i;
1798
1799     OMX_BUFFERHEADERTYPE *p_header;
1800     block_t *p_block = 0;
1801
1802     if( !p_pic ) return NULL;
1803
1804     /* Check for errors from codec */
1805     if(p_sys->b_error)
1806     {
1807         msg_Dbg(p_dec, "error during encoding");
1808         return NULL;
1809     }
1810
1811     /* Send the input buffer to the component */
1812     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1813     if(p_header)
1814     {
1815         /* In direct mode we pass the input pointer as is.
1816          * Otherwise we memcopy the data */
1817         if(p_sys->in.b_direct)
1818         {
1819             p_header->pOutputPortPrivate = p_header->pBuffer;
1820             p_header->pBuffer = p_pic->p[0].p_pixels;
1821         }
1822         else
1823         {
1824             CopyVlcPicture(p_dec, p_header, p_pic);
1825         }
1826
1827         p_header->nFilledLen = p_sys->in.i_frame_size;
1828         p_header->nOffset = 0;
1829         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1830         p_header->nTimeStamp = ToOmxTicks(p_pic->date);
1831         OMX_DBG( "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1832                  (int)p_header->nFilledLen );
1833         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1834         p_sys->in.b_flushed = false;
1835     }
1836
1837     /* Handle the PortSettingsChanged events */
1838     for(i = 0; i < p_sys->ports; i++)
1839     {
1840         OmxPort *p_port = &p_sys->p_ports[i];
1841         if(!p_port->b_reconfigure) continue;
1842         p_port->b_reconfigure = 0;
1843         omx_error = PortReconfigure(p_dec, p_port);
1844         CHECK_ERROR(omx_error, "PortReconfigure failed");
1845     }
1846
1847     /* Wait for the decoded frame */
1848     while(!p_block)
1849     {
1850         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1851
1852         if(p_header->nFilledLen)
1853         {
1854             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1855             {
1856                 /* TODO: need to store codec config */
1857                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1858             }
1859
1860             p_block = p_header->pAppPrivate;
1861             if(!p_block)
1862             {
1863                 /* We're not in direct rendering mode.
1864                  * Get a new block and copy the content */
1865                 p_block = block_Alloc( p_header->nFilledLen );
1866                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1867             }
1868
1869             p_block->i_buffer = p_header->nFilledLen;
1870             p_block->i_pts = p_block->i_dts = FromOmxTicks(p_header->nTimeStamp);
1871             p_header->nFilledLen = 0;
1872             p_header->pAppPrivate = 0;
1873         }
1874
1875         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1876         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1877     }
1878
1879     msg_Dbg(p_dec, "done");
1880     return p_block;
1881 error:
1882     p_sys->b_error = true;
1883     return NULL;
1884 }
1885
1886 /*****************************************************************************
1887  * CloseGeneric: omxil decoder destruction
1888  *****************************************************************************/
1889 static void CloseGeneric( vlc_object_t *p_this )
1890 {
1891     decoder_t *p_dec = (decoder_t *)p_this;
1892     decoder_sys_t *p_sys = p_dec->p_sys;
1893
1894     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1895
1896     DeinitOmxCore();
1897
1898     DeinitOmxEventQueue(&p_sys->event_queue);
1899
1900     OMX_FIFO_DESTROY( &p_sys->in.fifo );
1901     OMX_FIFO_DESTROY( &p_sys->out.fifo );
1902
1903     free( p_sys );
1904 }
1905
1906 /*****************************************************************************
1907  * OmxEventHandler:
1908  *****************************************************************************/
1909 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1910     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1911     OMX_U32 data_2, OMX_PTR event_data )
1912 {
1913     decoder_t *p_dec = (decoder_t *)app_data;
1914     decoder_sys_t *p_sys = p_dec->p_sys;
1915     unsigned int i;
1916     (void)omx_handle;
1917
1918     PrintOmxEvent((vlc_object_t *) p_dec, event, data_1, data_2, event_data);
1919     switch (event)
1920     {
1921     case OMX_EventError:
1922         //p_sys->b_error = true;
1923         break;
1924
1925     case OMX_EventPortSettingsChanged:
1926         if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition ||
1927             data_2 == OMX_IndexParamAudioPcm )
1928         {
1929             OMX_BUFFERHEADERTYPE *sentinel;
1930             for(i = 0; i < p_sys->ports; i++)
1931                 if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1932                     p_sys->p_ports[i].b_reconfigure = true;
1933             sentinel = calloc(1, sizeof(*sentinel));
1934             if (sentinel) {
1935                 sentinel->nFlags = SENTINEL_FLAG;
1936                 OMX_FIFO_PUT(&p_sys->in.fifo, sentinel);
1937             }
1938         }
1939         else if( data_2 == OMX_IndexConfigCommonOutputCrop )
1940         {
1941             for(i = 0; i < p_sys->ports; i++)
1942                 if(p_sys->p_ports[i].definition.nPortIndex == data_1)
1943                     p_sys->p_ports[i].b_update_def = true;
1944         }
1945         else
1946         {
1947             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
1948         }
1949         break;
1950     case OMX_EventParamOrConfigChanged:
1951         UpdatePixelAspect(p_dec);
1952         break;
1953
1954     default:
1955         break;
1956     }
1957
1958     PostOmxEvent(&p_sys->event_queue, event, data_1, data_2, event_data);
1959     return OMX_ErrorNone;
1960 }
1961
1962 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1963     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1964 {
1965     decoder_t *p_dec = (decoder_t *)app_data;
1966     decoder_sys_t *p_sys = p_dec->p_sys;
1967     (void)omx_handle;
1968
1969     OMX_DBG( "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1970
1971     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1972     {
1973         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1974         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1975         if(p_block) block_Release(p_block);
1976         omx_header->pAppPrivate = 0;
1977     }
1978     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1979
1980     return OMX_ErrorNone;
1981 }
1982
1983 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1984     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1985 {
1986     decoder_t *p_dec = (decoder_t *)app_data;
1987     decoder_sys_t *p_sys = p_dec->p_sys;
1988     (void)omx_handle;
1989
1990     OMX_DBG( "OmxFillBufferDone %p, %p, %i, %"PRId64, omx_header, omx_header->pBuffer,
1991              (int)omx_header->nFilledLen, FromOmxTicks(omx_header->nTimeStamp) );
1992
1993     if(omx_header->pInputPortPrivate)
1994     {
1995         omx_header->pBuffer = omx_header->pInputPortPrivate;
1996     }
1997     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1998
1999     return OMX_ErrorNone;
2000 }
2001
2002 #if defined(USE_IOMX)
2003
2004 /* Life cycle of buffers when using IOMX direct rendering (HwBuffer):
2005  *
2006  * <- android display
2007  * DequeueThread owned++
2008  * -> OMX_FillThisBuffer
2009  * ...
2010  * <- FillBufferDone OMX_FIFO_PUT
2011  * ...
2012  * DecodeVideoOutput OMX_FIFO_GET
2013  * -> vlc core
2014  * ...
2015  * DisplayBuffer
2016  * -> android display owned--
2017  */
2018
2019 /*****************************************************************************
2020  * HwBuffer_ChangeState
2021  *****************************************************************************/
2022 static void HwBuffer_ChangeState( decoder_t *p_dec, OmxPort *p_port,
2023                                   int i_index, int i_state )
2024 {
2025     VLC_UNUSED( p_dec );
2026     p_port->p_hwbuf->i_states[i_index] = i_state;
2027     if( i_state == BUF_STATE_OWNED )
2028         p_port->p_hwbuf->i_owned++;
2029     else
2030         p_port->p_hwbuf->i_owned--;
2031
2032     OMX_DBG( "buffer[%d]: state -> %d, owned buffers: %u",
2033              i_index, i_state, p_port->p_hwbuf->i_owned );
2034 }
2035
2036 /*****************************************************************************
2037  * HwBuffer_Init
2038  *****************************************************************************/
2039 static void HwBuffer_Init( decoder_t *p_dec, OmxPort *p_port )
2040 {
2041     VLC_UNUSED( p_dec );
2042     void *surf;
2043     JNIEnv *p_env;
2044     OMX_ERRORTYPE omx_error;
2045
2046     if( !p_port->b_direct || p_port->definition.eDir != OMX_DirOutput ||
2047         p_port->p_fmt->i_cat != VIDEO_ES )
2048         return;
2049
2050     msg_Dbg( p_dec, "HwBuffer_Init");
2051
2052     if( !(pf_enable_graphic_buffers && pf_get_graphic_buffer_usage &&
2053           pf_omx_hwbuffer_connect && pf_omx_hwbuffer_disconnect &&
2054           pf_omx_hwbuffer_setup && pf_omx_hwbuffer_get_min_undequeued &&
2055           pf_omx_hwbuffer_set_buffer_count && pf_omx_hwbuffer_setcrop &&
2056           pf_omx_hwbuffer_dequeue && pf_omx_hwbuffer_lock &&
2057           pf_omx_hwbuffer_queue && pf_omx_hwbuffer_cancel &&
2058           pf_omx_hwbuffer_get_hal_format &&
2059           ((OMX_COMPONENTTYPE*)p_port->omx_handle)->UseBuffer) )
2060     {
2061         msg_Warn( p_dec, "direct output port enabled but can't find "
2062                           "extra symbols, switch back to non direct" );
2063         goto error;
2064     }
2065
2066     p_port->p_hwbuf = calloc(1, sizeof(HwBuffer));
2067     if( !p_port->p_hwbuf )
2068     {
2069         goto error;
2070     }
2071     vlc_cond_init (&p_port->p_hwbuf->wait);
2072     p_port->p_hwbuf->p_library = LoadNativeWindowAPI( &p_port->p_hwbuf->native_window );
2073     if( !p_port->p_hwbuf->p_library )
2074     {
2075         msg_Warn( p_dec, "LoadNativeWindowAPI failed" );
2076         goto error;
2077     }
2078
2079     surf = jni_LockAndGetAndroidJavaSurface();
2080     if( !surf ) {
2081         jni_UnlockAndroidSurface();
2082         msg_Warn( p_dec, "jni_LockAndGetAndroidJavaSurface failed" );
2083         goto error;
2084     }
2085
2086     (*myVm)->AttachCurrentThread( myVm, &p_env, NULL );
2087     p_port->p_hwbuf->window = p_port->p_hwbuf->native_window.winFromSurface( p_env, surf );
2088     (*myVm)->DetachCurrentThread( myVm );
2089
2090     jni_UnlockAndroidSurface();
2091     if( !p_port->p_hwbuf->window ) {
2092         msg_Warn( p_dec, "winFromSurface failed" );
2093         goto error;
2094     }
2095     pf_omx_hwbuffer_connect( p_port->p_hwbuf->window );
2096
2097     omx_error = pf_enable_graphic_buffers( p_port->omx_handle,
2098                                            p_port->i_port_index, OMX_TRUE );
2099     CHECK_ERROR( omx_error, "can't enable graphic buffers" );
2100
2101     /* PortDefinition may change after pf_enable_graphic_buffers call */
2102     omx_error = OMX_GetParameter( p_port->omx_handle,
2103                                   OMX_IndexParamPortDefinition,
2104                                   &p_port->definition );
2105     CHECK_ERROR( omx_error, "OMX_GetParameter failed (GraphicBuffers) (%x : %s)",
2106                  omx_error, ErrorToString(omx_error) );
2107
2108
2109     msg_Dbg( p_dec, "direct output port enabled" );
2110     return;
2111 error:
2112     /* if HwBuffer_Init fails, we can fall back to non direct buffers */
2113     HwBuffer_Destroy( p_dec, p_port );
2114 }
2115
2116 /*****************************************************************************
2117  * HwBuffer_Destroy
2118  *****************************************************************************/
2119 static void HwBuffer_Destroy( decoder_t *p_dec, OmxPort *p_port )
2120 {
2121     if( p_port->p_hwbuf )
2122     {
2123         if( p_port->p_hwbuf->p_library )
2124         {
2125             if( p_port->p_hwbuf->window )
2126             {
2127                 HwBuffer_Stop( p_dec, p_port );
2128                 HwBuffer_FreeBuffers( p_dec, p_port );
2129                 HwBuffer_Join( p_dec, p_port );
2130                 pf_omx_hwbuffer_disconnect( p_port->p_hwbuf->window );
2131                 pf_enable_graphic_buffers( p_port->omx_handle,
2132                                            p_port->i_port_index, OMX_FALSE );
2133                 p_port->p_hwbuf->native_window.winRelease( p_port->p_hwbuf->window );
2134             }
2135             dlclose( p_port->p_hwbuf->p_library );
2136         }
2137
2138         vlc_cond_destroy( &p_port->p_hwbuf->wait );
2139         free( p_port->p_hwbuf );
2140         p_port->p_hwbuf = NULL;
2141     }
2142     p_port->b_direct = false;
2143 }
2144
2145 /*****************************************************************************
2146  * HwBuffer_AllocateBuffers
2147  *****************************************************************************/
2148 static int HwBuffer_AllocateBuffers( decoder_t *p_dec, OmxPort *p_port )
2149 {
2150     decoder_sys_t *p_sys = p_dec->p_sys;
2151     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
2152     unsigned int min_undequeued = 0;
2153     unsigned int i = 0;
2154     int colorFormat = def->format.video.eColorFormat;
2155     OMX_ERRORTYPE omx_error;
2156     OMX_U32 i_hw_usage;
2157
2158     if( !p_port->p_hwbuf )
2159         return 0;
2160
2161     omx_error = pf_omx_hwbuffer_get_hal_format( p_sys->psz_component, &colorFormat );
2162     if( omx_error != OMX_ErrorNone )
2163     {
2164         msg_Warn( p_dec, "pf_omx_hwbuffer_get_hal_format failed (Not fatal)" );
2165     }
2166
2167     omx_error = pf_get_graphic_buffer_usage( p_port->omx_handle,
2168                                              p_port->i_port_index,
2169                                              &i_hw_usage );
2170     if( omx_error != OMX_ErrorNone )
2171     {
2172         msg_Warn( p_dec, "pf_get_graphic_buffer_usage failed (Not fatal)" );
2173         i_hw_usage = 0;
2174     }
2175
2176     if( pf_omx_hwbuffer_setup( p_port->p_hwbuf->window,
2177                                def->format.video.nFrameWidth,
2178                                def->format.video.nFrameHeight,
2179                                colorFormat,
2180                                (int) i_hw_usage ) != 0 )
2181     {
2182         msg_Err( p_dec, "can't setup OMXHWBuffer" );
2183         goto error;
2184     }
2185
2186     if( pf_omx_hwbuffer_get_min_undequeued( p_port->p_hwbuf->window,
2187                                             &min_undequeued ) != 0 )
2188     {
2189         msg_Err( p_dec, "can't get min_undequeued" );
2190         goto error;
2191     }
2192
2193     if( def->nBufferCountActual < def->nBufferCountMin + min_undequeued )
2194     {
2195         unsigned int new_frames_num = def->nBufferCountMin + min_undequeued;
2196
2197         OMX_DBG( "AllocateBuffers: video out wants more frames: %lu vs %u",
2198                  p_port->definition.nBufferCountActual, new_frames_num );
2199
2200         p_port->definition.nBufferCountActual = new_frames_num;
2201         omx_error = OMX_SetParameter( p_dec->p_sys->omx_handle,
2202                                       OMX_IndexParamPortDefinition,
2203                                       &p_port->definition );
2204         CHECK_ERROR( omx_error, "OMX_SetParameter failed (%x : %s)",
2205                      omx_error, ErrorToString(omx_error) );
2206     }
2207
2208     if( pf_omx_hwbuffer_set_buffer_count( p_port->p_hwbuf->window,
2209                                           def->nBufferCountActual ) != 0 )
2210     {
2211         msg_Err( p_dec, "can't set buffer_count" );
2212         goto error;
2213     }
2214
2215     jni_SetAndroidSurfaceSize( def->format.video.nFrameWidth,
2216                                def->format.video.nFrameHeight,
2217                                def->format.video.nFrameWidth,
2218                                def->format.video.nFrameHeight,
2219                                p_dec->fmt_out.video.i_sar_num,
2220                                p_dec->fmt_out.video.i_sar_den );
2221
2222     p_port->p_hwbuf->i_buffers = p_port->definition.nBufferCountActual;
2223     p_port->p_hwbuf->i_max_owned = p_port->p_hwbuf->i_buffers - min_undequeued;
2224
2225     p_port->p_hwbuf->pp_handles = calloc( p_port->p_hwbuf->i_buffers,
2226                                           sizeof(void *) );
2227     if( !p_port->p_hwbuf->pp_handles )
2228         goto error;
2229
2230     p_port->p_hwbuf->i_states = calloc( p_port->p_hwbuf->i_buffers, sizeof(int) );
2231     if( !p_port->p_hwbuf->i_states )
2232         goto error;
2233
2234     p_port->p_hwbuf->inflight_picture = calloc( p_port->p_hwbuf->i_buffers,
2235                                                 sizeof(picture_t*) );
2236     if( !p_port->p_hwbuf->inflight_picture )
2237         goto error;
2238
2239     for(i = 0; i < p_port->p_hwbuf->i_buffers; i++)
2240     {
2241         void *p_handle = NULL;
2242
2243         if( pf_omx_hwbuffer_dequeue( p_port->p_hwbuf->window, &p_handle ) != 0 )
2244         {
2245             msg_Err( p_dec, "OMXHWBuffer_dequeue Fail" );
2246             goto error;
2247         }
2248         p_port->p_hwbuf->pp_handles[i] = p_handle;
2249     }
2250     for(i = 0; i < p_port->p_hwbuf->i_max_owned; i++)
2251         HwBuffer_ChangeState( p_dec, p_port, i, BUF_STATE_OWNED );
2252     for(; i < p_port->p_hwbuf->i_buffers; i++)
2253     {
2254         OMX_DBG( "canceling buffer(%d)", i );
2255         pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window,
2256                                 p_port->p_hwbuf->pp_handles[i] );
2257     }
2258
2259     return 0;
2260
2261 error:
2262
2263     msg_Err( p_dec, "HwBuffer_AllocateBuffers(%d) failed", def->eDir );
2264     return -1;
2265 }
2266
2267 /*****************************************************************************
2268  * HwBuffer_FreeBuffers
2269  *****************************************************************************/
2270 static int HwBuffer_FreeBuffers( decoder_t *p_dec, OmxPort *p_port )
2271 {
2272     msg_Dbg( p_dec, "HwBuffer_FreeBuffers");
2273
2274     HWBUFFER_LOCK();
2275
2276     p_port->p_hwbuf->b_run = false;
2277
2278     if( p_port->p_hwbuf->pp_handles )
2279     {
2280         for(unsigned int i = 0; i < p_port->p_hwbuf->i_buffers; i++)
2281         {
2282             void *p_handle = p_port->p_hwbuf->pp_handles[i];
2283
2284             if( p_handle && p_port->p_hwbuf->i_states[i] == BUF_STATE_OWNED )
2285             {
2286                 pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2287                 HwBuffer_ChangeState( p_dec, p_port, i, BUF_STATE_NOT_OWNED );
2288             }
2289         }
2290     }
2291     HWBUFFER_BROADCAST( p_port );
2292
2293     HWBUFFER_UNLOCK();
2294
2295     p_port->p_hwbuf->i_buffers = 0;
2296
2297     free( p_port->p_hwbuf->pp_handles );
2298     p_port->p_hwbuf->pp_handles = NULL;
2299
2300     free( p_port->p_hwbuf->i_states );
2301     p_port->p_hwbuf->i_states = NULL;
2302
2303     free( p_port->p_hwbuf->inflight_picture );
2304     p_port->p_hwbuf->inflight_picture = NULL;
2305
2306     return 0;
2307 }
2308
2309 /*****************************************************************************
2310  * HwBuffer_Start
2311  *****************************************************************************/
2312 static int HwBuffer_Start( decoder_t *p_dec, OmxPort *p_port )
2313 {
2314     OMX_BUFFERHEADERTYPE *p_header;
2315
2316     msg_Dbg( p_dec, "HwBuffer_Start" );
2317     HWBUFFER_LOCK();
2318
2319     /* fill all owned buffers dequeued by HwBuffer_AllocatesBuffers */
2320     for(unsigned int i = 0; i < p_port->p_hwbuf->i_buffers; i++)
2321     {
2322         p_header = p_port->pp_buffers[i];
2323
2324         if( p_header && p_port->p_hwbuf->i_states[i] == BUF_STATE_OWNED )
2325         {
2326             if( pf_omx_hwbuffer_lock( p_port->p_hwbuf->window,
2327                                       p_header->pBuffer ) != 0 )
2328             {
2329                 msg_Err( p_dec, "lock failed" );
2330                 HWBUFFER_UNLOCK();
2331                 return -1;
2332             }
2333             OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
2334             OMX_FillThisBuffer( p_port->omx_handle, p_header );
2335         }
2336     }
2337
2338     p_port->p_hwbuf->b_run = true;
2339     if( vlc_clone( &p_port->p_hwbuf->dequeue_thread,
2340                    DequeueThread, p_dec, VLC_THREAD_PRIORITY_LOW ) )
2341     {
2342         p_port->p_hwbuf->b_run = false;
2343         HWBUFFER_UNLOCK();
2344         return -1;
2345     }
2346
2347     HWBUFFER_UNLOCK();
2348
2349     return 0;
2350 }
2351
2352 /*****************************************************************************
2353  * HwBuffer_Stop: stop DequeueThread and invalidate all pictures that are sent
2354  * to vlc core. The thread can be stuck in pf_omx_hwbuffer_dequeue, so don't
2355  * join it now since it can be unblocked later by HwBuffer_FreeBuffers.
2356  *****************************************************************************/
2357 static int HwBuffer_Stop( decoder_t *p_dec, OmxPort *p_port )
2358 {
2359     VLC_UNUSED( p_dec );
2360
2361     msg_Dbg( p_dec, "HwBuffer_Stop" );
2362     HWBUFFER_LOCK();
2363
2364     p_port->p_hwbuf->b_run = false;
2365
2366     /* invalidate and release all inflight pictures */
2367     if( p_port->p_hwbuf->inflight_picture ) {
2368         for( unsigned int i = 0; i < p_port->i_buffers; ++i ) {
2369             picture_t *p_pic = p_port->p_hwbuf->inflight_picture[i];
2370             if( p_pic ) {
2371                 picture_sys_t *p_picsys = p_pic->p_sys;
2372                 if( p_picsys ) {
2373                     void *p_handle = p_port->pp_buffers[p_picsys->i_index]->pBuffer;
2374                     if( p_handle )
2375                     {
2376                         pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2377                         HwBuffer_ChangeState( p_dec, p_port, p_picsys->i_index,
2378                                               BUF_STATE_NOT_OWNED );
2379                     }
2380                     p_picsys->b_valid = false;
2381                 }
2382                 p_port->p_hwbuf->inflight_picture[i] = NULL;
2383             }
2384         }
2385     }
2386
2387     HWBUFFER_BROADCAST( p_port );
2388
2389     HWBUFFER_UNLOCK();
2390
2391     return 0;
2392 }
2393
2394 /*****************************************************************************
2395  * HwBuffer_Join: join DequeueThread previously stopped by HwBuffer_Stop.
2396  *****************************************************************************/
2397 static int HwBuffer_Join( decoder_t *p_dec, OmxPort *p_port )
2398 {
2399     VLC_UNUSED( p_dec );
2400
2401     if( p_port->p_hwbuf->dequeue_thread )
2402     {
2403         vlc_join( p_port->p_hwbuf->dequeue_thread, NULL );
2404         p_port->p_hwbuf->dequeue_thread = NULL;
2405     }
2406     return 0;
2407 }
2408
2409 /*****************************************************************************
2410  * HwBuffer_GetPic
2411  *****************************************************************************/
2412 static int HwBuffer_GetPic( decoder_t *p_dec, OmxPort *p_port,
2413                             picture_t **pp_pic)
2414 {
2415     int i_index = -1;
2416     picture_t *p_pic;
2417     picture_sys_t *p_picsys;
2418     OMX_BUFFERHEADERTYPE *p_header;
2419
2420     OMX_FIFO_PEEK(&p_port->fifo, p_header);
2421
2422     if( !p_header )
2423         return 0;
2424
2425     for(unsigned int i = 0; i < p_port->i_buffers; i++)
2426     {
2427         if( p_port->pp_buffers[i] == p_header )
2428         {
2429             i_index = i;
2430             break;
2431         }
2432     }
2433     if( i_index == -1 )
2434     {
2435         msg_Err( p_dec, "output buffer not found" );
2436         return -1;
2437     }
2438
2439     p_pic = decoder_NewPicture( p_dec );
2440     if(!p_pic)
2441     {
2442         msg_Err( p_dec, "decoder_NewPicture failed" );
2443         return -1;
2444     }
2445     p_pic->date = FromOmxTicks( p_header->nTimeStamp );
2446
2447     p_picsys = p_pic->p_sys;
2448     p_picsys->pf_display_callback = DisplayCallback;
2449     p_picsys->pf_unlock_callback = UnlockCallback;
2450     p_picsys->p_dec = p_dec;
2451     p_picsys->i_index = i_index;
2452     p_picsys->b_valid = true;
2453
2454     HWBUFFER_LOCK();
2455     p_port->p_hwbuf->inflight_picture[i_index] = p_pic;
2456     HWBUFFER_UNLOCK();
2457
2458     *pp_pic = p_pic;
2459     OMX_FIFO_GET( &p_port->fifo, p_header );
2460     return 0;
2461 }
2462
2463 /*****************************************************************************
2464  * HwBuffer_SetCrop
2465  *****************************************************************************/
2466 static void HwBuffer_SetCrop( decoder_t *p_dec, OmxPort *p_port,
2467                               OMX_CONFIG_RECTTYPE *p_rect )
2468 {
2469     VLC_UNUSED( p_dec );
2470
2471     pf_omx_hwbuffer_setcrop( p_port->p_hwbuf->window,
2472                              p_rect->nLeft, p_rect->nTop,
2473                              p_rect->nWidth, p_rect->nHeight );
2474 }
2475
2476 /*****************************************************************************
2477  * DequeueThread
2478  *****************************************************************************/
2479 static void *DequeueThread( void *data )
2480 {
2481     decoder_t *p_dec = data;
2482     decoder_sys_t *p_sys = p_dec->p_sys;;
2483     OmxPort *p_port = &p_sys->out;
2484     unsigned int i;
2485     int i_index = -1;
2486     int err;
2487     void *p_handle = NULL;
2488     OMX_BUFFERHEADERTYPE *p_header;
2489
2490     msg_Dbg( p_dec, "DequeueThread running");
2491     HWBUFFER_LOCK();
2492     while( p_port->p_hwbuf->b_run )
2493     {
2494         while( p_port->p_hwbuf->b_run &&
2495                p_port->p_hwbuf->i_owned >= p_port->p_hwbuf->i_max_owned )
2496             HWBUFFER_WAIT( p_port );
2497
2498         if( !p_port->p_hwbuf->b_run ) continue;
2499
2500         HWBUFFER_UNLOCK();
2501
2502
2503         /* The thread can be stuck here. It shouldn't happen since we make sure
2504          * we call the dequeue function if there is at least one buffer
2505          * available. */
2506         err = pf_omx_hwbuffer_dequeue( p_port->p_hwbuf->window, &p_handle );
2507         if( err == 0 )
2508             err = pf_omx_hwbuffer_lock( p_port->p_hwbuf->window, p_handle );
2509
2510         HWBUFFER_LOCK();
2511
2512         if( err != 0 ) {
2513             if( err != -EBUSY )
2514                 p_port->p_hwbuf->b_run = false;
2515             continue;
2516         }
2517
2518         if( !p_port->p_hwbuf->b_run )
2519         {
2520             pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2521             continue;
2522         }
2523
2524         for(i = 0; i < p_port->i_buffers; i++)
2525         {
2526             if( p_port->pp_buffers[i]->pBuffer == p_handle )
2527             {
2528                 i_index = i;
2529                 p_header = p_port->pp_buffers[i_index];
2530                 break;
2531             }
2532         }
2533         if( i_index == -1 )
2534         {
2535             msg_Err( p_dec, "pf_omx_hwbuffer_dequeue returned unknown handle" );
2536             continue;
2537         }
2538
2539         HwBuffer_ChangeState( p_dec, p_port, i_index, BUF_STATE_OWNED );
2540
2541         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
2542         OMX_FillThisBuffer( p_sys->omx_handle, p_header );
2543
2544         HWBUFFER_BROADCAST( p_port );
2545     }
2546     HWBUFFER_UNLOCK();
2547
2548     msg_Dbg( p_dec, "DequeueThread stopped");
2549     return NULL;
2550 }
2551
2552 /*****************************************************************************
2553  * vout callbacks
2554  *****************************************************************************/
2555 static void DisplayBuffer( picture_sys_t* p_picsys, bool b_render )
2556 {
2557     decoder_t *p_dec = p_picsys->p_dec;
2558     decoder_sys_t *p_sys = p_dec->p_sys;
2559     OmxPort *p_port = &p_sys->out;
2560     void *p_handle;
2561
2562     if( !p_picsys->b_valid ) return;
2563
2564     HWBUFFER_LOCK();
2565
2566     /* Picture might have been invalidated while waiting on the mutex. */
2567     if (!p_picsys->b_valid) {
2568         HWBUFFER_UNLOCK();
2569         return;
2570     }
2571
2572     p_handle = p_port->pp_buffers[p_picsys->i_index]->pBuffer;
2573
2574     OMX_DBG( "DisplayBuffer: %s %p",
2575              b_render ? "render" : "cancel", p_handle );
2576
2577     if( !p_handle )
2578     {
2579         msg_Err( p_dec, "DisplayBuffer: buffer handle invalid" );
2580         goto end;
2581     }
2582
2583     if( b_render )
2584         pf_omx_hwbuffer_queue( p_port->p_hwbuf->window, p_handle );
2585     else
2586         pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2587
2588     HwBuffer_ChangeState( p_dec, p_port, p_picsys->i_index, BUF_STATE_NOT_OWNED );
2589     HWBUFFER_BROADCAST( p_port );
2590
2591     p_port->p_hwbuf->inflight_picture[p_picsys->i_index] = NULL;
2592
2593 end:
2594     p_picsys->b_valid = false;
2595     p_picsys->i_index = -1;
2596
2597     HWBUFFER_UNLOCK();
2598 }
2599
2600 static void UnlockCallback( picture_sys_t* p_picsys )
2601 {
2602     DisplayBuffer( p_picsys, false );
2603 }
2604
2605 static void DisplayCallback( picture_sys_t* p_picsys )
2606 {
2607     DisplayBuffer( p_picsys, true );
2608 }
2609
2610 #endif // USE_IOMX