1 /*****************************************************************************
2  * gstdecode.c: Decoder module making use of gstreamer
3  *****************************************************************************
4  * Copyright (C) 2014-2016 VLC authors and VideoLAN
5  * $Id:
6  *
7  * Author: Vikram Fugro <vikram.fugro@gmail.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library 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 GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, 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 <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_codec.h>
34 
35 #include <gst/gst.h>
36 #include <gst/video/video.h>
37 #include <gst/video/gstvideometa.h>
38 
39 #include <gst/app/gstappsrc.h>
40 #include <gst/gstatomicqueue.h>
41 
42 #include "gstvlcpictureplaneallocator.h"
43 #include "gstvlcvideosink.h"
44 
45 struct decoder_sys_t
46 {
47     GstElement *p_decoder;
48     GstElement *p_decode_src;
49     GstElement *p_decode_in;
50     GstElement *p_decode_out;
51 
52     GstVlcPicturePlaneAllocator *p_allocator;
53 
54     GstBus *p_bus;
55 
56     GstVideoInfo vinfo;
57     GstAtomicQueue *p_que;
58     bool b_prerolled;
59     bool b_running;
60 };
61 
62 typedef struct
63 {
64     GstCaps *p_sinkcaps;
65     GstCaps *p_srccaps;
66 } sink_src_caps_t;
67 
68 /*****************************************************************************
69  * Local prototypes
70  *****************************************************************************/
71 static int  OpenDecoder( vlc_object_t* );
72 static void CloseDecoder( vlc_object_t* );
73 static int  DecodeBlock( decoder_t*, block_t* );
74 static void Flush( decoder_t * );
75 
76 #define MODULE_DESCRIPTION N_( "Uses GStreamer framework's plugins " \
77         "to decode the media codecs" )
78 
79 #define USEDECODEBIN_TEXT N_( "Use DecodeBin" )
80 #define USEDECODEBIN_LONGTEXT N_( \
81     "DecodeBin is a container element, that can add and " \
82     "manage multiple elements. Apart from adding the decoders, " \
83     "decodebin also adds elementary stream parsers which can provide " \
84     "more info such as codec profile, level and other attributes, " \
85     "in the form of GstCaps (Stream Capabilities) to decoder." )
86 
87 vlc_module_begin( )
88     set_shortname( "GstDecode" )
89     add_shortcut( "gstdecode" )
set_category(CAT_INPUT)90     set_category( CAT_INPUT )
91     set_subcategory( SUBCAT_INPUT_VCODEC )
92     /* decoder main module */
93     set_description( N_( "GStreamer Based Decoder" ) )
94     set_help( MODULE_DESCRIPTION )
95     set_capability( "video decoder", 50 )
96     set_section( N_( "Decoding" ) , NULL )
97     set_callbacks( OpenDecoder, CloseDecoder )
98     add_bool( "use-decodebin", true, USEDECODEBIN_TEXT,
99         USEDECODEBIN_LONGTEXT, false )
100 vlc_module_end( )
101 
102 void gst_vlc_dec_ensure_empty_queue( decoder_t *p_dec )
103 {
104     decoder_sys_t *p_sys = p_dec->p_sys;
105     int i_count = 0;
106 
107     msg_Dbg( p_dec, "Ensuring the decoder queue is empty");
108 
109     /* Busy wait with sleep; As this is rare case and the
110      * wait might at max go for 3-4 iterations, preferred to not
111      * to throw in a cond/lock here. */
112     while( p_sys->b_running && i_count < 60 &&
113             gst_atomic_queue_length( p_sys->p_que ))
114     {
115         msleep ( 15000 );
116         i_count++;
117     }
118 
119     if( p_sys->b_running )
120     {
121         if( !gst_atomic_queue_length( p_sys->p_que ))
122             msg_Dbg( p_dec, "Ensured the decoder queue is empty" );
123         else
124             msg_Warn( p_dec, "Timed out when ensuring an empty queue" );
125     }
126     else
127         msg_Dbg( p_dec, "Ensuring empty decoder queue not required; decoder \
128                 not running" );
129 }
130 
131 /* Emitted by appsrc when serving a seek request.
132  * Seek over here is only used for flushing the buffers.
133  * Returns TRUE always, as the 'real' seek will be
134  * done by VLC framework */
seek_data_cb(GstAppSrc * p_src,guint64 l_offset,gpointer p_data)135 static gboolean seek_data_cb( GstAppSrc *p_src, guint64 l_offset,
136         gpointer p_data )
137 {
138     VLC_UNUSED( p_src );
139     decoder_t *p_dec = p_data;
140     msg_Dbg( p_dec, "appsrc seeking to %"G_GUINT64_FORMAT, l_offset );
141     return TRUE;
142 }
143 
144 /* Emitted by decodebin and links decodebin to vlcvideosink.
145  * Since only one elementary codec stream is fed to decodebin,
146  * this signal cannot be emitted more than once. */
pad_added_cb(GstElement * p_ele,GstPad * p_pad,gpointer p_data)147 static void pad_added_cb( GstElement *p_ele, GstPad *p_pad, gpointer p_data )
148 {
149     VLC_UNUSED( p_ele );
150     decoder_t *p_dec = p_data;
151     decoder_sys_t *p_sys = p_dec->p_sys;
152 
153     if( likely( gst_pad_has_current_caps( p_pad ) ) )
154     {
155         GstPadLinkReturn ret;
156         GstPad *p_sinkpad;
157 
158         msg_Dbg( p_dec, "linking the decoder with the vsink");
159 
160         p_sinkpad = gst_element_get_static_pad(
161                 p_sys->p_decode_out, "sink" );
162         ret = gst_pad_link( p_pad, p_sinkpad );
163         if( ret != GST_PAD_LINK_OK )
164             msg_Err( p_dec, "failed to link decoder with vsink");
165 
166         gst_object_unref( p_sinkpad );
167     }
168     else
169     {
170         msg_Err( p_dec, "decodebin src pad has no caps" );
171         GST_ELEMENT_ERROR( p_sys->p_decoder, STREAM, FAILED,
172                 ( "vlc stream error" ), NULL );
173     }
174 }
175 
caps_handoff_cb(GstElement * p_ele,GstCaps * p_caps,gpointer p_data)176 static gboolean caps_handoff_cb( GstElement* p_ele, GstCaps *p_caps,
177         gpointer p_data )
178 {
179     VLC_UNUSED( p_ele );
180     decoder_t *p_dec = p_data;
181     decoder_sys_t *p_sys = p_dec->p_sys;
182     GstVideoAlignment align;
183 
184     msg_Info( p_dec, "got new caps %s", gst_caps_to_string( p_caps ));
185 
186     if( !gst_video_info_from_caps( &p_sys->vinfo, p_caps ))
187     {
188         msg_Err( p_dec, "failed to negotiate" );
189         return FALSE;
190     }
191 
192     gst_vlc_dec_ensure_empty_queue( p_dec );
193     gst_video_alignment_reset( &align );
194 
195     return gst_vlc_set_vout_fmt( &p_sys->vinfo, &align, p_caps, p_dec );
196 }
197 
198 /* Emitted by vlcvideosink for every buffer,
199  * Adds the buffer to the queue */
frame_handoff_cb(GstElement * p_ele,GstBuffer * p_buf,gpointer p_data)200 static void frame_handoff_cb( GstElement *p_ele, GstBuffer *p_buf,
201         gpointer p_data )
202 {
203     VLC_UNUSED( p_ele );
204     decoder_t *p_dec = p_data;
205     decoder_sys_t *p_sys = p_dec->p_sys;
206 
207     /* Push the buffer to the queue */
208     gst_atomic_queue_push( p_sys->p_que, gst_buffer_ref( p_buf ) );
209 }
210 
211 /* Copy the frame data from the GstBuffer (from decoder)
212  * to the picture obtained from downstream in VLC.
213  * This function should be avoided as much
214  * as possible, since it involves a complete frame copy. */
gst_CopyPicture(picture_t * p_pic,GstVideoFrame * p_frame)215 static void gst_CopyPicture( picture_t *p_pic, GstVideoFrame *p_frame )
216 {
217     int i_plane, i_planes, i_line, i_dst_stride, i_src_stride;
218     uint8_t *p_dst, *p_src;
219     int i_w, i_h;
220 
221     i_planes = p_pic->i_planes;
222     for( i_plane = 0; i_plane < i_planes; i_plane++ )
223     {
224         p_dst = p_pic->p[i_plane].p_pixels;
225         p_src = GST_VIDEO_FRAME_PLANE_DATA( p_frame, i_plane );
226         i_dst_stride = p_pic->p[i_plane].i_pitch;
227         i_src_stride = GST_VIDEO_FRAME_PLANE_STRIDE( p_frame, i_plane );
228 
229         i_w = GST_VIDEO_FRAME_COMP_WIDTH( p_frame,
230                 i_plane ) * GST_VIDEO_FRAME_COMP_PSTRIDE( p_frame, i_plane );
231         i_h = GST_VIDEO_FRAME_COMP_HEIGHT( p_frame, i_plane );
232 
233         for( i_line = 0;
234                 i_line < __MIN( p_pic->p[i_plane].i_lines, i_h );
235                 i_line++ )
236         {
237             memcpy( p_dst, p_src, i_w );
238             p_src += i_src_stride;
239             p_dst += i_dst_stride;
240         }
241     }
242 }
243 
244 /* Check if the element can use this caps */
find_decoder_func(gconstpointer p_p1,gconstpointer p_p2)245 static gint find_decoder_func( gconstpointer p_p1, gconstpointer p_p2 )
246 {
247     GstElementFactory *p_factory;
248     sink_src_caps_t *p_caps;
249 
250     p_factory = ( GstElementFactory* )p_p1;
251     p_caps = ( sink_src_caps_t* )p_p2;
252 
253     return !( gst_element_factory_can_sink_any_caps( p_factory,
254                 p_caps->p_sinkcaps ) &&
255             gst_element_factory_can_src_any_caps( p_factory,
256                 p_caps->p_srccaps ));
257 }
258 
default_msg_handler(decoder_t * p_dec,GstMessage * p_msg)259 static bool default_msg_handler( decoder_t *p_dec, GstMessage *p_msg )
260 {
261     bool err = false;
262 
263     switch( GST_MESSAGE_TYPE( p_msg ) ){
264     case GST_MESSAGE_ERROR:
265         {
266             gchar  *psz_debug;
267             GError *p_error;
268 
269             gst_message_parse_error( p_msg, &p_error, &psz_debug );
270             g_free( psz_debug );
271 
272             msg_Err( p_dec, "Error from %s: %s",
273                     GST_ELEMENT_NAME( GST_MESSAGE_SRC( p_msg ) ),
274                     p_error->message );
275             g_error_free( p_error );
276             err = true;
277         }
278         break;
279     case GST_MESSAGE_WARNING:
280         {
281             gchar  *psz_debug;
282             GError *p_error;
283 
284             gst_message_parse_warning( p_msg, &p_error, &psz_debug );
285             g_free( psz_debug );
286 
287             msg_Warn( p_dec, "Warning from %s: %s",
288                     GST_ELEMENT_NAME( GST_MESSAGE_SRC( p_msg ) ),
289                     p_error->message );
290             g_error_free( p_error );
291         }
292         break;
293     case GST_MESSAGE_INFO:
294         {
295             gchar  *psz_debug;
296             GError *p_error;
297 
298             gst_message_parse_info( p_msg, &p_error, &psz_debug );
299             g_free( psz_debug );
300 
301             msg_Info( p_dec, "Info from %s: %s",
302                     GST_ELEMENT_NAME( GST_MESSAGE_SRC( p_msg ) ),
303                     p_error->message );
304             g_error_free( p_error );
305         }
306         break;
307     default:
308         break;
309     }
310 
311     return err;
312 }
313 
vlc_gst_plugin_init(GstPlugin * p_plugin)314 static gboolean vlc_gst_plugin_init( GstPlugin *p_plugin )
315 {
316     if( !gst_element_register( p_plugin, "vlcvideosink", GST_RANK_NONE,
317                 GST_TYPE_VLC_VIDEO_SINK ))
318         return FALSE;
319 
320     return TRUE;
321 }
322 
323 /* gst_init( ) is not thread-safe, hence a thread-safe wrapper */
vlc_gst_init(void)324 static bool vlc_gst_init( void )
325 {
326     static vlc_mutex_t init_lock = VLC_STATIC_MUTEX;
327     static bool b_registered = false;
328     bool b_ret = true;
329 
330     vlc_mutex_lock( &init_lock );
331     gst_init( NULL, NULL );
332     if ( !b_registered )
333     {
334         b_ret = gst_plugin_register_static( 1, 0, "videolan",
335                 "VLC Gstreamer plugins", vlc_gst_plugin_init,
336                 "1.0.0", "LGPL", "NA", "vlc", "NA" );
337         b_registered = b_ret;
338     }
339     vlc_mutex_unlock( &init_lock );
340 
341     return b_ret;
342 }
343 
vlc_to_gst_fmt(const es_format_t * p_fmt)344 static GstStructure* vlc_to_gst_fmt( const es_format_t *p_fmt )
345 {
346     const video_format_t *p_vfmt = &p_fmt->video;
347     GstStructure *p_str = NULL;
348 
349     switch( p_fmt->i_codec ){
350     case VLC_CODEC_H264:
351         p_str = gst_structure_new_empty( "video/x-h264" );
352         gst_structure_set( p_str, "alignment", G_TYPE_STRING, "au", NULL );
353         if( p_fmt->i_extra )
354             gst_structure_set( p_str, "stream-format", G_TYPE_STRING, "avc",
355                     NULL );
356         else
357             gst_structure_set( p_str, "stream-format", G_TYPE_STRING,
358                     "byte-stream", NULL );
359         break;
360     case VLC_CODEC_MP4V:
361         p_str = gst_structure_new_empty( "video/mpeg" );
362         gst_structure_set( p_str, "mpegversion", G_TYPE_INT, 4,
363                 "systemstream", G_TYPE_BOOLEAN, FALSE, NULL );
364         break;
365     case VLC_CODEC_VP8:
366         p_str = gst_structure_new_empty( "video/x-vp8" );
367         break;
368     case VLC_CODEC_MPGV:
369         p_str = gst_structure_new_empty( "video/mpeg" );
370         gst_structure_set( p_str, "mpegversion", G_TYPE_INT, 2,
371                 "systemstream", G_TYPE_BOOLEAN, FALSE, NULL );
372         break;
373     case VLC_CODEC_FLV1:
374         p_str = gst_structure_new_empty( "video/x-flash-video" );
375         gst_structure_set( p_str, "flvversion", G_TYPE_INT, 1, NULL );
376         break;
377     case VLC_CODEC_WMV1:
378         p_str = gst_structure_new_empty( "video/x-wmv" );
379         gst_structure_set( p_str, "wmvversion", G_TYPE_INT, 1,
380                 "format", G_TYPE_STRING, "WMV1", NULL );
381         break;
382     case VLC_CODEC_WMV2:
383         p_str = gst_structure_new_empty( "video/x-wmv" );
384         gst_structure_set( p_str, "wmvversion", G_TYPE_INT, 2,
385                 "format", G_TYPE_STRING, "WMV2", NULL );
386         break;
387     case VLC_CODEC_WMV3:
388         p_str = gst_structure_new_empty( "video/x-wmv" );
389         gst_structure_set( p_str, "wmvversion", G_TYPE_INT, 3,
390                 "format", G_TYPE_STRING, "WMV3", NULL );
391         break;
392     case VLC_CODEC_VC1:
393         p_str = gst_structure_new_empty( "video/x-wmv" );
394         gst_structure_set( p_str, "wmvversion", G_TYPE_INT, 3,
395                 "format", G_TYPE_STRING, "WVC1", NULL );
396         break;
397     default:
398         /* unsupported codec */
399         return NULL;
400     }
401 
402     if( p_vfmt->i_width && p_vfmt->i_height )
403         gst_structure_set( p_str,
404                 "width", G_TYPE_INT, p_vfmt->i_width,
405                 "height", G_TYPE_INT, p_vfmt->i_height, NULL );
406 
407     if( p_vfmt->i_frame_rate && p_vfmt->i_frame_rate_base )
408         gst_structure_set( p_str, "framerate", GST_TYPE_FRACTION,
409                 p_vfmt->i_frame_rate,
410                 p_vfmt->i_frame_rate_base, NULL );
411 
412     if( p_vfmt->i_sar_num && p_vfmt->i_sar_den )
413         gst_structure_set( p_str, "pixel-aspect-ratio", GST_TYPE_FRACTION,
414                 p_vfmt->i_sar_num,
415                 p_vfmt->i_sar_den, NULL );
416 
417     if( p_fmt->i_extra )
418     {
419         GstBuffer *p_buf;
420 
421         p_buf = gst_buffer_new_wrapped_full( GST_MEMORY_FLAG_READONLY,
422                 p_fmt->p_extra, p_fmt->i_extra, 0,
423                 p_fmt->i_extra, NULL, NULL );
424         if( p_buf == NULL )
425         {
426             gst_structure_free( p_str );
427             return NULL;
428         }
429 
430         gst_structure_set( p_str, "codec_data", GST_TYPE_BUFFER, p_buf, NULL );
431         gst_buffer_unref( p_buf );
432     }
433 
434     return p_str;
435 }
436 
437 /*****************************************************************************
438  * OpenDecoder: probe the decoder and return score
439  *****************************************************************************/
OpenDecoder(vlc_object_t * p_this)440 static int OpenDecoder( vlc_object_t *p_this )
441 {
442     decoder_t *p_dec = ( decoder_t* )p_this;
443     decoder_sys_t *p_sys;
444     GstStateChangeReturn i_ret;
445     gboolean b_ret;
446     sink_src_caps_t caps = { NULL, NULL };
447     GstStructure *p_str;
448     GstAppSrcCallbacks cb;
449     int i_rval = VLC_SUCCESS;
450     GList *p_list;
451     bool dbin;
452 
453 #define VLC_GST_CHECK( r, v, s, t ) \
454     { if( r == v ){ msg_Err( p_dec, s ); i_rval = t; goto fail; } }
455 
456     if( !vlc_gst_init( ))
457     {
458         msg_Err( p_dec, "failed to register vlcvideosink" );
459         return VLC_EGENERIC;
460     }
461 
462     p_str = vlc_to_gst_fmt( &p_dec->fmt_in );
463     if( !p_str )
464         return VLC_EGENERIC;
465 
466     /* Allocate the memory needed to store the decoder's structure */
467     p_sys = p_dec->p_sys = calloc( 1, sizeof( *p_sys ) );
468     if( p_sys == NULL )
469     {
470         gst_structure_free( p_str );
471         return VLC_ENOMEM;
472     }
473 
474     dbin = var_CreateGetBool( p_dec, "use-decodebin" );
475     msg_Dbg( p_dec, "Using decodebin? %s", dbin ? "yes ":"no" );
476 
477     caps.p_sinkcaps = gst_caps_new_empty( );
478     gst_caps_append_structure( caps.p_sinkcaps, p_str );
479     /* Currently supports only system memory raw output format */
480     caps.p_srccaps = gst_caps_new_empty_simple( "video/x-raw" );
481 
482     /* Get the list of all the available gstreamer decoders */
483     p_list = gst_element_factory_list_get_elements(
484             GST_ELEMENT_FACTORY_TYPE_DECODER, GST_RANK_MARGINAL );
485     VLC_GST_CHECK( p_list, NULL, "no decoder list found", VLC_ENOMOD );
486     if( !dbin )
487     {
488         GList *p_l;
489         /* Sort them as per ranks */
490         p_list = g_list_sort( p_list, gst_plugin_feature_rank_compare_func );
491         VLC_GST_CHECK( p_list, NULL, "failed to sort decoders list",
492                 VLC_ENOMOD );
493         p_l = g_list_find_custom( p_list, &caps, find_decoder_func );
494         VLC_GST_CHECK( p_l, NULL, "no suitable decoder found",
495                 VLC_ENOMOD );
496         /* create the decoder with highest rank */
497         p_sys->p_decode_in = gst_element_factory_create(
498                 ( GstElementFactory* )p_l->data, NULL );
499         VLC_GST_CHECK( p_sys->p_decode_in, NULL,
500                 "failed to create decoder", VLC_ENOMOD );
501     }
502     else
503     {
504         GList *p_l;
505         /* Just check if any suitable decoder exists, rest will be
506          * handled by decodebin */
507         p_l = g_list_find_custom( p_list, &caps, find_decoder_func );
508         VLC_GST_CHECK( p_l, NULL, "no suitable decoder found",
509                 VLC_ENOMOD );
510     }
511     gst_plugin_feature_list_free( p_list );
512     p_list = NULL;
513     gst_caps_unref( caps.p_srccaps );
514     caps.p_srccaps = NULL;
515 
516     p_sys->b_prerolled = false;
517     p_sys->b_running = false;
518 
519     /* Queue: GStreamer thread will dump buffers into this queue,
520      * DecodeBlock() will pop out the buffers from the queue */
521     p_sys->p_que = gst_atomic_queue_new( 0 );
522     VLC_GST_CHECK( p_sys->p_que, NULL, "failed to create queue",
523             VLC_ENOMEM );
524 
525     p_sys->p_decode_src = gst_element_factory_make( "appsrc", NULL );
526     VLC_GST_CHECK( p_sys->p_decode_src, NULL, "appsrc not found",
527             VLC_ENOMOD );
528     g_object_set( G_OBJECT( p_sys->p_decode_src ), "caps", caps.p_sinkcaps,
529             "emit-signals", TRUE, "format", GST_FORMAT_BYTES,
530             "stream-type", GST_APP_STREAM_TYPE_SEEKABLE,
531             /* Making DecodeBlock() to block on appsrc with max queue size of 1 byte.
532              * This will make the push_buffer() tightly coupled with the buffer
533              * flow from appsrc -> decoder. push_buffer() will only return when
534              * the same buffer it just fed to appsrc has also been fed to the
535              * decoder element as well */
536             "block", TRUE, "max-bytes", ( guint64 )1, NULL );
537     gst_caps_unref( caps.p_sinkcaps );
538     caps.p_sinkcaps = NULL;
539     cb.enough_data = NULL;
540     cb.need_data = NULL;
541     cb.seek_data = seek_data_cb;
542     gst_app_src_set_callbacks( GST_APP_SRC( p_sys->p_decode_src ),
543             &cb, p_dec, NULL );
544 
545     if( dbin )
546     {
547         p_sys->p_decode_in = gst_element_factory_make( "decodebin", NULL );
548         VLC_GST_CHECK( p_sys->p_decode_in, NULL, "decodebin not found",
549                 VLC_ENOMOD );
550         //g_object_set( G_OBJECT( p_sys->p_decode_in ),
551         //"max-size-buffers", 2, NULL );
552         //g_signal_connect( G_OBJECT( p_sys->p_decode_in ), "no-more-pads",
553                 //G_CALLBACK( no_more_pads_cb ), p_dec );
554         g_signal_connect( G_OBJECT( p_sys->p_decode_in ), "pad-added",
555                 G_CALLBACK( pad_added_cb ), p_dec );
556 
557     }
558 
559     /* videosink: will emit signal for every available buffer */
560     p_sys->p_decode_out = gst_element_factory_make( "vlcvideosink", NULL );
561     VLC_GST_CHECK( p_sys->p_decode_out, NULL, "vlcvideosink not found",
562             VLC_ENOMOD );
563     p_sys->p_allocator = gst_vlc_picture_plane_allocator_new(
564             (gpointer) p_dec );
565     g_object_set( G_OBJECT( p_sys->p_decode_out ), "sync", FALSE, "allocator",
566             p_sys->p_allocator, "id", (gpointer) p_dec, NULL );
567     g_signal_connect( G_OBJECT( p_sys->p_decode_out ), "new-buffer",
568             G_CALLBACK( frame_handoff_cb ), p_dec );
569 
570     //FIXME: caps_signal
571 #if 0
572     g_signal_connect( G_OBJECT( p_sys->p_decode_out ), "new-caps",
573             G_CALLBACK( caps_handoff_cb ), p_dec );
574 #else
575     GST_VLC_VIDEO_SINK( p_sys->p_decode_out )->new_caps = caps_handoff_cb;
576 #endif
577 
578     p_sys->p_decoder = GST_ELEMENT( gst_bin_new( "decoder" ) );
579     VLC_GST_CHECK( p_sys->p_decoder, NULL, "bin not found", VLC_ENOMOD );
580     p_sys->p_bus = gst_bus_new( );
581     VLC_GST_CHECK( p_sys->p_bus, NULL, "failed to create bus",
582             VLC_ENOMOD );
583     gst_element_set_bus( p_sys->p_decoder, p_sys->p_bus );
584 
585     gst_bin_add_many( GST_BIN( p_sys->p_decoder ),
586             p_sys->p_decode_src, p_sys->p_decode_in,
587             p_sys->p_decode_out, NULL );
588     gst_object_ref( p_sys->p_decode_src );
589     gst_object_ref( p_sys->p_decode_in );
590     gst_object_ref( p_sys->p_decode_out );
591 
592     b_ret = gst_element_link( p_sys->p_decode_src, p_sys->p_decode_in );
593     VLC_GST_CHECK( b_ret, FALSE, "failed to link src <-> in",
594             VLC_EGENERIC );
595 
596     if( !dbin )
597     {
598         b_ret = gst_element_link( p_sys->p_decode_in, p_sys->p_decode_out );
599         VLC_GST_CHECK( b_ret, FALSE, "failed to link in <-> out",
600                 VLC_EGENERIC );
601     }
602 
603     /* set the pipeline to playing */
604     i_ret = gst_element_set_state( p_sys->p_decoder, GST_STATE_PLAYING );
605     VLC_GST_CHECK( i_ret, GST_STATE_CHANGE_FAILURE,
606             "set state failure", VLC_EGENERIC );
607     p_sys->b_running = true;
608 
609     /* Set callbacks */
610     p_dec->pf_decode = DecodeBlock;
611     p_dec->pf_flush  = Flush;
612 
613     return VLC_SUCCESS;
614 
615 fail:
616     if( caps.p_sinkcaps )
617         gst_caps_unref( caps.p_sinkcaps );
618     if( caps.p_srccaps )
619         gst_caps_unref( caps.p_srccaps );
620     if( p_list )
621         gst_plugin_feature_list_free( p_list );
622     CloseDecoder( ( vlc_object_t* )p_dec );
623     return i_rval;
624 }
625 
626 /* Flush */
Flush(decoder_t * p_dec)627 static void Flush( decoder_t *p_dec )
628 {
629     decoder_sys_t *p_sys = p_dec->p_sys;
630     GstBuffer *p_buffer;
631     gboolean b_ret;
632 
633     /* Send a new segment event. Seeking position is
634      * irrelevant in this case, as the main motive for a
635      * seek here, is to tell the elements to start flushing
636      * and start accepting buffers from a new time segment */
637     b_ret = gst_element_seek_simple( p_sys->p_decoder,
638             GST_FORMAT_BYTES, GST_SEEK_FLAG_FLUSH, 0 );
639     msg_Dbg( p_dec, "new segment event : %d", b_ret );
640 
641     /* flush the output buffers from the queue */
642     while( ( p_buffer = gst_atomic_queue_pop( p_sys->p_que ) ) )
643         gst_buffer_unref( p_buffer );
644 
645     p_sys->b_prerolled = false;
646 }
647 
648 /* Decode */
DecodeBlock(decoder_t * p_dec,block_t * p_block)649 static int DecodeBlock( decoder_t *p_dec, block_t *p_block )
650 {
651     picture_t *p_pic = NULL;
652     decoder_sys_t *p_sys = p_dec->p_sys;
653     GstMessage *p_msg;
654     GstBuffer *p_buf;
655 
656     if( !p_block ) /* No Drain */
657         return VLCDEC_SUCCESS;
658 
659     if( unlikely( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY |
660                     BLOCK_FLAG_CORRUPTED ) ) )
661     {
662         if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY )
663             Flush( p_dec );
664 
665         if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
666         {
667             block_Release( p_block );
668             goto done;
669         }
670     }
671 
672     if( likely( p_block->i_buffer ) )
673     {
674         p_buf = gst_buffer_new_wrapped_full( GST_MEMORY_FLAG_READONLY,
675                 p_block->p_start, p_block->i_size,
676                 p_block->p_buffer - p_block->p_start, p_block->i_buffer,
677                 p_block, ( GDestroyNotify )block_Release );
678         if( unlikely( p_buf == NULL ) )
679         {
680             msg_Err( p_dec, "failed to create input gstbuffer" );
681             block_Release( p_block );
682             return VLCDEC_ECRITICAL;
683         }
684 
685         if( p_block->i_dts > VLC_TS_INVALID )
686             GST_BUFFER_DTS( p_buf ) = gst_util_uint64_scale( p_block->i_dts,
687                     GST_SECOND, GST_MSECOND );
688 
689         if( p_block->i_pts <= VLC_TS_INVALID )
690             GST_BUFFER_PTS( p_buf ) = GST_BUFFER_DTS( p_buf );
691         else
692             GST_BUFFER_PTS( p_buf ) = gst_util_uint64_scale( p_block->i_pts,
693                     GST_SECOND, GST_MSECOND );
694 
695         if( p_block->i_length > VLC_TS_INVALID )
696             GST_BUFFER_DURATION( p_buf ) = gst_util_uint64_scale(
697                     p_block->i_length, GST_SECOND, GST_MSECOND );
698 
699         if( p_dec->fmt_in.video.i_frame_rate  &&
700                 p_dec->fmt_in.video.i_frame_rate_base )
701             GST_BUFFER_DURATION( p_buf ) = gst_util_uint64_scale( GST_SECOND,
702                     p_dec->fmt_in.video.i_frame_rate_base,
703                     p_dec->fmt_in.video.i_frame_rate );
704 
705         /* Give the input buffer to GStreamer Bin.
706          *
707          *  libvlc                      libvlc
708          *    \ (i/p)              (o/p) ^
709          *     \                        /
710          *   ___v____GSTREAMER BIN_____/____
711          *  |                               |
712          *  |   appsrc-->decode-->vlcsink   |
713          *  |_______________________________|
714          *
715          * * * * * * * * * * * * * * * * * * * * */
716         if( unlikely( gst_app_src_push_buffer(
717                         GST_APP_SRC_CAST( p_sys->p_decode_src ), p_buf )
718                     != GST_FLOW_OK ) )
719         {
720             /* block will be released internally,
721              * when gst_buffer_unref() is called */
722             msg_Err( p_dec, "failed to push buffer" );
723             return VLCDEC_ECRITICAL;
724         }
725     }
726     else
727         block_Release( p_block );
728 
729     /* Poll for any messages, errors */
730     p_msg = gst_bus_pop_filtered( p_sys->p_bus,
731             GST_MESSAGE_ASYNC_DONE | GST_MESSAGE_ERROR |
732             GST_MESSAGE_EOS | GST_MESSAGE_WARNING |
733             GST_MESSAGE_INFO );
734     if( p_msg )
735     {
736         switch( GST_MESSAGE_TYPE( p_msg ) ){
737         case GST_MESSAGE_EOS:
738             /* for debugging purpose */
739             msg_Warn( p_dec, "got unexpected eos" );
740             break;
741         /* First buffer received */
742         case GST_MESSAGE_ASYNC_DONE:
743             /* for debugging purpose */
744             p_sys->b_prerolled = true;
745             msg_Dbg( p_dec, "Pipeline is prerolled" );
746             break;
747         default:
748             if( default_msg_handler( p_dec, p_msg ) )
749             {
750                 gst_message_unref( p_msg );
751                 return VLCDEC_ECRITICAL;
752             }
753             break;
754         }
755         gst_message_unref( p_msg );
756     }
757 
758     /* Look for any output buffers in the queue */
759     if( gst_atomic_queue_peek( p_sys->p_que ) )
760     {
761         GstBuffer *p_buf = GST_BUFFER_CAST(
762                 gst_atomic_queue_pop( p_sys->p_que ));
763         GstMemory *p_mem;
764 
765         if(( p_mem = gst_buffer_peek_memory( p_buf, 0 )) &&
766             GST_IS_VLC_PICTURE_PLANE_ALLOCATOR( p_mem->allocator ))
767         {
768             p_pic = picture_Hold(( (GstVlcPicturePlane*) p_mem )->p_pic );
769         }
770         else
771         {
772             GstVideoFrame frame;
773 
774             /* Get a new picture */
775             if( decoder_UpdateVideoFormat( p_dec ) )
776                 goto done;
777             p_pic = decoder_NewPicture( p_dec );
778             if( !p_pic )
779                 goto done;
780 
781             if( unlikely( !gst_video_frame_map( &frame,
782                             &p_sys->vinfo, p_buf, GST_MAP_READ ) ) )
783             {
784                 msg_Err( p_dec, "failed to map gst video frame" );
785                 gst_buffer_unref( p_buf );
786                 return VLCDEC_ECRITICAL;
787             }
788 
789             gst_CopyPicture( p_pic, &frame );
790             gst_video_frame_unmap( &frame );
791         }
792 
793         if( likely( GST_BUFFER_PTS_IS_VALID( p_buf ) ) )
794             p_pic->date = gst_util_uint64_scale(
795                 GST_BUFFER_PTS( p_buf ), GST_MSECOND, GST_SECOND );
796         else
797             msg_Warn( p_dec, "Gst Buffer has no timestamp" );
798 
799         gst_buffer_unref( p_buf );
800     }
801 
802 done:
803     if( p_pic != NULL )
804         decoder_QueueVideo( p_dec, p_pic );
805     return VLCDEC_SUCCESS;
806 }
807 
808 /* Close the decoder instance */
CloseDecoder(vlc_object_t * p_this)809 static void CloseDecoder( vlc_object_t *p_this )
810 {
811     decoder_t *p_dec = ( decoder_t* )p_this;
812     decoder_sys_t *p_sys = p_dec->p_sys;
813     gboolean b_running = p_sys->b_running;
814 
815     if( b_running )
816     {
817         GstMessage *p_msg;
818         GstFlowReturn i_ret;
819 
820         p_sys->b_running = false;
821 
822         /* Send EOS to the pipeline */
823         i_ret = gst_app_src_end_of_stream(
824                 GST_APP_SRC_CAST( p_sys->p_decode_src ));
825         msg_Dbg( p_dec, "app src eos: %s", gst_flow_get_name( i_ret ) );
826 
827         /* and catch it on the bus with a timeout */
828         p_msg = gst_bus_timed_pop_filtered( p_sys->p_bus,
829                 2000000000ULL, GST_MESSAGE_EOS | GST_MESSAGE_ERROR );
830 
831         if( p_msg )
832         {
833             switch( GST_MESSAGE_TYPE( p_msg ) ){
834             case GST_MESSAGE_EOS:
835                 msg_Dbg( p_dec, "got eos" );
836                 break;
837             default:
838                 if( default_msg_handler( p_dec, p_msg ) )
839                 {
840                     msg_Err( p_dec, "pipeline may not close gracefully" );
841                     return;
842                 }
843                 break;
844             }
845 
846             gst_message_unref( p_msg );
847         }
848         else
849             msg_Warn( p_dec,
850                     "no message, pipeline may not close gracefully" );
851     }
852 
853     /* Remove any left-over buffers from the queue */
854     if( p_sys->p_que )
855     {
856         GstBuffer *p_buf;
857         while( ( p_buf = gst_atomic_queue_pop( p_sys->p_que ) ) )
858             gst_buffer_unref( p_buf );
859         gst_atomic_queue_unref( p_sys->p_que );
860     }
861 
862     if( b_running && gst_element_set_state( p_sys->p_decoder, GST_STATE_NULL )
863             != GST_STATE_CHANGE_SUCCESS )
864         msg_Err( p_dec,
865                 "failed to change the state to NULL," \
866                 "pipeline may not close gracefully" );
867 
868     if( p_sys->p_allocator )
869         gst_object_unref( p_sys->p_allocator );
870     if( p_sys->p_bus )
871         gst_object_unref( p_sys->p_bus );
872     if( p_sys->p_decode_src )
873         gst_object_unref( p_sys->p_decode_src );
874     if( p_sys->p_decode_in )
875         gst_object_unref( p_sys->p_decode_in );
876     if( p_sys->p_decode_out )
877         gst_object_unref( p_sys->p_decode_out );
878     if( p_sys->p_decoder )
879         gst_object_unref( p_sys->p_decoder );
880 
881     free( p_sys );
882 }
883