media: Do not stop thread twice if default_prepare() fails
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-media.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
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., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19 /**
20  * SECTION:rtsp-media
21  * @short_description: The media pipeline
22  * @see_also: #GstRTSPMediaFactory, #GstRTSPStream, #GstRTSPSession,
23  *     #GstRTSPSessionMedia
24  *
25  * a #GstRTSPMedia contains the complete GStreamer pipeline to manage the
26  * streaming to the clients. The actual data transfer is done by the
27  * #GstRTSPStream objects that are created and exposed by the #GstRTSPMedia.
28  *
29  * The #GstRTSPMedia is usually created from a #GstRTSPMediaFactory when the
30  * client does a DESCRIBE or SETUP of a resource.
31  *
32  * A media is created with gst_rtsp_media_new() that takes the element that will
33  * provide the streaming elements. For each of the streams, a new #GstRTSPStream
34  * object needs to be made with the gst_rtsp_media_create_stream() which takes
35  * the payloader element and the source pad that produces the RTP stream.
36  *
37  * The pipeline of the media is set to PAUSED with gst_rtsp_media_prepare(). The
38  * prepare method will add rtpbin and sinks and sources to send and receive RTP
39  * and RTCP packets from the clients. Each stream srcpad is connected to an
40  * input into the internal rtpbin.
41  *
42  * It is also possible to dynamically create #GstRTSPStream objects during the
43  * prepare phase. With gst_rtsp_media_get_status() you can check the status of
44  * the prepare phase.
45  *
46  * After the media is prepared, it is ready for streaming. It will usually be
47  * managed in a session with gst_rtsp_session_manage_media(). See
48  * #GstRTSPSession and #GstRTSPSessionMedia.
49  *
50  * The state of the media can be controlled with gst_rtsp_media_set_state ().
51  * Seeking can be done with gst_rtsp_media_seek().
52  *
53  * With gst_rtsp_media_unprepare() the pipeline is stopped and shut down. When
54  * gst_rtsp_media_set_eos_shutdown() an EOS will be sent to the pipeline to
55  * cleanly shut down.
56  *
57  * With gst_rtsp_media_set_shared(), the media can be shared between multiple
58  * clients. With gst_rtsp_media_set_reusable() you can control if the pipeline
59  * can be prepared again after an unprepare.
60  *
61  * Last reviewed on 2013-07-11 (1.0.0)
62  */
63
64 #include <string.h>
65 #include <stdlib.h>
66
67 #include <gst/app/gstappsrc.h>
68 #include <gst/app/gstappsink.h>
69
70 #include "rtsp-media.h"
71
72 #define GST_RTSP_MEDIA_GET_PRIVATE(obj)  \
73      (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_MEDIA, GstRTSPMediaPrivate))
74
75 struct _GstRTSPMediaPrivate
76 {
77   GMutex lock;
78   GCond cond;
79
80   /* protected by lock */
81   GstRTSPPermissions *permissions;
82   gboolean shared;
83   gboolean suspend_mode;
84   gboolean reusable;
85   GstRTSPProfile profiles;
86   GstRTSPLowerTrans protocols;
87   gboolean reused;
88   gboolean eos_shutdown;
89   guint buffer_size;
90   GstRTSPAddressPool *pool;
91   gboolean blocked;
92
93   GstElement *element;
94   GRecMutex state_lock;         /* locking order: state lock, lock */
95   GPtrArray *streams;           /* protected by lock */
96   GList *dynamic;               /* protected by lock */
97   GstRTSPMediaStatus status;    /* protected by lock */
98   gint prepare_count;
99   gint n_active;
100   gboolean adding;
101
102   /* the pipeline for the media */
103   GstElement *pipeline;
104   GstElement *fakesink;         /* protected by lock */
105   GSource *source;
106   guint id;
107   GstRTSPThread *thread;
108
109   gboolean time_provider;
110   GstNetTimeProvider *nettime;
111
112   gboolean is_live;
113   gboolean seekable;
114   gboolean buffering;
115   GstState target_state;
116
117   /* RTP session manager */
118   GstElement *rtpbin;
119
120   /* the range of media */
121   GstRTSPTimeRange range;       /* protected by lock */
122   GstClockTime range_start;
123   GstClockTime range_stop;
124 };
125
126 #define DEFAULT_SHARED          FALSE
127 #define DEFAULT_SUSPEND_MODE    GST_RTSP_SUSPEND_MODE_NONE
128 #define DEFAULT_REUSABLE        FALSE
129 #define DEFAULT_PROFILES        GST_RTSP_PROFILE_AVP
130 #define DEFAULT_PROTOCOLS       GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | \
131                                         GST_RTSP_LOWER_TRANS_TCP
132 #define DEFAULT_EOS_SHUTDOWN    FALSE
133 #define DEFAULT_BUFFER_SIZE     0x80000
134 #define DEFAULT_TIME_PROVIDER   FALSE
135
136 /* define to dump received RTCP packets */
137 #undef DUMP_STATS
138
139 enum
140 {
141   PROP_0,
142   PROP_SHARED,
143   PROP_SUSPEND_MODE,
144   PROP_REUSABLE,
145   PROP_PROFILES,
146   PROP_PROTOCOLS,
147   PROP_EOS_SHUTDOWN,
148   PROP_BUFFER_SIZE,
149   PROP_ELEMENT,
150   PROP_TIME_PROVIDER,
151   PROP_LAST
152 };
153
154 enum
155 {
156   SIGNAL_NEW_STREAM,
157   SIGNAL_REMOVED_STREAM,
158   SIGNAL_PREPARED,
159   SIGNAL_UNPREPARED,
160   SIGNAL_TARGET_STATE,
161   SIGNAL_NEW_STATE,
162   SIGNAL_LAST
163 };
164
165 GST_DEBUG_CATEGORY_STATIC (rtsp_media_debug);
166 #define GST_CAT_DEFAULT rtsp_media_debug
167
168 static void gst_rtsp_media_get_property (GObject * object, guint propid,
169     GValue * value, GParamSpec * pspec);
170 static void gst_rtsp_media_set_property (GObject * object, guint propid,
171     const GValue * value, GParamSpec * pspec);
172 static void gst_rtsp_media_finalize (GObject * obj);
173
174 static gboolean default_handle_message (GstRTSPMedia * media,
175     GstMessage * message);
176 static void finish_unprepare (GstRTSPMedia * media);
177 static gboolean default_prepare (GstRTSPMedia * media, GstRTSPThread * thread);
178 static gboolean default_unprepare (GstRTSPMedia * media);
179 static gboolean default_convert_range (GstRTSPMedia * media,
180     GstRTSPTimeRange * range, GstRTSPRangeUnit unit);
181 static gboolean default_query_position (GstRTSPMedia * media,
182     gint64 * position);
183 static gboolean default_query_stop (GstRTSPMedia * media, gint64 * stop);
184 static GstElement *default_create_rtpbin (GstRTSPMedia * media);
185 static gboolean default_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp,
186     GstSDPInfo * info);
187
188 static gboolean wait_preroll (GstRTSPMedia * media);
189
190 static guint gst_rtsp_media_signals[SIGNAL_LAST] = { 0 };
191
192 #define C_ENUM(v) ((gint) v)
193
194 #define GST_TYPE_RTSP_SUSPEND_MODE (gst_rtsp_suspend_mode_get_type())
195 GType
196 gst_rtsp_suspend_mode_get_type (void)
197 {
198   static gsize id = 0;
199   static const GEnumValue values[] = {
200     {C_ENUM (GST_RTSP_SUSPEND_MODE_NONE), "GST_RTSP_SUSPEND_MODE_NONE", "none"},
201     {C_ENUM (GST_RTSP_SUSPEND_MODE_PAUSE), "GST_RTSP_SUSPEND_MODE_PAUSE",
202         "pause"},
203     {C_ENUM (GST_RTSP_SUSPEND_MODE_RESET), "GST_RTSP_SUSPEND_MODE_RESET",
204         "reset"},
205     {0, NULL, NULL}
206   };
207
208   if (g_once_init_enter (&id)) {
209     GType tmp = g_enum_register_static ("GstRTSPSuspendMode", values);
210     g_once_init_leave (&id, tmp);
211   }
212   return (GType) id;
213 }
214
215 G_DEFINE_TYPE (GstRTSPMedia, gst_rtsp_media, G_TYPE_OBJECT);
216
217 static void
218 gst_rtsp_media_class_init (GstRTSPMediaClass * klass)
219 {
220   GObjectClass *gobject_class;
221
222   g_type_class_add_private (klass, sizeof (GstRTSPMediaPrivate));
223
224   gobject_class = G_OBJECT_CLASS (klass);
225
226   gobject_class->get_property = gst_rtsp_media_get_property;
227   gobject_class->set_property = gst_rtsp_media_set_property;
228   gobject_class->finalize = gst_rtsp_media_finalize;
229
230   g_object_class_install_property (gobject_class, PROP_SHARED,
231       g_param_spec_boolean ("shared", "Shared",
232           "If this media pipeline can be shared", DEFAULT_SHARED,
233           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
234
235   g_object_class_install_property (gobject_class, PROP_SUSPEND_MODE,
236       g_param_spec_enum ("suspend-mode", "Suspend Mode",
237           "How to suspend the media in PAUSED", GST_TYPE_RTSP_SUSPEND_MODE,
238           DEFAULT_SUSPEND_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
239
240   g_object_class_install_property (gobject_class, PROP_REUSABLE,
241       g_param_spec_boolean ("reusable", "Reusable",
242           "If this media pipeline can be reused after an unprepare",
243           DEFAULT_REUSABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
244
245   g_object_class_install_property (gobject_class, PROP_PROFILES,
246       g_param_spec_flags ("profiles", "Profiles",
247           "Allowed transfer profiles", GST_TYPE_RTSP_PROFILE,
248           DEFAULT_PROFILES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
249
250   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
251       g_param_spec_flags ("protocols", "Protocols",
252           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
253           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
254
255   g_object_class_install_property (gobject_class, PROP_EOS_SHUTDOWN,
256       g_param_spec_boolean ("eos-shutdown", "EOS Shutdown",
257           "Send an EOS event to the pipeline before unpreparing",
258           DEFAULT_EOS_SHUTDOWN, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
259
260   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
261       g_param_spec_uint ("buffer-size", "Buffer Size",
262           "The kernel UDP buffer size to use", 0, G_MAXUINT,
263           DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
264
265   g_object_class_install_property (gobject_class, PROP_ELEMENT,
266       g_param_spec_object ("element", "The Element",
267           "The GstBin to use for streaming the media", GST_TYPE_ELEMENT,
268           G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE));
269
270   g_object_class_install_property (gobject_class, PROP_TIME_PROVIDER,
271       g_param_spec_boolean ("time-provider", "Time Provider",
272           "Use a NetTimeProvider for clients",
273           DEFAULT_TIME_PROVIDER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
274
275   gst_rtsp_media_signals[SIGNAL_NEW_STREAM] =
276       g_signal_new ("new-stream", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
277       G_STRUCT_OFFSET (GstRTSPMediaClass, new_stream), NULL, NULL,
278       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_RTSP_STREAM);
279
280   gst_rtsp_media_signals[SIGNAL_REMOVED_STREAM] =
281       g_signal_new ("removed-stream", G_TYPE_FROM_CLASS (klass),
282       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPMediaClass, removed_stream),
283       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
284       GST_TYPE_RTSP_STREAM);
285
286   gst_rtsp_media_signals[SIGNAL_PREPARED] =
287       g_signal_new ("prepared", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
288       G_STRUCT_OFFSET (GstRTSPMediaClass, prepared), NULL, NULL,
289       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
290
291   gst_rtsp_media_signals[SIGNAL_UNPREPARED] =
292       g_signal_new ("unprepared", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
293       G_STRUCT_OFFSET (GstRTSPMediaClass, unprepared), NULL, NULL,
294       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
295
296   gst_rtsp_media_signals[SIGNAL_TARGET_STATE] =
297       g_signal_new ("target-state", G_TYPE_FROM_CLASS (klass),
298       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPMediaClass, new_state), NULL,
299       NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT);
300
301   gst_rtsp_media_signals[SIGNAL_NEW_STATE] =
302       g_signal_new ("new-state", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
303       G_STRUCT_OFFSET (GstRTSPMediaClass, new_state), NULL, NULL,
304       g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT);
305
306   GST_DEBUG_CATEGORY_INIT (rtsp_media_debug, "rtspmedia", 0, "GstRTSPMedia");
307
308   klass->handle_message = default_handle_message;
309   klass->prepare = default_prepare;
310   klass->unprepare = default_unprepare;
311   klass->convert_range = default_convert_range;
312   klass->query_position = default_query_position;
313   klass->query_stop = default_query_stop;
314   klass->create_rtpbin = default_create_rtpbin;
315   klass->setup_sdp = default_setup_sdp;
316 }
317
318 static void
319 gst_rtsp_media_init (GstRTSPMedia * media)
320 {
321   GstRTSPMediaPrivate *priv = GST_RTSP_MEDIA_GET_PRIVATE (media);
322
323   media->priv = priv;
324
325   priv->streams = g_ptr_array_new_with_free_func (g_object_unref);
326   g_mutex_init (&priv->lock);
327   g_cond_init (&priv->cond);
328   g_rec_mutex_init (&priv->state_lock);
329
330   priv->shared = DEFAULT_SHARED;
331   priv->suspend_mode = DEFAULT_SUSPEND_MODE;
332   priv->reusable = DEFAULT_REUSABLE;
333   priv->profiles = DEFAULT_PROFILES;
334   priv->protocols = DEFAULT_PROTOCOLS;
335   priv->eos_shutdown = DEFAULT_EOS_SHUTDOWN;
336   priv->buffer_size = DEFAULT_BUFFER_SIZE;
337   priv->time_provider = DEFAULT_TIME_PROVIDER;
338 }
339
340 static void
341 gst_rtsp_media_finalize (GObject * obj)
342 {
343   GstRTSPMediaPrivate *priv;
344   GstRTSPMedia *media;
345
346   media = GST_RTSP_MEDIA (obj);
347   priv = media->priv;
348
349   GST_INFO ("finalize media %p", media);
350
351   if (priv->permissions)
352     gst_rtsp_permissions_unref (priv->permissions);
353
354   g_ptr_array_unref (priv->streams);
355
356   g_list_free_full (priv->dynamic, gst_object_unref);
357
358   if (priv->pipeline)
359     gst_object_unref (priv->pipeline);
360   if (priv->nettime)
361     gst_object_unref (priv->nettime);
362   gst_object_unref (priv->element);
363   if (priv->pool)
364     g_object_unref (priv->pool);
365   g_mutex_clear (&priv->lock);
366   g_cond_clear (&priv->cond);
367   g_rec_mutex_clear (&priv->state_lock);
368
369   G_OBJECT_CLASS (gst_rtsp_media_parent_class)->finalize (obj);
370 }
371
372 static void
373 gst_rtsp_media_get_property (GObject * object, guint propid,
374     GValue * value, GParamSpec * pspec)
375 {
376   GstRTSPMedia *media = GST_RTSP_MEDIA (object);
377
378   switch (propid) {
379     case PROP_ELEMENT:
380       g_value_set_object (value, media->priv->element);
381       break;
382     case PROP_SHARED:
383       g_value_set_boolean (value, gst_rtsp_media_is_shared (media));
384       break;
385     case PROP_SUSPEND_MODE:
386       g_value_set_enum (value, gst_rtsp_media_get_suspend_mode (media));
387       break;
388     case PROP_REUSABLE:
389       g_value_set_boolean (value, gst_rtsp_media_is_reusable (media));
390       break;
391     case PROP_PROFILES:
392       g_value_set_flags (value, gst_rtsp_media_get_profiles (media));
393       break;
394     case PROP_PROTOCOLS:
395       g_value_set_flags (value, gst_rtsp_media_get_protocols (media));
396       break;
397     case PROP_EOS_SHUTDOWN:
398       g_value_set_boolean (value, gst_rtsp_media_is_eos_shutdown (media));
399       break;
400     case PROP_BUFFER_SIZE:
401       g_value_set_uint (value, gst_rtsp_media_get_buffer_size (media));
402       break;
403     case PROP_TIME_PROVIDER:
404       g_value_set_boolean (value, gst_rtsp_media_is_time_provider (media));
405       break;
406     default:
407       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
408   }
409 }
410
411 static void
412 gst_rtsp_media_set_property (GObject * object, guint propid,
413     const GValue * value, GParamSpec * pspec)
414 {
415   GstRTSPMedia *media = GST_RTSP_MEDIA (object);
416
417   switch (propid) {
418     case PROP_ELEMENT:
419       media->priv->element = g_value_get_object (value);
420       gst_object_ref_sink (media->priv->element);
421       break;
422     case PROP_SHARED:
423       gst_rtsp_media_set_shared (media, g_value_get_boolean (value));
424       break;
425     case PROP_SUSPEND_MODE:
426       gst_rtsp_media_set_suspend_mode (media, g_value_get_enum (value));
427       break;
428     case PROP_REUSABLE:
429       gst_rtsp_media_set_reusable (media, g_value_get_boolean (value));
430       break;
431     case PROP_PROFILES:
432       gst_rtsp_media_set_profiles (media, g_value_get_flags (value));
433       break;
434     case PROP_PROTOCOLS:
435       gst_rtsp_media_set_protocols (media, g_value_get_flags (value));
436       break;
437     case PROP_EOS_SHUTDOWN:
438       gst_rtsp_media_set_eos_shutdown (media, g_value_get_boolean (value));
439       break;
440     case PROP_BUFFER_SIZE:
441       gst_rtsp_media_set_buffer_size (media, g_value_get_uint (value));
442       break;
443     case PROP_TIME_PROVIDER:
444       gst_rtsp_media_use_time_provider (media, g_value_get_boolean (value));
445       break;
446     default:
447       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
448   }
449 }
450
451 static gboolean
452 default_query_position (GstRTSPMedia * media, gint64 * position)
453 {
454   return gst_element_query_position (media->priv->pipeline, GST_FORMAT_TIME,
455       position);
456 }
457
458 static gboolean
459 default_query_stop (GstRTSPMedia * media, gint64 * stop)
460 {
461   GstQuery *query;
462   gboolean res;
463
464   query = gst_query_new_segment (GST_FORMAT_TIME);
465   if ((res = gst_element_query (media->priv->pipeline, query))) {
466     GstFormat format;
467     gst_query_parse_segment (query, NULL, &format, NULL, stop);
468     if (format != GST_FORMAT_TIME)
469       *stop = -1;
470   }
471   gst_query_unref (query);
472   return res;
473 }
474
475 static GstElement *
476 default_create_rtpbin (GstRTSPMedia * media)
477 {
478   GstElement *rtpbin;
479
480   rtpbin = gst_element_factory_make ("rtpbin", NULL);
481
482   return rtpbin;
483 }
484
485 /* must be called with state lock */
486 static void
487 collect_media_stats (GstRTSPMedia * media)
488 {
489   GstRTSPMediaPrivate *priv = media->priv;
490   gint64 position, stop;
491
492   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
493       priv->status != GST_RTSP_MEDIA_STATUS_PREPARING)
494     return;
495
496   priv->range.unit = GST_RTSP_RANGE_NPT;
497
498   GST_INFO ("collect media stats");
499
500   if (priv->is_live) {
501     priv->range.min.type = GST_RTSP_TIME_NOW;
502     priv->range.min.seconds = -1;
503     priv->range_start = -1;
504     priv->range.max.type = GST_RTSP_TIME_END;
505     priv->range.max.seconds = -1;
506     priv->range_stop = -1;
507   } else {
508     GstRTSPMediaClass *klass;
509     gboolean ret;
510
511     klass = GST_RTSP_MEDIA_GET_CLASS (media);
512
513     /* get the position */
514     ret = FALSE;
515     if (klass->query_position)
516       ret = klass->query_position (media, &position);
517
518     if (!ret) {
519       GST_INFO ("position query failed");
520       position = 0;
521     }
522
523     /* get the current segment stop */
524     ret = FALSE;
525     if (klass->query_stop)
526       ret = klass->query_stop (media, &stop);
527
528     if (!ret) {
529       GST_INFO ("stop query failed");
530       stop = -1;
531     }
532
533     GST_INFO ("stats: position %" GST_TIME_FORMAT ", stop %"
534         GST_TIME_FORMAT, GST_TIME_ARGS (position), GST_TIME_ARGS (stop));
535
536     if (position == -1) {
537       priv->range.min.type = GST_RTSP_TIME_NOW;
538       priv->range.min.seconds = -1;
539       priv->range_start = -1;
540     } else {
541       priv->range.min.type = GST_RTSP_TIME_SECONDS;
542       priv->range.min.seconds = ((gdouble) position) / GST_SECOND;
543       priv->range_start = position;
544     }
545     if (stop == -1) {
546       priv->range.max.type = GST_RTSP_TIME_END;
547       priv->range.max.seconds = -1;
548       priv->range_stop = -1;
549     } else {
550       priv->range.max.type = GST_RTSP_TIME_SECONDS;
551       priv->range.max.seconds = ((gdouble) stop) / GST_SECOND;
552       priv->range_stop = stop;
553     }
554   }
555 }
556
557 /**
558  * gst_rtsp_media_new:
559  * @element: (transfer full): a #GstElement
560  *
561  * Create a new #GstRTSPMedia instance. @element is the bin element that
562  * provides the different streams. The #GstRTSPMedia object contains the
563  * element to produce RTP data for one or more related (audio/video/..)
564  * streams.
565  *
566  * Ownership is taken of @element.
567  *
568  * Returns: (transfer full): a new #GstRTSPMedia object.
569  */
570 GstRTSPMedia *
571 gst_rtsp_media_new (GstElement * element)
572 {
573   GstRTSPMedia *result;
574
575   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
576
577   result = g_object_new (GST_TYPE_RTSP_MEDIA, "element", element, NULL);
578
579   return result;
580 }
581
582 /**
583  * gst_rtsp_media_get_element:
584  * @media: a #GstRTSPMedia
585  *
586  * Get the element that was used when constructing @media.
587  *
588  * Returns: (transfer full): a #GstElement. Unref after usage.
589  */
590 GstElement *
591 gst_rtsp_media_get_element (GstRTSPMedia * media)
592 {
593   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
594
595   return gst_object_ref (media->priv->element);
596 }
597
598 /**
599  * gst_rtsp_media_take_pipeline:
600  * @media: a #GstRTSPMedia
601  * @pipeline: (transfer full): a #GstPipeline
602  *
603  * Set @pipeline as the #GstPipeline for @media. Ownership is
604  * taken of @pipeline.
605  */
606 void
607 gst_rtsp_media_take_pipeline (GstRTSPMedia * media, GstPipeline * pipeline)
608 {
609   GstRTSPMediaPrivate *priv;
610   GstElement *old;
611   GstNetTimeProvider *nettime;
612
613   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
614   g_return_if_fail (GST_IS_PIPELINE (pipeline));
615
616   priv = media->priv;
617
618   g_mutex_lock (&priv->lock);
619   old = priv->pipeline;
620   priv->pipeline = GST_ELEMENT_CAST (pipeline);
621   nettime = priv->nettime;
622   priv->nettime = NULL;
623   g_mutex_unlock (&priv->lock);
624
625   if (old)
626     gst_object_unref (old);
627
628   if (nettime)
629     gst_object_unref (nettime);
630
631   gst_bin_add (GST_BIN_CAST (pipeline), priv->element);
632 }
633
634 /**
635  * gst_rtsp_media_set_permissions:
636  * @media: a #GstRTSPMedia
637  * @permissions: (transfer none): a #GstRTSPPermissions
638  *
639  * Set @permissions on @media.
640  */
641 void
642 gst_rtsp_media_set_permissions (GstRTSPMedia * media,
643     GstRTSPPermissions * permissions)
644 {
645   GstRTSPMediaPrivate *priv;
646
647   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
648
649   priv = media->priv;
650
651   g_mutex_lock (&priv->lock);
652   if (priv->permissions)
653     gst_rtsp_permissions_unref (priv->permissions);
654   if ((priv->permissions = permissions))
655     gst_rtsp_permissions_ref (permissions);
656   g_mutex_unlock (&priv->lock);
657 }
658
659 /**
660  * gst_rtsp_media_get_permissions:
661  * @media: a #GstRTSPMedia
662  *
663  * Get the permissions object from @media.
664  *
665  * Returns: (transfer full): a #GstRTSPPermissions object, unref after usage.
666  */
667 GstRTSPPermissions *
668 gst_rtsp_media_get_permissions (GstRTSPMedia * media)
669 {
670   GstRTSPMediaPrivate *priv;
671   GstRTSPPermissions *result;
672
673   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
674
675   priv = media->priv;
676
677   g_mutex_lock (&priv->lock);
678   if ((result = priv->permissions))
679     gst_rtsp_permissions_ref (result);
680   g_mutex_unlock (&priv->lock);
681
682   return result;
683 }
684
685 /**
686  * gst_rtsp_media_set_suspend_mode:
687  * @media: a #GstRTSPMedia
688  * @mode: the new #GstRTSPSuspendMode
689  *
690  * Control how @ media will be suspended after the SDP has been generated and
691  * after a PAUSE request has been performed.
692  *
693  * Media must be unprepared when setting the suspend mode.
694  */
695 void
696 gst_rtsp_media_set_suspend_mode (GstRTSPMedia * media, GstRTSPSuspendMode mode)
697 {
698   GstRTSPMediaPrivate *priv;
699
700   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
701
702   priv = media->priv;
703
704   g_rec_mutex_lock (&priv->state_lock);
705   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED)
706     goto was_prepared;
707   priv->suspend_mode = mode;
708   g_rec_mutex_unlock (&priv->state_lock);
709
710   return;
711
712   /* ERRORS */
713 was_prepared:
714   {
715     GST_WARNING ("media %p was prepared", media);
716     g_rec_mutex_unlock (&priv->state_lock);
717   }
718 }
719
720 /**
721  * gst_rtsp_media_get_suspend_mode:
722  * @media: a #GstRTSPMedia
723  *
724  * Get how @media will be suspended.
725  *
726  * Returns: #GstRTSPSuspendMode.
727  */
728 GstRTSPSuspendMode
729 gst_rtsp_media_get_suspend_mode (GstRTSPMedia * media)
730 {
731   GstRTSPMediaPrivate *priv;
732   GstRTSPSuspendMode res;
733
734   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_RTSP_SUSPEND_MODE_NONE);
735
736   priv = media->priv;
737
738   g_rec_mutex_lock (&priv->state_lock);
739   res = priv->suspend_mode;
740   g_rec_mutex_unlock (&priv->state_lock);
741
742   return res;
743 }
744
745 /**
746  * gst_rtsp_media_set_shared:
747  * @media: a #GstRTSPMedia
748  * @shared: the new value
749  *
750  * Set or unset if the pipeline for @media can be shared will multiple clients.
751  * When @shared is %TRUE, client requests for this media will share the media
752  * pipeline.
753  */
754 void
755 gst_rtsp_media_set_shared (GstRTSPMedia * media, gboolean shared)
756 {
757   GstRTSPMediaPrivate *priv;
758
759   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
760
761   priv = media->priv;
762
763   g_mutex_lock (&priv->lock);
764   priv->shared = shared;
765   g_mutex_unlock (&priv->lock);
766 }
767
768 /**
769  * gst_rtsp_media_is_shared:
770  * @media: a #GstRTSPMedia
771  *
772  * Check if the pipeline for @media can be shared between multiple clients.
773  *
774  * Returns: %TRUE if the media can be shared between clients.
775  */
776 gboolean
777 gst_rtsp_media_is_shared (GstRTSPMedia * media)
778 {
779   GstRTSPMediaPrivate *priv;
780   gboolean res;
781
782   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
783
784   priv = media->priv;
785
786   g_mutex_lock (&priv->lock);
787   res = priv->shared;
788   g_mutex_unlock (&priv->lock);
789
790   return res;
791 }
792
793 /**
794  * gst_rtsp_media_set_reusable:
795  * @media: a #GstRTSPMedia
796  * @reusable: the new value
797  *
798  * Set or unset if the pipeline for @media can be reused after the pipeline has
799  * been unprepared.
800  */
801 void
802 gst_rtsp_media_set_reusable (GstRTSPMedia * media, gboolean reusable)
803 {
804   GstRTSPMediaPrivate *priv;
805
806   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
807
808   priv = media->priv;
809
810   g_mutex_lock (&priv->lock);
811   priv->reusable = reusable;
812   g_mutex_unlock (&priv->lock);
813 }
814
815 /**
816  * gst_rtsp_media_is_reusable:
817  * @media: a #GstRTSPMedia
818  *
819  * Check if the pipeline for @media can be reused after an unprepare.
820  *
821  * Returns: %TRUE if the media can be reused
822  */
823 gboolean
824 gst_rtsp_media_is_reusable (GstRTSPMedia * media)
825 {
826   GstRTSPMediaPrivate *priv;
827   gboolean res;
828
829   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
830
831   priv = media->priv;
832
833   g_mutex_lock (&priv->lock);
834   res = priv->reusable;
835   g_mutex_unlock (&priv->lock);
836
837   return res;
838 }
839
840 static void
841 do_set_profiles (GstRTSPStream * stream, GstRTSPProfile * profiles)
842 {
843   gst_rtsp_stream_set_profiles (stream, *profiles);
844 }
845
846 /**
847  * gst_rtsp_media_set_profiles:
848  * @media: a #GstRTSPMedia
849  * @profiles: the new flags
850  *
851  * Configure the allowed lower transport for @media.
852  */
853 void
854 gst_rtsp_media_set_profiles (GstRTSPMedia * media, GstRTSPProfile profiles)
855 {
856   GstRTSPMediaPrivate *priv;
857
858   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
859
860   priv = media->priv;
861
862   g_mutex_lock (&priv->lock);
863   priv->profiles = profiles;
864   g_ptr_array_foreach (priv->streams, (GFunc) do_set_profiles, &profiles);
865   g_mutex_unlock (&priv->lock);
866 }
867
868 /**
869  * gst_rtsp_media_get_profiles:
870  * @media: a #GstRTSPMedia
871  *
872  * Get the allowed profiles of @media.
873  *
874  * Returns: a #GstRTSPProfile
875  */
876 GstRTSPProfile
877 gst_rtsp_media_get_profiles (GstRTSPMedia * media)
878 {
879   GstRTSPMediaPrivate *priv;
880   GstRTSPProfile res;
881
882   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_RTSP_PROFILE_UNKNOWN);
883
884   priv = media->priv;
885
886   g_mutex_lock (&priv->lock);
887   res = priv->profiles;
888   g_mutex_unlock (&priv->lock);
889
890   return res;
891 }
892
893 static void
894 do_set_protocols (GstRTSPStream * stream, GstRTSPLowerTrans * protocols)
895 {
896   gst_rtsp_stream_set_protocols (stream, *protocols);
897 }
898
899 /**
900  * gst_rtsp_media_set_protocols:
901  * @media: a #GstRTSPMedia
902  * @protocols: the new flags
903  *
904  * Configure the allowed lower transport for @media.
905  */
906 void
907 gst_rtsp_media_set_protocols (GstRTSPMedia * media, GstRTSPLowerTrans protocols)
908 {
909   GstRTSPMediaPrivate *priv;
910
911   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
912
913   priv = media->priv;
914
915   g_mutex_lock (&priv->lock);
916   priv->protocols = protocols;
917   g_ptr_array_foreach (priv->streams, (GFunc) do_set_protocols, &protocols);
918   g_mutex_unlock (&priv->lock);
919 }
920
921 /**
922  * gst_rtsp_media_get_protocols:
923  * @media: a #GstRTSPMedia
924  *
925  * Get the allowed protocols of @media.
926  *
927  * Returns: a #GstRTSPLowerTrans
928  */
929 GstRTSPLowerTrans
930 gst_rtsp_media_get_protocols (GstRTSPMedia * media)
931 {
932   GstRTSPMediaPrivate *priv;
933   GstRTSPLowerTrans res;
934
935   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media),
936       GST_RTSP_LOWER_TRANS_UNKNOWN);
937
938   priv = media->priv;
939
940   g_mutex_lock (&priv->lock);
941   res = priv->protocols;
942   g_mutex_unlock (&priv->lock);
943
944   return res;
945 }
946
947 /**
948  * gst_rtsp_media_set_eos_shutdown:
949  * @media: a #GstRTSPMedia
950  * @eos_shutdown: the new value
951  *
952  * Set or unset if an EOS event will be sent to the pipeline for @media before
953  * it is unprepared.
954  */
955 void
956 gst_rtsp_media_set_eos_shutdown (GstRTSPMedia * media, gboolean eos_shutdown)
957 {
958   GstRTSPMediaPrivate *priv;
959
960   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
961
962   priv = media->priv;
963
964   g_mutex_lock (&priv->lock);
965   priv->eos_shutdown = eos_shutdown;
966   g_mutex_unlock (&priv->lock);
967 }
968
969 /**
970  * gst_rtsp_media_is_eos_shutdown:
971  * @media: a #GstRTSPMedia
972  *
973  * Check if the pipeline for @media will send an EOS down the pipeline before
974  * unpreparing.
975  *
976  * Returns: %TRUE if the media will send EOS before unpreparing.
977  */
978 gboolean
979 gst_rtsp_media_is_eos_shutdown (GstRTSPMedia * media)
980 {
981   GstRTSPMediaPrivate *priv;
982   gboolean res;
983
984   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
985
986   priv = media->priv;
987
988   g_mutex_lock (&priv->lock);
989   res = priv->eos_shutdown;
990   g_mutex_unlock (&priv->lock);
991
992   return res;
993 }
994
995 /**
996  * gst_rtsp_media_set_buffer_size:
997  * @media: a #GstRTSPMedia
998  * @size: the new value
999  *
1000  * Set the kernel UDP buffer size.
1001  */
1002 void
1003 gst_rtsp_media_set_buffer_size (GstRTSPMedia * media, guint size)
1004 {
1005   GstRTSPMediaPrivate *priv;
1006
1007   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1008
1009   GST_LOG_OBJECT (media, "set buffer size %u", size);
1010
1011   priv = media->priv;
1012
1013   g_mutex_lock (&priv->lock);
1014   priv->buffer_size = size;
1015   g_mutex_unlock (&priv->lock);
1016 }
1017
1018 /**
1019  * gst_rtsp_media_get_buffer_size:
1020  * @media: a #GstRTSPMedia
1021  *
1022  * Get the kernel UDP buffer size.
1023  *
1024  * Returns: the kernel UDP buffer size.
1025  */
1026 guint
1027 gst_rtsp_media_get_buffer_size (GstRTSPMedia * media)
1028 {
1029   GstRTSPMediaPrivate *priv;
1030   guint res;
1031
1032   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1033
1034   priv = media->priv;
1035
1036   g_mutex_unlock (&priv->lock);
1037   res = priv->buffer_size;
1038   g_mutex_unlock (&priv->lock);
1039
1040   return res;
1041 }
1042
1043 /**
1044  * gst_rtsp_media_use_time_provider:
1045  * @media: a #GstRTSPMedia
1046  * @time_provider: if a #GstNetTimeProvider should be used
1047  *
1048  * Set @media to provide a #GstNetTimeProvider.
1049  */
1050 void
1051 gst_rtsp_media_use_time_provider (GstRTSPMedia * media, gboolean time_provider)
1052 {
1053   GstRTSPMediaPrivate *priv;
1054
1055   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1056
1057   priv = media->priv;
1058
1059   g_mutex_lock (&priv->lock);
1060   priv->time_provider = time_provider;
1061   g_mutex_unlock (&priv->lock);
1062 }
1063
1064 /**
1065  * gst_rtsp_media_is_time_provider:
1066  * @media: a #GstRTSPMedia
1067  *
1068  * Check if @media can provide a #GstNetTimeProvider for its pipeline clock.
1069  *
1070  * Use gst_rtsp_media_get_time_provider() to get the network clock.
1071  *
1072  * Returns: %TRUE if @media can provide a #GstNetTimeProvider.
1073  */
1074 gboolean
1075 gst_rtsp_media_is_time_provider (GstRTSPMedia * media)
1076 {
1077   GstRTSPMediaPrivate *priv;
1078   gboolean res;
1079
1080   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1081
1082   priv = media->priv;
1083
1084   g_mutex_unlock (&priv->lock);
1085   res = priv->time_provider;
1086   g_mutex_unlock (&priv->lock);
1087
1088   return res;
1089 }
1090
1091 /**
1092  * gst_rtsp_media_set_address_pool:
1093  * @media: a #GstRTSPMedia
1094  * @pool: (transfer none): a #GstRTSPAddressPool
1095  *
1096  * configure @pool to be used as the address pool of @media.
1097  */
1098 void
1099 gst_rtsp_media_set_address_pool (GstRTSPMedia * media,
1100     GstRTSPAddressPool * pool)
1101 {
1102   GstRTSPMediaPrivate *priv;
1103   GstRTSPAddressPool *old;
1104
1105   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1106
1107   priv = media->priv;
1108
1109   GST_LOG_OBJECT (media, "set address pool %p", pool);
1110
1111   g_mutex_lock (&priv->lock);
1112   if ((old = priv->pool) != pool)
1113     priv->pool = pool ? g_object_ref (pool) : NULL;
1114   else
1115     old = NULL;
1116   g_ptr_array_foreach (priv->streams, (GFunc) gst_rtsp_stream_set_address_pool,
1117       pool);
1118   g_mutex_unlock (&priv->lock);
1119
1120   if (old)
1121     g_object_unref (old);
1122 }
1123
1124 /**
1125  * gst_rtsp_media_get_address_pool:
1126  * @media: a #GstRTSPMedia
1127  *
1128  * Get the #GstRTSPAddressPool used as the address pool of @media.
1129  *
1130  * Returns: (transfer full): the #GstRTSPAddressPool of @media. g_object_unref() after
1131  * usage.
1132  */
1133 GstRTSPAddressPool *
1134 gst_rtsp_media_get_address_pool (GstRTSPMedia * media)
1135 {
1136   GstRTSPMediaPrivate *priv;
1137   GstRTSPAddressPool *result;
1138
1139   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1140
1141   priv = media->priv;
1142
1143   g_mutex_lock (&priv->lock);
1144   if ((result = priv->pool))
1145     g_object_ref (result);
1146   g_mutex_unlock (&priv->lock);
1147
1148   return result;
1149 }
1150
1151 /**
1152  * gst_rtsp_media_collect_streams:
1153  * @media: a #GstRTSPMedia
1154  *
1155  * Find all payloader elements, they should be named pay\%d in the
1156  * element of @media, and create #GstRTSPStreams for them.
1157  *
1158  * Collect all dynamic elements, named dynpay\%d, and add them to
1159  * the list of dynamic elements.
1160  */
1161 void
1162 gst_rtsp_media_collect_streams (GstRTSPMedia * media)
1163 {
1164   GstRTSPMediaPrivate *priv;
1165   GstElement *element, *elem;
1166   GstPad *pad;
1167   gint i;
1168   gboolean have_elem;
1169
1170   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1171
1172   priv = media->priv;
1173   element = priv->element;
1174
1175   have_elem = TRUE;
1176   for (i = 0; have_elem; i++) {
1177     gchar *name;
1178
1179     have_elem = FALSE;
1180
1181     name = g_strdup_printf ("pay%d", i);
1182     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
1183       GST_INFO ("found stream %d with payloader %p", i, elem);
1184
1185       /* take the pad of the payloader */
1186       pad = gst_element_get_static_pad (elem, "src");
1187       /* create the stream */
1188       gst_rtsp_media_create_stream (media, elem, pad);
1189       gst_object_unref (pad);
1190       gst_object_unref (elem);
1191
1192       have_elem = TRUE;
1193     }
1194     g_free (name);
1195
1196     name = g_strdup_printf ("dynpay%d", i);
1197     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
1198       /* a stream that will dynamically create pads to provide RTP packets */
1199       GST_INFO ("found dynamic element %d, %p", i, elem);
1200
1201       g_mutex_lock (&priv->lock);
1202       priv->dynamic = g_list_prepend (priv->dynamic, elem);
1203       g_mutex_unlock (&priv->lock);
1204
1205       have_elem = TRUE;
1206     }
1207     g_free (name);
1208   }
1209 }
1210
1211 /**
1212  * gst_rtsp_media_create_stream:
1213  * @media: a #GstRTSPMedia
1214  * @payloader: a #GstElement
1215  * @srcpad: a source #GstPad
1216  *
1217  * Create a new stream in @media that provides RTP data on @srcpad.
1218  * @srcpad should be a pad of an element inside @media->element.
1219  *
1220  * Returns: (transfer none): a new #GstRTSPStream that remains valid for as long
1221  * as @media exists.
1222  */
1223 GstRTSPStream *
1224 gst_rtsp_media_create_stream (GstRTSPMedia * media, GstElement * payloader,
1225     GstPad * pad)
1226 {
1227   GstRTSPMediaPrivate *priv;
1228   GstRTSPStream *stream;
1229   GstPad *srcpad;
1230   gchar *name;
1231   gint idx;
1232
1233   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1234   g_return_val_if_fail (GST_IS_ELEMENT (payloader), NULL);
1235   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
1236   g_return_val_if_fail (GST_PAD_IS_SRC (pad), NULL);
1237
1238   priv = media->priv;
1239
1240   g_mutex_lock (&priv->lock);
1241   idx = priv->streams->len;
1242
1243   GST_DEBUG ("media %p: creating stream with index %d", media, idx);
1244
1245   name = g_strdup_printf ("src_%u", idx);
1246   srcpad = gst_ghost_pad_new (name, pad);
1247   gst_pad_set_active (srcpad, TRUE);
1248   gst_element_add_pad (priv->element, srcpad);
1249   g_free (name);
1250
1251   stream = gst_rtsp_stream_new (idx, payloader, srcpad);
1252   if (priv->pool)
1253     gst_rtsp_stream_set_address_pool (stream, priv->pool);
1254   gst_rtsp_stream_set_profiles (stream, priv->profiles);
1255   gst_rtsp_stream_set_protocols (stream, priv->protocols);
1256
1257   g_ptr_array_add (priv->streams, stream);
1258   g_mutex_unlock (&priv->lock);
1259
1260   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STREAM], 0, stream,
1261       NULL);
1262
1263   return stream;
1264 }
1265
1266 static void
1267 gst_rtsp_media_remove_stream (GstRTSPMedia * media, GstRTSPStream * stream)
1268 {
1269   GstRTSPMediaPrivate *priv;
1270   GstPad *srcpad;
1271
1272   priv = media->priv;
1273
1274   g_mutex_lock (&priv->lock);
1275   /* remove the ghostpad */
1276   srcpad = gst_rtsp_stream_get_srcpad (stream);
1277   gst_element_remove_pad (priv->element, srcpad);
1278   gst_object_unref (srcpad);
1279   /* now remove the stream */
1280   g_object_ref (stream);
1281   g_ptr_array_remove (priv->streams, stream);
1282   g_mutex_unlock (&priv->lock);
1283
1284   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_REMOVED_STREAM], 0,
1285       stream, NULL);
1286
1287   g_object_unref (stream);
1288 }
1289
1290 /**
1291  * gst_rtsp_media_n_streams:
1292  * @media: a #GstRTSPMedia
1293  *
1294  * Get the number of streams in this media.
1295  *
1296  * Returns: The number of streams.
1297  */
1298 guint
1299 gst_rtsp_media_n_streams (GstRTSPMedia * media)
1300 {
1301   GstRTSPMediaPrivate *priv;
1302   guint res;
1303
1304   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), 0);
1305
1306   priv = media->priv;
1307
1308   g_mutex_lock (&priv->lock);
1309   res = priv->streams->len;
1310   g_mutex_unlock (&priv->lock);
1311
1312   return res;
1313 }
1314
1315 /**
1316  * gst_rtsp_media_get_stream:
1317  * @media: a #GstRTSPMedia
1318  * @idx: the stream index
1319  *
1320  * Retrieve the stream with index @idx from @media.
1321  *
1322  * Returns: (transfer none): the #GstRTSPStream at index @idx or %NULL when a stream with
1323  * that index did not exist.
1324  */
1325 GstRTSPStream *
1326 gst_rtsp_media_get_stream (GstRTSPMedia * media, guint idx)
1327 {
1328   GstRTSPMediaPrivate *priv;
1329   GstRTSPStream *res;
1330
1331   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1332
1333   priv = media->priv;
1334
1335   g_mutex_lock (&priv->lock);
1336   if (idx < priv->streams->len)
1337     res = g_ptr_array_index (priv->streams, idx);
1338   else
1339     res = NULL;
1340   g_mutex_unlock (&priv->lock);
1341
1342   return res;
1343 }
1344
1345 /**
1346  * gst_rtsp_media_find_stream:
1347  * @media: a #GstRTSPMedia
1348  * @control: the control of the stream
1349  *
1350  * Find a stream in @media with @control as the control uri.
1351  *
1352  * Returns: (transfer none): the #GstRTSPStream with control uri @control
1353  * or %NULL when a stream with that control did not exist.
1354  */
1355 GstRTSPStream *
1356 gst_rtsp_media_find_stream (GstRTSPMedia * media, const gchar * control)
1357 {
1358   GstRTSPMediaPrivate *priv;
1359   GstRTSPStream *res;
1360   gint i;
1361
1362   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1363   g_return_val_if_fail (control != NULL, NULL);
1364
1365   priv = media->priv;
1366
1367   res = NULL;
1368
1369   g_mutex_lock (&priv->lock);
1370   for (i = 0; i < priv->streams->len; i++) {
1371     GstRTSPStream *test;
1372
1373     test = g_ptr_array_index (priv->streams, i);
1374     if (gst_rtsp_stream_has_control (test, control)) {
1375       res = test;
1376       break;
1377     }
1378   }
1379   g_mutex_unlock (&priv->lock);
1380
1381   return res;
1382 }
1383
1384 /* called with state-lock */
1385 static gboolean
1386 default_convert_range (GstRTSPMedia * media, GstRTSPTimeRange * range,
1387     GstRTSPRangeUnit unit)
1388 {
1389   return gst_rtsp_range_convert_units (range, unit);
1390 }
1391
1392 /**
1393  * gst_rtsp_media_get_range_string:
1394  * @media: a #GstRTSPMedia
1395  * @play: for the PLAY request
1396  * @unit: the unit to use for the string
1397  *
1398  * Get the current range as a string. @media must be prepared with
1399  * gst_rtsp_media_prepare ().
1400  *
1401  * Returns: (transfer full): The range as a string, g_free() after usage.
1402  */
1403 gchar *
1404 gst_rtsp_media_get_range_string (GstRTSPMedia * media, gboolean play,
1405     GstRTSPRangeUnit unit)
1406 {
1407   GstRTSPMediaClass *klass;
1408   GstRTSPMediaPrivate *priv;
1409   gchar *result;
1410   GstRTSPTimeRange range;
1411
1412   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1413   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1414   g_return_val_if_fail (klass->convert_range != NULL, FALSE);
1415
1416   priv = media->priv;
1417
1418   g_rec_mutex_lock (&priv->state_lock);
1419   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
1420       priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
1421     goto not_prepared;
1422
1423   g_mutex_lock (&priv->lock);
1424
1425   /* Update the range value with current position/duration */
1426   collect_media_stats (media);
1427
1428   /* make copy */
1429   range = priv->range;
1430
1431   if (!play && priv->n_active > 0) {
1432     range.min.type = GST_RTSP_TIME_NOW;
1433     range.min.seconds = -1;
1434   }
1435   g_mutex_unlock (&priv->lock);
1436   g_rec_mutex_unlock (&priv->state_lock);
1437
1438   if (!klass->convert_range (media, &range, unit))
1439     goto conversion_failed;
1440
1441   result = gst_rtsp_range_to_string (&range);
1442
1443   return result;
1444
1445   /* ERRORS */
1446 not_prepared:
1447   {
1448     GST_WARNING ("media %p was not prepared", media);
1449     g_rec_mutex_unlock (&priv->state_lock);
1450     return NULL;
1451   }
1452 conversion_failed:
1453   {
1454     GST_WARNING ("range conversion to unit %d failed", unit);
1455     return NULL;
1456   }
1457 }
1458
1459 static void
1460 stream_update_blocked (GstRTSPStream * stream, GstRTSPMedia * media)
1461 {
1462   gst_rtsp_stream_set_blocked (stream, media->priv->blocked);
1463 }
1464
1465 static void
1466 media_streams_set_blocked (GstRTSPMedia * media, gboolean blocked)
1467 {
1468   GstRTSPMediaPrivate *priv = media->priv;
1469
1470   GST_DEBUG ("media %p set blocked %d", media, blocked);
1471   priv->blocked = blocked;
1472   g_ptr_array_foreach (priv->streams, (GFunc) stream_update_blocked, media);
1473 }
1474
1475 static void
1476 gst_rtsp_media_set_status (GstRTSPMedia * media, GstRTSPMediaStatus status)
1477 {
1478   GstRTSPMediaPrivate *priv = media->priv;
1479
1480   g_mutex_lock (&priv->lock);
1481   priv->status = status;
1482   GST_DEBUG ("setting new status to %d", status);
1483   g_cond_broadcast (&priv->cond);
1484   g_mutex_unlock (&priv->lock);
1485 }
1486
1487 /**
1488  * gst_rtsp_media_get_status:
1489  * @media: a #GstRTSPMedia
1490  *
1491  * Get the status of @media. When @media is busy preparing, this function waits
1492  * until @media is prepared or in error.
1493  *
1494  * Returns: the status of @media.
1495  */
1496 GstRTSPMediaStatus
1497 gst_rtsp_media_get_status (GstRTSPMedia * media)
1498 {
1499   GstRTSPMediaPrivate *priv = media->priv;
1500   GstRTSPMediaStatus result;
1501   gint64 end_time;
1502
1503   g_mutex_lock (&priv->lock);
1504   end_time = g_get_monotonic_time () + 20 * G_TIME_SPAN_SECOND;
1505   /* while we are preparing, wait */
1506   while (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING) {
1507     GST_DEBUG ("waiting for status change");
1508     if (!g_cond_wait_until (&priv->cond, &priv->lock, end_time)) {
1509       GST_DEBUG ("timeout, assuming error status");
1510       priv->status = GST_RTSP_MEDIA_STATUS_ERROR;
1511     }
1512   }
1513   /* could be success or error */
1514   result = priv->status;
1515   GST_DEBUG ("got status %d", result);
1516   g_mutex_unlock (&priv->lock);
1517
1518   return result;
1519 }
1520
1521 /**
1522  * gst_rtsp_media_seek:
1523  * @media: a #GstRTSPMedia
1524  * @range: (transfer none): a #GstRTSPTimeRange
1525  *
1526  * Seek the pipeline of @media to @range. @media must be prepared with
1527  * gst_rtsp_media_prepare().
1528  *
1529  * Returns: %TRUE on success.
1530  */
1531 gboolean
1532 gst_rtsp_media_seek (GstRTSPMedia * media, GstRTSPTimeRange * range)
1533 {
1534   GstRTSPMediaClass *klass;
1535   GstRTSPMediaPrivate *priv;
1536   gboolean res;
1537   GstClockTime start, stop;
1538   GstSeekType start_type, stop_type;
1539   GstQuery *query;
1540
1541   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1542
1543   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1544   g_return_val_if_fail (range != NULL, FALSE);
1545   g_return_val_if_fail (klass->convert_range != NULL, FALSE);
1546
1547   priv = media->priv;
1548
1549   g_rec_mutex_lock (&priv->state_lock);
1550   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
1551     goto not_prepared;
1552
1553   /* Update the seekable state of the pipeline in case it changed */
1554   query = gst_query_new_seeking (GST_FORMAT_TIME);
1555   if (gst_element_query (priv->pipeline, query)) {
1556     GstFormat format;
1557     gboolean seekable;
1558     gint64 start, end;
1559
1560     gst_query_parse_seeking (query, &format, &seekable, &start, &end);
1561     priv->seekable = seekable;
1562   }
1563   gst_query_unref (query);
1564
1565   if (!priv->seekable)
1566     goto not_seekable;
1567
1568   start_type = stop_type = GST_SEEK_TYPE_NONE;
1569
1570   if (!klass->convert_range (media, range, GST_RTSP_RANGE_NPT))
1571     goto not_supported;
1572   gst_rtsp_range_get_times (range, &start, &stop);
1573
1574   GST_INFO ("got %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1575       GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1576   GST_INFO ("current %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1577       GST_TIME_ARGS (priv->range_start), GST_TIME_ARGS (priv->range_stop));
1578
1579   if (start != GST_CLOCK_TIME_NONE)
1580     start_type = GST_SEEK_TYPE_SET;
1581
1582   if (priv->range_stop == stop)
1583     stop = GST_CLOCK_TIME_NONE;
1584   else if (stop != GST_CLOCK_TIME_NONE)
1585     stop_type = GST_SEEK_TYPE_SET;
1586
1587   if (start != GST_CLOCK_TIME_NONE || stop != GST_CLOCK_TIME_NONE) {
1588     GstSeekFlags flags;
1589
1590     GST_INFO ("seeking to %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1591         GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1592
1593     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
1594     if (priv->blocked)
1595       media_streams_set_blocked (media, TRUE);
1596
1597     /* depends on the current playing state of the pipeline. We might need to
1598      * queue this until we get EOS. */
1599     flags = GST_SEEK_FLAG_FLUSH;
1600
1601     /* if range start was not supplied we must continue from current position.
1602      * but since we're doing a flushing seek, let us query the current position
1603      * so we end up at exactly the same position after the seek. */
1604     if (range->min.type == GST_RTSP_TIME_END) { /* Yepp, that's right! */
1605       gint64 position;
1606       gboolean ret = FALSE;
1607
1608       if (klass->query_position)
1609         ret = klass->query_position (media, &position);
1610
1611       if (!ret) {
1612         GST_WARNING ("position query failed");
1613       } else {
1614         GST_DEBUG ("doing accurate seek to %" GST_TIME_FORMAT,
1615             GST_TIME_ARGS (position));
1616         start = position;
1617         start_type = GST_SEEK_TYPE_SET;
1618         flags |= GST_SEEK_FLAG_ACCURATE;
1619       }
1620     } else {
1621       /* only set keyframe flag when modifying start */
1622       if (start_type != GST_SEEK_TYPE_NONE)
1623         flags |= GST_SEEK_FLAG_KEY_UNIT;
1624     }
1625
1626     /* FIXME, we only do forwards */
1627     res = gst_element_seek (priv->pipeline, 1.0, GST_FORMAT_TIME,
1628         flags, start_type, start, stop_type, stop);
1629
1630     /* and block for the seek to complete */
1631     GST_INFO ("done seeking %d", res);
1632     g_rec_mutex_unlock (&priv->state_lock);
1633
1634     /* wait until pipeline is prerolled again, this will also collect stats */
1635     if (!wait_preroll (media))
1636       goto preroll_failed;
1637
1638     g_rec_mutex_lock (&priv->state_lock);
1639     GST_INFO ("prerolled again");
1640   } else {
1641     GST_INFO ("no seek needed");
1642     res = TRUE;
1643   }
1644   g_rec_mutex_unlock (&priv->state_lock);
1645
1646   return res;
1647
1648   /* ERRORS */
1649 not_prepared:
1650   {
1651     g_rec_mutex_unlock (&priv->state_lock);
1652     GST_INFO ("media %p is not prepared", media);
1653     return FALSE;
1654   }
1655 not_seekable:
1656   {
1657     g_rec_mutex_unlock (&priv->state_lock);
1658     GST_INFO ("pipeline is not seekable");
1659     return FALSE;
1660   }
1661 not_supported:
1662   {
1663     g_rec_mutex_unlock (&priv->state_lock);
1664     GST_WARNING ("conversion to npt not supported");
1665     return FALSE;
1666   }
1667 preroll_failed:
1668   {
1669     GST_WARNING ("failed to preroll after seek");
1670     return FALSE;
1671   }
1672 }
1673
1674 static void
1675 stream_collect_blocking (GstRTSPStream * stream, gboolean * blocked)
1676 {
1677   *blocked &= gst_rtsp_stream_is_blocking (stream);
1678 }
1679
1680 static gboolean
1681 media_streams_blocking (GstRTSPMedia * media)
1682 {
1683   gboolean blocking = TRUE;
1684
1685   g_ptr_array_foreach (media->priv->streams, (GFunc) stream_collect_blocking,
1686       &blocking);
1687
1688   return blocking;
1689 }
1690
1691 static GstStateChangeReturn
1692 set_state (GstRTSPMedia * media, GstState state)
1693 {
1694   GstRTSPMediaPrivate *priv = media->priv;
1695   GstStateChangeReturn ret;
1696
1697   GST_INFO ("set state to %s for media %p", gst_element_state_get_name (state),
1698       media);
1699   ret = gst_element_set_state (priv->pipeline, state);
1700
1701   return ret;
1702 }
1703
1704 static GstStateChangeReturn
1705 set_target_state (GstRTSPMedia * media, GstState state, gboolean do_state)
1706 {
1707   GstRTSPMediaPrivate *priv = media->priv;
1708   GstStateChangeReturn ret;
1709
1710   GST_INFO ("set target state to %s for media %p",
1711       gst_element_state_get_name (state), media);
1712   priv->target_state = state;
1713
1714   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_TARGET_STATE], 0,
1715       priv->target_state, NULL);
1716
1717   if (do_state)
1718     ret = set_state (media, state);
1719   else
1720     ret = GST_STATE_CHANGE_SUCCESS;
1721
1722   return ret;
1723 }
1724
1725 /* called with state-lock */
1726 static gboolean
1727 default_handle_message (GstRTSPMedia * media, GstMessage * message)
1728 {
1729   GstRTSPMediaPrivate *priv = media->priv;
1730   GstMessageType type;
1731
1732   type = GST_MESSAGE_TYPE (message);
1733
1734   switch (type) {
1735     case GST_MESSAGE_STATE_CHANGED:
1736       break;
1737     case GST_MESSAGE_BUFFERING:
1738     {
1739       gint percent;
1740
1741       gst_message_parse_buffering (message, &percent);
1742
1743       /* no state management needed for live pipelines */
1744       if (priv->is_live)
1745         break;
1746
1747       if (percent == 100) {
1748         /* a 100% message means buffering is done */
1749         priv->buffering = FALSE;
1750         /* if the desired state is playing, go back */
1751         if (priv->target_state == GST_STATE_PLAYING) {
1752           GST_INFO ("Buffering done, setting pipeline to PLAYING");
1753           set_state (media, GST_STATE_PLAYING);
1754         } else {
1755           GST_INFO ("Buffering done");
1756         }
1757       } else {
1758         /* buffering busy */
1759         if (priv->buffering == FALSE) {
1760           if (priv->target_state == GST_STATE_PLAYING) {
1761             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
1762             GST_INFO ("Buffering, setting pipeline to PAUSED ...");
1763             set_state (media, GST_STATE_PAUSED);
1764           } else {
1765             GST_INFO ("Buffering ...");
1766           }
1767         }
1768         priv->buffering = TRUE;
1769       }
1770       break;
1771     }
1772     case GST_MESSAGE_LATENCY:
1773     {
1774       gst_bin_recalculate_latency (GST_BIN_CAST (priv->pipeline));
1775       break;
1776     }
1777     case GST_MESSAGE_ERROR:
1778     {
1779       GError *gerror;
1780       gchar *debug;
1781
1782       gst_message_parse_error (message, &gerror, &debug);
1783       GST_WARNING ("%p: got error %s (%s)", media, gerror->message, debug);
1784       g_error_free (gerror);
1785       g_free (debug);
1786
1787       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
1788       break;
1789     }
1790     case GST_MESSAGE_WARNING:
1791     {
1792       GError *gerror;
1793       gchar *debug;
1794
1795       gst_message_parse_warning (message, &gerror, &debug);
1796       GST_WARNING ("%p: got warning %s (%s)", media, gerror->message, debug);
1797       g_error_free (gerror);
1798       g_free (debug);
1799       break;
1800     }
1801     case GST_MESSAGE_ELEMENT:
1802     {
1803       const GstStructure *s;
1804
1805       s = gst_message_get_structure (message);
1806       if (gst_structure_has_name (s, "GstRTSPStreamBlocking")) {
1807         GST_DEBUG ("media received blocking message");
1808         if (priv->blocked && media_streams_blocking (media)) {
1809           GST_DEBUG ("media is blocking");
1810           collect_media_stats (media);
1811
1812           if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
1813             gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
1814         }
1815       }
1816       break;
1817     }
1818     case GST_MESSAGE_STREAM_STATUS:
1819       break;
1820     case GST_MESSAGE_ASYNC_DONE:
1821       if (priv->adding) {
1822         /* when we are dynamically adding pads, the addition of the udpsrc will
1823          * temporarily produce ASYNC_DONE messages. We have to ignore them and
1824          * wait for the final ASYNC_DONE after everything prerolled */
1825         GST_INFO ("%p: ignoring ASYNC_DONE", media);
1826       } else {
1827         GST_INFO ("%p: got ASYNC_DONE", media);
1828         collect_media_stats (media);
1829
1830         if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
1831           gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
1832       }
1833       break;
1834     case GST_MESSAGE_EOS:
1835       GST_INFO ("%p: got EOS", media);
1836
1837       if (priv->status == GST_RTSP_MEDIA_STATUS_UNPREPARING) {
1838         GST_DEBUG ("shutting down after EOS");
1839         finish_unprepare (media);
1840       }
1841       break;
1842     default:
1843       GST_INFO ("%p: got message type %d (%s)", media, type,
1844           gst_message_type_get_name (type));
1845       break;
1846   }
1847   return TRUE;
1848 }
1849
1850 static gboolean
1851 bus_message (GstBus * bus, GstMessage * message, GstRTSPMedia * media)
1852 {
1853   GstRTSPMediaPrivate *priv = media->priv;
1854   GstRTSPMediaClass *klass;
1855   gboolean ret;
1856
1857   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1858
1859   g_rec_mutex_lock (&priv->state_lock);
1860   if (klass->handle_message)
1861     ret = klass->handle_message (media, message);
1862   else
1863     ret = FALSE;
1864   g_rec_mutex_unlock (&priv->state_lock);
1865
1866   return ret;
1867 }
1868
1869 static void
1870 watch_destroyed (GstRTSPMedia * media)
1871 {
1872   GST_DEBUG_OBJECT (media, "source destroyed");
1873   g_object_unref (media);
1874 }
1875
1876 static GstElement *
1877 find_payload_element (GstElement * payloader)
1878 {
1879   GstElement *pay = NULL;
1880
1881   if (GST_IS_BIN (payloader)) {
1882     GstIterator *iter;
1883     GValue item = { 0 };
1884
1885     iter = gst_bin_iterate_recurse (GST_BIN (payloader));
1886     while (gst_iterator_next (iter, &item) == GST_ITERATOR_OK) {
1887       GstElement *element = (GstElement *) g_value_get_object (&item);
1888       GstElementClass *eclass = GST_ELEMENT_GET_CLASS (element);
1889       const gchar *klass;
1890
1891       klass =
1892           gst_element_class_get_metadata (eclass, GST_ELEMENT_METADATA_KLASS);
1893       if (klass == NULL)
1894         continue;
1895
1896       if (strstr (klass, "Payloader") && strstr (klass, "RTP")) {
1897         pay = gst_object_ref (element);
1898         g_value_unset (&item);
1899         break;
1900       }
1901       g_value_unset (&item);
1902     }
1903     gst_iterator_free (iter);
1904   } else {
1905     pay = g_object_ref (payloader);
1906   }
1907
1908   return pay;
1909 }
1910
1911 /* called from streaming threads */
1912 static void
1913 pad_added_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
1914 {
1915   GstRTSPMediaPrivate *priv = media->priv;
1916   GstRTSPStream *stream;
1917   GstElement *pay;
1918
1919   /* find the real payload element */
1920   pay = find_payload_element (element);
1921   stream = gst_rtsp_media_create_stream (media, pay, pad);
1922   gst_object_unref (pay);
1923
1924   GST_INFO ("pad added %s:%s, stream %p", GST_DEBUG_PAD_NAME (pad), stream);
1925
1926   g_rec_mutex_lock (&priv->state_lock);
1927   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARING)
1928     goto not_preparing;
1929
1930   g_object_set_data (G_OBJECT (pad), "gst-rtsp-dynpad-stream", stream);
1931
1932   /* we will be adding elements below that will cause ASYNC_DONE to be
1933    * posted in the bus. We want to ignore those messages until the
1934    * pipeline really prerolled. */
1935   priv->adding = TRUE;
1936
1937   /* join the element in the PAUSED state because this callback is
1938    * called from the streaming thread and it is PAUSED */
1939   if (!gst_rtsp_stream_join_bin (stream, GST_BIN (priv->pipeline),
1940           priv->rtpbin, GST_STATE_PAUSED)) {
1941     GST_WARNING ("failed to join bin element");
1942   }
1943
1944   priv->adding = FALSE;
1945   g_rec_mutex_unlock (&priv->state_lock);
1946
1947   return;
1948
1949   /* ERRORS */
1950 not_preparing:
1951   {
1952     gst_rtsp_media_remove_stream (media, stream);
1953     g_rec_mutex_unlock (&priv->state_lock);
1954     GST_INFO ("ignore pad because we are not preparing");
1955     return;
1956   }
1957 }
1958
1959 static void
1960 pad_removed_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
1961 {
1962   GstRTSPMediaPrivate *priv = media->priv;
1963   GstRTSPStream *stream;
1964
1965   stream = g_object_get_data (G_OBJECT (pad), "gst-rtsp-dynpad-stream");
1966   if (stream == NULL)
1967     return;
1968
1969   GST_INFO ("pad removed %s:%s, stream %p", GST_DEBUG_PAD_NAME (pad), stream);
1970
1971   g_rec_mutex_lock (&priv->state_lock);
1972   gst_rtsp_stream_leave_bin (stream, GST_BIN (priv->pipeline), priv->rtpbin);
1973   g_rec_mutex_unlock (&priv->state_lock);
1974
1975   gst_rtsp_media_remove_stream (media, stream);
1976 }
1977
1978 static void
1979 remove_fakesink (GstRTSPMediaPrivate * priv)
1980 {
1981   GstElement *fakesink;
1982
1983   g_mutex_lock (&priv->lock);
1984   if ((fakesink = priv->fakesink))
1985     gst_object_ref (fakesink);
1986   priv->fakesink = NULL;
1987   g_mutex_unlock (&priv->lock);
1988
1989   if (fakesink) {
1990     gst_bin_remove (GST_BIN (priv->pipeline), fakesink);
1991     gst_element_set_state (fakesink, GST_STATE_NULL);
1992     gst_object_unref (fakesink);
1993     GST_INFO ("removed fakesink");
1994   }
1995 }
1996
1997 static void
1998 no_more_pads_cb (GstElement * element, GstRTSPMedia * media)
1999 {
2000   GstRTSPMediaPrivate *priv = media->priv;
2001
2002   GST_INFO ("no more pads");
2003   remove_fakesink (priv);
2004 }
2005
2006 typedef struct _DynPaySignalHandlers DynPaySignalHandlers;
2007
2008 struct _DynPaySignalHandlers
2009 {
2010   gulong pad_added_handler;
2011   gulong pad_removed_handler;
2012   gulong no_more_pads_handler;
2013 };
2014
2015 static gboolean
2016 start_preroll (GstRTSPMedia * media)
2017 {
2018   GstRTSPMediaPrivate *priv = media->priv;
2019   GstStateChangeReturn ret;
2020
2021   GST_INFO ("setting pipeline to PAUSED for media %p", media);
2022   /* first go to PAUSED */
2023   ret = set_target_state (media, GST_STATE_PAUSED, TRUE);
2024
2025   switch (ret) {
2026     case GST_STATE_CHANGE_SUCCESS:
2027       GST_INFO ("SUCCESS state change for media %p", media);
2028       priv->seekable = TRUE;
2029       break;
2030     case GST_STATE_CHANGE_ASYNC:
2031       GST_INFO ("ASYNC state change for media %p", media);
2032       priv->seekable = TRUE;
2033       break;
2034     case GST_STATE_CHANGE_NO_PREROLL:
2035       /* we need to go to PLAYING */
2036       GST_INFO ("NO_PREROLL state change: live media %p", media);
2037       /* FIXME we disable seeking for live streams for now. We should perform a
2038        * seeking query in preroll instead */
2039       priv->seekable = FALSE;
2040       priv->is_live = TRUE;
2041       /* start blocked  to make sure nothing goes to the sink */
2042       media_streams_set_blocked (media, TRUE);
2043       ret = set_state (media, GST_STATE_PLAYING);
2044       if (ret == GST_STATE_CHANGE_FAILURE)
2045         goto state_failed;
2046       break;
2047     case GST_STATE_CHANGE_FAILURE:
2048       goto state_failed;
2049   }
2050
2051   return TRUE;
2052
2053 state_failed:
2054   {
2055     GST_WARNING ("failed to preroll pipeline");
2056     return FALSE;
2057   }
2058 }
2059
2060 static gboolean
2061 wait_preroll (GstRTSPMedia * media)
2062 {
2063   GstRTSPMediaStatus status;
2064
2065   GST_DEBUG ("wait to preroll pipeline");
2066
2067   /* wait until pipeline is prerolled */
2068   status = gst_rtsp_media_get_status (media);
2069   if (status == GST_RTSP_MEDIA_STATUS_ERROR)
2070     goto preroll_failed;
2071
2072   return TRUE;
2073
2074 preroll_failed:
2075   {
2076     GST_WARNING ("failed to preroll pipeline");
2077     return FALSE;
2078   }
2079 }
2080
2081 static gboolean
2082 start_prepare (GstRTSPMedia * media)
2083 {
2084   GstRTSPMediaPrivate *priv = media->priv;
2085   guint i;
2086   GList *walk;
2087
2088   /* link streams we already have, other streams might appear when we have
2089    * dynamic elements */
2090   for (i = 0; i < priv->streams->len; i++) {
2091     GstRTSPStream *stream;
2092
2093     stream = g_ptr_array_index (priv->streams, i);
2094
2095     if (!gst_rtsp_stream_join_bin (stream, GST_BIN (priv->pipeline),
2096             priv->rtpbin, GST_STATE_NULL)) {
2097       goto join_bin_failed;
2098     }
2099   }
2100
2101   for (walk = priv->dynamic; walk; walk = g_list_next (walk)) {
2102     GstElement *elem = walk->data;
2103     DynPaySignalHandlers *handlers = g_slice_new (DynPaySignalHandlers);
2104
2105     GST_INFO ("adding callbacks for dynamic element %p", elem);
2106
2107     handlers->pad_added_handler = g_signal_connect (elem, "pad-added",
2108         (GCallback) pad_added_cb, media);
2109     handlers->pad_removed_handler = g_signal_connect (elem, "pad-removed",
2110         (GCallback) pad_removed_cb, media);
2111     handlers->no_more_pads_handler = g_signal_connect (elem, "no-more-pads",
2112         (GCallback) no_more_pads_cb, media);
2113
2114     g_object_set_data (G_OBJECT (elem), "gst-rtsp-dynpay-handlers", handlers);
2115
2116     /* we add a fakesink here in order to make the state change async. We remove
2117      * the fakesink again in the no-more-pads callback. */
2118     priv->fakesink = gst_element_factory_make ("fakesink", "fakesink");
2119     gst_bin_add (GST_BIN (priv->pipeline), priv->fakesink);
2120   }
2121
2122   if (!start_preroll (media))
2123     goto preroll_failed;
2124
2125   return FALSE;
2126
2127 join_bin_failed:
2128   {
2129     GST_WARNING ("failed to join bin element");
2130     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2131     return FALSE;
2132   }
2133 preroll_failed:
2134   {
2135     GST_WARNING ("failed to preroll pipeline");
2136     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2137     return FALSE;
2138   }
2139 }
2140
2141 static gboolean
2142 default_prepare (GstRTSPMedia * media, GstRTSPThread * thread)
2143 {
2144   GstRTSPMediaPrivate *priv;
2145   GstRTSPMediaClass *klass;
2146   GstBus *bus;
2147   GMainContext *context;
2148   GSource *source;
2149
2150   priv = media->priv;
2151
2152   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2153
2154   if (!klass->create_rtpbin)
2155     goto no_create_rtpbin;
2156
2157   priv->rtpbin = klass->create_rtpbin (media);
2158   if (priv->rtpbin != NULL) {
2159     gboolean success = TRUE;
2160
2161     if (klass->setup_rtpbin)
2162       success = klass->setup_rtpbin (media, priv->rtpbin);
2163
2164     if (success == FALSE) {
2165       gst_object_unref (priv->rtpbin);
2166       priv->rtpbin = NULL;
2167     }
2168   }
2169   if (priv->rtpbin == NULL)
2170     goto no_rtpbin;
2171
2172   priv->thread = thread;
2173   context = (thread != NULL) ? (thread->context) : NULL;
2174
2175   bus = gst_pipeline_get_bus (GST_PIPELINE_CAST (priv->pipeline));
2176
2177   /* add the pipeline bus to our custom mainloop */
2178   priv->source = gst_bus_create_watch (bus);
2179   gst_object_unref (bus);
2180
2181   g_source_set_callback (priv->source, (GSourceFunc) bus_message,
2182       g_object_ref (media), (GDestroyNotify) watch_destroyed);
2183
2184   priv->id = g_source_attach (priv->source, context);
2185
2186   /* add stuff to the bin */
2187   gst_bin_add (GST_BIN (priv->pipeline), priv->rtpbin);
2188
2189   /* do remainder in context */
2190   source = g_idle_source_new ();
2191   g_source_set_callback (source, (GSourceFunc) start_prepare, media, NULL);
2192   g_source_attach (source, context);
2193   g_source_unref (source);
2194
2195   return TRUE;
2196
2197   /* ERRORS */
2198 no_create_rtpbin:
2199   {
2200     GST_ERROR ("no create_rtpbin function");
2201     g_critical ("no create_rtpbin vmethod function set");
2202     return FALSE;
2203   }
2204 no_rtpbin:
2205   {
2206     GST_WARNING ("no rtpbin element");
2207     g_warning ("failed to create element 'rtpbin', check your installation");
2208     return FALSE;
2209   }
2210 }
2211
2212 /**
2213  * gst_rtsp_media_prepare:
2214  * @media: a #GstRTSPMedia
2215  * @thread: (transfer full): a #GstRTSPThread to run the bus handler or %NULL
2216  *
2217  * Prepare @media for streaming. This function will create the objects
2218  * to manage the streaming. A pipeline must have been set on @media with
2219  * gst_rtsp_media_take_pipeline().
2220  *
2221  * It will preroll the pipeline and collect vital information about the streams
2222  * such as the duration.
2223  *
2224  * Returns: %TRUE on success.
2225  */
2226 gboolean
2227 gst_rtsp_media_prepare (GstRTSPMedia * media, GstRTSPThread * thread)
2228 {
2229   GstRTSPMediaPrivate *priv;
2230   GstRTSPMediaClass *klass;
2231
2232   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2233
2234   priv = media->priv;
2235
2236   g_rec_mutex_lock (&priv->state_lock);
2237   priv->prepare_count++;
2238
2239   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED ||
2240       priv->status == GST_RTSP_MEDIA_STATUS_SUSPENDED)
2241     goto was_prepared;
2242
2243   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2244     goto is_preparing;
2245
2246   if (priv->status != GST_RTSP_MEDIA_STATUS_UNPREPARED)
2247     goto not_unprepared;
2248
2249   if (!priv->reusable && priv->reused)
2250     goto is_reused;
2251
2252   GST_INFO ("preparing media %p", media);
2253
2254   /* reset some variables */
2255   priv->is_live = FALSE;
2256   priv->seekable = FALSE;
2257   priv->buffering = FALSE;
2258
2259   /* we're preparing now */
2260   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
2261
2262   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2263   if (klass->prepare) {
2264     if (!klass->prepare (media, thread))
2265       goto prepare_failed;
2266   }
2267
2268 wait_status:
2269   g_rec_mutex_unlock (&priv->state_lock);
2270
2271   /* now wait for all pads to be prerolled, FIXME, we should somehow be
2272    * able to do this async so that we don't block the server thread. */
2273   if (!wait_preroll (media))
2274     goto preroll_failed;
2275
2276   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_PREPARED], 0, NULL);
2277
2278   GST_INFO ("object %p is prerolled", media);
2279
2280   return TRUE;
2281
2282   /* OK */
2283 is_preparing:
2284   {
2285     /* we are not going to use the giving thread, so stop it. */
2286     if (thread)
2287       gst_rtsp_thread_stop (thread);
2288     goto wait_status;
2289   }
2290 was_prepared:
2291   {
2292     GST_LOG ("media %p was prepared", media);
2293     /* we are not going to use the giving thread, so stop it. */
2294     if (thread)
2295       gst_rtsp_thread_stop (thread);
2296     g_rec_mutex_unlock (&priv->state_lock);
2297     return TRUE;
2298   }
2299   /* ERRORS */
2300 not_unprepared:
2301   {
2302     /* we are not going to use the giving thread, so stop it. */
2303     if (thread)
2304       gst_rtsp_thread_stop (thread);
2305     GST_WARNING ("media %p was not unprepared", media);
2306     priv->prepare_count--;
2307     g_rec_mutex_unlock (&priv->state_lock);
2308     return FALSE;
2309   }
2310 is_reused:
2311   {
2312     /* we are not going to use the giving thread, so stop it. */
2313     if (thread)
2314       gst_rtsp_thread_stop (thread);
2315     priv->prepare_count--;
2316     g_rec_mutex_unlock (&priv->state_lock);
2317     GST_WARNING ("can not reuse media %p", media);
2318     return FALSE;
2319   }
2320 prepare_failed:
2321   {
2322     /* we are not going to use the giving thread, so stop it. */
2323     if (thread)
2324       gst_rtsp_thread_stop (thread);
2325     priv->prepare_count--;
2326     g_rec_mutex_unlock (&priv->state_lock);
2327     GST_ERROR ("failed to prepare media");
2328     return FALSE;
2329   }
2330 preroll_failed:
2331   {
2332     GST_WARNING ("failed to preroll pipeline");
2333     gst_rtsp_media_unprepare (media);
2334     return FALSE;
2335   }
2336 }
2337
2338 /* must be called with state-lock */
2339 static void
2340 finish_unprepare (GstRTSPMedia * media)
2341 {
2342   GstRTSPMediaPrivate *priv = media->priv;
2343   gint i;
2344   GList *walk;
2345
2346   GST_DEBUG ("shutting down");
2347
2348   /* release the lock on shutdown, otherwise pad_added_cb might try to
2349    * acquire the lock and then we deadlock */
2350   g_rec_mutex_unlock (&priv->state_lock);
2351   set_state (media, GST_STATE_NULL);
2352   g_rec_mutex_lock (&priv->state_lock);
2353   remove_fakesink (priv);
2354
2355   for (i = 0; i < priv->streams->len; i++) {
2356     GstRTSPStream *stream;
2357
2358     GST_INFO ("Removing elements of stream %d from pipeline", i);
2359
2360     stream = g_ptr_array_index (priv->streams, i);
2361
2362     gst_rtsp_stream_leave_bin (stream, GST_BIN (priv->pipeline), priv->rtpbin);
2363   }
2364
2365   /* remove the pad signal handlers */
2366   for (walk = priv->dynamic; walk; walk = g_list_next (walk)) {
2367     GstElement *elem = walk->data;
2368     DynPaySignalHandlers *handlers;
2369
2370     handlers =
2371         g_object_steal_data (G_OBJECT (elem), "gst-rtsp-dynpay-handlers");
2372     g_assert (handlers != NULL);
2373
2374     g_signal_handler_disconnect (G_OBJECT (elem), handlers->pad_added_handler);
2375     g_signal_handler_disconnect (G_OBJECT (elem),
2376         handlers->pad_removed_handler);
2377     g_signal_handler_disconnect (G_OBJECT (elem),
2378         handlers->no_more_pads_handler);
2379
2380     g_slice_free (DynPaySignalHandlers, handlers);
2381   }
2382
2383   gst_bin_remove (GST_BIN (priv->pipeline), priv->rtpbin);
2384   priv->rtpbin = NULL;
2385
2386   if (priv->nettime)
2387     gst_object_unref (priv->nettime);
2388   priv->nettime = NULL;
2389
2390   priv->reused = TRUE;
2391   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_UNPREPARED);
2392
2393   /* when the media is not reusable, this will effectively unref the media and
2394    * recreate it */
2395   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_UNPREPARED], 0, NULL);
2396
2397   /* the source has the last ref to the media */
2398   if (priv->source) {
2399     GST_DEBUG ("destroy source");
2400     g_source_destroy (priv->source);
2401     g_source_unref (priv->source);
2402   }
2403   if (priv->thread) {
2404     GST_DEBUG ("stop thread");
2405     gst_rtsp_thread_stop (priv->thread);
2406   }
2407 }
2408
2409 /* called with state-lock */
2410 static gboolean
2411 default_unprepare (GstRTSPMedia * media)
2412 {
2413   GstRTSPMediaPrivate *priv = media->priv;
2414
2415   if (priv->eos_shutdown) {
2416     GST_DEBUG ("sending EOS for shutdown");
2417     /* ref so that we don't disappear */
2418     gst_element_send_event (priv->pipeline, gst_event_new_eos ());
2419     /* we need to go to playing again for the EOS to propagate, normally in this
2420      * state, nothing is receiving data from us anymore so this is ok. */
2421     set_state (media, GST_STATE_PLAYING);
2422   } else {
2423     finish_unprepare (media);
2424   }
2425   return TRUE;
2426 }
2427
2428 /**
2429  * gst_rtsp_media_unprepare:
2430  * @media: a #GstRTSPMedia
2431  *
2432  * Unprepare @media. After this call, the media should be prepared again before
2433  * it can be used again. If the media is set to be non-reusable, a new instance
2434  * must be created.
2435  *
2436  * Returns: %TRUE on success.
2437  */
2438 gboolean
2439 gst_rtsp_media_unprepare (GstRTSPMedia * media)
2440 {
2441   GstRTSPMediaPrivate *priv;
2442   gboolean success;
2443
2444   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2445
2446   priv = media->priv;
2447
2448   g_rec_mutex_lock (&priv->state_lock);
2449   if (priv->status == GST_RTSP_MEDIA_STATUS_UNPREPARED)
2450     goto was_unprepared;
2451
2452   priv->prepare_count--;
2453   if (priv->prepare_count > 0)
2454     goto is_busy;
2455
2456   GST_INFO ("unprepare media %p", media);
2457   if (priv->blocked)
2458     media_streams_set_blocked (media, FALSE);
2459   set_target_state (media, GST_STATE_NULL, FALSE);
2460   success = TRUE;
2461
2462   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_UNPREPARING);
2463
2464   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED) {
2465     GstRTSPMediaClass *klass;
2466
2467     klass = GST_RTSP_MEDIA_GET_CLASS (media);
2468     if (klass->unprepare)
2469       success = klass->unprepare (media);
2470   } else {
2471     finish_unprepare (media);
2472   }
2473   g_rec_mutex_unlock (&priv->state_lock);
2474
2475   return success;
2476
2477 was_unprepared:
2478   {
2479     g_rec_mutex_unlock (&priv->state_lock);
2480     GST_INFO ("media %p was already unprepared", media);
2481     return TRUE;
2482   }
2483 is_busy:
2484   {
2485     GST_INFO ("media %p still prepared %d times", media, priv->prepare_count);
2486     g_rec_mutex_unlock (&priv->state_lock);
2487     return TRUE;
2488   }
2489 }
2490
2491 /* should be called with state-lock */
2492 static GstClock *
2493 get_clock_unlocked (GstRTSPMedia * media)
2494 {
2495   if (media->priv->status != GST_RTSP_MEDIA_STATUS_PREPARED) {
2496     GST_DEBUG_OBJECT (media, "media was not prepared");
2497     return NULL;
2498   }
2499   return gst_pipeline_get_clock (GST_PIPELINE_CAST (media->priv->pipeline));
2500 }
2501
2502 /**
2503  * gst_rtsp_media_get_clock:
2504  * @media: a #GstRTSPMedia
2505  *
2506  * Get the clock that is used by the pipeline in @media.
2507  *
2508  * @media must be prepared before this method returns a valid clock object.
2509  *
2510  * Returns: (transfer full): the #GstClock used by @media. unref after usage.
2511  */
2512 GstClock *
2513 gst_rtsp_media_get_clock (GstRTSPMedia * media)
2514 {
2515   GstClock *clock;
2516   GstRTSPMediaPrivate *priv;
2517
2518   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
2519
2520   priv = media->priv;
2521
2522   g_rec_mutex_lock (&priv->state_lock);
2523   clock = get_clock_unlocked (media);
2524   g_rec_mutex_unlock (&priv->state_lock);
2525
2526   return clock;
2527 }
2528
2529 /**
2530  * gst_rtsp_media_get_base_time:
2531  * @media: a #GstRTSPMedia
2532  *
2533  * Get the base_time that is used by the pipeline in @media.
2534  *
2535  * @media must be prepared before this method returns a valid base_time.
2536  *
2537  * Returns: the base_time used by @media.
2538  */
2539 GstClockTime
2540 gst_rtsp_media_get_base_time (GstRTSPMedia * media)
2541 {
2542   GstClockTime result;
2543   GstRTSPMediaPrivate *priv;
2544
2545   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_CLOCK_TIME_NONE);
2546
2547   priv = media->priv;
2548
2549   g_rec_mutex_lock (&priv->state_lock);
2550   if (media->priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
2551     goto not_prepared;
2552
2553   result = gst_element_get_base_time (media->priv->pipeline);
2554   g_rec_mutex_unlock (&priv->state_lock);
2555
2556   return result;
2557
2558   /* ERRORS */
2559 not_prepared:
2560   {
2561     g_rec_mutex_unlock (&priv->state_lock);
2562     GST_DEBUG_OBJECT (media, "media was not prepared");
2563     return GST_CLOCK_TIME_NONE;
2564   }
2565 }
2566
2567 /**
2568  * gst_rtsp_media_get_time_provider:
2569  * @media: a #GstRTSPMedia
2570  * @address: an address or %NULL
2571  * @port: a port or 0
2572  *
2573  * Get the #GstNetTimeProvider for the clock used by @media. The time provider
2574  * will listen on @address and @port for client time requests.
2575  *
2576  * Returns: (transfer full): the #GstNetTimeProvider of @media.
2577  */
2578 GstNetTimeProvider *
2579 gst_rtsp_media_get_time_provider (GstRTSPMedia * media, const gchar * address,
2580     guint16 port)
2581 {
2582   GstRTSPMediaPrivate *priv;
2583   GstNetTimeProvider *provider = NULL;
2584
2585   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
2586
2587   priv = media->priv;
2588
2589   g_rec_mutex_lock (&priv->state_lock);
2590   if (priv->time_provider) {
2591     if ((provider = priv->nettime) == NULL) {
2592       GstClock *clock;
2593
2594       if (priv->time_provider && (clock = get_clock_unlocked (media))) {
2595         provider = gst_net_time_provider_new (clock, address, port);
2596         gst_object_unref (clock);
2597
2598         priv->nettime = provider;
2599       }
2600     }
2601   }
2602   g_rec_mutex_unlock (&priv->state_lock);
2603
2604   if (provider)
2605     gst_object_ref (provider);
2606
2607   return provider;
2608 }
2609
2610 static gboolean
2611 default_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp, GstSDPInfo * info)
2612 {
2613   return gst_rtsp_sdp_from_media (sdp, info, media);
2614 }
2615
2616 /**
2617  * gst_rtsp_media_setup_sdp:
2618  * @media: a #GstRTSPMedia
2619  * @sdp: (transfer none): a #GstSDPMessage
2620  * @info: (transfer none): a #GstSDPInfo
2621  *
2622  * Add @media specific info to @sdp. @info is used to configure the connection
2623  * information in the SDP.
2624  *
2625  * Returns: TRUE on success.
2626  */
2627 gboolean
2628 gst_rtsp_media_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp,
2629     GstSDPInfo * info)
2630 {
2631   GstRTSPMediaPrivate *priv;
2632   GstRTSPMediaClass *klass;
2633   gboolean res;
2634
2635   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2636   g_return_val_if_fail (sdp != NULL, FALSE);
2637   g_return_val_if_fail (info != NULL, FALSE);
2638
2639   priv = media->priv;
2640
2641   g_rec_mutex_lock (&priv->state_lock);
2642
2643   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2644
2645   if (!klass->setup_sdp)
2646     goto no_setup_sdp;
2647
2648   res = klass->setup_sdp (media, sdp, info);
2649
2650   g_rec_mutex_unlock (&priv->state_lock);
2651
2652   return res;
2653
2654   /* ERRORS */
2655 no_setup_sdp:
2656   {
2657     g_rec_mutex_unlock (&priv->state_lock);
2658     GST_ERROR ("no setup_sdp function");
2659     g_critical ("no setup_sdp vmethod function set");
2660     return FALSE;
2661   }
2662 }
2663
2664 /**
2665  * gst_rtsp_media_suspend:
2666  * @media: a #GstRTSPMedia
2667  *
2668  * Suspend @media. The state of the pipeline managed by @media is set to
2669  * GST_STATE_NULL but all streams are kept. @media can be prepared again
2670  * with gst_rtsp_media_unsuspend()
2671  *
2672  * @media must be prepared with gst_rtsp_media_prepare();
2673  *
2674  * Returns: %TRUE on success.
2675  */
2676 gboolean
2677 gst_rtsp_media_suspend (GstRTSPMedia * media)
2678 {
2679   GstRTSPMediaPrivate *priv = media->priv;
2680   GstStateChangeReturn ret;
2681
2682   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2683
2684   GST_FIXME ("suspend for dynamic pipelines needs fixing");
2685
2686   g_rec_mutex_lock (&priv->state_lock);
2687   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
2688     goto not_prepared;
2689
2690   /* don't attempt to suspend when something is busy */
2691   if (priv->n_active > 0)
2692     goto done;
2693
2694   switch (priv->suspend_mode) {
2695     case GST_RTSP_SUSPEND_MODE_NONE:
2696       GST_DEBUG ("media %p no suspend", media);
2697       break;
2698     case GST_RTSP_SUSPEND_MODE_PAUSE:
2699       GST_DEBUG ("media %p suspend to PAUSED", media);
2700       ret = set_target_state (media, GST_STATE_PAUSED, TRUE);
2701       if (ret == GST_STATE_CHANGE_FAILURE)
2702         goto state_failed;
2703       break;
2704     case GST_RTSP_SUSPEND_MODE_RESET:
2705       GST_DEBUG ("media %p suspend to NULL", media);
2706       ret = set_target_state (media, GST_STATE_NULL, TRUE);
2707       if (ret == GST_STATE_CHANGE_FAILURE)
2708         goto state_failed;
2709       break;
2710     default:
2711       break;
2712   }
2713   /* let the streams do the state changes freely, if any */
2714   media_streams_set_blocked (media, FALSE);
2715   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_SUSPENDED);
2716 done:
2717   g_rec_mutex_unlock (&priv->state_lock);
2718
2719   return TRUE;
2720
2721   /* ERRORS */
2722 not_prepared:
2723   {
2724     g_rec_mutex_unlock (&priv->state_lock);
2725     GST_WARNING ("media %p was not prepared", media);
2726     return FALSE;
2727   }
2728 state_failed:
2729   {
2730     g_rec_mutex_unlock (&priv->state_lock);
2731     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2732     GST_WARNING ("failed changing pipeline's state for media %p", media);
2733     return FALSE;
2734   }
2735 }
2736
2737 /**
2738  * gst_rtsp_media_unsuspend:
2739  * @media: a #GstRTSPMedia
2740  *
2741  * Unsuspend @media if it was in a suspended state. This method does nothing
2742  * when the media was not in the suspended state.
2743  *
2744  * Returns: %TRUE on success.
2745  */
2746 gboolean
2747 gst_rtsp_media_unsuspend (GstRTSPMedia * media)
2748 {
2749   GstRTSPMediaPrivate *priv = media->priv;
2750
2751   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2752
2753   g_rec_mutex_lock (&priv->state_lock);
2754   if (priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
2755     goto done;
2756
2757   switch (priv->suspend_mode) {
2758     case GST_RTSP_SUSPEND_MODE_NONE:
2759       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2760       break;
2761     case GST_RTSP_SUSPEND_MODE_PAUSE:
2762       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2763       break;
2764     case GST_RTSP_SUSPEND_MODE_RESET:
2765     {
2766       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
2767       if (!start_preroll (media))
2768         goto start_failed;
2769       g_rec_mutex_unlock (&priv->state_lock);
2770
2771       if (!wait_preroll (media))
2772         goto preroll_failed;
2773
2774       g_rec_mutex_lock (&priv->state_lock);
2775     }
2776     default:
2777       break;
2778   }
2779 done:
2780   g_rec_mutex_unlock (&priv->state_lock);
2781
2782   return TRUE;
2783
2784   /* ERRORS */
2785 start_failed:
2786   {
2787     g_rec_mutex_unlock (&priv->state_lock);
2788     GST_WARNING ("failed to preroll pipeline");
2789     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2790     return FALSE;
2791   }
2792 preroll_failed:
2793   {
2794     GST_WARNING ("failed to preroll pipeline");
2795     return FALSE;
2796   }
2797 }
2798
2799 /* must be called with state-lock */
2800 static void
2801 media_set_pipeline_state_locked (GstRTSPMedia * media, GstState state)
2802 {
2803   GstRTSPMediaPrivate *priv = media->priv;
2804
2805   if (state == GST_STATE_NULL) {
2806     gst_rtsp_media_unprepare (media);
2807   } else {
2808     GST_INFO ("state %s media %p", gst_element_state_get_name (state), media);
2809     set_target_state (media, state, FALSE);
2810     /* when we are buffering, don't update the state yet, this will be done
2811      * when buffering finishes */
2812     if (priv->buffering) {
2813       GST_INFO ("Buffering busy, delay state change");
2814     } else {
2815       if (state == GST_STATE_PLAYING)
2816         /* make sure pads are not blocking anymore when going to PLAYING */
2817         media_streams_set_blocked (media, FALSE);
2818
2819       set_state (media, state);
2820
2821       /* and suspend after pause */
2822       if (state == GST_STATE_PAUSED)
2823         gst_rtsp_media_suspend (media);
2824     }
2825   }
2826 }
2827
2828 /**
2829  * gst_rtsp_media_set_pipeline_state:
2830  * @media: a #GstRTSPMedia
2831  * @state: the target state of the pipeline
2832  *
2833  * Set the state of the pipeline managed by @media to @state
2834  */
2835 void
2836 gst_rtsp_media_set_pipeline_state (GstRTSPMedia * media, GstState state)
2837 {
2838   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
2839
2840   g_rec_mutex_lock (&media->priv->state_lock);
2841   media_set_pipeline_state_locked (media, state);
2842   g_rec_mutex_unlock (&media->priv->state_lock);
2843 }
2844
2845 /**
2846  * gst_rtsp_media_set_state:
2847  * @media: a #GstRTSPMedia
2848  * @state: the target state of the media
2849  * @transports: (transfer none) (element-type GstRtspServer.RTSPStreamTransport):
2850  * a #GPtrArray of #GstRTSPStreamTransport pointers
2851  *
2852  * Set the state of @media to @state and for the transports in @transports.
2853  *
2854  * @media must be prepared with gst_rtsp_media_prepare();
2855  *
2856  * Returns: %TRUE on success.
2857  */
2858 gboolean
2859 gst_rtsp_media_set_state (GstRTSPMedia * media, GstState state,
2860     GPtrArray * transports)
2861 {
2862   GstRTSPMediaPrivate *priv;
2863   gint i;
2864   gboolean activate, deactivate, do_state;
2865   gint old_active;
2866
2867   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2868   g_return_val_if_fail (transports != NULL, FALSE);
2869
2870   priv = media->priv;
2871
2872   g_rec_mutex_lock (&priv->state_lock);
2873   if (priv->status == GST_RTSP_MEDIA_STATUS_ERROR)
2874     goto error_status;
2875   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
2876       priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
2877     goto not_prepared;
2878
2879   /* NULL and READY are the same */
2880   if (state == GST_STATE_READY)
2881     state = GST_STATE_NULL;
2882
2883   activate = deactivate = FALSE;
2884
2885   GST_INFO ("going to state %s media %p", gst_element_state_get_name (state),
2886       media);
2887
2888   switch (state) {
2889     case GST_STATE_NULL:
2890     case GST_STATE_PAUSED:
2891       /* we're going from PLAYING to PAUSED, READY or NULL, deactivate */
2892       if (priv->target_state == GST_STATE_PLAYING)
2893         deactivate = TRUE;
2894       break;
2895     case GST_STATE_PLAYING:
2896       /* we're going to PLAYING, activate */
2897       activate = TRUE;
2898       break;
2899     default:
2900       break;
2901   }
2902   old_active = priv->n_active;
2903
2904   for (i = 0; i < transports->len; i++) {
2905     GstRTSPStreamTransport *trans;
2906
2907     /* we need a non-NULL entry in the array */
2908     trans = g_ptr_array_index (transports, i);
2909     if (trans == NULL)
2910       continue;
2911
2912     if (activate) {
2913       if (gst_rtsp_stream_transport_set_active (trans, TRUE))
2914         priv->n_active++;
2915     } else if (deactivate) {
2916       if (gst_rtsp_stream_transport_set_active (trans, FALSE))
2917         priv->n_active--;
2918     }
2919   }
2920
2921   /* we just activated the first media, do the playing state change */
2922   if (old_active == 0 && activate)
2923     do_state = TRUE;
2924   /* if we have no more active media, do the downward state changes */
2925   else if (priv->n_active == 0)
2926     do_state = TRUE;
2927   else
2928     do_state = FALSE;
2929
2930   GST_INFO ("state %d active %d media %p do_state %d", state, priv->n_active,
2931       media, do_state);
2932
2933   if (priv->target_state != state) {
2934     if (do_state)
2935       media_set_pipeline_state_locked (media, state);
2936
2937     g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STATE], 0, state,
2938         NULL);
2939   }
2940
2941   /* remember where we are */
2942   if (state != GST_STATE_NULL && (state == GST_STATE_PAUSED ||
2943           old_active != priv->n_active))
2944     collect_media_stats (media);
2945
2946   g_rec_mutex_unlock (&priv->state_lock);
2947
2948   return TRUE;
2949
2950   /* ERRORS */
2951 not_prepared:
2952   {
2953     GST_WARNING ("media %p was not prepared", media);
2954     g_rec_mutex_unlock (&priv->state_lock);
2955     return FALSE;
2956   }
2957 error_status:
2958   {
2959     GST_WARNING ("media %p in error status while changing to state %d",
2960         media, state);
2961     if (state == GST_STATE_NULL) {
2962       for (i = 0; i < transports->len; i++) {
2963         GstRTSPStreamTransport *trans;
2964
2965         /* we need a non-NULL entry in the array */
2966         trans = g_ptr_array_index (transports, i);
2967         if (trans == NULL)
2968           continue;
2969
2970         gst_rtsp_stream_transport_set_active (trans, FALSE);
2971       }
2972       priv->n_active = 0;
2973     }
2974     g_rec_mutex_unlock (&priv->state_lock);
2975     return FALSE;
2976   }
2977 }