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