]> git.sesse.net Git - vlc/blob - modules/codec/omxil/omxil.c
omxil: add android hw buffers support (zero copy)
[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", false,
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, 200000);
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     bool b_reconfig;
1536     block_t *p_block;
1537
1538     if( !pp_block || !*pp_block )
1539         return NULL;
1540
1541     p_block = *pp_block;
1542
1543     /* Check for errors from codec */
1544     if(p_sys->b_error)
1545     {
1546         msg_Dbg(p_dec, "error during decoding");
1547         block_Release( p_block );
1548         return 0;
1549     }
1550
1551     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1552     {
1553         block_Release( p_block );
1554         if(!p_sys->in.b_flushed)
1555         {
1556             msg_Dbg(p_dec, "flushing");
1557             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1558                              p_sys->in.definition.nPortIndex, 0 );
1559         }
1560         p_sys->in.b_flushed = true;
1561         return NULL;
1562     }
1563
1564     /* Use the aspect ratio provided by the input (ie read from packetizer).
1565      * In case the we get aspect ratio info from the decoder (as in the
1566      * broadcom OMX implementation on RPi), don't let the packetizer values
1567      * override what the decoder says, if anything - otherwise always update
1568      * even if it already is set (since it can change within a stream). */
1569     if((p_dec->fmt_in.video.i_sar_num != 0 && p_dec->fmt_in.video.i_sar_den != 0) &&
1570        (p_dec->fmt_out.video.i_sar_num == 0 || p_dec->fmt_out.video.i_sar_den == 0 ||
1571              !p_sys->b_aspect_ratio_handled))
1572     {
1573         p_dec->fmt_out.video.i_sar_num = p_dec->fmt_in.video.i_sar_num;
1574         p_dec->fmt_out.video.i_sar_den = p_dec->fmt_in.video.i_sar_den;
1575     }
1576
1577     /* Take care of decoded frames first */
1578     if( DecodeVideoOutput( p_dec, &p_sys->out, &p_pic ) != 0 )
1579         goto error;
1580
1581     if( DecodeVideoInput( p_dec, &p_sys->in, pp_block, 0, &b_reconfig ) != 0 )
1582         goto error;
1583
1584     /* If we don't have a p_pic from the first try. Try again */
1585     if( !b_reconfig && !p_pic &&
1586         DecodeVideoOutput( p_dec, &p_sys->out, &p_pic ) != 0 )
1587         goto error;
1588
1589     /* Handle the PortSettingsChanged events */
1590     for(i = 0; i < p_sys->ports; i++)
1591     {
1592         OmxPort *p_port = &p_sys->p_ports[i];
1593         if(p_port->b_reconfigure)
1594         {
1595             omx_error = PortReconfigure(p_dec, p_port);
1596             p_port->b_reconfigure = 0;
1597             CHECK_ERROR(omx_error, "PortReconfigure failed");
1598         }
1599         if(p_port->b_update_def)
1600         {
1601             omx_error = GetPortDefinition(p_dec, p_port, p_port->p_fmt);
1602             p_port->b_update_def = 0;
1603             CHECK_ERROR(omx_error, "GetPortDefinition failed");
1604         }
1605     }
1606
1607     return p_pic;
1608 error:
1609     p_sys->b_error = true;
1610     return NULL;
1611 }
1612
1613 /*****************************************************************************
1614  * DecodeAudio: Called to decode one frame
1615  *****************************************************************************/
1616 block_t *DecodeAudio ( decoder_t *p_dec, block_t **pp_block )
1617 {
1618     decoder_sys_t *p_sys = p_dec->p_sys;
1619     block_t *p_buffer = NULL;
1620     OMX_BUFFERHEADERTYPE *p_header;
1621     OMX_ERRORTYPE omx_error;
1622     block_t *p_block;
1623     unsigned int i;
1624
1625     if( !pp_block || !*pp_block ) return NULL;
1626
1627     p_block = *pp_block;
1628
1629     /* Check for errors from codec */
1630     if(p_sys->b_error)
1631     {
1632         msg_Dbg(p_dec, "error during decoding");
1633         block_Release( p_block );
1634         return 0;
1635     }
1636
1637     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
1638     {
1639         block_Release( p_block );
1640         date_Set( &p_sys->end_date, 0 );
1641         if(!p_sys->in.b_flushed)
1642         {
1643             msg_Dbg(p_dec, "flushing");
1644             OMX_SendCommand( p_sys->omx_handle, OMX_CommandFlush,
1645                              p_sys->in.definition.nPortIndex, 0 );
1646         }
1647         p_sys->in.b_flushed = true;
1648         return NULL;
1649     }
1650
1651     if( !date_Get( &p_sys->end_date ) )
1652     {
1653         if( !p_block->i_pts )
1654         {
1655             /* We've just started the stream, wait for the first PTS. */
1656             block_Release( p_block );
1657             return NULL;
1658         }
1659         date_Set( &p_sys->end_date, p_block->i_pts );
1660     }
1661
1662     /* Take care of decoded frames first */
1663     while(!p_buffer)
1664     {
1665         unsigned int i_samples = 0;
1666
1667         OMX_FIFO_PEEK(&p_sys->out.fifo, p_header);
1668         if(!p_header) break; /* No frame available */
1669
1670         if (p_sys->out.p_fmt->audio.i_channels)
1671             i_samples = p_header->nFilledLen / p_sys->out.p_fmt->audio.i_channels / 2;
1672         if(i_samples)
1673         {
1674             p_buffer = decoder_NewAudioBuffer( p_dec, i_samples );
1675             if( !p_buffer ) break; /* No audio buffer available */
1676
1677             memcpy( p_buffer->p_buffer, p_header->pBuffer, p_buffer->i_buffer );
1678             p_header->nFilledLen = 0;
1679
1680             int64_t timestamp = FromOmxTicks(p_header->nTimeStamp);
1681             if( timestamp != 0 &&
1682                 timestamp != date_Get( &p_sys->end_date ) )
1683                 date_Set( &p_sys->end_date, timestamp );
1684
1685             p_buffer->i_pts = date_Get( &p_sys->end_date );
1686             p_buffer->i_length = date_Increment( &p_sys->end_date, i_samples ) -
1687                 p_buffer->i_pts;
1688         }
1689
1690         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1691         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1692         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1693     }
1694
1695
1696     /* Send the input buffer to the component */
1697     OMX_FIFO_GET_TIMEOUT(&p_sys->in.fifo, p_header, 200000);
1698
1699     if (p_header && p_header->nFlags & SENTINEL_FLAG) {
1700         free(p_header);
1701         goto reconfig;
1702     }
1703
1704     if(p_header)
1705     {
1706         p_header->nFilledLen = p_block->i_buffer;
1707         p_header->nOffset = 0;
1708         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1709         p_header->nTimeStamp = ToOmxTicks(p_block->i_dts);
1710
1711         /* In direct mode we pass the input pointer as is.
1712          * Otherwise we memcopy the data */
1713         if(p_sys->in.b_direct)
1714         {
1715             p_header->pOutputPortPrivate = p_header->pBuffer;
1716             p_header->pBuffer = p_block->p_buffer;
1717             p_header->pAppPrivate = p_block;
1718         }
1719         else
1720         {
1721             if(p_header->nFilledLen > p_header->nAllocLen)
1722             {
1723                 msg_Dbg(p_dec, "buffer too small (%i,%i)",
1724                         (int)p_header->nFilledLen, (int)p_header->nAllocLen);
1725                 p_header->nFilledLen = p_header->nAllocLen;
1726             }
1727             memcpy(p_header->pBuffer, p_block->p_buffer, p_header->nFilledLen );
1728             block_Release(p_block);
1729         }
1730
1731         OMX_DBG( "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1732                  (int)p_header->nFilledLen );
1733         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1734         p_sys->in.b_flushed = false;
1735         *pp_block = NULL; /* Avoid being fed the same packet again */
1736     }
1737
1738 reconfig:
1739     /* Handle the PortSettingsChanged events */
1740     for(i = 0; i < p_sys->ports; i++)
1741     {
1742         OmxPort *p_port = &p_sys->p_ports[i];
1743         if(!p_port->b_reconfigure) continue;
1744         p_port->b_reconfigure = 0;
1745         omx_error = PortReconfigure(p_dec, p_port);
1746         CHECK_ERROR(omx_error, "PortReconfigure failed");
1747     }
1748
1749     return p_buffer;
1750 error:
1751     p_sys->b_error = true;
1752     return NULL;
1753 }
1754
1755 /*****************************************************************************
1756  * EncodeVideo: Called to encode one frame
1757  *****************************************************************************/
1758 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pic )
1759 {
1760     decoder_t *p_dec = ( decoder_t *)p_enc;
1761     decoder_sys_t *p_sys = p_dec->p_sys;
1762     OMX_ERRORTYPE omx_error;
1763     unsigned int i;
1764
1765     OMX_BUFFERHEADERTYPE *p_header;
1766     block_t *p_block = 0;
1767
1768     if( !p_pic ) return NULL;
1769
1770     /* Check for errors from codec */
1771     if(p_sys->b_error)
1772     {
1773         msg_Dbg(p_dec, "error during encoding");
1774         return NULL;
1775     }
1776
1777     /* Send the input buffer to the component */
1778     OMX_FIFO_GET(&p_sys->in.fifo, p_header);
1779     if(p_header)
1780     {
1781         /* In direct mode we pass the input pointer as is.
1782          * Otherwise we memcopy the data */
1783         if(p_sys->in.b_direct)
1784         {
1785             p_header->pOutputPortPrivate = p_header->pBuffer;
1786             p_header->pBuffer = p_pic->p[0].p_pixels;
1787         }
1788         else
1789         {
1790             CopyVlcPicture(p_dec, p_header, p_pic);
1791         }
1792
1793         p_header->nFilledLen = p_sys->in.i_frame_size;
1794         p_header->nOffset = 0;
1795         p_header->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
1796         p_header->nTimeStamp = ToOmxTicks(p_pic->date);
1797         OMX_DBG( "EmptyThisBuffer %p, %p, %i", p_header, p_header->pBuffer,
1798                  (int)p_header->nFilledLen );
1799         OMX_EmptyThisBuffer(p_sys->omx_handle, p_header);
1800         p_sys->in.b_flushed = false;
1801     }
1802
1803     /* Handle the PortSettingsChanged events */
1804     for(i = 0; i < p_sys->ports; i++)
1805     {
1806         OmxPort *p_port = &p_sys->p_ports[i];
1807         if(!p_port->b_reconfigure) continue;
1808         p_port->b_reconfigure = 0;
1809         omx_error = PortReconfigure(p_dec, p_port);
1810         CHECK_ERROR(omx_error, "PortReconfigure failed");
1811     }
1812
1813     /* Wait for the decoded frame */
1814     while(!p_block)
1815     {
1816         OMX_FIFO_GET(&p_sys->out.fifo, p_header);
1817
1818         if(p_header->nFilledLen)
1819         {
1820             if(p_header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)
1821             {
1822                 /* TODO: need to store codec config */
1823                 msg_Dbg(p_dec, "received codec config %i", (int)p_header->nFilledLen);
1824             }
1825
1826             p_block = p_header->pAppPrivate;
1827             if(!p_block)
1828             {
1829                 /* We're not in direct rendering mode.
1830                  * Get a new block and copy the content */
1831                 p_block = block_Alloc( p_header->nFilledLen );
1832                 memcpy(p_block->p_buffer, p_header->pBuffer, p_header->nFilledLen );
1833             }
1834
1835             p_block->i_buffer = p_header->nFilledLen;
1836             p_block->i_pts = p_block->i_dts = FromOmxTicks(p_header->nTimeStamp);
1837             p_header->nFilledLen = 0;
1838             p_header->pAppPrivate = 0;
1839         }
1840
1841         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
1842         OMX_FillThisBuffer(p_sys->omx_handle, p_header);
1843     }
1844
1845     msg_Dbg(p_dec, "done");
1846     return p_block;
1847 error:
1848     p_sys->b_error = true;
1849     return NULL;
1850 }
1851
1852 /*****************************************************************************
1853  * CloseGeneric: omxil decoder destruction
1854  *****************************************************************************/
1855 static void CloseGeneric( vlc_object_t *p_this )
1856 {
1857     decoder_t *p_dec = (decoder_t *)p_this;
1858     decoder_sys_t *p_sys = p_dec->p_sys;
1859
1860     if(p_sys->omx_handle) DeinitialiseComponent(p_dec, p_sys->omx_handle);
1861
1862     DeinitOmxCore();
1863
1864     DeinitOmxEventQueue(&p_sys->event_queue);
1865
1866     OMX_FIFO_DESTROY( &p_sys->in.fifo );
1867     OMX_FIFO_DESTROY( &p_sys->out.fifo );
1868
1869     free( p_sys );
1870 }
1871
1872 /*****************************************************************************
1873  * OmxEventHandler:
1874  *****************************************************************************/
1875 static OMX_ERRORTYPE OmxEventHandler( OMX_HANDLETYPE omx_handle,
1876     OMX_PTR app_data, OMX_EVENTTYPE event, OMX_U32 data_1,
1877     OMX_U32 data_2, OMX_PTR event_data )
1878 {
1879     decoder_t *p_dec = (decoder_t *)app_data;
1880     decoder_sys_t *p_sys = p_dec->p_sys;
1881     unsigned int i;
1882     (void)omx_handle;
1883
1884     PrintOmxEvent((vlc_object_t *) p_dec, event, data_1, data_2, event_data);
1885     switch (event)
1886     {
1887     case OMX_EventError:
1888         //p_sys->b_error = true;
1889         break;
1890
1891     case OMX_EventPortSettingsChanged:
1892         if( data_2 == 0 || data_2 == OMX_IndexParamPortDefinition ||
1893             data_2 == OMX_IndexParamAudioPcm )
1894         {
1895             OMX_BUFFERHEADERTYPE *sentinel;
1896             for(i = 0; i < p_sys->ports; i++)
1897                 if(p_sys->p_ports[i].definition.eDir == OMX_DirOutput)
1898                     p_sys->p_ports[i].b_reconfigure = true;
1899             sentinel = calloc(1, sizeof(*sentinel));
1900             if (sentinel) {
1901                 sentinel->nFlags = SENTINEL_FLAG;
1902                 OMX_FIFO_PUT(&p_sys->in.fifo, sentinel);
1903             }
1904         }
1905         else if( data_2 == OMX_IndexConfigCommonOutputCrop )
1906         {
1907             for(i = 0; i < p_sys->ports; i++)
1908                 if(p_sys->p_ports[i].definition.nPortIndex == data_1)
1909                     p_sys->p_ports[i].b_update_def = true;
1910         }
1911         else
1912         {
1913             msg_Dbg( p_dec, "Unhandled setting change %x", (unsigned int)data_2 );
1914         }
1915         break;
1916     case OMX_EventParamOrConfigChanged:
1917         UpdatePixelAspect(p_dec);
1918         break;
1919
1920     default:
1921         break;
1922     }
1923
1924     PostOmxEvent(&p_sys->event_queue, event, data_1, data_2, event_data);
1925     return OMX_ErrorNone;
1926 }
1927
1928 static OMX_ERRORTYPE OmxEmptyBufferDone( OMX_HANDLETYPE omx_handle,
1929     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1930 {
1931     decoder_t *p_dec = (decoder_t *)app_data;
1932     decoder_sys_t *p_sys = p_dec->p_sys;
1933     (void)omx_handle;
1934
1935     OMX_DBG( "OmxEmptyBufferDone %p, %p", omx_header, omx_header->pBuffer );
1936
1937     if(omx_header->pAppPrivate || omx_header->pOutputPortPrivate)
1938     {
1939         block_t *p_block = (block_t *)omx_header->pAppPrivate;
1940         omx_header->pBuffer = omx_header->pOutputPortPrivate;
1941         if(p_block) block_Release(p_block);
1942         omx_header->pAppPrivate = 0;
1943     }
1944     OMX_FIFO_PUT(&p_sys->in.fifo, omx_header);
1945
1946     return OMX_ErrorNone;
1947 }
1948
1949 static OMX_ERRORTYPE OmxFillBufferDone( OMX_HANDLETYPE omx_handle,
1950     OMX_PTR app_data, OMX_BUFFERHEADERTYPE *omx_header )
1951 {
1952     decoder_t *p_dec = (decoder_t *)app_data;
1953     decoder_sys_t *p_sys = p_dec->p_sys;
1954     (void)omx_handle;
1955
1956     OMX_DBG( "OmxFillBufferDone %p, %p, %i, %"PRId64, omx_header, omx_header->pBuffer,
1957              (int)omx_header->nFilledLen, FromOmxTicks(omx_header->nTimeStamp) );
1958
1959     if(omx_header->pInputPortPrivate)
1960     {
1961         omx_header->pBuffer = omx_header->pInputPortPrivate;
1962     }
1963     OMX_FIFO_PUT(&p_sys->out.fifo, omx_header);
1964
1965     return OMX_ErrorNone;
1966 }
1967
1968 #if defined(USE_IOMX)
1969
1970 /* Life cycle of buffers when using IOMX direct rendering (HwBuffer):
1971  *
1972  * <- android display
1973  * DequeueThread owned++
1974  * -> OMX_FillThisBuffer
1975  * ...
1976  * <- FillBufferDone OMX_FIFO_PUT
1977  * ...
1978  * DecodeVideoOutput OMX_FIFO_GET
1979  * -> vlc core
1980  * ...
1981  * DisplayBuffer
1982  * -> android display owned--
1983  */
1984
1985 /*****************************************************************************
1986  * HwBuffer_ChangeState
1987  *****************************************************************************/
1988 static void HwBuffer_ChangeState( decoder_t *p_dec, OmxPort *p_port,
1989                                   int i_index, int i_state )
1990 {
1991     VLC_UNUSED( p_dec );
1992     p_port->p_hwbuf->i_states[i_index] = i_state;
1993     if( i_state == BUF_STATE_OWNED )
1994         p_port->p_hwbuf->i_owned++;
1995     else
1996         p_port->p_hwbuf->i_owned--;
1997
1998     OMX_DBG( "buffer[%d]: state -> %d, owned buffers: %u",
1999              i_index, i_state, p_port->p_hwbuf->i_owned );
2000 }
2001
2002 /*****************************************************************************
2003  * HwBuffer_Init
2004  *****************************************************************************/
2005 static void HwBuffer_Init( decoder_t *p_dec, OmxPort *p_port )
2006 {
2007     VLC_UNUSED( p_dec );
2008     void *surf;
2009     JNIEnv *p_env;
2010     OMX_ERRORTYPE omx_error;
2011
2012     if( !p_port->b_direct || p_port->definition.eDir != OMX_DirOutput ||
2013         p_port->p_fmt->i_cat != VIDEO_ES )
2014         return;
2015
2016     msg_Dbg( p_dec, "HwBuffer_Init");
2017
2018     if( !(pf_enable_graphic_buffers && pf_get_graphic_buffer_usage &&
2019           pf_omx_hwbuffer_connect && pf_omx_hwbuffer_disconnect &&
2020           pf_omx_hwbuffer_setup && pf_omx_hwbuffer_setcrop &&
2021           pf_omx_hwbuffer_dequeue && pf_omx_hwbuffer_queue &&
2022           pf_omx_hwbuffer_cancel &&
2023           ((OMX_COMPONENTTYPE*)p_port->omx_handle)->UseBuffer) )
2024     {
2025         msg_Warn( p_dec, "direct output port enabled but can't find "
2026                           "extra symbols, switch back to non direct" );
2027         goto error;
2028     }
2029
2030     p_port->p_hwbuf = calloc(1, sizeof(HwBuffer));
2031     if( !p_port->p_hwbuf )
2032     {
2033         goto error;
2034     }
2035     vlc_cond_init (&p_port->p_hwbuf->wait);
2036     p_port->p_hwbuf->p_library = LoadNativeWindowAPI( &p_port->p_hwbuf->native_window );
2037     if( !p_port->p_hwbuf->p_library )
2038     {
2039         msg_Warn( p_dec, "LoadNativeWindowAPI failed" );
2040         goto error;
2041     }
2042
2043     surf = jni_LockAndGetAndroidJavaSurface();
2044     if( !surf ) {
2045         jni_UnlockAndroidSurface();
2046         msg_Warn( p_dec, "jni_LockAndGetAndroidJavaSurface failed" );
2047         goto error;
2048     }
2049
2050     (*myVm)->AttachCurrentThread( myVm, &p_env, NULL );
2051     p_port->p_hwbuf->window = p_port->p_hwbuf->native_window.winFromSurface( p_env, surf );
2052     (*myVm)->DetachCurrentThread( myVm );
2053
2054     jni_UnlockAndroidSurface();
2055     if( !p_port->p_hwbuf->window ) {
2056         msg_Warn( p_dec, "winFromSurface failed" );
2057         goto error;
2058     }
2059     pf_omx_hwbuffer_connect( p_port->p_hwbuf->window );
2060
2061     omx_error = pf_enable_graphic_buffers( p_port->omx_handle,
2062                                            p_port->i_port_index, OMX_TRUE );
2063     CHECK_ERROR( omx_error, "can't enable graphic buffers" );
2064
2065     /* PortDefinition may change after pf_enable_graphic_buffers call */
2066     omx_error = OMX_GetParameter( p_port->omx_handle,
2067                                   OMX_IndexParamPortDefinition,
2068                                   &p_port->definition );
2069     CHECK_ERROR( omx_error, "OMX_GetParameter failed (GraphicBuffers) (%x : %s)",
2070                  omx_error, ErrorToString(omx_error) );
2071
2072
2073     msg_Dbg( p_dec, "direct output port enabled" );
2074     return;
2075 error:
2076     /* if HwBuffer_Init fails, we can fall back to non direct buffers */
2077     HwBuffer_Destroy( p_dec, p_port );
2078 }
2079
2080 /*****************************************************************************
2081  * HwBuffer_Destroy
2082  *****************************************************************************/
2083 static void HwBuffer_Destroy( decoder_t *p_dec, OmxPort *p_port )
2084 {
2085     if( p_port->p_hwbuf )
2086     {
2087         if( p_port->p_hwbuf->p_library )
2088         {
2089             if( p_port->p_hwbuf->window )
2090             {
2091                 HwBuffer_Stop( p_dec, p_port );
2092                 HwBuffer_FreeBuffers( p_dec, p_port );
2093                 HwBuffer_Join( p_dec, p_port );
2094                 pf_omx_hwbuffer_disconnect( p_port->p_hwbuf->window );
2095                 pf_enable_graphic_buffers( p_port->omx_handle,
2096                                            p_port->i_port_index, OMX_FALSE );
2097                 p_port->p_hwbuf->native_window.winRelease( p_port->p_hwbuf->window );
2098             }
2099             dlclose( p_port->p_hwbuf->p_library );
2100         }
2101
2102         vlc_cond_destroy( &p_port->p_hwbuf->wait );
2103         free( p_port->p_hwbuf );
2104         p_port->p_hwbuf = NULL;
2105     }
2106     p_port->b_direct = false;
2107 }
2108
2109 /*****************************************************************************
2110  * HwBuffer_AllocateBuffers
2111  *****************************************************************************/
2112 static int HwBuffer_AllocateBuffers( decoder_t *p_dec, OmxPort *p_port )
2113 {
2114     decoder_sys_t *p_sys = p_dec->p_sys;
2115     OMX_PARAM_PORTDEFINITIONTYPE *def = &p_port->definition;
2116     unsigned int min_undequeued = 0;
2117     unsigned int num_frames = def->nBufferCountMin;
2118     unsigned int i = 0;
2119     int colorFormat = def->format.video.eColorFormat;
2120     OMX_ERRORTYPE omx_error;
2121     OMX_U32 i_hw_usage;
2122
2123     if( !p_port->p_hwbuf )
2124         return 0;
2125
2126     if( !strncmp( p_sys->psz_component, "OMX.SEC.", 8 ) ) {
2127         switch( colorFormat ) {
2128         case OMX_COLOR_FormatYUV420SemiPlanar:
2129             colorFormat = 0x105; // HAL_PIXEL_FORMAT_YCbCr_420_SP
2130             break;
2131         case OMX_COLOR_FormatYUV420Planar:
2132             colorFormat = 0x101; // HAL_PIXEL_FORMAT_YCbCr_420_P
2133             break;
2134         }
2135     }
2136
2137     omx_error = pf_get_graphic_buffer_usage( p_port->omx_handle,
2138                                              p_port->i_port_index,
2139                                              &i_hw_usage );
2140     if( omx_error != OMX_ErrorNone )
2141     {
2142         msg_Warn( p_dec, "pf_get_graphic_buffer_usage failed (Not fatal)" );
2143         i_hw_usage = 0;
2144     }
2145
2146     if( pf_omx_hwbuffer_setup( p_port->p_hwbuf->window,
2147                                def->format.video.nFrameWidth,
2148                                def->format.video.nFrameHeight,
2149                                colorFormat,
2150                                (int) i_hw_usage,
2151                                &num_frames, &min_undequeued) != 0 )
2152     {
2153         msg_Err( p_dec, "can't setup OMXHWBuffer" );
2154         goto error;
2155     }
2156
2157     if( num_frames != p_port->definition.nBufferCountActual )
2158     {
2159         OMX_DBG( "AllocateBuffers: video out wants more frames: %lu vs %u",
2160                  p_port->definition.nBufferCountActual, num_frames);
2161
2162         p_port->definition.nBufferCountActual = num_frames;
2163         omx_error = OMX_SetParameter( p_dec->p_sys->omx_handle,
2164                                       OMX_IndexParamPortDefinition,
2165                                       &p_port->definition );
2166         CHECK_ERROR( omx_error, "OMX_SetParameter failed (%x : %s)",
2167                      omx_error, ErrorToString(omx_error) );
2168     }
2169
2170     jni_SetAndroidSurfaceSize( def->format.video.nFrameWidth,
2171                                def->format.video.nFrameHeight,
2172                                def->format.video.nFrameWidth,
2173                                def->format.video.nFrameHeight,
2174                                p_dec->fmt_out.video.i_sar_num,
2175                                p_dec->fmt_out.video.i_sar_den );
2176
2177     p_port->p_hwbuf->i_buffers = p_port->definition.nBufferCountActual;
2178     p_port->p_hwbuf->i_max_owned = p_port->p_hwbuf->i_buffers - min_undequeued;
2179
2180     p_port->p_hwbuf->pp_handles = calloc( p_port->p_hwbuf->i_buffers,
2181                                           sizeof(void *) );
2182     if( !p_port->p_hwbuf->pp_handles )
2183         goto error;
2184
2185     p_port->p_hwbuf->i_states = calloc( p_port->p_hwbuf->i_buffers, sizeof(int) );
2186     if( !p_port->p_hwbuf->i_states )
2187         goto error;
2188
2189     p_port->p_hwbuf->inflight_picture = calloc( p_port->p_hwbuf->i_buffers,
2190                                                 sizeof(picture_t*) );
2191     if( !p_port->p_hwbuf->inflight_picture )
2192         goto error;
2193
2194     for(i = 0; i < p_port->p_hwbuf->i_buffers; i++)
2195     {
2196         void *p_handle = NULL;
2197
2198         if( pf_omx_hwbuffer_dequeue( p_port->p_hwbuf->window, &p_handle ) != 0 )
2199         {
2200             msg_Err( p_dec, "OMXHWBuffer_dequeue Fail" );
2201             goto error;
2202         }
2203         p_port->p_hwbuf->pp_handles[i] = p_handle;
2204     }
2205     for(i = 0; i < p_port->p_hwbuf->i_max_owned; i++)
2206         HwBuffer_ChangeState( p_dec, p_port, i, BUF_STATE_OWNED );
2207     for(; i < p_port->p_hwbuf->i_buffers; i++)
2208     {
2209         OMX_DBG( "canceling buffer(%d)", i );
2210         pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window,
2211                                 p_port->p_hwbuf->pp_handles[i] );
2212     }
2213
2214     return 0;
2215
2216 error:
2217
2218     msg_Err( p_dec, "HwBuffer_AllocateBuffers(%d) failed", def->eDir );
2219     return -1;
2220 }
2221
2222 /*****************************************************************************
2223  * HwBuffer_FreeBuffers
2224  *****************************************************************************/
2225 static int HwBuffer_FreeBuffers( decoder_t *p_dec, OmxPort *p_port )
2226 {
2227     msg_Dbg( p_dec, "HwBuffer_FreeBuffers");
2228
2229     HWBUFFER_LOCK();
2230
2231     p_port->p_hwbuf->b_run = false;
2232
2233     if( p_port->p_hwbuf->pp_handles )
2234     {
2235         for(unsigned int i = 0; i < p_port->p_hwbuf->i_buffers; i++)
2236         {
2237             void *p_handle = p_port->p_hwbuf->pp_handles[i];
2238
2239             if( p_handle && p_port->p_hwbuf->i_states[i] == BUF_STATE_OWNED )
2240             {
2241                 pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2242                 HwBuffer_ChangeState( p_dec, p_port, i, BUF_STATE_NOT_OWNED );
2243             }
2244         }
2245     }
2246     HWBUFFER_BROADCAST( p_port );
2247
2248     HWBUFFER_UNLOCK();
2249
2250     p_port->p_hwbuf->i_buffers = 0;
2251
2252     free( p_port->p_hwbuf->pp_handles );
2253     p_port->p_hwbuf->pp_handles = NULL;
2254
2255     free( p_port->p_hwbuf->i_states );
2256     p_port->p_hwbuf->i_states = NULL;
2257
2258     free( p_port->p_hwbuf->inflight_picture );
2259     p_port->p_hwbuf->inflight_picture = NULL;
2260
2261     return 0;
2262 }
2263
2264 /*****************************************************************************
2265  * HwBuffer_Start
2266  *****************************************************************************/
2267 static int HwBuffer_Start( decoder_t *p_dec, OmxPort *p_port )
2268 {
2269     OMX_BUFFERHEADERTYPE *p_header;
2270
2271     msg_Dbg( p_dec, "HwBuffer_Start" );
2272     HWBUFFER_LOCK();
2273
2274     /* fill all owned buffers dequeued by HwBuffer_AllocatesBuffers */
2275     for(unsigned int i = 0; i < p_port->p_hwbuf->i_buffers; i++)
2276     {
2277         p_header = p_port->pp_buffers[i];
2278
2279         if( p_header && p_port->p_hwbuf->i_states[i] == BUF_STATE_OWNED )
2280         {
2281             OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
2282             OMX_FillThisBuffer( p_port->omx_handle, p_header );
2283         }
2284     }
2285
2286     p_port->p_hwbuf->b_run = true;
2287     if( vlc_clone( &p_port->p_hwbuf->dequeue_thread,
2288                    DequeueThread, p_dec, VLC_THREAD_PRIORITY_LOW ) )
2289     {
2290         p_port->p_hwbuf->b_run = false;
2291         HWBUFFER_UNLOCK();
2292         return -1;
2293     }
2294
2295     HWBUFFER_UNLOCK();
2296
2297     return 0;
2298 }
2299
2300 /*****************************************************************************
2301  * HwBuffer_Stop: stop DequeueThread and invalidate all pictures that are sent
2302  * to vlc core. The thread can be stuck in pf_omx_hwbuffer_dequeue, so don't
2303  * join it now since it can be unblocked later by HwBuffer_FreeBuffers.
2304  *****************************************************************************/
2305 static int HwBuffer_Stop( decoder_t *p_dec, OmxPort *p_port )
2306 {
2307     VLC_UNUSED( p_dec );
2308
2309     msg_Dbg( p_dec, "HwBuffer_Stop" );
2310     HWBUFFER_LOCK();
2311
2312     p_port->p_hwbuf->b_run = false;
2313
2314     /* invalidate and release all inflight pictures */
2315     if( p_port->p_hwbuf->inflight_picture ) {
2316         for( unsigned int i = 0; i < p_port->i_buffers; ++i ) {
2317             picture_t *p_pic = p_port->p_hwbuf->inflight_picture[i];
2318             if( p_pic ) {
2319                 picture_sys_t *p_picsys = p_pic->p_sys;
2320                 if( p_picsys ) {
2321                     void *p_handle = p_port->pp_buffers[p_picsys->i_index]->pBuffer;
2322                     if( p_handle )
2323                     {
2324                         pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2325                         HwBuffer_ChangeState( p_dec, p_port, p_picsys->i_index,
2326                                               BUF_STATE_NOT_OWNED );
2327                     }
2328                     p_picsys->b_valid = false;
2329                 }
2330                 p_port->p_hwbuf->inflight_picture[i] = NULL;
2331             }
2332         }
2333     }
2334
2335     HWBUFFER_BROADCAST( p_port );
2336
2337     HWBUFFER_UNLOCK();
2338
2339     return 0;
2340 }
2341
2342 /*****************************************************************************
2343  * HwBuffer_Join: join DequeueThread previously stopped by HwBuffer_Stop.
2344  *****************************************************************************/
2345 static int HwBuffer_Join( decoder_t *p_dec, OmxPort *p_port )
2346 {
2347     VLC_UNUSED( p_dec );
2348
2349     if( p_port->p_hwbuf->dequeue_thread )
2350     {
2351         vlc_join( p_port->p_hwbuf->dequeue_thread, NULL );
2352         p_port->p_hwbuf->dequeue_thread = NULL;
2353     }
2354     return 0;
2355 }
2356
2357 /*****************************************************************************
2358  * HwBuffer_GetPic
2359  *****************************************************************************/
2360 static int HwBuffer_GetPic( decoder_t *p_dec, OmxPort *p_port,
2361                             picture_t **pp_pic)
2362 {
2363     int i_index = -1;
2364     picture_t *p_pic;
2365     picture_sys_t *p_picsys;
2366     OMX_BUFFERHEADERTYPE *p_header;
2367
2368     OMX_FIFO_PEEK(&p_port->fifo, p_header);
2369
2370     if( !p_header )
2371         return 0;
2372
2373     for(unsigned int i = 0; i < p_port->i_buffers; i++)
2374     {
2375         if( p_port->pp_buffers[i] == p_header )
2376         {
2377             i_index = i;
2378             break;
2379         }
2380     }
2381     if( i_index == -1 )
2382     {
2383         msg_Err( p_dec, "output buffer not found" );
2384         return -1;
2385     }
2386
2387     p_pic = decoder_NewPicture( p_dec );
2388     if(!p_pic)
2389     {
2390         msg_Err( p_dec, "decoder_NewPicture failed" );
2391         return -1;
2392     }
2393     p_pic->date = FromOmxTicks( p_header->nTimeStamp );
2394
2395     p_picsys = p_pic->p_sys;
2396     p_picsys->pf_display_callback = DisplayCallback;
2397     p_picsys->pf_unlock_callback = UnlockCallback;
2398     p_picsys->p_dec = p_dec;
2399     p_picsys->i_index = i_index;
2400     p_picsys->b_valid = true;
2401
2402     HWBUFFER_LOCK();
2403     p_port->p_hwbuf->inflight_picture[i_index] = p_pic;
2404     HWBUFFER_UNLOCK();
2405
2406     *pp_pic = p_pic;
2407     OMX_FIFO_GET( &p_port->fifo, p_header );
2408     return 0;
2409 }
2410
2411 /*****************************************************************************
2412  * HwBuffer_SetCrop
2413  *****************************************************************************/
2414 static void HwBuffer_SetCrop( decoder_t *p_dec, OmxPort *p_port,
2415                               OMX_CONFIG_RECTTYPE *p_rect )
2416 {
2417     VLC_UNUSED( p_dec );
2418
2419     pf_omx_hwbuffer_setcrop( p_port->p_hwbuf->window,
2420                              p_rect->nLeft, p_rect->nTop,
2421                              p_rect->nWidth, p_rect->nHeight );
2422 }
2423
2424 /*****************************************************************************
2425  * DequeueThread
2426  *****************************************************************************/
2427 static void *DequeueThread( void *data )
2428 {
2429     decoder_t *p_dec = data;
2430     decoder_sys_t *p_sys = p_dec->p_sys;;
2431     OmxPort *p_port = &p_sys->out;
2432     unsigned int i;
2433     int i_index = -1;
2434     int err;
2435     void *p_handle = NULL;
2436     OMX_BUFFERHEADERTYPE *p_header;
2437
2438     msg_Dbg( p_dec, "DequeueThread running");
2439     HWBUFFER_LOCK();
2440     while( p_port->p_hwbuf->b_run )
2441     {
2442         while( p_port->p_hwbuf->b_run &&
2443                p_port->p_hwbuf->i_owned >= p_port->p_hwbuf->i_max_owned )
2444             HWBUFFER_WAIT( p_port );
2445
2446         if( !p_port->p_hwbuf->b_run ) continue;
2447
2448         HWBUFFER_UNLOCK();
2449
2450
2451         /* The thread can be stuck here. It shouldn't happen since we make sure
2452          * we call the dequeue function if there is at least one buffer
2453          * available. */
2454         err = pf_omx_hwbuffer_dequeue( p_port->p_hwbuf->window, &p_handle );
2455
2456         HWBUFFER_LOCK();
2457
2458         if( err != 0 ) {
2459             if( err != -EBUSY )
2460                 p_port->p_hwbuf->b_run = false;
2461             continue;
2462         }
2463
2464         if( !p_port->p_hwbuf->b_run )
2465         {
2466             pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2467             continue;
2468         }
2469
2470         for(i = 0; i < p_port->i_buffers; i++)
2471         {
2472             if( p_port->pp_buffers[i]->pBuffer == p_handle )
2473             {
2474                 i_index = i;
2475                 p_header = p_port->pp_buffers[i_index];
2476                 break;
2477             }
2478         }
2479         if( i_index == -1 )
2480         {
2481             msg_Err( p_dec, "pf_omx_hwbuffer_dequeue returned unknown handle" );
2482             continue;
2483         }
2484
2485         HwBuffer_ChangeState( p_dec, p_port, i_index, BUF_STATE_OWNED );
2486
2487         OMX_DBG( "FillThisBuffer %p, %p", p_header, p_header->pBuffer );
2488         OMX_FillThisBuffer( p_sys->omx_handle, p_header );
2489
2490         HWBUFFER_BROADCAST( p_port );
2491     }
2492     HWBUFFER_UNLOCK();
2493
2494     msg_Dbg( p_dec, "DequeueThread stopped");
2495     return NULL;
2496 }
2497
2498 /*****************************************************************************
2499  * vout callbacks
2500  *****************************************************************************/
2501 static void DisplayBuffer( picture_sys_t* p_picsys, bool b_render )
2502 {
2503     decoder_t *p_dec = p_picsys->p_dec;
2504     decoder_sys_t *p_sys = p_dec->p_sys;
2505     OmxPort *p_port = &p_sys->out;
2506     void *p_handle;
2507
2508     if( !p_picsys->b_valid ) return;
2509
2510     HWBUFFER_LOCK();
2511
2512     /* Picture might have been invalidated while waiting on the mutex. */
2513     if (!p_picsys->b_valid) {
2514         HWBUFFER_UNLOCK();
2515         return;
2516     }
2517
2518     p_handle = p_port->pp_buffers[p_picsys->i_index]->pBuffer;
2519
2520     OMX_DBG( "DisplayBuffer: %s %p",
2521              b_render ? "render" : "cancel", p_handle );
2522
2523     if( !p_handle )
2524     {
2525         msg_Err( p_dec, "DisplayBuffer: buffer handle invalid" );
2526         goto end;
2527     }
2528
2529     if( b_render )
2530         pf_omx_hwbuffer_queue( p_port->p_hwbuf->window, p_handle );
2531     else
2532         pf_omx_hwbuffer_cancel( p_port->p_hwbuf->window, p_handle );
2533
2534     HwBuffer_ChangeState( p_dec, p_port, p_picsys->i_index, BUF_STATE_NOT_OWNED );
2535     HWBUFFER_BROADCAST( p_port );
2536
2537     p_port->p_hwbuf->inflight_picture[p_picsys->i_index] = NULL;
2538
2539 end:
2540     p_picsys->b_valid = false;
2541     p_picsys->i_index = -1;
2542
2543     HWBUFFER_UNLOCK();
2544 }
2545
2546 static void UnlockCallback( picture_sys_t* p_picsys )
2547 {
2548     DisplayBuffer( p_picsys, false );
2549 }
2550
2551 static void DisplayCallback( picture_sys_t* p_picsys )
2552 {
2553     DisplayBuffer( p_picsys, true );
2554 }
2555
2556 #endif // USE_IOMX