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