rtsp-media: fix logic for collect_streams
[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_unlock (&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
1859   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1860
1861   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1862   g_return_val_if_fail (range != NULL, FALSE);
1863   g_return_val_if_fail (klass->convert_range != NULL, FALSE);
1864
1865   priv = media->priv;
1866
1867   g_rec_mutex_lock (&priv->state_lock);
1868   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
1869     goto not_prepared;
1870
1871   /* Update the seekable state of the pipeline in case it changed */
1872   if ((priv->transport_mode & GST_RTSP_TRANSPORT_MODE_RECORD)) {
1873     /* TODO: Seeking for RECORD? */
1874     priv->seekable = FALSE;
1875   } else {
1876     query = gst_query_new_seeking (GST_FORMAT_TIME);
1877     if (gst_element_query (priv->pipeline, query)) {
1878       GstFormat format;
1879       gboolean seekable;
1880       gint64 start, end;
1881
1882       gst_query_parse_seeking (query, &format, &seekable, &start, &end);
1883       priv->seekable = seekable;
1884     }
1885     gst_query_unref (query);
1886   }
1887
1888   if (!priv->seekable)
1889     goto not_seekable;
1890
1891   start_type = stop_type = GST_SEEK_TYPE_NONE;
1892
1893   if (!klass->convert_range (media, range, GST_RTSP_RANGE_NPT))
1894     goto not_supported;
1895   gst_rtsp_range_get_times (range, &start, &stop);
1896
1897   GST_INFO ("got %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1898       GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1899   GST_INFO ("current %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1900       GST_TIME_ARGS (priv->range_start), GST_TIME_ARGS (priv->range_stop));
1901
1902   if (start != GST_CLOCK_TIME_NONE)
1903     start_type = GST_SEEK_TYPE_SET;
1904
1905   if (priv->range_stop == stop)
1906     stop = GST_CLOCK_TIME_NONE;
1907   else if (stop != GST_CLOCK_TIME_NONE)
1908     stop_type = GST_SEEK_TYPE_SET;
1909
1910   if (start != GST_CLOCK_TIME_NONE || stop != GST_CLOCK_TIME_NONE) {
1911     GstSeekFlags flags;
1912
1913     GST_INFO ("seeking to %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1914         GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
1915
1916     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
1917     if (priv->blocked)
1918       media_streams_set_blocked (media, TRUE);
1919
1920     /* depends on the current playing state of the pipeline. We might need to
1921      * queue this until we get EOS. */
1922     flags = GST_SEEK_FLAG_FLUSH;
1923
1924     /* if range start was not supplied we must continue from current position.
1925      * but since we're doing a flushing seek, let us query the current position
1926      * so we end up at exactly the same position after the seek. */
1927     if (range->min.type == GST_RTSP_TIME_END) { /* Yepp, that's right! */
1928       gint64 position;
1929       gboolean ret = FALSE;
1930
1931       if (klass->query_position)
1932         ret = klass->query_position (media, &position);
1933
1934       if (!ret) {
1935         GST_WARNING ("position query failed");
1936       } else {
1937         GST_DEBUG ("doing accurate seek to %" GST_TIME_FORMAT,
1938             GST_TIME_ARGS (position));
1939         start = position;
1940         start_type = GST_SEEK_TYPE_SET;
1941         flags |= GST_SEEK_FLAG_ACCURATE;
1942       }
1943     } else {
1944       /* only set keyframe flag when modifying start */
1945       if (start_type != GST_SEEK_TYPE_NONE)
1946         flags |= GST_SEEK_FLAG_KEY_UNIT;
1947     }
1948
1949     /* FIXME, we only do forwards playback, no trick modes yet */
1950     res = gst_element_seek (priv->pipeline, 1.0, GST_FORMAT_TIME,
1951         flags, start_type, start, stop_type, stop);
1952
1953     /* and block for the seek to complete */
1954     GST_INFO ("done seeking %d", res);
1955     g_rec_mutex_unlock (&priv->state_lock);
1956
1957     /* wait until pipeline is prerolled again, this will also collect stats */
1958     if (!wait_preroll (media))
1959       goto preroll_failed;
1960
1961     g_rec_mutex_lock (&priv->state_lock);
1962     GST_INFO ("prerolled again");
1963   } else {
1964     GST_INFO ("no seek needed");
1965     res = TRUE;
1966   }
1967   g_rec_mutex_unlock (&priv->state_lock);
1968
1969   return res;
1970
1971   /* ERRORS */
1972 not_prepared:
1973   {
1974     g_rec_mutex_unlock (&priv->state_lock);
1975     GST_INFO ("media %p is not prepared", media);
1976     return FALSE;
1977   }
1978 not_seekable:
1979   {
1980     g_rec_mutex_unlock (&priv->state_lock);
1981     GST_INFO ("pipeline is not seekable");
1982     return FALSE;
1983   }
1984 not_supported:
1985   {
1986     g_rec_mutex_unlock (&priv->state_lock);
1987     GST_WARNING ("conversion to npt not supported");
1988     return FALSE;
1989   }
1990 preroll_failed:
1991   {
1992     GST_WARNING ("failed to preroll after seek");
1993     return FALSE;
1994   }
1995 }
1996
1997 static void
1998 stream_collect_blocking (GstRTSPStream * stream, gboolean * blocked)
1999 {
2000   *blocked &= gst_rtsp_stream_is_blocking (stream);
2001 }
2002
2003 static gboolean
2004 media_streams_blocking (GstRTSPMedia * media)
2005 {
2006   gboolean blocking = TRUE;
2007
2008   g_ptr_array_foreach (media->priv->streams, (GFunc) stream_collect_blocking,
2009       &blocking);
2010
2011   return blocking;
2012 }
2013
2014 static GstStateChangeReturn
2015 set_state (GstRTSPMedia * media, GstState state)
2016 {
2017   GstRTSPMediaPrivate *priv = media->priv;
2018   GstStateChangeReturn ret;
2019
2020   GST_INFO ("set state to %s for media %p", gst_element_state_get_name (state),
2021       media);
2022   ret = gst_element_set_state (priv->pipeline, state);
2023
2024   return ret;
2025 }
2026
2027 static GstStateChangeReturn
2028 set_target_state (GstRTSPMedia * media, GstState state, gboolean do_state)
2029 {
2030   GstRTSPMediaPrivate *priv = media->priv;
2031   GstStateChangeReturn ret;
2032
2033   GST_INFO ("set target state to %s for media %p",
2034       gst_element_state_get_name (state), media);
2035   priv->target_state = state;
2036
2037   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_TARGET_STATE], 0,
2038       priv->target_state, NULL);
2039
2040   if (do_state)
2041     ret = set_state (media, state);
2042   else
2043     ret = GST_STATE_CHANGE_SUCCESS;
2044
2045   return ret;
2046 }
2047
2048 /* called with state-lock */
2049 static gboolean
2050 default_handle_message (GstRTSPMedia * media, GstMessage * message)
2051 {
2052   GstRTSPMediaPrivate *priv = media->priv;
2053   GstMessageType type;
2054
2055   type = GST_MESSAGE_TYPE (message);
2056
2057   switch (type) {
2058     case GST_MESSAGE_STATE_CHANGED:
2059     {
2060       GstState old, new, pending;
2061
2062       if (GST_MESSAGE_SRC (message) != GST_OBJECT (priv->pipeline))
2063         break;
2064
2065       gst_message_parse_state_changed (message, &old, &new, &pending);
2066
2067       GST_DEBUG ("%p: went from %s to %s (pending %s)", media,
2068           gst_element_state_get_name (old), gst_element_state_get_name (new),
2069           gst_element_state_get_name (pending));
2070       if ((priv->transport_mode & GST_RTSP_TRANSPORT_MODE_RECORD)
2071           && old == GST_STATE_READY && new == GST_STATE_PAUSED) {
2072         GST_INFO ("%p: went to PAUSED, prepared now", media);
2073         collect_media_stats (media);
2074
2075         if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2076           gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2077       }
2078
2079       break;
2080     }
2081     case GST_MESSAGE_BUFFERING:
2082     {
2083       gint percent;
2084
2085       gst_message_parse_buffering (message, &percent);
2086
2087       /* no state management needed for live pipelines */
2088       if (priv->is_live)
2089         break;
2090
2091       if (percent == 100) {
2092         /* a 100% message means buffering is done */
2093         priv->buffering = FALSE;
2094         /* if the desired state is playing, go back */
2095         if (priv->target_state == GST_STATE_PLAYING) {
2096           GST_INFO ("Buffering done, setting pipeline to PLAYING");
2097           set_state (media, GST_STATE_PLAYING);
2098         } else {
2099           GST_INFO ("Buffering done");
2100         }
2101       } else {
2102         /* buffering busy */
2103         if (priv->buffering == FALSE) {
2104           if (priv->target_state == GST_STATE_PLAYING) {
2105             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
2106             GST_INFO ("Buffering, setting pipeline to PAUSED ...");
2107             set_state (media, GST_STATE_PAUSED);
2108           } else {
2109             GST_INFO ("Buffering ...");
2110           }
2111         }
2112         priv->buffering = TRUE;
2113       }
2114       break;
2115     }
2116     case GST_MESSAGE_LATENCY:
2117     {
2118       gst_bin_recalculate_latency (GST_BIN_CAST (priv->pipeline));
2119       break;
2120     }
2121     case GST_MESSAGE_ERROR:
2122     {
2123       GError *gerror;
2124       gchar *debug;
2125
2126       gst_message_parse_error (message, &gerror, &debug);
2127       GST_WARNING ("%p: got error %s (%s)", media, gerror->message, debug);
2128       g_error_free (gerror);
2129       g_free (debug);
2130
2131       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2132       break;
2133     }
2134     case GST_MESSAGE_WARNING:
2135     {
2136       GError *gerror;
2137       gchar *debug;
2138
2139       gst_message_parse_warning (message, &gerror, &debug);
2140       GST_WARNING ("%p: got warning %s (%s)", media, gerror->message, debug);
2141       g_error_free (gerror);
2142       g_free (debug);
2143       break;
2144     }
2145     case GST_MESSAGE_ELEMENT:
2146     {
2147       const GstStructure *s;
2148
2149       s = gst_message_get_structure (message);
2150       if (gst_structure_has_name (s, "GstRTSPStreamBlocking")) {
2151         GST_DEBUG ("media received blocking message");
2152         if (priv->blocked && media_streams_blocking (media)) {
2153           GST_DEBUG ("media is blocking");
2154           collect_media_stats (media);
2155
2156           if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2157             gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2158         }
2159       }
2160       break;
2161     }
2162     case GST_MESSAGE_STREAM_STATUS:
2163       break;
2164     case GST_MESSAGE_ASYNC_DONE:
2165       if (priv->adding) {
2166         /* when we are dynamically adding pads, the addition of the udpsrc will
2167          * temporarily produce ASYNC_DONE messages. We have to ignore them and
2168          * wait for the final ASYNC_DONE after everything prerolled */
2169         GST_INFO ("%p: ignoring ASYNC_DONE", media);
2170       } else {
2171         GST_INFO ("%p: got ASYNC_DONE", media);
2172         collect_media_stats (media);
2173
2174         if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2175           gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
2176       }
2177       break;
2178     case GST_MESSAGE_EOS:
2179       GST_INFO ("%p: got EOS", media);
2180
2181       if (priv->status == GST_RTSP_MEDIA_STATUS_UNPREPARING) {
2182         GST_DEBUG ("shutting down after EOS");
2183         finish_unprepare (media);
2184       }
2185       break;
2186     default:
2187       GST_INFO ("%p: got message type %d (%s)", media, type,
2188           gst_message_type_get_name (type));
2189       break;
2190   }
2191   return TRUE;
2192 }
2193
2194 static gboolean
2195 bus_message (GstBus * bus, GstMessage * message, GstRTSPMedia * media)
2196 {
2197   GstRTSPMediaPrivate *priv = media->priv;
2198   GstRTSPMediaClass *klass;
2199   gboolean ret;
2200
2201   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2202
2203   g_rec_mutex_lock (&priv->state_lock);
2204   if (klass->handle_message)
2205     ret = klass->handle_message (media, message);
2206   else
2207     ret = FALSE;
2208   g_rec_mutex_unlock (&priv->state_lock);
2209
2210   return ret;
2211 }
2212
2213 static void
2214 watch_destroyed (GstRTSPMedia * media)
2215 {
2216   GST_DEBUG_OBJECT (media, "source destroyed");
2217   g_object_unref (media);
2218 }
2219
2220 static GstElement *
2221 find_payload_element (GstElement * payloader)
2222 {
2223   GstElement *pay = NULL;
2224
2225   if (GST_IS_BIN (payloader)) {
2226     GstIterator *iter;
2227     GValue item = { 0 };
2228
2229     iter = gst_bin_iterate_recurse (GST_BIN (payloader));
2230     while (gst_iterator_next (iter, &item) == GST_ITERATOR_OK) {
2231       GstElement *element = (GstElement *) g_value_get_object (&item);
2232       GstElementClass *eclass = GST_ELEMENT_GET_CLASS (element);
2233       const gchar *klass;
2234
2235       klass =
2236           gst_element_class_get_metadata (eclass, GST_ELEMENT_METADATA_KLASS);
2237       if (klass == NULL)
2238         continue;
2239
2240       if (strstr (klass, "Payloader") && strstr (klass, "RTP")) {
2241         pay = gst_object_ref (element);
2242         g_value_unset (&item);
2243         break;
2244       }
2245       g_value_unset (&item);
2246     }
2247     gst_iterator_free (iter);
2248   } else {
2249     pay = g_object_ref (payloader);
2250   }
2251
2252   return pay;
2253 }
2254
2255 /* called from streaming threads */
2256 static void
2257 pad_added_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
2258 {
2259   GstRTSPMediaPrivate *priv = media->priv;
2260   GstRTSPStream *stream;
2261   GstElement *pay;
2262
2263   /* find the real payload element */
2264   pay = find_payload_element (element);
2265   stream = gst_rtsp_media_create_stream (media, pay, pad);
2266   gst_object_unref (pay);
2267
2268   GST_INFO ("pad added %s:%s, stream %p", GST_DEBUG_PAD_NAME (pad), stream);
2269
2270   g_rec_mutex_lock (&priv->state_lock);
2271   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARING)
2272     goto not_preparing;
2273
2274   g_object_set_data (G_OBJECT (pad), "gst-rtsp-dynpad-stream", stream);
2275
2276   /* we will be adding elements below that will cause ASYNC_DONE to be
2277    * posted in the bus. We want to ignore those messages until the
2278    * pipeline really prerolled. */
2279   priv->adding = TRUE;
2280
2281   /* join the element in the PAUSED state because this callback is
2282    * called from the streaming thread and it is PAUSED */
2283   if (!gst_rtsp_stream_join_bin (stream, GST_BIN (priv->pipeline),
2284           priv->rtpbin, GST_STATE_PAUSED)) {
2285     GST_WARNING ("failed to join bin element");
2286   }
2287
2288   priv->adding = FALSE;
2289   g_rec_mutex_unlock (&priv->state_lock);
2290
2291   return;
2292
2293   /* ERRORS */
2294 not_preparing:
2295   {
2296     gst_rtsp_media_remove_stream (media, stream);
2297     g_rec_mutex_unlock (&priv->state_lock);
2298     GST_INFO ("ignore pad because we are not preparing");
2299     return;
2300   }
2301 }
2302
2303 static void
2304 pad_removed_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
2305 {
2306   GstRTSPMediaPrivate *priv = media->priv;
2307   GstRTSPStream *stream;
2308
2309   stream = g_object_get_data (G_OBJECT (pad), "gst-rtsp-dynpad-stream");
2310   if (stream == NULL)
2311     return;
2312
2313   GST_INFO ("pad removed %s:%s, stream %p", GST_DEBUG_PAD_NAME (pad), stream);
2314
2315   g_rec_mutex_lock (&priv->state_lock);
2316   gst_rtsp_stream_leave_bin (stream, GST_BIN (priv->pipeline), priv->rtpbin);
2317   g_rec_mutex_unlock (&priv->state_lock);
2318
2319   gst_rtsp_media_remove_stream (media, stream);
2320 }
2321
2322 static void
2323 remove_fakesink (GstRTSPMediaPrivate * priv)
2324 {
2325   GstElement *fakesink;
2326
2327   g_mutex_lock (&priv->lock);
2328   if ((fakesink = priv->fakesink))
2329     gst_object_ref (fakesink);
2330   priv->fakesink = NULL;
2331   g_mutex_unlock (&priv->lock);
2332
2333   if (fakesink) {
2334     gst_bin_remove (GST_BIN (priv->pipeline), fakesink);
2335     gst_element_set_state (fakesink, GST_STATE_NULL);
2336     gst_object_unref (fakesink);
2337     GST_INFO ("removed fakesink");
2338   }
2339 }
2340
2341 static void
2342 no_more_pads_cb (GstElement * element, GstRTSPMedia * media)
2343 {
2344   GstRTSPMediaPrivate *priv = media->priv;
2345
2346   GST_INFO ("no more pads");
2347   remove_fakesink (priv);
2348 }
2349
2350 typedef struct _DynPaySignalHandlers DynPaySignalHandlers;
2351
2352 struct _DynPaySignalHandlers
2353 {
2354   gulong pad_added_handler;
2355   gulong pad_removed_handler;
2356   gulong no_more_pads_handler;
2357 };
2358
2359 static gboolean
2360 start_preroll (GstRTSPMedia * media)
2361 {
2362   GstRTSPMediaPrivate *priv = media->priv;
2363   GstStateChangeReturn ret;
2364
2365   GST_INFO ("setting pipeline to PAUSED for media %p", media);
2366   /* first go to PAUSED */
2367   ret = set_target_state (media, GST_STATE_PAUSED, TRUE);
2368
2369   switch (ret) {
2370     case GST_STATE_CHANGE_SUCCESS:
2371       GST_INFO ("SUCCESS state change for media %p", media);
2372       priv->seekable = TRUE;
2373       break;
2374     case GST_STATE_CHANGE_ASYNC:
2375       GST_INFO ("ASYNC state change for media %p", media);
2376       priv->seekable = TRUE;
2377       break;
2378     case GST_STATE_CHANGE_NO_PREROLL:
2379       /* we need to go to PLAYING */
2380       GST_INFO ("NO_PREROLL state change: live media %p", media);
2381       /* FIXME we disable seeking for live streams for now. We should perform a
2382        * seeking query in preroll instead */
2383       priv->seekable = FALSE;
2384       priv->is_live = TRUE;
2385       if (!(priv->transport_mode & GST_RTSP_TRANSPORT_MODE_RECORD)) {
2386         /* start blocked  to make sure nothing goes to the sink */
2387         media_streams_set_blocked (media, TRUE);
2388       }
2389       ret = set_state (media, GST_STATE_PLAYING);
2390       if (ret == GST_STATE_CHANGE_FAILURE)
2391         goto state_failed;
2392       break;
2393     case GST_STATE_CHANGE_FAILURE:
2394       goto state_failed;
2395   }
2396
2397   return TRUE;
2398
2399 state_failed:
2400   {
2401     GST_WARNING ("failed to preroll pipeline");
2402     return FALSE;
2403   }
2404 }
2405
2406 static gboolean
2407 wait_preroll (GstRTSPMedia * media)
2408 {
2409   GstRTSPMediaStatus status;
2410
2411   GST_DEBUG ("wait to preroll pipeline");
2412
2413   /* wait until pipeline is prerolled */
2414   status = gst_rtsp_media_get_status (media);
2415   if (status == GST_RTSP_MEDIA_STATUS_ERROR)
2416     goto preroll_failed;
2417
2418   return TRUE;
2419
2420 preroll_failed:
2421   {
2422     GST_WARNING ("failed to preroll pipeline");
2423     return FALSE;
2424   }
2425 }
2426
2427 static gboolean
2428 start_prepare (GstRTSPMedia * media)
2429 {
2430   GstRTSPMediaPrivate *priv = media->priv;
2431   guint i;
2432   GList *walk;
2433
2434   /* link streams we already have, other streams might appear when we have
2435    * dynamic elements */
2436   for (i = 0; i < priv->streams->len; i++) {
2437     GstRTSPStream *stream;
2438
2439     stream = g_ptr_array_index (priv->streams, i);
2440
2441     if (!gst_rtsp_stream_join_bin (stream, GST_BIN (priv->pipeline),
2442             priv->rtpbin, GST_STATE_NULL)) {
2443       goto join_bin_failed;
2444     }
2445   }
2446
2447   if (priv->rtpbin)
2448     g_object_set (priv->rtpbin, "do-retransmission", priv->rtx_time > 0, NULL);
2449
2450   for (walk = priv->dynamic; walk; walk = g_list_next (walk)) {
2451     GstElement *elem = walk->data;
2452     DynPaySignalHandlers *handlers = g_slice_new (DynPaySignalHandlers);
2453
2454     GST_INFO ("adding callbacks for dynamic element %p", elem);
2455
2456     handlers->pad_added_handler = g_signal_connect (elem, "pad-added",
2457         (GCallback) pad_added_cb, media);
2458     handlers->pad_removed_handler = g_signal_connect (elem, "pad-removed",
2459         (GCallback) pad_removed_cb, media);
2460     handlers->no_more_pads_handler = g_signal_connect (elem, "no-more-pads",
2461         (GCallback) no_more_pads_cb, media);
2462
2463     g_object_set_data (G_OBJECT (elem), "gst-rtsp-dynpay-handlers", handlers);
2464
2465     /* we add a fakesink here in order to make the state change async. We remove
2466      * the fakesink again in the no-more-pads callback. */
2467     priv->fakesink = gst_element_factory_make ("fakesink", "fakesink");
2468     gst_bin_add (GST_BIN (priv->pipeline), priv->fakesink);
2469   }
2470
2471   if (!start_preroll (media))
2472     goto preroll_failed;
2473
2474   return FALSE;
2475
2476 join_bin_failed:
2477   {
2478     GST_WARNING ("failed to join bin element");
2479     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2480     return FALSE;
2481   }
2482 preroll_failed:
2483   {
2484     GST_WARNING ("failed to preroll pipeline");
2485     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
2486     return FALSE;
2487   }
2488 }
2489
2490 static gboolean
2491 default_prepare (GstRTSPMedia * media, GstRTSPThread * thread)
2492 {
2493   GstRTSPMediaPrivate *priv;
2494   GstRTSPMediaClass *klass;
2495   GstBus *bus;
2496   GMainContext *context;
2497   GSource *source;
2498
2499   priv = media->priv;
2500
2501   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2502
2503   if (!klass->create_rtpbin)
2504     goto no_create_rtpbin;
2505
2506   priv->rtpbin = klass->create_rtpbin (media);
2507   if (priv->rtpbin != NULL) {
2508     gboolean success = TRUE;
2509
2510     g_object_set (priv->rtpbin, "latency", priv->latency, NULL);
2511
2512     if (klass->setup_rtpbin)
2513       success = klass->setup_rtpbin (media, priv->rtpbin);
2514
2515     if (success == FALSE) {
2516       gst_object_unref (priv->rtpbin);
2517       priv->rtpbin = NULL;
2518     }
2519   }
2520   if (priv->rtpbin == NULL)
2521     goto no_rtpbin;
2522
2523   priv->thread = thread;
2524   context = (thread != NULL) ? (thread->context) : NULL;
2525
2526   bus = gst_pipeline_get_bus (GST_PIPELINE_CAST (priv->pipeline));
2527
2528   /* add the pipeline bus to our custom mainloop */
2529   priv->source = gst_bus_create_watch (bus);
2530   gst_object_unref (bus);
2531
2532   g_source_set_callback (priv->source, (GSourceFunc) bus_message,
2533       g_object_ref (media), (GDestroyNotify) watch_destroyed);
2534
2535   priv->id = g_source_attach (priv->source, context);
2536
2537   /* add stuff to the bin */
2538   gst_bin_add (GST_BIN (priv->pipeline), priv->rtpbin);
2539
2540   /* do remainder in context */
2541   source = g_idle_source_new ();
2542   g_source_set_callback (source, (GSourceFunc) start_prepare, media, NULL);
2543   g_source_attach (source, context);
2544   g_source_unref (source);
2545
2546   return TRUE;
2547
2548   /* ERRORS */
2549 no_create_rtpbin:
2550   {
2551     GST_ERROR ("no create_rtpbin function");
2552     g_critical ("no create_rtpbin vmethod function set");
2553     return FALSE;
2554   }
2555 no_rtpbin:
2556   {
2557     GST_WARNING ("no rtpbin element");
2558     g_warning ("failed to create element 'rtpbin', check your installation");
2559     return FALSE;
2560   }
2561 }
2562
2563 /**
2564  * gst_rtsp_media_prepare:
2565  * @media: a #GstRTSPMedia
2566  * @thread: (transfer full) (allow-none): a #GstRTSPThread to run the
2567  *   bus handler or %NULL
2568  *
2569  * Prepare @media for streaming. This function will create the objects
2570  * to manage the streaming. A pipeline must have been set on @media with
2571  * gst_rtsp_media_take_pipeline().
2572  *
2573  * It will preroll the pipeline and collect vital information about the streams
2574  * such as the duration.
2575  *
2576  * Returns: %TRUE on success.
2577  */
2578 gboolean
2579 gst_rtsp_media_prepare (GstRTSPMedia * media, GstRTSPThread * thread)
2580 {
2581   GstRTSPMediaPrivate *priv;
2582   GstRTSPMediaClass *klass;
2583
2584   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2585
2586   priv = media->priv;
2587
2588   g_rec_mutex_lock (&priv->state_lock);
2589   priv->prepare_count++;
2590
2591   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED ||
2592       priv->status == GST_RTSP_MEDIA_STATUS_SUSPENDED)
2593     goto was_prepared;
2594
2595   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARING)
2596     goto is_preparing;
2597
2598   if (priv->status != GST_RTSP_MEDIA_STATUS_UNPREPARED)
2599     goto not_unprepared;
2600
2601   if (!priv->reusable && priv->reused)
2602     goto is_reused;
2603
2604   GST_INFO ("preparing media %p", media);
2605
2606   /* reset some variables */
2607   priv->is_live = FALSE;
2608   priv->seekable = FALSE;
2609   priv->buffering = FALSE;
2610
2611   /* we're preparing now */
2612   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
2613
2614   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2615   if (klass->prepare) {
2616     if (!klass->prepare (media, thread))
2617       goto prepare_failed;
2618   }
2619
2620 wait_status:
2621   g_rec_mutex_unlock (&priv->state_lock);
2622
2623   /* now wait for all pads to be prerolled, FIXME, we should somehow be
2624    * able to do this async so that we don't block the server thread. */
2625   if (!wait_preroll (media))
2626     goto preroll_failed;
2627
2628   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_PREPARED], 0, NULL);
2629
2630   GST_INFO ("object %p is prerolled", media);
2631
2632   return TRUE;
2633
2634   /* OK */
2635 is_preparing:
2636   {
2637     /* we are not going to use the giving thread, so stop it. */
2638     if (thread)
2639       gst_rtsp_thread_stop (thread);
2640     goto wait_status;
2641   }
2642 was_prepared:
2643   {
2644     GST_LOG ("media %p was prepared", media);
2645     /* we are not going to use the giving thread, so stop it. */
2646     if (thread)
2647       gst_rtsp_thread_stop (thread);
2648     g_rec_mutex_unlock (&priv->state_lock);
2649     return TRUE;
2650   }
2651   /* ERRORS */
2652 not_unprepared:
2653   {
2654     /* we are not going to use the giving thread, so stop it. */
2655     if (thread)
2656       gst_rtsp_thread_stop (thread);
2657     GST_WARNING ("media %p was not unprepared", media);
2658     priv->prepare_count--;
2659     g_rec_mutex_unlock (&priv->state_lock);
2660     return FALSE;
2661   }
2662 is_reused:
2663   {
2664     /* we are not going to use the giving thread, so stop it. */
2665     if (thread)
2666       gst_rtsp_thread_stop (thread);
2667     priv->prepare_count--;
2668     g_rec_mutex_unlock (&priv->state_lock);
2669     GST_WARNING ("can not reuse media %p", media);
2670     return FALSE;
2671   }
2672 prepare_failed:
2673   {
2674     /* we are not going to use the giving thread, so stop it. */
2675     if (thread)
2676       gst_rtsp_thread_stop (thread);
2677     priv->prepare_count--;
2678     g_rec_mutex_unlock (&priv->state_lock);
2679     GST_ERROR ("failed to prepare media");
2680     return FALSE;
2681   }
2682 preroll_failed:
2683   {
2684     GST_WARNING ("failed to preroll pipeline");
2685     gst_rtsp_media_unprepare (media);
2686     return FALSE;
2687   }
2688 }
2689
2690 /* must be called with state-lock */
2691 static void
2692 finish_unprepare (GstRTSPMedia * media)
2693 {
2694   GstRTSPMediaPrivate *priv = media->priv;
2695   gint i;
2696   GList *walk;
2697
2698   GST_DEBUG ("shutting down");
2699
2700   /* release the lock on shutdown, otherwise pad_added_cb might try to
2701    * acquire the lock and then we deadlock */
2702   g_rec_mutex_unlock (&priv->state_lock);
2703   set_state (media, GST_STATE_NULL);
2704   g_rec_mutex_lock (&priv->state_lock);
2705   remove_fakesink (priv);
2706
2707   for (i = 0; i < priv->streams->len; i++) {
2708     GstRTSPStream *stream;
2709
2710     GST_INFO ("Removing elements of stream %d from pipeline", i);
2711
2712     stream = g_ptr_array_index (priv->streams, i);
2713
2714     gst_rtsp_stream_leave_bin (stream, GST_BIN (priv->pipeline), priv->rtpbin);
2715   }
2716
2717   /* remove the pad signal handlers */
2718   for (walk = priv->dynamic; walk; walk = g_list_next (walk)) {
2719     GstElement *elem = walk->data;
2720     DynPaySignalHandlers *handlers;
2721
2722     handlers =
2723         g_object_steal_data (G_OBJECT (elem), "gst-rtsp-dynpay-handlers");
2724     g_assert (handlers != NULL);
2725
2726     g_signal_handler_disconnect (G_OBJECT (elem), handlers->pad_added_handler);
2727     g_signal_handler_disconnect (G_OBJECT (elem),
2728         handlers->pad_removed_handler);
2729     g_signal_handler_disconnect (G_OBJECT (elem),
2730         handlers->no_more_pads_handler);
2731
2732     g_slice_free (DynPaySignalHandlers, handlers);
2733   }
2734
2735   gst_bin_remove (GST_BIN (priv->pipeline), priv->rtpbin);
2736   priv->rtpbin = NULL;
2737
2738   if (priv->nettime)
2739     gst_object_unref (priv->nettime);
2740   priv->nettime = NULL;
2741
2742   priv->reused = TRUE;
2743   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_UNPREPARED);
2744
2745   /* when the media is not reusable, this will effectively unref the media and
2746    * recreate it */
2747   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_UNPREPARED], 0, NULL);
2748
2749   /* the source has the last ref to the media */
2750   if (priv->source) {
2751     GST_DEBUG ("destroy source");
2752     g_source_destroy (priv->source);
2753     g_source_unref (priv->source);
2754   }
2755   if (priv->thread) {
2756     GST_DEBUG ("stop thread");
2757     gst_rtsp_thread_stop (priv->thread);
2758   }
2759 }
2760
2761 /* called with state-lock */
2762 static gboolean
2763 default_unprepare (GstRTSPMedia * media)
2764 {
2765   GstRTSPMediaPrivate *priv = media->priv;
2766
2767   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_UNPREPARING);
2768
2769   if (priv->eos_shutdown) {
2770     GST_DEBUG ("sending EOS for shutdown");
2771     /* ref so that we don't disappear */
2772     gst_element_send_event (priv->pipeline, gst_event_new_eos ());
2773     /* we need to go to playing again for the EOS to propagate, normally in this
2774      * state, nothing is receiving data from us anymore so this is ok. */
2775     set_state (media, GST_STATE_PLAYING);
2776   } else {
2777     finish_unprepare (media);
2778   }
2779   return TRUE;
2780 }
2781
2782 /**
2783  * gst_rtsp_media_unprepare:
2784  * @media: a #GstRTSPMedia
2785  *
2786  * Unprepare @media. After this call, the media should be prepared again before
2787  * it can be used again. If the media is set to be non-reusable, a new instance
2788  * must be created.
2789  *
2790  * Returns: %TRUE on success.
2791  */
2792 gboolean
2793 gst_rtsp_media_unprepare (GstRTSPMedia * media)
2794 {
2795   GstRTSPMediaPrivate *priv;
2796   gboolean success;
2797
2798   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2799
2800   priv = media->priv;
2801
2802   g_rec_mutex_lock (&priv->state_lock);
2803   if (priv->status == GST_RTSP_MEDIA_STATUS_UNPREPARED)
2804     goto was_unprepared;
2805
2806   priv->prepare_count--;
2807   if (priv->prepare_count > 0)
2808     goto is_busy;
2809
2810   GST_INFO ("unprepare media %p", media);
2811   if (priv->blocked)
2812     media_streams_set_blocked (media, FALSE);
2813   set_target_state (media, GST_STATE_NULL, FALSE);
2814   success = TRUE;
2815
2816   if (priv->status == GST_RTSP_MEDIA_STATUS_PREPARED) {
2817     GstRTSPMediaClass *klass;
2818
2819     klass = GST_RTSP_MEDIA_GET_CLASS (media);
2820     if (klass->unprepare)
2821       success = klass->unprepare (media);
2822   } else {
2823     finish_unprepare (media);
2824   }
2825   g_rec_mutex_unlock (&priv->state_lock);
2826
2827   return success;
2828
2829 was_unprepared:
2830   {
2831     g_rec_mutex_unlock (&priv->state_lock);
2832     GST_INFO ("media %p was already unprepared", media);
2833     return TRUE;
2834   }
2835 is_busy:
2836   {
2837     GST_INFO ("media %p still prepared %d times", media, priv->prepare_count);
2838     g_rec_mutex_unlock (&priv->state_lock);
2839     return TRUE;
2840   }
2841 }
2842
2843 /* should be called with state-lock */
2844 static GstClock *
2845 get_clock_unlocked (GstRTSPMedia * media)
2846 {
2847   if (media->priv->status != GST_RTSP_MEDIA_STATUS_PREPARED) {
2848     GST_DEBUG_OBJECT (media, "media was not prepared");
2849     return NULL;
2850   }
2851   return gst_pipeline_get_clock (GST_PIPELINE_CAST (media->priv->pipeline));
2852 }
2853
2854 /**
2855  * gst_rtsp_media_get_clock:
2856  * @media: a #GstRTSPMedia
2857  *
2858  * Get the clock that is used by the pipeline in @media.
2859  *
2860  * @media must be prepared before this method returns a valid clock object.
2861  *
2862  * Returns: (transfer full): the #GstClock used by @media. unref after usage.
2863  */
2864 GstClock *
2865 gst_rtsp_media_get_clock (GstRTSPMedia * media)
2866 {
2867   GstClock *clock;
2868   GstRTSPMediaPrivate *priv;
2869
2870   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
2871
2872   priv = media->priv;
2873
2874   g_rec_mutex_lock (&priv->state_lock);
2875   clock = get_clock_unlocked (media);
2876   g_rec_mutex_unlock (&priv->state_lock);
2877
2878   return clock;
2879 }
2880
2881 /**
2882  * gst_rtsp_media_get_base_time:
2883  * @media: a #GstRTSPMedia
2884  *
2885  * Get the base_time that is used by the pipeline in @media.
2886  *
2887  * @media must be prepared before this method returns a valid base_time.
2888  *
2889  * Returns: the base_time used by @media.
2890  */
2891 GstClockTime
2892 gst_rtsp_media_get_base_time (GstRTSPMedia * media)
2893 {
2894   GstClockTime result;
2895   GstRTSPMediaPrivate *priv;
2896
2897   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), GST_CLOCK_TIME_NONE);
2898
2899   priv = media->priv;
2900
2901   g_rec_mutex_lock (&priv->state_lock);
2902   if (media->priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
2903     goto not_prepared;
2904
2905   result = gst_element_get_base_time (media->priv->pipeline);
2906   g_rec_mutex_unlock (&priv->state_lock);
2907
2908   return result;
2909
2910   /* ERRORS */
2911 not_prepared:
2912   {
2913     g_rec_mutex_unlock (&priv->state_lock);
2914     GST_DEBUG_OBJECT (media, "media was not prepared");
2915     return GST_CLOCK_TIME_NONE;
2916   }
2917 }
2918
2919 /**
2920  * gst_rtsp_media_get_time_provider:
2921  * @media: a #GstRTSPMedia
2922  * @address: (allow-none): an address or %NULL
2923  * @port: a port or 0
2924  *
2925  * Get the #GstNetTimeProvider for the clock used by @media. The time provider
2926  * will listen on @address and @port for client time requests.
2927  *
2928  * Returns: (transfer full): the #GstNetTimeProvider of @media.
2929  */
2930 GstNetTimeProvider *
2931 gst_rtsp_media_get_time_provider (GstRTSPMedia * media, const gchar * address,
2932     guint16 port)
2933 {
2934   GstRTSPMediaPrivate *priv;
2935   GstNetTimeProvider *provider = NULL;
2936
2937   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
2938
2939   priv = media->priv;
2940
2941   g_rec_mutex_lock (&priv->state_lock);
2942   if (priv->time_provider) {
2943     if ((provider = priv->nettime) == NULL) {
2944       GstClock *clock;
2945
2946       if (priv->time_provider && (clock = get_clock_unlocked (media))) {
2947         provider = gst_net_time_provider_new (clock, address, port);
2948         gst_object_unref (clock);
2949
2950         priv->nettime = provider;
2951       }
2952     }
2953   }
2954   g_rec_mutex_unlock (&priv->state_lock);
2955
2956   if (provider)
2957     gst_object_ref (provider);
2958
2959   return provider;
2960 }
2961
2962 static gboolean
2963 default_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp, GstSDPInfo * info)
2964 {
2965   return gst_rtsp_sdp_from_media (sdp, info, media);
2966 }
2967
2968 /**
2969  * gst_rtsp_media_setup_sdp:
2970  * @media: a #GstRTSPMedia
2971  * @sdp: (transfer none): a #GstSDPMessage
2972  * @info: (transfer none): a #GstSDPInfo
2973  *
2974  * Add @media specific info to @sdp. @info is used to configure the connection
2975  * information in the SDP.
2976  *
2977  * Returns: TRUE on success.
2978  */
2979 gboolean
2980 gst_rtsp_media_setup_sdp (GstRTSPMedia * media, GstSDPMessage * sdp,
2981     GstSDPInfo * info)
2982 {
2983   GstRTSPMediaPrivate *priv;
2984   GstRTSPMediaClass *klass;
2985   gboolean res;
2986
2987   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
2988   g_return_val_if_fail (sdp != NULL, FALSE);
2989   g_return_val_if_fail (info != NULL, FALSE);
2990
2991   priv = media->priv;
2992
2993   g_rec_mutex_lock (&priv->state_lock);
2994
2995   klass = GST_RTSP_MEDIA_GET_CLASS (media);
2996
2997   if (!klass->setup_sdp)
2998     goto no_setup_sdp;
2999
3000   res = klass->setup_sdp (media, sdp, info);
3001
3002   g_rec_mutex_unlock (&priv->state_lock);
3003
3004   return res;
3005
3006   /* ERRORS */
3007 no_setup_sdp:
3008   {
3009     g_rec_mutex_unlock (&priv->state_lock);
3010     GST_ERROR ("no setup_sdp function");
3011     g_critical ("no setup_sdp vmethod function set");
3012     return FALSE;
3013   }
3014 }
3015
3016 static const gchar *
3017 rtsp_get_attribute_for_pt (const GstSDPMedia * media, const gchar * name,
3018     gint pt)
3019 {
3020   guint i;
3021
3022   for (i = 0;; i++) {
3023     const gchar *attr;
3024     gint val;
3025
3026     if ((attr = gst_sdp_media_get_attribute_val_n (media, name, i)) == NULL)
3027       break;
3028
3029     if (sscanf (attr, "%d ", &val) != 1)
3030       continue;
3031
3032     if (val == pt)
3033       return attr;
3034   }
3035   return NULL;
3036 }
3037
3038 #define PARSE_INT(p, del, res)          \
3039 G_STMT_START {                          \
3040   gchar *t = p;                         \
3041   p = strstr (p, del);                  \
3042   if (p == NULL)                        \
3043     res = -1;                           \
3044   else {                                \
3045     *p = '\0';                          \
3046     p++;                                \
3047     res = atoi (t);                     \
3048   }                                     \
3049 } G_STMT_END
3050
3051 #define PARSE_STRING(p, del, res)       \
3052 G_STMT_START {                          \
3053   gchar *t = p;                         \
3054   p = strstr (p, del);                  \
3055   if (p == NULL) {                      \
3056     res = NULL;                         \
3057     p = t;                              \
3058   }                                     \
3059   else {                                \
3060     *p = '\0';                          \
3061     p++;                                \
3062     res = t;                            \
3063   }                                     \
3064 } G_STMT_END
3065
3066 #define SKIP_SPACES(p)                  \
3067   while (*p && g_ascii_isspace (*p))    \
3068     p++;
3069
3070 /* rtpmap contains:
3071  *
3072  *  <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
3073  */
3074 static gboolean
3075 parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
3076     gint * rate, gchar ** params)
3077 {
3078   gchar *p, *t;
3079
3080   p = (gchar *) rtpmap;
3081
3082   PARSE_INT (p, " ", *payload);
3083   if (*payload == -1)
3084     return FALSE;
3085
3086   SKIP_SPACES (p);
3087   if (*p == '\0')
3088     return FALSE;
3089
3090   PARSE_STRING (p, "/", *name);
3091   if (*name == NULL) {
3092     GST_DEBUG ("no rate, name %s", p);
3093     /* no rate, assume -1 then, this is not supposed to happen but RealMedia
3094      * streams seem to omit the rate. */
3095     *name = p;
3096     *rate = -1;
3097     return TRUE;
3098   }
3099
3100   t = p;
3101   p = strstr (p, "/");
3102   if (p == NULL) {
3103     *rate = atoi (t);
3104     return TRUE;
3105   }
3106   *p = '\0';
3107   p++;
3108   *rate = atoi (t);
3109
3110   t = p;
3111   if (*p == '\0')
3112     return TRUE;
3113   *params = t;
3114
3115   return TRUE;
3116 }
3117
3118 /*
3119  *  Mapping of caps to and from SDP fields:
3120  *
3121  *   a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
3122  *   a=fmtp:<payload> <param>[=<value>];...
3123  */
3124 static GstCaps *
3125 media_to_caps (gint pt, const GstSDPMedia * media)
3126 {
3127   GstCaps *caps;
3128   const gchar *rtpmap;
3129   const gchar *fmtp;
3130   gchar *name = NULL;
3131   gint rate = -1;
3132   gchar *params = NULL;
3133   gchar *tmp;
3134   GstStructure *s;
3135   gint payload = 0;
3136   gboolean ret;
3137
3138   /* get and parse rtpmap */
3139   rtpmap = rtsp_get_attribute_for_pt (media, "rtpmap", pt);
3140
3141   if (rtpmap) {
3142     ret = parse_rtpmap (rtpmap, &payload, &name, &rate, &params);
3143     if (!ret) {
3144       g_warning ("error parsing rtpmap, ignoring");
3145       rtpmap = NULL;
3146     }
3147   }
3148   /* dynamic payloads need rtpmap or we fail */
3149   if (rtpmap == NULL && pt >= 96)
3150     goto no_rtpmap;
3151
3152   /* check if we have a rate, if not, we need to look up the rate from the
3153    * default rates based on the payload types. */
3154   if (rate == -1) {
3155     const GstRTPPayloadInfo *info;
3156
3157     if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
3158       /* dynamic types, use media and encoding_name */
3159       tmp = g_ascii_strdown (media->media, -1);
3160       info = gst_rtp_payload_info_for_name (tmp, name);
3161       g_free (tmp);
3162     } else {
3163       /* static types, use payload type */
3164       info = gst_rtp_payload_info_for_pt (pt);
3165     }
3166
3167     if (info) {
3168       if ((rate = info->clock_rate) == 0)
3169         rate = -1;
3170     }
3171     /* we fail if we cannot find one */
3172     if (rate == -1)
3173       goto no_rate;
3174   }
3175
3176   tmp = g_ascii_strdown (media->media, -1);
3177   caps = gst_caps_new_simple ("application/x-unknown",
3178       "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
3179   g_free (tmp);
3180   s = gst_caps_get_structure (caps, 0);
3181
3182   gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
3183
3184   /* encoding name must be upper case */
3185   if (name != NULL) {
3186     tmp = g_ascii_strup (name, -1);
3187     gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
3188     g_free (tmp);
3189   }
3190
3191   /* params must be lower case */
3192   if (params != NULL) {
3193     tmp = g_ascii_strdown (params, -1);
3194     gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
3195     g_free (tmp);
3196   }
3197
3198   /* parse optional fmtp: field */
3199   if ((fmtp = rtsp_get_attribute_for_pt (media, "fmtp", pt))) {
3200     gchar *p;
3201     gint payload = 0;
3202
3203     p = (gchar *) fmtp;
3204
3205     /* p is now of the format <payload> <param>[=<value>];... */
3206     PARSE_INT (p, " ", payload);
3207     if (payload != -1 && payload == pt) {
3208       gchar **pairs;
3209       gint i;
3210
3211       /* <param>[=<value>] are separated with ';' */
3212       pairs = g_strsplit (p, ";", 0);
3213       for (i = 0; pairs[i]; i++) {
3214         gchar *valpos;
3215         const gchar *val, *key;
3216
3217         /* the key may not have a '=', the value can have other '='s */
3218         valpos = strstr (pairs[i], "=");
3219         if (valpos) {
3220           /* we have a '=' and thus a value, remove the '=' with \0 */
3221           *valpos = '\0';
3222           /* value is everything between '=' and ';'. We split the pairs at ;
3223            * boundaries so we can take the remainder of the value. Some servers
3224            * put spaces around the value which we strip off here. Alternatively
3225            * we could strip those spaces in the depayloaders should these spaces
3226            * actually carry any meaning in the future. */
3227           val = g_strstrip (valpos + 1);
3228         } else {
3229           /* simple <param>;.. is translated into <param>=1;... */
3230           val = "1";
3231         }
3232         /* strip the key of spaces, convert key to lowercase but not the value. */
3233         key = g_strstrip (pairs[i]);
3234         if (strlen (key) > 1) {
3235           tmp = g_ascii_strdown (key, -1);
3236           gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
3237           g_free (tmp);
3238         }
3239       }
3240       g_strfreev (pairs);
3241     }
3242   }
3243   return caps;
3244
3245   /* ERRORS */
3246 no_rtpmap:
3247   {
3248     g_warning ("rtpmap type not given for dynamic payload %d", pt);
3249     return NULL;
3250   }
3251 no_rate:
3252   {
3253     g_warning ("rate unknown for payload type %d", pt);
3254     return NULL;
3255   }
3256 }
3257
3258 static gboolean
3259 parse_keymgmt (const gchar * keymgmt, GstCaps * caps)
3260 {
3261   gboolean res = FALSE;
3262   gchar *p, *kmpid;
3263   gsize size;
3264   guchar *data;
3265   GstMIKEYMessage *msg;
3266   const GstMIKEYPayload *payload;
3267   const gchar *srtp_cipher;
3268   const gchar *srtp_auth;
3269
3270   p = (gchar *) keymgmt;
3271
3272   SKIP_SPACES (p);
3273   if (*p == '\0')
3274     return FALSE;
3275
3276   PARSE_STRING (p, " ", kmpid);
3277   if (!g_str_equal (kmpid, "mikey"))
3278     return FALSE;
3279
3280   data = g_base64_decode (p, &size);
3281   if (data == NULL)
3282     return FALSE;
3283
3284   msg = gst_mikey_message_new_from_data (data, size, NULL, NULL);
3285   g_free (data);
3286   if (msg == NULL)
3287     return FALSE;
3288
3289   srtp_cipher = "aes-128-icm";
3290   srtp_auth = "hmac-sha1-80";
3291
3292   /* check the Security policy if any */
3293   if ((payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, 0))) {
3294     GstMIKEYPayloadSP *p = (GstMIKEYPayloadSP *) payload;
3295     guint len, i;
3296
3297     if (p->proto != GST_MIKEY_SEC_PROTO_SRTP)
3298       goto done;
3299
3300     len = gst_mikey_payload_sp_get_n_params (payload);
3301     for (i = 0; i < len; i++) {
3302       const GstMIKEYPayloadSPParam *param =
3303           gst_mikey_payload_sp_get_param (payload, i);
3304
3305       switch (param->type) {
3306         case GST_MIKEY_SP_SRTP_ENC_ALG:
3307           switch (param->val[0]) {
3308             case 0:
3309               srtp_cipher = "null";
3310               break;
3311             case 2:
3312             case 1:
3313               srtp_cipher = "aes-128-icm";
3314               break;
3315             default:
3316               break;
3317           }
3318           break;
3319         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
3320           switch (param->val[0]) {
3321             case AES_128_KEY_LEN:
3322               srtp_cipher = "aes-128-icm";
3323               break;
3324             case AES_256_KEY_LEN:
3325               srtp_cipher = "aes-256-icm";
3326               break;
3327             default:
3328               break;
3329           }
3330           break;
3331         case GST_MIKEY_SP_SRTP_AUTH_ALG:
3332           switch (param->val[0]) {
3333             case 0:
3334               srtp_auth = "null";
3335               break;
3336             case 2:
3337             case 1:
3338               srtp_auth = "hmac-sha1-80";
3339               break;
3340             default:
3341               break;
3342           }
3343           break;
3344         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
3345           switch (param->val[0]) {
3346             case HMAC_32_KEY_LEN:
3347               srtp_auth = "hmac-sha1-32";
3348               break;
3349             case HMAC_80_KEY_LEN:
3350               srtp_auth = "hmac-sha1-80";
3351               break;
3352             default:
3353               break;
3354           }
3355           break;
3356         case GST_MIKEY_SP_SRTP_SRTP_ENC:
3357           break;
3358         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
3359           break;
3360         default:
3361           break;
3362       }
3363     }
3364   }
3365
3366   if (!(payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_KEMAC, 0)))
3367     goto done;
3368   else {
3369     GstMIKEYPayloadKEMAC *p = (GstMIKEYPayloadKEMAC *) payload;
3370     const GstMIKEYPayload *sub;
3371     GstMIKEYPayloadKeyData *pkd;
3372     GstBuffer *buf;
3373
3374     if (p->enc_alg != GST_MIKEY_ENC_NULL || p->mac_alg != GST_MIKEY_MAC_NULL)
3375       goto done;
3376
3377     if (!(sub = gst_mikey_payload_kemac_get_sub (payload, 0)))
3378       goto done;
3379
3380     if (sub->type != GST_MIKEY_PT_KEY_DATA)
3381       goto done;
3382
3383     pkd = (GstMIKEYPayloadKeyData *) sub;
3384     buf =
3385         gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
3386         pkd->key_len);
3387     gst_caps_set_simple (caps, "srtp-key", GST_TYPE_BUFFER, buf, NULL);
3388   }
3389
3390   gst_caps_set_simple (caps,
3391       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
3392       "srtp-auth", G_TYPE_STRING, srtp_auth,
3393       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
3394       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
3395
3396   res = TRUE;
3397 done:
3398   gst_mikey_message_unref (msg);
3399
3400   return res;
3401 }
3402
3403 /*
3404  * Mapping SDP attributes to caps
3405  *
3406  * prepend 'a-' to IANA registered sdp attributes names
3407  * (ie: not prefixed with 'x-') in order to avoid
3408  * collision with gstreamer standard caps properties names
3409  */
3410 static void
3411 sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
3412 {
3413   if (attributes->len > 0) {
3414     GstStructure *s;
3415     guint i;
3416
3417     s = gst_caps_get_structure (caps, 0);
3418
3419     for (i = 0; i < attributes->len; i++) {
3420       GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
3421       gchar *tofree, *key;
3422
3423       key = attr->key;
3424
3425       /* skip some of the attribute we already handle */
3426       if (!strcmp (key, "fmtp"))
3427         continue;
3428       if (!strcmp (key, "rtpmap"))
3429         continue;
3430       if (!strcmp (key, "control"))
3431         continue;
3432       if (!strcmp (key, "range"))
3433         continue;
3434       if (g_str_equal (key, "key-mgmt")) {
3435         parse_keymgmt (attr->value, caps);
3436         continue;
3437       }
3438
3439       /* string must be valid UTF8 */
3440       if (!g_utf8_validate (attr->value, -1, NULL))
3441         continue;
3442
3443       if (!g_str_has_prefix (key, "x-"))
3444         tofree = key = g_strdup_printf ("a-%s", key);
3445       else
3446         tofree = NULL;
3447
3448       GST_DEBUG ("adding caps: %s=%s", key, attr->value);
3449       gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
3450       g_free (tofree);
3451     }
3452   }
3453 }
3454
3455 static gboolean
3456 default_handle_sdp (GstRTSPMedia * media, GstSDPMessage * sdp)
3457 {
3458   GstRTSPMediaPrivate *priv = media->priv;
3459   gint i, medias_len;
3460
3461   medias_len = gst_sdp_message_medias_len (sdp);
3462   if (medias_len != priv->streams->len) {
3463     GST_ERROR ("%p: Media has more or less streams than SDP (%d /= %d)", media,
3464         priv->streams->len, medias_len);
3465     return FALSE;
3466   }
3467
3468   for (i = 0; i < medias_len; i++) {
3469     const gchar *proto, *media_type;
3470     const GstSDPMedia *sdp_media = gst_sdp_message_get_media (sdp, i);
3471     GstRTSPStream *stream;
3472     gint j, formats_len;
3473     const gchar *control;
3474     GstRTSPProfile profile, profiles;
3475
3476     stream = g_ptr_array_index (priv->streams, i);
3477
3478     /* TODO: Should we do something with the other SDP information? */
3479
3480     /* get proto */
3481     proto = gst_sdp_media_get_proto (sdp_media);
3482     if (proto == NULL) {
3483       GST_ERROR ("%p: SDP media %d has no proto", media, i);
3484       return FALSE;
3485     }
3486
3487     if (g_str_equal (proto, "RTP/AVP")) {
3488       media_type = "application/x-rtp";
3489       profile = GST_RTSP_PROFILE_AVP;
3490     } else if (g_str_equal (proto, "RTP/SAVP")) {
3491       media_type = "application/x-srtp";
3492       profile = GST_RTSP_PROFILE_SAVP;
3493     } else if (g_str_equal (proto, "RTP/AVPF")) {
3494       media_type = "application/x-rtp";
3495       profile = GST_RTSP_PROFILE_AVPF;
3496     } else if (g_str_equal (proto, "RTP/SAVPF")) {
3497       media_type = "application/x-srtp";
3498       profile = GST_RTSP_PROFILE_SAVPF;
3499     } else {
3500       GST_ERROR ("%p: unsupported profile '%s' for stream %d", media, proto, i);
3501       return FALSE;
3502     }
3503
3504     profiles = gst_rtsp_stream_get_profiles (stream);
3505     if ((profiles & profile) == 0) {
3506       GST_ERROR ("%p: unsupported profile '%s' for stream %d", media, proto, i);
3507       return FALSE;
3508     }
3509
3510     formats_len = gst_sdp_media_formats_len (sdp_media);
3511     for (j = 0; j < formats_len; j++) {
3512       gint pt;
3513       GstCaps *caps;
3514       GstStructure *s;
3515
3516       pt = atoi (gst_sdp_media_get_format (sdp_media, j));
3517
3518       GST_DEBUG (" looking at %d pt: %d", j, pt);
3519
3520       /* convert caps */
3521       caps = media_to_caps (pt, sdp_media);
3522       if (caps == NULL) {
3523         GST_WARNING (" skipping pt %d without caps", pt);
3524         continue;
3525       }
3526
3527       /* do some tweaks */
3528       GST_DEBUG ("mapping sdp session level attributes to caps");
3529       sdp_attributes_to_caps (sdp->attributes, caps);
3530       GST_DEBUG ("mapping sdp media level attributes to caps");
3531       sdp_attributes_to_caps (sdp_media->attributes, caps);
3532
3533       s = gst_caps_get_structure (caps, 0);
3534       gst_structure_set_name (s, media_type);
3535
3536       gst_rtsp_stream_set_pt_map (stream, pt, caps);
3537       gst_caps_unref (caps);
3538     }
3539
3540     control = gst_sdp_media_get_attribute_val (sdp_media, "control");
3541     if (control)
3542       gst_rtsp_stream_set_control (stream, control);
3543
3544   }
3545
3546   return TRUE;
3547 }
3548
3549 /**
3550  * gst_rtsp_media_handle_sdp:
3551  * @media: a #GstRTSPMedia
3552  * @sdp: (transfer none): a #GstSDPMessage
3553  *
3554  * Configure an SDP on @media for receiving streams
3555  *
3556  * Returns: TRUE on success.
3557  */
3558 gboolean
3559 gst_rtsp_media_handle_sdp (GstRTSPMedia * media, GstSDPMessage * sdp)
3560 {
3561   GstRTSPMediaPrivate *priv;
3562   GstRTSPMediaClass *klass;
3563   gboolean res;
3564
3565   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3566   g_return_val_if_fail (sdp != NULL, FALSE);
3567
3568   priv = media->priv;
3569
3570   g_rec_mutex_lock (&priv->state_lock);
3571
3572   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3573
3574   if (!klass->handle_sdp)
3575     goto no_handle_sdp;
3576
3577   res = klass->handle_sdp (media, sdp);
3578
3579   g_rec_mutex_unlock (&priv->state_lock);
3580
3581   return res;
3582
3583   /* ERRORS */
3584 no_handle_sdp:
3585   {
3586     g_rec_mutex_unlock (&priv->state_lock);
3587     GST_ERROR ("no handle_sdp function");
3588     g_critical ("no handle_sdp vmethod function set");
3589     return FALSE;
3590   }
3591 }
3592
3593 static void
3594 do_set_seqnum (GstRTSPStream * stream)
3595 {
3596   guint16 seq_num;
3597   seq_num = gst_rtsp_stream_get_current_seqnum (stream);
3598   gst_rtsp_stream_set_seqnum_offset (stream, seq_num + 1);
3599 }
3600
3601 /* call with state_lock */
3602 gboolean
3603 default_suspend (GstRTSPMedia * media)
3604 {
3605   GstRTSPMediaPrivate *priv = media->priv;
3606   GstStateChangeReturn ret;
3607
3608   switch (priv->suspend_mode) {
3609     case GST_RTSP_SUSPEND_MODE_NONE:
3610       GST_DEBUG ("media %p no suspend", media);
3611       break;
3612     case GST_RTSP_SUSPEND_MODE_PAUSE:
3613       GST_DEBUG ("media %p suspend to PAUSED", media);
3614       ret = set_target_state (media, GST_STATE_PAUSED, TRUE);
3615       if (ret == GST_STATE_CHANGE_FAILURE)
3616         goto state_failed;
3617       break;
3618     case GST_RTSP_SUSPEND_MODE_RESET:
3619       GST_DEBUG ("media %p suspend to NULL", media);
3620       ret = set_target_state (media, GST_STATE_NULL, TRUE);
3621       if (ret == GST_STATE_CHANGE_FAILURE)
3622         goto state_failed;
3623       /* Because payloader needs to set the sequence number as
3624        * monotonic, we need to preserve the sequence number
3625        * after pause. (otherwise going from pause to play,  which
3626        * is actually from NULL to PLAY will create a new sequence
3627        * number. */
3628       g_ptr_array_foreach (priv->streams, (GFunc) do_set_seqnum, NULL);
3629       break;
3630     default:
3631       break;
3632   }
3633
3634   /* let the streams do the state changes freely, if any */
3635   media_streams_set_blocked (media, FALSE);
3636
3637   return TRUE;
3638
3639   /* ERRORS */
3640 state_failed:
3641   {
3642     GST_WARNING ("failed changing pipeline's state for media %p", media);
3643     return FALSE;
3644   }
3645 }
3646
3647 /**
3648  * gst_rtsp_media_suspend:
3649  * @media: a #GstRTSPMedia
3650  *
3651  * Suspend @media. The state of the pipeline managed by @media is set to
3652  * GST_STATE_NULL but all streams are kept. @media can be prepared again
3653  * with gst_rtsp_media_unsuspend()
3654  *
3655  * @media must be prepared with gst_rtsp_media_prepare();
3656  *
3657  * Returns: %TRUE on success.
3658  */
3659 gboolean
3660 gst_rtsp_media_suspend (GstRTSPMedia * media)
3661 {
3662   GstRTSPMediaPrivate *priv = media->priv;
3663   GstRTSPMediaClass *klass;
3664
3665   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3666
3667   GST_FIXME ("suspend for dynamic pipelines needs fixing");
3668
3669   g_rec_mutex_lock (&priv->state_lock);
3670   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED)
3671     goto not_prepared;
3672
3673   /* don't attempt to suspend when something is busy */
3674   if (priv->n_active > 0)
3675     goto done;
3676
3677   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3678   if (klass->suspend) {
3679     if (!klass->suspend (media))
3680       goto suspend_failed;
3681   }
3682
3683   gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_SUSPENDED);
3684 done:
3685   g_rec_mutex_unlock (&priv->state_lock);
3686
3687   return TRUE;
3688
3689   /* ERRORS */
3690 not_prepared:
3691   {
3692     g_rec_mutex_unlock (&priv->state_lock);
3693     GST_WARNING ("media %p was not prepared", media);
3694     return FALSE;
3695   }
3696 suspend_failed:
3697   {
3698     g_rec_mutex_unlock (&priv->state_lock);
3699     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
3700     GST_WARNING ("failed to suspend media %p", media);
3701     return FALSE;
3702   }
3703 }
3704
3705 /* call with state_lock */
3706 gboolean
3707 default_unsuspend (GstRTSPMedia * media)
3708 {
3709   GstRTSPMediaPrivate *priv = media->priv;
3710
3711   switch (priv->suspend_mode) {
3712     case GST_RTSP_SUSPEND_MODE_NONE:
3713       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
3714       break;
3715     case GST_RTSP_SUSPEND_MODE_PAUSE:
3716       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
3717       break;
3718     case GST_RTSP_SUSPEND_MODE_RESET:
3719     {
3720       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARING);
3721       if (!start_preroll (media))
3722         goto start_failed;
3723       g_rec_mutex_unlock (&priv->state_lock);
3724
3725       if (!wait_preroll (media))
3726         goto preroll_failed;
3727
3728       g_rec_mutex_lock (&priv->state_lock);
3729     }
3730     default:
3731       break;
3732   }
3733
3734   return TRUE;
3735
3736   /* ERRORS */
3737 start_failed:
3738   {
3739     GST_WARNING ("failed to preroll pipeline");
3740     return FALSE;
3741   }
3742 preroll_failed:
3743   {
3744     GST_WARNING ("failed to preroll pipeline");
3745     return FALSE;
3746   }
3747 }
3748
3749 /**
3750  * gst_rtsp_media_unsuspend:
3751  * @media: a #GstRTSPMedia
3752  *
3753  * Unsuspend @media if it was in a suspended state. This method does nothing
3754  * when the media was not in the suspended state.
3755  *
3756  * Returns: %TRUE on success.
3757  */
3758 gboolean
3759 gst_rtsp_media_unsuspend (GstRTSPMedia * media)
3760 {
3761   GstRTSPMediaPrivate *priv = media->priv;
3762   GstRTSPMediaClass *klass;
3763
3764   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3765
3766   g_rec_mutex_lock (&priv->state_lock);
3767   if (priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
3768     goto done;
3769
3770   klass = GST_RTSP_MEDIA_GET_CLASS (media);
3771   if (klass->unsuspend) {
3772     if (!klass->unsuspend (media))
3773       goto unsuspend_failed;
3774   }
3775
3776 done:
3777   g_rec_mutex_unlock (&priv->state_lock);
3778
3779   return TRUE;
3780
3781   /* ERRORS */
3782 unsuspend_failed:
3783   {
3784     g_rec_mutex_unlock (&priv->state_lock);
3785     GST_WARNING ("failed to unsuspend media %p", media);
3786     gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
3787     return FALSE;
3788   }
3789 }
3790
3791 /* must be called with state-lock */
3792 static void
3793 media_set_pipeline_state_locked (GstRTSPMedia * media, GstState state)
3794 {
3795   GstRTSPMediaPrivate *priv = media->priv;
3796
3797   if (state == GST_STATE_NULL) {
3798     gst_rtsp_media_unprepare (media);
3799   } else {
3800     GST_INFO ("state %s media %p", gst_element_state_get_name (state), media);
3801     set_target_state (media, state, FALSE);
3802     /* when we are buffering, don't update the state yet, this will be done
3803      * when buffering finishes */
3804     if (priv->buffering) {
3805       GST_INFO ("Buffering busy, delay state change");
3806     } else {
3807       if (state == GST_STATE_PLAYING)
3808         /* make sure pads are not blocking anymore when going to PLAYING */
3809         media_streams_set_blocked (media, FALSE);
3810
3811       set_state (media, state);
3812
3813       /* and suspend after pause */
3814       if (state == GST_STATE_PAUSED)
3815         gst_rtsp_media_suspend (media);
3816     }
3817   }
3818 }
3819
3820 /**
3821  * gst_rtsp_media_set_pipeline_state:
3822  * @media: a #GstRTSPMedia
3823  * @state: the target state of the pipeline
3824  *
3825  * Set the state of the pipeline managed by @media to @state
3826  */
3827 void
3828 gst_rtsp_media_set_pipeline_state (GstRTSPMedia * media, GstState state)
3829 {
3830   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
3831
3832   g_rec_mutex_lock (&media->priv->state_lock);
3833   media_set_pipeline_state_locked (media, state);
3834   g_rec_mutex_unlock (&media->priv->state_lock);
3835 }
3836
3837 /**
3838  * gst_rtsp_media_set_state:
3839  * @media: a #GstRTSPMedia
3840  * @state: the target state of the media
3841  * @transports: (transfer none) (element-type GstRtspServer.RTSPStreamTransport):
3842  * a #GPtrArray of #GstRTSPStreamTransport pointers
3843  *
3844  * Set the state of @media to @state and for the transports in @transports.
3845  *
3846  * @media must be prepared with gst_rtsp_media_prepare();
3847  *
3848  * Returns: %TRUE on success.
3849  */
3850 gboolean
3851 gst_rtsp_media_set_state (GstRTSPMedia * media, GstState state,
3852     GPtrArray * transports)
3853 {
3854   GstRTSPMediaPrivate *priv;
3855   gint i;
3856   gboolean activate, deactivate, do_state;
3857   gint old_active;
3858
3859   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
3860   g_return_val_if_fail (transports != NULL, FALSE);
3861
3862   priv = media->priv;
3863
3864   g_rec_mutex_lock (&priv->state_lock);
3865   if (priv->status == GST_RTSP_MEDIA_STATUS_ERROR)
3866     goto error_status;
3867   if (priv->status != GST_RTSP_MEDIA_STATUS_PREPARED &&
3868       priv->status != GST_RTSP_MEDIA_STATUS_SUSPENDED)
3869     goto not_prepared;
3870
3871   /* NULL and READY are the same */
3872   if (state == GST_STATE_READY)
3873     state = GST_STATE_NULL;
3874
3875   activate = deactivate = FALSE;
3876
3877   GST_INFO ("going to state %s media %p, target state %s",
3878       gst_element_state_get_name (state), media,
3879       gst_element_state_get_name (priv->target_state));
3880
3881   switch (state) {
3882     case GST_STATE_NULL:
3883       /* we're going from PLAYING or PAUSED to READY or NULL, deactivate */
3884       if (priv->target_state >= GST_STATE_PAUSED)
3885         deactivate = TRUE;
3886       break;
3887     case GST_STATE_PAUSED:
3888       /* we're going from PLAYING to PAUSED, READY or NULL, deactivate */
3889       if (priv->target_state == GST_STATE_PLAYING)
3890         deactivate = TRUE;
3891       break;
3892     case GST_STATE_PLAYING:
3893       /* we're going to PLAYING, activate */
3894       activate = TRUE;
3895       break;
3896     default:
3897       break;
3898   }
3899   old_active = priv->n_active;
3900
3901   GST_DEBUG ("%d transports, activate %d, deactivate %d", transports->len,
3902       activate, deactivate);
3903   for (i = 0; i < transports->len; i++) {
3904     GstRTSPStreamTransport *trans;
3905
3906     /* we need a non-NULL entry in the array */
3907     trans = g_ptr_array_index (transports, i);
3908     if (trans == NULL)
3909       continue;
3910
3911     if (activate) {
3912       if (gst_rtsp_stream_transport_set_active (trans, TRUE))
3913         priv->n_active++;
3914     } else if (deactivate) {
3915       if (gst_rtsp_stream_transport_set_active (trans, FALSE))
3916         priv->n_active--;
3917     }
3918   }
3919
3920   /* we just activated the first media, do the playing state change */
3921   if (old_active == 0 && activate)
3922     do_state = TRUE;
3923   /* if we have no more active media, do the downward state changes */
3924   else if (priv->n_active == 0)
3925     do_state = TRUE;
3926   else
3927     do_state = FALSE;
3928
3929   GST_INFO ("state %d active %d media %p do_state %d", state, priv->n_active,
3930       media, do_state);
3931
3932   if (priv->target_state != state) {
3933     if (do_state)
3934       media_set_pipeline_state_locked (media, state);
3935
3936     g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STATE], 0, state,
3937         NULL);
3938   }
3939
3940   /* remember where we are */
3941   if (state != GST_STATE_NULL && (state == GST_STATE_PAUSED ||
3942           old_active != priv->n_active))
3943     collect_media_stats (media);
3944
3945   g_rec_mutex_unlock (&priv->state_lock);
3946
3947   return TRUE;
3948
3949   /* ERRORS */
3950 not_prepared:
3951   {
3952     GST_WARNING ("media %p was not prepared", media);
3953     g_rec_mutex_unlock (&priv->state_lock);
3954     return FALSE;
3955   }
3956 error_status:
3957   {
3958     GST_WARNING ("media %p in error status while changing to state %d",
3959         media, state);
3960     if (state == GST_STATE_NULL) {
3961       for (i = 0; i < transports->len; i++) {
3962         GstRTSPStreamTransport *trans;
3963
3964         /* we need a non-NULL entry in the array */
3965         trans = g_ptr_array_index (transports, i);
3966         if (trans == NULL)
3967           continue;
3968
3969         gst_rtsp_stream_transport_set_active (trans, FALSE);
3970       }
3971       priv->n_active = 0;
3972     }
3973     g_rec_mutex_unlock (&priv->state_lock);
3974     return FALSE;
3975   }
3976 }
3977
3978 /**
3979  * gst_rtsp_media_set_transport_mode:
3980  * @media: a #GstRTSPMedia
3981  * @mode: the new value
3982  *
3983  * Sets if the media pipeline can work in PLAY or RECORD mode
3984  */
3985 void
3986 gst_rtsp_media_set_transport_mode (GstRTSPMedia * media,
3987     GstRTSPTransportMode mode)
3988 {
3989   GstRTSPMediaPrivate *priv;
3990
3991   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
3992
3993   priv = media->priv;
3994
3995   g_mutex_lock (&priv->lock);
3996   priv->transport_mode = mode;
3997   g_mutex_unlock (&priv->lock);
3998 }
3999
4000 /**
4001  * gst_rtsp_media_get_transport_mode:
4002  * @media: a #GstRTSPMedia
4003  *
4004  * Check if the pipeline for @media can be used for PLAY or RECORD methods.
4005  *
4006  * Returns: The transport mode.
4007  */
4008 GstRTSPTransportMode
4009 gst_rtsp_media_get_transport_mode (GstRTSPMedia * media)
4010 {
4011   GstRTSPMediaPrivate *priv;
4012   GstRTSPTransportMode res;
4013
4014   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
4015
4016   priv = media->priv;
4017
4018   g_mutex_lock (&priv->lock);
4019   res = priv->transport_mode;
4020   g_mutex_unlock (&priv->lock);
4021
4022   return res;
4023 }