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