playback: element_init returns void
[platform/upstream/gstreamer.git] / gst / playback / gstplaybin3.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  * Copyright (C) <2011> Sebastian Dröge <sebastian.droege@collabora.co.uk>
4  * Copyright (C) <2013> Collabora Ltd.
5  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
6  * Copyright (C) <2015> Jan Schmidt <jan@centricular.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /**
24  * SECTION:element-playbin3
25  * @title: playbin3
26  *
27  * playbin3 provides a stand-alone everything-in-one abstraction for an
28  * audio and/or video player. It differs from the previous playbin (playbin2)
29  * by supporting publication and selection of available streams via the
30  * #GstStreamCollection message and #GST_EVENT_SELECT_STREAMS event API.
31  *
32  * > playbin3 is still experimental API and a technology preview.
33  * > Its behaviour and exposed API is subject to change.
34  *
35  * playbin3 can handle both audio and video files and features
36  *
37  * * automatic file type recognition and based on that automatic
38  * selection and usage of the right audio/video/subtitle demuxers/decoders
39  *
40  * * auxiliary files - such as external subtitles and audio tracks
41  * * visualisations for audio files
42  * * subtitle support for video files. Subtitles can be store in external
43  *   files.
44  * * stream selection between different video/audio/subtitles streams
45  * * meta info (tag) extraction
46  * * easy access to the last video sample
47  * * buffering when playing streams over a network
48  * * volume control with mute option
49  *
50  * ## Usage
51  *
52  * A playbin element can be created just like any other element using
53  * gst_element_factory_make(). The file/URI to play should be set via the #GstPlayBin3:uri
54  * property. This must be an absolute URI, relative file paths are not allowed.
55  * Example URIs are file:///home/joe/movie.avi or http://www.joedoe.com/foo.ogg
56  *
57  * Playbin3 is a #GstPipeline. It will notify the application of everything
58  * that's happening (errors, end of stream, tags found, state changes, etc.)
59  * by posting messages on its #GstBus. The application needs to watch the
60  * bus.
61  *
62  * Playback can be initiated by setting the element to PLAYING state using
63  * gst_element_set_state(). Note that the state change will take place in
64  * the background in a separate thread, when the function returns playback
65  * is probably not happening yet and any errors might not have occurred yet.
66  * Applications using playbin3 should ideally be written to deal with things
67  * completely asynchroneous.
68  *
69  * When playback has finished (an EOS message has been received on the bus)
70  * or an error has occurred (an ERROR message has been received on the bus) or
71  * the user wants to play a different track, playbin3 should be set back to
72  * READY or NULL state, then the #GstPlayBin3:uri property should be set to the
73  * new location and then playbin3 be set to PLAYING state again.
74  *
75  * Seeking can be done using gst_element_seek_simple() or gst_element_seek()
76  * on the playbin3 element. Again, the seek will not be executed
77  * instantaneously, but will be done in a background thread. When the seek
78  * call returns the seek will most likely still be in process. An application
79  * may wait for the seek to finish (or fail) using gst_element_get_state() with
80  * -1 as the timeout, but this will block the user interface and is not
81  * recommended at all.
82  *
83  * Applications may query the current position and duration of the stream
84  * via gst_element_query_position() and gst_element_query_duration() and
85  * setting the format passed to GST_FORMAT_TIME. If the query was successful,
86  * the duration or position will have been returned in units of nanoseconds.
87  *
88  * ## Selecting streams
89  *
90  * The recommended way to select streams (instead of the default selection) is
91  * to listen to GST_MESSAGE_STREAM_COLLECTION messages on the GstBus and send a
92  * GST_EVENT_SELECT_STREAMS on the pipeline with the selected streams. This
93  * provides more information and flexibility compared to the legacy #GstPlayBin
94  * property and signal-based mechanism.
95  *
96  * Note: The application should not assume that collections will not change
97  * throughout a single file. If it wishes to modify the default selection, it
98  * should always respond to new collections posted on the bus with a
99  * GST_EVENT_SELECT_STREAMS.
100  *
101  * ## Advanced Usage: specifying the audio and video sink
102  *
103  * By default, if no audio sink or video sink has been specified via the
104  * #GstPlayBin3:audio-sink or #GstPlayBin3:video-sink property, playbin3 will use the autoaudiosink
105  * and autovideosink elements to find the first-best available output method.
106  * This should work in most cases, but is not always desirable. Often either
107  * the user or application might want to specify more explicitly what to use
108  * for audio and video output.
109  *
110  * If the application wants more control over how audio or video should be
111  * output, it may create the audio/video sink elements itself (for example
112  * using gst_element_factory_make()) and provide them to playbin3 using the
113  * #GstPlayBin3:audio-sink or #GstPlayBin3:video-sink property.
114  *
115  * GNOME-based applications, for example, will usually want to create
116  * gconfaudiosink and gconfvideosink elements and make playbin3 use those,
117  * so that output happens to whatever the user has configured in the GNOME
118  * Multimedia System Selector configuration dialog.
119  *
120  * The sink elements do not necessarily need to be ready-made sinks. It is
121  * possible to create container elements that look like a sink to playbin3,
122  * but in reality contain a number of custom elements linked together. This
123  * can be achieved by creating a #GstBin and putting elements in there and
124  * linking them, and then creating a sink #GstGhostPad for the bin and pointing
125  * it to the sink pad of the first element within the bin. This can be used
126  * for a number of purposes, for example to force output to a particular
127  * format or to modify or observe the data before it is output.
128  *
129  * It is also possible to 'suppress' audio and/or video output by using
130  * 'fakesink' elements (or capture it from there using the fakesink element's
131  * "handoff" signal, which, nota bene, is fired from the streaming thread!).
132  *
133  * ## Retrieving Tags and Other Meta Data
134  *
135  * Most of the common meta data (artist, title, etc.) can be retrieved by
136  * watching for TAG messages on the pipeline's bus (see above).
137  *
138  * Other more specific meta information like width/height/framerate of video
139  * streams or samplerate/number of channels of audio streams can be obtained
140  * from the negotiated caps on the sink pads of the sinks.
141  *
142  * ## Buffering
143  * Playbin3 handles buffering automatically for the most part, but applications
144  * need to handle parts of the buffering process as well. Whenever playbin3 is
145  * buffering, it will post BUFFERING messages on the bus with a percentage
146  * value that shows the progress of the buffering process. Applications need
147  * to set playbin3 to PLAYING or PAUSED state in response to these messages.
148  * They may also want to convey the buffering progress to the user in some
149  * way. Here is how to extract the percentage information from the message:
150  * |[
151  * switch (GST_MESSAGE_TYPE (msg)) {
152  *   case GST_MESSAGE_BUFFERING: {
153  *     gint percent = 0;
154  *     gst_message_parse_buffering (msg, &percent);
155  *     g_print ("Buffering (%u percent done)", percent);
156  *     break;
157  *   }
158  *   ...
159  * }
160  * ]|
161  *
162  * Note that applications should keep/set the pipeline in the PAUSED state when
163  * a BUFFERING message is received with a buffer percent value < 100 and set
164  * the pipeline back to PLAYING state when a BUFFERING message with a value
165  * of 100 percent is received (if PLAYING is the desired state, that is).
166  *
167  * ## Embedding the video window in your application
168  * By default, playbin3 (or rather the video sinks used) will create their own
169  * window. Applications will usually want to force output to a window of their
170  * own, however. This can be done using the #GstVideoOverlay interface, which most
171  * video sinks implement. See the documentation there for more details.
172  *
173  * ## Specifying which CD/DVD device to use
174  *
175  * The device to use for CDs/DVDs needs to be set on the source element playbin3
176  * creates before it is opened. The most generic way of doing this is to connect
177  * to playbin3's "source-setup" signal, which will be emitted by playbin3 when
178  * it has created the source element for a particular URI. In the signal
179  * callback you can check if the source element has a "device" property and set
180  * it appropriately. In some cases the device can also be set as part of the
181  * URI, but it depends on the elements involved if this will work or not. For
182  * example, for DVD menu playback, the following syntax might work (if the
183  * resindvd plugin is used): dvd://[/path/to/device]
184  *
185  * ## Handling redirects
186  *
187  * Some elements may post 'redirect' messages on the bus to tell the
188  * application to open another location. These are element messages containing
189  * a structure named 'redirect' along with a 'new-location' field of string
190  * type. The new location may be a relative or an absolute URI. Examples
191  * for such redirects can be found in many quicktime movie trailers.
192  *
193  * ## Examples
194  * |[
195  * gst-launch-1.0 -v playbin3 uri=file:///path/to/somefile.mp4
196  * ]|
197  *  This will play back the given AVI video file, given that the video and
198  * audio decoders required to decode the content are installed. Since no
199  * special audio sink or video sink is supplied (via playbin3's audio-sink or
200  * video-sink properties) playbin3 will try to find a suitable audio and
201  * video sink automatically using the autoaudiosink and autovideosink elements.
202  * |[
203  * gst-launch-1.0 -v playbin3 uri=cdda://4
204  * ]|
205  *  This will play back track 4 on an audio CD in your disc drive (assuming
206  * the drive is detected automatically by the plugin).
207  * |[
208  * gst-launch-1.0 -v playbin3 uri=dvd://
209  * ]|
210  *  This will play back the DVD in your disc drive (assuming
211  * the drive is detected automatically by the plugin).
212  *
213  */
214
215 #ifdef HAVE_CONFIG_H
216 #include "config.h"
217 #endif
218
219 #include <string.h>
220 #include <gst/gst.h>
221
222 #include <gst/gst-i18n-plugin.h>
223 #include <gst/pbutils/pbutils.h>
224 #include <gst/audio/streamvolume.h>
225 #include <gst/video/video-info.h>
226 #include <gst/video/video-multiview.h>
227 #include <gst/video/videooverlay.h>
228 #include <gst/video/navigation.h>
229 #include <gst/video/colorbalance.h>
230 #include "gstplay-enum.h"
231 #include "gstplaybackelements.h"
232 #include "gstplaysink.h"
233 #include "gstsubtitleoverlay.h"
234 #include "gstplaybackutils.h"
235
236 GST_DEBUG_CATEGORY_STATIC (gst_play_bin3_debug);
237 #define GST_CAT_DEFAULT gst_play_bin3_debug
238
239 #define GST_TYPE_PLAY_BIN               (gst_play_bin3_get_type())
240 #define GST_PLAY_BIN3(obj)               (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PLAY_BIN,GstPlayBin3))
241 #define GST_PLAY_BIN3_CLASS(klass)       (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PLAY_BIN,GstPlayBin3Class))
242 #define GST_IS_PLAY_BIN(obj)            (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PLAY_BIN))
243 #define GST_IS_PLAY_BIN_CLASS(klass)    (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PLAY_BIN))
244
245 #define ULONG_TO_POINTER(number)        ((gpointer) (guintptr) (number))
246 #define POINTER_TO_ULONG(number)        ((guintptr) (number))
247
248 #define VOLUME_MAX_DOUBLE 10.0
249
250 typedef struct _GstPlayBin3 GstPlayBin3;
251 typedef struct _GstPlayBin3Class GstPlayBin3Class;
252 typedef struct _GstSourceGroup GstSourceGroup;
253 typedef struct _GstSourceCombine GstSourceCombine;
254 typedef struct _SourcePad SourcePad;
255
256 typedef GstCaps *(*SourceCombineGetMediaCapsFunc) (void);
257
258 /* GstSourceCombine controls all the information regarding a certain
259  * media type.
260  *
261  * It can control a custom combiner element (by default none)
262  */
263 struct _GstSourceCombine
264 {
265   const gchar *media_type;      /* the media type for the combiner */
266   SourceCombineGetMediaCapsFunc get_media_caps; /* more complex caps for the combiner */
267   GstPlaySinkType type;         /* the sink pad type of the combiner */
268   GstStreamType stream_type;    /* The GstStreamType of the combiner */
269
270   GstElement *combiner;         /* the combiner */
271   GPtrArray *channels;          /* Array of GstPad ? */
272
273   GstPad *srcpad;               /* the source pad of the combiner */
274   GstPad *sinkpad;              /* the sinkpad of the sink when the combiner
275                                  * is linked */
276
277   GPtrArray *streams;           /* Sorted array of GstStream for the given type */
278
279   gboolean has_active_pad;      /* stream combiner has the "active-pad" property */
280
281   gboolean is_concat;           /* The stream combiner is the 'concat' element */
282 };
283
284 #define GST_SOURCE_GROUP_GET_LOCK(group) (&((GstSourceGroup*)(group))->lock)
285 #define GST_SOURCE_GROUP_LOCK(group) (g_mutex_lock (GST_SOURCE_GROUP_GET_LOCK(group)))
286 #define GST_SOURCE_GROUP_UNLOCK(group) (g_mutex_unlock (GST_SOURCE_GROUP_GET_LOCK(group)))
287
288 enum
289 {
290   PLAYBIN_STREAM_AUDIO = 0,
291   PLAYBIN_STREAM_VIDEO,
292   PLAYBIN_STREAM_TEXT,
293   PLAYBIN_STREAM_LAST
294 };
295
296 /* names matching the enum above */
297 static const gchar *stream_type_names[] = {
298   "audio", "video", "text"
299 };
300
301
302 #define STREAM_TYPES_FORMAT "s%s%s"
303 #define STREAM_TYPES_ARGS(s) (s) & GST_STREAM_TYPE_AUDIO ? "audio " : "", \
304     (s) & GST_STREAM_TYPE_VIDEO ? "video " : "",                        \
305     (s) & GST_STREAM_TYPE_TEXT ? "text " : ""
306
307
308
309 #if 0                           /* AUTOPLUG DISABLED */
310 static void avelements_free (gpointer data);
311 static GSequence *avelements_create (GstPlayBin3 * playbin,
312     gboolean isaudioelement);
313 #endif
314
315 /* The GstAudioVideoElement structure holding the audio/video decoder
316  * and the audio/video sink factories together with field indicating
317  * the number of common caps features */
318 typedef struct
319 {
320   GstElementFactory *dec;       /* audio:video decoder */
321   GstElementFactory *sink;      /* audio:video sink */
322   guint n_comm_cf;              /* number of common caps features */
323 } GstAVElement;
324
325 /* a structure to hold information about a uridecodebin pad */
326 struct _SourcePad
327 {
328   GstPad *pad;                  /* The controlled pad */
329   GstStreamType stream_type;    /* stream type of the controlled pad */
330   gulong event_probe_id;
331 };
332
333 /* a structure to hold the objects for decoding a uri and the subtitle uri
334  */
335 struct _GstSourceGroup
336 {
337   GstPlayBin3 *playbin;
338
339   GMutex lock;
340
341   gboolean valid;               /* the group has valid info to start playback */
342   gboolean active;              /* the group is active */
343
344   gboolean playing;             /* the group is currently playing
345                                  * (outputted on the sinks) */
346
347   /* properties */
348   gchar *uri;
349   gchar *suburi;
350
351   /* The currently outputted group_id */
352   guint group_id;
353
354   /* Bit-wise set of stream types we have requested from uridecodebin3 */
355   GstStreamType selected_stream_types;
356
357   /* Bit-wise set of stream types for which pads are present */
358   GstStreamType present_stream_types;
359
360   /* TRUE if a 'about-to-finish' needs to be posted once we have
361    * got source pads for all requested stream types
362    *
363    * FIXME : Move this logic to uridecodebin3 later */
364   gboolean pending_about_to_finish;
365
366   /* uridecodebin to handle uri and suburi */
367   GstElement *uridecodebin;
368
369   /* Active sinks for each media type. These are initialized with
370    * the configured or currently used sink, otherwise
371    * left as NULL and playbin tries to automatically
372    * select a good sink */
373   GstElement *audio_sink;
374   GstElement *video_sink;
375   GstElement *text_sink;
376
377   /* List of source pads */
378   GList *source_pads;
379
380   /* uridecodebin signals */
381   gulong pad_added_id;
382   gulong pad_removed_id;
383   gulong select_stream_id;
384   gulong source_setup_id;
385   gulong about_to_finish_id;
386
387 #if 0                           /* AUTOPLUG DISABLED */
388   gulong autoplug_factories_id;
389   gulong autoplug_select_id;
390   gulong autoplug_continue_id;
391   gulong autoplug_query_id;
392 #endif
393
394   gboolean stream_changed_pending;
395
396   /* Active stream collection */
397   GstStreamCollection *collection;
398
399
400   /* buffering message stored for after switching */
401   GstMessage *pending_buffering_msg;
402 };
403
404 #define GST_PLAY_BIN3_GET_LOCK(bin) (&((GstPlayBin3*)(bin))->lock)
405 #define GST_PLAY_BIN3_LOCK(bin) (g_rec_mutex_lock (GST_PLAY_BIN3_GET_LOCK(bin)))
406 #define GST_PLAY_BIN3_UNLOCK(bin) (g_rec_mutex_unlock (GST_PLAY_BIN3_GET_LOCK(bin)))
407
408 /* lock to protect dynamic callbacks, like no-more-pads */
409 #define GST_PLAY_BIN3_DYN_LOCK(bin)    g_mutex_lock (&(bin)->dyn_lock)
410 #define GST_PLAY_BIN3_DYN_UNLOCK(bin)  g_mutex_unlock (&(bin)->dyn_lock)
411
412 /* lock for shutdown */
413 #define GST_PLAY_BIN3_SHUTDOWN_LOCK(bin,label)                  \
414   G_STMT_START {                                                \
415     if (G_UNLIKELY (g_atomic_int_get (&bin->shutdown)))         \
416       goto label;                                               \
417     GST_PLAY_BIN3_DYN_LOCK (bin);                               \
418     if (G_UNLIKELY (g_atomic_int_get (&bin->shutdown))) {       \
419       GST_PLAY_BIN3_DYN_UNLOCK (bin);                           \
420       goto label;                                               \
421     }                                                           \
422   } G_STMT_END
423
424 /* unlock for shutdown */
425 #define GST_PLAY_BIN3_SHUTDOWN_UNLOCK(bin)      \
426   GST_PLAY_BIN3_DYN_UNLOCK (bin);               \
427
428 /**
429  * GstPlayBin3:
430  *
431  * playbin element structure
432  */
433 struct _GstPlayBin3
434 {
435   GstPipeline parent;
436
437   GRecMutex lock;               /* to protect group switching */
438
439   /* the input groups, we use a double buffer to switch between current and next */
440   GstSourceGroup groups[2];     /* array with group info */
441   GstSourceGroup *curr_group;   /* pointer to the currently playing group */
442   GstSourceGroup *next_group;   /* pointer to the next group */
443
444   /* Array of GstPad controlled by each combiner */
445   GPtrArray *channels[PLAYBIN_STREAM_LAST];     /* links to combiner pads */
446
447   /* combiners for different streams */
448   GstSourceCombine combiner[PLAYBIN_STREAM_LAST];
449
450   /* Bit-wise set of stream types we have requested from uridecodebin3.
451    * Calculated as the combination of the 'selected_stream_types' of
452    * each sourcegroup */
453   GstStreamType selected_stream_types;
454
455   /* Bit-wise set of configured output stream types (i.e. active
456      playsink inputs and combiners) */
457   GstStreamType active_stream_types;
458
459   /* properties */
460   guint64 connection_speed;     /* connection speed in bits/sec (0 = unknown) */
461   gint current_video;           /* the currently selected stream */
462   gint current_audio;           /* the currently selected stream */
463   gint current_text;            /* the currently selected stream */
464
465   gboolean do_stream_selections;        /* Set to TRUE when any of current-{video|audio|text} are set to
466                                            say playbin should do backwards-compatibility behaviours */
467
468   guint64 buffer_duration;      /* When buffering, the max buffer duration (ns) */
469   guint buffer_size;            /* When buffering, the max buffer size (bytes) */
470   gboolean force_aspect_ratio;
471
472   /* Multiview/stereoscopic overrides */
473   GstVideoMultiviewFramePacking multiview_mode;
474   GstVideoMultiviewFlags multiview_flags;
475
476   /* our play sink */
477   GstPlaySink *playsink;
478
479   /* Task for (de)activating groups, protected by the activation lock */
480   GstTask *activation_task;
481   GRecMutex activation_lock;
482
483   /* lock protecting dynamic adding/removing */
484   GMutex dyn_lock;
485   /* if we are shutting down or not */
486   gint shutdown;
487   gboolean async_pending;       /* async-start has been emitted */
488
489   GMutex elements_lock;
490   guint32 elements_cookie;
491   GList *elements;              /* factories we can use for selecting elements */
492
493   gboolean have_selector;       /* set to FALSE when we fail to create an
494                                  * input-selector, so that we only post a
495                                  * warning once */
496
497   gboolean video_pending_flush_finish;  /* whether we are pending to send a custom
498                                          * custom-video-flush-finish event
499                                          * on pad activation */
500   gboolean audio_pending_flush_finish;  /* whether we are pending to send a custom
501                                          * custom-audio-flush-finish event
502                                          * on pad activation */
503   gboolean text_pending_flush_finish;   /* whether we are pending to send a custom
504                                          * custom-subtitle-flush-finish event
505                                          * on pad activation */
506
507   GstElement *audio_sink;       /* configured audio sink, or NULL      */
508   GstElement *video_sink;       /* configured video sink, or NULL      */
509   GstElement *text_sink;        /* configured text sink, or NULL       */
510
511   GstElement *audio_stream_combiner;    /* configured audio stream combiner, or NULL */
512   GstElement *video_stream_combiner;    /* configured video stream combiner, or NULL */
513   GstElement *text_stream_combiner;     /* configured text stream combiner, or NULL */
514
515   GSequence *aelements;         /* a list of GstAVElements for audio stream */
516   GSequence *velements;         /* a list of GstAVElements for video stream */
517
518   guint64 ring_buffer_max_size; /* 0 means disabled */
519 };
520
521 struct _GstPlayBin3Class
522 {
523   GstPipelineClass parent_class;
524
525   /* notify app that the current uri finished decoding and it is possible to
526    * queue a new one for gapless playback */
527   void (*about_to_finish) (GstPlayBin3 * playbin);
528
529   /* get the last video sample and convert it to the given caps */
530   GstSample *(*convert_sample) (GstPlayBin3 * playbin, GstCaps * caps);
531 };
532
533 /* props */
534 #define DEFAULT_URI               NULL
535 #define DEFAULT_SUBURI            NULL
536 #define DEFAULT_FLAGS             GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_TEXT | \
537                                   GST_PLAY_FLAG_SOFT_VOLUME | GST_PLAY_FLAG_DEINTERLACE | \
538                                   GST_PLAY_FLAG_SOFT_COLORBALANCE | GST_PLAY_FLAG_BUFFERING
539 #define DEFAULT_CURRENT_VIDEO     -1
540 #define DEFAULT_CURRENT_AUDIO     -1
541 #define DEFAULT_CURRENT_TEXT      -1
542 #define DEFAULT_SUBTITLE_ENCODING NULL
543 #define DEFAULT_AUDIO_SINK        NULL
544 #define DEFAULT_VIDEO_SINK        NULL
545 #define DEFAULT_VIS_PLUGIN        NULL
546 #define DEFAULT_TEXT_SINK         NULL
547 #define DEFAULT_VOLUME            1.0
548 #define DEFAULT_MUTE              FALSE
549 #define DEFAULT_FRAME             NULL
550 #define DEFAULT_FONT_DESC         NULL
551 #define DEFAULT_CONNECTION_SPEED  0
552 #define DEFAULT_BUFFER_DURATION   -1
553 #define DEFAULT_BUFFER_SIZE       -1
554 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
555
556 enum
557 {
558   PROP_0,
559   PROP_URI,
560   PROP_CURRENT_URI,
561   PROP_SUBURI,
562   PROP_CURRENT_SUBURI,
563   PROP_FLAGS,
564   PROP_SUBTITLE_ENCODING,
565   PROP_AUDIO_SINK,
566   PROP_VIDEO_SINK,
567   PROP_VIS_PLUGIN,
568   PROP_TEXT_SINK,
569   PROP_VIDEO_STREAM_COMBINER,
570   PROP_AUDIO_STREAM_COMBINER,
571   PROP_TEXT_STREAM_COMBINER,
572   PROP_VOLUME,
573   PROP_MUTE,
574   PROP_SAMPLE,
575   PROP_FONT_DESC,
576   PROP_CONNECTION_SPEED,
577   PROP_BUFFER_SIZE,
578   PROP_BUFFER_DURATION,
579   PROP_AV_OFFSET,
580   PROP_TEXT_OFFSET,
581   PROP_RING_BUFFER_MAX_SIZE,
582   PROP_FORCE_ASPECT_RATIO,
583   PROP_AUDIO_FILTER,
584   PROP_VIDEO_FILTER,
585   PROP_MULTIVIEW_MODE,
586   PROP_MULTIVIEW_FLAGS
587 };
588
589 /* signals */
590 enum
591 {
592   SIGNAL_ABOUT_TO_FINISH,
593   SIGNAL_CONVERT_SAMPLE,
594   SIGNAL_SOURCE_SETUP,
595   SIGNAL_ELEMENT_SETUP,
596   LAST_SIGNAL
597 };
598
599 #if 0                           /* AUTOPLUG DISABLED */
600 static GstStaticCaps raw_audio_caps = GST_STATIC_CAPS ("audio/x-raw(ANY)");
601 static GstStaticCaps raw_video_caps = GST_STATIC_CAPS ("video/x-raw(ANY)");
602 #endif
603
604 static void gst_play_bin3_finalize (GObject * object);
605
606 static void gst_play_bin3_set_property (GObject * object, guint prop_id,
607     const GValue * value, GParamSpec * spec);
608 static void gst_play_bin3_get_property (GObject * object, guint prop_id,
609     GValue * value, GParamSpec * spec);
610
611 static GstStateChangeReturn gst_play_bin3_change_state (GstElement * element,
612     GstStateChange transition);
613
614 static void gst_play_bin3_handle_message (GstBin * bin, GstMessage * message);
615 static void gst_play_bin3_deep_element_added (GstBin * playbin,
616     GstBin * sub_bin, GstElement * child);
617 static gboolean gst_play_bin3_send_event (GstElement * element,
618     GstEvent * event);
619
620 static GstSample *gst_play_bin3_convert_sample (GstPlayBin3 * playbin,
621     GstCaps * caps);
622
623 static GstStateChangeReturn setup_next_source (GstPlayBin3 * playbin);
624
625 static void gst_play_bin3_check_group_status (GstPlayBin3 * playbin);
626 static void emit_about_to_finish (GstPlayBin3 * playbin);
627 static void reconfigure_output (GstPlayBin3 * playbin);
628 static void pad_removed_cb (GstElement * decodebin, GstPad * pad,
629     GstSourceGroup * group);
630
631 static gint select_stream_cb (GstElement * decodebin,
632     GstStreamCollection * collection, GstStream * stream,
633     GstSourceGroup * group);
634
635 static void do_stream_selection (GstPlayBin3 * playbin, GstSourceGroup * group);
636
637 static GstElementClass *parent_class;
638
639 static guint gst_play_bin3_signals[LAST_SIGNAL] = { 0 };
640
641 #define REMOVE_SIGNAL(obj,id)                   \
642   if (id) {                                     \
643     g_signal_handler_disconnect (obj, id);      \
644     id = 0;                                     \
645   }
646
647 static void gst_play_bin3_overlay_init (gpointer g_iface,
648     gpointer g_iface_data);
649 static void gst_play_bin3_navigation_init (gpointer g_iface,
650     gpointer g_iface_data);
651 static void gst_play_bin3_colorbalance_init (gpointer g_iface,
652     gpointer g_iface_data);
653
654 static void
655 _do_init_type (GType type)
656 {
657   static const GInterfaceInfo svol_info = {
658     NULL, NULL, NULL
659   };
660   static const GInterfaceInfo ov_info = {
661     gst_play_bin3_overlay_init,
662     NULL, NULL
663   };
664   static const GInterfaceInfo nav_info = {
665     gst_play_bin3_navigation_init,
666     NULL, NULL
667   };
668   static const GInterfaceInfo col_info = {
669     gst_play_bin3_colorbalance_init,
670     NULL, NULL
671   };
672
673   g_type_add_interface_static (type, GST_TYPE_STREAM_VOLUME, &svol_info);
674   g_type_add_interface_static (type, GST_TYPE_VIDEO_OVERLAY, &ov_info);
675   g_type_add_interface_static (type, GST_TYPE_NAVIGATION, &nav_info);
676   g_type_add_interface_static (type, GST_TYPE_COLOR_BALANCE, &col_info);
677 }
678
679 static GType gst_play_bin3_get_type (void);
680 G_DEFINE_TYPE_WITH_CODE (GstPlayBin3, gst_play_bin3, GST_TYPE_PIPELINE,
681     _do_init_type (g_define_type_id));
682
683 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (playbin3,
684     gst_play_bin3_custom_element_init);
685
686 static void
687 gst_play_bin3_class_init (GstPlayBin3Class * klass)
688 {
689   GObjectClass *gobject_klass;
690   GstElementClass *gstelement_klass;
691   GstBinClass *gstbin_klass;
692
693   gobject_klass = (GObjectClass *) klass;
694   gstelement_klass = (GstElementClass *) klass;
695   gstbin_klass = (GstBinClass *) klass;
696
697   parent_class = g_type_class_peek_parent (klass);
698
699   gobject_klass->set_property = gst_play_bin3_set_property;
700   gobject_klass->get_property = gst_play_bin3_get_property;
701
702   gobject_klass->finalize = gst_play_bin3_finalize;
703
704   /**
705    * GstPlayBin3:uri
706    *
707    * Set the next URI that playbin will play. This property can be set from the
708    * about-to-finish signal to queue the next media file.
709    */
710   g_object_class_install_property (gobject_klass, PROP_URI,
711       g_param_spec_string ("uri", "URI", "URI of the media to play",
712           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
713
714   /**
715    * GstPlayBin3:current-uri
716    *
717    * The currently playing uri.
718    */
719   g_object_class_install_property (gobject_klass, PROP_CURRENT_URI,
720       g_param_spec_string ("current-uri", "Current URI",
721           "The currently playing URI", NULL,
722           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
723
724   /**
725    * GstPlayBin3:suburi
726    *
727    * Set the next subtitle URI that playbin will play. This property can be
728    * set from the about-to-finish signal to queue the next subtitle media file.
729    */
730   g_object_class_install_property (gobject_klass, PROP_SUBURI,
731       g_param_spec_string ("suburi", ".sub-URI", "Optional URI of a subtitle",
732           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
733
734   /**
735    * GstPlayBin3:current-suburi
736    *
737    * The currently playing subtitle uri.
738    */
739   g_object_class_install_property (gobject_klass, PROP_CURRENT_SUBURI,
740       g_param_spec_string ("current-suburi", "Current .sub-URI",
741           "The currently playing URI of a subtitle",
742           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
743
744   /**
745    * GstPlayBin3:flags
746    *
747    * Control the behaviour of playbin.
748    */
749   g_object_class_install_property (gobject_klass, PROP_FLAGS,
750       g_param_spec_flags ("flags", "Flags", "Flags to control behaviour",
751           GST_TYPE_PLAY_FLAGS, DEFAULT_FLAGS,
752           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
753
754   g_object_class_install_property (gobject_klass, PROP_SUBTITLE_ENCODING,
755       g_param_spec_string ("subtitle-encoding", "subtitle encoding",
756           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
757           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
758           "be checked for an encoding to use. If that is not set either, "
759           "ISO-8859-15 will be assumed.", NULL,
760           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
761
762   g_object_class_install_property (gobject_klass, PROP_VIDEO_FILTER,
763       g_param_spec_object ("video-filter", "Video filter",
764           "the video filter(s) to apply, if possible",
765           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
766   g_object_class_install_property (gobject_klass, PROP_AUDIO_FILTER,
767       g_param_spec_object ("audio-filter", "Audio filter",
768           "the audio filter(s) to apply, if possible",
769           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
770   /**
771    * GstPlayBin3:video-sink
772    *
773    * Get or set the video sink to use for video output. If set to
774    * NULL, one will be auto-selected. To disable video entirely, unset
775    * the VIDEO flag in the #GstPlayBin3:flags property.
776    *
777    */
778   g_object_class_install_property (gobject_klass, PROP_VIDEO_SINK,
779       g_param_spec_object ("video-sink", "Video Sink",
780           "the video output element to use (NULL = default sink)",
781           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
782   /**
783    * GstPlayBin3:audio-sink
784    *
785    * Get or set the audio sink to use for audio output. If set to
786    * NULL, one will be auto-selected. To disable audio entirely, unset
787    * the AUDIO flag in the #GstPlayBin3:flags property.
788    *
789    */
790   g_object_class_install_property (gobject_klass, PROP_AUDIO_SINK,
791       g_param_spec_object ("audio-sink", "Audio Sink",
792           "the audio output element to use (NULL = default sink)",
793           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
794   g_object_class_install_property (gobject_klass, PROP_VIS_PLUGIN,
795       g_param_spec_object ("vis-plugin", "Vis plugin",
796           "the visualization element to use (NULL = default)",
797           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
798   g_object_class_install_property (gobject_klass, PROP_TEXT_SINK,
799       g_param_spec_object ("text-sink", "Text plugin",
800           "the text output element to use (NULL = default subtitleoverlay)",
801           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
802   /**
803    * GstPlayBin3:video-stream-combiner
804    *
805    * Get or set the current video stream combiner. By default, no
806    * element is used and the selected stream is used directly.
807    */
808   g_object_class_install_property (gobject_klass, PROP_VIDEO_STREAM_COMBINER,
809       g_param_spec_object ("video-stream-combiner", "Video stream combiner",
810           "Current video stream combiner (default: none)",
811           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
812
813   /**
814    * GstPlayBin3:audio-stream-combiner
815    *
816    * Get or set the current audio stream combiner. By default, no
817    * element is used and the selected stream is used directly.
818    */
819   g_object_class_install_property (gobject_klass, PROP_AUDIO_STREAM_COMBINER,
820       g_param_spec_object ("audio-stream-combiner", "Audio stream combiner",
821           "Current audio stream combiner (default: none))",
822           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
823
824   /**
825    * GstPlayBin3:text-stream-combiner
826    *
827    * Get or set the current text stream combiner. By default, no
828    * element is used and the selected stream is used directly.
829    */
830   g_object_class_install_property (gobject_klass, PROP_TEXT_STREAM_COMBINER,
831       g_param_spec_object ("text-stream-combiner", "Text stream combiner",
832           "Current text stream combiner (default: none)",
833           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
834
835   /**
836    * GstPlayBin3:volume:
837    *
838    * Get or set the current audio stream volume. 1.0 means 100%,
839    * 0.0 means mute. This uses a linear volume scale.
840    *
841    */
842   g_object_class_install_property (gobject_klass, PROP_VOLUME,
843       g_param_spec_double ("volume", "Volume", "The audio volume, 1.0=100%",
844           0.0, VOLUME_MAX_DOUBLE, 1.0,
845           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
846   g_object_class_install_property (gobject_klass, PROP_MUTE,
847       g_param_spec_boolean ("mute", "Mute",
848           "Mute the audio channel without changing the volume", FALSE,
849           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
850
851   /**
852    * GstPlayBin3:sample:
853    * @playbin: a #GstPlayBin3
854    *
855    * Get the currently rendered or prerolled sample in the video sink.
856    * The #GstCaps in the sample will describe the format of the buffer.
857    */
858   g_object_class_install_property (gobject_klass, PROP_SAMPLE,
859       g_param_spec_boxed ("sample", "Sample",
860           "The last sample (NULL = no video available)",
861           GST_TYPE_SAMPLE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
862
863   g_object_class_install_property (gobject_klass, PROP_FONT_DESC,
864       g_param_spec_string ("subtitle-font-desc",
865           "Subtitle font description",
866           "Pango font description of font "
867           "to be used for subtitle rendering", NULL,
868           G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
869
870   g_object_class_install_property (gobject_klass, PROP_CONNECTION_SPEED,
871       g_param_spec_uint64 ("connection-speed", "Connection Speed",
872           "Network connection speed in kbps (0 = unknown)",
873           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
874           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
875
876   g_object_class_install_property (gobject_klass, PROP_BUFFER_SIZE,
877       g_param_spec_int ("buffer-size", "Buffer size (bytes)",
878           "Buffer size when buffering network streams",
879           -1, G_MAXINT, DEFAULT_BUFFER_SIZE,
880           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
881   g_object_class_install_property (gobject_klass, PROP_BUFFER_DURATION,
882       g_param_spec_int64 ("buffer-duration", "Buffer duration (ns)",
883           "Buffer duration when buffering network streams",
884           -1, G_MAXINT64, DEFAULT_BUFFER_DURATION,
885           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
886   /**
887    * GstPlayBin3:av-offset:
888    *
889    * Control the synchronisation offset between the audio and video streams.
890    * Positive values make the audio ahead of the video and negative values make
891    * the audio go behind the video.
892    */
893   g_object_class_install_property (gobject_klass, PROP_AV_OFFSET,
894       g_param_spec_int64 ("av-offset", "AV Offset",
895           "The synchronisation offset between audio and video in nanoseconds",
896           G_MININT64, G_MAXINT64, 0,
897           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
898   /**
899    * GstPlayBin3:text-offset:
900    *
901    * Control the synchronisation offset between the text and video streams.
902    * Positive values make the text ahead of the video and negative values make
903    * the text go behind the video.
904    */
905   g_object_class_install_property (gobject_klass, PROP_TEXT_OFFSET,
906       g_param_spec_int64 ("text-offset", "Text Offset",
907           "The synchronisation offset between text and video in nanoseconds",
908           G_MININT64, G_MAXINT64, 0,
909           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
910
911   /**
912    * GstPlayBin3:ring-buffer-max-size
913    *
914    * The maximum size of the ring buffer in bytes. If set to 0, the ring
915    * buffer is disabled. Default 0.
916    */
917   g_object_class_install_property (gobject_klass, PROP_RING_BUFFER_MAX_SIZE,
918       g_param_spec_uint64 ("ring-buffer-max-size",
919           "Max. ring buffer size (bytes)",
920           "Max. amount of data in the ring buffer (bytes, 0 = ring buffer disabled)",
921           0, G_MAXUINT, DEFAULT_RING_BUFFER_MAX_SIZE,
922           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
923
924   /**
925    * GstPlayBin3::force-aspect-ratio:
926    *
927    * Requests the video sink to enforce the video display aspect ratio.
928    */
929   g_object_class_install_property (gobject_klass, PROP_FORCE_ASPECT_RATIO,
930       g_param_spec_boolean ("force-aspect-ratio", "Force Aspect Ratio",
931           "When enabled, scaling will respect original aspect ratio", TRUE,
932           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
933
934   /**
935    * GstPlayBin3::video-multiview-mode:
936    *
937    * Set the stereoscopic mode for video streams that don't contain
938    * any information in the stream, so they can be correctly played
939    * as 3D streams. If a video already has multiview information
940    * encoded, this property can override other modes in the set,
941    * but cannot be used to re-interpret MVC or mixed-mono streams.
942    *
943    * See Also: The #GstPlayBin3::video-multiview-flags property
944    *
945    */
946   g_object_class_install_property (gobject_klass, PROP_MULTIVIEW_MODE,
947       g_param_spec_enum ("video-multiview-mode",
948           "Multiview Mode Override",
949           "Re-interpret a video stream as one of several frame-packed stereoscopic modes.",
950           GST_TYPE_VIDEO_MULTIVIEW_FRAME_PACKING,
951           GST_VIDEO_MULTIVIEW_FRAME_PACKING_NONE,
952           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
953
954   /**
955    * GstPlayBin3::video-multiview-flags:
956    *
957    * When overriding the multiview mode of an input stream,
958    * these flags modify details of the view layout.
959    *
960    * See Also: The #GstPlayBin3::video-multiview-mode property
961    */
962   g_object_class_install_property (gobject_klass, PROP_MULTIVIEW_FLAGS,
963       g_param_spec_flags ("video-multiview-flags",
964           "Multiview Flags Override",
965           "Override details of the multiview frame layout",
966           GST_TYPE_VIDEO_MULTIVIEW_FLAGS, GST_VIDEO_MULTIVIEW_FLAGS_NONE,
967           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
968
969   /**
970    * GstPlayBin3::about-to-finish
971    * @playbin: a #GstPlayBin3
972    *
973    * This signal is emitted when the current uri is about to finish. You can
974    * set the uri and suburi to make sure that playback continues.
975    *
976    * This signal is emitted from the context of a GStreamer streaming thread.
977    */
978   gst_play_bin3_signals[SIGNAL_ABOUT_TO_FINISH] =
979       g_signal_new ("about-to-finish", G_TYPE_FROM_CLASS (klass),
980       G_SIGNAL_RUN_LAST,
981       G_STRUCT_OFFSET (GstPlayBin3Class, about_to_finish), NULL, NULL,
982       NULL, G_TYPE_NONE, 0, G_TYPE_NONE);
983
984
985   /**
986    * GstPlayBin3::source-setup:
987    * @playbin: a #GstPlayBin3
988    * @source: source element
989    *
990    * This signal is emitted after the source element has been created, so
991    * it can be configured by setting additional properties (e.g. set a
992    * proxy server for an http source, or set the device and read speed for
993    * an audio cd source). This is functionally equivalent to connecting to
994    * the notify::source signal, but more convenient.
995    *
996    * This signal is usually emitted from the context of a GStreamer streaming
997    * thread.
998    */
999   gst_play_bin3_signals[SIGNAL_SOURCE_SETUP] =
1000       g_signal_new ("source-setup", G_TYPE_FROM_CLASS (klass),
1001       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
1002
1003   /**
1004    * GstPlayBin3::element-setup:
1005    * @playbin: a #GstPlayBin3
1006    * @element: an element that was added to the playbin hierarchy
1007    *
1008    * This signal is emitted when a new element is added to playbin or any of
1009    * its sub-bins. This signal can be used to configure elements, e.g. to set
1010    * properties on decoders. This is functionally equivalent to connecting to
1011    * the deep-element-added signal, but more convenient.
1012    *
1013    * This signal is usually emitted from the context of a GStreamer streaming
1014    * thread, so might be called at the same time as code running in the main
1015    * application thread.
1016    *
1017    * Since: 1.10
1018    */
1019   gst_play_bin3_signals[SIGNAL_ELEMENT_SETUP] =
1020       g_signal_new ("element-setup", G_TYPE_FROM_CLASS (klass),
1021       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
1022
1023   /**
1024    * GstPlayBin3::convert-sample
1025    * @playbin: a #GstPlayBin3
1026    * @caps: the target format of the frame
1027    *
1028    * Action signal to retrieve the currently playing video frame in the format
1029    * specified by @caps.
1030    * If @caps is %NULL, no conversion will be performed and this function is
1031    * equivalent to the #GstPlayBin3:sample property.
1032    *
1033    * Returns: a #GstSample of the current video frame converted to #caps.
1034    * The caps on the sample will describe the final layout of the buffer data.
1035    * %NULL is returned when no current buffer can be retrieved or when the
1036    * conversion failed.
1037    */
1038   gst_play_bin3_signals[SIGNAL_CONVERT_SAMPLE] =
1039       g_signal_new ("convert-sample", G_TYPE_FROM_CLASS (klass),
1040       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1041       G_STRUCT_OFFSET (GstPlayBin3Class, convert_sample), NULL, NULL,
1042       NULL, GST_TYPE_SAMPLE, 1, GST_TYPE_CAPS);
1043
1044   klass->convert_sample = gst_play_bin3_convert_sample;
1045
1046   gst_element_class_set_static_metadata (gstelement_klass,
1047       "Player Bin 3", "Generic/Bin/Player",
1048       "Autoplug and play media from an uri",
1049       "Wim Taymans <wim.taymans@gmail.com>");
1050
1051   gstelement_klass->change_state =
1052       GST_DEBUG_FUNCPTR (gst_play_bin3_change_state);
1053   gstelement_klass->send_event = GST_DEBUG_FUNCPTR (gst_play_bin3_send_event);
1054
1055   gstbin_klass->handle_message =
1056       GST_DEBUG_FUNCPTR (gst_play_bin3_handle_message);
1057   gstbin_klass->deep_element_added =
1058       GST_DEBUG_FUNCPTR (gst_play_bin3_deep_element_added);
1059 }
1060
1061 static void
1062 do_async_start (GstPlayBin3 * playbin)
1063 {
1064   GstMessage *message;
1065
1066   playbin->async_pending = TRUE;
1067
1068   message = gst_message_new_async_start (GST_OBJECT_CAST (playbin));
1069   GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST (playbin),
1070       message);
1071 }
1072
1073 static void
1074 do_async_done (GstPlayBin3 * playbin)
1075 {
1076   GstMessage *message;
1077
1078   if (playbin->async_pending) {
1079     GST_DEBUG_OBJECT (playbin, "posting ASYNC_DONE");
1080     message =
1081         gst_message_new_async_done (GST_OBJECT_CAST (playbin),
1082         GST_CLOCK_TIME_NONE);
1083     GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST (playbin),
1084         message);
1085
1086     playbin->async_pending = FALSE;
1087   }
1088 }
1089
1090 /* init combiners. The combiner is found by finding the first prefix that
1091  * matches the media. */
1092 static void
1093 init_combiners (GstPlayBin3 * playbin)
1094 {
1095   gint i;
1096
1097   /* store the array for the different channels */
1098   for (i = 0; i < PLAYBIN_STREAM_LAST; i++)
1099     playbin->channels[i] = g_ptr_array_new ();
1100
1101   playbin->combiner[PLAYBIN_STREAM_AUDIO].media_type = "audio";
1102   playbin->combiner[PLAYBIN_STREAM_AUDIO].type = GST_PLAY_SINK_TYPE_AUDIO;
1103   playbin->combiner[PLAYBIN_STREAM_AUDIO].stream_type = GST_STREAM_TYPE_AUDIO;
1104   playbin->combiner[PLAYBIN_STREAM_AUDIO].channels = playbin->channels[0];
1105   playbin->combiner[PLAYBIN_STREAM_AUDIO].streams =
1106       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
1107
1108   playbin->combiner[PLAYBIN_STREAM_VIDEO].media_type = "video";
1109   playbin->combiner[PLAYBIN_STREAM_VIDEO].type = GST_PLAY_SINK_TYPE_VIDEO;
1110   playbin->combiner[PLAYBIN_STREAM_VIDEO].stream_type = GST_STREAM_TYPE_VIDEO;
1111   playbin->combiner[PLAYBIN_STREAM_VIDEO].channels = playbin->channels[1];
1112   playbin->combiner[PLAYBIN_STREAM_VIDEO].streams =
1113       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
1114
1115   playbin->combiner[PLAYBIN_STREAM_TEXT].media_type = "text";
1116   playbin->combiner[PLAYBIN_STREAM_TEXT].get_media_caps =
1117       gst_subtitle_overlay_create_factory_caps;
1118   playbin->combiner[PLAYBIN_STREAM_TEXT].type = GST_PLAY_SINK_TYPE_TEXT;
1119   playbin->combiner[PLAYBIN_STREAM_TEXT].stream_type = GST_STREAM_TYPE_TEXT;
1120   playbin->combiner[PLAYBIN_STREAM_TEXT].channels = playbin->channels[2];
1121   playbin->combiner[PLAYBIN_STREAM_TEXT].streams =
1122       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
1123 }
1124
1125 /* Update the combiner information to be in sync with the current collection
1126  *
1127  * FIXME : "current" collection doesn't mean anything until we have a "combined"
1128  *  collection of all groups */
1129 static void
1130 update_combiner_info (GstPlayBin3 * playbin, GstStreamCollection * collection)
1131 {
1132   guint i, len;
1133
1134   if (collection == NULL)
1135     return;
1136
1137   GST_DEBUG_OBJECT (playbin, "Updating combiner info");
1138
1139   /* Wipe current combiner streams */
1140   g_ptr_array_free (playbin->combiner[PLAYBIN_STREAM_AUDIO].streams, TRUE);
1141   g_ptr_array_free (playbin->combiner[PLAYBIN_STREAM_VIDEO].streams, TRUE);
1142   g_ptr_array_free (playbin->combiner[PLAYBIN_STREAM_TEXT].streams, TRUE);
1143   playbin->combiner[PLAYBIN_STREAM_AUDIO].streams =
1144       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
1145   playbin->combiner[PLAYBIN_STREAM_VIDEO].streams =
1146       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
1147   playbin->combiner[PLAYBIN_STREAM_TEXT].streams =
1148       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
1149
1150   len = gst_stream_collection_get_size (collection);
1151   for (i = 0; i < len; i++) {
1152     GstStream *stream = gst_stream_collection_get_stream (collection, i);
1153     GstStreamType stype = gst_stream_get_stream_type (stream);
1154
1155     if (stype & GST_STREAM_TYPE_AUDIO) {
1156       g_ptr_array_add (playbin->combiner[PLAYBIN_STREAM_AUDIO].streams,
1157           gst_object_ref (stream));
1158     } else if (stype & GST_STREAM_TYPE_VIDEO) {
1159       g_ptr_array_add (playbin->combiner[PLAYBIN_STREAM_VIDEO].streams,
1160           gst_object_ref (stream));
1161     } else if (stype & GST_STREAM_TYPE_TEXT) {
1162       g_ptr_array_add (playbin->combiner[PLAYBIN_STREAM_TEXT].streams,
1163           gst_object_ref (stream));
1164     }
1165   }
1166
1167   GST_DEBUG_OBJECT (playbin, "There are %d audio streams",
1168       playbin->combiner[PLAYBIN_STREAM_AUDIO].streams->len);
1169   GST_DEBUG_OBJECT (playbin, "There are %d video streams",
1170       playbin->combiner[PLAYBIN_STREAM_VIDEO].streams->len);
1171   GST_DEBUG_OBJECT (playbin, "There are %d text streams",
1172       playbin->combiner[PLAYBIN_STREAM_TEXT].streams->len);
1173 }
1174
1175 #ifndef GST_DISABLE_GST_DEBUG
1176 #define debug_groups(playbin) G_STMT_START {    \
1177     guint i;                                    \
1178                                                 \
1179     for (i = 0; i < 2; i++) {                           \
1180       GstSourceGroup *group = &playbin->groups[i];      \
1181                                                         \
1182       GST_DEBUG ("GstSourceGroup #%d (%s)", i, (group == playbin->curr_group) ? "current" : (group == playbin->next_group) ? "next" : "unused"); \
1183       GST_DEBUG ("  valid:%d , active:%d , playing:%d", group->valid, group->active, group->playing); \
1184       GST_DEBUG ("  uri:%s", group->uri);                               \
1185       GST_DEBUG ("  suburi:%s", group->suburi);                         \
1186       GST_DEBUG ("  group_id:%d", group->group_id);                     \
1187       GST_DEBUG ("  pending_about_to_finish:%d", group->pending_about_to_finish); \
1188     }                                                                   \
1189   } G_STMT_END
1190 #else
1191 #define debug_groups(p) {}
1192 #endif
1193
1194 static void
1195 init_group (GstPlayBin3 * playbin, GstSourceGroup * group)
1196 {
1197   g_mutex_init (&group->lock);
1198
1199   group->stream_changed_pending = FALSE;
1200   group->group_id = GST_GROUP_ID_INVALID;
1201
1202   group->playbin = playbin;
1203 }
1204
1205 static void
1206 free_group (GstPlayBin3 * playbin, GstSourceGroup * group)
1207 {
1208   g_free (group->uri);
1209   g_free (group->suburi);
1210
1211   g_mutex_clear (&group->lock);
1212   group->stream_changed_pending = FALSE;
1213
1214   if (group->pending_buffering_msg)
1215     gst_message_unref (group->pending_buffering_msg);
1216   group->pending_buffering_msg = NULL;
1217
1218   gst_object_replace ((GstObject **) & group->collection, NULL);
1219
1220   gst_object_replace ((GstObject **) & group->audio_sink, NULL);
1221   gst_object_replace ((GstObject **) & group->video_sink, NULL);
1222   gst_object_replace ((GstObject **) & group->text_sink, NULL);
1223 }
1224
1225 static void
1226 notify_volume_cb (GObject * combiner, GParamSpec * pspec, GstPlayBin3 * playbin)
1227 {
1228   g_object_notify (G_OBJECT (playbin), "volume");
1229 }
1230
1231 static void
1232 notify_mute_cb (GObject * combiner, GParamSpec * pspec, GstPlayBin3 * playbin)
1233 {
1234   g_object_notify (G_OBJECT (playbin), "mute");
1235 }
1236
1237 static void
1238 colorbalance_value_changed_cb (GstColorBalance * balance,
1239     GstColorBalanceChannel * channel, gint value, GstPlayBin3 * playbin)
1240 {
1241   gst_color_balance_value_changed (GST_COLOR_BALANCE (playbin), channel, value);
1242 }
1243
1244 #if 0                           /* AUTOPLUG DISABLED */
1245 static gint
1246 compare_factories_func (gconstpointer p1, gconstpointer p2)
1247 {
1248   GstPluginFeature *f1, *f2;
1249   gboolean is_sink1, is_sink2;
1250   gboolean is_parser1, is_parser2;
1251
1252   f1 = (GstPluginFeature *) p1;
1253   f2 = (GstPluginFeature *) p2;
1254
1255   is_sink1 = gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (f1),
1256       GST_ELEMENT_FACTORY_TYPE_SINK);
1257   is_sink2 = gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (f2),
1258       GST_ELEMENT_FACTORY_TYPE_SINK);
1259   is_parser1 = gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (f1),
1260       GST_ELEMENT_FACTORY_TYPE_PARSER);
1261   is_parser2 = gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (f2),
1262       GST_ELEMENT_FACTORY_TYPE_PARSER);
1263
1264   /* First we want all sinks as we prefer a sink if it directly
1265    * supports the current caps */
1266   if (is_sink1 && !is_sink2)
1267     return -1;
1268   else if (!is_sink1 && is_sink2)
1269     return 1;
1270
1271   /* Then we want all parsers as we always want to plug parsers
1272    * before decoders */
1273   if (is_parser1 && !is_parser2)
1274     return -1;
1275   else if (!is_parser1 && is_parser2)
1276     return 1;
1277
1278   /* And if it's a both a parser or sink we first sort by rank
1279    * and then by factory name */
1280   return gst_plugin_feature_rank_compare_func (p1, p2);
1281 }
1282
1283 /* Must be called with elements lock! */
1284 static void
1285 gst_play_bin3_update_elements_list (GstPlayBin3 * playbin)
1286 {
1287   GList *res, *tmp;
1288   guint cookie;
1289
1290   cookie = gst_registry_get_feature_list_cookie (gst_registry_get ());
1291
1292   if (!playbin->elements || playbin->elements_cookie != cookie) {
1293     if (playbin->elements)
1294       gst_plugin_feature_list_free (playbin->elements);
1295     res =
1296         gst_element_factory_list_get_elements
1297         (GST_ELEMENT_FACTORY_TYPE_DECODABLE, GST_RANK_MARGINAL);
1298     tmp =
1299         gst_element_factory_list_get_elements
1300         (GST_ELEMENT_FACTORY_TYPE_AUDIOVIDEO_SINKS, GST_RANK_MARGINAL);
1301     playbin->elements = g_list_concat (res, tmp);
1302     playbin->elements = g_list_sort (playbin->elements, compare_factories_func);
1303   }
1304
1305   if (!playbin->aelements || playbin->elements_cookie != cookie) {
1306     if (playbin->aelements)
1307       g_sequence_free (playbin->aelements);
1308     playbin->aelements = avelements_create (playbin, TRUE);
1309   }
1310
1311   if (!playbin->velements || playbin->elements_cookie != cookie) {
1312     if (playbin->velements)
1313       g_sequence_free (playbin->velements);
1314     playbin->velements = avelements_create (playbin, FALSE);
1315   }
1316
1317   playbin->elements_cookie = cookie;
1318 }
1319 #endif
1320
1321 static void
1322 gst_play_bin3_init (GstPlayBin3 * playbin)
1323 {
1324   g_rec_mutex_init (&playbin->lock);
1325   g_mutex_init (&playbin->dyn_lock);
1326
1327   /* assume we can create an input-selector */
1328   playbin->have_selector = TRUE;
1329
1330   init_combiners (playbin);
1331
1332   /* init groups */
1333   playbin->curr_group = &playbin->groups[0];
1334   playbin->next_group = &playbin->groups[1];
1335   init_group (playbin, &playbin->groups[0]);
1336   init_group (playbin, &playbin->groups[1]);
1337
1338   /* first filter out the interesting element factories */
1339   g_mutex_init (&playbin->elements_lock);
1340
1341   g_rec_mutex_init (&playbin->activation_lock);
1342
1343   /* add sink */
1344   playbin->playsink =
1345       g_object_new (GST_TYPE_PLAY_SINK, "name", "playsink", "send-event-mode",
1346       1, NULL);
1347   gst_bin_add (GST_BIN_CAST (playbin), GST_ELEMENT_CAST (playbin->playsink));
1348   gst_play_sink_set_flags (playbin->playsink, DEFAULT_FLAGS);
1349   /* Connect to notify::volume and notify::mute signals for proxying */
1350   g_signal_connect (playbin->playsink, "notify::volume",
1351       G_CALLBACK (notify_volume_cb), playbin);
1352   g_signal_connect (playbin->playsink, "notify::mute",
1353       G_CALLBACK (notify_mute_cb), playbin);
1354   g_signal_connect (playbin->playsink, "value-changed",
1355       G_CALLBACK (colorbalance_value_changed_cb), playbin);
1356
1357   playbin->current_video = DEFAULT_CURRENT_VIDEO;
1358   playbin->current_audio = DEFAULT_CURRENT_AUDIO;
1359   playbin->current_text = DEFAULT_CURRENT_TEXT;
1360
1361   playbin->buffer_duration = DEFAULT_BUFFER_DURATION;
1362   playbin->buffer_size = DEFAULT_BUFFER_SIZE;
1363   playbin->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
1364
1365   playbin->force_aspect_ratio = TRUE;
1366
1367   playbin->multiview_mode = GST_VIDEO_MULTIVIEW_FRAME_PACKING_NONE;
1368   playbin->multiview_flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE;
1369 }
1370
1371 static void
1372 gst_play_bin3_finalize (GObject * object)
1373 {
1374   GstPlayBin3 *playbin;
1375   gint i;
1376
1377   playbin = GST_PLAY_BIN3 (object);
1378
1379   free_group (playbin, &playbin->groups[0]);
1380   free_group (playbin, &playbin->groups[1]);
1381
1382   for (i = 0; i < PLAYBIN_STREAM_LAST; i++)
1383     g_ptr_array_free (playbin->channels[i], TRUE);
1384
1385   /* Setting states to NULL is safe here because playsink
1386    * will already be gone and none of these sinks will be
1387    * a child of playsink
1388    */
1389   if (playbin->video_sink) {
1390     gst_element_set_state (playbin->video_sink, GST_STATE_NULL);
1391     gst_object_unref (playbin->video_sink);
1392   }
1393   if (playbin->audio_sink) {
1394     gst_element_set_state (playbin->audio_sink, GST_STATE_NULL);
1395     gst_object_unref (playbin->audio_sink);
1396   }
1397   if (playbin->text_sink) {
1398     gst_element_set_state (playbin->text_sink, GST_STATE_NULL);
1399     gst_object_unref (playbin->text_sink);
1400   }
1401
1402   if (playbin->video_stream_combiner) {
1403     gst_element_set_state (playbin->video_stream_combiner, GST_STATE_NULL);
1404     gst_object_unref (playbin->video_stream_combiner);
1405   }
1406   if (playbin->audio_stream_combiner) {
1407     gst_element_set_state (playbin->audio_stream_combiner, GST_STATE_NULL);
1408     gst_object_unref (playbin->audio_stream_combiner);
1409   }
1410   if (playbin->text_stream_combiner) {
1411     gst_element_set_state (playbin->text_stream_combiner, GST_STATE_NULL);
1412     gst_object_unref (playbin->text_stream_combiner);
1413   }
1414
1415   g_ptr_array_free (playbin->combiner[PLAYBIN_STREAM_AUDIO].streams, TRUE);
1416   g_ptr_array_free (playbin->combiner[PLAYBIN_STREAM_VIDEO].streams, TRUE);
1417   g_ptr_array_free (playbin->combiner[PLAYBIN_STREAM_TEXT].streams, TRUE);
1418
1419   if (playbin->elements)
1420     gst_plugin_feature_list_free (playbin->elements);
1421
1422   if (playbin->aelements)
1423     g_sequence_free (playbin->aelements);
1424
1425   if (playbin->velements)
1426     g_sequence_free (playbin->velements);
1427
1428   g_rec_mutex_clear (&playbin->activation_lock);
1429   g_rec_mutex_clear (&playbin->lock);
1430   g_mutex_clear (&playbin->dyn_lock);
1431   g_mutex_clear (&playbin->elements_lock);
1432
1433   G_OBJECT_CLASS (parent_class)->finalize (object);
1434 }
1435
1436 static gboolean
1437 gst_playbin_uri_is_valid (GstPlayBin3 * playbin, const gchar * uri)
1438 {
1439   const gchar *c;
1440
1441   GST_LOG_OBJECT (playbin, "checking uri '%s'", uri);
1442
1443   /* this just checks the protocol */
1444   if (!gst_uri_is_valid (uri))
1445     return FALSE;
1446
1447   for (c = uri; *c != '\0'; ++c) {
1448     if (!g_ascii_isprint (*c))
1449       goto invalid;
1450     if (*c == ' ')
1451       goto invalid;
1452   }
1453
1454   return TRUE;
1455
1456 invalid:
1457   {
1458     GST_WARNING_OBJECT (playbin, "uri '%s' not valid, character #%u",
1459         uri, (guint) ((guintptr) c - (guintptr) uri));
1460     return FALSE;
1461   }
1462 }
1463
1464 static void
1465 gst_play_bin3_set_uri (GstPlayBin3 * playbin, const gchar * uri)
1466 {
1467   GstSourceGroup *group;
1468
1469   if (uri == NULL) {
1470     g_warning ("cannot set NULL uri");
1471     return;
1472   }
1473
1474   if (!gst_playbin_uri_is_valid (playbin, uri)) {
1475     if (g_str_has_prefix (uri, "file:")) {
1476       GST_WARNING_OBJECT (playbin, "not entirely correct file URI '%s' - make "
1477           "sure to escape spaces and non-ASCII characters properly and specify "
1478           "an absolute path. Use gst_filename_to_uri() to convert filenames "
1479           "to URIs", uri);
1480     } else {
1481       /* GST_ERROR_OBJECT (playbin, "malformed URI '%s'", uri); */
1482     }
1483   }
1484
1485   GST_PLAY_BIN3_LOCK (playbin);
1486   group = playbin->next_group;
1487
1488   GST_SOURCE_GROUP_LOCK (group);
1489   /* store the uri in the next group we will play */
1490   g_free (group->uri);
1491   group->uri = g_strdup (uri);
1492   group->valid = TRUE;
1493   GST_SOURCE_GROUP_UNLOCK (group);
1494
1495   GST_DEBUG ("set new uri to %s", uri);
1496   GST_PLAY_BIN3_UNLOCK (playbin);
1497 }
1498
1499 static void
1500 gst_play_bin3_set_suburi (GstPlayBin3 * playbin, const gchar * suburi)
1501 {
1502   GstSourceGroup *group;
1503
1504   GST_PLAY_BIN3_LOCK (playbin);
1505   group = playbin->next_group;
1506
1507   GST_SOURCE_GROUP_LOCK (group);
1508   g_free (group->suburi);
1509   group->suburi = g_strdup (suburi);
1510   GST_SOURCE_GROUP_UNLOCK (group);
1511
1512   GST_DEBUG ("setting new .sub uri to %s", suburi);
1513
1514   GST_PLAY_BIN3_UNLOCK (playbin);
1515 }
1516
1517 static void
1518 gst_play_bin3_set_flags (GstPlayBin3 * playbin, GstPlayFlags flags)
1519 {
1520   GstPlayFlags old_flags;
1521   old_flags = gst_play_sink_get_flags (playbin->playsink);
1522
1523   if (flags != old_flags) {
1524     gst_play_sink_set_flags (playbin->playsink, flags);
1525     gst_play_sink_reconfigure (playbin->playsink);
1526   }
1527 }
1528
1529 static GstPlayFlags
1530 gst_play_bin3_get_flags (GstPlayBin3 * playbin)
1531 {
1532   GstPlayFlags flags;
1533
1534   flags = gst_play_sink_get_flags (playbin->playsink);
1535
1536   return flags;
1537 }
1538
1539 /* get the currently playing group or if nothing is playing, the next
1540  * group. Must be called with the PLAY_BIN_LOCK. */
1541 static GstSourceGroup *
1542 get_group (GstPlayBin3 * playbin)
1543 {
1544   GstSourceGroup *result;
1545
1546   if (!(result = playbin->curr_group))
1547     result = playbin->next_group;
1548
1549   return result;
1550 }
1551
1552
1553 static GstSample *
1554 gst_play_bin3_convert_sample (GstPlayBin3 * playbin, GstCaps * caps)
1555 {
1556   return gst_play_sink_convert_sample (playbin->playsink, caps);
1557 }
1558
1559 static gboolean
1560 gst_play_bin3_send_custom_event (GstObject * combiner, const gchar * event_name)
1561 {
1562   GstPad *src;
1563   GstPad *peer;
1564   GstStructure *s;
1565   GstEvent *event;
1566   gboolean ret = FALSE;
1567
1568   src = gst_element_get_static_pad (GST_ELEMENT_CAST (combiner), "src");
1569   peer = gst_pad_get_peer (src);
1570   if (peer) {
1571     s = gst_structure_new_empty (event_name);
1572     event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_OOB, s);
1573     gst_pad_send_event (peer, event);
1574     gst_object_unref (peer);
1575     ret = TRUE;
1576   }
1577   gst_object_unref (src);
1578   return ret;
1579 }
1580
1581 static gboolean
1582 gst_play_bin3_set_current_stream (GstPlayBin3 * playbin,
1583     gint stream_type, gint * current_value, gint stream,
1584     gboolean * flush_marker)
1585 {
1586   GstSourceCombine *combine;
1587   GPtrArray *channels;
1588   GstPad *sinkpad;
1589
1590   GST_PLAY_BIN3_LOCK (playbin);
1591   /* This function is only called if the app sets
1592    * one of the current-* properties, which means it doesn't
1593    * handle collections or select-streams yet */
1594   playbin->do_stream_selections = TRUE;
1595
1596   combine = playbin->combiner + stream_type;
1597   channels = playbin->channels[stream_type];
1598
1599   GST_DEBUG_OBJECT (playbin, "Changing current %s stream %d -> %d",
1600       stream_type_names[stream_type], *current_value, stream);
1601
1602   if (combine->combiner == NULL || combine->is_concat) {
1603     /* FIXME: Check that the current_value is within range */
1604     *current_value = stream;
1605     do_stream_selection (playbin, playbin->curr_group);
1606     GST_PLAY_BIN3_UNLOCK (playbin);
1607     return TRUE;
1608   }
1609
1610   GST_DEBUG_OBJECT (playbin, "Using old style combiner");
1611
1612   if (!combine->has_active_pad)
1613     goto no_active_pad;
1614   if (channels == NULL)
1615     goto no_channels;
1616
1617   if (stream == -1 || channels->len <= stream) {
1618     sinkpad = NULL;
1619   } else {
1620     /* take channel from selected stream */
1621     sinkpad = g_ptr_array_index (channels, stream);
1622   }
1623
1624   if (sinkpad)
1625     gst_object_ref (sinkpad);
1626   GST_PLAY_BIN3_UNLOCK (playbin);
1627
1628   if (sinkpad) {
1629     GstObject *combiner;
1630
1631     if ((combiner = gst_pad_get_parent (sinkpad))) {
1632       GstPad *old_sinkpad;
1633
1634       g_object_get (combiner, "active-pad", &old_sinkpad, NULL);
1635
1636       if (old_sinkpad != sinkpad) {
1637         /* FIXME: Is there actually any reason playsink
1638          * needs special names for each type of stream we flush? */
1639         gchar *flush_event_name = g_strdup_printf ("playsink-custom-%s-flush",
1640             stream_type_names[stream_type]);
1641         if (gst_play_bin3_send_custom_event (combiner, flush_event_name))
1642           *flush_marker = TRUE;
1643         g_free (flush_event_name);
1644
1645         /* activate the selected pad */
1646         g_object_set (combiner, "active-pad", sinkpad, NULL);
1647       }
1648
1649       if (old_sinkpad)
1650         gst_object_unref (old_sinkpad);
1651
1652       gst_object_unref (combiner);
1653     }
1654     gst_object_unref (sinkpad);
1655   }
1656   return TRUE;
1657
1658 no_active_pad:
1659   {
1660     GST_PLAY_BIN3_UNLOCK (playbin);
1661     GST_WARNING_OBJECT (playbin,
1662         "can't switch %s, the stream combiner's sink pads don't have the \"active-pad\" property",
1663         stream_type_names[stream_type]);
1664     return FALSE;
1665   }
1666 no_channels:
1667   {
1668     GST_PLAY_BIN3_UNLOCK (playbin);
1669     GST_DEBUG_OBJECT (playbin, "can't switch video, we have no channels");
1670     return FALSE;
1671   }
1672 }
1673
1674 static gboolean
1675 gst_play_bin3_set_current_video_stream (GstPlayBin3 * playbin, gint stream)
1676 {
1677   return gst_play_bin3_set_current_stream (playbin, PLAYBIN_STREAM_VIDEO,
1678       &playbin->current_video, stream, &playbin->video_pending_flush_finish);
1679 }
1680
1681 static gboolean
1682 gst_play_bin3_set_current_audio_stream (GstPlayBin3 * playbin, gint stream)
1683 {
1684   return gst_play_bin3_set_current_stream (playbin, PLAYBIN_STREAM_AUDIO,
1685       &playbin->current_audio, stream, &playbin->audio_pending_flush_finish);
1686 }
1687
1688 static gboolean
1689 gst_play_bin3_set_current_text_stream (GstPlayBin3 * playbin, gint stream)
1690 {
1691   return gst_play_bin3_set_current_stream (playbin, PLAYBIN_STREAM_TEXT,
1692       &playbin->current_text, stream, &playbin->text_pending_flush_finish);
1693 }
1694
1695
1696 static void
1697 gst_play_bin3_set_sink (GstPlayBin3 * playbin, GstPlaySinkType type,
1698     const gchar * dbg, GstElement ** elem, GstElement * sink)
1699 {
1700   GST_INFO_OBJECT (playbin, "Setting %s sink to %" GST_PTR_FORMAT, dbg, sink);
1701
1702   gst_play_sink_set_sink (playbin->playsink, type, sink);
1703
1704   if (*elem)
1705     gst_object_unref (*elem);
1706   *elem = sink ? gst_object_ref (sink) : NULL;
1707 }
1708
1709 static void
1710 gst_play_bin3_set_stream_combiner (GstPlayBin3 * playbin, GstElement ** elem,
1711     const gchar * dbg, GstElement * combiner)
1712 {
1713   GST_INFO_OBJECT (playbin, "Setting %s stream combiner to %" GST_PTR_FORMAT,
1714       dbg, combiner);
1715
1716   GST_PLAY_BIN3_LOCK (playbin);
1717   if (*elem != combiner) {
1718     GstElement *old;
1719
1720     old = *elem;
1721     if (combiner)
1722       gst_object_ref_sink (combiner);
1723
1724     *elem = combiner;
1725     if (old)
1726       gst_object_unref (old);
1727   }
1728   GST_LOG_OBJECT (playbin, "%s stream combiner now %" GST_PTR_FORMAT, dbg,
1729       *elem);
1730   GST_PLAY_BIN3_UNLOCK (playbin);
1731 }
1732
1733 static void
1734 gst_play_bin3_set_encoding (GstPlayBin3 * playbin, const gchar * encoding)
1735 {
1736   GST_PLAY_BIN3_LOCK (playbin);
1737   gst_play_sink_set_subtitle_encoding (playbin->playsink, encoding);
1738   GST_PLAY_BIN3_UNLOCK (playbin);
1739 }
1740
1741 static void
1742 gst_play_bin3_set_property (GObject * object, guint prop_id,
1743     const GValue * value, GParamSpec * pspec)
1744 {
1745   GstPlayBin3 *playbin = GST_PLAY_BIN3 (object);
1746
1747   switch (prop_id) {
1748     case PROP_URI:
1749       gst_play_bin3_set_uri (playbin, g_value_get_string (value));
1750       break;
1751     case PROP_SUBURI:
1752       gst_play_bin3_set_suburi (playbin, g_value_get_string (value));
1753       break;
1754     case PROP_FLAGS:
1755       gst_play_bin3_set_flags (playbin, g_value_get_flags (value));
1756       if (playbin->curr_group) {
1757         GST_SOURCE_GROUP_LOCK (playbin->curr_group);
1758         if (playbin->curr_group->uridecodebin) {
1759           g_object_set (playbin->curr_group->uridecodebin, "download",
1760               (g_value_get_flags (value) & GST_PLAY_FLAG_DOWNLOAD) != 0, NULL);
1761         }
1762         GST_SOURCE_GROUP_UNLOCK (playbin->curr_group);
1763       }
1764       break;
1765     case PROP_SUBTITLE_ENCODING:
1766       gst_play_bin3_set_encoding (playbin, g_value_get_string (value));
1767       break;
1768     case PROP_VIDEO_FILTER:
1769       gst_play_sink_set_filter (playbin->playsink, GST_PLAY_SINK_TYPE_VIDEO,
1770           GST_ELEMENT (g_value_get_object (value)));
1771       break;
1772     case PROP_AUDIO_FILTER:
1773       gst_play_sink_set_filter (playbin->playsink, GST_PLAY_SINK_TYPE_AUDIO,
1774           GST_ELEMENT (g_value_get_object (value)));
1775       break;
1776     case PROP_VIDEO_SINK:
1777       gst_play_bin3_set_sink (playbin, GST_PLAY_SINK_TYPE_VIDEO, "video",
1778           &playbin->video_sink, g_value_get_object (value));
1779       break;
1780     case PROP_AUDIO_SINK:
1781       gst_play_bin3_set_sink (playbin, GST_PLAY_SINK_TYPE_AUDIO, "audio",
1782           &playbin->audio_sink, g_value_get_object (value));
1783       break;
1784     case PROP_VIS_PLUGIN:
1785       gst_play_sink_set_vis_plugin (playbin->playsink,
1786           g_value_get_object (value));
1787       break;
1788     case PROP_TEXT_SINK:
1789       gst_play_bin3_set_sink (playbin, GST_PLAY_SINK_TYPE_TEXT, "text",
1790           &playbin->text_sink, g_value_get_object (value));
1791       break;
1792     case PROP_VIDEO_STREAM_COMBINER:
1793       gst_play_bin3_set_stream_combiner (playbin,
1794           &playbin->video_stream_combiner, "video", g_value_get_object (value));
1795       break;
1796     case PROP_AUDIO_STREAM_COMBINER:
1797       gst_play_bin3_set_stream_combiner (playbin,
1798           &playbin->audio_stream_combiner, "audio", g_value_get_object (value));
1799       break;
1800     case PROP_TEXT_STREAM_COMBINER:
1801       gst_play_bin3_set_stream_combiner (playbin,
1802           &playbin->text_stream_combiner, "text", g_value_get_object (value));
1803       break;
1804     case PROP_VOLUME:
1805       gst_play_sink_set_volume (playbin->playsink, g_value_get_double (value));
1806       break;
1807     case PROP_MUTE:
1808       gst_play_sink_set_mute (playbin->playsink, g_value_get_boolean (value));
1809       break;
1810     case PROP_FONT_DESC:
1811       gst_play_sink_set_font_desc (playbin->playsink,
1812           g_value_get_string (value));
1813       break;
1814     case PROP_CONNECTION_SPEED:
1815       GST_PLAY_BIN3_LOCK (playbin);
1816       playbin->connection_speed = g_value_get_uint64 (value) * 1000;
1817       GST_PLAY_BIN3_UNLOCK (playbin);
1818       break;
1819     case PROP_BUFFER_SIZE:
1820       playbin->buffer_size = g_value_get_int (value);
1821       break;
1822     case PROP_BUFFER_DURATION:
1823       playbin->buffer_duration = g_value_get_int64 (value);
1824       break;
1825     case PROP_AV_OFFSET:
1826       gst_play_sink_set_av_offset (playbin->playsink,
1827           g_value_get_int64 (value));
1828       break;
1829     case PROP_TEXT_OFFSET:
1830       gst_play_sink_set_text_offset (playbin->playsink,
1831           g_value_get_int64 (value));
1832       break;
1833     case PROP_RING_BUFFER_MAX_SIZE:
1834       playbin->ring_buffer_max_size = g_value_get_uint64 (value);
1835       if (playbin->curr_group) {
1836         GST_SOURCE_GROUP_LOCK (playbin->curr_group);
1837         if (playbin->curr_group->uridecodebin) {
1838           g_object_set (playbin->curr_group->uridecodebin,
1839               "ring-buffer-max-size", playbin->ring_buffer_max_size, NULL);
1840         }
1841         GST_SOURCE_GROUP_UNLOCK (playbin->curr_group);
1842       }
1843       break;
1844     case PROP_FORCE_ASPECT_RATIO:
1845       g_object_set (playbin->playsink, "force-aspect-ratio",
1846           g_value_get_boolean (value), NULL);
1847       break;
1848     case PROP_MULTIVIEW_MODE:
1849       GST_PLAY_BIN3_LOCK (playbin);
1850       playbin->multiview_mode = g_value_get_enum (value);
1851       GST_PLAY_BIN3_UNLOCK (playbin);
1852       break;
1853     case PROP_MULTIVIEW_FLAGS:
1854       GST_PLAY_BIN3_LOCK (playbin);
1855       playbin->multiview_flags = g_value_get_flags (value);
1856       GST_PLAY_BIN3_UNLOCK (playbin);
1857       break;
1858     default:
1859       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1860       break;
1861   }
1862 }
1863
1864 static GstElement *
1865 gst_play_bin3_get_current_sink (GstPlayBin3 * playbin, GstElement ** elem,
1866     const gchar * dbg, GstPlaySinkType type)
1867 {
1868   GstElement *sink = gst_play_sink_get_sink (playbin->playsink, type);
1869
1870   GST_LOG_OBJECT (playbin, "play_sink_get_sink() returned %s sink %"
1871       GST_PTR_FORMAT ", the originally set %s sink is %" GST_PTR_FORMAT,
1872       dbg, sink, dbg, *elem);
1873
1874   if (sink == NULL) {
1875     GST_PLAY_BIN3_LOCK (playbin);
1876     if ((sink = *elem))
1877       gst_object_ref (sink);
1878     GST_PLAY_BIN3_UNLOCK (playbin);
1879   }
1880
1881   return sink;
1882 }
1883
1884 static GstElement *
1885 gst_play_bin3_get_current_stream_combiner (GstPlayBin3 * playbin,
1886     GstElement ** elem, const gchar * dbg, int stream_type)
1887 {
1888   GstElement *combiner;
1889
1890   GST_PLAY_BIN3_LOCK (playbin);
1891   /* The special concat element should never be returned */
1892   if (playbin->combiner[stream_type].is_concat)
1893     combiner = NULL;
1894   else if ((combiner = playbin->combiner[stream_type].combiner))
1895     gst_object_ref (combiner);
1896   else if ((combiner = *elem))
1897     gst_object_ref (combiner);
1898   GST_PLAY_BIN3_UNLOCK (playbin);
1899
1900   return combiner;
1901 }
1902
1903 static void
1904 gst_play_bin3_get_property (GObject * object, guint prop_id, GValue * value,
1905     GParamSpec * pspec)
1906 {
1907   GstPlayBin3 *playbin = GST_PLAY_BIN3 (object);
1908
1909   switch (prop_id) {
1910     case PROP_URI:
1911     {
1912       GstSourceGroup *group;
1913
1914       GST_PLAY_BIN3_LOCK (playbin);
1915       group = playbin->next_group;
1916       g_value_set_string (value, group->uri);
1917       GST_PLAY_BIN3_UNLOCK (playbin);
1918       break;
1919     }
1920     case PROP_CURRENT_URI:
1921     {
1922       GstSourceGroup *group;
1923
1924       GST_PLAY_BIN3_LOCK (playbin);
1925       group = get_group (playbin);
1926       g_value_set_string (value, group->uri);
1927       GST_PLAY_BIN3_UNLOCK (playbin);
1928       break;
1929     }
1930     case PROP_SUBURI:
1931     {
1932       GstSourceGroup *group;
1933
1934       GST_PLAY_BIN3_LOCK (playbin);
1935       group = playbin->next_group;
1936       g_value_set_string (value, group->suburi);
1937       GST_PLAY_BIN3_UNLOCK (playbin);
1938       break;
1939     }
1940     case PROP_CURRENT_SUBURI:
1941     {
1942       GstSourceGroup *group;
1943
1944       GST_PLAY_BIN3_LOCK (playbin);
1945       group = get_group (playbin);
1946       g_value_set_string (value, group->suburi);
1947       GST_PLAY_BIN3_UNLOCK (playbin);
1948       break;
1949     }
1950     case PROP_FLAGS:
1951       g_value_set_flags (value, gst_play_bin3_get_flags (playbin));
1952       break;
1953     case PROP_SUBTITLE_ENCODING:
1954       GST_PLAY_BIN3_LOCK (playbin);
1955       g_value_take_string (value,
1956           gst_play_sink_get_subtitle_encoding (playbin->playsink));
1957       GST_PLAY_BIN3_UNLOCK (playbin);
1958       break;
1959     case PROP_VIDEO_FILTER:
1960       g_value_take_object (value,
1961           gst_play_sink_get_filter (playbin->playsink,
1962               GST_PLAY_SINK_TYPE_VIDEO));
1963       break;
1964     case PROP_AUDIO_FILTER:
1965       g_value_take_object (value,
1966           gst_play_sink_get_filter (playbin->playsink,
1967               GST_PLAY_SINK_TYPE_AUDIO));
1968       break;
1969     case PROP_VIDEO_SINK:
1970       g_value_take_object (value,
1971           gst_play_bin3_get_current_sink (playbin, &playbin->video_sink,
1972               "video", GST_PLAY_SINK_TYPE_VIDEO));
1973       break;
1974     case PROP_AUDIO_SINK:
1975       g_value_take_object (value,
1976           gst_play_bin3_get_current_sink (playbin, &playbin->audio_sink,
1977               "audio", GST_PLAY_SINK_TYPE_AUDIO));
1978       break;
1979     case PROP_VIS_PLUGIN:
1980       g_value_take_object (value,
1981           gst_play_sink_get_vis_plugin (playbin->playsink));
1982       break;
1983     case PROP_TEXT_SINK:
1984       g_value_take_object (value,
1985           gst_play_bin3_get_current_sink (playbin, &playbin->text_sink,
1986               "text", GST_PLAY_SINK_TYPE_TEXT));
1987       break;
1988     case PROP_VIDEO_STREAM_COMBINER:
1989       g_value_take_object (value,
1990           gst_play_bin3_get_current_stream_combiner (playbin,
1991               &playbin->video_stream_combiner, "video", PLAYBIN_STREAM_VIDEO));
1992       break;
1993     case PROP_AUDIO_STREAM_COMBINER:
1994       g_value_take_object (value,
1995           gst_play_bin3_get_current_stream_combiner (playbin,
1996               &playbin->audio_stream_combiner, "audio", PLAYBIN_STREAM_AUDIO));
1997       break;
1998     case PROP_TEXT_STREAM_COMBINER:
1999       g_value_take_object (value,
2000           gst_play_bin3_get_current_stream_combiner (playbin,
2001               &playbin->text_stream_combiner, "text", PLAYBIN_STREAM_TEXT));
2002       break;
2003     case PROP_VOLUME:
2004       g_value_set_double (value, gst_play_sink_get_volume (playbin->playsink));
2005       break;
2006     case PROP_MUTE:
2007       g_value_set_boolean (value, gst_play_sink_get_mute (playbin->playsink));
2008       break;
2009     case PROP_SAMPLE:
2010       gst_value_take_sample (value,
2011           gst_play_sink_get_last_sample (playbin->playsink));
2012       break;
2013     case PROP_FONT_DESC:
2014       g_value_take_string (value,
2015           gst_play_sink_get_font_desc (playbin->playsink));
2016       break;
2017     case PROP_CONNECTION_SPEED:
2018       GST_PLAY_BIN3_LOCK (playbin);
2019       g_value_set_uint64 (value, playbin->connection_speed / 1000);
2020       GST_PLAY_BIN3_UNLOCK (playbin);
2021       break;
2022     case PROP_BUFFER_SIZE:
2023       GST_OBJECT_LOCK (playbin);
2024       g_value_set_int (value, playbin->buffer_size);
2025       GST_OBJECT_UNLOCK (playbin);
2026       break;
2027     case PROP_BUFFER_DURATION:
2028       GST_OBJECT_LOCK (playbin);
2029       g_value_set_int64 (value, playbin->buffer_duration);
2030       GST_OBJECT_UNLOCK (playbin);
2031       break;
2032     case PROP_AV_OFFSET:
2033       g_value_set_int64 (value,
2034           gst_play_sink_get_av_offset (playbin->playsink));
2035       break;
2036     case PROP_TEXT_OFFSET:
2037       g_value_set_int64 (value,
2038           gst_play_sink_get_text_offset (playbin->playsink));
2039       break;
2040     case PROP_RING_BUFFER_MAX_SIZE:
2041       g_value_set_uint64 (value, playbin->ring_buffer_max_size);
2042       break;
2043     case PROP_FORCE_ASPECT_RATIO:{
2044       gboolean v;
2045
2046       g_object_get (playbin->playsink, "force-aspect-ratio", &v, NULL);
2047       g_value_set_boolean (value, v);
2048       break;
2049     }
2050     case PROP_MULTIVIEW_MODE:
2051       GST_OBJECT_LOCK (playbin);
2052       g_value_set_enum (value, playbin->multiview_mode);
2053       GST_OBJECT_UNLOCK (playbin);
2054       break;
2055     case PROP_MULTIVIEW_FLAGS:
2056       GST_OBJECT_LOCK (playbin);
2057       g_value_set_flags (value, playbin->multiview_flags);
2058       GST_OBJECT_UNLOCK (playbin);
2059       break;
2060     default:
2061       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2062       break;
2063   }
2064 }
2065
2066 static gint
2067 get_combiner_stream_id (GstPlayBin3 * playbin, GstSourceCombine * combine,
2068     GList * full_list)
2069 {
2070   gint i;
2071   GList *tmp;
2072
2073   for (i = 0; i < combine->streams->len; i++) {
2074     GstStream *stream = (GstStream *) g_ptr_array_index (combine->streams, i);
2075     const gchar *sid = gst_stream_get_stream_id (stream);
2076     for (tmp = full_list; tmp; tmp = tmp->next) {
2077       gchar *orig = (gchar *) tmp->data;
2078       if (!g_strcmp0 (orig, sid))
2079         return i;
2080     }
2081   }
2082
2083   /* Fallback */
2084   return -1;
2085 }
2086
2087 static GList *
2088 extend_list_of_streams (GstPlayBin3 * playbin, GstStreamType stype,
2089     GList * list, GstStreamCollection * collection)
2090 {
2091   GList *tmp, *res;
2092   gint i, nb;
2093
2094   res = list;
2095
2096   nb = gst_stream_collection_get_size (collection);
2097   for (i = 0; i < nb; i++) {
2098     GstStream *stream = gst_stream_collection_get_stream (collection, i);
2099     GstStreamType curtype = gst_stream_get_stream_type (stream);
2100     if (stype == curtype) {
2101       gboolean already_there = FALSE;
2102       const gchar *sid = gst_stream_get_stream_id (stream);
2103       for (tmp = res; tmp; tmp = tmp->next) {
2104         const gchar *other = (const gchar *) tmp->data;
2105         if (!g_strcmp0 (sid, other)) {
2106           already_there = TRUE;
2107           break;
2108         }
2109       }
2110       if (!already_there) {
2111         GST_DEBUG_OBJECT (playbin, "Adding stream %s", sid);
2112         res = g_list_append (res, g_strdup (sid));
2113       }
2114     }
2115   }
2116
2117   return res;
2118 }
2119
2120 static GstEvent *
2121 update_select_streams_event (GstPlayBin3 * playbin, GstEvent * event,
2122     GstSourceGroup * group)
2123 {
2124   GList *streams = NULL;
2125   GList *to_use;
2126   gint combine_id;
2127
2128   if (!playbin->audio_stream_combiner && !playbin->video_stream_combiner &&
2129       !playbin->text_stream_combiner) {
2130     /* Nothing to do */
2131     GST_DEBUG_OBJECT (playbin,
2132         "No custom combiners, no need to modify SELECT_STREAMS event");
2133     return event;
2134   }
2135
2136   if (!group->collection) {
2137     GST_DEBUG_OBJECT (playbin,
2138         "No stream collection for group, no need to modify SELECT_STREAMS event");
2139     return event;
2140   }
2141
2142   gst_event_parse_select_streams (event, &streams);
2143   to_use = g_list_copy_deep (streams, (GCopyFunc) g_strdup, NULL);
2144
2145   /* For each combiner, we want to add all streams of that type to the
2146    * selection */
2147   if (playbin->audio_stream_combiner) {
2148     to_use =
2149         extend_list_of_streams (playbin, GST_STREAM_TYPE_AUDIO, to_use,
2150         group->collection);
2151     combine_id =
2152         get_combiner_stream_id (playbin,
2153         &playbin->combiner[PLAYBIN_STREAM_AUDIO], streams);
2154     if (combine_id != -1)
2155       gst_play_bin3_set_current_audio_stream (playbin, combine_id);
2156   }
2157   if (playbin->video_stream_combiner) {
2158     to_use =
2159         extend_list_of_streams (playbin, GST_STREAM_TYPE_VIDEO, to_use,
2160         group->collection);
2161     combine_id =
2162         get_combiner_stream_id (playbin,
2163         &playbin->combiner[PLAYBIN_STREAM_VIDEO], streams);
2164     if (combine_id != -1)
2165       gst_play_bin3_set_current_video_stream (playbin, combine_id);
2166   }
2167   if (playbin->text_stream_combiner) {
2168     to_use =
2169         extend_list_of_streams (playbin, GST_STREAM_TYPE_TEXT, to_use,
2170         group->collection);
2171     combine_id =
2172         get_combiner_stream_id (playbin,
2173         &playbin->combiner[PLAYBIN_STREAM_TEXT], streams);
2174     if (combine_id != -1)
2175       gst_play_bin3_set_current_text_stream (playbin, combine_id);
2176   }
2177
2178   gst_event_unref (event);
2179   event = gst_event_new_select_streams (to_use);
2180
2181   if (streams)
2182     g_list_free_full (streams, g_free);
2183   if (to_use)
2184     g_list_free_full (to_use, g_free);
2185
2186   return event;
2187 }
2188
2189 /* Returns TRUE if the given list of streams belongs to the stream collection */
2190 static gboolean
2191 gst_streams_belong_to_collection (GList * streams,
2192     GstStreamCollection * collection)
2193 {
2194   GList *tmp;
2195   guint i, nb;
2196
2197   if (streams == NULL || collection == NULL)
2198     return FALSE;
2199   nb = gst_stream_collection_get_size (collection);
2200   if (nb == 0)
2201     return FALSE;
2202
2203   for (tmp = streams; tmp; tmp = tmp->next) {
2204     const gchar *cand = (const gchar *) tmp->data;
2205     gboolean found = FALSE;
2206
2207     for (i = 0; i < nb; i++) {
2208       GstStream *stream = gst_stream_collection_get_stream (collection, i);
2209       if (!g_strcmp0 (cand, gst_stream_get_stream_id (stream))) {
2210         found = TRUE;
2211         break;
2212       }
2213     }
2214     if (!found)
2215       return FALSE;
2216   }
2217   return TRUE;
2218 }
2219
2220 static GstSourceGroup *
2221 get_source_group_for_streams (GstPlayBin3 * playbin, GstEvent * event)
2222 {
2223   GList *streams;
2224   GstSourceGroup *res = NULL;
2225
2226   gst_event_parse_select_streams (event, &streams);
2227   if (playbin->curr_group->collection &&
2228       gst_streams_belong_to_collection (streams,
2229           playbin->curr_group->collection))
2230     res = playbin->curr_group;
2231   else if (playbin->next_group->collection &&
2232       gst_streams_belong_to_collection (streams,
2233           playbin->next_group->collection))
2234     res = playbin->next_group;
2235   g_list_free_full (streams, g_free);
2236
2237   return res;
2238 }
2239
2240 static GstStreamType
2241 get_stream_type_for_event (GstStreamCollection * collection, GstEvent * event)
2242 {
2243   GList *stream_list = NULL;
2244   GList *tmp;
2245   GstStreamType res = 0;
2246   guint i, len;
2247
2248   gst_event_parse_select_streams (event, &stream_list);
2249   len = gst_stream_collection_get_size (collection);
2250   for (tmp = stream_list; tmp; tmp = tmp->next) {
2251     gchar *stid = (gchar *) tmp->data;
2252
2253     for (i = 0; i < len; i++) {
2254       GstStream *stream = gst_stream_collection_get_stream (collection, i);
2255       if (!g_strcmp0 (stid, gst_stream_get_stream_id (stream))) {
2256         res |= gst_stream_get_stream_type (stream);
2257       }
2258     }
2259   }
2260   g_list_free_full (stream_list, g_free);
2261
2262   return res;
2263 }
2264
2265 static gboolean
2266 gst_play_bin3_send_event (GstElement * element, GstEvent * event)
2267 {
2268   GstPlayBin3 *playbin = GST_PLAY_BIN3 (element);
2269
2270   if (GST_EVENT_TYPE (event) == GST_EVENT_SELECT_STREAMS) {
2271     gboolean res;
2272     GstSourceGroup *group;
2273
2274     GST_PLAY_BIN3_LOCK (playbin);
2275     GST_LOG_OBJECT (playbin,
2276         "App sent select-streams, we won't do anything ourselves now");
2277     /* This is probably already false, but it doesn't hurt to be sure */
2278     playbin->do_stream_selections = FALSE;
2279
2280     group = get_source_group_for_streams (playbin, event);
2281     if (group == NULL) {
2282       GST_WARNING_OBJECT (playbin,
2283           "Can't figure out to which uridecodebin the select-streams event should be sent to");
2284       GST_PLAY_BIN3_UNLOCK (playbin);
2285       return FALSE;
2286     }
2287
2288     /* If we have custom combiners, we need to extend the selection with
2289      * the list of all streams for that given type since we will be handling
2290      * the selection with that combiner */
2291     event = update_select_streams_event (playbin, event, group);
2292
2293     if (group->collection) {
2294       group->selected_stream_types =
2295           get_stream_type_for_event (group->collection, event);
2296       playbin->selected_stream_types =
2297           playbin->groups[0].selected_stream_types | playbin->
2298           groups[1].selected_stream_types;
2299       if (playbin->active_stream_types != playbin->selected_stream_types)
2300         reconfigure_output (playbin);
2301     }
2302
2303     /* Send this event directly to uridecodebin, so it works even
2304      * if uridecodebin didn't add any pads yet */
2305     res = gst_element_send_event (group->uridecodebin, event);
2306     GST_PLAY_BIN3_UNLOCK (playbin);
2307
2308     return res;
2309   }
2310
2311   /* Send event directly to playsink instead of letting GstBin iterate
2312    * over all sink elements. The latter might send the event multiple times
2313    * in case the SEEK causes a reconfiguration of the pipeline, as can easily
2314    * happen with adaptive streaming demuxers.
2315    *
2316    * What would then happen is that the iterator would be reset, we send the
2317    * event again, and on the second time it will fail in the majority of cases
2318    * because the pipeline is still being reconfigured
2319    */
2320   if (GST_EVENT_IS_UPSTREAM (event)) {
2321     return gst_element_send_event (GST_ELEMENT_CAST (playbin->playsink), event);
2322   }
2323
2324   return GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
2325 }
2326
2327 /* Called with playbin lock held */
2328 static void
2329 do_stream_selection (GstPlayBin3 * playbin, GstSourceGroup * group)
2330 {
2331   GstStreamCollection *collection;
2332   guint i, nb_streams;
2333   GList *streams = NULL;
2334   gint nb_video = 0, nb_audio = 0, nb_text = 0;
2335   GstStreamType chosen_stream_types = 0;
2336
2337   if (group == NULL)
2338     return;
2339
2340   collection = group->collection;
2341   if (collection == NULL) {
2342     GST_LOG_OBJECT (playbin, "No stream collection. Not doing stream-select");
2343     return;
2344   }
2345
2346   nb_streams = gst_stream_collection_get_size (collection);
2347   if (nb_streams == 0) {
2348     GST_INFO_OBJECT (playbin, "Empty collection received! Ignoring");
2349   }
2350
2351   GST_DEBUG_OBJECT (playbin, "Doing selection on collection with %d streams",
2352       nb_streams);
2353
2354   /* Iterate the collection and choose the streams that match
2355    * either the current-* setting, or all streams of a type if there's
2356    * a combiner for that type */
2357   for (i = 0; i < nb_streams; i++) {
2358     GstStream *stream = gst_stream_collection_get_stream (collection, i);
2359     GstStreamType stream_type = gst_stream_get_stream_type (stream);
2360     const gchar *stream_id = gst_stream_get_stream_id (stream);
2361     gint pb_stream_type = -1;
2362     gboolean select_this = FALSE;
2363
2364     GST_LOG_OBJECT (playbin, "Looking at stream #%d : %s", i, stream_id);
2365
2366     if (stream_type & GST_STREAM_TYPE_AUDIO) {
2367       pb_stream_type = PLAYBIN_STREAM_AUDIO;
2368       /* Select the stream if it's the current one or if there's a custom selector */
2369       select_this =
2370           (nb_audio == playbin->current_audio ||
2371           (playbin->current_audio == -1 && nb_audio == 0) ||
2372           playbin->audio_stream_combiner != NULL);
2373       nb_audio++;
2374     } else if (stream_type & GST_STREAM_TYPE_VIDEO) {
2375       pb_stream_type = PLAYBIN_STREAM_VIDEO;
2376       select_this =
2377           (nb_video == playbin->current_video ||
2378           (playbin->current_video == -1 && nb_video == 0) ||
2379           playbin->video_stream_combiner != NULL);
2380       nb_video++;
2381     } else if (stream_type & GST_STREAM_TYPE_TEXT) {
2382       pb_stream_type = PLAYBIN_STREAM_TEXT;
2383       select_this =
2384           (nb_text == playbin->current_text ||
2385           (playbin->current_text == -1 && nb_text == 0) ||
2386           playbin->text_stream_combiner != NULL);
2387       nb_text++;
2388     }
2389     if (pb_stream_type < 0) {
2390       GST_DEBUG_OBJECT (playbin,
2391           "Stream %d (id %s) of unhandled type %s. Ignoring", i, stream_id,
2392           gst_stream_type_get_name (stream_type));
2393       continue;
2394     }
2395     if (select_this) {
2396       GST_DEBUG_OBJECT (playbin, "Selecting stream %s of type %s",
2397           stream_id, gst_stream_type_get_name (stream_type));
2398       /* Don't build the list if we're not in charge of stream selection */
2399       if (playbin->do_stream_selections)
2400         streams = g_list_append (streams, (gpointer) stream_id);
2401       chosen_stream_types |= stream_type;
2402     }
2403   }
2404
2405   if (streams) {
2406     if (group->uridecodebin) {
2407       GstEvent *ev = gst_event_new_select_streams (streams);
2408       gst_element_send_event (group->uridecodebin, ev);
2409     }
2410     g_list_free (streams);
2411   }
2412
2413   group->selected_stream_types = chosen_stream_types;
2414   /* Update global selected_stream_types */
2415   playbin->selected_stream_types =
2416       playbin->groups[0].selected_stream_types | playbin->
2417       groups[1].selected_stream_types;
2418   if (playbin->active_stream_types != playbin->selected_stream_types)
2419     reconfigure_output (playbin);
2420 }
2421
2422 /* Return the GstSourceGroup to which this element belongs
2423  * Can be NULL (if it belongs to playsink for example) */
2424 static GstSourceGroup *
2425 find_source_group_owner (GstPlayBin3 * playbin, GstObject * element)
2426 {
2427   if (playbin->curr_group->uridecodebin
2428       && gst_object_has_as_ancestor (element,
2429           GST_OBJECT_CAST (playbin->curr_group->uridecodebin)))
2430     return playbin->curr_group;
2431   if (playbin->next_group->uridecodebin
2432       && gst_object_has_as_ancestor (element,
2433           GST_OBJECT_CAST (playbin->next_group->uridecodebin)))
2434     return playbin->next_group;
2435   return NULL;
2436 }
2437
2438 static void
2439 gst_play_bin3_handle_message (GstBin * bin, GstMessage * msg)
2440 {
2441   GstPlayBin3 *playbin = GST_PLAY_BIN3 (bin);
2442
2443   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_STREAM_START) {
2444     GstSourceGroup *group = NULL, *other_group = NULL;
2445     gboolean changed = FALSE;
2446     guint group_id;
2447     GstMessage *buffering_msg;
2448
2449     if (!gst_message_parse_group_id (msg, &group_id)) {
2450       GST_ERROR_OBJECT (bin,
2451           "Could not get group_id from STREAM_START message !");
2452       goto beach;
2453     }
2454     GST_DEBUG_OBJECT (bin, "STREAM_START group_id:%u", group_id);
2455
2456     /* Figure out to which group this group_id corresponds */
2457     GST_PLAY_BIN3_LOCK (playbin);
2458     if (playbin->groups[0].group_id == group_id) {
2459       group = &playbin->groups[0];
2460       other_group = &playbin->groups[1];
2461     } else if (playbin->groups[1].group_id == group_id) {
2462       group = &playbin->groups[1];
2463       other_group = &playbin->groups[0];
2464     }
2465     if (group == NULL) {
2466       GST_ERROR_OBJECT (bin, "group_id %u is not provided by any group !",
2467           group_id);
2468       GST_PLAY_BIN3_UNLOCK (playbin);
2469       goto beach;
2470     }
2471
2472     debug_groups (playbin);
2473
2474     /* Do the switch now ! */
2475     playbin->curr_group = group;
2476     playbin->next_group = other_group;
2477
2478     GST_SOURCE_GROUP_LOCK (group);
2479     if (group->playing == FALSE)
2480       changed = TRUE;
2481     group->playing = TRUE;
2482     buffering_msg = group->pending_buffering_msg;
2483     group->pending_buffering_msg = NULL;
2484     GST_SOURCE_GROUP_UNLOCK (group);
2485
2486     GST_SOURCE_GROUP_LOCK (other_group);
2487     other_group->playing = FALSE;
2488     GST_SOURCE_GROUP_UNLOCK (other_group);
2489
2490     debug_groups (playbin);
2491     GST_PLAY_BIN3_UNLOCK (playbin);
2492     if (changed)
2493       gst_play_bin3_check_group_status (playbin);
2494     else
2495       GST_DEBUG_OBJECT (bin, "Groups didn't changed");
2496     /* If there was a pending buffering message to send, do it now */
2497     if (buffering_msg)
2498       GST_BIN_CLASS (parent_class)->handle_message (bin, buffering_msg);
2499   } else if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_BUFFERING) {
2500     GstSourceGroup *group;
2501
2502     /* Only post buffering messages for group which is currently playing */
2503     group = find_source_group_owner (playbin, msg->src);
2504     GST_SOURCE_GROUP_LOCK (group);
2505     if (!group->playing) {
2506       GST_DEBUG_OBJECT (playbin, "Storing buffering message from pending group "
2507           "%p %" GST_PTR_FORMAT, group, msg);
2508       gst_message_replace (&group->pending_buffering_msg, msg);
2509       gst_message_unref (msg);
2510       msg = NULL;
2511     }
2512     GST_SOURCE_GROUP_UNLOCK (group);
2513   } else if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_STREAM_COLLECTION) {
2514     GstStreamCollection *collection = NULL;
2515
2516     gst_message_parse_stream_collection (msg, &collection);
2517
2518     if (collection) {
2519       gboolean pstate = playbin->do_stream_selections;
2520       GstSourceGroup *target_group = NULL;
2521
2522       GST_PLAY_BIN3_LOCK (playbin);
2523       GST_DEBUG_OBJECT (playbin,
2524           "STREAM_COLLECTION: Got a collection from %" GST_PTR_FORMAT,
2525           msg->src);
2526       target_group = find_source_group_owner (playbin, msg->src);
2527       if (target_group)
2528         gst_object_replace ((GstObject **) & target_group->collection,
2529             (GstObject *) collection);
2530       /* FIXME: Only do the following if it's the current group? */
2531       if (target_group == playbin->curr_group)
2532         update_combiner_info (playbin, target_group->collection);
2533       if (pstate)
2534         playbin->do_stream_selections = FALSE;
2535       do_stream_selection (playbin, target_group);
2536       if (pstate)
2537         playbin->do_stream_selections = TRUE;
2538       GST_PLAY_BIN3_UNLOCK (playbin);
2539
2540       gst_object_unref (collection);
2541     }
2542   }
2543
2544 beach:
2545   if (msg)
2546     GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
2547 }
2548
2549 static void
2550 gst_play_bin3_deep_element_added (GstBin * playbin, GstBin * sub_bin,
2551     GstElement * child)
2552 {
2553   GST_LOG_OBJECT (playbin, "element %" GST_PTR_FORMAT " was added to "
2554       "%" GST_PTR_FORMAT, child, sub_bin);
2555
2556   g_signal_emit (playbin, gst_play_bin3_signals[SIGNAL_ELEMENT_SETUP], 0,
2557       child);
2558
2559   GST_BIN_CLASS (parent_class)->deep_element_added (playbin, sub_bin, child);
2560 }
2561
2562 /* Returns current stream number, or -1 if none has been selected yet */
2563 static int
2564 get_current_stream_number (GstPlayBin3 * playbin, GstSourceCombine * combine,
2565     GPtrArray * channels)
2566 {
2567   /* Internal API cleanup would make this easier... */
2568   int i;
2569   GstPad *pad, *current;
2570   GstObject *combiner = NULL;
2571   int ret = -1;
2572
2573   if (!combine->has_active_pad) {
2574     GST_WARNING_OBJECT (playbin,
2575         "combiner doesn't have the \"active-pad\" property");
2576     return ret;
2577   }
2578
2579   for (i = 0; i < channels->len; i++) {
2580     pad = g_ptr_array_index (channels, i);
2581     if ((combiner = gst_pad_get_parent (pad))) {
2582       g_object_get (combiner, "active-pad", &current, NULL);
2583       gst_object_unref (combiner);
2584
2585       if (pad == current) {
2586         gst_object_unref (current);
2587         ret = i;
2588         break;
2589       }
2590
2591       if (current)
2592         gst_object_unref (current);
2593     }
2594   }
2595
2596   return ret;
2597 }
2598
2599 static void
2600 combiner_active_pad_changed (GObject * combiner, GParamSpec * pspec,
2601     GstPlayBin3 * playbin)
2602 {
2603   GstSourceCombine *combine = NULL;
2604   GPtrArray *channels = NULL;
2605   int i;
2606
2607   GST_PLAY_BIN3_LOCK (playbin);
2608
2609   for (i = 0; i < PLAYBIN_STREAM_LAST; i++) {
2610     if (combiner == G_OBJECT (playbin->combiner[i].combiner)) {
2611       combine = &playbin->combiner[i];
2612       channels = playbin->channels[i];
2613     }
2614   }
2615
2616   /* We got a pad-change after our group got switched out; no need to notify */
2617   if (!combine) {
2618     GST_PLAY_BIN3_UNLOCK (playbin);
2619     return;
2620   }
2621
2622   switch (combine->type) {
2623     case GST_PLAY_SINK_TYPE_VIDEO:
2624       playbin->current_video = get_current_stream_number (playbin,
2625           combine, channels);
2626
2627       if (playbin->video_pending_flush_finish) {
2628         playbin->video_pending_flush_finish = FALSE;
2629         GST_PLAY_BIN3_UNLOCK (playbin);
2630         gst_play_bin3_send_custom_event (GST_OBJECT (combiner),
2631             "playsink-custom-video-flush-finish");
2632       }
2633       break;
2634     case GST_PLAY_SINK_TYPE_AUDIO:
2635       playbin->current_audio = get_current_stream_number (playbin,
2636           combine, channels);
2637
2638       if (playbin->audio_pending_flush_finish) {
2639         playbin->audio_pending_flush_finish = FALSE;
2640         GST_PLAY_BIN3_UNLOCK (playbin);
2641         gst_play_bin3_send_custom_event (GST_OBJECT (combiner),
2642             "playsink-custom-audio-flush-finish");
2643       }
2644       break;
2645     case GST_PLAY_SINK_TYPE_TEXT:
2646       playbin->current_text = get_current_stream_number (playbin,
2647           combine, channels);
2648
2649       if (playbin->text_pending_flush_finish) {
2650         playbin->text_pending_flush_finish = FALSE;
2651         GST_PLAY_BIN3_UNLOCK (playbin);
2652         gst_play_bin3_send_custom_event (GST_OBJECT (combiner),
2653             "playsink-custom-subtitle-flush-finish");
2654       }
2655       break;
2656     default:
2657       break;
2658   }
2659   GST_PLAY_BIN3_UNLOCK (playbin);
2660 }
2661
2662 static GstCaps *
2663 update_video_multiview_caps (GstPlayBin3 * playbin, GstCaps * caps)
2664 {
2665   GstVideoMultiviewMode mv_mode;
2666   GstVideoMultiviewMode cur_mv_mode;
2667   guint mv_flags, cur_mv_flags;
2668   GstStructure *s;
2669   const gchar *mview_mode_str;
2670   GstCaps *out_caps;
2671
2672   GST_OBJECT_LOCK (playbin);
2673   mv_mode = (GstVideoMultiviewMode) playbin->multiview_mode;
2674   mv_flags = playbin->multiview_flags;
2675   GST_OBJECT_UNLOCK (playbin);
2676
2677   if (mv_mode == GST_VIDEO_MULTIVIEW_MODE_NONE)
2678     return NULL;
2679
2680   cur_mv_mode = GST_VIDEO_MULTIVIEW_MODE_NONE;
2681   cur_mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE;
2682
2683   s = gst_caps_get_structure (caps, 0);
2684
2685   gst_structure_get_flagset (s, "multiview-flags", &cur_mv_flags, NULL);
2686   if ((mview_mode_str = gst_structure_get_string (s, "multiview-mode")))
2687     cur_mv_mode = gst_video_multiview_mode_from_caps_string (mview_mode_str);
2688
2689   /* We can't override an existing annotated multiview mode, except
2690    * maybe (in the future) we could change some flags. */
2691   if ((gint) cur_mv_mode > GST_VIDEO_MULTIVIEW_MAX_FRAME_PACKING) {
2692     GST_INFO_OBJECT (playbin, "Cannot override existing multiview mode");
2693     return NULL;
2694   }
2695
2696   mview_mode_str = gst_video_multiview_mode_to_caps_string (mv_mode);
2697   g_assert (mview_mode_str != NULL);
2698   out_caps = gst_caps_copy (caps);
2699   s = gst_caps_get_structure (out_caps, 0);
2700
2701   gst_structure_set (s, "multiview-mode", G_TYPE_STRING, mview_mode_str,
2702       "multiview-flags", GST_TYPE_VIDEO_MULTIVIEW_FLAGSET, mv_flags,
2703       GST_FLAG_SET_MASK_EXACT, NULL);
2704
2705   return out_caps;
2706 }
2707
2708 static void
2709 emit_about_to_finish (GstPlayBin3 * playbin)
2710 {
2711   GST_DEBUG_OBJECT (playbin, "Emitting about-to-finish");
2712
2713   /* after this call, we should have a next group to activate or we EOS */
2714   g_signal_emit (G_OBJECT (playbin),
2715       gst_play_bin3_signals[SIGNAL_ABOUT_TO_FINISH], 0, NULL);
2716
2717   debug_groups (playbin);
2718
2719   /* now activate the next group. If the app did not set a uri, this will
2720    * fail and we can do EOS */
2721   setup_next_source (playbin);
2722 }
2723
2724 static SourcePad *
2725 find_source_pad (GstSourceGroup * group, GstPad * target)
2726 {
2727   GList *tmp;
2728
2729   for (tmp = group->source_pads; tmp; tmp = tmp->next) {
2730     SourcePad *res = (SourcePad *) tmp->data;
2731     if (res->pad == target)
2732       return res;
2733   }
2734   return NULL;
2735 }
2736
2737 static GstPadProbeReturn
2738 _decodebin_event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer udata)
2739 {
2740   GstPadProbeReturn ret = GST_PAD_PROBE_OK;
2741   GstSourceGroup *group = (GstSourceGroup *) udata;
2742   GstPlayBin3 *playbin = group->playbin;
2743   GstEvent *event = GST_PAD_PROBE_INFO_DATA (info);
2744
2745   switch (GST_EVENT_TYPE (event)) {
2746     case GST_EVENT_CAPS:{
2747       GstCaps *caps = NULL;
2748       const GstStructure *s;
2749       const gchar *name;
2750
2751       gst_event_parse_caps (event, &caps);
2752       /* If video caps, check if we should override multiview flags */
2753       s = gst_caps_get_structure (caps, 0);
2754       name = gst_structure_get_name (s);
2755       if (g_str_has_prefix (name, "video/")) {
2756         caps = update_video_multiview_caps (playbin, caps);
2757         if (caps) {
2758           gst_event_unref (event);
2759           event = gst_event_new_caps (caps);
2760           GST_PAD_PROBE_INFO_DATA (info) = event;
2761           gst_caps_unref (caps);
2762         }
2763       }
2764       break;
2765     }
2766     case GST_EVENT_STREAM_START:
2767     {
2768       guint group_id;
2769       if (gst_event_parse_group_id (event, &group_id)) {
2770         GST_LOG_OBJECT (pad, "STREAM_START group_id:%u", group_id);
2771         if (group->group_id == GST_GROUP_ID_INVALID)
2772           group->group_id = group_id;
2773         else if (group->group_id != group_id) {
2774           GST_DEBUG_OBJECT (pad, "group_id changing from %u to %u",
2775               group->group_id, group_id);
2776           group->group_id = group_id;
2777         }
2778       }
2779       break;
2780     }
2781     default:
2782       break;
2783   }
2784
2785   return ret;
2786 }
2787
2788 static void
2789 control_source_pad (GstSourceGroup * group, GstPad * pad,
2790     GstStreamType stream_type)
2791 {
2792   SourcePad *sourcepad = g_slice_new0 (SourcePad);
2793
2794   sourcepad->pad = pad;
2795   sourcepad->event_probe_id =
2796       gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
2797       _decodebin_event_probe, group, NULL);
2798   sourcepad->stream_type = stream_type;
2799   group->source_pads = g_list_append (group->source_pads, sourcepad);
2800 }
2801
2802 static void
2803 remove_combiner (GstPlayBin3 * playbin, GstSourceCombine * combine)
2804 {
2805   gint n;
2806
2807   if (combine->combiner == NULL) {
2808     GST_DEBUG_OBJECT (playbin, "No combiner element to remove");
2809     return;
2810   }
2811
2812   /* Go over all sink pads and release them ! */
2813   for (n = 0; n < combine->channels->len; n++) {
2814     GstPad *sinkpad = g_ptr_array_index (combine->channels, n);
2815
2816     gst_element_release_request_pad (combine->combiner, sinkpad);
2817     gst_object_unref (sinkpad);
2818   }
2819   g_ptr_array_set_size (combine->channels, 0);
2820
2821   gst_element_set_state (combine->combiner, GST_STATE_NULL);
2822   gst_bin_remove (GST_BIN_CAST (playbin), combine->combiner);
2823   combine->combiner = NULL;
2824
2825 }
2826
2827 /* Create the combiner element if needed for the given combine */
2828 static void
2829 create_combiner (GstPlayBin3 * playbin, GstSourceCombine * combine)
2830 {
2831   GstElement *custom_combiner = NULL;
2832
2833   if (combine->combiner) {
2834     GST_WARNING_OBJECT (playbin, "Combiner element already exists!");
2835     return;
2836   }
2837
2838   if (combine->stream_type == GST_STREAM_TYPE_VIDEO)
2839     custom_combiner = playbin->video_stream_combiner;
2840   else if (combine->stream_type == GST_STREAM_TYPE_AUDIO)
2841     custom_combiner = playbin->audio_stream_combiner;
2842   else if (combine->stream_type == GST_STREAM_TYPE_TEXT)
2843     custom_combiner = playbin->text_stream_combiner;
2844
2845   combine->combiner = custom_combiner;
2846
2847   if (!combine->combiner) {
2848     gchar *concat_name;
2849     GST_DEBUG_OBJECT (playbin,
2850         "No custom combiner requested, using 'concat' element");
2851     concat_name = g_strdup_printf ("%s-concat", combine->media_type);
2852     combine->combiner = gst_element_factory_make ("concat", concat_name);
2853     g_object_set (combine->combiner, "adjust-base", FALSE, NULL);
2854     g_free (concat_name);
2855     combine->is_concat = TRUE;
2856   }
2857
2858   combine->srcpad = gst_element_get_static_pad (combine->combiner, "src");
2859
2860   /* We only want to use 'active-pad' if it's a regular combiner that
2861    * will consume all streams, and not concat (which is just used for
2862    * gapless) */
2863   if (!combine->is_concat) {
2864     combine->has_active_pad =
2865         g_object_class_find_property (G_OBJECT_GET_CLASS (combine->combiner),
2866         "active-pad") != NULL;
2867
2868     if (combine->has_active_pad)
2869       g_signal_connect (combine->combiner, "notify::active-pad",
2870           G_CALLBACK (combiner_active_pad_changed), playbin);
2871   }
2872
2873   GST_DEBUG_OBJECT (playbin, "adding new stream combiner %" GST_PTR_FORMAT,
2874       combine->combiner);
2875   gst_bin_add (GST_BIN_CAST (playbin), combine->combiner);
2876   gst_element_sync_state_with_parent (combine->combiner);
2877 }
2878
2879 static gboolean
2880 combiner_control_pad (GstPlayBin3 * playbin, GstSourceCombine * combine,
2881     GstPad * srcpad)
2882 {
2883   GstPadLinkReturn res;
2884
2885   GST_DEBUG_OBJECT (playbin, "srcpad %" GST_PTR_FORMAT, srcpad);
2886
2887   if (combine->combiner) {
2888     GstPad *sinkpad =
2889         gst_element_get_request_pad (combine->combiner, "sink_%u");
2890
2891     if (sinkpad == NULL)
2892       goto request_pad_failed;
2893
2894     GST_DEBUG_OBJECT (playbin, "Got new combiner pad %" GST_PTR_FORMAT,
2895         sinkpad);
2896
2897     /* store the pad in the array */
2898     GST_DEBUG_OBJECT (playbin, "pad %" GST_PTR_FORMAT " added to array",
2899         sinkpad);
2900     g_ptr_array_add (combine->channels, sinkpad);
2901
2902     res = gst_pad_link (srcpad, sinkpad);
2903     if (GST_PAD_LINK_FAILED (res))
2904       goto failed_combiner_link;
2905
2906     GST_DEBUG_OBJECT (playbin,
2907         "linked pad %" GST_PTR_FORMAT " to combiner %" GST_PTR_FORMAT, srcpad,
2908         combine->combiner);
2909
2910   } else {
2911     GST_LOG_OBJECT (playbin, "combine->sinkpad:%" GST_PTR_FORMAT,
2912         combine->sinkpad);
2913     g_assert (combine->sinkpad != NULL);
2914     /* Connect directly to playsink */
2915     if (gst_pad_is_linked (combine->sinkpad))
2916       goto sinkpad_already_linked;
2917
2918     GST_DEBUG_OBJECT (playbin, "Linking new pad straight to playsink");
2919     res = gst_pad_link (srcpad, combine->sinkpad);
2920
2921     if (res != GST_PAD_LINK_OK)
2922       goto failed_sinkpad_link;
2923   }
2924
2925   return TRUE;
2926
2927   /* Failure cases */
2928 request_pad_failed:
2929   GST_ELEMENT_ERROR (playbin, CORE, PAD,
2930       ("Internal playbin error."),
2931       ("Failed to get request pad from combiner %p.", combine->combiner));
2932   return FALSE;
2933
2934
2935 sinkpad_already_linked:
2936   GST_ELEMENT_ERROR (playbin, CORE, PAD,
2937       ("Internal playbin error."), ("playsink pad already used !"));
2938   return FALSE;
2939
2940 failed_sinkpad_link:
2941   GST_ELEMENT_ERROR (playbin, CORE, PAD,
2942       ("Internal playbin error."),
2943       ("Failed to link pad to sink. Error %d", res));
2944   return FALSE;
2945
2946 failed_combiner_link:
2947   GST_ELEMENT_ERROR (playbin, CORE, PAD,
2948       ("Internal playbin error."),
2949       ("Failed to link pad to combiner. Error %d", res));
2950   return FALSE;
2951 }
2952
2953 static void
2954 combiner_release_pad (GstPlayBin3 * playbin, GstSourceCombine * combine,
2955     GstPad * pad)
2956 {
2957   if (combine->combiner) {
2958     GstPad *peer = gst_pad_get_peer (pad);
2959
2960     if (peer) {
2961       GST_DEBUG_OBJECT (playbin, "Removing combiner pad %" GST_PTR_FORMAT,
2962           peer);
2963       g_ptr_array_remove (combine->channels, peer);
2964
2965       gst_element_release_request_pad (combine->combiner, peer);
2966       gst_object_unref (peer);
2967     }
2968   } else {
2969     /* Release direct link if present */
2970     if (combine->sinkpad) {
2971       GST_DEBUG_OBJECT (playbin, "Unlinking pad from playsink sinkpad");
2972       gst_pad_unlink (pad, combine->sinkpad);
2973     }
2974   }
2975 }
2976
2977 /* Call after pad was unlinked from (potential) combiner */
2978 static void
2979 release_source_pad (GstPlayBin3 * playbin, GstSourceGroup * group, GstPad * pad)
2980 {
2981   SourcePad *sourcepad;
2982   GList *tmp;
2983   GstStreamType alltype = 0;
2984
2985   sourcepad = find_source_pad (group, pad);
2986   if (!sourcepad) {
2987     GST_DEBUG_OBJECT (playbin, "Not a pad controlled by us ?");
2988     return;
2989   }
2990
2991   if (sourcepad->event_probe_id) {
2992     gst_pad_remove_probe (pad, sourcepad->event_probe_id);
2993     sourcepad->event_probe_id = 0;
2994   }
2995
2996   /* Remove from list of controlled pads and check again for EOS status */
2997   group->source_pads = g_list_remove (group->source_pads, sourcepad);
2998   g_slice_free (SourcePad, sourcepad);
2999
3000   /* Update present stream types */
3001   for (tmp = group->source_pads; tmp; tmp = tmp->next) {
3002     SourcePad *cand = (SourcePad *) tmp->data;
3003     alltype |= cand->stream_type;
3004   }
3005   group->present_stream_types = alltype;
3006 }
3007
3008 /* this function is called when a new pad is added to decodebin. We check the
3009  * type of the pad and add it to the combiner element
3010  */
3011 static void
3012 pad_added_cb (GstElement * uridecodebin, GstPad * pad, GstSourceGroup * group)
3013 {
3014   GstSourceCombine *combine = NULL;
3015   gint pb_stream_type = -1;
3016   gchar *pad_name;
3017   GstPlayBin3 *playbin = group->playbin;
3018
3019   GST_PLAY_BIN3_SHUTDOWN_LOCK (playbin, shutdown);
3020
3021   pad_name = gst_object_get_name (GST_OBJECT (pad));
3022
3023   GST_DEBUG_OBJECT (playbin, "decoded pad %s:%s added",
3024       GST_DEBUG_PAD_NAME (pad));
3025
3026   /* major type of the pad, this determines the combiner to use,
3027      try exact match first */
3028   if (g_str_has_prefix (pad_name, "video")) {
3029     pb_stream_type = PLAYBIN_STREAM_VIDEO;
3030   } else if (g_str_has_prefix (pad_name, "audio")) {
3031     pb_stream_type = PLAYBIN_STREAM_AUDIO;
3032   } else if (g_str_has_prefix (pad_name, "text")) {
3033     pb_stream_type = PLAYBIN_STREAM_TEXT;
3034   }
3035
3036   g_free (pad_name);
3037
3038   /* no stream type found for the media type, don't bother linking it to a
3039    * combiner. This will leave the pad unlinked and thus ignored. */
3040   if (pb_stream_type < 0) {
3041     GST_PLAY_BIN3_SHUTDOWN_UNLOCK (playbin);
3042     goto unknown_type;
3043   }
3044
3045   combine = &playbin->combiner[pb_stream_type];
3046
3047   combiner_control_pad (playbin, combine, pad);
3048
3049   control_source_pad (group, pad, combine->stream_type);
3050
3051   /* Update present stream_types and check whether we should post a pending about-to-finish */
3052   group->present_stream_types |= combine->stream_type;
3053
3054   if (group->playing && group->pending_about_to_finish
3055       && group->present_stream_types == group->selected_stream_types) {
3056     group->pending_about_to_finish = FALSE;
3057     emit_about_to_finish (playbin);
3058   }
3059
3060   GST_PLAY_BIN3_SHUTDOWN_UNLOCK (playbin);
3061
3062   return;
3063
3064   /* ERRORS */
3065 unknown_type:
3066   GST_DEBUG_OBJECT (playbin, "Ignoring pad with unknown type");
3067   return;
3068
3069 shutdown:
3070   {
3071     GST_DEBUG ("ignoring, we are shutting down. Pad will be left unlinked");
3072     /* not going to done as we didn't request the caps */
3073     return;
3074   }
3075 }
3076
3077 /* called when a pad is removed from the decodebin. We unlink the pad from
3078  * the combiner. */
3079 static void
3080 pad_removed_cb (GstElement * decodebin, GstPad * pad, GstSourceGroup * group)
3081 {
3082   GstSourceCombine *combine;
3083   GstPlayBin3 *playbin = group->playbin;
3084
3085   GST_DEBUG_OBJECT (playbin,
3086       "decoded pad %s:%s removed", GST_DEBUG_PAD_NAME (pad));
3087
3088   GST_PLAY_BIN3_LOCK (playbin);
3089
3090   /* Get combiner for pad */
3091   if (g_str_has_prefix (GST_PAD_NAME (pad), "video"))
3092     combine = &playbin->combiner[PLAYBIN_STREAM_VIDEO];
3093   else if (g_str_has_prefix (GST_PAD_NAME (pad), "audio"))
3094     combine = &playbin->combiner[PLAYBIN_STREAM_AUDIO];
3095   else if (g_str_has_prefix (GST_PAD_NAME (pad), "text"))
3096     combine = &playbin->combiner[PLAYBIN_STREAM_TEXT];
3097   else
3098     return;
3099
3100   combiner_release_pad (playbin, combine, pad);
3101   release_source_pad (playbin, group, pad);
3102
3103   GST_PLAY_BIN3_UNLOCK (playbin);
3104 }
3105
3106
3107 static gint
3108 select_stream_cb (GstElement * decodebin, GstStreamCollection * collection,
3109     GstStream * stream, GstSourceGroup * group)
3110 {
3111   GstStreamType stype = gst_stream_get_stream_type (stream);
3112   GstElement *combiner = NULL;
3113   GstPlayBin3 *playbin = group->playbin;
3114
3115   if (stype & GST_STREAM_TYPE_AUDIO)
3116     combiner = playbin->audio_stream_combiner;
3117   else if (stype & GST_STREAM_TYPE_VIDEO)
3118     combiner = playbin->video_stream_combiner;
3119   else if (stype & GST_STREAM_TYPE_TEXT)
3120     combiner = playbin->text_stream_combiner;
3121
3122   if (combiner) {
3123     GST_DEBUG_OBJECT (playbin, "Got a combiner, requesting stream activation");
3124     return 1;
3125   }
3126
3127   /* Let decodebin3 decide otherwise */
3128   return -1;
3129 }
3130
3131 /* We get called when the selected stream types change and
3132  * reconfiguration of output (i.e. playsink and potential combiners)
3133  * are required.
3134  */
3135 static void
3136 reconfigure_output (GstPlayBin3 * playbin)
3137 {
3138   GstPadLinkReturn res;
3139   gint i;
3140
3141   g_assert (playbin->selected_stream_types != playbin->active_stream_types);
3142
3143   GST_DEBUG_OBJECT (playbin, "selected_stream_types : %" STREAM_TYPES_FORMAT,
3144       STREAM_TYPES_ARGS (playbin->selected_stream_types));
3145   GST_DEBUG_OBJECT (playbin, "active_stream_types : %" STREAM_TYPES_FORMAT,
3146       STREAM_TYPES_ARGS (playbin->active_stream_types));
3147
3148   GST_PLAY_BIN3_LOCK (playbin);
3149
3150   /* Make sure combiners/playsink are in sync with selected stream types */
3151   for (i = 0; i < PLAYBIN_STREAM_LAST; i++) {
3152     GstSourceCombine *combine = &playbin->combiner[i];
3153     gboolean is_selected =
3154         (combine->stream_type & playbin->selected_stream_types) ==
3155         combine->stream_type;
3156     gboolean is_active =
3157         (combine->stream_type & playbin->active_stream_types) ==
3158         combine->stream_type;
3159
3160     GST_DEBUG_OBJECT (playbin, "Stream type status: '%s' %s %s",
3161         combine->media_type, is_selected ? "selected" : "NOT selected",
3162         is_active ? "active" : "NOT active");
3163     /* FIXME : Remove asserts below once enough testing has been done */
3164
3165     if (is_selected && is_active) {
3166       GST_DEBUG_OBJECT (playbin, "Stream type '%s' already active",
3167           combine->media_type);
3168     } else if (is_active && !is_selected) {
3169       GST_DEBUG_OBJECT (playbin, "Stream type '%s' is no longer requested",
3170           combine->media_type);
3171
3172       /* Unlink combiner from sink */
3173       if (combine->srcpad) {
3174         GST_LOG_OBJECT (playbin, "Unlinking from sink");
3175         if (combine->sinkpad)
3176           gst_pad_unlink (combine->srcpad, combine->sinkpad);
3177         gst_object_unref (combine->srcpad);
3178         combine->srcpad = NULL;
3179       }
3180
3181       if (combine->sinkpad) {
3182         /* Release playsink sink pad */
3183         GST_LOG_OBJECT (playbin, "Releasing playsink pad");
3184         gst_play_sink_release_pad (playbin->playsink, combine->sinkpad);
3185         gst_object_unref (combine->sinkpad);
3186         combine->sinkpad = NULL;
3187       }
3188
3189       /* Release combiner */
3190       GST_FIXME_OBJECT (playbin, "Release combiner");
3191       remove_combiner (playbin, combine);
3192     } else if (!is_active && is_selected) {
3193       GST_DEBUG_OBJECT (playbin, "Stream type '%s' is now requested",
3194           combine->media_type);
3195
3196       /* If we are shutting down, do *not* add more combiners */
3197       if (g_atomic_int_get (&playbin->shutdown))
3198         continue;
3199
3200       g_assert (combine->sinkpad == NULL);
3201
3202       /* Request playsink sink pad */
3203       combine->sinkpad =
3204           gst_play_sink_request_pad (playbin->playsink, combine->type);
3205       gst_object_ref (combine->sinkpad);
3206       /* Create combiner if needed and link it */
3207       create_combiner (playbin, combine);
3208       if (combine->combiner) {
3209         res = gst_pad_link (combine->srcpad, combine->sinkpad);
3210         GST_DEBUG_OBJECT (playbin, "linked type %s, result: %d",
3211             combine->media_type, res);
3212         if (res != GST_PAD_LINK_OK) {
3213           GST_ELEMENT_ERROR (playbin, CORE, PAD,
3214               ("Internal playbin error."),
3215               ("Failed to link combiner to sink. Error %d", res));
3216         }
3217
3218       }
3219     }
3220   }
3221
3222   playbin->active_stream_types = playbin->selected_stream_types;
3223
3224   GST_PLAY_BIN3_UNLOCK (playbin);
3225
3226   gst_play_sink_reconfigure (playbin->playsink);
3227
3228   do_async_done (playbin);
3229
3230   GST_DEBUG_OBJECT (playbin, "selected_stream_types : %" STREAM_TYPES_FORMAT,
3231       STREAM_TYPES_ARGS (playbin->selected_stream_types));
3232   GST_DEBUG_OBJECT (playbin, "active_stream_types : %" STREAM_TYPES_FORMAT,
3233       STREAM_TYPES_ARGS (playbin->active_stream_types));
3234
3235   return;
3236 }
3237
3238 static void
3239 about_to_finish_cb (GstElement * uridecodebin, GstSourceGroup * group)
3240 {
3241   GstPlayBin3 *playbin = group->playbin;
3242   GST_DEBUG_OBJECT (playbin, "about to finish in group %p", group);
3243
3244   GST_LOG_OBJECT (playbin, "selected_stream_types:%" STREAM_TYPES_FORMAT,
3245       STREAM_TYPES_ARGS (group->selected_stream_types));
3246   GST_LOG_OBJECT (playbin, "present_stream_types:%" STREAM_TYPES_FORMAT,
3247       STREAM_TYPES_ARGS (group->present_stream_types));
3248
3249   if (group->selected_stream_types == 0
3250       || (group->selected_stream_types != group->present_stream_types)) {
3251     GST_LOG_OBJECT (playbin,
3252         "Delaying emission of signal until this group is ready");
3253     group->pending_about_to_finish = TRUE;
3254   } else
3255     emit_about_to_finish (playbin);
3256 }
3257
3258 #if 0                           /* AUTOPLUG DISABLED */
3259 /* Like gst_element_factory_can_sink_any_caps() but doesn't
3260  * allow ANY caps on the sinkpad template */
3261 static gboolean
3262 _factory_can_sink_caps (GstElementFactory * factory, GstCaps * caps)
3263 {
3264   const GList *templs;
3265
3266   templs = gst_element_factory_get_static_pad_templates (factory);
3267
3268   while (templs) {
3269     GstStaticPadTemplate *templ = (GstStaticPadTemplate *) templs->data;
3270
3271     if (templ->direction == GST_PAD_SINK) {
3272       GstCaps *templcaps = gst_static_caps_get (&templ->static_caps);
3273
3274       if (!gst_caps_is_any (templcaps)
3275           && gst_caps_is_subset (caps, templcaps)) {
3276         gst_caps_unref (templcaps);
3277         return TRUE;
3278       }
3279       gst_caps_unref (templcaps);
3280     }
3281     templs = g_list_next (templs);
3282   }
3283
3284   return FALSE;
3285 }
3286
3287 static void
3288 avelements_free (gpointer avelement)
3289 {
3290   GstAVElement *elm = (GstAVElement *) avelement;
3291
3292   if (elm->dec)
3293     gst_object_unref (elm->dec);
3294   if (elm->sink)
3295     gst_object_unref (elm->sink);
3296   g_slice_free (GstAVElement, elm);
3297 }
3298
3299 static gint
3300 avelement_compare_decoder (gconstpointer p1, gconstpointer p2,
3301     gpointer user_data)
3302 {
3303   GstAVElement *v1, *v2;
3304
3305   v1 = (GstAVElement *) p1;
3306   v2 = (GstAVElement *) p2;
3307
3308   return strcmp (GST_OBJECT_NAME (v1->dec), GST_OBJECT_NAME (v2->dec));
3309 }
3310
3311 static gint
3312 avelement_lookup_decoder (gconstpointer p1, gconstpointer p2,
3313     gpointer user_data)
3314 {
3315   GstAVElement *v1;
3316   GstElementFactory *f2;
3317
3318   v1 = (GstAVElement *) p1;
3319   f2 = (GstElementFactory *) p2;
3320
3321   return strcmp (GST_OBJECT_NAME (v1->dec), GST_OBJECT_NAME (f2));
3322 }
3323
3324 static gint
3325 avelement_compare (gconstpointer p1, gconstpointer p2)
3326 {
3327   GstAVElement *v1, *v2;
3328   GstPluginFeature *fd1, *fd2, *fs1, *fs2;
3329   gint64 diff, v1_rank, v2_rank;
3330
3331   v1 = (GstAVElement *) p1;
3332   v2 = (GstAVElement *) p2;
3333
3334   fd1 = (GstPluginFeature *) v1->dec;
3335   fd2 = (GstPluginFeature *) v2->dec;
3336
3337   /* If both have a sink, we also compare their ranks */
3338   if (v1->sink && v2->sink) {
3339     fs1 = (GstPluginFeature *) v1->sink;
3340     fs2 = (GstPluginFeature *) v2->sink;
3341     v1_rank = (gint64) gst_plugin_feature_get_rank (fd1) *
3342         gst_plugin_feature_get_rank (fs1);
3343     v2_rank = (gint64) gst_plugin_feature_get_rank (fd2) *
3344         gst_plugin_feature_get_rank (fs2);
3345   } else {
3346     v1_rank = gst_plugin_feature_get_rank (fd1);
3347     v2_rank = gst_plugin_feature_get_rank (fd2);
3348     fs1 = fs2 = NULL;
3349   }
3350
3351   /* comparison based on the rank */
3352   diff = v2_rank - v1_rank;
3353   if (diff < 0)
3354     return -1;
3355   else if (diff > 0)
3356     return 1;
3357
3358   /* comparison based on number of common caps features */
3359   diff = v2->n_comm_cf - v1->n_comm_cf;
3360   if (diff != 0)
3361     return diff;
3362
3363   if (fs1 && fs2) {
3364     /* comparison based on the name of sink elements */
3365     diff = strcmp (GST_OBJECT_NAME (fs1), GST_OBJECT_NAME (fs2));
3366     if (diff != 0)
3367       return diff;
3368   }
3369
3370   /* comparison based on the name of decoder elements */
3371   return strcmp (GST_OBJECT_NAME (fd1), GST_OBJECT_NAME (fd2));
3372 }
3373
3374 static GSequence *
3375 avelements_create (GstPlayBin3 * playbin, gboolean isaudioelement)
3376 {
3377   GstElementFactory *d_factory, *s_factory;
3378   GList *dec_list, *sink_list, *dl, *sl;
3379   GSequence *ave_seq = NULL;
3380   GstAVElement *ave;
3381   guint n_common_cf = 0;
3382
3383   if (isaudioelement) {
3384     sink_list = gst_element_factory_list_get_elements
3385         (GST_ELEMENT_FACTORY_TYPE_SINK |
3386         GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO, GST_RANK_MARGINAL);
3387     dec_list =
3388         gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_DECODER
3389         | GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO, GST_RANK_MARGINAL);
3390   } else {
3391     sink_list = gst_element_factory_list_get_elements
3392         (GST_ELEMENT_FACTORY_TYPE_SINK |
3393         GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
3394         GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE, GST_RANK_MARGINAL);
3395
3396     dec_list =
3397         gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_DECODER
3398         | GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
3399         GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE, GST_RANK_MARGINAL);
3400   }
3401
3402   /* create a list of audio/video elements. Each element in the list
3403    * is holding an audio/video decoder and an audio/video sink in which
3404    * the decoders srcpad template caps and sink element's sinkpad template
3405    * caps are compatible */
3406   dl = dec_list;
3407   sl = sink_list;
3408
3409   ave_seq = g_sequence_new ((GDestroyNotify) avelements_free);
3410
3411   for (; dl; dl = dl->next) {
3412     d_factory = (GstElementFactory *) dl->data;
3413     for (; sl; sl = sl->next) {
3414       s_factory = (GstElementFactory *) sl->data;
3415
3416       n_common_cf =
3417           gst_playback_utils_get_n_common_capsfeatures (d_factory, s_factory,
3418           gst_play_bin3_get_flags (playbin), isaudioelement);
3419       if (n_common_cf < 1)
3420         continue;
3421
3422       ave = g_slice_new (GstAVElement);
3423       ave->dec = gst_object_ref (d_factory);
3424       ave->sink = gst_object_ref (s_factory);
3425       ave->n_comm_cf = n_common_cf;
3426       g_sequence_append (ave_seq, ave);
3427     }
3428     sl = sink_list;
3429   }
3430   g_sequence_sort (ave_seq, (GCompareDataFunc) avelement_compare_decoder, NULL);
3431
3432   gst_plugin_feature_list_free (dec_list);
3433   gst_plugin_feature_list_free (sink_list);
3434
3435   return ave_seq;
3436 }
3437
3438 static gboolean
3439 avelement_iter_is_equal (GSequenceIter * iter, GstElementFactory * factory)
3440 {
3441   GstAVElement *ave;
3442
3443   if (!iter)
3444     return FALSE;
3445
3446   ave = g_sequence_get (iter);
3447   if (!ave)
3448     return FALSE;
3449
3450   return strcmp (GST_OBJECT_NAME (ave->dec), GST_OBJECT_NAME (factory)) == 0;
3451 }
3452
3453 static GList *
3454 create_decoders_list (GList * factory_list, GSequence * avelements)
3455 {
3456   GList *dec_list = NULL, *tmp;
3457   GList *ave_list = NULL;
3458   GList *ave_free_list = NULL;
3459   GstAVElement *ave, *best_ave;
3460
3461   g_return_val_if_fail (factory_list != NULL, NULL);
3462   g_return_val_if_fail (avelements != NULL, NULL);
3463
3464   for (tmp = factory_list; tmp; tmp = tmp->next) {
3465     GstElementFactory *factory = (GstElementFactory *) tmp->data;
3466
3467     /* if there are parsers or sink elements, add them first */
3468     if (gst_element_factory_list_is_type (factory,
3469             GST_ELEMENT_FACTORY_TYPE_PARSER) ||
3470         gst_element_factory_list_is_type (factory,
3471             GST_ELEMENT_FACTORY_TYPE_SINK)) {
3472       dec_list = g_list_prepend (dec_list, gst_object_ref (factory));
3473     } else {
3474       GSequenceIter *seq_iter;
3475
3476       seq_iter =
3477           g_sequence_lookup (avelements, factory,
3478           (GCompareDataFunc) avelement_lookup_decoder, NULL);
3479       if (!seq_iter) {
3480         GstAVElement *ave = g_slice_new0 (GstAVElement);
3481
3482         ave->dec = factory;
3483         ave->sink = NULL;
3484         /* There's at least raw */
3485         ave->n_comm_cf = 1;
3486
3487         ave_list = g_list_prepend (ave_list, ave);
3488
3489         /* We need to free these later */
3490         ave_free_list = g_list_prepend (ave_free_list, ave);
3491         continue;
3492       }
3493
3494       /* Go to first iter with that decoder */
3495       do {
3496         GSequenceIter *tmp_seq_iter;
3497
3498         tmp_seq_iter = g_sequence_iter_prev (seq_iter);
3499         if (!avelement_iter_is_equal (tmp_seq_iter, factory))
3500           break;
3501         seq_iter = tmp_seq_iter;
3502       } while (!g_sequence_iter_is_begin (seq_iter));
3503
3504       /* Get the best ranked GstAVElement for that factory */
3505       best_ave = NULL;
3506       while (!g_sequence_iter_is_end (seq_iter)
3507           && avelement_iter_is_equal (seq_iter, factory)) {
3508         ave = g_sequence_get (seq_iter);
3509
3510         if (!best_ave || avelement_compare (ave, best_ave) < 0)
3511           best_ave = ave;
3512
3513         seq_iter = g_sequence_iter_next (seq_iter);
3514       }
3515       ave_list = g_list_prepend (ave_list, best_ave);
3516     }
3517   }
3518
3519   /* Sort all GstAVElements by their relative ranks and insert
3520    * into the decoders list */
3521   ave_list = g_list_sort (ave_list, (GCompareFunc) avelement_compare);
3522   for (tmp = ave_list; tmp; tmp = tmp->next) {
3523     ave = (GstAVElement *) tmp->data;
3524     dec_list = g_list_prepend (dec_list, gst_object_ref (ave->dec));
3525   }
3526   g_list_free (ave_list);
3527   gst_plugin_feature_list_free (factory_list);
3528
3529   for (tmp = ave_free_list; tmp; tmp = tmp->next)
3530     g_slice_free (GstAVElement, tmp->data);
3531   g_list_free (ave_free_list);
3532
3533   dec_list = g_list_reverse (dec_list);
3534
3535   return dec_list;
3536 }
3537
3538 /* Called when we must provide a list of factories to plug to @pad with @caps.
3539  * We first check if we have a sink that can handle the format and if we do, we
3540  * return NULL, to expose the pad. If we have no sink (or the sink does not
3541  * work), we return the list of elements that can connect. */
3542 static GValueArray *
3543 autoplug_factories_cb (GstElement * decodebin, GstPad * pad,
3544     GstCaps * caps, GstSourceGroup * group)
3545 {
3546   GstPlayBin3 *playbin;
3547   GList *factory_list, *tmp;
3548   GValueArray *result;
3549   gboolean unref_caps = FALSE;
3550   gboolean isaudiodeclist = FALSE;
3551   gboolean isvideodeclist = FALSE;
3552
3553   if (!caps) {
3554     caps = gst_caps_new_any ();
3555     unref_caps = TRUE;
3556   }
3557
3558   playbin = group->playbin;
3559
3560   GST_DEBUG_OBJECT (playbin, "factories group %p for %s:%s, %" GST_PTR_FORMAT,
3561       group, GST_DEBUG_PAD_NAME (pad), caps);
3562
3563   /* filter out the elements based on the caps. */
3564   g_mutex_lock (&playbin->elements_lock);
3565   gst_play_bin3_update_elements_list (playbin);
3566   factory_list =
3567       gst_element_factory_list_filter (playbin->elements, caps, GST_PAD_SINK,
3568       gst_caps_is_fixed (caps));
3569   g_mutex_unlock (&playbin->elements_lock);
3570
3571   GST_DEBUG_OBJECT (playbin, "found factories %p", factory_list);
3572   GST_PLUGIN_FEATURE_LIST_DEBUG (factory_list);
3573
3574   /* check whether the caps are asking for a list of audio/video decoders */
3575   tmp = factory_list;
3576   if (!gst_caps_is_any (caps)) {
3577     for (; tmp; tmp = tmp->next) {
3578       GstElementFactory *factory = (GstElementFactory *) tmp->data;
3579
3580       isvideodeclist = gst_element_factory_list_is_type (factory,
3581           GST_ELEMENT_FACTORY_TYPE_DECODER |
3582           GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
3583           GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE);
3584       isaudiodeclist = gst_element_factory_list_is_type (factory,
3585           GST_ELEMENT_FACTORY_TYPE_DECODER |
3586           GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO);
3587
3588       if (isaudiodeclist || isvideodeclist)
3589         break;
3590     }
3591   }
3592
3593   if (isaudiodeclist || isvideodeclist) {
3594     GSequence **ave_list;
3595     if (isaudiodeclist)
3596       ave_list = &playbin->aelements;
3597     else
3598       ave_list = &playbin->velements;
3599
3600     g_mutex_lock (&playbin->elements_lock);
3601     /* sort factory_list based on the GstAVElement list priority */
3602     factory_list = create_decoders_list (factory_list, *ave_list);
3603     g_mutex_unlock (&playbin->elements_lock);
3604   }
3605
3606   /* 2 additional elements for the already set audio/video sinks */
3607   result = g_value_array_new (g_list_length (factory_list) + 2);
3608
3609   /* Check if we already have an audio/video sink and if this is the case
3610    * put it as the first element of the array */
3611   if (group->audio_sink) {
3612     GstElementFactory *factory = gst_element_get_factory (group->audio_sink);
3613
3614     if (factory && _factory_can_sink_caps (factory, caps)) {
3615       GValue val = { 0, };
3616
3617       g_value_init (&val, G_TYPE_OBJECT);
3618       g_value_set_object (&val, factory);
3619       result = g_value_array_append (result, &val);
3620       g_value_unset (&val);
3621     }
3622   }
3623
3624   if (group->video_sink) {
3625     GstElementFactory *factory = gst_element_get_factory (group->video_sink);
3626
3627     if (factory && _factory_can_sink_caps (factory, caps)) {
3628       GValue val = { 0, };
3629
3630       g_value_init (&val, G_TYPE_OBJECT);
3631       g_value_set_object (&val, factory);
3632       result = g_value_array_append (result, &val);
3633       g_value_unset (&val);
3634     }
3635   }
3636
3637   for (tmp = factory_list; tmp; tmp = tmp->next) {
3638     GstElementFactory *factory = GST_ELEMENT_FACTORY_CAST (tmp->data);
3639     GValue val = { 0, };
3640
3641     if (group->audio_sink && gst_element_factory_list_is_type (factory,
3642             GST_ELEMENT_FACTORY_TYPE_SINK |
3643             GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO)) {
3644       continue;
3645     }
3646     if (group->video_sink && gst_element_factory_list_is_type (factory,
3647             GST_ELEMENT_FACTORY_TYPE_SINK | GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO
3648             | GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE)) {
3649       continue;
3650     }
3651
3652     g_value_init (&val, G_TYPE_OBJECT);
3653     g_value_set_object (&val, factory);
3654     g_value_array_append (result, &val);
3655     g_value_unset (&val);
3656   }
3657   gst_plugin_feature_list_free (factory_list);
3658
3659   if (unref_caps)
3660     gst_caps_unref (caps);
3661
3662   return result;
3663 }
3664 #endif
3665
3666 static GstBusSyncReply
3667 activate_sink_bus_handler (GstBus * bus, GstMessage * msg,
3668     GstPlayBin3 * playbin)
3669 {
3670   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ERROR) {
3671     /* Only proxy errors from a fixed sink. If that fails we can just error out
3672      * early as stuff will fail later anyway */
3673     if (playbin->audio_sink
3674         && gst_object_has_as_ancestor (GST_MESSAGE_SRC (msg),
3675             GST_OBJECT_CAST (playbin->audio_sink)))
3676       gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
3677     else if (playbin->video_sink
3678         && gst_object_has_as_ancestor (GST_MESSAGE_SRC (msg),
3679             GST_OBJECT_CAST (playbin->video_sink)))
3680       gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
3681     else if (playbin->text_sink
3682         && gst_object_has_as_ancestor (GST_MESSAGE_SRC (msg),
3683             GST_OBJECT_CAST (playbin->text_sink)))
3684       gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
3685     else
3686       gst_message_unref (msg);
3687   } else if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_HAVE_CONTEXT) {
3688     GstContext *context;
3689
3690     gst_message_parse_have_context (msg, &context);
3691     gst_element_set_context (GST_ELEMENT_CAST (playbin), context);
3692     gst_context_unref (context);
3693     gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
3694   } else {
3695     gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
3696   }
3697
3698   /* Doesn't really matter, nothing is using this bus */
3699   return GST_BUS_DROP;
3700 }
3701
3702 static gboolean
3703 activate_sink (GstPlayBin3 * playbin, GstElement * sink, gboolean * activated)
3704 {
3705   GstState state;
3706   GstBus *bus = NULL;
3707   GstStateChangeReturn sret;
3708   gboolean ret = FALSE;
3709
3710   if (activated)
3711     *activated = FALSE;
3712
3713   GST_OBJECT_LOCK (sink);
3714   state = GST_STATE (sink);
3715   GST_OBJECT_UNLOCK (sink);
3716   if (state >= GST_STATE_READY) {
3717     ret = TRUE;
3718     goto done;
3719   }
3720
3721   if (!GST_OBJECT_PARENT (sink)) {
3722     bus = gst_bus_new ();
3723     gst_bus_set_sync_handler (bus,
3724         (GstBusSyncHandler) activate_sink_bus_handler, playbin, NULL);
3725     gst_element_set_bus (sink, bus);
3726   }
3727
3728   sret = gst_element_set_state (sink, GST_STATE_READY);
3729   if (sret == GST_STATE_CHANGE_FAILURE)
3730     goto done;
3731
3732   if (activated)
3733     *activated = TRUE;
3734   ret = TRUE;
3735
3736 done:
3737   if (bus) {
3738     gst_element_set_bus (sink, NULL);
3739     gst_object_unref (bus);
3740   }
3741
3742   return ret;
3743 }
3744
3745 #if 0                           /* AUTOPLUG DISABLED */
3746 /* autoplug-continue decides, if a pad has raw caps that can be exposed
3747  * directly or if further decoding is necessary. We use this to expose
3748  * supported subtitles directly */
3749
3750 /* FIXME 0.11: Remove the checks for ANY caps, a sink should specify
3751  * explicitly the caps it supports and if it claims to support ANY
3752  * caps it really should support everything */
3753 static gboolean
3754 autoplug_continue_cb (GstElement * element, GstPad * pad, GstCaps * caps,
3755     GstSourceGroup * group)
3756 {
3757   gboolean ret = TRUE;
3758   GstPad *sinkpad = NULL;
3759   gboolean activated_sink;
3760
3761   GST_SOURCE_GROUP_LOCK (group);
3762
3763   if (group->text_sink &&
3764       activate_sink (group->playbin, group->text_sink, &activated_sink)) {
3765     sinkpad = gst_element_get_static_pad (group->text_sink, "sink");
3766     if (sinkpad) {
3767       GstCaps *sinkcaps;
3768
3769       sinkcaps = gst_pad_query_caps (sinkpad, NULL);
3770       if (!gst_caps_is_any (sinkcaps))
3771         ret = !gst_pad_query_accept_caps (sinkpad, caps);
3772       gst_caps_unref (sinkcaps);
3773       gst_object_unref (sinkpad);
3774     }
3775     if (activated_sink)
3776       gst_element_set_state (group->text_sink, GST_STATE_NULL);
3777   } else {
3778     GstCaps *subcaps = gst_subtitle_overlay_create_factory_caps ();
3779     ret = !gst_caps_is_subset (caps, subcaps);
3780     gst_caps_unref (subcaps);
3781   }
3782   /* If autoplugging can stop don't do additional checks */
3783   if (!ret)
3784     goto done;
3785
3786   if (group->audio_sink &&
3787       activate_sink (group->playbin, group->audio_sink, &activated_sink)) {
3788
3789     sinkpad = gst_element_get_static_pad (group->audio_sink, "sink");
3790     if (sinkpad) {
3791       GstCaps *sinkcaps;
3792
3793       sinkcaps = gst_pad_query_caps (sinkpad, NULL);
3794       if (!gst_caps_is_any (sinkcaps))
3795         ret = !gst_pad_query_accept_caps (sinkpad, caps);
3796       gst_caps_unref (sinkcaps);
3797       gst_object_unref (sinkpad);
3798     }
3799     if (activated_sink)
3800       gst_element_set_state (group->audio_sink, GST_STATE_NULL);
3801   }
3802   if (!ret)
3803     goto done;
3804
3805   if (group->video_sink
3806       && activate_sink (group->playbin, group->video_sink, &activated_sink)) {
3807     sinkpad = gst_element_get_static_pad (group->video_sink, "sink");
3808     if (sinkpad) {
3809       GstCaps *sinkcaps;
3810
3811       sinkcaps = gst_pad_query_caps (sinkpad, NULL);
3812       if (!gst_caps_is_any (sinkcaps))
3813         ret = !gst_pad_query_accept_caps (sinkpad, caps);
3814       gst_caps_unref (sinkcaps);
3815       gst_object_unref (sinkpad);
3816     }
3817     if (activated_sink)
3818       gst_element_set_state (group->video_sink, GST_STATE_NULL);
3819   }
3820
3821 done:
3822   GST_SOURCE_GROUP_UNLOCK (group);
3823
3824   GST_DEBUG_OBJECT (group->playbin,
3825       "continue autoplugging group %p for %s:%s, %" GST_PTR_FORMAT ": %d",
3826       group, GST_DEBUG_PAD_NAME (pad), caps, ret);
3827
3828   return ret;
3829 }
3830
3831 static gboolean
3832 sink_accepts_caps (GstPlayBin3 * playbin, GstElement * sink, GstCaps * caps)
3833 {
3834   GstPad *sinkpad;
3835
3836   if ((sinkpad = gst_element_get_static_pad (sink, "sink"))) {
3837     /* Got the sink pad, now let's see if the element actually does accept the
3838      * caps that we have */
3839     if (!gst_pad_query_accept_caps (sinkpad, caps)) {
3840       gst_object_unref (sinkpad);
3841       return FALSE;
3842     }
3843     gst_object_unref (sinkpad);
3844   }
3845
3846   return TRUE;
3847 }
3848
3849 /* We are asked to select an element. See if the next element to check
3850  * is a sink. If this is the case, we see if the sink works by setting it to
3851  * READY. If the sink works, we return SELECT_EXPOSE to make decodebin
3852  * expose the raw pad so that we can setup the mixers. */
3853 static GstAutoplugSelectResult
3854 autoplug_select_cb (GstElement * decodebin, GstPad * pad,
3855     GstCaps * caps, GstElementFactory * factory, GstSourceGroup * group)
3856 {
3857   GstPlayBin3 *playbin;
3858   GstElement *element;
3859   const gchar *klass;
3860   GstPlaySinkType type;
3861   GstElement **sinkp;
3862   GList *ave_list = NULL, *l;
3863   GstAVElement *ave = NULL;
3864   GSequence *ave_seq = NULL;
3865   GSequenceIter *seq_iter;
3866
3867   playbin = group->playbin;
3868
3869   GST_DEBUG_OBJECT (playbin, "select group %p for %s:%s, %" GST_PTR_FORMAT,
3870       group, GST_DEBUG_PAD_NAME (pad), caps);
3871
3872   GST_DEBUG_OBJECT (playbin, "checking factory %s", GST_OBJECT_NAME (factory));
3873
3874   /* if it's not a sink, we make sure the element is compatible with
3875    * the fixed sink */
3876   if (!gst_element_factory_list_is_type (factory,
3877           GST_ELEMENT_FACTORY_TYPE_SINK)) {
3878     gboolean isvideodec = gst_element_factory_list_is_type (factory,
3879         GST_ELEMENT_FACTORY_TYPE_DECODER |
3880         GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
3881         GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE);
3882     gboolean isaudiodec = gst_element_factory_list_is_type (factory,
3883         GST_ELEMENT_FACTORY_TYPE_DECODER |
3884         GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO);
3885
3886     if (!isvideodec && !isaudiodec)
3887       return GST_AUTOPLUG_SELECT_TRY;
3888
3889     GST_SOURCE_GROUP_LOCK (group);
3890     g_mutex_lock (&playbin->elements_lock);
3891
3892     if (isaudiodec) {
3893       ave_seq = playbin->aelements;
3894       sinkp = &group->audio_sink;
3895     } else {
3896       ave_seq = playbin->velements;
3897       sinkp = &group->video_sink;
3898     }
3899
3900     seq_iter =
3901         g_sequence_lookup (ave_seq, factory,
3902         (GCompareDataFunc) avelement_lookup_decoder, NULL);
3903     if (seq_iter) {
3904       /* Go to first iter with that decoder */
3905       do {
3906         GSequenceIter *tmp_seq_iter;
3907
3908         tmp_seq_iter = g_sequence_iter_prev (seq_iter);
3909         if (!avelement_iter_is_equal (tmp_seq_iter, factory))
3910           break;
3911         seq_iter = tmp_seq_iter;
3912       } while (!g_sequence_iter_is_begin (seq_iter));
3913
3914       while (!g_sequence_iter_is_end (seq_iter)
3915           && avelement_iter_is_equal (seq_iter, factory)) {
3916         ave = g_sequence_get (seq_iter);
3917         ave_list = g_list_prepend (ave_list, ave);
3918         seq_iter = g_sequence_iter_next (seq_iter);
3919       }
3920
3921       /* Sort all GstAVElements by their relative ranks and insert
3922        * into the decoders list */
3923       ave_list = g_list_sort (ave_list, (GCompareFunc) avelement_compare);
3924     } else {
3925       ave_list = g_list_prepend (ave_list, NULL);
3926     }
3927
3928     /* if it is a decoder and we don't have a fixed sink, then find out
3929      * the matching audio/video sink from GstAVElements list */
3930     for (l = ave_list; l; l = l->next) {
3931       gboolean created_sink = FALSE;
3932
3933       ave = (GstAVElement *) l->data;
3934
3935       if (((isaudiodec && !group->audio_sink) ||
3936               (isvideodec && !group->video_sink))) {
3937         if (ave && ave->sink) {
3938           GST_DEBUG_OBJECT (playbin,
3939               "Trying to create sink '%s' for decoder '%s'",
3940               gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (ave->sink)),
3941               gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
3942           if ((*sinkp = gst_element_factory_create (ave->sink, NULL)) == NULL) {
3943             GST_WARNING_OBJECT (playbin,
3944                 "Could not create an element from %s",
3945                 gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (ave->sink)));
3946             continue;
3947           } else {
3948             if (!activate_sink (playbin, *sinkp, NULL)) {
3949               gst_object_unref (*sinkp);
3950               *sinkp = NULL;
3951               GST_WARNING_OBJECT (playbin,
3952                   "Could not activate sink %s",
3953                   gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (ave->sink)));
3954               continue;
3955             }
3956             gst_object_ref_sink (*sinkp);
3957             created_sink = TRUE;
3958           }
3959         }
3960       }
3961
3962       /* If it is a decoder and we have a fixed sink for the media
3963        * type it outputs, check that the decoder is compatible with this sink */
3964       if ((isaudiodec && group->audio_sink) || (isvideodec
3965               && group->video_sink)) {
3966         gboolean compatible = FALSE;
3967         GstPad *sinkpad;
3968         GstCaps *caps;
3969         GstElement *sink;
3970
3971         sink = *sinkp;
3972
3973         if ((sinkpad = gst_element_get_static_pad (sink, "sink"))) {
3974           GstPlayFlags flags = gst_play_bin3_get_flags (playbin);
3975           GstCaps *raw_caps =
3976               (isaudiodec) ? gst_static_caps_get (&raw_audio_caps) :
3977               gst_static_caps_get (&raw_video_caps);
3978
3979           caps = gst_pad_query_caps (sinkpad, NULL);
3980
3981           /* If the sink supports raw audio/video, we first check
3982            * if the decoder could output any raw audio/video format
3983            * and assume it is compatible with the sink then. We don't
3984            * do a complete compatibility check here if converters
3985            * are plugged between the decoder and the sink because
3986            * the converters will convert between raw formats and
3987            * even if the decoder format is not supported by the decoder
3988            * a converter will convert it.
3989            *
3990            * We assume here that the converters can convert between
3991            * any raw format.
3992            */
3993           if ((isaudiodec && !(flags & GST_PLAY_FLAG_NATIVE_AUDIO)
3994                   && gst_caps_can_intersect (caps, raw_caps)) || (!isaudiodec
3995                   && !(flags & GST_PLAY_FLAG_NATIVE_VIDEO)
3996                   && gst_caps_can_intersect (caps, raw_caps))) {
3997             compatible =
3998                 gst_element_factory_can_src_any_caps (factory, raw_caps)
3999                 || gst_element_factory_can_src_any_caps (factory, caps);
4000           } else {
4001             compatible = gst_element_factory_can_src_any_caps (factory, caps);
4002           }
4003
4004           gst_object_unref (sinkpad);
4005           gst_caps_unref (caps);
4006         }
4007
4008         if (compatible)
4009           break;
4010
4011         GST_DEBUG_OBJECT (playbin, "%s not compatible with the fixed sink",
4012             GST_OBJECT_NAME (factory));
4013
4014         /* If it is not compatible, either continue with the next possible
4015          * sink or if we have a fixed sink, skip the decoder */
4016         if (created_sink) {
4017           gst_element_set_state (*sinkp, GST_STATE_NULL);
4018           gst_object_unref (*sinkp);
4019           *sinkp = NULL;
4020         } else {
4021           g_mutex_unlock (&playbin->elements_lock);
4022           GST_SOURCE_GROUP_UNLOCK (group);
4023           return GST_AUTOPLUG_SELECT_SKIP;
4024         }
4025       }
4026     }
4027     g_list_free (ave_list);
4028     g_mutex_unlock (&playbin->elements_lock);
4029     GST_SOURCE_GROUP_UNLOCK (group);
4030     return GST_AUTOPLUG_SELECT_TRY;
4031   }
4032
4033   /* it's a sink, see if an instance of it actually works */
4034   GST_DEBUG_OBJECT (playbin, "we found a sink '%s'", GST_OBJECT_NAME (factory));
4035
4036   klass =
4037       gst_element_factory_get_metadata (factory, GST_ELEMENT_METADATA_KLASS);
4038
4039   /* figure out the klass */
4040   if (strstr (klass, "Audio")) {
4041     GST_DEBUG_OBJECT (playbin, "we found an audio sink");
4042     type = GST_PLAY_SINK_TYPE_AUDIO;
4043     sinkp = &group->audio_sink;
4044   } else if (strstr (klass, "Video")) {
4045     GST_DEBUG_OBJECT (playbin, "we found a video sink");
4046     type = GST_PLAY_SINK_TYPE_VIDEO;
4047     sinkp = &group->video_sink;
4048   } else {
4049     /* unknown klass, skip this element */
4050     GST_WARNING_OBJECT (playbin, "unknown sink klass %s found", klass);
4051     return GST_AUTOPLUG_SELECT_SKIP;
4052   }
4053
4054   /* if we are asked to do visualisations and it's an audio sink, skip the
4055    * element. We can only do visualisations with raw sinks */
4056   if (gst_play_sink_get_flags (playbin->playsink) & GST_PLAY_FLAG_VIS) {
4057     if (type == GST_PLAY_SINK_TYPE_AUDIO) {
4058       GST_DEBUG_OBJECT (playbin, "skip audio sink because of vis");
4059       return GST_AUTOPLUG_SELECT_SKIP;
4060     }
4061   }
4062
4063   /* now see if we already have a sink element */
4064   GST_SOURCE_GROUP_LOCK (group);
4065   if (*sinkp && GST_STATE (*sinkp) >= GST_STATE_READY) {
4066     GstElement *sink = gst_object_ref (*sinkp);
4067
4068     if (sink_accepts_caps (playbin, sink, caps)) {
4069       GST_DEBUG_OBJECT (playbin,
4070           "Existing sink '%s' accepts caps: %" GST_PTR_FORMAT,
4071           GST_ELEMENT_NAME (sink), caps);
4072       gst_object_unref (sink);
4073       GST_SOURCE_GROUP_UNLOCK (group);
4074       return GST_AUTOPLUG_SELECT_EXPOSE;
4075     } else {
4076       GST_DEBUG_OBJECT (playbin,
4077           "Existing sink '%s' does not accept caps: %" GST_PTR_FORMAT,
4078           GST_ELEMENT_NAME (sink), caps);
4079       gst_object_unref (sink);
4080       GST_SOURCE_GROUP_UNLOCK (group);
4081       return GST_AUTOPLUG_SELECT_SKIP;
4082     }
4083   }
4084   GST_DEBUG_OBJECT (playbin, "we have no pending sink, try to create '%s'",
4085       gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
4086
4087   if ((*sinkp = gst_element_factory_create (factory, NULL)) == NULL) {
4088     GST_WARNING_OBJECT (playbin, "Could not create an element from %s",
4089         gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
4090     GST_SOURCE_GROUP_UNLOCK (group);
4091     return GST_AUTOPLUG_SELECT_SKIP;
4092   }
4093
4094   element = *sinkp;
4095
4096   if (!activate_sink (playbin, element, NULL)) {
4097     GST_WARNING_OBJECT (playbin, "Could not activate sink %s",
4098         gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
4099     *sinkp = NULL;
4100     gst_object_unref (element);
4101     GST_SOURCE_GROUP_UNLOCK (group);
4102     return GST_AUTOPLUG_SELECT_SKIP;
4103   }
4104
4105   /* Check if the selected sink actually supports the
4106    * caps and can be set to READY*/
4107   if (!sink_accepts_caps (playbin, element, caps)) {
4108     *sinkp = NULL;
4109     gst_element_set_state (element, GST_STATE_NULL);
4110     gst_object_unref (element);
4111     GST_SOURCE_GROUP_UNLOCK (group);
4112     return GST_AUTOPLUG_SELECT_SKIP;
4113   }
4114
4115   /* remember the sink in the group now, the element is floating, we take
4116    * ownership now
4117    *
4118    * store the sink in the group, we will configure it later when we
4119    * reconfigure the sink */
4120   GST_DEBUG_OBJECT (playbin, "remember sink");
4121   gst_object_ref_sink (element);
4122   GST_SOURCE_GROUP_UNLOCK (group);
4123
4124   /* tell decodebin to expose the pad because we are going to use this
4125    * sink */
4126   GST_DEBUG_OBJECT (playbin, "we found a working sink, expose pad");
4127
4128   return GST_AUTOPLUG_SELECT_EXPOSE;
4129 }
4130
4131 #define GST_PLAY_BIN3_FILTER_CAPS(filter,caps) G_STMT_START {                  \
4132   if ((filter)) {                                                             \
4133     GstCaps *intersection =                                                   \
4134         gst_caps_intersect_full ((filter), (caps), GST_CAPS_INTERSECT_FIRST); \
4135     gst_caps_unref ((caps));                                                  \
4136     (caps) = intersection;                                                    \
4137   }                                                                           \
4138 } G_STMT_END
4139
4140 static gboolean
4141 autoplug_query_caps (GstElement * uridecodebin, GstPad * pad,
4142     GstElement * element, GstQuery * query, GstSourceGroup * group)
4143 {
4144   GstCaps *filter, *result = NULL;
4145   GstElement *sink;
4146   GstPad *sinkpad = NULL;
4147   GstElementFactory *factory;
4148   GstElementFactoryListType factory_type;
4149   gboolean have_sink = FALSE;
4150
4151   GST_SOURCE_GROUP_LOCK (group);
4152   gst_query_parse_caps (query, &filter);
4153
4154   factory = gst_element_get_factory (element);
4155   if (!factory)
4156     goto done;
4157
4158   if (gst_element_factory_list_is_type (factory,
4159           GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
4160           GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE)) {
4161     factory_type =
4162         GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
4163         GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE;
4164
4165     if ((sink = group->video_sink)) {
4166       sinkpad = gst_element_get_static_pad (sink, "sink");
4167       if (sinkpad) {
4168         GstCaps *sinkcaps;
4169
4170         sinkcaps = gst_pad_query_caps (sinkpad, filter);
4171         if (!gst_caps_is_any (sinkcaps)) {
4172           if (!result)
4173             result = sinkcaps;
4174           else
4175             result = gst_caps_merge (result, sinkcaps);
4176         } else {
4177           gst_caps_unref (sinkcaps);
4178         }
4179         gst_object_unref (sinkpad);
4180       }
4181       have_sink = TRUE;
4182     }
4183   } else if (gst_element_factory_list_is_type (factory,
4184           GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO)) {
4185     factory_type = GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO;
4186
4187     if ((sink = group->audio_sink)) {
4188       sinkpad = gst_element_get_static_pad (sink, "sink");
4189       if (sinkpad) {
4190         GstCaps *sinkcaps;
4191
4192         sinkcaps = gst_pad_query_caps (sinkpad, filter);
4193         if (!gst_caps_is_any (sinkcaps)) {
4194           if (!result)
4195             result = sinkcaps;
4196           else
4197             result = gst_caps_merge (result, sinkcaps);
4198         } else {
4199           gst_caps_unref (sinkcaps);
4200         }
4201         gst_object_unref (sinkpad);
4202       }
4203       have_sink = TRUE;
4204     }
4205   } else if (gst_element_factory_list_is_type (factory,
4206           GST_ELEMENT_FACTORY_TYPE_MEDIA_SUBTITLE)) {
4207     factory_type = GST_ELEMENT_FACTORY_TYPE_MEDIA_SUBTITLE;
4208
4209     if ((sink = group->playbin->text_sink)) {
4210       sinkpad = gst_element_get_static_pad (sink, "sink");
4211       if (sinkpad) {
4212         GstCaps *sinkcaps;
4213
4214         sinkcaps = gst_pad_query_caps (sinkpad, filter);
4215         if (!gst_caps_is_any (sinkcaps)) {
4216           if (!result)
4217             result = sinkcaps;
4218           else
4219             result = gst_caps_merge (result, sinkcaps);
4220         } else {
4221           gst_caps_unref (sinkcaps);
4222         }
4223         gst_object_unref (sinkpad);
4224       }
4225       have_sink = TRUE;
4226     } else {
4227       GstCaps *subcaps = gst_subtitle_overlay_create_factory_caps ();
4228       GST_PLAY_BIN3_FILTER_CAPS (filter, subcaps);
4229       if (!result)
4230         result = subcaps;
4231       else
4232         result = gst_caps_merge (result, subcaps);
4233     }
4234   } else {
4235     goto done;
4236   }
4237
4238   if (!have_sink) {
4239     GValueArray *factories;
4240     gint i, n;
4241
4242     factories = autoplug_factories_cb (uridecodebin, pad, NULL, group);
4243     n = factories->n_values;
4244     for (i = 0; i < n; i++) {
4245       GValue *v = g_value_array_get_nth (factories, i);
4246       GstElementFactory *f = g_value_get_object (v);
4247       const GList *templates;
4248       const GList *l;
4249       GstCaps *templ_caps;
4250
4251       if (!gst_element_factory_list_is_type (f, factory_type))
4252         continue;
4253
4254       templates = gst_element_factory_get_static_pad_templates (f);
4255
4256       for (l = templates; l; l = l->next) {
4257         templ_caps = gst_static_pad_template_get_caps (l->data);
4258
4259         if (!gst_caps_is_any (templ_caps)) {
4260           GST_PLAY_BIN3_FILTER_CAPS (filter, templ_caps);
4261           if (!result)
4262             result = templ_caps;
4263           else
4264             result = gst_caps_merge (result, templ_caps);
4265         } else {
4266           gst_caps_unref (templ_caps);
4267         }
4268       }
4269     }
4270     g_value_array_free (factories);
4271   }
4272
4273 done:
4274   GST_SOURCE_GROUP_UNLOCK (group);
4275
4276   if (!result)
4277     return FALSE;
4278
4279   /* Add the actual decoder/parser/etc caps at the very end to
4280    * make sure we don't cause empty caps to be returned, e.g.
4281    * if a parser asks us but a decoder is required after it
4282    * because no sink can handle the format directly.
4283    */
4284   {
4285     GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
4286
4287     if (target) {
4288       GstCaps *target_caps = gst_pad_get_pad_template_caps (target);
4289       GST_PLAY_BIN3_FILTER_CAPS (filter, target_caps);
4290       result = gst_caps_merge (result, target_caps);
4291       gst_object_unref (target);
4292     }
4293   }
4294
4295
4296   gst_query_set_caps_result (query, result);
4297   gst_caps_unref (result);
4298
4299   return TRUE;
4300 }
4301
4302 static gboolean
4303 autoplug_query_context (GstElement * uridecodebin, GstPad * pad,
4304     GstElement * element, GstQuery * query, GstSourceGroup * group)
4305 {
4306   GstElement *sink;
4307   GstPad *sinkpad = NULL;
4308   GstElementFactory *factory;
4309   gboolean res = FALSE;
4310
4311   GST_SOURCE_GROUP_LOCK (group);
4312
4313   factory = gst_element_get_factory (element);
4314   if (!factory)
4315     goto done;
4316
4317   if (gst_element_factory_list_is_type (factory,
4318           GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
4319           GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE)) {
4320     if ((sink = group->video_sink)) {
4321       sinkpad = gst_element_get_static_pad (sink, "sink");
4322       if (sinkpad) {
4323         res = gst_pad_query (sinkpad, query);
4324         gst_object_unref (sinkpad);
4325       }
4326     }
4327   } else if (gst_element_factory_list_is_type (factory,
4328           GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO)) {
4329     if ((sink = group->audio_sink)) {
4330       sinkpad = gst_element_get_static_pad (sink, "sink");
4331       if (sinkpad) {
4332         res = gst_pad_query (sinkpad, query);
4333         gst_object_unref (sinkpad);
4334       }
4335     }
4336   } else if (gst_element_factory_list_is_type (factory,
4337           GST_ELEMENT_FACTORY_TYPE_MEDIA_SUBTITLE)) {
4338     if ((sink = group->playbin->text_sink)) {
4339       sinkpad = gst_element_get_static_pad (sink, "sink");
4340       if (sinkpad) {
4341         res = gst_pad_query (sinkpad, query);
4342         gst_object_unref (sinkpad);
4343       }
4344     }
4345   } else {
4346     goto done;
4347   }
4348
4349 done:
4350   GST_SOURCE_GROUP_UNLOCK (group);
4351
4352   return res;
4353 }
4354
4355 static gboolean
4356 autoplug_query_cb (GstElement * uridecodebin, GstPad * pad,
4357     GstElement * element, GstQuery * query, GstSourceGroup * group)
4358 {
4359
4360   switch (GST_QUERY_TYPE (query)) {
4361     case GST_QUERY_CAPS:
4362       return autoplug_query_caps (uridecodebin, pad, element, query, group);
4363     case GST_QUERY_CONTEXT:
4364       return autoplug_query_context (uridecodebin, pad, element, query, group);
4365     default:
4366       return FALSE;
4367   }
4368 }
4369 #endif
4370
4371 /* must be called with the group lock */
4372 static gboolean
4373 group_set_locked_state_unlocked (GstPlayBin3 * playbin, GstSourceGroup * group,
4374     gboolean locked)
4375 {
4376   GST_DEBUG_OBJECT (playbin, "locked_state %d on group %p", locked, group);
4377
4378   if (group->uridecodebin)
4379     gst_element_set_locked_state (group->uridecodebin, locked);
4380
4381   return TRUE;
4382 }
4383
4384 static gboolean
4385 make_or_reuse_element (GstPlayBin3 * playbin, const gchar * name,
4386     GstElement ** elem)
4387 {
4388   if (*elem) {
4389     GST_DEBUG_OBJECT (playbin, "reusing existing %s", name);
4390     gst_element_set_state (*elem, GST_STATE_READY);
4391     /* no need to take extra ref, we already have one
4392      * and the bin will add one since it is no longer floating,
4393      * as we added a non-floating ref when removing it from the
4394      * bin earlier */
4395   } else {
4396     GstElement *new_elem;
4397     GST_DEBUG_OBJECT (playbin, "making new %s", name);
4398     new_elem = gst_element_factory_make (name, NULL);
4399     if (!new_elem)
4400       return FALSE;
4401     *elem = gst_object_ref (new_elem);
4402   }
4403
4404   if (GST_OBJECT_PARENT (*elem) != GST_OBJECT_CAST (playbin))
4405     gst_bin_add (GST_BIN_CAST (playbin), *elem);
4406   return TRUE;
4407 }
4408
4409
4410 static void
4411 source_setup_cb (GstElement * element, GstElement * source,
4412     GstSourceGroup * group)
4413 {
4414   g_signal_emit (group->playbin, gst_play_bin3_signals[SIGNAL_SOURCE_SETUP], 0,
4415       source);
4416 }
4417
4418 /* must be called with PLAY_BIN_LOCK */
4419 static GstStateChangeReturn
4420 activate_group (GstPlayBin3 * playbin, GstSourceGroup * group)
4421 {
4422   GstElement *uridecodebin = NULL;
4423   GstPlayFlags flags;
4424   gboolean audio_sink_activated = FALSE;
4425   gboolean video_sink_activated = FALSE;
4426   gboolean text_sink_activated = FALSE;
4427   GstStateChangeReturn state_ret;
4428
4429   g_return_val_if_fail (group->valid, GST_STATE_CHANGE_FAILURE);
4430   g_return_val_if_fail (!group->active, GST_STATE_CHANGE_FAILURE);
4431
4432   GST_DEBUG_OBJECT (playbin, "activating group %p", group);
4433
4434   GST_SOURCE_GROUP_LOCK (group);
4435
4436   /* First set up the custom sinks */
4437   if (playbin->audio_sink)
4438     group->audio_sink = gst_object_ref (playbin->audio_sink);
4439   else
4440     group->audio_sink =
4441         gst_play_sink_get_sink (playbin->playsink, GST_PLAY_SINK_TYPE_AUDIO);
4442
4443   if (group->audio_sink) {
4444     if (!activate_sink (playbin, group->audio_sink, &audio_sink_activated)) {
4445       if (group->audio_sink == playbin->audio_sink) {
4446         goto sink_failure;
4447       } else {
4448         gst_object_unref (group->audio_sink);
4449         group->audio_sink = NULL;
4450       }
4451     }
4452   }
4453
4454   if (playbin->video_sink)
4455     group->video_sink = gst_object_ref (playbin->video_sink);
4456   else
4457     group->video_sink =
4458         gst_play_sink_get_sink (playbin->playsink, GST_PLAY_SINK_TYPE_VIDEO);
4459
4460   if (group->video_sink) {
4461     if (!activate_sink (playbin, group->video_sink, &video_sink_activated)) {
4462       if (group->video_sink == playbin->video_sink) {
4463         goto sink_failure;
4464       } else {
4465         gst_object_unref (group->video_sink);
4466         group->video_sink = NULL;
4467       }
4468     }
4469   }
4470
4471   if (playbin->text_sink)
4472     group->text_sink = gst_object_ref (playbin->text_sink);
4473   else
4474     group->text_sink =
4475         gst_play_sink_get_sink (playbin->playsink, GST_PLAY_SINK_TYPE_TEXT);
4476
4477   if (group->text_sink) {
4478     if (!activate_sink (playbin, group->text_sink, &text_sink_activated)) {
4479       if (group->text_sink == playbin->text_sink) {
4480         goto sink_failure;
4481       } else {
4482         gst_object_unref (group->text_sink);
4483         group->text_sink = NULL;
4484       }
4485     }
4486   }
4487
4488
4489   if (!make_or_reuse_element (playbin, "uridecodebin3", &group->uridecodebin))
4490     goto no_uridecodebin;
4491   uridecodebin = group->uridecodebin;
4492
4493   flags = gst_play_sink_get_flags (playbin->playsink);
4494
4495   g_object_set (uridecodebin,
4496       /* configure connection speed */
4497       "connection-speed", playbin->connection_speed / 1000,
4498       /* configure uri */
4499       "uri", group->uri,
4500       /* configure download buffering */
4501       "download", ((flags & GST_PLAY_FLAG_DOWNLOAD) != 0),
4502       /* configure buffering of demuxed/parsed data */
4503       "use-buffering", ((flags & GST_PLAY_FLAG_BUFFERING) != 0),
4504       /* configure buffering parameters */
4505       "buffer-duration", playbin->buffer_duration,
4506       "buffer-size", playbin->buffer_size,
4507       "ring-buffer-max-size", playbin->ring_buffer_max_size, NULL);
4508
4509   group->pad_added_id = g_signal_connect (uridecodebin, "pad-added",
4510       G_CALLBACK (pad_added_cb), group);
4511   group->pad_removed_id = g_signal_connect (uridecodebin,
4512       "pad-removed", G_CALLBACK (pad_removed_cb), group);
4513   group->select_stream_id = g_signal_connect (uridecodebin, "select-stream",
4514       G_CALLBACK (select_stream_cb), group);
4515   group->source_setup_id = g_signal_connect (uridecodebin, "source-setup",
4516       G_CALLBACK (source_setup_cb), group);
4517   group->about_to_finish_id =
4518       g_signal_connect (uridecodebin, "about-to-finish",
4519       G_CALLBACK (about_to_finish_cb), group);
4520
4521   if (group->suburi)
4522     g_object_set (group->uridecodebin, "suburi", group->suburi, NULL);
4523
4524   /* release the group lock before setting the state of the source bins, they
4525    * might fire signals in this thread that we need to handle with the
4526    * group_lock taken. */
4527   GST_SOURCE_GROUP_UNLOCK (group);
4528
4529   if ((state_ret =
4530           gst_element_set_state (uridecodebin,
4531               GST_STATE_PAUSED)) == GST_STATE_CHANGE_FAILURE)
4532     goto uridecodebin_failure;
4533
4534   GST_SOURCE_GROUP_LOCK (group);
4535   /* allow state changes of the playbin affect the group elements now */
4536   group_set_locked_state_unlocked (playbin, group, FALSE);
4537   group->active = TRUE;
4538   GST_SOURCE_GROUP_UNLOCK (group);
4539
4540   return state_ret;
4541
4542   /* ERRORS */
4543 no_uridecodebin:
4544   {
4545     GstMessage *msg;
4546
4547     GST_SOURCE_GROUP_UNLOCK (group);
4548     msg =
4549         gst_missing_element_message_new (GST_ELEMENT_CAST (playbin),
4550         "uridecodebin3");
4551     gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
4552
4553     GST_ELEMENT_ERROR (playbin, CORE, MISSING_PLUGIN,
4554         (_("Could not create \"uridecodebin3\" element.")), (NULL));
4555
4556     GST_SOURCE_GROUP_LOCK (group);
4557
4558     goto error_cleanup;
4559   }
4560 uridecodebin_failure:
4561   {
4562     GST_DEBUG_OBJECT (playbin, "failed state change of uridecodebin");
4563     GST_SOURCE_GROUP_LOCK (group);
4564     goto error_cleanup;
4565   }
4566 sink_failure:
4567   {
4568     GST_ERROR_OBJECT (playbin, "failed to activate sinks");
4569     goto error_cleanup;
4570   }
4571
4572 error_cleanup:
4573   {
4574     group->selected_stream_types = 0;
4575
4576     /* delete any custom sinks we might have */
4577     if (group->audio_sink) {
4578       /* If this is a automatically created sink set it to NULL */
4579       if (audio_sink_activated)
4580         gst_element_set_state (group->audio_sink, GST_STATE_NULL);
4581       gst_object_unref (group->audio_sink);
4582     }
4583     group->audio_sink = NULL;
4584
4585     if (group->video_sink) {
4586       /* If this is a automatically created sink set it to NULL */
4587       if (video_sink_activated)
4588         gst_element_set_state (group->video_sink, GST_STATE_NULL);
4589       gst_object_unref (group->video_sink);
4590     }
4591     group->video_sink = NULL;
4592
4593     if (group->text_sink) {
4594       /* If this is a automatically created sink set it to NULL */
4595       if (text_sink_activated)
4596         gst_element_set_state (group->text_sink, GST_STATE_NULL);
4597       gst_object_unref (group->text_sink);
4598     }
4599     group->text_sink = NULL;
4600
4601     if (uridecodebin) {
4602       REMOVE_SIGNAL (group->uridecodebin, group->pad_added_id);
4603       REMOVE_SIGNAL (group->uridecodebin, group->pad_removed_id);
4604       REMOVE_SIGNAL (group->uridecodebin, group->select_stream_id);
4605       REMOVE_SIGNAL (group->uridecodebin, group->source_setup_id);
4606       REMOVE_SIGNAL (group->uridecodebin, group->about_to_finish_id);
4607 #if 0
4608       REMOVE_SIGNAL (group->urisourcebin, group->autoplug_factories_id);
4609       REMOVE_SIGNAL (group->urisourcebin, group->autoplug_select_id);
4610       REMOVE_SIGNAL (group->urisourcebin, group->autoplug_continue_id);
4611       REMOVE_SIGNAL (group->urisourcebin, group->autoplug_query_id);
4612 #endif
4613
4614       gst_element_set_state (uridecodebin, GST_STATE_NULL);
4615       gst_bin_remove (GST_BIN_CAST (playbin), uridecodebin);
4616     }
4617
4618     GST_SOURCE_GROUP_UNLOCK (group);
4619
4620     return GST_STATE_CHANGE_FAILURE;
4621   }
4622 }
4623
4624 /* must be called with PLAY_BIN_LOCK */
4625 static gboolean
4626 deactivate_group (GstPlayBin3 * playbin, GstSourceGroup * group)
4627 {
4628   g_return_val_if_fail (group->active, FALSE);
4629   g_return_val_if_fail (group->valid, FALSE);
4630
4631   GST_DEBUG_OBJECT (playbin, "unlinking group %p", group);
4632
4633   GST_SOURCE_GROUP_LOCK (group);
4634   group->active = FALSE;
4635   group->playing = FALSE;
4636   group->group_id = GST_GROUP_ID_INVALID;
4637
4638   group->selected_stream_types = 0;
4639   /* Update global selected_stream_types */
4640   playbin->selected_stream_types =
4641       playbin->groups[0].selected_stream_types | playbin->
4642       groups[1].selected_stream_types;
4643   if (playbin->active_stream_types != playbin->selected_stream_types)
4644     reconfigure_output (playbin);
4645
4646 #if 0
4647   /* delete any custom sinks we might have.
4648    * conditionally set them to null if they aren't inside playsink yet */
4649   if (group->audio_sink) {
4650     if (!gst_object_has_as_ancestor (GST_OBJECT_CAST (group->audio_sink),
4651             GST_OBJECT_CAST (playbin->playsink))) {
4652       gst_element_set_state (group->audio_sink, GST_STATE_NULL);
4653     }
4654     gst_object_unref (group->audio_sink);
4655   }
4656   group->audio_sink = NULL;
4657   if (group->video_sink) {
4658     if (!gst_object_has_as_ancestor (GST_OBJECT_CAST (group->video_sink),
4659             GST_OBJECT_CAST (playbin->playsink))) {
4660       gst_element_set_state (group->video_sink, GST_STATE_NULL);
4661     }
4662     gst_object_unref (group->video_sink);
4663   }
4664   group->video_sink = NULL;
4665   if (group->text_sink) {
4666     if (!gst_object_has_as_ancestor (GST_OBJECT_CAST (group->text_sink),
4667             GST_OBJECT_CAST (playbin->playsink))) {
4668       gst_element_set_state (group->text_sink, GST_STATE_NULL);
4669     }
4670     gst_object_unref (group->text_sink);
4671   }
4672   group->text_sink = NULL;
4673 #endif
4674
4675   if (group->uridecodebin) {
4676     REMOVE_SIGNAL (group->uridecodebin, group->select_stream_id);
4677     REMOVE_SIGNAL (group->uridecodebin, group->source_setup_id);
4678     REMOVE_SIGNAL (group->uridecodebin, group->about_to_finish_id);
4679
4680     gst_element_set_state (group->uridecodebin, GST_STATE_NULL);
4681     gst_bin_remove (GST_BIN_CAST (playbin), group->uridecodebin);
4682
4683     REMOVE_SIGNAL (group->uridecodebin, group->pad_added_id);
4684     REMOVE_SIGNAL (group->uridecodebin, group->pad_removed_id);
4685 #if 0
4686     REMOVE_SIGNAL (group->urisourcebin, group->autoplug_factories_id);
4687     REMOVE_SIGNAL (group->urisourcebin, group->autoplug_select_id);
4688     REMOVE_SIGNAL (group->urisourcebin, group->autoplug_continue_id);
4689     REMOVE_SIGNAL (group->urisourcebin, group->autoplug_query_id);
4690 #endif
4691   }
4692
4693   GST_SOURCE_GROUP_UNLOCK (group);
4694
4695   GST_DEBUG_OBJECT (playbin, "Done");
4696
4697   return TRUE;
4698 }
4699
4700 /* setup the next group to play, this assumes the next_group is valid and
4701  * configured. It swaps out the current_group and activates the valid
4702  * next_group. */
4703 static GstStateChangeReturn
4704 setup_next_source (GstPlayBin3 * playbin)
4705 {
4706   GstSourceGroup *new_group;
4707   GstStateChangeReturn state_ret;
4708
4709   GST_DEBUG_OBJECT (playbin, "setup next source");
4710
4711   debug_groups (playbin);
4712
4713   /* see if there is a next group */
4714   GST_PLAY_BIN3_LOCK (playbin);
4715   new_group = playbin->next_group;
4716   if (!new_group || !new_group->valid || new_group->active)
4717     goto no_next_group;
4718
4719   /* activate the new group */
4720   state_ret = activate_group (playbin, new_group);
4721   if (state_ret == GST_STATE_CHANGE_FAILURE)
4722     goto activate_failed;
4723
4724   GST_PLAY_BIN3_UNLOCK (playbin);
4725
4726   debug_groups (playbin);
4727
4728   return state_ret;
4729
4730   /* ERRORS */
4731 no_next_group:
4732   {
4733     GST_DEBUG_OBJECT (playbin, "no next group");
4734     GST_PLAY_BIN3_UNLOCK (playbin);
4735     return GST_STATE_CHANGE_FAILURE;
4736   }
4737 activate_failed:
4738   {
4739     new_group->stream_changed_pending = FALSE;
4740     GST_DEBUG_OBJECT (playbin, "activate failed");
4741     new_group->valid = FALSE;
4742     GST_PLAY_BIN3_UNLOCK (playbin);
4743     return GST_STATE_CHANGE_FAILURE;
4744   }
4745 }
4746
4747 /* The group that is currently playing is copied again to the
4748  * next_group so that it will start playing the next time.
4749  */
4750 static gboolean
4751 save_current_group (GstPlayBin3 * playbin)
4752 {
4753   GstSourceGroup *curr_group;
4754
4755   GST_DEBUG_OBJECT (playbin, "save current group");
4756
4757   /* see if there is a current group */
4758   GST_PLAY_BIN3_LOCK (playbin);
4759   curr_group = playbin->curr_group;
4760   if (curr_group && curr_group->valid && curr_group->active) {
4761     /* unlink our pads with the sink */
4762     deactivate_group (playbin, curr_group);
4763   }
4764   /* swap old and new */
4765   playbin->curr_group = playbin->next_group;
4766   playbin->next_group = curr_group;
4767   GST_PLAY_BIN3_UNLOCK (playbin);
4768
4769   return TRUE;
4770 }
4771
4772 /* clear the locked state from all groups. This function is called before a
4773  * state change to NULL is performed on them. */
4774 static gboolean
4775 groups_set_locked_state (GstPlayBin3 * playbin, gboolean locked)
4776 {
4777   GST_DEBUG_OBJECT (playbin, "setting locked state to %d on all groups",
4778       locked);
4779
4780   GST_PLAY_BIN3_LOCK (playbin);
4781   GST_SOURCE_GROUP_LOCK (playbin->curr_group);
4782   group_set_locked_state_unlocked (playbin, playbin->curr_group, locked);
4783   GST_SOURCE_GROUP_UNLOCK (playbin->curr_group);
4784   GST_SOURCE_GROUP_LOCK (playbin->next_group);
4785   group_set_locked_state_unlocked (playbin, playbin->next_group, locked);
4786   GST_SOURCE_GROUP_UNLOCK (playbin->next_group);
4787   GST_PLAY_BIN3_UNLOCK (playbin);
4788
4789   return TRUE;
4790 }
4791
4792 static void
4793 gst_play_bin3_check_group_status (GstPlayBin3 * playbin)
4794 {
4795   if (playbin->activation_task)
4796     gst_task_start (playbin->activation_task);
4797 }
4798
4799 static void
4800 gst_play_bin3_activation_thread (GstPlayBin3 * playbin)
4801 {
4802   GST_DEBUG_OBJECT (playbin, "starting");
4803
4804   debug_groups (playbin);
4805
4806   /* Check if next_group needs to be deactivated */
4807   GST_PLAY_BIN3_LOCK (playbin);
4808   if (playbin->next_group->active) {
4809     deactivate_group (playbin, playbin->next_group);
4810     playbin->next_group->valid = FALSE;
4811   }
4812
4813   /* Is there a pending about-to-finish to be emitted ? */
4814   GST_SOURCE_GROUP_LOCK (playbin->curr_group);
4815   if (playbin->curr_group->pending_about_to_finish) {
4816     GST_LOG_OBJECT (playbin, "Propagating about-to-finish");
4817     playbin->curr_group->pending_about_to_finish = FALSE;
4818     GST_SOURCE_GROUP_UNLOCK (playbin->curr_group);
4819     /* This will activate the next source afterwards */
4820     emit_about_to_finish (playbin);
4821   } else
4822     GST_SOURCE_GROUP_UNLOCK (playbin->curr_group);
4823
4824   GST_LOG_OBJECT (playbin, "Pausing task");
4825   if (playbin->activation_task)
4826     gst_task_pause (playbin->activation_task);
4827   GST_PLAY_BIN3_UNLOCK (playbin);
4828
4829   GST_DEBUG_OBJECT (playbin, "done");
4830   return;
4831 }
4832
4833 static gboolean
4834 gst_play_bin3_start (GstPlayBin3 * playbin)
4835 {
4836   GST_DEBUG_OBJECT (playbin, "starting");
4837
4838   GST_PLAY_BIN3_LOCK (playbin);
4839
4840   if (playbin->activation_task == NULL) {
4841     playbin->activation_task =
4842         gst_task_new ((GstTaskFunction) gst_play_bin3_activation_thread,
4843         playbin, NULL);
4844     if (playbin->activation_task == NULL)
4845       goto task_error;
4846     gst_task_set_lock (playbin->activation_task, &playbin->activation_lock);
4847   }
4848   GST_LOG_OBJECT (playbin, "clearing shutdown flag");
4849   g_atomic_int_set (&playbin->shutdown, 0);
4850   do_async_start (playbin);
4851
4852   GST_PLAY_BIN3_UNLOCK (playbin);
4853
4854   return TRUE;
4855
4856 task_error:
4857   {
4858     GST_PLAY_BIN3_UNLOCK (playbin);
4859     GST_ERROR_OBJECT (playbin, "Failed to create task");
4860     return FALSE;
4861   }
4862 }
4863
4864 static void
4865 gst_play_bin3_stop (GstPlayBin3 * playbin)
4866 {
4867   GstTask *task;
4868
4869   GST_DEBUG_OBJECT (playbin, "stopping");
4870
4871   /* FIXME unlock our waiting groups */
4872   GST_LOG_OBJECT (playbin, "setting shutdown flag");
4873   g_atomic_int_set (&playbin->shutdown, 1);
4874
4875   /* wait for all callbacks to end by taking the lock.
4876    * No dynamic (critical) new callbacks will
4877    * be able to happen as we set the shutdown flag. */
4878   GST_PLAY_BIN3_DYN_LOCK (playbin);
4879   GST_LOG_OBJECT (playbin, "dynamic lock taken, we can continue shutdown");
4880   GST_PLAY_BIN3_DYN_UNLOCK (playbin);
4881
4882   /* Stop the activation task */
4883   GST_PLAY_BIN3_LOCK (playbin);
4884   if ((task = playbin->activation_task)) {
4885     playbin->activation_task = NULL;
4886     GST_PLAY_BIN3_UNLOCK (playbin);
4887
4888     gst_task_stop (task);
4889
4890     /* Make sure task is not running */
4891     g_rec_mutex_lock (&playbin->activation_lock);
4892     g_rec_mutex_unlock (&playbin->activation_lock);
4893
4894     /* Wait for task to finish and unref it */
4895     gst_task_join (task);
4896     gst_object_unref (task);
4897
4898     GST_PLAY_BIN3_LOCK (playbin);
4899   }
4900   GST_PLAY_BIN3_UNLOCK (playbin);
4901 }
4902
4903 static GstStateChangeReturn
4904 gst_play_bin3_change_state (GstElement * element, GstStateChange transition)
4905 {
4906   GstStateChangeReturn ret;
4907   GstPlayBin3 *playbin;
4908   gboolean do_save = FALSE;
4909
4910   playbin = GST_PLAY_BIN3 (element);
4911
4912   switch (transition) {
4913     case GST_STATE_CHANGE_READY_TO_PAUSED:
4914       if (!gst_play_bin3_start (playbin))
4915         return GST_STATE_CHANGE_FAILURE;
4916       break;
4917     case GST_STATE_CHANGE_PAUSED_TO_READY:
4918     async_down:
4919       gst_play_bin3_stop (playbin);
4920       if (!do_save)
4921         break;
4922     case GST_STATE_CHANGE_READY_TO_NULL:
4923       /* we go async to PAUSED, so if that fails, we never make it to PAUSED
4924        * and we will never be called with the GST_STATE_CHANGE_PAUSED_TO_READY.
4925        * Make sure we do go through the same steps (see above) for
4926        * proper cleanup */
4927       if (!g_atomic_int_get (&playbin->shutdown)) {
4928         do_save = TRUE;
4929         goto async_down;
4930       }
4931
4932       /* unlock so that all groups go to NULL */
4933       groups_set_locked_state (playbin, FALSE);
4934       break;
4935     default:
4936       break;
4937   }
4938
4939   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4940   if (ret == GST_STATE_CHANGE_FAILURE)
4941     goto failure;
4942
4943   switch (transition) {
4944     case GST_STATE_CHANGE_READY_TO_PAUSED:
4945       if ((ret = setup_next_source (playbin)) == GST_STATE_CHANGE_FAILURE)
4946         goto failure;
4947       if (ret == GST_STATE_CHANGE_SUCCESS)
4948         ret = GST_STATE_CHANGE_ASYNC;
4949
4950       break;
4951     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4952       do_async_done (playbin);
4953       /* FIXME Release audio device when we implement that */
4954       break;
4955     case GST_STATE_CHANGE_PAUSED_TO_READY:
4956       save_current_group (playbin);
4957       break;
4958     case GST_STATE_CHANGE_READY_TO_NULL:
4959     {
4960       guint i;
4961
4962       /* also do missed state change down to READY */
4963       if (do_save)
4964         save_current_group (playbin);
4965       /* Deactivate the groups, set uridecodebin to NULL and unref it */
4966       for (i = 0; i < 2; i++) {
4967         if (playbin->groups[i].active && playbin->groups[i].valid) {
4968           deactivate_group (playbin, &playbin->groups[i]);
4969           playbin->groups[i].valid = FALSE;
4970         }
4971
4972         if (playbin->groups[i].uridecodebin) {
4973           gst_element_set_state (playbin->groups[i].uridecodebin,
4974               GST_STATE_NULL);
4975           gst_object_unref (playbin->groups[i].uridecodebin);
4976           playbin->groups[i].uridecodebin = NULL;
4977         }
4978
4979       }
4980
4981       /* Set our sinks back to NULL, they might not be child of playbin */
4982       if (playbin->audio_sink)
4983         gst_element_set_state (playbin->audio_sink, GST_STATE_NULL);
4984       if (playbin->video_sink)
4985         gst_element_set_state (playbin->video_sink, GST_STATE_NULL);
4986       if (playbin->text_sink)
4987         gst_element_set_state (playbin->text_sink, GST_STATE_NULL);
4988
4989       if (playbin->video_stream_combiner)
4990         gst_element_set_state (playbin->video_stream_combiner, GST_STATE_NULL);
4991       if (playbin->audio_stream_combiner)
4992         gst_element_set_state (playbin->audio_stream_combiner, GST_STATE_NULL);
4993       if (playbin->text_stream_combiner)
4994         gst_element_set_state (playbin->text_stream_combiner, GST_STATE_NULL);
4995
4996       /* make sure the groups don't perform a state change anymore until we
4997        * enable them again */
4998       groups_set_locked_state (playbin, TRUE);
4999       break;
5000     }
5001     default:
5002       break;
5003   }
5004
5005   if (ret == GST_STATE_CHANGE_NO_PREROLL)
5006     do_async_done (playbin);
5007
5008   return ret;
5009
5010   /* ERRORS */
5011 failure:
5012   {
5013     do_async_done (playbin);
5014
5015     if (transition == GST_STATE_CHANGE_READY_TO_PAUSED) {
5016       GstSourceGroup *curr_group;
5017
5018       curr_group = playbin->curr_group;
5019       if (curr_group) {
5020         if (curr_group->active && curr_group->valid) {
5021           /* unlink our pads with the sink */
5022           deactivate_group (playbin, curr_group);
5023         }
5024         curr_group->valid = FALSE;
5025       }
5026
5027       /* Swap current and next group back */
5028       playbin->curr_group = playbin->next_group;
5029       playbin->next_group = curr_group;
5030     }
5031     return ret;
5032   }
5033 }
5034
5035 static void
5036 gst_play_bin3_overlay_expose (GstVideoOverlay * overlay)
5037 {
5038   GstPlayBin3 *playbin = GST_PLAY_BIN3 (overlay);
5039
5040   gst_video_overlay_expose (GST_VIDEO_OVERLAY (playbin->playsink));
5041 }
5042
5043 static void
5044 gst_play_bin3_overlay_handle_events (GstVideoOverlay * overlay,
5045     gboolean handle_events)
5046 {
5047   GstPlayBin3 *playbin = GST_PLAY_BIN3 (overlay);
5048
5049   gst_video_overlay_handle_events (GST_VIDEO_OVERLAY (playbin->playsink),
5050       handle_events);
5051 }
5052
5053 static void
5054 gst_play_bin3_overlay_set_render_rectangle (GstVideoOverlay * overlay, gint x,
5055     gint y, gint width, gint height)
5056 {
5057   GstPlayBin3 *playbin = GST_PLAY_BIN3 (overlay);
5058
5059   gst_video_overlay_set_render_rectangle (GST_VIDEO_OVERLAY (playbin->playsink),
5060       x, y, width, height);
5061 }
5062
5063 static void
5064 gst_play_bin3_overlay_set_window_handle (GstVideoOverlay * overlay,
5065     guintptr handle)
5066 {
5067   GstPlayBin3 *playbin = GST_PLAY_BIN3 (overlay);
5068
5069   gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (playbin->playsink),
5070       handle);
5071 }
5072
5073 static void
5074 gst_play_bin3_overlay_init (gpointer g_iface, gpointer g_iface_data)
5075 {
5076   GstVideoOverlayInterface *iface = (GstVideoOverlayInterface *) g_iface;
5077   iface->expose = gst_play_bin3_overlay_expose;
5078   iface->handle_events = gst_play_bin3_overlay_handle_events;
5079   iface->set_render_rectangle = gst_play_bin3_overlay_set_render_rectangle;
5080   iface->set_window_handle = gst_play_bin3_overlay_set_window_handle;
5081 }
5082
5083 static void
5084 gst_play_bin3_navigation_send_event (GstNavigation * navigation,
5085     GstStructure * structure)
5086 {
5087   GstPlayBin3 *playbin = GST_PLAY_BIN3 (navigation);
5088
5089   gst_navigation_send_event (GST_NAVIGATION (playbin->playsink), structure);
5090 }
5091
5092 static void
5093 gst_play_bin3_navigation_init (gpointer g_iface, gpointer g_iface_data)
5094 {
5095   GstNavigationInterface *iface = (GstNavigationInterface *) g_iface;
5096
5097   iface->send_event = gst_play_bin3_navigation_send_event;
5098 }
5099
5100 static const GList *
5101 gst_play_bin3_colorbalance_list_channels (GstColorBalance * balance)
5102 {
5103   GstPlayBin3 *playbin = GST_PLAY_BIN3 (balance);
5104
5105   return
5106       gst_color_balance_list_channels (GST_COLOR_BALANCE (playbin->playsink));
5107 }
5108
5109 static void
5110 gst_play_bin3_colorbalance_set_value (GstColorBalance * balance,
5111     GstColorBalanceChannel * channel, gint value)
5112 {
5113   GstPlayBin3 *playbin = GST_PLAY_BIN3 (balance);
5114
5115   gst_color_balance_set_value (GST_COLOR_BALANCE (playbin->playsink), channel,
5116       value);
5117 }
5118
5119 static gint
5120 gst_play_bin3_colorbalance_get_value (GstColorBalance * balance,
5121     GstColorBalanceChannel * channel)
5122 {
5123   GstPlayBin3 *playbin = GST_PLAY_BIN3 (balance);
5124
5125   return gst_color_balance_get_value (GST_COLOR_BALANCE (playbin->playsink),
5126       channel);
5127 }
5128
5129 static GstColorBalanceType
5130 gst_play_bin3_colorbalance_get_balance_type (GstColorBalance * balance)
5131 {
5132   GstPlayBin3 *playbin = GST_PLAY_BIN3 (balance);
5133
5134   return
5135       gst_color_balance_get_balance_type (GST_COLOR_BALANCE
5136       (playbin->playsink));
5137 }
5138
5139 static void
5140 gst_play_bin3_colorbalance_init (gpointer g_iface, gpointer g_iface_data)
5141 {
5142   GstColorBalanceInterface *iface = (GstColorBalanceInterface *) g_iface;
5143
5144   iface->list_channels = gst_play_bin3_colorbalance_list_channels;
5145   iface->set_value = gst_play_bin3_colorbalance_set_value;
5146   iface->get_value = gst_play_bin3_colorbalance_get_value;
5147   iface->get_balance_type = gst_play_bin3_colorbalance_get_balance_type;
5148 }
5149
5150 gboolean
5151 gst_play_bin3_custom_element_init (GstPlugin * plugin)
5152 {
5153   gboolean ret = TRUE;
5154
5155   GST_DEBUG_CATEGORY_INIT (gst_play_bin3_debug, "playbin3", 0, "play bin3");
5156
5157   playback_element_init (plugin);
5158
5159   if (g_getenv ("USE_PLAYBIN3"))
5160     ret &= gst_element_register (plugin, "playbin", GST_RANK_NONE,
5161         GST_TYPE_PLAY_BIN);
5162   else
5163     ret &= gst_element_register (plugin, "playbin3", GST_RANK_NONE,
5164         GST_TYPE_PLAY_BIN);
5165
5166   return ret;
5167 }