2483504a4d55d82307624ecc11656485401822ed
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-media.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  * Copyright (C) 2015 Centricular Ltd
4  *     Author: Sebastian Dröge <sebastian@centricular.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /**
22  * SECTION:rtsp-media
23  * @short_description: The media pipeline
24  * @see_also: #GstRTSPMediaFactory, #GstRTSPStream, #GstRTSPSession,
25  *     #GstRTSPSessionMedia
26  *
27  * a #GstRTSPMedia contains the complete GStreamer pipeline to manage the
28  * streaming to the clients. The actual data transfer is done by the
29  * #GstRTSPStream objects that are created and exposed by the #GstRTSPMedia.
30  *
31  * The #GstRTSPMedia is usually created from a #GstRTSPMediaFactory when the
32  * client does a DESCRIBE or SETUP of a resource.
33  *
34  * A media is created with gst_rtsp_media_new() that takes the element that will
35  * provide the streaming elements. For each of the streams, a new #GstRTSPStream
36  * object needs to be made with the gst_rtsp_media_create_stream() which takes
37  * the payloader element and the source pad that produces the RTP stream.
38  *
39  * The pipeline of the media is set to PAUSED with gst_rtsp_media_prepare(). The
40  * prepare method will add rtpbin and sinks and sources to send and receive RTP
41  * and RTCP packets from the clients. Each stream srcpad is connected to an
42  * input into the internal rtpbin.
43  *
44  * It is also possible to dynamically create #GstRTSPStream objects during the
45  * prepare phase. With gst_rtsp_media_get_status() you can check the status of
46  * the prepare phase.
47  *
48  * After the media is prepared, it is ready for streaming. It will usually be
49  * managed in a session with gst_rtsp_session_manage_media(). See
50  * #GstRTSPSession and #GstRTSPSessionMedia.
51  *
52  * The state of the media can be controlled with gst_rtsp_media_set_state ().
53  * Seeking can be done with gst_rtsp_media_seek().
54  *
55  * With gst_rtsp_media_unprepare() the pipeline is stopped and shut down. When
56  * gst_rtsp_media_set_eos_shutdown() an EOS will be sent to the pipeline to
57  * cleanly shut down.
58  *
59  * With gst_rtsp_media_set_shared(), the media can be shared between multiple
60  * clients. With gst_rtsp_media_set_reusable() you can control if the pipeline
61  * can be prepared again after an unprepare.
62  *
63  * Last reviewed on 2013-07-11 (1.0.0)
64  */
65
66 #include <stdio.h>
67 #include <string.h>
68 #include <stdlib.h>
69
70 #include <gst/app/gstappsrc.h>
71 #include <gst/app/gstappsink.h>
72
73 #include <gst/sdp/gstmikey.h>
74 #include <gst/rtp/gstrtppayloads.h>
75
76 #define AES_128_KEY_LEN 16
77 #define AES_256_KEY_LEN 32
78
79 #define HMAC_32_KEY_LEN 4
80 #define HMAC_80_KEY_LEN 10
81
82 #include "rtsp-media.h"
83
84 #define GST_RTSP_MEDIA_GET_PRIVATE(obj)  \
85      (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_MEDIA, GstRTSPMediaPrivate))
86
87 struct _GstRTSPMediaPrivate
88 {
89   GMutex lock;
90   GCond cond;
91
92   /* protected by lock */
93   GstRTSPPermissions *permissions;
94   gboolean shared;
95   gboolean suspend_mode;
96   gboolean reusable;
97   GstRTSPProfile profiles;
98   GstRTSPLowerTrans protocols;
99   gboolean reused;
100   gboolean eos_shutdown;
101   guint buffer_size;
102   GstRTSPAddressPool *pool;
103   gboolean blocked;
104   GstRTSPTransportMode transport_mode;
105
106   GstElement *element;
107   GRecMutex state_lock;         /* locking order: state lock, lock */
108   GPtrArray *streams;           /* protected by lock */
109   GList *dynamic;               /* protected by lock */
110   GstRTSPMediaStatus status;    /* protected by lock */
111   gint prepare_count;
112   gint n_active;
113   gboolean adding;
114
115   /* the pipeline for the media */
116   GstElement *pipeline;
117   GstElement *fakesink;         /* protected by lock */
118   GSource *source;
119   guint id;
120   GstRTSPThread *thread;
121
122   gboolean time_provider;
123   GstNetTimeProvider *nettime;
124
125   gboolean is_live;
126   gboolean seekable;
127   gboolean buffering;
128   GstState target_state;
129
130   /* RTP session manager */
131   GstElement *rtpbin;
132
133   /* the range of media */
134   GstRTSPTimeRange range;       /* protected by lock */
135   GstClockTime range_start;
136   GstClockTime range_stop;
137
138   GList *payloads;              /* protected by lock */
139   GstClockTime rtx_time;        /* protected by lock */
140   guint latency;                /* protected by lock */
141 };
142
143 #define DEFAULT_SHARED          FALSE
144 #define DEFAULT_SUSPEND_MODE    GST_RTSP_SUSPEND_MODE_NONE
145 #define DEFAULT_REUSABLE        FALSE
146 #define DEFAULT_PROFILES        GST_RTSP_PROFILE_AVP
147 #define DEFAULT_PROTOCOLS       GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | \
148                                         GST_RTSP_LOWER_TRANS_TCP
149 #define DEFAULT_EOS_SHUTDOWN    FALSE
150 #define DEFAULT_BUFFER_SIZE     0x80000
151 #define DEFAULT_TIME_PROVIDER   FALSE
152 #define DEFAULT_LATENCY         200
153 #define DEFAULT_TRANSPORT_MODE  GST_RTSP_TRANSPORT_MODE_PLAY
154
155 /* define to dump received RTCP packets */
156 #undef DUMP_STATS
157
158 enum
159 {
160   PROP_0,
161   PROP_SHARED,
162   PROP_SUSPEND_MODE,
163   PROP_REUSABLE,
164   PROP_PROFILES,
165   PROP_PROTOCOLS,
166   PROP_EOS_SHUTDOWN,
167   PROP_BUFFER_SIZE,
168   PROP_ELEMENT,
169   PROP_TIME_PROVIDER,
170   PROP_LATENCY,
171   PROP_TRANSPORT_MODE,
172   PROP_LAST
173 };
174
175 enum
176 {
177   SIGNAL_NEW_STREAM,
178   SIGNAL_REMOVED_STREAM,
179   SIGNAL_PREPARED,
180   SIGNAL_UNPREPARED,
181   SIGNAL_TARGET_STATE,
182   SIGNAL_NEW_STATE,
183   SIGNAL_LAST
184 };
185
186 GST_DEBUG_CATEGORY_STATIC (rtsp_media_debug);
187 #define GST_CAT_DEFAULT rtsp_media_debug
188
189 static void gst_rtsp_media_get_property (GObject * object, guint propid,
190     GValue * value, GParamSpec * pspec);
191 static void gst_rtsp_media_set_property (GObject * object, guint propid,
192     const GValue * value, GParamSpec * pspec);
193 static void gst_rtsp_media_finalize (GObject * obj);
194
195 static gboolean default_handle_message (GstRTSPMedia * media,
196     GstMessage * message);
197 static void finish_unprepare (GstRTSPMedia * media);
198 static gboolean default_prepare (GstRTSPMedia * media, GstRTSPThread * thread);
199 static gboolean default_unprepare (GstRTSPMedia * media);
200 static gboolean default_suspend (GstRTSPMedia * media);
201 static gboolean default_unsuspend (GstRTSPMedia * media);
202 static gboolean default_convert_range (GstRTSPMedia * media,
203     GstRTSPTimeRange * range, GstRTSPRangeUnit unit);
204 static gboolean default_query_position (GstRTSPMedia * media,
205     gint64 * position);
206 static gboolean default_query_stop (GstRTSPMedia * media, gint64 * stop);
207 static GstElement *default_create_rtpbin (GstRTSPMedia * media);
208 static gboolean default_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp,
209     GstSDPInfo * info);
210 static gboolean default_handle_sdp (GstRTSPMedia * media, GstSDPMessage * sdp);
211
212 static gboolean wait_preroll (GstRTSPMedia * media);
213
214 static GstElement *find_payload_element (GstElement * payloader);
215
216 static guint gst_rtsp_media_signals[SIGNAL_LAST] = { 0 };
217
218 #define C_ENUM(v) ((gint) v)
219
220 GType
221 gst_rtsp_suspend_mode_get_type (void)
222 {
223   static gsize id = 0;
224   static const GEnumValue values[] = {
225     {C_ENUM (GST_RTSP_SUSPEND_MODE_NONE), "GST_RTSP_SUSPEND_MODE_NONE", "none"},
226     {C_ENUM (GST_RTSP_SUSPEND_MODE_PAUSE), "GST_RTSP_SUSPEND_MODE_PAUSE",
227         "pause"},
228     {C_ENUM (GST_RTSP_SUSPEND_MODE_RESET), "GST_RTSP_SUSPEND_MODE_RESET",
229         "reset"},
230     {0, NULL, NULL}
231   };
232
233   if (g_once_init_enter (&id)) {
234     GType tmp = g_enum_register_static ("GstRTSPSuspendMode", values);
235     g_once_init_leave (&id, tmp);
236   }
237   return (GType) id;
238 }
239
240 #define C_FLAGS(v) ((guint) v)
241
242 GType
243 gst_rtsp_transport_mode_get_type (void)
244 {
245   static gsize id = 0;
246   static const GFlagsValue values[] = {
247     {C_FLAGS (GST_RTSP_TRANSPORT_MODE_PLAY), "GST_RTSP_TRANSPORT_MODE_PLAY",
248         "play"},
249     {C_FLAGS (GST_RTSP_TRANSPORT_MODE_RECORD), "GST_RTSP_TRANSPORT_MODE_RECORD",
250         "record"},
251     {0, NULL, NULL}
252   };
253
254   if (g_once_init_enter (&id)) {
255     GType tmp = g_flags_register_static ("GstRTSPTransportMode", values);
256     g_once_init_leave (&id, tmp);
257   }
258   return (GType) id;
259 }
260
261 G_DEFINE_TYPE (GstRTSPMedia, gst_rtsp_media, G_TYPE_OBJECT);
262
263 static void
264 gst_rtsp_media_class_init (GstRTSPMediaClass * klass)
265 {
266   GObjectClass *gobject_class;
267
268   g_type_class_add_private (klass, sizeof (GstRTSPMediaPrivate));
269
270   gobject_class = G_OBJECT_CLASS (klass);
271
272   gobject_class->get_property = gst_rtsp_media_get_property;
273   gobject_class->set_property = gst_rtsp_media_set_property;
274   gobject_class->finalize = gst_rtsp_media_finalize;
275
276   g_object_class_install_property (gobject_class, PROP_SHARED,
277       g_param_spec_boolean ("shared", "Shared",
278           "If this media pipeline can be shared", DEFAULT_SHARED,
279           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
280
281   g_object_class_install_property (gobject_class, PROP_SUSPEND_MODE,
282       g_param_spec_enum ("suspend-mode", "Suspend Mode",
283           "How to suspend the media in PAUSED", GST_TYPE_RTSP_SUSPEND_MODE,
284           DEFAULT_SUSPEND_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
285
286   g_object_class_install_property (gobject_class, PROP_REUSABLE,
287       g_param_spec_boolean ("reusable", "Reusable",
288           "If this media pipeline can be reused after an unprepare",
289           DEFAULT_REUSABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
290
291   g_object_class_install_property (gobject_class, PROP_PROFILES,
292       g_param_spec_flags ("profiles", "Profiles",
293           "Allowed transfer profiles", GST_TYPE_RTSP_PROFILE,
294           DEFAULT_PROFILES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
295
296   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
297       g_param_spec_flags ("protocols", "Protocols",
298           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
299           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
300
301   g_object_class_install_property (gobject_class, PROP_EOS_SHUTDOWN,
302       g_param_spec_boolean ("eos-shutdown", "EOS Shutdown",
303           "Send an EOS event to the pipeline before unpreparing",
304           DEFAULT_EOS_SHUTDOWN, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
305
306   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
307       g_param_spec_uint ("buffer-size", "Buffer Size",
308           "The kernel UDP buffer size to use", 0, G_MAXUINT,
309           DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
310
311   g_object_class_install_property (gobject_class, PROP_ELEMENT,
312       g_param_spec_object ("element", "The Element",
313           "The GstBin to use for streaming the media", GST_TYPE_ELEMENT,
314           G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE));
315
316   g_object_class_install_property (gobject_class, PROP_TIME_PROVIDER,
317       g_param_spec_boolean ("time-provider", "Time Provider",
318           "Use a NetTimeProvider for clients",
319           DEFAULT_TIME_PROVIDER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
320
321   g_object_class_install_property (gobject_class, PROP_LATENCY,
322       g_param_spec_uint ("latency", "Latency",
323           "Latency used for receiving media in milliseconds", 0, G_MAXUINT,
324           DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
325
326   g_object_class_install_property (gobject_class, PROP_TRANSPORT_MODE,
327       g_param_spec_flags ("transport-mode", "Transport Mode",
328           "If this media pipeline can be used for PLAY or RECORD",
329           GST_TYPE_RTSP_TRANSPORT_MODE, DEFAULT_TRANSPORT_MODE,
330           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331
332   gst_rtsp_media_signals[SIGNAL_NEW_STREAM] =
333       g_signal_new ("new-stream", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
334       G_STRUCT_OFFSET (GstRTSPMediaClass, new_stream), NULL, NULL,
335       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_RTSP_STREAM);
336
337   gst_rtsp_media_signals[SIGNAL_REMOVED_STREAM] =
338       g_signal_new ("removed-stream", G_TYPE_FROM_CLASS (klass),
339       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPMediaClass, removed_stream),
340       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
341       GST_TYPE_RTSP_STREAM);
342
343   gst_rtsp_media_signals[SIGNAL_PREPARED] =
344       g_signal_new ("prepared", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
345       G_STRUCT_OFFSET (GstRTSPMediaClass, prepared), NULL, NULL,
346       g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
347
348   gst_rtsp_media_signals[SIGNAL_UNPREPARED] =
349       g_signal_new ("unprepared", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
350       G_STRUCT_OFFSET (GstRTSPMediaClass, unprepared), NULL, NULL,
351       g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
352
353   gst_rtsp_media_signals[SIGNAL_TARGET_STATE] =
354       g_signal_new ("target-state", G_TYPE_FROM_CLASS (klass),
355       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPMediaClass, target_state),
356       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1, G_TYPE_INT);
357
358   gst_rtsp_media_signals[SIGNAL_NEW_STATE] =
359       g_signal_new ("new-state", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
360       G_STRUCT_OFFSET (GstRTSPMediaClass, new_state), NULL, NULL,
361       g_cclosure_marshal_generic, G_TYPE_NONE, 1, G_TYPE_INT);
362
363   GST_DEBUG_CATEGORY_INIT (rtsp_media_debug, "rtspmedia", 0, "GstRTSPMedia");
364
365   klass->handle_message = default_handle_message;
366   klass->prepare = default_prepare;
367   klass->unprepare = default_unprepare;
368   klass->suspend = default_suspend;
369   klass->unsuspend = default_unsuspend;
370   klass->convert_range = default_convert_range;
371   klass->query_position = default_query_position;
372   klass->query_stop = default_query_stop;
373   klass->create_rtpbin = default_create_rtpbin;
374   klass->setup_sdp = default_setup_sdp;
375   klass->handle_sdp = default_handle_sdp;
376 }
377
378 static void
379 gst_rtsp_media_init (GstRTSPMedia * media)
380 {
381   GstRTSPMediaPrivate *priv = GST_RTSP_MEDIA_GET_PRIVATE (media);
382
383   media->priv = priv;
384
385   priv->streams = g_ptr_array_new_with_free_func (g_object_unref);
386   g_mutex_init (&priv->lock);
387   g_cond_init (&priv->cond);
388   g_rec_mutex_init (&priv->state_lock);
389
390   priv->shared = DEFAULT_SHARED;
391   priv->suspend_mode = DEFAULT_SUSPEND_MODE;
392   priv->reusable = DEFAULT_REUSABLE;
393   priv->profiles = DEFAULT_PROFILES;
394   priv->protocols = DEFAULT_PROTOCOLS;
395   priv->eos_shutdown = DEFAULT_EOS_SHUTDOWN;
396   priv->buffer_size = DEFAULT_BUFFER_SIZE;
397   priv->time_provider = DEFAULT_TIME_PROVIDER;
398   priv->transport_mode = DEFAULT_TRANSPORT_MODE;
399 }
400
401 static void
402 gst_rtsp_media_finalize (GObject * obj)
403 {
404   GstRTSPMediaPrivate *priv;
405   GstRTSPMedia *media;
406
407   media = GST_RTSP_MEDIA (obj);
408   priv = media->priv;
409
410   GST_INFO ("finalize media %p", media);
411
412   if (priv->permissions)
413     gst_rtsp_permissions_unref (priv->permissions);
414
415   g_ptr_array_unref (priv->streams);
416
417   g_list_free_full (priv->dynamic, gst_object_unref);
418
419   if (priv->pipeline)
420     gst_object_unref (priv->pipeline);
421   if (priv->nettime)
422     gst_object_unref (priv->nettime);
423   gst_object_unref (priv->element);
424   if (priv->pool)
425     g_object_unref (priv->pool);
426   if (priv->payloads)
427     g_list_free (priv->payloads);
428   g_mutex_clear (&priv->lock);
429   g_cond_clear (&priv->cond);
430   g_rec_mutex_clear (&priv->state_lock);
431
432   G_OBJECT_CLASS (gst_rtsp_media_parent_class)->finalize (obj);
433 }
434
435 static void
436 gst_rtsp_media_get_property (GObject * object, guint propid,
437     GValue * value, GParamSpec * pspec)
438 {
439   GstRTSPMedia *media = GST_RTSP_MEDIA (object);
440
441   switch (propid) {
442     case PROP_ELEMENT:
443       g_value_set_object (value, media->priv->element);
444       break;
445     case PROP_SHARED:
446       g_value_set_boolean (value, gst_rtsp_media_is_shared (media));
447       break;
448     case PROP_SUSPEND_MODE:
449       g_value_set_enum (value, gst_rtsp_media_get_suspend_mode (media));
450       break;
451     case PROP_REUSABLE:
452       g_value_set_boolean (value, gst_rtsp_media_is_reusable (media));
453       break;
454     case PROP_PROFILES:
455       g_value_set_flags (value, gst_rtsp_media_get_profiles (media));
456       break;
457     case PROP_PROTOCOLS:
458       g_value_set_flags (value, gst_rtsp_media_get_protocols (media));
459       break;
460     case PROP_EOS_SHUTDOWN:
461       g_value_set_boolean (value, gst_rtsp_media_is_eos_shutdown (media));
462       break;
463     case PROP_BUFFER_SIZE:
464       g_value_set_uint (value, gst_rtsp_media_get_buffer_size (media));
465       break;
466     case PROP_TIME_PROVIDER:
467       g_value_set_boolean (value, gst_rtsp_media_is_time_provider (media));
468       break;
469     case PROP_LATENCY:
470       g_value_set_uint (value, gst_rtsp_media_get_latency (media));
471       break;
472     case PROP_TRANSPORT_MODE:
473       g_value_set_flags (value, gst_rtsp_media_get_transport_mode (media));
474       break;
475     default:
476       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
477   }
478 }
479
480 static void
481 gst_rtsp_media_set_property (GObject * object, guint propid,
482     const GValue * value, GParamSpec * pspec)
483 {
484   GstRTSPMedia *media = GST_RTSP_MEDIA (object);
485
486   switch (propid) {
487     case PROP_ELEMENT:
488       media->priv->element = g_value_get_object (value);
489       gst_object_ref_sink (media->priv->element);
490       break;
491     case PROP_SHARED:
492       gst_rtsp_media_set_shared (media, g_value_get_boolean (value));
493       break;
494     case PROP_SUSPEND_MODE:
495       gst_rtsp_media_set_suspend_mode (media, g_value_get_enum (value));
496       break;
497     case PROP_REUSABLE:
498       gst_rtsp_media_set_reusable (media, g_value_get_boolean (value));
499       break;
500     case PROP_PROFILES:
501       gst_rtsp_media_set_profiles (media, g_value_get_flags (value));
502       break;
503     case PROP_PROTOCOLS:
504       gst_rtsp_media_set_protocols (media, g_value_get_flags (value));
505       break;
506     case PROP_EOS_SHUTDOWN:
507       gst_rtsp_media_set_eos_shutdown (media, g_value_get_boolean (value));
508       break;
509     case PROP_BUFFER_SIZE:
510       gst_rtsp_media_set_buffer_size (media, g_value_get_uint (value));
511       break;
512     case PROP_TIME_PROVIDER:
513       gst_rtsp_media_use_time_provider (media, g_value_get_boolean (value));
514       break;
515     case PROP_LATENCY:
516       gst_rtsp_media_set_latency (media, g_value_get_uint (value));
517       break;
518     case PROP_TRANSPORT_MODE:
519       gst_rtsp_media_set_transport_mode (media, g_value_get_flags (value));
520       break;
521     default:
522       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
523   }
524 }
525
526 typedef struct
527 {
528   gint64 position;
529   gboolean ret;
530 } DoQueryPositionData;
531
532 static void
533 do_query_position (GstRTSPStream * stream, DoQueryPositionData * data)
534 {
535   gint64 tmp;
536
537   if (gst_rtsp_stream_query_position (stream, &tmp)) {
538     data->position = MAX (data->position, tmp);
539     data->ret = TRUE;
540   }
541 }
542
543 static gboolean
544 default_query_position (GstRTSPMedia * media, gint64 * position)
545 {
546   GstRTSPMediaPrivate *priv;
547   DoQueryPositionData data;
548
549   priv = media->priv;
550
551   data.position = -1;
552   data.ret = FALSE;
553
554   g_ptr_array_foreach (priv->streams, (GFunc) do_query_position, &data);
555
556   *position = data.position;
557
558   return data.ret;
559 }
560
561 typedef struct
562 {
563   gint64 stop;
564   gboolean ret;
565 } DoQueryStopData;
566
567 static void
568 do_query_stop (GstRTSPStream * stream, DoQueryStopData * data)
569 {
570   gint64 tmp;
571
572   if (gst_rtsp_stream_query_stop (stream, &tmp)) {
573     data->stop = MAX (data->stop, tmp);
574     data->ret = TRUE;
575   }
576 }
577
578 static gboolean
579 default_query_stop (GstRTSPMedia * media, gint64 * stop)
580 {
581   GstRTSPMediaPrivate *priv;
582   DoQueryStopData data;
583
584   priv = media->priv;
585
586   data.stop = -1;
587   data.ret = FALSE;
588
589   g_ptr_array_foreach (priv->streams, (GFunc) do_query_stop, &data);
590
591   *stop = data.stop;
592
593   return data.ret;
594 }
595
596 static GstElement *
597 default_create_rtpbin (GstRTSPMedia * media)
598 {
599   GstElement *rtpbin;
600
601   rtpbin = gst_element_factory_make ("rtpbin", NULL);
602
603   return rtpbin;
604 }
605
606 /* must be called with state lock */
607 static void
608 collect_media_stats (GstRTSPMedia * media)
609 {
610   GstRTSPMediaPrivate *priv = media->priv;
611   gint64 position = 0, stop = -1;
612
613   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
614       priv->status != GST_RTSP_MEDIA_STATUS_PREPARING)
615     return;
616
617   priv->range.unit = GST_RTSP_RANGE_NPT;
618
619   GST_INFO ("collect media stats");
620
621   if (priv->is_live) {
622     priv->range.min.type = GST_RTSP_TIME_NOW;
623     priv->range.min.seconds = -1;
624     priv->range_start = -1;
625     priv->range.max.type = GST_RTSP_TIME_END;
626     priv->range.max.seconds = -1;
627     priv->range_stop = -1;
628   } else {
629     GstRTSPMediaClass *klass;
630     gboolean ret;
631
632     klass = GST_RTSP_MEDIA_GET_CLASS (media);
633
634     /* get the position */
635     ret = FALSE;
636     if (klass->query_position)
637       ret = klass->query_position (media, &position);
638
639     if (!ret) {
640       GST_INFO ("position query failed");
641       position = 0;
642     }
643
644     /* get the current segment stop */
645     ret = FALSE;
646     if (klass->query_stop)
647       ret = klass->query_stop (media, &stop);
648
649     if (!ret) {
650       GST_INFO ("stop query failed");
651       stop = -1;
652     }
653
654     GST_INFO ("stats: position %" GST_TIME_FORMAT ", stop %"
655         GST_TIME_FORMAT, GST_TIME_ARGS (position), GST_TIME_ARGS (stop));
656
657     if (position == -1) {
658       priv->range.min.type = GST_RTSP_TIME_NOW;
659       priv->range.min.seconds = -1;
660       priv->range_start = -1;
661     } else {
662       priv->range.min.type = GST_RTSP_TIME_SECONDS;
663       priv->range.min.seconds = ((gdouble) position) / GST_SECOND;
664       priv->range_start = position;
665     }
666     if (stop == -1) {
667       priv->range.max.type = GST_RTSP_TIME_END;
668       priv->range.max.seconds = -1;
669       priv->range_stop = -1;
670     } else {
671       priv->range.max.type = GST_RTSP_TIME_SECONDS;
672       priv->range.max.seconds = ((gdouble) stop) / GST_SECOND;
673       priv->range_stop = stop;
674     }
675   }
676 }
677
678 /**
679  * gst_rtsp_media_new:
680  * @element: (transfer full): a #GstElement
681  *
682  * Create a new #GstRTSPMedia instance. @element is the bin element that
683  * provides the different streams. The #GstRTSPMedia object contains the
684  * element to produce RTP data for one or more related (audio/video/..)
685  * streams.
686  *
687  * Ownership is taken of @element.
688  *
689  * Returns: (transfer full): a new #GstRTSPMedia object.
690  */
691 GstRTSPMedia *
692 gst_rtsp_media_new (GstElement * element)
693 {
694   GstRTSPMedia *result;
695
696   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
697
698   result = g_object_new (GST_TYPE_RTSP_MEDIA, "element", element, NULL);
699
700   return result;
701 }
702
703 /**
704  * gst_rtsp_media_get_element:
705  * @media: a #GstRTSPMedia
706  *
707  * Get the element that was used when constructing @media.
708  *
709  * Returns: (transfer full): a #GstElement. Unref after usage.
710  */
711 GstElement *
712 gst_rtsp_media_get_element (GstRTSPMedia * media)
713 {
714   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
715
716   return gst_object_ref (media->priv->element);
717 }
718
719 /**
720  * gst_rtsp_media_take_pipeline:
721  * @media: a #GstRTSPMedia
722  * @pipeline: (transfer full): a #GstPipeline
723  *
724  * Set @pipeline as the #GstPipeline for @media. Ownership is
725  * taken of @pipeline.
726  */
727 void
728 gst_rtsp_media_take_pipeline (GstRTSPMedia * media, GstPipeline * pipeline)
729 {
730   GstRTSPMediaPrivate *priv;
731   GstElement *old;
732   GstNetTimeProvider *nettime;
733
734   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
735   g_return_if_fail (GST_IS_PIPELINE (pipeline));
736
737   priv = media->priv;
738
739   g_mutex_lock (&priv->lock);
740   old = priv->pipeline;
741   priv->pipeline = GST_ELEMENT_CAST (pipeline);
742   nettime = priv->nettime;
743   priv->nettime = NULL;
744   g_mutex_unlock (&priv->lock);
745
746   if (old)
747     gst_object_unref (old);
748
749   if (nettime)
750     gst_object_unref (nettime);
751
752   gst_bin_add (GST_BIN_CAST (pipeline), priv->element);
753 }
754
755 /**
756  * gst_rtsp_media_set_permissions:
757  * @media: a #GstRTSPMedia
758  * @permissions: (transfer none): a #GstRTSPPermissions
759  *
760  * Set @permissions on @media.
761  */
762 void
763 gst_rtsp_media_set_permissions (GstRTSPMedia * media,
764     GstRTSPPermissions * permissions)
765 {
766   GstRTSPMediaPrivate *priv;
767
768   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
769
770   priv = media->priv;
771
772   g_mutex_lock (&priv->lock);
773   if (priv->permissions)
774     gst_rtsp_permissions_unref (priv->permissions);
775   if ((priv->permissions = permissions))
776     gst_rtsp_permissions_ref (permissions);
777   g_mutex_unlock (&priv->lock);
778 }
779
780 /**
781  * gst_rtsp_media_get_permissions:
782  * @media: a #GstRTSPMedia
783  *
784  * Get the permissions object from @media.
785  *
786  * Returns: (transfer full): a #GstRTSPPermissions object, unref after usage.
787  */
788 GstRTSPPermissions *
789 gst_rtsp_media_get_permissions (GstRTSPMedia * media)
790 {
791   GstRTSPMediaPrivate *priv;
792   GstRTSPPermissions *result;
793
794   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
795
796   priv = media->priv;
797
798   g_mutex_lock (&priv->lock);
799   if ((result = priv->permissions))
800     gst_rtsp_permissions_ref (result);
801   g_mutex_unlock (&priv->lock);
802
803   return result;
804 }
805
806 /**
807  * gst_rtsp_media_set_suspend_mode:
808  * @media: a #GstRTSPMedia
809  * @mode: the new #GstRTSPSuspendMode
810  *
811  * Control how @ media will be suspended after the SDP has been generated and
812  * after a PAUSE request has been performed.
813  *
814  * Media must be unprepared when setting the suspend mode.
815  */
816 void
817 gst_rtsp_media_set_suspend_mode (GstRTSPMedia * media, GstRTSPSuspendMode mode)
818 {
819   GstRTSPMediaPrivate *priv;
820
821   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
822
823   priv = media->priv;
824
825   g_rec_mutex_lock (&priv->state_lock);
826   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED)
827     goto was_prepared;
828   priv->suspend_mode = mode;
829   g_rec_mutex_unlock (&priv->state_lock);
830
831   return;
832
833   /* ERRORS */
834 was_prepared:
835   {
836     GST_WARNING ("media %p was prepared", media);
837     g_rec_mutex_unlock (&priv->state_lock);
838   }
839 }
840
841 /**
842  * gst_rtsp_media_get_suspend_mode:
843  * @media: a #GstRTSPMedia
844  *
845  * Get how @media will be suspended.
846  *
847  * Returns: #GstRTSPSuspendMode.
848  */
849 GstRTSPSuspendMode
850 gst_rtsp_media_get_suspend_mode (GstRTSPMedia * media)
851 {
852   GstRTSPMediaPrivate *priv;
853   GstRTSPSuspendMode res;
854
855   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_RTSP_SUSPEND_MODE_NONE);
856
857   priv = media->priv;
858
859   g_rec_mutex_lock (&priv->state_lock);
860   res = priv->suspend_mode;
861   g_rec_mutex_unlock (&priv->state_lock);
862
863   return res;
864 }
865
866 /**
867  * gst_rtsp_media_set_shared:
868  * @media: a #GstRTSPMedia
869  * @shared: the new value
870  *
871  * Set or unset if the pipeline for @media can be shared will multiple clients.
872  * When @shared is %TRUE, client requests for this media will share the media
873  * pipeline.
874  */
875 void
876 gst_rtsp_media_set_shared (GstRTSPMedia * media, gboolean shared)
877 {
878   GstRTSPMediaPrivate *priv;
879
880   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
881
882   priv = media->priv;
883
884   g_mutex_lock (&priv->lock);
885   priv->shared = shared;
886   g_mutex_unlock (&priv->lock);
887 }
888
889 /**
890  * gst_rtsp_media_is_shared:
891  * @media: a #GstRTSPMedia
892  *
893  * Check if the pipeline for @media can be shared between multiple clients.
894  *
895  * Returns: %TRUE if the media can be shared between clients.
896  */
897 gboolean
898 gst_rtsp_media_is_shared (GstRTSPMedia * media)
899 {
900   GstRTSPMediaPrivate *priv;
901   gboolean res;
902
903   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
904
905   priv = media->priv;
906
907   g_mutex_lock (&priv->lock);
908   res = priv->shared;
909   g_mutex_unlock (&priv->lock);
910
911   return res;
912 }
913
914 /**
915  * gst_rtsp_media_set_reusable:
916  * @media: a #GstRTSPMedia
917  * @reusable: the new value
918  *
919  * Set or unset if the pipeline for @media can be reused after the pipeline has
920  * been unprepared.
921  */
922 void
923 gst_rtsp_media_set_reusable (GstRTSPMedia * media, gboolean reusable)
924 {
925   GstRTSPMediaPrivate *priv;
926
927   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
928
929   priv = media->priv;
930
931   g_mutex_lock (&priv->lock);
932   priv->reusable = reusable;
933   g_mutex_unlock (&priv->lock);
934 }
935
936 /**
937  * gst_rtsp_media_is_reusable:
938  * @media: a #GstRTSPMedia
939  *
940  * Check if the pipeline for @media can be reused after an unprepare.
941  *
942  * Returns: %TRUE if the media can be reused
943  */
944 gboolean
945 gst_rtsp_media_is_reusable (GstRTSPMedia * media)
946 {
947   GstRTSPMediaPrivate *priv;
948   gboolean res;
949
950   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
951
952   priv = media->priv;
953
954   g_mutex_lock (&priv->lock);
955   res = priv->reusable;
956   g_mutex_unlock (&priv->lock);
957
958   return res;
959 }
960
961 static void
962 do_set_profiles (GstRTSPStream * stream, GstRTSPProfile * profiles)
963 {
964   gst_rtsp_stream_set_profiles (stream, *profiles);
965 }
966
967 /**
968  * gst_rtsp_media_set_profiles:
969  * @media: a #GstRTSPMedia
970  * @profiles: the new flags
971  *
972  * Configure the allowed lower transport for @media.
973  */
974 void
975 gst_rtsp_media_set_profiles (GstRTSPMedia * media, GstRTSPProfile profiles)
976 {
977   GstRTSPMediaPrivate *priv;
978
979   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
980
981   priv = media->priv;
982
983   g_mutex_lock (&priv->lock);
984   priv->profiles = profiles;
985   g_ptr_array_foreach (priv->streams, (GFunc) do_set_profiles, &profiles);
986   g_mutex_unlock (&priv->lock);
987 }
988
989 /**
990  * gst_rtsp_media_get_profiles:
991  * @media: a #GstRTSPMedia
992  *
993  * Get the allowed profiles of @media.
994  *
995  * Returns: a #GstRTSPProfile
996  */
997 GstRTSPProfile
998 gst_rtsp_media_get_profiles (GstRTSPMedia * media)
999 {
1000   GstRTSPMediaPrivate *priv;
1001   GstRTSPProfile res;
1002
1003   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_RTSP_PROFILE_UNKNOWN);
1004
1005   priv = media->priv;
1006
1007   g_mutex_lock (&priv->lock);
1008   res = priv->profiles;
1009   g_mutex_unlock (&priv->lock);
1010
1011   return res;
1012 }
1013
1014 static void
1015 do_set_protocols (GstRTSPStream * stream, GstRTSPLowerTrans * protocols)
1016 {
1017   gst_rtsp_stream_set_protocols (stream, *protocols);
1018 }
1019
1020 /**
1021  * gst_rtsp_media_set_protocols:
1022  * @media: a #GstRTSPMedia
1023  * @protocols: the new flags
1024  *
1025  * Configure the allowed lower transport for @media.
1026  */
1027 void
1028 gst_rtsp_media_set_protocols (GstRTSPMedia * media, GstRTSPLowerTrans protocols)
1029 {
1030   GstRTSPMediaPrivate *priv;
1031
1032   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1033
1034   priv = media->priv;
1035
1036   g_mutex_lock (&priv->lock);
1037   priv->protocols = protocols;
1038   g_ptr_array_foreach (priv->streams, (GFunc) do_set_protocols, &protocols);
1039   g_mutex_unlock (&priv->lock);
1040 }
1041
1042 /**
1043  * gst_rtsp_media_get_protocols:
1044  * @media: a #GstRTSPMedia
1045  *
1046  * Get the allowed protocols of @media.
1047  *
1048  * Returns: a #GstRTSPLowerTrans
1049  */
1050 GstRTSPLowerTrans
1051 gst_rtsp_media_get_protocols (GstRTSPMedia * media)
1052 {
1053   GstRTSPMediaPrivate *priv;
1054   GstRTSPLowerTrans res;
1055
1056   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media),
1057       GST_RTSP_LOWER_TRANS_UNKNOWN);
1058
1059   priv = media->priv;
1060
1061   g_mutex_lock (&priv->lock);
1062   res = priv->protocols;
1063   g_mutex_unlock (&priv->lock);
1064
1065   return res;
1066 }
1067
1068 /**
1069  * gst_rtsp_media_set_eos_shutdown:
1070  * @media: a #GstRTSPMedia
1071  * @eos_shutdown: the new value
1072  *
1073  * Set or unset if an EOS event will be sent to the pipeline for @media before
1074  * it is unprepared.
1075  */
1076 void
1077 gst_rtsp_media_set_eos_shutdown (GstRTSPMedia * media, gboolean eos_shutdown)
1078 {
1079   GstRTSPMediaPrivate *priv;
1080
1081   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1082
1083   priv = media->priv;
1084
1085   g_mutex_lock (&priv->lock);
1086   priv->eos_shutdown = eos_shutdown;
1087   g_mutex_unlock (&priv->lock);
1088 }
1089
1090 /**
1091  * gst_rtsp_media_is_eos_shutdown:
1092  * @media: a #GstRTSPMedia
1093  *
1094  * Check if the pipeline for @media will send an EOS down the pipeline before
1095  * unpreparing.
1096  *
1097  * Returns: %TRUE if the media will send EOS before unpreparing.
1098  */
1099 gboolean
1100 gst_rtsp_media_is_eos_shutdown (GstRTSPMedia * media)
1101 {
1102   GstRTSPMediaPrivate *priv;
1103   gboolean res;
1104
1105   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1106
1107   priv = media->priv;
1108
1109   g_mutex_lock (&priv->lock);
1110   res = priv->eos_shutdown;
1111   g_mutex_unlock (&priv->lock);
1112
1113   return res;
1114 }
1115
1116 /**
1117  * gst_rtsp_media_set_buffer_size:
1118  * @media: a #GstRTSPMedia
1119  * @size: the new value
1120  *
1121  * Set the kernel UDP buffer size.
1122  */
1123 void
1124 gst_rtsp_media_set_buffer_size (GstRTSPMedia * media, guint size)
1125 {
1126   GstRTSPMediaPrivate *priv;
1127   guint i;
1128
1129   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1130
1131   GST_LOG_OBJECT (media, "set buffer size %u", size);
1132
1133   priv = media->priv;
1134
1135   g_mutex_lock (&priv->lock);
1136   priv->buffer_size = size;
1137
1138   for (i = 0; i < priv->streams->len; i++) {
1139     GstRTSPStream *stream = g_ptr_array_index (priv->streams, i);
1140     gst_rtsp_stream_set_buffer_size (stream, size);
1141   }
1142   g_mutex_unlock (&priv->lock);
1143 }
1144
1145 /**
1146  * gst_rtsp_media_get_buffer_size:
1147  * @media: a #GstRTSPMedia
1148  *
1149  * Get the kernel UDP buffer size.
1150  *
1151  * Returns: the kernel UDP buffer size.
1152  */
1153 guint
1154 gst_rtsp_media_get_buffer_size (GstRTSPMedia * media)
1155 {
1156   GstRTSPMediaPrivate *priv;
1157   guint res;
1158
1159   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1160
1161   priv = media->priv;
1162
1163   g_mutex_lock (&priv->lock);
1164   res = priv->buffer_size;
1165   g_mutex_unlock (&priv->lock);
1166
1167   return res;
1168 }
1169
1170 /**
1171  * gst_rtsp_media_set_retransmission_time:
1172  * @media: a #GstRTSPMedia
1173  * @time: the new value
1174  *
1175  * Set the amount of time to store retransmission packets.
1176  */
1177 void
1178 gst_rtsp_media_set_retransmission_time (GstRTSPMedia * media, GstClockTime time)
1179 {
1180   GstRTSPMediaPrivate *priv;
1181   guint i;
1182
1183   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1184
1185   GST_LOG_OBJECT (media, "set retransmission time %" G_GUINT64_FORMAT, time);
1186
1187   priv = media->priv;
1188
1189   g_mutex_lock (&priv->lock);
1190   priv->rtx_time = time;
1191   for (i = 0; i < priv->streams->len; i++) {
1192     GstRTSPStream *stream = g_ptr_array_index (priv->streams, i);
1193
1194     gst_rtsp_stream_set_retransmission_time (stream, time);
1195   }
1196
1197   if (priv->rtpbin)
1198     g_object_set (priv->rtpbin, "do-retransmission", time > 0, NULL);
1199   g_mutex_unlock (&priv->lock);
1200 }
1201
1202 /**
1203  * gst_rtsp_media_get_retransmission_time:
1204  * @media: a #GstRTSPMedia
1205  *
1206  * Get the amount of time to store retransmission data.
1207  *
1208  * Returns: the amount of time to store retransmission data.
1209  */
1210 GstClockTime
1211 gst_rtsp_media_get_retransmission_time (GstRTSPMedia * media)
1212 {
1213   GstRTSPMediaPrivate *priv;
1214   GstClockTime res;
1215
1216   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1217
1218   priv = media->priv;
1219
1220   g_mutex_unlock (&priv->lock);
1221   res = priv->rtx_time;
1222   g_mutex_unlock (&priv->lock);
1223
1224   return res;
1225 }
1226
1227 /**
1228  * gst_rtsp_media_set_latncy:
1229  * @media: a #GstRTSPMedia
1230  * @latency: latency in milliseconds
1231  *
1232  * Configure the latency used for receiving media.
1233  */
1234 void
1235 gst_rtsp_media_set_latency (GstRTSPMedia * media, guint latency)
1236 {
1237   GstRTSPMediaPrivate *priv;
1238
1239   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1240
1241   GST_LOG_OBJECT (media, "set latency %ums", latency);
1242
1243   priv = media->priv;
1244
1245   g_mutex_lock (&priv->lock);
1246   priv->latency = latency;
1247   if (priv->rtpbin)
1248     g_object_set (priv->rtpbin, "latency", latency, NULL);
1249   g_mutex_unlock (&priv->lock);
1250 }
1251
1252 /**
1253  * gst_rtsp_media_get_latency:
1254  * @media: a #GstRTSPMedia
1255  *
1256  * Get the latency that is used for receiving media.
1257  *
1258  * Returns: latency in milliseconds
1259  */
1260 guint
1261 gst_rtsp_media_get_latency (GstRTSPMedia * media)
1262 {
1263   GstRTSPMediaPrivate *priv;
1264   guint res;
1265
1266   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1267
1268   priv = media->priv;
1269
1270   g_mutex_unlock (&priv->lock);
1271   res = priv->latency;
1272   g_mutex_unlock (&priv->lock);
1273
1274   return res;
1275 }
1276
1277 /**
1278  * gst_rtsp_media_use_time_provider:
1279  * @media: a #GstRTSPMedia
1280  * @time_provider: if a #GstNetTimeProvider should be used
1281  *
1282  * Set @media to provide a #GstNetTimeProvider.
1283  */
1284 void
1285 gst_rtsp_media_use_time_provider (GstRTSPMedia * media, gboolean time_provider)
1286 {
1287   GstRTSPMediaPrivate *priv;
1288
1289   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1290
1291   priv = media->priv;
1292
1293   g_mutex_lock (&priv->lock);
1294   priv->time_provider = time_provider;
1295   g_mutex_unlock (&priv->lock);
1296 }
1297
1298 /**
1299  * gst_rtsp_media_is_time_provider:
1300  * @media: a #GstRTSPMedia
1301  *
1302  * Check if @media can provide a #GstNetTimeProvider for its pipeline clock.
1303  *
1304  * Use gst_rtsp_media_get_time_provider() to get the network clock.
1305  *
1306  * Returns: %TRUE if @media can provide a #GstNetTimeProvider.
1307  */
1308 gboolean
1309 gst_rtsp_media_is_time_provider (GstRTSPMedia * media)
1310 {
1311   GstRTSPMediaPrivate *priv;
1312   gboolean res;
1313
1314   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1315
1316   priv = media->priv;
1317
1318   g_mutex_unlock (&priv->lock);
1319   res = priv->time_provider;
1320   g_mutex_unlock (&priv->lock);
1321
1322   return res;
1323 }
1324
1325 /**
1326  * gst_rtsp_media_set_address_pool:
1327  * @media: a #GstRTSPMedia
1328  * @pool: (transfer none): a #GstRTSPAddressPool
1329  *
1330  * configure @pool to be used as the address pool of @media.
1331  */
1332 void
1333 gst_rtsp_media_set_address_pool (GstRTSPMedia * media,
1334     GstRTSPAddressPool * pool)
1335 {
1336   GstRTSPMediaPrivate *priv;
1337   GstRTSPAddressPool *old;
1338
1339   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1340
1341   priv = media->priv;
1342
1343   GST_LOG_OBJECT (media, "set address pool %p", pool);
1344
1345   g_mutex_lock (&priv->lock);
1346   if ((old = priv->pool) != pool)
1347     priv->pool = pool ? g_object_ref (pool) : NULL;
1348   else
1349     old = NULL;
1350   g_ptr_array_foreach (priv->streams, (GFunc) gst_rtsp_stream_set_address_pool,
1351       pool);
1352   g_mutex_unlock (&priv->lock);
1353
1354   if (old)
1355     g_object_unref (old);
1356 }
1357
1358 /**
1359  * gst_rtsp_media_get_address_pool:
1360  * @media: a #GstRTSPMedia
1361  *
1362  * Get the #GstRTSPAddressPool used as the address pool of @media.
1363  *
1364  * Returns: (transfer full): the #GstRTSPAddressPool of @media. g_object_unref() after
1365  * usage.
1366  */
1367 GstRTSPAddressPool *
1368 gst_rtsp_media_get_address_pool (GstRTSPMedia * media)
1369 {
1370   GstRTSPMediaPrivate *priv;
1371   GstRTSPAddressPool *result;
1372
1373   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1374
1375   priv = media->priv;
1376
1377   g_mutex_lock (&priv->lock);
1378   if ((result = priv->pool))
1379     g_object_ref (result);
1380   g_mutex_unlock (&priv->lock);
1381
1382   return result;
1383 }
1384
1385 static GList *
1386 _find_payload_types (GstRTSPMedia * media)
1387 {
1388   gint i, n;
1389   GQueue queue = G_QUEUE_INIT;
1390
1391   n = media->priv->streams->len;
1392   for (i = 0; i < n; i++) {
1393     GstRTSPStream *stream = g_ptr_array_index (media->priv->streams, i);
1394     guint pt = gst_rtsp_stream_get_pt (stream);
1395
1396     g_queue_push_tail (&queue, GUINT_TO_POINTER (pt));
1397   }
1398
1399   return queue.head;
1400 }
1401
1402 static guint
1403 _next_available_pt (GList * payloads)
1404 {
1405   guint i;
1406
1407   for (i = 96; i <= 127; i++) {
1408     GList *iter = g_list_find (payloads, GINT_TO_POINTER (i));
1409     if (!iter)
1410       return GPOINTER_TO_UINT (i);
1411   }
1412
1413   return 0;
1414 }
1415
1416 /**
1417  * gst_rtsp_media_collect_streams:
1418  * @media: a #GstRTSPMedia
1419  *
1420  * Find all payloader elements, they should be named pay\%d in the
1421  * element of @media, and create #GstRTSPStreams for them.
1422  *
1423  * Collect all dynamic elements, named dynpay\%d, and add them to
1424  * the list of dynamic elements.
1425  *
1426  * Find all depayloader elements, they should be named depay\%d in the
1427  * element of @media, and create #GstRTSPStreams for them.
1428  */
1429 void
1430 gst_rtsp_media_collect_streams (GstRTSPMedia * media)
1431 {
1432   GstRTSPMediaPrivate *priv;
1433   GstElement *element, *elem;
1434   GstPad *pad;
1435   gint i;
1436   gboolean have_elem;
1437   gboolean more_elem_remaining = TRUE;
1438   GstRTSPTransportMode mode = 0;
1439
1440   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
1441
1442   priv = media->priv;
1443   element = priv->element;
1444
1445   have_elem = FALSE;
1446   for (i = 0; more_elem_remaining; i++) {
1447     gchar *name;
1448
1449     more_elem_remaining = FALSE;
1450
1451     name = g_strdup_printf ("pay%d", i);
1452     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
1453       GstElement *pay;
1454       GST_INFO ("found stream %d with payloader %p", i, elem);
1455
1456       /* take the pad of the payloader */
1457       pad = gst_element_get_static_pad (elem, "src");
1458
1459       /* find the real payload element in case elem is a GstBin */
1460       pay = find_payload_element (elem);
1461
1462       /* create the stream */
1463       if (pay == NULL) {
1464         GST_WARNING ("could not find real payloader, using bin");
1465         gst_rtsp_media_create_stream (media, elem, pad);
1466       } else {
1467         gst_rtsp_media_create_stream (media, pay, pad);
1468         gst_object_unref (pay);
1469       }
1470
1471       gst_object_unref (pad);
1472       gst_object_unref (elem);
1473
1474       have_elem = TRUE;
1475       more_elem_remaining = TRUE;
1476       mode |= GST_RTSP_TRANSPORT_MODE_PLAY;
1477     }
1478     g_free (name);
1479
1480     name = g_strdup_printf ("dynpay%d", i);
1481     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
1482       /* a stream that will dynamically create pads to provide RTP packets */
1483       GST_INFO ("found dynamic element %d, %p", i, elem);
1484
1485       g_mutex_lock (&priv->lock);
1486       priv->dynamic = g_list_prepend (priv->dynamic, elem);
1487       g_mutex_unlock (&priv->lock);
1488
1489       have_elem = TRUE;
1490       more_elem_remaining = TRUE;
1491       mode |= GST_RTSP_TRANSPORT_MODE_PLAY;
1492     }
1493     g_free (name);
1494
1495     name = g_strdup_printf ("depay%d", i);
1496     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
1497       GST_INFO ("found stream %d with depayloader %p", i, elem);
1498
1499       /* take the pad of the payloader */
1500       pad = gst_element_get_static_pad (elem, "sink");
1501       /* create the stream */
1502       gst_rtsp_media_create_stream (media, elem, pad);
1503       gst_object_unref (pad);
1504       gst_object_unref (elem);
1505
1506       have_elem = TRUE;
1507       more_elem_remaining = TRUE;
1508       mode |= GST_RTSP_TRANSPORT_MODE_RECORD;
1509     }
1510     g_free (name);
1511   }
1512
1513   if (have_elem) {
1514     if (priv->transport_mode != mode)
1515       GST_WARNING ("found different mode than expected (0x%02x != 0x%02d)",
1516           priv->transport_mode, mode);
1517   }
1518 }
1519
1520 /**
1521  * gst_rtsp_media_create_stream:
1522  * @media: a #GstRTSPMedia
1523  * @payloader: a #GstElement
1524  * @pad: a #GstPad
1525  *
1526  * Create a new stream in @media that provides RTP data on @pad.
1527  * @pad should be a pad of an element inside @media->element.
1528  *
1529  * Returns: (transfer none): a new #GstRTSPStream that remains valid for as long
1530  * as @media exists.
1531  */
1532 GstRTSPStream *
1533 gst_rtsp_media_create_stream (GstRTSPMedia * media, GstElement * payloader,
1534     GstPad * pad)
1535 {
1536   GstRTSPMediaPrivate *priv;
1537   GstRTSPStream *stream;
1538   GstPad *ghostpad;
1539   gchar *name;
1540   gint idx;
1541
1542   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1543   g_return_val_if_fail (GST_IS_ELEMENT (payloader), NULL);
1544   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
1545
1546   priv = media->priv;
1547
1548   g_mutex_lock (&priv->lock);
1549   idx = priv->streams->len;
1550
1551   GST_DEBUG ("media %p: creating stream with index %d", media, idx);
1552
1553   if (GST_PAD_IS_SRC (pad))
1554     name = g_strdup_printf ("src_%u", idx);
1555   else
1556     name = g_strdup_printf ("sink_%u", idx);
1557
1558   ghostpad = gst_ghost_pad_new (name, pad);
1559   gst_pad_set_active (ghostpad, TRUE);
1560   gst_element_add_pad (priv->element, ghostpad);
1561   g_free (name);
1562
1563   stream = gst_rtsp_stream_new (idx, payloader, ghostpad);
1564   if (priv->pool)
1565     gst_rtsp_stream_set_address_pool (stream, priv->pool);
1566   gst_rtsp_stream_set_profiles (stream, priv->profiles);
1567   gst_rtsp_stream_set_protocols (stream, priv->protocols);
1568   gst_rtsp_stream_set_retransmission_time (stream, priv->rtx_time);
1569   gst_rtsp_stream_set_buffer_size (stream, priv->buffer_size);
1570
1571   g_ptr_array_add (priv->streams, stream);
1572
1573   if (GST_PAD_IS_SRC (pad)) {
1574     gint i, n;
1575
1576     if (priv->payloads)
1577       g_list_free (priv->payloads);
1578     priv->payloads = _find_payload_types (media);
1579
1580     n = priv->streams->len;
1581     for (i = 0; i < n; i++) {
1582       GstRTSPStream *stream = g_ptr_array_index (priv->streams, i);
1583       guint rtx_pt = _next_available_pt (priv->payloads);
1584
1585       if (rtx_pt == 0) {
1586         GST_WARNING ("Ran out of space of dynamic payload types");
1587         break;
1588       }
1589
1590       gst_rtsp_stream_set_retransmission_pt (stream, rtx_pt);
1591
1592       priv->payloads =
1593           g_list_append (priv->payloads, GUINT_TO_POINTER (rtx_pt));
1594     }
1595   }
1596   g_mutex_unlock (&priv->lock);
1597
1598   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STREAM], 0, stream,
1599       NULL);
1600
1601   return stream;
1602 }
1603
1604 static void
1605 gst_rtsp_media_remove_stream (GstRTSPMedia * media, GstRTSPStream * stream)
1606 {
1607   GstRTSPMediaPrivate *priv;
1608   GstPad *srcpad;
1609
1610   priv = media->priv;
1611
1612   g_mutex_lock (&priv->lock);
1613   /* remove the ghostpad */
1614   srcpad = gst_rtsp_stream_get_srcpad (stream);
1615   gst_element_remove_pad (priv->element, srcpad);
1616   gst_object_unref (srcpad);
1617   /* now remove the stream */
1618   g_object_ref (stream);
1619   g_ptr_array_remove (priv->streams, stream);
1620   g_mutex_unlock (&priv->lock);
1621
1622   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_REMOVED_STREAM], 0,
1623       stream, NULL);
1624
1625   g_object_unref (stream);
1626 }
1627
1628 /**
1629  * gst_rtsp_media_n_streams:
1630  * @media: a #GstRTSPMedia
1631  *
1632  * Get the number of streams in this media.
1633  *
1634  * Returns: The number of streams.
1635  */
1636 guint
1637 gst_rtsp_media_n_streams (GstRTSPMedia * media)
1638 {
1639   GstRTSPMediaPrivate *priv;
1640   guint res;
1641
1642   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), 0);
1643
1644   priv = media->priv;
1645
1646   g_mutex_lock (&priv->lock);
1647   res = priv->streams->len;
1648   g_mutex_unlock (&priv->lock);
1649
1650   return res;
1651 }
1652
1653 /**
1654  * gst_rtsp_media_get_stream:
1655  * @media: a #GstRTSPMedia
1656  * @idx: the stream index
1657  *
1658  * Retrieve the stream with index @idx from @media.
1659  *
1660  * Returns: (nullable) (transfer none): the #GstRTSPStream at index
1661  * @idx or %NULL when a stream with that index did not exist.
1662  */
1663 GstRTSPStream *
1664 gst_rtsp_media_get_stream (GstRTSPMedia * media, guint idx)
1665 {
1666   GstRTSPMediaPrivate *priv;
1667   GstRTSPStream *res;
1668
1669   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1670
1671   priv = media->priv;
1672
1673   g_mutex_lock (&priv->lock);
1674   if (idx < priv->streams->len)
1675     res = g_ptr_array_index (priv->streams, idx);
1676   else
1677     res = NULL;
1678   g_mutex_unlock (&priv->lock);
1679
1680   return res;
1681 }
1682
1683 /**
1684  * gst_rtsp_media_find_stream:
1685  * @media: a #GstRTSPMedia
1686  * @control: the control of the stream
1687  *
1688  * Find a stream in @media with @control as the control uri.
1689  *
1690  * Returns: (nullable) (transfer none): the #GstRTSPStream with
1691  * control uri @control or %NULL when a stream with that control did
1692  * not exist.
1693  */
1694 GstRTSPStream *
1695 gst_rtsp_media_find_stream (GstRTSPMedia * media, const gchar * control)
1696 {
1697   GstRTSPMediaPrivate *priv;
1698   GstRTSPStream *res;
1699   gint i;
1700
1701   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1702   g_return_val_if_fail (control != NULL, NULL);
1703
1704   priv = media->priv;
1705
1706   res = NULL;
1707
1708   g_mutex_lock (&priv->lock);
1709   for (i = 0; i < priv->streams->len; i++) {
1710     GstRTSPStream *test;
1711
1712     test = g_ptr_array_index (priv->streams, i);
1713     if (gst_rtsp_stream_has_control (test, control)) {
1714       res = test;
1715       break;
1716     }
1717   }
1718   g_mutex_unlock (&priv->lock);
1719
1720   return res;
1721 }
1722
1723 /* called with state-lock */
1724 static gboolean
1725 default_convert_range (GstRTSPMedia * media, GstRTSPTimeRange * range,
1726     GstRTSPRangeUnit unit)
1727 {
1728   return gst_rtsp_range_convert_units (range, unit);
1729 }
1730
1731 /**
1732  * gst_rtsp_media_get_range_string:
1733  * @media: a #GstRTSPMedia
1734  * @play: for the PLAY request
1735  * @unit: the unit to use for the string
1736  *
1737  * Get the current range as a string. @media must be prepared with
1738  * gst_rtsp_media_prepare ().
1739  *
1740  * Returns: (transfer full): The range as a string, g_free() after usage.
1741  */
1742 gchar *
1743 gst_rtsp_media_get_range_string (GstRTSPMedia * media, gboolean play,
1744     GstRTSPRangeUnit unit)
1745 {
1746   GstRTSPMediaClass *klass;
1747   GstRTSPMediaPrivate *priv;
1748   gchar *result;
1749   GstRTSPTimeRange range;
1750
1751   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1752   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
1753   g_return_val_if_fail (klass->convert_range != NULL, FALSE);
1754
1755   priv = media->priv;
1756
1757   g_rec_mutex_lock (&priv->state_lock);
1758   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
1759       priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
1760     goto not_prepared;
1761
1762   g_mutex_lock (&priv->lock);
1763
1764   /* Update the range value with current position/duration */
1765   collect_media_stats (media);
1766
1767   /* make copy */
1768   range = priv->range;
1769
1770   if (!play && priv->n_active > 0) {
1771     range.min.type = GST_RTSP_TIME_NOW;
1772     range.min.seconds = -1;
1773   }
1774   g_mutex_unlock (&priv->lock);
1775   g_rec_mutex_unlock (&priv->state_lock);
1776
1777   if (!klass->convert_range (media, &range, unit))
1778     goto conversion_failed;
1779
1780   result = gst_rtsp_range_to_string (&range);
1781
1782   return result;
1783
1784   /* ERRORS */
1785 not_prepared:
1786   {
1787     GST_WARNING ("media %p was not prepared", media);
1788     g_rec_mutex_unlock (&priv->state_lock);
1789     return NULL;
1790   }
1791 conversion_failed:
1792   {
1793     GST_WARNING ("range conversion to unit %d failed", unit);
1794     return NULL;
1795   }
1796 }
1797
1798 static void
1799 stream_update_blocked (GstRTSPStream * stream, GstRTSPMedia * media)
1800 {
1801   gst_rtsp_stream_set_blocked (stream, media->priv->blocked);
1802 }
1803
1804 static void
1805 media_streams_set_blocked (GstRTSPMedia * media, gboolean blocked)
1806 {
1807   GstRTSPMediaPrivate *priv = media->priv;
1808
1809   GST_DEBUG ("media %p set blocked %d", media, blocked);
1810   priv->blocked = blocked;
1811   g_ptr_array_foreach (priv->streams, (GFunc) stream_update_blocked, media);
1812 }
1813
1814 static void
1815 gst_rtsp_media_set_status (GstRTSPMedia * media, GstRTSPMediaStatus status)
1816 {
1817   GstRTSPMediaPrivate *priv = media->priv;
1818
1819   g_mutex_lock (&priv->lock);
1820   priv->status = status;
1821   GST_DEBUG ("setting new status to %d", status);
1822   g_cond_broadcast (&priv->cond);
1823   g_mutex_unlock (&priv->lock);
1824 }
1825
1826 /**
1827  * gst_rtsp_media_get_status:
1828  * @media: a #GstRTSPMedia
1829  *
1830  * Get the status of @media. When @media is busy preparing, this function waits
1831  * until @media is prepared or in error.
1832  *
1833  * Returns: the status of @media.
1834  */
1835 GstRTSPMediaStatus
1836 gst_rtsp_media_get_status (GstRTSPMedia * media)
1837 {
1838   GstRTSPMediaPrivate *priv = media->priv;
1839   GstRTSPMediaStatus result;
1840   gint64 end_time;
1841
1842   g_mutex_lock (&priv->lock);
1843   end_time = g_get_monotonic_time () + 20 * G_TIME_SPAN_SECOND;
1844   /* while we are preparing, wait */
1845   while (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING) {
1846     GST_DEBUG ("waiting for status change");
1847     if (!g_cond_wait_until (&priv->cond, &priv->lock, end_time)) {
1848       GST_DEBUG ("timeout, assuming error status");
1849       priv->status = GST_RTSP_MEDIA_STATUS_ERROR;
1850     }
1851   }
1852   /* could be success or error */
1853   result = priv->status;
1854   GST_DEBUG ("got status %d", result);
1855   g_mutex_unlock (&priv->lock);
1856
1857   return result;
1858 }
1859
1860 /**
1861  * gst_rtsp_media_seek:
1862  * @media: a #GstRTSPMedia
1863  * @range: (transfer none): a #GstRTSPTimeRange
1864  *
1865  * Seek the pipeline of @media to @range. @media must be prepared with
1866  * gst_rtsp_media_prepare().
1867  *
1868  * Returns: %TRUE on success.
1869  */
1870 gboolean
1871 gst_rtsp_media_seek (GstRTSPMedia * media, GstRTSPTimeRange * range)
1872 {
1873   GstRTSPMediaClass *klass;
1874   GstRTSPMediaPrivate *priv;
1875   gboolean res;
1876   GstClockTime start, stop;
1877   GstSeekType start_type, stop_type;
1878   GstQuery *query;
1879   gint64 current_position;
1880
1881   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1882
1883   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1884   g_return_val_if_fail (range != NULL, FALSE);
1885   g_return_val_if_fail (klass->convert_range != NULL, FALSE);
1886
1887   priv = media->priv;
1888
1889   g_rec_mutex_lock (&priv->state_lock);
1890   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
1891     goto not_prepared;
1892
1893   /* Update the seekable state of the pipeline in case it changed */
1894   if ((priv->transport_mode & GST_RTSP_TRANSPORT_MODE_RECORD)) {
1895     /* TODO: Seeking for RECORD? */
1896     priv->seekable = FALSE;
1897   } else {
1898     query = gst_query_new_seeking (GST_FORMAT_TIME);
1899     if (gst_element_query (priv->pipeline, query)) {
1900       GstFormat format;
1901       gboolean seekable;
1902       gint64 start, end;
1903
1904       gst_query_parse_seeking (query, &format, &seekable, &start, &end);
1905       priv->seekable = seekable;
1906     }
1907     gst_query_unref (query);
1908   }
1909
1910   if (!priv->seekable)
1911     goto not_seekable;
1912
1913   start_type = stop_type = GST_SEEK_TYPE_NONE;
1914
1915   if (!klass->convert_range (media, range, GST_RTSP_RANGE_NPT))
1916     goto not_supported;
1917   gst_rtsp_range_get_times (range, &start, &stop);
1918
1919   GST_INFO ("got %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1920       GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1921   GST_INFO ("current %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1922       GST_TIME_ARGS (priv->range_start), GST_TIME_ARGS (priv->range_stop));
1923
1924   current_position = -1;
1925   if (klass->query_position)
1926     klass->query_position (media, &current_position);
1927   GST_INFO ("current media position %" GST_TIME_FORMAT,
1928       GST_TIME_ARGS (current_position));
1929
1930   if (start != GST_CLOCK_TIME_NONE)
1931     start_type = GST_SEEK_TYPE_SET;
1932
1933   if (priv->range_stop == stop)
1934     stop = GST_CLOCK_TIME_NONE;
1935   else if (stop != GST_CLOCK_TIME_NONE)
1936     stop_type = GST_SEEK_TYPE_SET;
1937
1938   if (start != GST_CLOCK_TIME_NONE || stop != GST_CLOCK_TIME_NONE) {
1939     GstSeekFlags flags;
1940
1941     GST_INFO ("seeking to %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1942         GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1943
1944     /* depends on the current playing state of the pipeline. We might need to
1945      * queue this until we get EOS. */
1946     flags = GST_SEEK_FLAG_FLUSH;
1947
1948     /* if range start was not supplied we must continue from current position.
1949      * but since we're doing a flushing seek, let us query the current position
1950      * so we end up at exactly the same position after the seek. */
1951     if (range->min.type == GST_RTSP_TIME_END) { /* Yepp, that's right! */
1952       if (current_position == -1) {
1953         GST_WARNING ("current position unknown");
1954       } else {
1955         GST_DEBUG ("doing accurate seek to %" GST_TIME_FORMAT,
1956             GST_TIME_ARGS (current_position));
1957         start = current_position;
1958         start_type = GST_SEEK_TYPE_SET;
1959         flags |= GST_SEEK_FLAG_ACCURATE;
1960       }
1961     } else {
1962       /* only set keyframe flag when modifying start */
1963       if (start_type != GST_SEEK_TYPE_NONE)
1964         flags |= GST_SEEK_FLAG_KEY_UNIT;
1965     }
1966
1967     if (start == current_position && stop_type == GST_SEEK_TYPE_NONE) {
1968       GST_DEBUG ("not seeking because no position change");
1969       res = TRUE;
1970     } else {
1971       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
1972       if (priv->blocked)
1973         media_streams_set_blocked (media, TRUE);
1974
1975       /* FIXME, we only do forwards playback, no trick modes yet */
1976       res = gst_element_seek (priv->pipeline, 1.0, GST_FORMAT_TIME,
1977           flags, start_type, start, stop_type, stop);
1978
1979       /* and block for the seek to complete */
1980       GST_INFO ("done seeking %d", res);
1981       if (!res)
1982         goto seek_failed;
1983
1984       g_rec_mutex_unlock (&priv->state_lock);
1985
1986       /* wait until pipeline is prerolled again, this will also collect stats */
1987       if (!wait_preroll (media))
1988         goto preroll_failed;
1989
1990       g_rec_mutex_lock (&priv->state_lock);
1991       GST_INFO ("prerolled again");
1992     }
1993   } else {
1994     GST_INFO ("no seek needed");
1995     res = TRUE;
1996   }
1997   g_rec_mutex_unlock (&priv->state_lock);
1998
1999   return res;
2000
2001   /* ERRORS */
2002 not_prepared:
2003   {
2004     g_rec_mutex_unlock (&priv->state_lock);
2005     GST_INFO ("media %p is not prepared", media);
2006     return FALSE;
2007   }
2008 not_seekable:
2009   {
2010     g_rec_mutex_unlock (&priv->state_lock);
2011     GST_INFO ("pipeline is not seekable");
2012     return FALSE;
2013   }
2014 not_supported:
2015   {
2016     g_rec_mutex_unlock (&priv->state_lock);
2017     GST_WARNING ("conversion to npt not supported");
2018     return FALSE;
2019   }
2020 seek_failed:
2021   {
2022     g_rec_mutex_unlock (&priv->state_lock);
2023     GST_INFO ("seeking failed");
2024     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2025     return FALSE;
2026   }
2027 preroll_failed:
2028   {
2029     GST_WARNING ("failed to preroll after seek");
2030     return FALSE;
2031   }
2032 }
2033
2034 static void
2035 stream_collect_blocking (GstRTSPStream * stream, gboolean * blocked)
2036 {
2037   *blocked &= gst_rtsp_stream_is_blocking (stream);
2038 }
2039
2040 static gboolean
2041 media_streams_blocking (GstRTSPMedia * media)
2042 {
2043   gboolean blocking = TRUE;
2044
2045   g_ptr_array_foreach (media->priv->streams, (GFunc) stream_collect_blocking,
2046       &blocking);
2047
2048   return blocking;
2049 }
2050
2051 static GstStateChangeReturn
2052 set_state (GstRTSPMedia * media, GstState state)
2053 {
2054   GstRTSPMediaPrivate *priv = media->priv;
2055   GstStateChangeReturn ret;
2056
2057   GST_INFO ("set state to %s for media %p", gst_element_state_get_name (state),
2058       media);
2059   ret = gst_element_set_state (priv->pipeline, state);
2060
2061   return ret;
2062 }
2063
2064 static GstStateChangeReturn
2065 set_target_state (GstRTSPMedia * media, GstState state, gboolean do_state)
2066 {
2067   GstRTSPMediaPrivate *priv = media->priv;
2068   GstStateChangeReturn ret;
2069
2070   GST_INFO ("set target state to %s for media %p",
2071       gst_element_state_get_name (state), media);
2072   priv->target_state = state;
2073
2074   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_TARGET_STATE], 0,
2075       priv->target_state, NULL);
2076
2077   if (do_state)
2078     ret = set_state (media, state);
2079   else
2080     ret = GST_STATE_CHANGE_SUCCESS;
2081
2082   return ret;
2083 }
2084
2085 /* called with state-lock */
2086 static gboolean
2087 default_handle_message (GstRTSPMedia * media, GstMessage * message)
2088 {
2089   GstRTSPMediaPrivate *priv = media->priv;
2090   GstMessageType type;
2091
2092   type = GST_MESSAGE_TYPE (message);
2093
2094   switch (type) {
2095     case GST_MESSAGE_STATE_CHANGED:
2096     {
2097       GstState old, new, pending;
2098
2099       if (GST_MESSAGE_SRC (message) != GST_OBJECT (priv->pipeline))
2100         break;
2101
2102       gst_message_parse_state_changed (message, &old, &new, &pending);
2103
2104       GST_DEBUG ("%p: went from %s to %s (pending %s)", media,
2105           gst_element_state_get_name (old), gst_element_state_get_name (new),
2106           gst_element_state_get_name (pending));
2107       if ((priv->transport_mode & GST_RTSP_TRANSPORT_MODE_RECORD)
2108           && old == GST_STATE_READY && new == GST_STATE_PAUSED) {
2109         GST_INFO ("%p: went to PAUSED, prepared now", media);
2110         collect_media_stats (media);
2111
2112         if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2113           gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2114       }
2115
2116       break;
2117     }
2118     case GST_MESSAGE_BUFFERING:
2119     {
2120       gint percent;
2121
2122       gst_message_parse_buffering (message, &percent);
2123
2124       /* no state management needed for live pipelines */
2125       if (priv->is_live)
2126         break;
2127
2128       if (percent == 100) {
2129         /* a 100% message means buffering is done */
2130         priv->buffering = FALSE;
2131         /* if the desired state is playing, go back */
2132         if (priv->target_state == GST_STATE_PLAYING) {
2133           GST_INFO ("Buffering done, setting pipeline to PLAYING");
2134           set_state (media, GST_STATE_PLAYING);
2135         } else {
2136           GST_INFO ("Buffering done");
2137         }
2138       } else {
2139         /* buffering busy */
2140         if (priv->buffering == FALSE) {
2141           if (priv->target_state == GST_STATE_PLAYING) {
2142             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
2143             GST_INFO ("Buffering, setting pipeline to PAUSED ...");
2144             set_state (media, GST_STATE_PAUSED);
2145           } else {
2146             GST_INFO ("Buffering ...");
2147           }
2148         }
2149         priv->buffering = TRUE;
2150       }
2151       break;
2152     }
2153     case GST_MESSAGE_LATENCY:
2154     {
2155       gst_bin_recalculate_latency (GST_BIN_CAST (priv->pipeline));
2156       break;
2157     }
2158     case GST_MESSAGE_ERROR:
2159     {
2160       GError *gerror;
2161       gchar *debug;
2162
2163       gst_message_parse_error (message, &gerror, &debug);
2164       GST_WARNING ("%p: got error %s (%s)", media, gerror->message, debug);
2165       g_error_free (gerror);
2166       g_free (debug);
2167
2168       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2169       break;
2170     }
2171     case GST_MESSAGE_WARNING:
2172     {
2173       GError *gerror;
2174       gchar *debug;
2175
2176       gst_message_parse_warning (message, &gerror, &debug);
2177       GST_WARNING ("%p: got warning %s (%s)", media, gerror->message, debug);
2178       g_error_free (gerror);
2179       g_free (debug);
2180       break;
2181     }
2182     case GST_MESSAGE_ELEMENT:
2183     {
2184       const GstStructure *s;
2185
2186       s = gst_message_get_structure (message);
2187       if (gst_structure_has_name (s, "GstRTSPStreamBlocking")) {
2188         GST_DEBUG ("media received blocking message");
2189         if (priv->blocked && media_streams_blocking (media)) {
2190           GST_DEBUG ("media is blocking");
2191           collect_media_stats (media);
2192
2193           if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2194             gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2195         }
2196       }
2197       break;
2198     }
2199     case GST_MESSAGE_STREAM_STATUS:
2200       break;
2201     case GST_MESSAGE_ASYNC_DONE:
2202       if (priv->adding) {
2203         /* when we are dynamically adding pads, the addition of the udpsrc will
2204          * temporarily produce ASYNC_DONE messages. We have to ignore them and
2205          * wait for the final ASYNC_DONE after everything prerolled */
2206         GST_INFO ("%p: ignoring ASYNC_DONE", media);
2207       } else {
2208         GST_INFO ("%p: got ASYNC_DONE", media);
2209         collect_media_stats (media);
2210
2211         if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2212           gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2213       }
2214       break;
2215     case GST_MESSAGE_EOS:
2216       GST_INFO ("%p: got EOS", media);
2217
2218       if (priv->status == GST_RTSP_MEDIA_STATUS_UNPREPARING) {
2219         GST_DEBUG ("shutting down after EOS");
2220         finish_unprepare (media);
2221       }
2222       break;
2223     default:
2224       GST_INFO ("%p: got message type %d (%s)", media, type,
2225           gst_message_type_get_name (type));
2226       break;
2227   }
2228   return TRUE;
2229 }
2230
2231 static gboolean
2232 bus_message (GstBus * bus, GstMessage * message, GstRTSPMedia * media)
2233 {
2234   GstRTSPMediaPrivate *priv = media->priv;
2235   GstRTSPMediaClass *klass;
2236   gboolean ret;
2237
2238   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2239
2240   g_rec_mutex_lock (&priv->state_lock);
2241   if (klass->handle_message)
2242     ret = klass->handle_message (media, message);
2243   else
2244     ret = FALSE;
2245   g_rec_mutex_unlock (&priv->state_lock);
2246
2247   return ret;
2248 }
2249
2250 static void
2251 watch_destroyed (GstRTSPMedia * media)
2252 {
2253   GST_DEBUG_OBJECT (media, "source destroyed");
2254   g_object_unref (media);
2255 }
2256
2257 static GstElement *
2258 find_payload_element (GstElement * payloader)
2259 {
2260   GstElement *pay = NULL;
2261
2262   if (GST_IS_BIN (payloader)) {
2263     GstIterator *iter;
2264     GValue item = { 0 };
2265
2266     iter = gst_bin_iterate_recurse (GST_BIN (payloader));
2267     while (gst_iterator_next (iter, &item) == GST_ITERATOR_OK) {
2268       GstElement *element = (GstElement *) g_value_get_object (&item);
2269       GstElementClass *eclass = GST_ELEMENT_GET_CLASS (element);
2270       const gchar *klass;
2271
2272       klass =
2273           gst_element_class_get_metadata (eclass, GST_ELEMENT_METADATA_KLASS);
2274       if (klass == NULL)
2275         continue;
2276
2277       if (strstr (klass, "Payloader") && strstr (klass, "RTP")) {
2278         pay = gst_object_ref (element);
2279         g_value_unset (&item);
2280         break;
2281       }
2282       g_value_unset (&item);
2283     }
2284     gst_iterator_free (iter);
2285   } else {
2286     pay = g_object_ref (payloader);
2287   }
2288
2289   return pay;
2290 }
2291
2292 /* called from streaming threads */
2293 static void
2294 pad_added_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
2295 {
2296   GstRTSPMediaPrivate *priv = media->priv;
2297   GstRTSPStream *stream;
2298   GstElement *pay;
2299
2300   /* find the real payload element */
2301   pay = find_payload_element (element);
2302   stream = gst_rtsp_media_create_stream (media, pay, pad);
2303   gst_object_unref (pay);
2304
2305   GST_INFO ("pad added %s:%s, stream %p", GST_DEBUG_PAD_NAME (pad), stream);
2306
2307   g_rec_mutex_lock (&priv->state_lock);
2308   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARING)
2309     goto not_preparing;
2310
2311   g_object_set_data (G_OBJECT (pad), "gst-rtsp-dynpad-stream", stream);
2312
2313   /* we will be adding elements below that will cause ASYNC_DONE to be
2314    * posted in the bus. We want to ignore those messages until the
2315    * pipeline really prerolled. */
2316   priv->adding = TRUE;
2317
2318   /* join the element in the PAUSED state because this callback is
2319    * called from the streaming thread and it is PAUSED */
2320   if (!gst_rtsp_stream_join_bin (stream, GST_BIN (priv->pipeline),
2321           priv->rtpbin, GST_STATE_PAUSED)) {
2322     GST_WARNING ("failed to join bin element");
2323   }
2324
2325   priv->adding = FALSE;
2326   g_rec_mutex_unlock (&priv->state_lock);
2327
2328   return;
2329
2330   /* ERRORS */
2331 not_preparing:
2332   {
2333     gst_rtsp_media_remove_stream (media, stream);
2334     g_rec_mutex_unlock (&priv->state_lock);
2335     GST_INFO ("ignore pad because we are not preparing");
2336     return;
2337   }
2338 }
2339
2340 static void
2341 pad_removed_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
2342 {
2343   GstRTSPMediaPrivate *priv = media->priv;
2344   GstRTSPStream *stream;
2345
2346   stream = g_object_get_data (G_OBJECT (pad), "gst-rtsp-dynpad-stream");
2347   if (stream == NULL)
2348     return;
2349
2350   GST_INFO ("pad removed %s:%s, stream %p", GST_DEBUG_PAD_NAME (pad), stream);
2351
2352   g_rec_mutex_lock (&priv->state_lock);
2353   gst_rtsp_stream_leave_bin (stream, GST_BIN (priv->pipeline), priv->rtpbin);
2354   g_rec_mutex_unlock (&priv->state_lock);
2355
2356   gst_rtsp_media_remove_stream (media, stream);
2357 }
2358
2359 static void
2360 remove_fakesink (GstRTSPMediaPrivate * priv)
2361 {
2362   GstElement *fakesink;
2363
2364   g_mutex_lock (&priv->lock);
2365   if ((fakesink = priv->fakesink))
2366     gst_object_ref (fakesink);
2367   priv->fakesink = NULL;
2368   g_mutex_unlock (&priv->lock);
2369
2370   if (fakesink) {
2371     gst_bin_remove (GST_BIN (priv->pipeline), fakesink);
2372     gst_element_set_state (fakesink, GST_STATE_NULL);
2373     gst_object_unref (fakesink);
2374     GST_INFO ("removed fakesink");
2375   }
2376 }
2377
2378 static void
2379 no_more_pads_cb (GstElement * element, GstRTSPMedia * media)
2380 {
2381   GstRTSPMediaPrivate *priv = media->priv;
2382
2383   GST_INFO ("no more pads");
2384   remove_fakesink (priv);
2385 }
2386
2387 typedef struct _DynPaySignalHandlers DynPaySignalHandlers;
2388
2389 struct _DynPaySignalHandlers
2390 {
2391   gulong pad_added_handler;
2392   gulong pad_removed_handler;
2393   gulong no_more_pads_handler;
2394 };
2395
2396 static gboolean
2397 start_preroll (GstRTSPMedia * media)
2398 {
2399   GstRTSPMediaPrivate *priv = media->priv;
2400   GstStateChangeReturn ret;
2401
2402   GST_INFO ("setting pipeline to PAUSED for media %p", media);
2403   /* first go to PAUSED */
2404   ret = set_target_state (media, GST_STATE_PAUSED, TRUE);
2405
2406   switch (ret) {
2407     case GST_STATE_CHANGE_SUCCESS:
2408       GST_INFO ("SUCCESS state change for media %p", media);
2409       priv->seekable = TRUE;
2410       break;
2411     case GST_STATE_CHANGE_ASYNC:
2412       GST_INFO ("ASYNC state change for media %p", media);
2413       priv->seekable = TRUE;
2414       break;
2415     case GST_STATE_CHANGE_NO_PREROLL:
2416       /* we need to go to PLAYING */
2417       GST_INFO ("NO_PREROLL state change: live media %p", media);
2418       /* FIXME we disable seeking for live streams for now. We should perform a
2419        * seeking query in preroll instead */
2420       priv->seekable = FALSE;
2421       priv->is_live = TRUE;
2422       if (!(priv->transport_mode & GST_RTSP_TRANSPORT_MODE_RECORD)) {
2423         /* start blocked  to make sure nothing goes to the sink */
2424         media_streams_set_blocked (media, TRUE);
2425       }
2426       ret = set_state (media, GST_STATE_PLAYING);
2427       if (ret == GST_STATE_CHANGE_FAILURE)
2428         goto state_failed;
2429       break;
2430     case GST_STATE_CHANGE_FAILURE:
2431       goto state_failed;
2432   }
2433
2434   return TRUE;
2435
2436 state_failed:
2437   {
2438     GST_WARNING ("failed to preroll pipeline");
2439     return FALSE;
2440   }
2441 }
2442
2443 static gboolean
2444 wait_preroll (GstRTSPMedia * media)
2445 {
2446   GstRTSPMediaStatus status;
2447
2448   GST_DEBUG ("wait to preroll pipeline");
2449
2450   /* wait until pipeline is prerolled */
2451   status = gst_rtsp_media_get_status (media);
2452   if (status == GST_RTSP_MEDIA_STATUS_ERROR)
2453     goto preroll_failed;
2454
2455   return TRUE;
2456
2457 preroll_failed:
2458   {
2459     GST_WARNING ("failed to preroll pipeline");
2460     return FALSE;
2461   }
2462 }
2463
2464 static GstElement *
2465 request_aux_sender (GstElement * rtpbin, guint sessid, GstRTSPMedia * media)
2466 {
2467   GstRTSPMediaPrivate *priv = media->priv;
2468   GstRTSPStream *stream = NULL;
2469   guint i;
2470
2471   g_mutex_lock (&priv->lock);
2472   for (i = 0; i < priv->streams->len; i++) {
2473     stream = g_ptr_array_index (priv->streams, i);
2474
2475     if (sessid == gst_rtsp_stream_get_index (stream))
2476       break;
2477   }
2478   g_mutex_unlock (&priv->lock);
2479
2480   return gst_rtsp_stream_request_aux_sender (stream, sessid);
2481 }
2482
2483 static gboolean
2484 start_prepare (GstRTSPMedia * media)
2485 {
2486   GstRTSPMediaPrivate *priv = media->priv;
2487   guint i;
2488   GList *walk;
2489
2490   /* link streams we already have, other streams might appear when we have
2491    * dynamic elements */
2492   for (i = 0; i < priv->streams->len; i++) {
2493     GstRTSPStream *stream;
2494
2495     stream = g_ptr_array_index (priv->streams, i);
2496
2497     if (priv->rtx_time > 0) {
2498       /* enable retransmission by setting rtprtxsend as the "aux" element of rtpbin */
2499       g_signal_connect (priv->rtpbin, "request-aux-sender",
2500           (GCallback) request_aux_sender, media);
2501     }
2502
2503     if (!gst_rtsp_stream_join_bin (stream, GST_BIN (priv->pipeline),
2504             priv->rtpbin, GST_STATE_NULL)) {
2505       goto join_bin_failed;
2506     }
2507   }
2508
2509   if (priv->rtpbin)
2510     g_object_set (priv->rtpbin, "do-retransmission", priv->rtx_time > 0, NULL);
2511
2512   for (walk = priv->dynamic; walk; walk = g_list_next (walk)) {
2513     GstElement *elem = walk->data;
2514     DynPaySignalHandlers *handlers = g_slice_new (DynPaySignalHandlers);
2515
2516     GST_INFO ("adding callbacks for dynamic element %p", elem);
2517
2518     handlers->pad_added_handler = g_signal_connect (elem, "pad-added",
2519         (GCallback) pad_added_cb, media);
2520     handlers->pad_removed_handler = g_signal_connect (elem, "pad-removed",
2521         (GCallback) pad_removed_cb, media);
2522     handlers->no_more_pads_handler = g_signal_connect (elem, "no-more-pads",
2523         (GCallback) no_more_pads_cb, media);
2524
2525     g_object_set_data (G_OBJECT (elem), "gst-rtsp-dynpay-handlers", handlers);
2526
2527     if (!priv->fakesink) {
2528       /* we add a fakesink here in order to make the state change async. We remove
2529        * the fakesink again in the no-more-pads callback. */
2530       priv->fakesink = gst_element_factory_make ("fakesink", "fakesink");
2531       gst_bin_add (GST_BIN (priv->pipeline), priv->fakesink);
2532     }
2533   }
2534
2535   if (!start_preroll (media))
2536     goto preroll_failed;
2537
2538   return FALSE;
2539
2540 join_bin_failed:
2541   {
2542     GST_WARNING ("failed to join bin element");
2543     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2544     return FALSE;
2545   }
2546 preroll_failed:
2547   {
2548     GST_WARNING ("failed to preroll pipeline");
2549     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2550     return FALSE;
2551   }
2552 }
2553
2554 static gboolean
2555 default_prepare (GstRTSPMedia * media, GstRTSPThread * thread)
2556 {
2557   GstRTSPMediaPrivate *priv;
2558   GstRTSPMediaClass *klass;
2559   GstBus *bus;
2560   GMainContext *context;
2561   GSource *source;
2562
2563   priv = media->priv;
2564
2565   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2566
2567   if (!klass->create_rtpbin)
2568     goto no_create_rtpbin;
2569
2570   priv->rtpbin = klass->create_rtpbin (media);
2571   if (priv->rtpbin != NULL) {
2572     gboolean success = TRUE;
2573
2574     g_object_set (priv->rtpbin, "latency", priv->latency, NULL);
2575
2576     if (klass->setup_rtpbin)
2577       success = klass->setup_rtpbin (media, priv->rtpbin);
2578
2579     if (success == FALSE) {
2580       gst_object_unref (priv->rtpbin);
2581       priv->rtpbin = NULL;
2582     }
2583   }
2584   if (priv->rtpbin == NULL)
2585     goto no_rtpbin;
2586
2587   priv->thread = thread;
2588   context = (thread != NULL) ? (thread->context) : NULL;
2589
2590   bus = gst_pipeline_get_bus (GST_PIPELINE_CAST (priv->pipeline));
2591
2592   /* add the pipeline bus to our custom mainloop */
2593   priv->source = gst_bus_create_watch (bus);
2594   gst_object_unref (bus);
2595
2596   g_source_set_callback (priv->source, (GSourceFunc) bus_message,
2597       g_object_ref (media), (GDestroyNotify) watch_destroyed);
2598
2599   priv->id = g_source_attach (priv->source, context);
2600
2601   /* add stuff to the bin */
2602   gst_bin_add (GST_BIN (priv->pipeline), priv->rtpbin);
2603
2604   /* do remainder in context */
2605   source = g_idle_source_new ();
2606   g_source_set_callback (source, (GSourceFunc) start_prepare, media, NULL);
2607   g_source_attach (source, context);
2608   g_source_unref (source);
2609
2610   return TRUE;
2611
2612   /* ERRORS */
2613 no_create_rtpbin:
2614   {
2615     GST_ERROR ("no create_rtpbin function");
2616     g_critical ("no create_rtpbin vmethod function set");
2617     return FALSE;
2618   }
2619 no_rtpbin:
2620   {
2621     GST_WARNING ("no rtpbin element");
2622     g_warning ("failed to create element 'rtpbin', check your installation");
2623     return FALSE;
2624   }
2625 }
2626
2627 /**
2628  * gst_rtsp_media_prepare:
2629  * @media: a #GstRTSPMedia
2630  * @thread: (transfer full) (allow-none): a #GstRTSPThread to run the
2631  *   bus handler or %NULL
2632  *
2633  * Prepare @media for streaming. This function will create the objects
2634  * to manage the streaming. A pipeline must have been set on @media with
2635  * gst_rtsp_media_take_pipeline().
2636  *
2637  * It will preroll the pipeline and collect vital information about the streams
2638  * such as the duration.
2639  *
2640  * Returns: %TRUE on success.
2641  */
2642 gboolean
2643 gst_rtsp_media_prepare (GstRTSPMedia * media, GstRTSPThread * thread)
2644 {
2645   GstRTSPMediaPrivate *priv;
2646   GstRTSPMediaClass *klass;
2647
2648   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2649
2650   priv = media->priv;
2651
2652   g_rec_mutex_lock (&priv->state_lock);
2653   priv->prepare_count++;
2654
2655   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED ||
2656       priv->status == GST_RTSP_MEDIA_STATUS_SUSPENDED)
2657     goto was_prepared;
2658
2659   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2660     goto is_preparing;
2661
2662   if (priv->status != GST_RTSP_MEDIA_STATUS_UNPREPARED)
2663     goto not_unprepared;
2664
2665   if (!priv->reusable && priv->reused)
2666     goto is_reused;
2667
2668   GST_INFO ("preparing media %p", media);
2669
2670   /* reset some variables */
2671   priv->is_live = FALSE;
2672   priv->seekable = FALSE;
2673   priv->buffering = FALSE;
2674
2675   /* we're preparing now */
2676   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
2677
2678   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2679   if (klass->prepare) {
2680     if (!klass->prepare (media, thread))
2681       goto prepare_failed;
2682   }
2683
2684 wait_status:
2685   g_rec_mutex_unlock (&priv->state_lock);
2686
2687   /* now wait for all pads to be prerolled, FIXME, we should somehow be
2688    * able to do this async so that we don't block the server thread. */
2689   if (!wait_preroll (media))
2690     goto preroll_failed;
2691
2692   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_PREPARED], 0, NULL);
2693
2694   GST_INFO ("object %p is prerolled", media);
2695
2696   return TRUE;
2697
2698   /* OK */
2699 is_preparing:
2700   {
2701     /* we are not going to use the giving thread, so stop it. */
2702     if (thread)
2703       gst_rtsp_thread_stop (thread);
2704     goto wait_status;
2705   }
2706 was_prepared:
2707   {
2708     GST_LOG ("media %p was prepared", media);
2709     /* we are not going to use the giving thread, so stop it. */
2710     if (thread)
2711       gst_rtsp_thread_stop (thread);
2712     g_rec_mutex_unlock (&priv->state_lock);
2713     return TRUE;
2714   }
2715   /* ERRORS */
2716 not_unprepared:
2717   {
2718     /* we are not going to use the giving thread, so stop it. */
2719     if (thread)
2720       gst_rtsp_thread_stop (thread);
2721     GST_WARNING ("media %p was not unprepared", media);
2722     priv->prepare_count--;
2723     g_rec_mutex_unlock (&priv->state_lock);
2724     return FALSE;
2725   }
2726 is_reused:
2727   {
2728     /* we are not going to use the giving thread, so stop it. */
2729     if (thread)
2730       gst_rtsp_thread_stop (thread);
2731     priv->prepare_count--;
2732     g_rec_mutex_unlock (&priv->state_lock);
2733     GST_WARNING ("can not reuse media %p", media);
2734     return FALSE;
2735   }
2736 prepare_failed:
2737   {
2738     /* we are not going to use the giving thread, so stop it. */
2739     if (thread)
2740       gst_rtsp_thread_stop (thread);
2741     priv->prepare_count--;
2742     g_rec_mutex_unlock (&priv->state_lock);
2743     GST_ERROR ("failed to prepare media");
2744     return FALSE;
2745   }
2746 preroll_failed:
2747   {
2748     GST_WARNING ("failed to preroll pipeline");
2749     gst_rtsp_media_unprepare (media);
2750     return FALSE;
2751   }
2752 }
2753
2754 /* must be called with state-lock */
2755 static void
2756 finish_unprepare (GstRTSPMedia * media)
2757 {
2758   GstRTSPMediaPrivate *priv = media->priv;
2759   gint i;
2760   GList *walk;
2761
2762   GST_DEBUG ("shutting down");
2763
2764   /* release the lock on shutdown, otherwise pad_added_cb might try to
2765    * acquire the lock and then we deadlock */
2766   g_rec_mutex_unlock (&priv->state_lock);
2767   set_state (media, GST_STATE_NULL);
2768   g_rec_mutex_lock (&priv->state_lock);
2769   remove_fakesink (priv);
2770
2771   for (i = 0; i < priv->streams->len; i++) {
2772     GstRTSPStream *stream;
2773
2774     GST_INFO ("Removing elements of stream %d from pipeline", i);
2775
2776     stream = g_ptr_array_index (priv->streams, i);
2777
2778     gst_rtsp_stream_leave_bin (stream, GST_BIN (priv->pipeline), priv->rtpbin);
2779   }
2780
2781   /* remove the pad signal handlers */
2782   for (walk = priv->dynamic; walk; walk = g_list_next (walk)) {
2783     GstElement *elem = walk->data;
2784     DynPaySignalHandlers *handlers;
2785
2786     handlers =
2787         g_object_steal_data (G_OBJECT (elem), "gst-rtsp-dynpay-handlers");
2788     g_assert (handlers != NULL);
2789
2790     g_signal_handler_disconnect (G_OBJECT (elem), handlers->pad_added_handler);
2791     g_signal_handler_disconnect (G_OBJECT (elem),
2792         handlers->pad_removed_handler);
2793     g_signal_handler_disconnect (G_OBJECT (elem),
2794         handlers->no_more_pads_handler);
2795
2796     g_slice_free (DynPaySignalHandlers, handlers);
2797   }
2798
2799   gst_bin_remove (GST_BIN (priv->pipeline), priv->rtpbin);
2800   priv->rtpbin = NULL;
2801
2802   if (priv->nettime)
2803     gst_object_unref (priv->nettime);
2804   priv->nettime = NULL;
2805
2806   priv->reused = TRUE;
2807   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_UNPREPARED);
2808
2809   /* when the media is not reusable, this will effectively unref the media and
2810    * recreate it */
2811   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_UNPREPARED], 0, NULL);
2812
2813   /* the source has the last ref to the media */
2814   if (priv->source) {
2815     GST_DEBUG ("destroy source");
2816     g_source_destroy (priv->source);
2817     g_source_unref (priv->source);
2818   }
2819   if (priv->thread) {
2820     GST_DEBUG ("stop thread");
2821     gst_rtsp_thread_stop (priv->thread);
2822   }
2823 }
2824
2825 /* called with state-lock */
2826 static gboolean
2827 default_unprepare (GstRTSPMedia * media)
2828 {
2829   GstRTSPMediaPrivate *priv = media->priv;
2830
2831   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_UNPREPARING);
2832
2833   if (priv->eos_shutdown) {
2834     GST_DEBUG ("sending EOS for shutdown");
2835     /* ref so that we don't disappear */
2836     gst_element_send_event (priv->pipeline, gst_event_new_eos ());
2837     /* we need to go to playing again for the EOS to propagate, normally in this
2838      * state, nothing is receiving data from us anymore so this is ok. */
2839     set_state (media, GST_STATE_PLAYING);
2840   } else {
2841     finish_unprepare (media);
2842   }
2843   return TRUE;
2844 }
2845
2846 /**
2847  * gst_rtsp_media_unprepare:
2848  * @media: a #GstRTSPMedia
2849  *
2850  * Unprepare @media. After this call, the media should be prepared again before
2851  * it can be used again. If the media is set to be non-reusable, a new instance
2852  * must be created.
2853  *
2854  * Returns: %TRUE on success.
2855  */
2856 gboolean
2857 gst_rtsp_media_unprepare (GstRTSPMedia * media)
2858 {
2859   GstRTSPMediaPrivate *priv;
2860   gboolean success;
2861
2862   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2863
2864   priv = media->priv;
2865
2866   g_rec_mutex_lock (&priv->state_lock);
2867   if (priv->status == GST_RTSP_MEDIA_STATUS_UNPREPARED)
2868     goto was_unprepared;
2869
2870   priv->prepare_count--;
2871   if (priv->prepare_count > 0)
2872     goto is_busy;
2873
2874   GST_INFO ("unprepare media %p", media);
2875   if (priv->blocked)
2876     media_streams_set_blocked (media, FALSE);
2877   set_target_state (media, GST_STATE_NULL, FALSE);
2878   success = TRUE;
2879
2880   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED) {
2881     GstRTSPMediaClass *klass;
2882
2883     klass = GST_RTSP_MEDIA_GET_CLASS (media);
2884     if (klass->unprepare)
2885       success = klass->unprepare (media);
2886   } else {
2887     finish_unprepare (media);
2888   }
2889   g_rec_mutex_unlock (&priv->state_lock);
2890
2891   return success;
2892
2893 was_unprepared:
2894   {
2895     g_rec_mutex_unlock (&priv->state_lock);
2896     GST_INFO ("media %p was already unprepared", media);
2897     return TRUE;
2898   }
2899 is_busy:
2900   {
2901     GST_INFO ("media %p still prepared %d times", media, priv->prepare_count);
2902     g_rec_mutex_unlock (&priv->state_lock);
2903     return TRUE;
2904   }
2905 }
2906
2907 /* should be called with state-lock */
2908 static GstClock *
2909 get_clock_unlocked (GstRTSPMedia * media)
2910 {
2911   if (media->priv->status != GST_RTSP_MEDIA_STATUS_PREPARED) {
2912     GST_DEBUG_OBJECT (media, "media was not prepared");
2913     return NULL;
2914   }
2915   return gst_pipeline_get_clock (GST_PIPELINE_CAST (media->priv->pipeline));
2916 }
2917
2918 /**
2919  * gst_rtsp_media_get_clock:
2920  * @media: a #GstRTSPMedia
2921  *
2922  * Get the clock that is used by the pipeline in @media.
2923  *
2924  * @media must be prepared before this method returns a valid clock object.
2925  *
2926  * Returns: (transfer full): the #GstClock used by @media. unref after usage.
2927  */
2928 GstClock *
2929 gst_rtsp_media_get_clock (GstRTSPMedia * media)
2930 {
2931   GstClock *clock;
2932   GstRTSPMediaPrivate *priv;
2933
2934   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
2935
2936   priv = media->priv;
2937
2938   g_rec_mutex_lock (&priv->state_lock);
2939   clock = get_clock_unlocked (media);
2940   g_rec_mutex_unlock (&priv->state_lock);
2941
2942   return clock;
2943 }
2944
2945 /**
2946  * gst_rtsp_media_get_base_time:
2947  * @media: a #GstRTSPMedia
2948  *
2949  * Get the base_time that is used by the pipeline in @media.
2950  *
2951  * @media must be prepared before this method returns a valid base_time.
2952  *
2953  * Returns: the base_time used by @media.
2954  */
2955 GstClockTime
2956 gst_rtsp_media_get_base_time (GstRTSPMedia * media)
2957 {
2958   GstClockTime result;
2959   GstRTSPMediaPrivate *priv;
2960
2961   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_CLOCK_TIME_NONE);
2962
2963   priv = media->priv;
2964
2965   g_rec_mutex_lock (&priv->state_lock);
2966   if (media->priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
2967     goto not_prepared;
2968
2969   result = gst_element_get_base_time (media->priv->pipeline);
2970   g_rec_mutex_unlock (&priv->state_lock);
2971
2972   return result;
2973
2974   /* ERRORS */
2975 not_prepared:
2976   {
2977     g_rec_mutex_unlock (&priv->state_lock);
2978     GST_DEBUG_OBJECT (media, "media was not prepared");
2979     return GST_CLOCK_TIME_NONE;
2980   }
2981 }
2982
2983 /**
2984  * gst_rtsp_media_get_time_provider:
2985  * @media: a #GstRTSPMedia
2986  * @address: (allow-none): an address or %NULL
2987  * @port: a port or 0
2988  *
2989  * Get the #GstNetTimeProvider for the clock used by @media. The time provider
2990  * will listen on @address and @port for client time requests.
2991  *
2992  * Returns: (transfer full): the #GstNetTimeProvider of @media.
2993  */
2994 GstNetTimeProvider *
2995 gst_rtsp_media_get_time_provider (GstRTSPMedia * media, const gchar * address,
2996     guint16 port)
2997 {
2998   GstRTSPMediaPrivate *priv;
2999   GstNetTimeProvider *provider = NULL;
3000
3001   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
3002
3003   priv = media->priv;
3004
3005   g_rec_mutex_lock (&priv->state_lock);
3006   if (priv->time_provider) {
3007     if ((provider = priv->nettime) == NULL) {
3008       GstClock *clock;
3009
3010       if (priv->time_provider && (clock = get_clock_unlocked (media))) {
3011         provider = gst_net_time_provider_new (clock, address, port);
3012         gst_object_unref (clock);
3013
3014         priv->nettime = provider;
3015       }
3016     }
3017   }
3018   g_rec_mutex_unlock (&priv->state_lock);
3019
3020   if (provider)
3021     gst_object_ref (provider);
3022
3023   return provider;
3024 }
3025
3026 static gboolean
3027 default_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp, GstSDPInfo * info)
3028 {
3029   return gst_rtsp_sdp_from_media (sdp, info, media);
3030 }
3031
3032 /**
3033  * gst_rtsp_media_setup_sdp:
3034  * @media: a #GstRTSPMedia
3035  * @sdp: (transfer none): a #GstSDPMessage
3036  * @info: (transfer none): a #GstSDPInfo
3037  *
3038  * Add @media specific info to @sdp. @info is used to configure the connection
3039  * information in the SDP.
3040  *
3041  * Returns: TRUE on success.
3042  */
3043 gboolean
3044 gst_rtsp_media_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp,
3045     GstSDPInfo * info)
3046 {
3047   GstRTSPMediaPrivate *priv;
3048   GstRTSPMediaClass *klass;
3049   gboolean res;
3050
3051   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3052   g_return_val_if_fail (sdp != NULL, FALSE);
3053   g_return_val_if_fail (info != NULL, FALSE);
3054
3055   priv = media->priv;
3056
3057   g_rec_mutex_lock (&priv->state_lock);
3058
3059   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3060
3061   if (!klass->setup_sdp)
3062     goto no_setup_sdp;
3063
3064   res = klass->setup_sdp (media, sdp, info);
3065
3066   g_rec_mutex_unlock (&priv->state_lock);
3067
3068   return res;
3069
3070   /* ERRORS */
3071 no_setup_sdp:
3072   {
3073     g_rec_mutex_unlock (&priv->state_lock);
3074     GST_ERROR ("no setup_sdp function");
3075     g_critical ("no setup_sdp vmethod function set");
3076     return FALSE;
3077   }
3078 }
3079
3080 static const gchar *
3081 rtsp_get_attribute_for_pt (const GstSDPMedia * media, const gchar * name,
3082     gint pt)
3083 {
3084   guint i;
3085
3086   for (i = 0;; i++) {
3087     const gchar *attr;
3088     gint val;
3089
3090     if ((attr = gst_sdp_media_get_attribute_val_n (media, name, i)) == NULL)
3091       break;
3092
3093     if (sscanf (attr, "%d ", &val) != 1)
3094       continue;
3095
3096     if (val == pt)
3097       return attr;
3098   }
3099   return NULL;
3100 }
3101
3102 #define PARSE_INT(p, del, res)          \
3103 G_STMT_START {                          \
3104   gchar *t = p;                         \
3105   p = strstr (p, del);                  \
3106   if (p == NULL)                        \
3107     res = -1;                           \
3108   else {                                \
3109     *p = '\0';                          \
3110     p++;                                \
3111     res = atoi (t);                     \
3112   }                                     \
3113 } G_STMT_END
3114
3115 #define PARSE_STRING(p, del, res)       \
3116 G_STMT_START {                          \
3117   gchar *t = p;                         \
3118   p = strstr (p, del);                  \
3119   if (p == NULL) {                      \
3120     res = NULL;                         \
3121     p = t;                              \
3122   }                                     \
3123   else {                                \
3124     *p = '\0';                          \
3125     p++;                                \
3126     res = t;                            \
3127   }                                     \
3128 } G_STMT_END
3129
3130 #define SKIP_SPACES(p)                  \
3131   while (*p && g_ascii_isspace (*p))    \
3132     p++;
3133
3134 /* rtpmap contains:
3135  *
3136  *  <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
3137  */
3138 static gboolean
3139 parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
3140     gint * rate, gchar ** params)
3141 {
3142   gchar *p, *t;
3143
3144   p = (gchar *) rtpmap;
3145
3146   PARSE_INT (p, " ", *payload);
3147   if (*payload == -1)
3148     return FALSE;
3149
3150   SKIP_SPACES (p);
3151   if (*p == '\0')
3152     return FALSE;
3153
3154   PARSE_STRING (p, "/", *name);
3155   if (*name == NULL) {
3156     GST_DEBUG ("no rate, name %s", p);
3157     /* no rate, assume -1 then, this is not supposed to happen but RealMedia
3158      * streams seem to omit the rate. */
3159     *name = p;
3160     *rate = -1;
3161     return TRUE;
3162   }
3163
3164   t = p;
3165   p = strstr (p, "/");
3166   if (p == NULL) {
3167     *rate = atoi (t);
3168     return TRUE;
3169   }
3170   *p = '\0';
3171   p++;
3172   *rate = atoi (t);
3173
3174   t = p;
3175   if (*p == '\0')
3176     return TRUE;
3177   *params = t;
3178
3179   return TRUE;
3180 }
3181
3182 /*
3183  *  Mapping of caps to and from SDP fields:
3184  *
3185  *   a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
3186  *   a=framesize:<payload> <width>-<height>
3187  *   a=fmtp:<payload> <param>[=<value>];...
3188  */
3189 static GstCaps *
3190 media_to_caps (gint pt, const GstSDPMedia * media)
3191 {
3192   GstCaps *caps;
3193   const gchar *rtpmap;
3194   const gchar *fmtp;
3195   const gchar *framesize;
3196   gchar *name = NULL;
3197   gint rate = -1;
3198   gchar *params = NULL;
3199   gchar *tmp;
3200   GstStructure *s;
3201   gint payload = 0;
3202   gboolean ret;
3203
3204   /* get and parse rtpmap */
3205   rtpmap = rtsp_get_attribute_for_pt (media, "rtpmap", pt);
3206
3207   if (rtpmap) {
3208     ret = parse_rtpmap (rtpmap, &payload, &name, &rate, &params);
3209     if (!ret) {
3210       g_warning ("error parsing rtpmap, ignoring");
3211       rtpmap = NULL;
3212     }
3213   }
3214   /* dynamic payloads need rtpmap or we fail */
3215   if (rtpmap == NULL && pt >= 96)
3216     goto no_rtpmap;
3217
3218   /* check if we have a rate, if not, we need to look up the rate from the
3219    * default rates based on the payload types. */
3220   if (rate == -1) {
3221     const GstRTPPayloadInfo *info;
3222
3223     if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
3224       /* dynamic types, use media and encoding_name */
3225       tmp = g_ascii_strdown (media->media, -1);
3226       info = gst_rtp_payload_info_for_name (tmp, name);
3227       g_free (tmp);
3228     } else {
3229       /* static types, use payload type */
3230       info = gst_rtp_payload_info_for_pt (pt);
3231     }
3232
3233     if (info) {
3234       if ((rate = info->clock_rate) == 0)
3235         rate = -1;
3236     }
3237     /* we fail if we cannot find one */
3238     if (rate == -1)
3239       goto no_rate;
3240   }
3241
3242   tmp = g_ascii_strdown (media->media, -1);
3243   caps = gst_caps_new_simple ("application/x-unknown",
3244       "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
3245   g_free (tmp);
3246   s = gst_caps_get_structure (caps, 0);
3247
3248   gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
3249
3250   /* encoding name must be upper case */
3251   if (name != NULL) {
3252     tmp = g_ascii_strup (name, -1);
3253     gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
3254     g_free (tmp);
3255   }
3256
3257   /* params must be lower case */
3258   if (params != NULL) {
3259     tmp = g_ascii_strdown (params, -1);
3260     gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
3261     g_free (tmp);
3262   }
3263
3264   /* parse optional fmtp: field */
3265   if ((fmtp = rtsp_get_attribute_for_pt (media, "fmtp", pt))) {
3266     gchar *p;
3267     gint payload = 0;
3268
3269     p = (gchar *) fmtp;
3270
3271     /* p is now of the format <payload> <param>[=<value>];... */
3272     PARSE_INT (p, " ", payload);
3273     if (payload != -1 && payload == pt) {
3274       gchar **pairs;
3275       gint i;
3276
3277       /* <param>[=<value>] are separated with ';' */
3278       pairs = g_strsplit (p, ";", 0);
3279       for (i = 0; pairs[i]; i++) {
3280         gchar *valpos;
3281         const gchar *val, *key;
3282         gint j;
3283         const gchar *reserved_keys[] =
3284             { "media", "payload", "clock-rate", "encoding-name",
3285           "encoding-params"
3286         };
3287
3288         /* the key may not have a '=', the value can have other '='s */
3289         valpos = strstr (pairs[i], "=");
3290         if (valpos) {
3291           /* we have a '=' and thus a value, remove the '=' with \0 */
3292           *valpos = '\0';
3293           /* value is everything between '=' and ';'. We split the pairs at ;
3294            * boundaries so we can take the remainder of the value. Some servers
3295            * put spaces around the value which we strip off here. Alternatively
3296            * we could strip those spaces in the depayloaders should these spaces
3297            * actually carry any meaning in the future. */
3298           val = g_strstrip (valpos + 1);
3299         } else {
3300           /* simple <param>;.. is translated into <param>=1;... */
3301           val = "1";
3302         }
3303         /* strip the key of spaces, convert key to lowercase but not the value. */
3304         key = g_strstrip (pairs[i]);
3305
3306         /* skip keys from the fmtp, which we already use ourselves for the
3307          * caps. Some software is adding random things like clock-rate into
3308          * the fmtp, and we would otherwise here set a string-typed clock-rate
3309          * in the caps... and thus fail to create valid RTP caps
3310          */
3311         for (j = 0; j < G_N_ELEMENTS (reserved_keys); j++) {
3312           if (g_ascii_strcasecmp (reserved_keys[j], key) == 0) {
3313             key = "";
3314             break;
3315           }
3316         }
3317
3318         if (strlen (key) > 1) {
3319           tmp = g_ascii_strdown (key, -1);
3320           gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
3321           g_free (tmp);
3322         }
3323       }
3324       g_strfreev (pairs);
3325     }
3326   }
3327
3328   /* parse framesize: field */
3329   if ((framesize = gst_sdp_media_get_attribute_val (media, "framesize"))) {
3330     gchar *p;
3331
3332     /* p is now of the format <payload> <width>-<height> */
3333     p = (gchar *) framesize;
3334
3335     PARSE_INT (p, " ", payload);
3336     if (payload != -1 && payload == pt) {
3337       gst_structure_set (s, "a-framesize", G_TYPE_STRING, p, NULL);
3338     }
3339   }
3340   return caps;
3341
3342   /* ERRORS */
3343 no_rtpmap:
3344   {
3345     g_warning ("rtpmap type not given for dynamic payload %d", pt);
3346     return NULL;
3347   }
3348 no_rate:
3349   {
3350     g_warning ("rate unknown for payload type %d", pt);
3351     return NULL;
3352   }
3353 }
3354
3355 static gboolean
3356 parse_keymgmt (const gchar * keymgmt, GstCaps * caps)
3357 {
3358   gboolean res = FALSE;
3359   gchar *p, *kmpid;
3360   gsize size;
3361   guchar *data;
3362   GstMIKEYMessage *msg;
3363   const GstMIKEYPayload *payload;
3364   const gchar *srtp_cipher;
3365   const gchar *srtp_auth;
3366
3367   p = (gchar *) keymgmt;
3368
3369   SKIP_SPACES (p);
3370   if (*p == '\0')
3371     return FALSE;
3372
3373   PARSE_STRING (p, " ", kmpid);
3374   if (!g_str_equal (kmpid, "mikey"))
3375     return FALSE;
3376
3377   data = g_base64_decode (p, &size);
3378   if (data == NULL)
3379     return FALSE;
3380
3381   msg = gst_mikey_message_new_from_data (data, size, NULL, NULL);
3382   g_free (data);
3383   if (msg == NULL)
3384     return FALSE;
3385
3386   srtp_cipher = "aes-128-icm";
3387   srtp_auth = "hmac-sha1-80";
3388
3389   /* check the Security policy if any */
3390   if ((payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, 0))) {
3391     GstMIKEYPayloadSP *p = (GstMIKEYPayloadSP *) payload;
3392     guint len, i;
3393
3394     if (p->proto != GST_MIKEY_SEC_PROTO_SRTP)
3395       goto done;
3396
3397     len = gst_mikey_payload_sp_get_n_params (payload);
3398     for (i = 0; i < len; i++) {
3399       const GstMIKEYPayloadSPParam *param =
3400           gst_mikey_payload_sp_get_param (payload, i);
3401
3402       switch (param->type) {
3403         case GST_MIKEY_SP_SRTP_ENC_ALG:
3404           switch (param->val[0]) {
3405             case 0:
3406               srtp_cipher = "null";
3407               break;
3408             case 2:
3409             case 1:
3410               srtp_cipher = "aes-128-icm";
3411               break;
3412             default:
3413               break;
3414           }
3415           break;
3416         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
3417           switch (param->val[0]) {
3418             case AES_128_KEY_LEN:
3419               srtp_cipher = "aes-128-icm";
3420               break;
3421             case AES_256_KEY_LEN:
3422               srtp_cipher = "aes-256-icm";
3423               break;
3424             default:
3425               break;
3426           }
3427           break;
3428         case GST_MIKEY_SP_SRTP_AUTH_ALG:
3429           switch (param->val[0]) {
3430             case 0:
3431               srtp_auth = "null";
3432               break;
3433             case 2:
3434             case 1:
3435               srtp_auth = "hmac-sha1-80";
3436               break;
3437             default:
3438               break;
3439           }
3440           break;
3441         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
3442           switch (param->val[0]) {
3443             case HMAC_32_KEY_LEN:
3444               srtp_auth = "hmac-sha1-32";
3445               break;
3446             case HMAC_80_KEY_LEN:
3447               srtp_auth = "hmac-sha1-80";
3448               break;
3449             default:
3450               break;
3451           }
3452           break;
3453         case GST_MIKEY_SP_SRTP_SRTP_ENC:
3454           break;
3455         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
3456           break;
3457         default:
3458           break;
3459       }
3460     }
3461   }
3462
3463   if (!(payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_KEMAC, 0)))
3464     goto done;
3465   else {
3466     GstMIKEYPayloadKEMAC *p = (GstMIKEYPayloadKEMAC *) payload;
3467     const GstMIKEYPayload *sub;
3468     GstMIKEYPayloadKeyData *pkd;
3469     GstBuffer *buf;
3470
3471     if (p->enc_alg != GST_MIKEY_ENC_NULL || p->mac_alg != GST_MIKEY_MAC_NULL)
3472       goto done;
3473
3474     if (!(sub = gst_mikey_payload_kemac_get_sub (payload, 0)))
3475       goto done;
3476
3477     if (sub->type != GST_MIKEY_PT_KEY_DATA)
3478       goto done;
3479
3480     pkd = (GstMIKEYPayloadKeyData *) sub;
3481     buf =
3482         gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
3483         pkd->key_len);
3484     gst_caps_set_simple (caps, "srtp-key", GST_TYPE_BUFFER, buf, NULL);
3485   }
3486
3487   gst_caps_set_simple (caps,
3488       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
3489       "srtp-auth", G_TYPE_STRING, srtp_auth,
3490       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
3491       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
3492
3493   res = TRUE;
3494 done:
3495   gst_mikey_message_unref (msg);
3496
3497   return res;
3498 }
3499
3500 /*
3501  * Mapping SDP attributes to caps
3502  *
3503  * prepend 'a-' to IANA registered sdp attributes names
3504  * (ie: not prefixed with 'x-') in order to avoid
3505  * collision with gstreamer standard caps properties names
3506  */
3507 static void
3508 sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
3509 {
3510   if (attributes->len > 0) {
3511     GstStructure *s;
3512     guint i;
3513
3514     s = gst_caps_get_structure (caps, 0);
3515
3516     for (i = 0; i < attributes->len; i++) {
3517       GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
3518       gchar *tofree, *key;
3519
3520       key = attr->key;
3521
3522       /* skip some of the attribute we already handle */
3523       if (!strcmp (key, "fmtp"))
3524         continue;
3525       if (!strcmp (key, "rtpmap"))
3526         continue;
3527       if (!strcmp (key, "control"))
3528         continue;
3529       if (!strcmp (key, "range"))
3530         continue;
3531       if (!strcmp (key, "framesize"))
3532         continue;
3533       if (g_str_equal (key, "key-mgmt")) {
3534         parse_keymgmt (attr->value, caps);
3535         continue;
3536       }
3537
3538       /* string must be valid UTF8 */
3539       if (!g_utf8_validate (attr->value, -1, NULL))
3540         continue;
3541
3542       if (!g_str_has_prefix (key, "x-"))
3543         tofree = key = g_strdup_printf ("a-%s", key);
3544       else
3545         tofree = NULL;
3546
3547       GST_DEBUG ("adding caps: %s=%s", key, attr->value);
3548       gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
3549       g_free (tofree);
3550     }
3551   }
3552 }
3553
3554 static gboolean
3555 default_handle_sdp (GstRTSPMedia * media, GstSDPMessage * sdp)
3556 {
3557   GstRTSPMediaPrivate *priv = media->priv;
3558   gint i, medias_len;
3559
3560   medias_len = gst_sdp_message_medias_len (sdp);
3561   if (medias_len != priv->streams->len) {
3562     GST_ERROR ("%p: Media has more or less streams than SDP (%d /= %d)", media,
3563         priv->streams->len, medias_len);
3564     return FALSE;
3565   }
3566
3567   for (i = 0; i < medias_len; i++) {
3568     const gchar *proto, *media_type;
3569     const GstSDPMedia *sdp_media = gst_sdp_message_get_media (sdp, i);
3570     GstRTSPStream *stream;
3571     gint j, formats_len;
3572     const gchar *control;
3573     GstRTSPProfile profile, profiles;
3574
3575     stream = g_ptr_array_index (priv->streams, i);
3576
3577     /* TODO: Should we do something with the other SDP information? */
3578
3579     /* get proto */
3580     proto = gst_sdp_media_get_proto (sdp_media);
3581     if (proto == NULL) {
3582       GST_ERROR ("%p: SDP media %d has no proto", media, i);
3583       return FALSE;
3584     }
3585
3586     if (g_str_equal (proto, "RTP/AVP")) {
3587       media_type = "application/x-rtp";
3588       profile = GST_RTSP_PROFILE_AVP;
3589     } else if (g_str_equal (proto, "RTP/SAVP")) {
3590       media_type = "application/x-srtp";
3591       profile = GST_RTSP_PROFILE_SAVP;
3592     } else if (g_str_equal (proto, "RTP/AVPF")) {
3593       media_type = "application/x-rtp";
3594       profile = GST_RTSP_PROFILE_AVPF;
3595     } else if (g_str_equal (proto, "RTP/SAVPF")) {
3596       media_type = "application/x-srtp";
3597       profile = GST_RTSP_PROFILE_SAVPF;
3598     } else {
3599       GST_ERROR ("%p: unsupported profile '%s' for stream %d", media, proto, i);
3600       return FALSE;
3601     }
3602
3603     profiles = gst_rtsp_stream_get_profiles (stream);
3604     if ((profiles & profile) == 0) {
3605       GST_ERROR ("%p: unsupported profile '%s' for stream %d", media, proto, i);
3606       return FALSE;
3607     }
3608
3609     formats_len = gst_sdp_media_formats_len (sdp_media);
3610     for (j = 0; j < formats_len; j++) {
3611       gint pt;
3612       GstCaps *caps;
3613       GstStructure *s;
3614
3615       pt = atoi (gst_sdp_media_get_format (sdp_media, j));
3616
3617       GST_DEBUG (" looking at %d pt: %d", j, pt);
3618
3619       /* convert caps */
3620       caps = media_to_caps (pt, sdp_media);
3621       if (caps == NULL) {
3622         GST_WARNING (" skipping pt %d without caps", pt);
3623         continue;
3624       }
3625
3626       /* do some tweaks */
3627       GST_DEBUG ("mapping sdp session level attributes to caps");
3628       sdp_attributes_to_caps (sdp->attributes, caps);
3629       GST_DEBUG ("mapping sdp media level attributes to caps");
3630       sdp_attributes_to_caps (sdp_media->attributes, caps);
3631
3632       s = gst_caps_get_structure (caps, 0);
3633       gst_structure_set_name (s, media_type);
3634
3635       gst_rtsp_stream_set_pt_map (stream, pt, caps);
3636       gst_caps_unref (caps);
3637     }
3638
3639     control = gst_sdp_media_get_attribute_val (sdp_media, "control");
3640     if (control)
3641       gst_rtsp_stream_set_control (stream, control);
3642
3643   }
3644
3645   return TRUE;
3646 }
3647
3648 /**
3649  * gst_rtsp_media_handle_sdp:
3650  * @media: a #GstRTSPMedia
3651  * @sdp: (transfer none): a #GstSDPMessage
3652  *
3653  * Configure an SDP on @media for receiving streams
3654  *
3655  * Returns: TRUE on success.
3656  */
3657 gboolean
3658 gst_rtsp_media_handle_sdp (GstRTSPMedia * media, GstSDPMessage * sdp)
3659 {
3660   GstRTSPMediaPrivate *priv;
3661   GstRTSPMediaClass *klass;
3662   gboolean res;
3663
3664   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3665   g_return_val_if_fail (sdp != NULL, FALSE);
3666
3667   priv = media->priv;
3668
3669   g_rec_mutex_lock (&priv->state_lock);
3670
3671   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3672
3673   if (!klass->handle_sdp)
3674     goto no_handle_sdp;
3675
3676   res = klass->handle_sdp (media, sdp);
3677
3678   g_rec_mutex_unlock (&priv->state_lock);
3679
3680   return res;
3681
3682   /* ERRORS */
3683 no_handle_sdp:
3684   {
3685     g_rec_mutex_unlock (&priv->state_lock);
3686     GST_ERROR ("no handle_sdp function");
3687     g_critical ("no handle_sdp vmethod function set");
3688     return FALSE;
3689   }
3690 }
3691
3692 static void
3693 do_set_seqnum (GstRTSPStream * stream)
3694 {
3695   guint16 seq_num;
3696   seq_num = gst_rtsp_stream_get_current_seqnum (stream);
3697   gst_rtsp_stream_set_seqnum_offset (stream, seq_num + 1);
3698 }
3699
3700 /* call with state_lock */
3701 static gboolean
3702 default_suspend (GstRTSPMedia * media)
3703 {
3704   GstRTSPMediaPrivate *priv = media->priv;
3705   GstStateChangeReturn ret;
3706   gboolean unblock = FALSE;
3707
3708   switch (priv->suspend_mode) {
3709     case GST_RTSP_SUSPEND_MODE_NONE:
3710       GST_DEBUG ("media %p no suspend", media);
3711       break;
3712     case GST_RTSP_SUSPEND_MODE_PAUSE:
3713       GST_DEBUG ("media %p suspend to PAUSED", media);
3714       ret = set_target_state (media, GST_STATE_PAUSED, TRUE);
3715       if (ret == GST_STATE_CHANGE_FAILURE)
3716         goto state_failed;
3717       unblock = TRUE;
3718       break;
3719     case GST_RTSP_SUSPEND_MODE_RESET:
3720       GST_DEBUG ("media %p suspend to NULL", media);
3721       ret = set_target_state (media, GST_STATE_NULL, TRUE);
3722       if (ret == GST_STATE_CHANGE_FAILURE)
3723         goto state_failed;
3724       /* Because payloader needs to set the sequence number as
3725        * monotonic, we need to preserve the sequence number
3726        * after pause. (otherwise going from pause to play,  which
3727        * is actually from NULL to PLAY will create a new sequence
3728        * number. */
3729       g_ptr_array_foreach (priv->streams, (GFunc) do_set_seqnum, NULL);
3730       unblock = TRUE;
3731       break;
3732     default:
3733       break;
3734   }
3735
3736   /* let the streams do the state changes freely, if any */
3737   if (unblock)
3738     media_streams_set_blocked (media, FALSE);
3739
3740   return TRUE;
3741
3742   /* ERRORS */
3743 state_failed:
3744   {
3745     GST_WARNING ("failed changing pipeline's state for media %p", media);
3746     return FALSE;
3747   }
3748 }
3749
3750 /**
3751  * gst_rtsp_media_suspend:
3752  * @media: a #GstRTSPMedia
3753  *
3754  * Suspend @media. The state of the pipeline managed by @media is set to
3755  * GST_STATE_NULL but all streams are kept. @media can be prepared again
3756  * with gst_rtsp_media_unsuspend()
3757  *
3758  * @media must be prepared with gst_rtsp_media_prepare();
3759  *
3760  * Returns: %TRUE on success.
3761  */
3762 gboolean
3763 gst_rtsp_media_suspend (GstRTSPMedia * media)
3764 {
3765   GstRTSPMediaPrivate *priv = media->priv;
3766   GstRTSPMediaClass *klass;
3767
3768   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3769
3770   GST_FIXME ("suspend for dynamic pipelines needs fixing");
3771
3772   g_rec_mutex_lock (&priv->state_lock);
3773   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
3774     goto not_prepared;
3775
3776   /* don't attempt to suspend when something is busy */
3777   if (priv->n_active > 0)
3778     goto done;
3779
3780   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3781   if (klass->suspend) {
3782     if (!klass->suspend (media))
3783       goto suspend_failed;
3784   }
3785
3786   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_SUSPENDED);
3787 done:
3788   g_rec_mutex_unlock (&priv->state_lock);
3789
3790   return TRUE;
3791
3792   /* ERRORS */
3793 not_prepared:
3794   {
3795     g_rec_mutex_unlock (&priv->state_lock);
3796     GST_WARNING ("media %p was not prepared", media);
3797     return FALSE;
3798   }
3799 suspend_failed:
3800   {
3801     g_rec_mutex_unlock (&priv->state_lock);
3802     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
3803     GST_WARNING ("failed to suspend media %p", media);
3804     return FALSE;
3805   }
3806 }
3807
3808 /* call with state_lock */
3809 static gboolean
3810 default_unsuspend (GstRTSPMedia * media)
3811 {
3812   GstRTSPMediaPrivate *priv = media->priv;
3813
3814   switch (priv->suspend_mode) {
3815     case GST_RTSP_SUSPEND_MODE_NONE:
3816       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
3817       break;
3818     case GST_RTSP_SUSPEND_MODE_PAUSE:
3819       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
3820       break;
3821     case GST_RTSP_SUSPEND_MODE_RESET:
3822     {
3823       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
3824       if (!start_preroll (media))
3825         goto start_failed;
3826       g_rec_mutex_unlock (&priv->state_lock);
3827
3828       if (!wait_preroll (media))
3829         goto preroll_failed;
3830
3831       g_rec_mutex_lock (&priv->state_lock);
3832     }
3833     default:
3834       break;
3835   }
3836
3837   return TRUE;
3838
3839   /* ERRORS */
3840 start_failed:
3841   {
3842     GST_WARNING ("failed to preroll pipeline");
3843     return FALSE;
3844   }
3845 preroll_failed:
3846   {
3847     GST_WARNING ("failed to preroll pipeline");
3848     return FALSE;
3849   }
3850 }
3851
3852 /**
3853  * gst_rtsp_media_unsuspend:
3854  * @media: a #GstRTSPMedia
3855  *
3856  * Unsuspend @media if it was in a suspended state. This method does nothing
3857  * when the media was not in the suspended state.
3858  *
3859  * Returns: %TRUE on success.
3860  */
3861 gboolean
3862 gst_rtsp_media_unsuspend (GstRTSPMedia * media)
3863 {
3864   GstRTSPMediaPrivate *priv = media->priv;
3865   GstRTSPMediaClass *klass;
3866
3867   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3868
3869   g_rec_mutex_lock (&priv->state_lock);
3870   if (priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
3871     goto done;
3872
3873   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3874   if (klass->unsuspend) {
3875     if (!klass->unsuspend (media))
3876       goto unsuspend_failed;
3877   }
3878
3879 done:
3880   g_rec_mutex_unlock (&priv->state_lock);
3881
3882   return TRUE;
3883
3884   /* ERRORS */
3885 unsuspend_failed:
3886   {
3887     g_rec_mutex_unlock (&priv->state_lock);
3888     GST_WARNING ("failed to unsuspend media %p", media);
3889     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
3890     return FALSE;
3891   }
3892 }
3893
3894 /* must be called with state-lock */
3895 static void
3896 media_set_pipeline_state_locked (GstRTSPMedia * media, GstState state)
3897 {
3898   GstRTSPMediaPrivate *priv = media->priv;
3899
3900   if (state == GST_STATE_NULL) {
3901     gst_rtsp_media_unprepare (media);
3902   } else {
3903     GST_INFO ("state %s media %p", gst_element_state_get_name (state), media);
3904     set_target_state (media, state, FALSE);
3905     /* when we are buffering, don't update the state yet, this will be done
3906      * when buffering finishes */
3907     if (priv->buffering) {
3908       GST_INFO ("Buffering busy, delay state change");
3909     } else {
3910       if (state == GST_STATE_PLAYING)
3911         /* make sure pads are not blocking anymore when going to PLAYING */
3912         media_streams_set_blocked (media, FALSE);
3913
3914       set_state (media, state);
3915
3916       /* and suspend after pause */
3917       if (state == GST_STATE_PAUSED)
3918         gst_rtsp_media_suspend (media);
3919     }
3920   }
3921 }
3922
3923 /**
3924  * gst_rtsp_media_set_pipeline_state:
3925  * @media: a #GstRTSPMedia
3926  * @state: the target state of the pipeline
3927  *
3928  * Set the state of the pipeline managed by @media to @state
3929  */
3930 void
3931 gst_rtsp_media_set_pipeline_state (GstRTSPMedia * media, GstState state)
3932 {
3933   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
3934
3935   g_rec_mutex_lock (&media->priv->state_lock);
3936   media_set_pipeline_state_locked (media, state);
3937   g_rec_mutex_unlock (&media->priv->state_lock);
3938 }
3939
3940 /**
3941  * gst_rtsp_media_set_state:
3942  * @media: a #GstRTSPMedia
3943  * @state: the target state of the media
3944  * @transports: (transfer none) (element-type GstRtspServer.RTSPStreamTransport):
3945  * a #GPtrArray of #GstRTSPStreamTransport pointers
3946  *
3947  * Set the state of @media to @state and for the transports in @transports.
3948  *
3949  * @media must be prepared with gst_rtsp_media_prepare();
3950  *
3951  * Returns: %TRUE on success.
3952  */
3953 gboolean
3954 gst_rtsp_media_set_state (GstRTSPMedia * media, GstState state,
3955     GPtrArray * transports)
3956 {
3957   GstRTSPMediaPrivate *priv;
3958   gint i;
3959   gboolean activate, deactivate, do_state;
3960   gint old_active;
3961
3962   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3963   g_return_val_if_fail (transports != NULL, FALSE);
3964
3965   priv = media->priv;
3966
3967   g_rec_mutex_lock (&priv->state_lock);
3968   if (priv->status == GST_RTSP_MEDIA_STATUS_ERROR)
3969     goto error_status;
3970   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
3971       priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
3972     goto not_prepared;
3973
3974   /* NULL and READY are the same */
3975   if (state == GST_STATE_READY)
3976     state = GST_STATE_NULL;
3977
3978   activate = deactivate = FALSE;
3979
3980   GST_INFO ("going to state %s media %p, target state %s",
3981       gst_element_state_get_name (state), media,
3982       gst_element_state_get_name (priv->target_state));
3983
3984   switch (state) {
3985     case GST_STATE_NULL:
3986       /* we're going from PLAYING or PAUSED to READY or NULL, deactivate */
3987       if (priv->target_state >= GST_STATE_PAUSED)
3988         deactivate = TRUE;
3989       break;
3990     case GST_STATE_PAUSED:
3991       /* we're going from PLAYING to PAUSED, READY or NULL, deactivate */
3992       if (priv->target_state == GST_STATE_PLAYING)
3993         deactivate = TRUE;
3994       break;
3995     case GST_STATE_PLAYING:
3996       /* we're going to PLAYING, activate */
3997       activate = TRUE;
3998       break;
3999     default:
4000       break;
4001   }
4002   old_active = priv->n_active;
4003
4004   GST_DEBUG ("%d transports, activate %d, deactivate %d", transports->len,
4005       activate, deactivate);
4006   for (i = 0; i < transports->len; i++) {
4007     GstRTSPStreamTransport *trans;
4008
4009     /* we need a non-NULL entry in the array */
4010     trans = g_ptr_array_index (transports, i);
4011     if (trans == NULL)
4012       continue;
4013
4014     if (activate) {
4015       if (gst_rtsp_stream_transport_set_active (trans, TRUE))
4016         priv->n_active++;
4017     } else if (deactivate) {
4018       if (gst_rtsp_stream_transport_set_active (trans, FALSE))
4019         priv->n_active--;
4020     }
4021   }
4022
4023   /* we just activated the first media, do the playing state change */
4024   if (old_active == 0 && activate)
4025     do_state = TRUE;
4026   /* if we have no more active media, do the downward state changes */
4027   else if (priv->n_active == 0)
4028     do_state = TRUE;
4029   else
4030     do_state = FALSE;
4031
4032   GST_INFO ("state %d active %d media %p do_state %d", state, priv->n_active,
4033       media, do_state);
4034
4035   if (priv->target_state != state) {
4036     if (do_state)
4037       media_set_pipeline_state_locked (media, state);
4038
4039     g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STATE], 0, state,
4040         NULL);
4041   }
4042
4043   /* remember where we are */
4044   if (state != GST_STATE_NULL && (state == GST_STATE_PAUSED ||
4045           old_active != priv->n_active))
4046     collect_media_stats (media);
4047
4048   g_rec_mutex_unlock (&priv->state_lock);
4049
4050   return TRUE;
4051
4052   /* ERRORS */
4053 not_prepared:
4054   {
4055     GST_WARNING ("media %p was not prepared", media);
4056     g_rec_mutex_unlock (&priv->state_lock);
4057     return FALSE;
4058   }
4059 error_status:
4060   {
4061     GST_WARNING ("media %p in error status while changing to state %d",
4062         media, state);
4063     if (state == GST_STATE_NULL) {
4064       for (i = 0; i < transports->len; i++) {
4065         GstRTSPStreamTransport *trans;
4066
4067         /* we need a non-NULL entry in the array */
4068         trans = g_ptr_array_index (transports, i);
4069         if (trans == NULL)
4070           continue;
4071
4072         gst_rtsp_stream_transport_set_active (trans, FALSE);
4073       }
4074       priv->n_active = 0;
4075     }
4076     g_rec_mutex_unlock (&priv->state_lock);
4077     return FALSE;
4078   }
4079 }
4080
4081 /**
4082  * gst_rtsp_media_set_transport_mode:
4083  * @media: a #GstRTSPMedia
4084  * @mode: the new value
4085  *
4086  * Sets if the media pipeline can work in PLAY or RECORD mode
4087  */
4088 void
4089 gst_rtsp_media_set_transport_mode (GstRTSPMedia * media,
4090     GstRTSPTransportMode mode)
4091 {
4092   GstRTSPMediaPrivate *priv;
4093
4094   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
4095
4096   priv = media->priv;
4097
4098   g_mutex_lock (&priv->lock);
4099   priv->transport_mode = mode;
4100   g_mutex_unlock (&priv->lock);
4101 }
4102
4103 /**
4104  * gst_rtsp_media_get_transport_mode:
4105  * @media: a #GstRTSPMedia
4106  *
4107  * Check if the pipeline for @media can be used for PLAY or RECORD methods.
4108  *
4109  * Returns: The transport mode.
4110  */
4111 GstRTSPTransportMode
4112 gst_rtsp_media_get_transport_mode (GstRTSPMedia * media)
4113 {
4114   GstRTSPMediaPrivate *priv;
4115   GstRTSPTransportMode res;
4116
4117   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
4118
4119   priv = media->priv;
4120
4121   g_mutex_lock (&priv->lock);
4122   res = priv->transport_mode;
4123   g_mutex_unlock (&priv->lock);
4124
4125   return res;
4126 }