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