gst/playback/gstdecodebin.c: Make the window for a race in typefind and shutting...
[platform/upstream/gstreamer.git] / gst / playback / gstplaybin.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-playbin
22  *
23  * <refsect2>
24  * <para>
25  * Playbin provides a stand-alone everything-in-one abstraction for an
26  * audio and/or video player.
27  * </para>
28  * <para>
29  * It can handle both audio and video files and features
30  * <itemizedlist>
31  * <listitem>
32  * automatic file type recognition and based on that automatic
33  * selection and usage of the right audio/video/subtitle demuxers/decoders
34  * </listitem>
35  * <listitem>
36  * visualisations for audio files
37  * </listitem>
38  * <listitem>
39  * subtitle support for video files
40  * </listitem>
41  * <listitem>
42  * stream selection between different audio/subtitles streams
43  * </listitem>
44  * <listitem>
45  * meta info (tag) extraction
46  * </listitem>
47  * <listitem>
48  * easy access to the last video frame
49  * </listitem>
50  * <listitem>
51  * buffering when playing streams over a network
52  * </listitem>
53  * <listitem>
54  * volume control
55  * </listitem>
56  * </itemizedlist>
57  * </para>
58  * <title>Usage</title>
59  * <para>
60  * A playbin element can be created just like any other element using
61  * gst_element_factory_make(). The file/URI to play should be set via the "uri"
62  * property. This must be an absolute URI, relative file paths are not allowed.
63  * Example URIs are file:///home/joe/movie.avi or http://www.joedoe.com/foo.ogg
64  * </para>
65  * <para>
66  * Playbin is a #GstPipeline. It will notify the application of everything
67  * that's happening (errors, end of stream, tags found, state changes, etc.)
68  * by posting messages on its #GstBus. The application needs to watch the
69  * bus.
70  * </para>
71  * <para>
72  * Playback can be initiated by setting the element to PLAYING state using
73  * gst_element_set_state(). Note that the state change will take place in
74  * the background in a separate thread, when the function returns playback
75  * is probably not happening yet and any errors might not have occured yet.
76  * Applications using playbin should ideally be written to deal with things
77  * completely asynchroneous.
78  * </para>
79  * <para>
80  * When playback has finished (an EOS message has been received on the bus)
81  * or an error has occured (an ERROR message has been received on the bus) or
82  * the user wants to play a different track, playbin should be set back to
83  * READY or NULL state, then the "uri" property should be set to the new
84  * location and then playbin be set to PLAYING state again.
85  * </para>
86  * <para>
87  * Seeking can be done using gst_element_seek_simple() or gst_element_seek()
88  * on the playbin element. Again, the seek will not be executed
89  * instantaneously, but will be done in a background thread. When the seek
90  * call returns the seek will most likely still be in process. An application
91  * may wait for the seek to finish (or fail) using gst_element_get_state() with
92  * -1 as the timeout, but this will block the user interface and is not
93  * recommended at all.
94  * </para>
95  * <para>
96  * Applications may query the current position and duration of the stream
97  * via gst_element_query_position() and gst_element_query_duration() and
98  * setting the format passed to GST_FORMAT_TIME. If the query was successful,
99  * the duration or position will have been returned in units of nanoseconds.
100  * </para>
101  * <title>Advanced Usage: specifying the audio and video sink</title>
102  * <para>
103  * By default, if no audio sink or video sink has been specified via the
104  * "audio-sink" or "video-sink" property, playbin 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  * </para>
110  * <para>
111  * If the application wants more control over how audio or video should be
112  * output, it may create the audio/video sink elements itself (for example
113  * using gst_element_factory_make()) and provide them to playbin using the
114  * "audio-sink" or "video-sink" property.
115  * </para>
116  * <para>
117  * GNOME-based applications, for example, will usually want to create
118  * gconfaudiosink and gconfvideosink elements and make playbin use those,
119  * so that output happens to whatever the user has configured in the GNOME
120  * Multimedia System Selector confinguration dialog.
121  * </para>
122  * <para>
123  * The sink elements do not necessarily need to be ready-made sinks. It is
124  * possible to create container elements that look like a sink to playbin,
125  * but in reality contain a number of custom elements linked together. This
126  * can be achieved by creating a #GstBin and putting elements in there and
127  * linking them, and then creating a sink #GstGhostPad for the bin and pointing
128  * it to the sink pad of the first element within the bin. This can be used
129  * for a number of purposes, for example to force output to a particular
130  * format or to modify or observe the data before it is output.
131  * </para>
132  * <para>
133  * It is also possible to 'suppress' audio and/or video output by using
134  * 'fakesink' elements (or capture it from there using the fakesink element's
135  * "handoff" signal, which, nota bene, is fired from the streaming thread!).
136  * </para>
137  * <title>Retrieving Tags and Other Meta Data</title>
138  * <para>
139  * Most of the common meta data (artist, title, etc.) can be retrieved by
140  * watching for TAG messages on the pipeline's bus (see above).
141  * </para>
142  * <para>
143  * Other more specific meta information like width/height/framerate of video
144  * streams or samplerate/number of channels of audio streams can be obtained
145  * using the "stream-info" property, which will return a GList of stream info
146  * objects, one for each stream. These are opaque objects that can only be
147  * accessed via the standard GObject property interface, ie. g_object_get().
148  * Each stream info object has the following properties:
149  * <itemizedlist>
150  * <listitem>"object" (GstObject) (the decoder source pad usually)</listitem>
151  * <listitem>"type" (enum) (if this is an audio/video/subtitle stream)</listitem>
152  * <listitem>"decoder" (string) (name of decoder used to decode this stream)</listitem>
153  * <listitem>"mute" (boolean) (to mute or unmute this stream)</listitem>
154  * <listitem>"caps" (GstCaps) (caps of the decoded stream)</listitem>
155  * <listitem>"language-code" (string) (ISO-639 language code for this stream, mostly used for audio/subtitle streams)</listitem>
156  * <listitem>"codec" (string) (format this stream was encoded in)</listitem>
157  * </itemizedlist>
158  * Stream information from the stream-info properties is best queried once
159  * playbin has changed into PAUSED or PLAYING state (which can be detected
160  * via a state-changed message on the bus where old_state=READY and
161  * new_state=PAUSED), since before that the list might not be complete yet or
162  * not contain all available information (like language-codes).
163  * </para>
164  * <title>Buffering</title>
165  * <para>
166  * Playbin handles buffering automatically for the most part, but applications
167  * need to handle parts of the buffering process as well. Whenever playbin is
168  * buffering, it will post BUFFERING messages on the bus with a percentage
169  * value that shows the progress of the buffering process. Applications need
170  * to set playbin to PLAYING or PAUSED state in response to these messages.
171  * They may also want to convey the buffering progress to the user in some
172  * way. Here is how to extract the percentage information from the message
173  * (requires GStreamer >= 0.10.11):
174  * </para>
175  * <para>
176  * <programlisting>
177  * switch (GST_MESSAGE_TYPE (msg)) {
178  *   case GST_MESSAGE_BUFFERING: {
179  *     gint percent = 0;
180  *     gst_message_parse_buffering (msg, &amp;percent);
181  *     g_print ("Buffering (%%u percent done)", percent);
182  *     break;
183  *   }
184  *   ...
185  * }
186  * </programlisting>
187  * Note that applications should keep/set the pipeline in the PAUSED state when
188  * a BUFFERING message is received with a buffer percent value < 100 and set
189  * the pipeline back to PLAYING state when a BUFFERING message with a value
190  * of 100 percent is received (if PLAYING is the desired state, that is).
191  * </para>
192  * <title>Embedding the video window in your application</title>
193  * <para>
194  * By default, playbin (or rather the video sinks used) will create their own
195  * window. Applications will usually want to force output to a window of their
196  * own, however. This can be done using the GstXOverlay interface, which most
197  * video sinks implement. See the documentation there for more details.
198  * </para>
199  * <title>Specifying which CD/DVD device to use</title>
200  * <para>
201  * The device to use for CDs/DVDs needs to be set on the source element
202  * playbin creates before it is opened. The only way to do this at the moment
203  * is to connect to playbin's "notify::source" signal, which will be emitted
204  * by playbin when it has created the source element for a particular URI.
205  * In the signal callback you can check if the source element has a "device"
206  * property and set it appropriately. In future ways might be added to specify
207  * the device as part of the URI, but at the time of writing this is not
208  * possible yet.
209  * </para>
210  * <title>Examples</title>
211  * <para>
212  * Here is a simple pipeline to play back a video or audio file:
213  * <programlisting>
214  * gst-launch -v playbin uri=file:///path/to/somefile.avi
215  * </programlisting>
216  * This will play back the given AVI video file, given that the video and
217  * audio decoders required to decode the content are installed. Since no
218  * special audio sink or video sink is supplied (not possible via gst-launch),
219  * playbin will try to find a suitable audio and video sink automatically
220  * using the autoaudiosink and autovideosink elements.
221  * </para>
222  * <para>
223  * Here is a another pipeline to play track 4 of an audio CD:
224  * <programlisting>
225  * gst-launch -v playbin uri=cdda://4
226  * </programlisting>
227  * This will play back track 4 on an audio CD in your disc drive (assuming
228  * the drive is detected automatically by the plugin).
229  * </para>
230  * <para>
231  * Here is a another pipeline to play title 1 of a DVD:
232  * <programlisting>
233  * gst-launch -v playbin uri=dvd://1
234  * </programlisting>
235  * This will play back title 1 of a DVD in your disc drive (assuming
236  * the drive is detected automatically by the plugin).
237  * </para>
238  * </refsect2>
239  */
240
241 #ifdef HAVE_CONFIG_H
242 #include "config.h"
243 #endif
244
245 #include <string.h>
246 #include <gst/gst.h>
247
248 #include <gst/gst-i18n-plugin.h>
249 #include <gst/pbutils/pbutils.h>
250
251 #include "gstplaybasebin.h"
252
253 GST_DEBUG_CATEGORY_STATIC (gst_play_bin_debug);
254 #define GST_CAT_DEFAULT gst_play_bin_debug
255
256 #define GST_TYPE_PLAY_BIN               (gst_play_bin_get_type())
257 #define GST_PLAY_BIN(obj)               (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PLAY_BIN,GstPlayBin))
258 #define GST_PLAY_BIN_CLASS(klass)       (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PLAY_BIN,GstPlayBinClass))
259 #define GST_IS_PLAY_BIN(obj)            (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PLAY_BIN))
260 #define GST_IS_PLAY_BIN_CLASS(klass)    (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PLAY_BIN))
261
262 #define VOLUME_MAX_DOUBLE 10.0
263
264 typedef struct _GstPlayBin GstPlayBin;
265 typedef struct _GstPlayBinClass GstPlayBinClass;
266
267 struct _GstPlayBin
268 {
269   GstPlayBaseBin parent;
270
271   /* the configurable elements */
272   GstElement *fakesink;
273   GstElement *audio_sink;
274   GstElement *video_sink;
275   GstElement *visualisation;
276   GstElement *pending_visualisation;
277   GstElement *volume_element;
278   GstElement *textoverlay_element;
279   gfloat volume;
280
281   /* these are the currently active sinks */
282   GList *sinks;
283
284   /* the last captured frame for snapshots */
285   GstBuffer *frame;
286
287   /* our cache for the sinks */
288   GHashTable *cache;
289
290   /* font description */
291   gchar *font_desc;
292
293   /* indication if the pipeline is live */
294   gboolean is_live;
295 };
296
297 struct _GstPlayBinClass
298 {
299   GstPlayBaseBinClass parent_class;
300 };
301
302 /* props */
303 enum
304 {
305   ARG_0,
306   ARG_AUDIO_SINK,
307   ARG_VIDEO_SINK,
308   ARG_VIS_PLUGIN,
309   ARG_VOLUME,
310   ARG_FRAME,
311   ARG_FONT_DESC
312 };
313
314 /* signals */
315 enum
316 {
317   LAST_SIGNAL
318 };
319
320 static void gst_play_bin_class_init (GstPlayBinClass * klass);
321 static void gst_play_bin_init (GstPlayBin * play_bin);
322 static void gst_play_bin_dispose (GObject * object);
323
324 static gboolean setup_sinks (GstPlayBaseBin * play_base_bin,
325     GstPlayBaseGroup * group);
326 static void remove_sinks (GstPlayBin * play_bin);
327
328 static void gst_play_bin_set_property (GObject * object, guint prop_id,
329     const GValue * value, GParamSpec * spec);
330 static void gst_play_bin_get_property (GObject * object, guint prop_id,
331     GValue * value, GParamSpec * spec);
332
333 static gboolean gst_play_bin_send_event (GstElement * element,
334     GstEvent * event);
335 static GstStateChangeReturn gst_play_bin_change_state (GstElement * element,
336     GstStateChange transition);
337
338 static void gst_play_bin_handle_message (GstBin * bin, GstMessage * message);
339
340 static GstElementClass *parent_class;
341
342 //static guint gst_play_bin_signals[LAST_SIGNAL] = { 0 };
343
344 static const GstElementDetails gst_play_bin_details =
345 GST_ELEMENT_DETAILS ("Player Bin",
346     "Generic/Bin/Player",
347     "Autoplug and play media from an uri",
348     "Wim Taymans <wim@fluendo.com>");
349
350 static GType
351 gst_play_bin_get_type (void)
352 {
353   static GType gst_play_bin_type = 0;
354
355   if (!gst_play_bin_type) {
356     static const GTypeInfo gst_play_bin_info = {
357       sizeof (GstPlayBinClass),
358       NULL,
359       NULL,
360       (GClassInitFunc) gst_play_bin_class_init,
361       NULL,
362       NULL,
363       sizeof (GstPlayBin),
364       0,
365       (GInstanceInitFunc) gst_play_bin_init,
366       NULL
367     };
368
369     gst_play_bin_type = g_type_register_static (GST_TYPE_PLAY_BASE_BIN,
370         "GstPlayBin", &gst_play_bin_info, 0);
371   }
372
373   return gst_play_bin_type;
374 }
375
376 static void
377 gst_play_bin_class_init (GstPlayBinClass * klass)
378 {
379   GObjectClass *gobject_klass;
380   GstElementClass *gstelement_klass;
381   GstBinClass *gstbin_klass;
382   GstPlayBaseBinClass *playbasebin_klass;
383
384   gobject_klass = (GObjectClass *) klass;
385   gstelement_klass = (GstElementClass *) klass;
386   gstbin_klass = (GstBinClass *) klass;
387   playbasebin_klass = (GstPlayBaseBinClass *) klass;
388
389   parent_class = g_type_class_peek_parent (klass);
390
391   gobject_klass->set_property = gst_play_bin_set_property;
392   gobject_klass->get_property = gst_play_bin_get_property;
393
394   g_object_class_install_property (gobject_klass, ARG_VIDEO_SINK,
395       g_param_spec_object ("video-sink", "Video Sink",
396           "the video output element to use (NULL = default sink)",
397           GST_TYPE_ELEMENT, G_PARAM_READWRITE));
398   g_object_class_install_property (gobject_klass, ARG_AUDIO_SINK,
399       g_param_spec_object ("audio-sink", "Audio Sink",
400           "the audio output element to use (NULL = default sink)",
401           GST_TYPE_ELEMENT, G_PARAM_READWRITE));
402   g_object_class_install_property (gobject_klass, ARG_VIS_PLUGIN,
403       g_param_spec_object ("vis-plugin", "Vis plugin",
404           "the visualization element to use (NULL = none)",
405           GST_TYPE_ELEMENT, G_PARAM_READWRITE));
406   g_object_class_install_property (gobject_klass, ARG_VOLUME,
407       g_param_spec_double ("volume", "volume", "volume",
408           0.0, VOLUME_MAX_DOUBLE, 1.0, G_PARAM_READWRITE));
409   g_object_class_install_property (gobject_klass, ARG_FRAME,
410       gst_param_spec_mini_object ("frame", "Frame",
411           "The last frame (NULL = no video available)",
412           GST_TYPE_BUFFER, G_PARAM_READABLE));
413   g_object_class_install_property (gobject_klass, ARG_FONT_DESC,
414       g_param_spec_string ("subtitle-font-desc",
415           "Subtitle font description",
416           "Pango font description of font "
417           "to be used for subtitle rendering", NULL, G_PARAM_WRITABLE));
418
419   gobject_klass->dispose = GST_DEBUG_FUNCPTR (gst_play_bin_dispose);
420
421   gst_element_class_set_details (gstelement_klass, &gst_play_bin_details);
422
423   gstelement_klass->change_state =
424       GST_DEBUG_FUNCPTR (gst_play_bin_change_state);
425   gstelement_klass->send_event = GST_DEBUG_FUNCPTR (gst_play_bin_send_event);
426
427   gstbin_klass->handle_message =
428       GST_DEBUG_FUNCPTR (gst_play_bin_handle_message);
429
430   playbasebin_klass->setup_output_pads = setup_sinks;
431 }
432
433 static void
434 gst_play_bin_init (GstPlayBin * play_bin)
435 {
436   play_bin->video_sink = NULL;
437   play_bin->audio_sink = NULL;
438   play_bin->visualisation = NULL;
439   play_bin->pending_visualisation = NULL;
440   play_bin->volume_element = NULL;
441   play_bin->textoverlay_element = NULL;
442   play_bin->volume = 1.0;
443   play_bin->sinks = NULL;
444   play_bin->frame = NULL;
445   play_bin->font_desc = NULL;
446   play_bin->cache = g_hash_table_new_full (g_str_hash, g_str_equal,
447       NULL, (GDestroyNotify) gst_object_unref);
448 }
449
450 static void
451 gst_play_bin_dispose (GObject * object)
452 {
453   GstPlayBin *play_bin;
454
455   play_bin = GST_PLAY_BIN (object);
456
457   if (play_bin->cache != NULL) {
458     remove_sinks (play_bin);
459     g_hash_table_destroy (play_bin->cache);
460     play_bin->cache = NULL;
461   }
462
463   if (play_bin->audio_sink != NULL) {
464     gst_element_set_state (play_bin->audio_sink, GST_STATE_NULL);
465     gst_object_unref (play_bin->audio_sink);
466     play_bin->audio_sink = NULL;
467   }
468   if (play_bin->video_sink != NULL) {
469     gst_element_set_state (play_bin->video_sink, GST_STATE_NULL);
470     gst_object_unref (play_bin->video_sink);
471     play_bin->video_sink = NULL;
472   }
473   if (play_bin->visualisation != NULL) {
474     gst_element_set_state (play_bin->visualisation, GST_STATE_NULL);
475     gst_object_unref (play_bin->visualisation);
476     play_bin->visualisation = NULL;
477   }
478   if (play_bin->pending_visualisation != NULL) {
479     gst_element_set_state (play_bin->pending_visualisation, GST_STATE_NULL);
480     gst_object_unref (play_bin->pending_visualisation);
481     play_bin->pending_visualisation = NULL;
482   }
483   if (play_bin->textoverlay_element != NULL) {
484     gst_object_unref (play_bin->textoverlay_element);
485     play_bin->textoverlay_element = NULL;
486   }
487   g_free (play_bin->font_desc);
488   play_bin->font_desc = NULL;
489
490   G_OBJECT_CLASS (parent_class)->dispose (object);
491 }
492
493 static void
494 gst_play_bin_vis_unblocked (GstPad * tee_pad, gboolean blocked,
495     gpointer user_data)
496 {
497   GstPlayBin *play_bin = GST_PLAY_BIN (user_data);
498
499   if (play_bin->pending_visualisation)
500     gst_pad_set_blocked_async (tee_pad, FALSE, gst_play_bin_vis_unblocked,
501         play_bin);
502 }
503
504 static void
505 gst_play_bin_vis_blocked (GstPad * tee_pad, gboolean blocked,
506     gpointer user_data)
507 {
508   GstPlayBin *play_bin = GST_PLAY_BIN (user_data);
509   GstBin *vis_bin = NULL;
510   GstPad *vis_sink_pad = NULL, *vis_src_pad = NULL, *vqueue_pad = NULL;
511   GstState bin_state;
512   GstElement *pending_visualisation;
513
514   GST_OBJECT_LOCK (play_bin);
515   pending_visualisation = play_bin->pending_visualisation;
516   play_bin->pending_visualisation = NULL;
517   GST_OBJECT_UNLOCK (play_bin);
518
519   /* We want to disable visualisation */
520   if (!GST_IS_ELEMENT (pending_visualisation)) {
521     /* Set visualisation element to READY */
522     gst_element_set_state (play_bin->visualisation, GST_STATE_READY);
523     goto beach;
524   }
525
526   vis_bin =
527       GST_BIN_CAST (gst_object_get_parent (GST_OBJECT_CAST (play_bin->
528               visualisation)));
529
530   if (!GST_IS_BIN (vis_bin) || !GST_IS_PAD (tee_pad)) {
531     goto beach;
532   }
533
534   vis_src_pad = gst_element_get_pad (play_bin->visualisation, "src");
535   vis_sink_pad = gst_pad_get_peer (tee_pad);
536
537   /* Can be fakesink */
538   if (GST_IS_PAD (vis_src_pad)) {
539     vqueue_pad = gst_pad_get_peer (vis_src_pad);
540   }
541
542   if (!GST_IS_PAD (vis_sink_pad)) {
543     goto beach;
544   }
545
546   /* Check the bin's state */
547   GST_OBJECT_LOCK (vis_bin);
548   bin_state = GST_STATE (vis_bin);
549   GST_OBJECT_UNLOCK (vis_bin);
550
551   /* Unlink */
552   gst_pad_unlink (tee_pad, vis_sink_pad);
553   gst_object_unref (vis_sink_pad);
554   vis_sink_pad = NULL;
555
556   if (GST_IS_PAD (vqueue_pad)) {
557     gst_pad_unlink (vis_src_pad, vqueue_pad);
558     gst_object_unref (vis_src_pad);
559     vis_src_pad = NULL;
560   }
561
562   /* Remove from vis_bin */
563   gst_bin_remove (vis_bin, play_bin->visualisation);
564   /* Set state to NULL */
565   gst_element_set_state (play_bin->visualisation, GST_STATE_NULL);
566   /* And loose our ref */
567   gst_object_unref (play_bin->visualisation);
568
569   if (pending_visualisation) {
570     /* Ref this new visualisation element before adding to the bin */
571     gst_object_ref (pending_visualisation);
572     /* Add the new one */
573     gst_bin_add (vis_bin, pending_visualisation);
574     /* Synchronizing state */
575     gst_element_set_state (pending_visualisation, bin_state);
576
577     vis_sink_pad = gst_element_get_pad (pending_visualisation, "sink");
578     vis_src_pad = gst_element_get_pad (pending_visualisation, "src");
579
580     if (!GST_IS_PAD (vis_sink_pad) || !GST_IS_PAD (vis_src_pad)) {
581       goto beach;
582     }
583
584     /* Link */
585     gst_pad_link (tee_pad, vis_sink_pad);
586     gst_pad_link (vis_src_pad, vqueue_pad);
587   }
588
589   /* We are done */
590   gst_object_unref (play_bin->visualisation);
591   play_bin->visualisation = pending_visualisation;
592
593 beach:
594   if (vis_sink_pad) {
595     gst_object_unref (vis_sink_pad);
596   }
597   if (vis_src_pad) {
598     gst_object_unref (vis_src_pad);
599   }
600   if (vqueue_pad) {
601     gst_object_unref (vqueue_pad);
602   }
603   if (vis_bin) {
604     gst_object_unref (vis_bin);
605   }
606
607   /* Unblock the pad */
608   gst_pad_set_blocked_async (tee_pad, FALSE, gst_play_bin_vis_unblocked,
609       play_bin);
610 }
611
612 static void
613 gst_play_bin_set_property (GObject * object, guint prop_id,
614     const GValue * value, GParamSpec * pspec)
615 {
616   GstPlayBin *play_bin;
617
618   play_bin = GST_PLAY_BIN (object);
619
620   switch (prop_id) {
621     case ARG_VIDEO_SINK:
622       if (play_bin->video_sink != NULL) {
623         gst_object_unref (play_bin->video_sink);
624       }
625       play_bin->video_sink = g_value_get_object (value);
626       if (play_bin->video_sink != NULL) {
627         gst_object_ref (play_bin->video_sink);
628         gst_object_sink (GST_OBJECT_CAST (play_bin->video_sink));
629       }
630       /* when changing the videosink, we just remove the
631        * video pipeline from the cache so that it will be
632        * regenerated with the new sink element */
633       g_hash_table_remove (play_bin->cache, "vbin");
634       break;
635     case ARG_AUDIO_SINK:
636       if (play_bin->audio_sink != NULL) {
637         gst_object_unref (play_bin->audio_sink);
638       }
639       play_bin->audio_sink = g_value_get_object (value);
640       if (play_bin->audio_sink != NULL) {
641         gst_object_ref (play_bin->audio_sink);
642         gst_object_sink (GST_OBJECT_CAST (play_bin->audio_sink));
643       }
644       g_hash_table_remove (play_bin->cache, "abin");
645       break;
646     case ARG_VIS_PLUGIN:
647     {
648       GstElement *pending_visualisation =
649           GST_ELEMENT_CAST (g_value_get_object (value));
650
651       /* Take ownership */
652       if (pending_visualisation) {
653         gst_object_ref (pending_visualisation);
654         gst_object_sink (pending_visualisation);
655       }
656
657       /* Do we already have a visualisation change pending ? */
658       GST_OBJECT_LOCK (play_bin);
659       if (play_bin->pending_visualisation) {
660         gst_object_unref (play_bin->pending_visualisation);
661         play_bin->pending_visualisation = pending_visualisation;
662         GST_OBJECT_UNLOCK (play_bin);
663       } else {
664         GST_OBJECT_UNLOCK (play_bin);
665         /* Was there a visualisation already set ? */
666         if (play_bin->visualisation != NULL) {
667           GstBin *vis_bin = NULL;
668
669           vis_bin =
670               GST_BIN_CAST (gst_object_get_parent (GST_OBJECT_CAST (play_bin->
671                       visualisation)));
672
673           /* Check if the visualisation is already in a bin */
674           if (GST_IS_BIN (vis_bin)) {
675             GstPad *vis_sink_pad = NULL, *tee_pad = NULL;
676
677             /* Now get tee pad and block it async */
678             vis_sink_pad = gst_element_get_pad (play_bin->visualisation,
679                 "sink");
680             if (!GST_IS_PAD (vis_sink_pad)) {
681               goto beach;
682             }
683             tee_pad = gst_pad_get_peer (vis_sink_pad);
684             if (!GST_IS_PAD (tee_pad)) {
685               goto beach;
686             }
687
688             play_bin->pending_visualisation = pending_visualisation;
689             /* Block with callback */
690             gst_pad_set_blocked_async (tee_pad, TRUE, gst_play_bin_vis_blocked,
691                 play_bin);
692           beach:
693             if (vis_sink_pad) {
694               gst_object_unref (vis_sink_pad);
695             }
696             if (tee_pad) {
697               gst_object_unref (tee_pad);
698             }
699             gst_object_unref (vis_bin);
700           } else {
701             play_bin->visualisation = pending_visualisation;
702           }
703         } else {
704           play_bin->visualisation = pending_visualisation;
705         }
706       }
707       break;
708     }
709     case ARG_VOLUME:
710       play_bin->volume = g_value_get_double (value);
711       if (play_bin->volume_element) {
712         g_object_set (G_OBJECT (play_bin->volume_element), "volume",
713             play_bin->volume, NULL);
714       }
715       break;
716     case ARG_FONT_DESC:
717       g_free (play_bin->font_desc);
718       play_bin->font_desc = g_strdup (g_value_get_string (value));
719       if (play_bin->textoverlay_element) {
720         g_object_set (G_OBJECT (play_bin->textoverlay_element),
721             "font-desc", g_value_get_string (value), NULL);
722       }
723       break;
724     default:
725       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
726       break;
727   }
728 }
729
730 static void
731 gst_play_bin_get_property (GObject * object, guint prop_id, GValue * value,
732     GParamSpec * pspec)
733 {
734   GstPlayBin *play_bin;
735
736   play_bin = GST_PLAY_BIN (object);
737
738   switch (prop_id) {
739     case ARG_VIDEO_SINK:
740       g_value_set_object (value, play_bin->video_sink);
741       break;
742     case ARG_AUDIO_SINK:
743       g_value_set_object (value, play_bin->audio_sink);
744       break;
745     case ARG_VIS_PLUGIN:
746       g_value_set_object (value, play_bin->visualisation);
747       break;
748     case ARG_VOLUME:
749       g_value_set_double (value, play_bin->volume);
750       break;
751     case ARG_FRAME:{
752       GstBuffer *cur_frame = NULL;
753
754       gst_buffer_replace (&cur_frame, play_bin->frame);
755       gst_value_take_buffer (value, cur_frame);
756       break;
757     }
758     default:
759       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
760       break;
761   }
762 }
763
764 /* signal fired when the identity has received a new buffer. This is used for
765  * making screenshots.
766  */
767 static void
768 handoff (GstElement * identity, GstBuffer * frame, gpointer data)
769 {
770   GstPlayBin *play_bin = GST_PLAY_BIN (data);
771
772   /* applications need to know the buffer caps,
773    * make sure they are always set on the frame */
774   if (GST_BUFFER_CAPS (frame) == NULL) {
775     GstPad *pad;
776
777     if ((pad = gst_element_get_pad (identity, "sink"))) {
778       gst_buffer_set_caps (frame, GST_PAD_CAPS (pad));
779       gst_object_unref (pad);
780     }
781   }
782
783   gst_buffer_replace (&play_bin->frame, frame);
784 }
785
786 static void
787 post_missing_element_message (GstPlayBin * playbin, const gchar * name)
788 {
789   GstMessage *msg;
790
791   msg = gst_missing_element_message_new (GST_ELEMENT_CAST (playbin), name);
792   gst_element_post_message (GST_ELEMENT_CAST (playbin), msg);
793 }
794
795 /* make the element (bin) that contains the elements needed to perform
796  * video display. We connect a handoff signal to identity so that we
797  * can grab snapshots. Identity's sinkpad is ghosted to vbin.
798  *
799  *  +-------------------------------------------------------------+
800  *  | vbin                                                        |
801  *  |      +--------+   +----------+   +----------+   +---------+ |
802  *  |      |identity|   |colorspace|   |videoscale|   |videosink| |
803  *  |   +-sink     src-sink       src-sink       src-sink       | |
804  *  |   |  +---+----+   +----------+   +----------+   +---------+ |
805  * sink-+      |                                                  |
806  *  +----------|--------------------------------------------------+
807  *           handoff
808  */
809 static GstElement *
810 gen_video_element (GstPlayBin * play_bin)
811 {
812   GstElement *element;
813   GstElement *conv;
814
815   GstElement *scale;
816   GstElement *sink;
817   GstElement *identity;
818   GstPad *pad;
819
820   /* first see if we have it in the cache */
821   element = g_hash_table_lookup (play_bin->cache, "vbin");
822   if (element != NULL) {
823     return element;
824   }
825
826   if (play_bin->video_sink) {
827     sink = play_bin->video_sink;
828   } else {
829     sink = gst_element_factory_make ("autovideosink", "videosink");
830     if (sink == NULL) {
831       sink = gst_element_factory_make ("xvimagesink", "videosink");
832     }
833     if (sink == NULL)
834       goto no_sinks;
835   }
836   gst_object_ref (sink);
837   g_hash_table_insert (play_bin->cache, "video_sink", sink);
838
839   /* create a bin to hold objects, as we create them we add them to this bin so
840    * that when something goes wrong we only need to unref the bin */
841   element = gst_bin_new ("vbin");
842   gst_bin_add (GST_BIN_CAST (element), sink);
843
844   conv = gst_element_factory_make ("ffmpegcolorspace", "vconv");
845   if (conv == NULL)
846     goto no_colorspace;
847   gst_bin_add (GST_BIN_CAST (element), conv);
848
849   scale = gst_element_factory_make ("videoscale", "vscale");
850   if (scale == NULL)
851     goto no_videoscale;
852   gst_bin_add (GST_BIN_CAST (element), scale);
853
854   identity = gst_element_factory_make ("identity", "id");
855   g_object_set (identity, "silent", TRUE, NULL);
856   g_signal_connect (identity, "handoff", G_CALLBACK (handoff), play_bin);
857   gst_bin_add (GST_BIN_CAST (element), identity);
858
859   gst_element_link_pads (identity, "src", conv, "sink");
860   gst_element_link_pads (conv, "src", scale, "sink");
861   /* be more careful with the pad from the custom sink element, it might not
862    * be named 'sink' */
863   if (!gst_element_link_pads (scale, "src", sink, NULL))
864     goto link_failed;
865
866   pad = gst_element_get_pad (identity, "sink");
867   gst_element_add_pad (element, gst_ghost_pad_new ("sink", pad));
868   gst_object_unref (pad);
869
870   gst_element_set_state (element, GST_STATE_READY);
871
872   /* since we're gonna add it to a bin but don't want to lose it,
873    * we keep a reference. */
874   gst_object_ref (element);
875   g_hash_table_insert (play_bin->cache, "vbin", element);
876
877   return element;
878
879   /* ERRORS */
880 no_sinks:
881   {
882     post_missing_element_message (play_bin, "autovideosink");
883     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
884         (_("Both autovideosink and xvimagesink elements are missing.")),
885         (NULL));
886     return NULL;
887   }
888 no_colorspace:
889   {
890     post_missing_element_message (play_bin, "ffmpegcolorspace");
891     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
892         (_("Missing element '%s' - check your GStreamer installation."),
893             "ffmpegcolorspace"), (NULL));
894     gst_object_unref (element);
895     return NULL;
896   }
897
898 no_videoscale:
899   {
900     post_missing_element_message (play_bin, "videoscale");
901     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
902         (_("Missing element '%s' - check your GStreamer installation."),
903             "videoscale"), ("possibly a liboil version mismatch?"));
904     gst_object_unref (element);
905     return NULL;
906   }
907 link_failed:
908   {
909     GST_ELEMENT_ERROR (play_bin, CORE, PAD,
910         (NULL), ("Failed to configure the video sink."));
911     gst_object_unref (element);
912     return NULL;
913   }
914 }
915
916 /* make an element for playback of video with subtitles embedded.
917  *
918  *  +--------------------------------------------------+
919  *  | tbin                  +-------------+            |
920  *  |          +-----+      | textoverlay |   +------+ |
921  *  |          | csp | +--video_sink      |   | vbin | |
922  * video_sink-sink  src+ +-text_sink     src-sink    | |
923  *  |          +-----+   |  +-------------+   +------+ |
924  * text_sink-------------+                             |
925  *  +--------------------------------------------------+
926  *
927  *  If there is no subtitle renderer this function will simply return the
928  *  videosink without the text_sink pad.
929  */
930 static GstElement *
931 gen_text_element (GstPlayBin * play_bin)
932 {
933   GstElement *element, *csp, *overlay, *vbin;
934   GstPad *pad;
935
936   /* Create the video rendering bin, error is posted when this fails. */
937   vbin = gen_video_element (play_bin);
938   if (!vbin)
939     return NULL;
940
941   /* Text overlay */
942   overlay = gst_element_factory_make ("textoverlay", "overlay");
943
944   /* If no overlay return the video bin without subtitle support. */
945   if (!overlay)
946     goto no_overlay;
947
948   /* Create our bin */
949   element = gst_bin_new ("textbin");
950
951   /* Set some parameters */
952   g_object_set (G_OBJECT (overlay),
953       "halign", "center", "valign", "bottom", NULL);
954   if (play_bin->font_desc) {
955     g_object_set (G_OBJECT (overlay), "font-desc", play_bin->font_desc, NULL);
956   }
957
958   /* Take a ref */
959   play_bin->textoverlay_element = GST_ELEMENT_CAST (gst_object_ref (overlay));
960
961   /* we know this will succeed, as the video bin already created one before */
962   csp = gst_element_factory_make ("ffmpegcolorspace", "subtitlecsp");
963
964   /* Add our elements */
965   gst_bin_add_many (GST_BIN_CAST (element), csp, overlay, vbin, NULL);
966
967   /* Link */
968   gst_element_link_pads (csp, "src", overlay, "video_sink");
969   gst_element_link_pads (overlay, "src", vbin, "sink");
970
971   /* Add ghost pads on the subtitle bin */
972   pad = gst_element_get_pad (overlay, "text_sink");
973   gst_element_add_pad (element, gst_ghost_pad_new ("text_sink", pad));
974   gst_object_unref (pad);
975
976   pad = gst_element_get_pad (csp, "sink");
977   gst_element_add_pad (element, gst_ghost_pad_new ("sink", pad));
978   gst_object_unref (pad);
979
980   /* Set state to READY */
981   gst_element_set_state (element, GST_STATE_READY);
982
983   return element;
984
985   /* ERRORS */
986 no_overlay:
987   {
988     post_missing_element_message (play_bin, "textoverlay");
989     GST_WARNING_OBJECT (play_bin,
990         "No overlay (pango) element, subtitles disabled");
991     return vbin;
992   }
993 }
994
995 /* make the element (bin) that contains the elements needed to perform
996  * audio playback.
997  *
998  *  +-------------------------------------------------------------+
999  *  | abin                                                        |
1000  *  |      +---------+   +----------+   +---------+   +---------+ |
1001  *  |      |audioconv|   |audioscale|   | volume  |   |audiosink| |
1002  *  |   +-sink      src-sink       src-sink      src-sink       | |
1003  *  |   |  +---------+   +----------+   +---------+   +---------+ |
1004  * sink-+                                                         |
1005  *  +-------------------------------------------------------------+
1006  */
1007 static GstElement *
1008 gen_audio_element (GstPlayBin * play_bin)
1009 {
1010   gboolean res;
1011   GstElement *element;
1012   GstElement *conv;
1013   GstElement *scale;
1014   GstElement *sink;
1015   GstElement *volume;
1016   GstPad *pad;
1017
1018   element = g_hash_table_lookup (play_bin->cache, "abin");
1019   if (element != NULL)
1020     return element;
1021
1022   if (play_bin->audio_sink) {
1023     sink = play_bin->audio_sink;
1024   } else {
1025     sink = gst_element_factory_make ("autoaudiosink", "audiosink");
1026     if (sink == NULL) {
1027       sink = gst_element_factory_make ("alsasink", "audiosink");
1028     }
1029     if (sink == NULL)
1030       goto no_sinks;
1031
1032     play_bin->audio_sink = GST_ELEMENT_CAST (gst_object_ref (sink));
1033   }
1034
1035   gst_object_ref (sink);
1036   g_hash_table_insert (play_bin->cache, "audio_sink", sink);
1037
1038   element = gst_bin_new ("abin");
1039   gst_bin_add (GST_BIN_CAST (element), sink);
1040
1041   conv = gst_element_factory_make ("audioconvert", "aconv");
1042   if (conv == NULL)
1043     goto no_audioconvert;
1044   gst_bin_add (GST_BIN_CAST (element), conv);
1045
1046   scale = gst_element_factory_make ("audioresample", "aresample");
1047   if (scale == NULL)
1048     goto no_audioresample;
1049   gst_bin_add (GST_BIN_CAST (element), scale);
1050
1051   volume = gst_element_factory_make ("volume", "volume");
1052   g_object_set (G_OBJECT (volume), "volume", play_bin->volume, NULL);
1053   play_bin->volume_element = volume;
1054   gst_bin_add (GST_BIN_CAST (element), volume);
1055
1056   res = gst_element_link_pads (conv, "src", scale, "sink");
1057   res &= gst_element_link_pads (scale, "src", volume, "sink");
1058   res &= gst_element_link_pads (volume, "src", sink, NULL);
1059   if (!res)
1060     goto link_failed;
1061
1062   pad = gst_element_get_pad (conv, "sink");
1063   gst_element_add_pad (element, gst_ghost_pad_new ("sink", pad));
1064   gst_object_unref (pad);
1065
1066   gst_element_set_state (element, GST_STATE_READY);
1067
1068   /* since we're gonna add it to a bin but don't want to lose it,
1069    * we keep a reference. */
1070   gst_object_ref (element);
1071   g_hash_table_insert (play_bin->cache, "abin", element);
1072
1073   return element;
1074
1075   /* ERRORS */
1076 no_sinks:
1077   {
1078     post_missing_element_message (play_bin, "autoaudiosink");
1079     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
1080         (_("Both autoaudiosink and alsasink elements are missing.")), (NULL));
1081     return NULL;
1082   }
1083 no_audioconvert:
1084   {
1085     post_missing_element_message (play_bin, "audioconvert");
1086     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
1087         (_("Missing element '%s' - check your GStreamer installation."),
1088             "audioconvert"), ("possibly a liboil version mismatch?"));
1089     gst_object_unref (element);
1090     return NULL;
1091   }
1092
1093 no_audioresample:
1094   {
1095     post_missing_element_message (play_bin, "audioresample");
1096     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
1097         (_("Missing element '%s' - check your GStreamer installation."),
1098             "audioresample"), ("possibly a liboil version mismatch?"));
1099     gst_object_unref (element);
1100     return NULL;
1101   }
1102 link_failed:
1103   {
1104     GST_ELEMENT_ERROR (play_bin, CORE, PAD,
1105         (NULL), ("Failed to configure the audio sink."));
1106     gst_object_unref (element);
1107     return NULL;
1108   }
1109 }
1110
1111 /* make the element (bin) that contains the elements needed to perform
1112  * visualisation ouput.  The idea is to split the audio using tee, then
1113  * sending the output to the regular audio bin and the other output to
1114  * the vis plugin that transforms it into a video that is rendered with the
1115  * normal video bin. The video and audio bins are run in threads to make sure
1116  * they don't block eachother.
1117  *
1118  *  +-----------------------------------------------------------------------+
1119  *  | visbin                                                                |
1120  *  |      +------+   +--------+   +----------------+                       |
1121  *  |      | tee  |   | aqueue |   |   abin ...     |                       |
1122  *  |   +-sink   src-sink     src-sink              |                       |
1123  *  |   |  |      |   +--------+   +----------------+                       |
1124  *  |   |  |      |                                                         |
1125  *  |   |  |      |   +------+   +------------+   +------+   +-----------+  |
1126  *  |   |  |      |   |vqueue|   | audioconv  |   | vis  |   | vbin ...  |  |
1127  *  |   |  |     src-sink   src-sink + samp  src-sink   src-sink         |  |
1128  *  |   |  |      |   +------+   +------------+   +------+   +-----------+  |
1129  *  |   |  |      |                                                         |
1130  *  |   |  +------+                                                         |
1131  * sink-+                                                                   |
1132  *  +-----------------------------------------------------------------------+
1133  */
1134 static GstElement *
1135 gen_vis_element (GstPlayBin * play_bin)
1136 {
1137   gboolean res;
1138   GstElement *element;
1139   GstElement *tee;
1140   GstElement *asink;
1141   GstElement *vsink;
1142   GstElement *conv;
1143   GstElement *resamp;
1144   GstElement *conv2;
1145   GstElement *vis;
1146   GstElement *vqueue, *aqueue;
1147   GstPad *pad, *rpad;
1148
1149   /* errors are already posted when these fail. */
1150   asink = gen_audio_element (play_bin);
1151   if (!asink)
1152     return NULL;
1153   vsink = gen_video_element (play_bin);
1154   if (!vsink) {
1155     gst_object_unref (asink);
1156     return NULL;
1157   }
1158
1159   element = gst_bin_new ("visbin");
1160   tee = gst_element_factory_make ("tee", "tee");
1161
1162   vqueue = gst_element_factory_make ("queue", "vqueue");
1163   aqueue = gst_element_factory_make ("queue", "aqueue");
1164
1165   gst_bin_add (GST_BIN_CAST (element), asink);
1166   gst_bin_add (GST_BIN_CAST (element), vqueue);
1167   gst_bin_add (GST_BIN_CAST (element), aqueue);
1168   gst_bin_add (GST_BIN_CAST (element), vsink);
1169   gst_bin_add (GST_BIN_CAST (element), tee);
1170
1171   conv = gst_element_factory_make ("audioconvert", "aconv");
1172   if (conv == NULL)
1173     goto no_audioconvert;
1174   gst_bin_add (GST_BIN_CAST (element), conv);
1175
1176   resamp = gst_element_factory_make ("audioresample", "aresamp");
1177   if (resamp == NULL)
1178     goto no_audioresample;
1179   gst_bin_add (GST_BIN_CAST (element), resamp);
1180
1181   conv2 = gst_element_factory_make ("audioconvert", "aconv2");
1182   if (conv2 == NULL)
1183     goto no_audioconvert;
1184   gst_bin_add (GST_BIN_CAST (element), conv2);
1185
1186   if (play_bin->visualisation) {
1187     gst_object_ref (play_bin->visualisation);
1188     vis = play_bin->visualisation;
1189   } else {
1190     vis = gst_element_factory_make ("goom", "vis");
1191     if (!vis)
1192       goto no_goom;
1193   }
1194   gst_bin_add (GST_BIN_CAST (element), vis);
1195
1196   res = gst_element_link_pads (vqueue, "src", conv, "sink");
1197   res &= gst_element_link_pads (conv, "src", resamp, "sink");
1198   res &= gst_element_link_pads (resamp, "src", conv2, "sink");
1199   res &= gst_element_link_pads (conv2, "src", vis, "sink");
1200   res &= gst_element_link_pads (vis, "src", vsink, "sink");
1201   if (!res)
1202     goto link_failed;
1203
1204   pad = gst_element_get_pad (aqueue, "sink");
1205   rpad = gst_element_get_request_pad (tee, "src%d");
1206   gst_pad_link (rpad, pad);
1207   gst_object_unref (rpad);
1208   gst_object_unref (pad);
1209   gst_element_link_pads (aqueue, "src", asink, "sink");
1210
1211   pad = gst_element_get_pad (vqueue, "sink");
1212   rpad = gst_element_get_request_pad (tee, "src%d");
1213   gst_pad_link (rpad, pad);
1214   gst_object_unref (rpad);
1215   gst_object_unref (pad);
1216
1217   pad = gst_element_get_pad (tee, "sink");
1218   gst_element_add_pad (element, gst_ghost_pad_new ("sink", pad));
1219   gst_object_unref (pad);
1220
1221   return element;
1222
1223   /* ERRORS */
1224 no_audioconvert:
1225   {
1226     post_missing_element_message (play_bin, "audioconvert");
1227     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
1228         (_("Missing element '%s' - check your GStreamer installation."),
1229             "audioconvert"), ("possibly a liboil version mismatch?"));
1230     gst_object_unref (element);
1231     return NULL;
1232   }
1233 no_audioresample:
1234   {
1235     post_missing_element_message (play_bin, "audioresample");
1236     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
1237         (_("Missing element '%s' - check your GStreamer installation."),
1238             "audioresample"), (NULL));
1239     gst_object_unref (element);
1240     return NULL;
1241   }
1242 no_goom:
1243   {
1244     post_missing_element_message (play_bin, "goom");
1245     GST_ELEMENT_ERROR (play_bin, CORE, MISSING_PLUGIN,
1246         (_("Missing element '%s' - check your GStreamer installation."),
1247             "goom"), (NULL));
1248     gst_object_unref (element);
1249     return NULL;
1250   }
1251 link_failed:
1252   {
1253     GST_ELEMENT_ERROR (play_bin, CORE, PAD,
1254         (NULL), ("Failed to configure the visualisation element."));
1255     gst_object_unref (element);
1256     return NULL;
1257   }
1258 }
1259
1260 /* get rid of all installed sinks */
1261 static void
1262 remove_sinks (GstPlayBin * play_bin)
1263 {
1264   GList *sinks;
1265   GstObject *parent;
1266   GstElement *element;
1267   GstPad *pad, *peer;
1268
1269   if (play_bin->cache == NULL)
1270     return;
1271
1272   GST_DEBUG ("removesinks");
1273   element = g_hash_table_lookup (play_bin->cache, "abin");
1274   if (element != NULL) {
1275     parent = gst_element_get_parent (element);
1276     if (parent != NULL) {
1277       /* we remove the element from the parent so that
1278        * there is no unwanted state change when the parent
1279        * is disposed */
1280       play_bin->sinks = g_list_remove (play_bin->sinks, element);
1281       gst_element_set_state (element, GST_STATE_NULL);
1282       gst_bin_remove (GST_BIN_CAST (parent), element);
1283       gst_object_unref (parent);
1284     }
1285     pad = gst_element_get_pad (element, "sink");
1286     if (pad != NULL) {
1287       peer = gst_pad_get_peer (pad);
1288       if (peer != NULL) {
1289         gst_pad_unlink (peer, pad);
1290         gst_object_unref (peer);
1291       }
1292       gst_object_unref (pad);
1293     }
1294   }
1295   element = g_hash_table_lookup (play_bin->cache, "vbin");
1296   if (element != NULL) {
1297     parent = gst_element_get_parent (element);
1298     if (parent != NULL) {
1299       play_bin->sinks = g_list_remove (play_bin->sinks, element);
1300       gst_element_set_state (element, GST_STATE_NULL);
1301       gst_bin_remove (GST_BIN_CAST (parent), element);
1302       gst_object_unref (parent);
1303     }
1304     pad = gst_element_get_pad (element, "sink");
1305     if (pad != NULL) {
1306       peer = gst_pad_get_peer (pad);
1307       if (peer != NULL) {
1308         gst_pad_unlink (peer, pad);
1309         gst_object_unref (peer);
1310       }
1311       gst_object_unref (pad);
1312     }
1313   }
1314
1315   for (sinks = play_bin->sinks; sinks; sinks = g_list_next (sinks)) {
1316     GstElement *element = GST_ELEMENT_CAST (sinks->data);
1317     GstPad *pad;
1318     GstPad *peer;
1319
1320     pad = gst_element_get_pad (element, "sink");
1321
1322     GST_LOG ("removing sink %p", element);
1323
1324     peer = gst_pad_get_peer (pad);
1325     if (peer) {
1326       gst_pad_unlink (peer, pad);
1327       gst_object_unref (peer);
1328     }
1329     gst_object_unref (pad);
1330
1331     gst_element_set_state (element, GST_STATE_NULL);
1332     gst_bin_remove (GST_BIN_CAST (play_bin), element);
1333   }
1334   g_list_free (play_bin->sinks);
1335   play_bin->sinks = NULL;
1336
1337   if (play_bin->visualisation) {
1338     GstElement *vis_bin;
1339
1340     vis_bin =
1341         GST_ELEMENT_CAST (gst_element_get_parent (play_bin->visualisation));
1342
1343     gst_element_set_state (play_bin->visualisation, GST_STATE_NULL);
1344
1345     if (vis_bin) {
1346       gst_bin_remove (GST_BIN_CAST (vis_bin), play_bin->visualisation);
1347       gst_object_unref (vis_bin);
1348     }
1349   }
1350
1351   if (play_bin->frame) {
1352     gst_buffer_unref (play_bin->frame);
1353     play_bin->frame = NULL;
1354   }
1355
1356   if (play_bin->textoverlay_element) {
1357     gst_object_unref (play_bin->textoverlay_element);
1358     play_bin->textoverlay_element = NULL;
1359   }
1360 }
1361
1362 /* loop over the streams and set up the pipeline to play this
1363  * media file. First we count the number of audio and video streams.
1364  * If there is no video stream but there exists an audio stream,
1365  * we install a visualisation pipeline.
1366  *
1367  * Also make sure to only connect the first audio and video pad. FIXME
1368  * this should eventually be handled with a tuner interface so that
1369  * one can switch the streams.
1370  *
1371  * This function takes ownership of @sink.*
1372  */
1373 static gboolean
1374 add_sink (GstPlayBin * play_bin, GstElement * sink, GstPad * srcpad,
1375     GstPad * subtitle_pad)
1376 {
1377   GstPad *sinkpad;
1378   GstPadLinkReturn linkres;
1379   GstElement *parent;
1380   GstStateChangeReturn stateret;
1381   GstState state;
1382
1383   g_return_val_if_fail (sink != NULL, FALSE);
1384
1385   state = GST_STATE_PAUSED;
1386
1387   /* this is only for debugging */
1388   parent = gst_pad_get_parent_element (srcpad);
1389   if (parent) {
1390     GST_DEBUG ("Adding sink %" GST_PTR_FORMAT
1391         " with state %d (parent: %d, peer: %d)", sink,
1392         GST_STATE (sink), GST_STATE (play_bin), GST_STATE (parent));
1393     gst_object_unref (parent);
1394   }
1395   gst_bin_add (GST_BIN_CAST (play_bin), sink);
1396
1397   /* bring it to the required state so we can link to the peer without
1398    * breaking the flow */
1399   stateret = gst_element_set_state (sink, state);
1400   if (stateret == GST_STATE_CHANGE_FAILURE)
1401     goto state_failed;
1402
1403   /* we found a sink for this stream, now try to install it */
1404   sinkpad = gst_element_get_pad (sink, "sink");
1405   linkres = gst_pad_link (srcpad, sinkpad);
1406   gst_object_unref (sinkpad);
1407
1408   /* try to link the pad of the sink to the stream */
1409   if (GST_PAD_LINK_FAILED (linkres))
1410     goto link_failed;
1411
1412   if (GST_IS_PAD (subtitle_pad)) {
1413     sinkpad = gst_element_get_pad (sink, "text_sink");
1414     linkres = gst_pad_link (subtitle_pad, sinkpad);
1415     gst_object_unref (sinkpad);
1416   }
1417
1418   /* try to link the subtitle pad of the sink to the stream, this is not
1419    * fatal. */
1420   if (GST_PAD_LINK_FAILED (linkres))
1421     goto subtitle_failed;
1422
1423 done:
1424   /* we got the sink succesfully linked, now keep the sink
1425    * in our internal list */
1426   play_bin->sinks = g_list_prepend (play_bin->sinks, sink);
1427
1428   return TRUE;
1429
1430   /* ERRORS */
1431 state_failed:
1432   {
1433     gst_element_set_state (sink, GST_STATE_NULL);
1434     gst_bin_remove (GST_BIN_CAST (play_bin), sink);
1435     GST_DEBUG_OBJECT (play_bin, "state change failure when adding sink");
1436     return FALSE;
1437   }
1438 link_failed:
1439   {
1440     gchar *capsstr;
1441     GstCaps *caps;
1442
1443     /* could not link this stream */
1444     caps = gst_pad_get_caps (srcpad);
1445     capsstr = gst_caps_to_string (caps);
1446     g_warning ("could not link %s: %d", capsstr, linkres);
1447     GST_DEBUG_OBJECT (play_bin,
1448         "link failed when adding sink, caps %s, reason %d", capsstr, linkres);
1449     g_free (capsstr);
1450     gst_caps_unref (caps);
1451
1452     gst_element_set_state (sink, GST_STATE_NULL);
1453     gst_bin_remove (GST_BIN_CAST (play_bin), sink);
1454     return FALSE;
1455   }
1456 subtitle_failed:
1457   {
1458     GstCaps *caps;
1459
1460     /* could not link this stream */
1461     caps = gst_pad_get_caps (subtitle_pad);
1462     GST_WARNING_OBJECT (play_bin, "subtitle link failed when adding sink, "
1463         "caps = %" GST_PTR_FORMAT ", reason %d", caps, linkres);
1464     gst_caps_unref (caps);
1465
1466     /* not fatal */
1467     goto done;
1468   }
1469 }
1470
1471 static void
1472 dummy_blocked_cb (GstPad * pad, gboolean blocked, gpointer user_data)
1473 {
1474 }
1475
1476 static gboolean
1477 setup_sinks (GstPlayBaseBin * play_base_bin, GstPlayBaseGroup * group)
1478 {
1479   GstPlayBin *play_bin = GST_PLAY_BIN (play_base_bin);
1480   GList *streaminfo = NULL, *s;
1481   gboolean need_vis = FALSE;
1482   gboolean need_text = FALSE;
1483   GstPad *textsrcpad = NULL, *pad = NULL, *origtextsrcpad = NULL;
1484   GstElement *sink;
1485   gboolean res = TRUE;
1486
1487   /* get rid of existing sinks */
1488   if (play_bin->sinks) {
1489     remove_sinks (play_bin);
1490   }
1491   GST_DEBUG_OBJECT (play_base_bin, "setupsinks");
1492
1493   /* find out what to do */
1494   if (group->type[GST_STREAM_TYPE_VIDEO - 1].npads > 0 &&
1495       group->type[GST_STREAM_TYPE_TEXT - 1].npads > 0) {
1496     need_text = TRUE;
1497   } else if (group->type[GST_STREAM_TYPE_VIDEO - 1].npads == 0 &&
1498       group->type[GST_STREAM_TYPE_AUDIO - 1].npads > 0 &&
1499       play_bin->visualisation != NULL) {
1500     need_vis = TRUE;
1501   }
1502
1503   /* now actually connect everything */
1504   g_object_get (G_OBJECT (play_base_bin), "stream-info", &streaminfo, NULL);
1505   for (s = streaminfo; s; s = g_list_next (s)) {
1506     GObject *obj = G_OBJECT (s->data);
1507     gint type;
1508     GstObject *object;
1509
1510     g_object_get (obj, "type", &type, NULL);
1511     g_object_get (obj, "object", &object, NULL);
1512   }
1513
1514   /* link audio */
1515   if (group->type[GST_STREAM_TYPE_AUDIO - 1].npads > 0) {
1516     if (need_vis) {
1517       sink = gen_vis_element (play_bin);
1518     } else {
1519       sink = gen_audio_element (play_bin);
1520     }
1521     if (!sink)
1522       return FALSE;
1523
1524     pad = gst_element_get_pad (group->type[GST_STREAM_TYPE_AUDIO - 1].preroll,
1525         "src");
1526     res = add_sink (play_bin, sink, pad, NULL);
1527     gst_object_unref (pad);
1528   }
1529
1530   /* link video */
1531   if (group->type[GST_STREAM_TYPE_VIDEO - 1].npads > 0) {
1532     if (need_text) {
1533       GstObject *parent = NULL, *grandparent = NULL;
1534       GstPad *ghost = NULL;
1535
1536       sink = gen_text_element (play_bin);
1537       textsrcpad =
1538           gst_element_get_pad (group->type[GST_STREAM_TYPE_TEXT - 1].preroll,
1539           "src");
1540
1541       /* This pad is from subtitle-bin, we need to create a ghost pad to have
1542          common grandparents */
1543       parent = gst_object_get_parent (GST_OBJECT_CAST (textsrcpad));
1544       if (!parent) {
1545         GST_WARNING_OBJECT (textsrcpad, "subtitle pad has no parent !");
1546         gst_object_unref (textsrcpad);
1547         textsrcpad = NULL;
1548         goto beach;
1549       }
1550
1551       grandparent = gst_object_get_parent (parent);
1552       if (!grandparent) {
1553         GST_WARNING_OBJECT (textsrcpad, "subtitle pad has no grandparent !");
1554         gst_object_unref (parent);
1555         gst_object_unref (textsrcpad);
1556         textsrcpad = NULL;
1557         goto beach;
1558       }
1559
1560       /* We ghost the pad on subtitle_bin only, if the text pad is from the
1561          media demuxer we keep it as it is */
1562       if (!GST_IS_PLAY_BIN (grandparent)) {
1563         GST_DEBUG_OBJECT (textsrcpad, "this subtitle pad is from a subtitle "
1564             "file, ghosting to a suitable hierarchy");
1565         /* Block the pad first, because as soon as we add a ghostpad, the queue
1566          * will try and start pushing */
1567         gst_pad_set_blocked_async (textsrcpad, TRUE, dummy_blocked_cb, NULL);
1568         origtextsrcpad = gst_object_ref (textsrcpad);
1569
1570         ghost = gst_ghost_pad_new ("text_src", textsrcpad);
1571         if (!GST_IS_PAD (ghost)) {
1572           GST_WARNING_OBJECT (textsrcpad, "failed creating ghost pad for "
1573               "subtitle-bin");
1574           gst_object_unref (parent);
1575           gst_object_unref (grandparent);
1576           gst_object_unref (textsrcpad);
1577           textsrcpad = NULL;
1578           goto beach;
1579         }
1580
1581         gst_pad_set_active (ghost, TRUE);
1582         if (gst_element_add_pad (GST_ELEMENT_CAST (grandparent), ghost)) {
1583           gst_object_unref (textsrcpad);
1584           textsrcpad = gst_object_ref (ghost);
1585         } else {
1586           GST_WARNING_OBJECT (ghost, "failed adding ghost pad on subtitle-bin");
1587           gst_pad_set_active (ghost, FALSE);
1588           gst_object_unref (ghost);
1589           gst_object_unref (textsrcpad);
1590           textsrcpad = NULL;
1591         }
1592       } else {
1593         GST_DEBUG_OBJECT (textsrcpad, "this subtitle pad is from the demuxer "
1594             "no changes to hierarchy needed");
1595       }
1596
1597       gst_object_unref (parent);
1598       gst_object_unref (grandparent);
1599     } else {
1600       sink = gen_video_element (play_bin);
1601     }
1602   beach:
1603     if (!sink)
1604       return FALSE;
1605     pad = gst_element_get_pad (group->type[GST_STREAM_TYPE_VIDEO - 1].preroll,
1606         "src");
1607     res = add_sink (play_bin, sink, pad, textsrcpad);
1608     gst_object_unref (pad);
1609     if (textsrcpad)
1610       gst_object_unref (textsrcpad);
1611     if (origtextsrcpad) {
1612       gst_pad_set_blocked_async (origtextsrcpad, FALSE, dummy_blocked_cb, NULL);
1613       gst_object_unref (origtextsrcpad);
1614     }
1615   }
1616
1617   /* remove the sinks now, pipeline get_state will now wait for the
1618    * sinks to preroll */
1619   if (play_bin->fakesink) {
1620     gst_element_set_state (play_bin->fakesink, GST_STATE_NULL);
1621     gst_bin_remove (GST_BIN_CAST (play_bin), play_bin->fakesink);
1622     play_bin->fakesink = NULL;
1623   }
1624
1625   return res;
1626 }
1627
1628 /* Send an event to our sinks until one of them works; don't then send to the
1629  * remaining sinks (unlike GstBin)
1630  */
1631 static gboolean
1632 gst_play_bin_send_event_to_sink (GstPlayBin * play_bin, GstEvent * event)
1633 {
1634   GList *sinks = play_bin->sinks;
1635   gboolean res = TRUE;
1636
1637   while (sinks) {
1638     GstElement *sink = GST_ELEMENT_CAST (sinks->data);
1639
1640     gst_event_ref (event);
1641     if ((res = gst_element_send_event (sink, event))) {
1642       GST_DEBUG_OBJECT (play_bin,
1643           "Sent event succesfully to sink %" GST_PTR_FORMAT, sink);
1644       break;
1645     }
1646     GST_DEBUG_OBJECT (play_bin,
1647         "Event failed when sent to sink %" GST_PTR_FORMAT, sink);
1648
1649     sinks = g_list_next (sinks);
1650   }
1651
1652   gst_event_unref (event);
1653
1654   return res;
1655 }
1656
1657 /* We only want to send the event to a single sink (overriding GstBin's
1658  * behaviour), but we want to keep GstPipeline's behaviour - wrapping seek
1659  * events appropriately. So, this is a messy duplication of code. */
1660 static gboolean
1661 gst_play_bin_send_event (GstElement * element, GstEvent * event)
1662 {
1663   gboolean res = FALSE;
1664   GstEventType event_type = GST_EVENT_TYPE (event);
1665
1666   switch (event_type) {
1667     case GST_EVENT_SEEK:
1668       GST_DEBUG_OBJECT (element, "Sending seek event to a sink");
1669       res = gst_play_bin_send_event_to_sink (GST_PLAY_BIN (element), event);
1670       break;
1671     default:
1672       res = parent_class->send_event (element, event);
1673       break;
1674   }
1675
1676   return res;
1677 }
1678
1679 static void
1680 value_list_append_structure_list (GValue * list_val, GstStructure ** first,
1681     GList * structure_list)
1682 {
1683   GList *l;
1684
1685   for (l = structure_list; l != NULL; l = l->next) {
1686     GValue val = { 0, };
1687
1688     if (*first == NULL)
1689       *first = gst_structure_copy ((GstStructure *) l->data);
1690
1691     g_value_init (&val, GST_TYPE_STRUCTURE);
1692     g_value_take_boxed (&val, gst_structure_copy ((GstStructure *) l->data));
1693     gst_value_list_append_value (list_val, &val);
1694     g_value_unset (&val);
1695   }
1696 }
1697
1698 /* if it's a redirect message with multiple redirect locations we might
1699  * want to pick a different 'best' location depending on the required
1700  * bitrates and the connection speed */
1701 static GstMessage *
1702 gst_play_bin_handle_redirect_message (GstPlayBin * playbin, GstMessage * msg)
1703 {
1704   const GValue *locations_list, *location_val;
1705   GstMessage *new_msg;
1706   GstStructure *new_structure = NULL;
1707   GList *l_good = NULL, *l_neutral = NULL, *l_bad = NULL;
1708   GValue new_list = { 0, };
1709   guint size, i;
1710   GstPlayBaseBin *playbasebin = GST_PLAY_BASE_BIN (playbin);
1711   guint connection_speed = playbasebin->connection_speed;
1712
1713   GST_DEBUG_OBJECT (playbin, "redirect message: %" GST_PTR_FORMAT, msg);
1714   GST_DEBUG_OBJECT (playbin, "connection speed: %u", connection_speed);
1715
1716   if (connection_speed == 0 || msg->structure == NULL)
1717     return msg;
1718
1719   locations_list = gst_structure_get_value (msg->structure, "locations");
1720   if (locations_list == NULL)
1721     return msg;
1722
1723   size = gst_value_list_get_size (locations_list);
1724   if (size < 2)
1725     return msg;
1726
1727   /* maintain existing order as much as possible, just sort references
1728    * with too high a bitrate to the end (the assumption being that if
1729    * bitrates are given they are given for all interesting streams and
1730    * that the you-need-at-least-version-xyz redirect has the same bitrate
1731    * as the lowest referenced redirect alternative) */
1732   for (i = 0; i < size; ++i) {
1733     const GstStructure *s;
1734     gint bitrate = 0;
1735
1736     location_val = gst_value_list_get_value (locations_list, i);
1737     s = (const GstStructure *) g_value_get_boxed (location_val);
1738     if (!gst_structure_get_int (s, "minimum-bitrate", &bitrate) || bitrate <= 0) {
1739       GST_DEBUG_OBJECT (playbin, "no bitrate: %" GST_PTR_FORMAT, s);
1740       l_neutral = g_list_append (l_neutral, (gpointer) s);
1741     } else if (bitrate > connection_speed) {
1742       GST_DEBUG_OBJECT (playbin, "bitrate too high: %" GST_PTR_FORMAT, s);
1743       l_bad = g_list_append (l_bad, (gpointer) s);
1744     } else if (bitrate <= connection_speed) {
1745       GST_DEBUG_OBJECT (playbin, "bitrate OK: %" GST_PTR_FORMAT, s);
1746       l_good = g_list_append (l_good, (gpointer) s);
1747     }
1748   }
1749
1750   g_value_init (&new_list, GST_TYPE_LIST);
1751   value_list_append_structure_list (&new_list, &new_structure, l_good);
1752   value_list_append_structure_list (&new_list, &new_structure, l_neutral);
1753   value_list_append_structure_list (&new_list, &new_structure, l_bad);
1754   gst_structure_set_value (new_structure, "locations", &new_list);
1755   g_value_unset (&new_list);
1756
1757   g_list_free (l_good);
1758   g_list_free (l_neutral);
1759   g_list_free (l_bad);
1760
1761   new_msg = gst_message_new_element (msg->src, new_structure);
1762   gst_message_unref (msg);
1763
1764   GST_DEBUG_OBJECT (playbin, "new redirect message: %" GST_PTR_FORMAT, new_msg);
1765   return new_msg;
1766 }
1767
1768 static void
1769 gst_play_bin_handle_message (GstBin * bin, GstMessage * msg)
1770 {
1771   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ELEMENT && msg->structure != NULL
1772       && gst_structure_has_name (msg->structure, "redirect")) {
1773     msg = gst_play_bin_handle_redirect_message (GST_PLAY_BIN (bin), msg);
1774   }
1775
1776   GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
1777 }
1778
1779 static GstStateChangeReturn
1780 gst_play_bin_change_state (GstElement * element, GstStateChange transition)
1781 {
1782   GstStateChangeReturn ret;
1783   GstPlayBin *play_bin;
1784
1785   play_bin = GST_PLAY_BIN (element);
1786
1787
1788   switch (transition) {
1789     case GST_STATE_CHANGE_READY_TO_PAUSED:
1790       /* this really is the easiest way to make the state change return
1791        * ASYNC until we added the sinks */
1792       if (!play_bin->fakesink) {
1793         play_bin->fakesink = gst_element_factory_make ("fakesink", "test");
1794         gst_bin_add (GST_BIN_CAST (play_bin), play_bin->fakesink);
1795       }
1796       break;
1797     default:
1798       break;
1799   }
1800
1801   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1802   if (ret == GST_STATE_CHANGE_FAILURE)
1803     return ret;
1804
1805   switch (transition) {
1806     case GST_STATE_CHANGE_READY_TO_PAUSED:
1807       /* remember us being a live pipeline */
1808       play_bin->is_live = (ret == GST_STATE_CHANGE_NO_PREROLL);
1809       GST_DEBUG_OBJECT (play_bin, "is live: %d", play_bin->is_live);
1810       break;
1811     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1812       /* FIXME Release audio device when we implement that */
1813       break;
1814     case GST_STATE_CHANGE_PAUSED_TO_READY:
1815     case GST_STATE_CHANGE_READY_TO_NULL:
1816       /* remove sinks we added */
1817       remove_sinks (play_bin);
1818       /* and there might be a fakesink we need to clean up now */
1819       if (play_bin->fakesink) {
1820         gst_element_set_state (play_bin->fakesink, GST_STATE_NULL);
1821         gst_bin_remove (GST_BIN_CAST (play_bin), play_bin->fakesink);
1822         play_bin->fakesink = NULL;
1823       }
1824       break;
1825     default:
1826       break;
1827   }
1828
1829   return ret;
1830 }
1831
1832 static gboolean
1833 plugin_init (GstPlugin * plugin)
1834 {
1835   GST_DEBUG_CATEGORY_INIT (gst_play_bin_debug, "playbin", 0, "play bin");
1836
1837   gst_pb_utils_init ();
1838
1839 #ifdef ENABLE_NLS
1840   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
1841       LOCALEDIR);
1842   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
1843 #endif /* ENABLE_NLS */
1844
1845   return gst_element_register (plugin, "playbin", GST_RANK_NONE,
1846       GST_TYPE_PLAY_BIN);
1847 }
1848
1849 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1850     GST_VERSION_MINOR,
1851     "playbin",
1852     "player bin", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME,
1853     GST_PACKAGE_ORIGIN)