dfd89bc8720c06fffead073a296b36c6b28ed6a8
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-media.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include <string.h>
21 #include <stdlib.h>
22
23 #include <gst/app/gstappsrc.h>
24 #include <gst/app/gstappsink.h>
25
26 #include "rtsp-media.h"
27
28 #define DEFAULT_SHARED          FALSE
29 #define DEFAULT_REUSABLE        FALSE
30 #define DEFAULT_PROTOCOLS       GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_TCP
31 //#define DEFAULT_PROTOCOLS      GST_RTSP_LOWER_TRANS_UDP_MCAST
32 #define DEFAULT_EOS_SHUTDOWN    FALSE
33 #define DEFAULT_BUFFER_SIZE     0x80000
34
35 /* define to dump received RTCP packets */
36 #undef DUMP_STATS
37
38 enum
39 {
40   PROP_0,
41   PROP_SHARED,
42   PROP_REUSABLE,
43   PROP_PROTOCOLS,
44   PROP_EOS_SHUTDOWN,
45   PROP_BUFFER_SIZE,
46   PROP_LAST
47 };
48
49 enum
50 {
51   SIGNAL_NEW_STREAM,
52   SIGNAL_PREPARED,
53   SIGNAL_UNPREPARED,
54   SIGNAL_NEW_STATE,
55   SIGNAL_LAST
56 };
57
58 GST_DEBUG_CATEGORY_STATIC (rtsp_media_debug);
59 #define GST_CAT_DEFAULT rtsp_media_debug
60
61 static void gst_rtsp_media_get_property (GObject * object, guint propid,
62     GValue * value, GParamSpec * pspec);
63 static void gst_rtsp_media_set_property (GObject * object, guint propid,
64     const GValue * value, GParamSpec * pspec);
65 static void gst_rtsp_media_finalize (GObject * obj);
66
67 static gpointer do_loop (GstRTSPMediaClass * klass);
68 static gboolean default_handle_message (GstRTSPMedia * media,
69     GstMessage * message);
70 static void finish_unprepare (GstRTSPMedia * media);
71 static gboolean default_unprepare (GstRTSPMedia * media);
72
73 static guint gst_rtsp_media_signals[SIGNAL_LAST] = { 0 };
74
75 G_DEFINE_TYPE (GstRTSPMedia, gst_rtsp_media, G_TYPE_OBJECT);
76
77 static void
78 gst_rtsp_media_class_init (GstRTSPMediaClass * klass)
79 {
80   GObjectClass *gobject_class;
81
82   gobject_class = G_OBJECT_CLASS (klass);
83
84   gobject_class->get_property = gst_rtsp_media_get_property;
85   gobject_class->set_property = gst_rtsp_media_set_property;
86   gobject_class->finalize = gst_rtsp_media_finalize;
87
88   g_object_class_install_property (gobject_class, PROP_SHARED,
89       g_param_spec_boolean ("shared", "Shared",
90           "If this media pipeline can be shared", DEFAULT_SHARED,
91           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
92
93   g_object_class_install_property (gobject_class, PROP_REUSABLE,
94       g_param_spec_boolean ("reusable", "Reusable",
95           "If this media pipeline can be reused after an unprepare",
96           DEFAULT_REUSABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
97
98   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
99       g_param_spec_flags ("protocols", "Protocols",
100           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
101           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
102
103   g_object_class_install_property (gobject_class, PROP_EOS_SHUTDOWN,
104       g_param_spec_boolean ("eos-shutdown", "EOS Shutdown",
105           "Send an EOS event to the pipeline before unpreparing",
106           DEFAULT_EOS_SHUTDOWN, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
107
108   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
109       g_param_spec_uint ("buffer-size", "Buffer Size",
110           "The kernel UDP buffer size to use", 0, G_MAXUINT,
111           DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
112
113   gst_rtsp_media_signals[SIGNAL_NEW_STREAM] =
114       g_signal_new ("new-stream", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
115       G_STRUCT_OFFSET (GstRTSPMediaClass, new_stream), NULL, NULL,
116       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_RTSP_STREAM);
117
118   gst_rtsp_media_signals[SIGNAL_PREPARED] =
119       g_signal_new ("prepared", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
120       G_STRUCT_OFFSET (GstRTSPMediaClass, prepared), NULL, NULL,
121       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
122
123   gst_rtsp_media_signals[SIGNAL_UNPREPARED] =
124       g_signal_new ("unprepared", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
125       G_STRUCT_OFFSET (GstRTSPMediaClass, unprepared), NULL, NULL,
126       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
127
128   gst_rtsp_media_signals[SIGNAL_NEW_STATE] =
129       g_signal_new ("new-state", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
130       G_STRUCT_OFFSET (GstRTSPMediaClass, new_state), NULL, NULL,
131       g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 0, G_TYPE_INT);
132
133   klass->context = g_main_context_new ();
134   klass->loop = g_main_loop_new (klass->context, TRUE);
135
136   GST_DEBUG_CATEGORY_INIT (rtsp_media_debug, "rtspmedia", 0, "GstRTSPMedia");
137
138   klass->thread = g_thread_new ("Bus Thread", (GThreadFunc) do_loop, klass);
139
140   klass->handle_message = default_handle_message;
141   klass->unprepare = default_unprepare;
142 }
143
144 static void
145 gst_rtsp_media_init (GstRTSPMedia * media)
146 {
147   media->streams = g_ptr_array_new_with_free_func (g_object_unref);
148   g_mutex_init (&media->lock);
149   g_cond_init (&media->cond);
150   g_rec_mutex_init (&media->state_lock);
151
152   media->shared = DEFAULT_SHARED;
153   media->reusable = DEFAULT_REUSABLE;
154   media->protocols = DEFAULT_PROTOCOLS;
155   media->eos_shutdown = DEFAULT_EOS_SHUTDOWN;
156   media->buffer_size = DEFAULT_BUFFER_SIZE;
157 }
158
159 static void
160 gst_rtsp_media_finalize (GObject * obj)
161 {
162   GstRTSPMedia *media;
163
164   media = GST_RTSP_MEDIA (obj);
165
166   GST_INFO ("finalize media %p", media);
167
168   gst_rtsp_media_unprepare (media);
169
170   g_ptr_array_unref (media->streams);
171
172   g_list_free_full (media->dynamic, gst_object_unref);
173
174   if (media->source) {
175     g_source_destroy (media->source);
176     g_source_unref (media->source);
177   }
178   if (media->auth)
179     g_object_unref (media->auth);
180   if (media->pool)
181     g_object_unref (media->pool);
182   g_mutex_clear (&media->lock);
183   g_cond_clear (&media->cond);
184   g_rec_mutex_clear (&media->state_lock);
185
186   G_OBJECT_CLASS (gst_rtsp_media_parent_class)->finalize (obj);
187 }
188
189 static void
190 gst_rtsp_media_get_property (GObject * object, guint propid,
191     GValue * value, GParamSpec * pspec)
192 {
193   GstRTSPMedia *media = GST_RTSP_MEDIA (object);
194
195   switch (propid) {
196     case PROP_SHARED:
197       g_value_set_boolean (value, gst_rtsp_media_is_shared (media));
198       break;
199     case PROP_REUSABLE:
200       g_value_set_boolean (value, gst_rtsp_media_is_reusable (media));
201       break;
202     case PROP_PROTOCOLS:
203       g_value_set_flags (value, gst_rtsp_media_get_protocols (media));
204       break;
205     case PROP_EOS_SHUTDOWN:
206       g_value_set_boolean (value, gst_rtsp_media_is_eos_shutdown (media));
207       break;
208     case PROP_BUFFER_SIZE:
209       g_value_set_uint (value, gst_rtsp_media_get_buffer_size (media));
210       break;
211     default:
212       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
213   }
214 }
215
216 static void
217 gst_rtsp_media_set_property (GObject * object, guint propid,
218     const GValue * value, GParamSpec * pspec)
219 {
220   GstRTSPMedia *media = GST_RTSP_MEDIA (object);
221
222   switch (propid) {
223     case PROP_SHARED:
224       gst_rtsp_media_set_shared (media, g_value_get_boolean (value));
225       break;
226     case PROP_REUSABLE:
227       gst_rtsp_media_set_reusable (media, g_value_get_boolean (value));
228       break;
229     case PROP_PROTOCOLS:
230       gst_rtsp_media_set_protocols (media, g_value_get_flags (value));
231       break;
232     case PROP_EOS_SHUTDOWN:
233       gst_rtsp_media_set_eos_shutdown (media, g_value_get_boolean (value));
234       break;
235     case PROP_BUFFER_SIZE:
236       gst_rtsp_media_set_buffer_size (media, g_value_get_uint (value));
237       break;
238     default:
239       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
240   }
241 }
242
243 static gpointer
244 do_loop (GstRTSPMediaClass * klass)
245 {
246   GST_INFO ("enter mainloop");
247   g_main_loop_run (klass->loop);
248   GST_INFO ("exit mainloop");
249
250   return NULL;
251 }
252
253 /* must be called with state lock */
254 static void
255 collect_media_stats (GstRTSPMedia * media)
256 {
257   gint64 position, duration;
258
259   media->range.unit = GST_RTSP_RANGE_NPT;
260
261   GST_INFO ("collect media stats");
262
263   if (media->is_live) {
264     media->range.min.type = GST_RTSP_TIME_NOW;
265     media->range.min.seconds = -1;
266     media->range.max.type = GST_RTSP_TIME_END;
267     media->range.max.seconds = -1;
268   } else {
269     /* get the position */
270     if (!gst_element_query_position (media->pipeline, GST_FORMAT_TIME,
271             &position)) {
272       GST_INFO ("position query failed");
273       position = 0;
274     }
275
276     /* get the duration */
277     if (!gst_element_query_duration (media->pipeline, GST_FORMAT_TIME,
278             &duration)) {
279       GST_INFO ("duration query failed");
280       duration = -1;
281     }
282
283     GST_INFO ("stats: position %" GST_TIME_FORMAT ", duration %"
284         GST_TIME_FORMAT, GST_TIME_ARGS (position), GST_TIME_ARGS (duration));
285
286     if (position == -1) {
287       media->range.min.type = GST_RTSP_TIME_NOW;
288       media->range.min.seconds = -1;
289     } else {
290       media->range.min.type = GST_RTSP_TIME_SECONDS;
291       media->range.min.seconds = ((gdouble) position) / GST_SECOND;
292     }
293     if (duration == -1) {
294       media->range.max.type = GST_RTSP_TIME_END;
295       media->range.max.seconds = -1;
296     } else {
297       media->range.max.type = GST_RTSP_TIME_SECONDS;
298       media->range.max.seconds = ((gdouble) duration) / GST_SECOND;
299     }
300   }
301 }
302
303 /**
304  * gst_rtsp_media_new:
305  *
306  * Create a new #GstRTSPMedia instance. The #GstRTSPMedia object contains the
307  * element to produce RTP data for one or more related (audio/video/..)
308  * streams.
309  *
310  * Returns: a new #GstRTSPMedia object.
311  */
312 GstRTSPMedia *
313 gst_rtsp_media_new (void)
314 {
315   GstRTSPMedia *result;
316
317   result = g_object_new (GST_TYPE_RTSP_MEDIA, NULL);
318
319   return result;
320 }
321
322 /**
323  * gst_rtsp_media_set_shared:
324  * @media: a #GstRTSPMedia
325  * @shared: the new value
326  *
327  * Set or unset if the pipeline for @media can be shared will multiple clients.
328  * When @shared is %TRUE, client requests for this media will share the media
329  * pipeline.
330  */
331 void
332 gst_rtsp_media_set_shared (GstRTSPMedia * media, gboolean shared)
333 {
334   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
335
336   g_mutex_lock (&media->lock);
337   media->shared = shared;
338   g_mutex_unlock (&media->lock);
339 }
340
341 /**
342  * gst_rtsp_media_is_shared:
343  * @media: a #GstRTSPMedia
344  *
345  * Check if the pipeline for @media can be shared between multiple clients.
346  *
347  * Returns: %TRUE if the media can be shared between clients.
348  */
349 gboolean
350 gst_rtsp_media_is_shared (GstRTSPMedia * media)
351 {
352   gboolean res;
353
354   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
355
356   g_mutex_lock (&media->lock);
357   res = media->shared;
358   g_mutex_unlock (&media->lock);
359
360   return res;
361 }
362
363 /**
364  * gst_rtsp_media_set_reusable:
365  * @media: a #GstRTSPMedia
366  * @reusable: the new value
367  *
368  * Set or unset if the pipeline for @media can be reused after the pipeline has
369  * been unprepared.
370  */
371 void
372 gst_rtsp_media_set_reusable (GstRTSPMedia * media, gboolean reusable)
373 {
374   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
375
376   g_mutex_lock (&media->lock);
377   media->reusable = reusable;
378   g_mutex_unlock (&media->lock);
379 }
380
381 /**
382  * gst_rtsp_media_is_reusable:
383  * @media: a #GstRTSPMedia
384  *
385  * Check if the pipeline for @media can be reused after an unprepare.
386  *
387  * Returns: %TRUE if the media can be reused
388  */
389 gboolean
390 gst_rtsp_media_is_reusable (GstRTSPMedia * media)
391 {
392   gboolean res;
393
394   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
395
396   g_mutex_lock (&media->lock);
397   res = media->reusable;
398   g_mutex_unlock (&media->lock);
399
400   return res;
401 }
402
403 /**
404  * gst_rtsp_media_set_protocols:
405  * @media: a #GstRTSPMedia
406  * @protocols: the new flags
407  *
408  * Configure the allowed lower transport for @media.
409  */
410 void
411 gst_rtsp_media_set_protocols (GstRTSPMedia * media, GstRTSPLowerTrans protocols)
412 {
413   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
414
415   g_mutex_lock (&media->lock);
416   media->protocols = protocols;
417   g_mutex_unlock (&media->lock);
418 }
419
420 /**
421  * gst_rtsp_media_get_protocols:
422  * @media: a #GstRTSPMedia
423  *
424  * Get the allowed protocols of @media.
425  *
426  * Returns: a #GstRTSPLowerTrans
427  */
428 GstRTSPLowerTrans
429 gst_rtsp_media_get_protocols (GstRTSPMedia * media)
430 {
431   GstRTSPLowerTrans res;
432
433   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media),
434       GST_RTSP_LOWER_TRANS_UNKNOWN);
435
436   g_mutex_lock (&media->lock);
437   res = media->protocols;
438   g_mutex_unlock (&media->lock);
439
440   return res;
441 }
442
443 /**
444  * gst_rtsp_media_set_eos_shutdown:
445  * @media: a #GstRTSPMedia
446  * @eos_shutdown: the new value
447  *
448  * Set or unset if an EOS event will be sent to the pipeline for @media before
449  * it is unprepared.
450  */
451 void
452 gst_rtsp_media_set_eos_shutdown (GstRTSPMedia * media, gboolean eos_shutdown)
453 {
454   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
455
456   g_mutex_lock (&media->lock);
457   media->eos_shutdown = eos_shutdown;
458   g_mutex_unlock (&media->lock);
459 }
460
461 /**
462  * gst_rtsp_media_is_eos_shutdown:
463  * @media: a #GstRTSPMedia
464  *
465  * Check if the pipeline for @media will send an EOS down the pipeline before
466  * unpreparing.
467  *
468  * Returns: %TRUE if the media will send EOS before unpreparing.
469  */
470 gboolean
471 gst_rtsp_media_is_eos_shutdown (GstRTSPMedia * media)
472 {
473   gboolean res;
474
475   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
476
477   g_mutex_lock (&media->lock);
478   res = media->eos_shutdown;
479   g_mutex_unlock (&media->lock);
480
481   return res;
482 }
483
484 /**
485  * gst_rtsp_media_set_buffer_size:
486  * @media: a #GstRTSPMedia
487  * @size: the new value
488  *
489  * Set the kernel UDP buffer size.
490  */
491 void
492 gst_rtsp_media_set_buffer_size (GstRTSPMedia * media, guint size)
493 {
494   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
495
496   GST_LOG_OBJECT (media, "set buffer size %u", size);
497
498   g_mutex_lock (&media->lock);
499   media->buffer_size = size;
500   g_mutex_unlock (&media->lock);
501 }
502
503 /**
504  * gst_rtsp_media_get_buffer_size:
505  * @media: a #GstRTSPMedia
506  *
507  * Get the kernel UDP buffer size.
508  *
509  * Returns: the kernel UDP buffer size.
510  */
511 guint
512 gst_rtsp_media_get_buffer_size (GstRTSPMedia * media)
513 {
514   guint res;
515
516   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
517
518   g_mutex_unlock (&media->lock);
519   res = media->buffer_size;
520   g_mutex_unlock (&media->lock);
521
522   return res;
523 }
524
525 /**
526  * gst_rtsp_media_set_auth:
527  * @media: a #GstRTSPMedia
528  * @auth: a #GstRTSPAuth
529  *
530  * configure @auth to be used as the authentication manager of @media.
531  */
532 void
533 gst_rtsp_media_set_auth (GstRTSPMedia * media, GstRTSPAuth * auth)
534 {
535   GstRTSPAuth *old;
536
537   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
538
539   GST_LOG_OBJECT (media, "set auth %p", auth);
540
541   g_mutex_lock (&media->lock);
542   if ((old = media->auth) != auth)
543     media->auth = auth ? g_object_ref (auth) : NULL;
544   else
545     old = NULL;
546   g_mutex_unlock (&media->lock);
547
548   if (old)
549     g_object_unref (old);
550 }
551
552 /**
553  * gst_rtsp_media_get_auth:
554  * @media: a #GstRTSPMedia
555  *
556  * Get the #GstRTSPAuth used as the authentication manager of @media.
557  *
558  * Returns: (transfer full): the #GstRTSPAuth of @media. g_object_unref() after
559  * usage.
560  */
561 GstRTSPAuth *
562 gst_rtsp_media_get_auth (GstRTSPMedia * media)
563 {
564   GstRTSPAuth *result;
565
566   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
567
568   g_mutex_lock (&media->lock);
569   if ((result = media->auth))
570     g_object_ref (result);
571   g_mutex_unlock (&media->lock);
572
573   return result;
574 }
575
576 /**
577  * gst_rtsp_media_set_address_pool:
578  * @media: a #GstRTSPMedia
579  * @pool: a #GstRTSPAddressPool
580  *
581  * configure @pool to be used as the address pool of @media.
582  */
583 void
584 gst_rtsp_media_set_address_pool (GstRTSPMedia * media,
585     GstRTSPAddressPool * pool)
586 {
587   GstRTSPAddressPool *old;
588
589   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
590
591   GST_LOG_OBJECT (media, "set address pool %p", pool);
592
593   g_mutex_lock (&media->lock);
594   if ((old = media->pool) != pool)
595     media->pool = pool ? g_object_ref (pool) : NULL;
596   else
597     old = NULL;
598   g_ptr_array_foreach (media->streams, (GFunc) gst_rtsp_stream_set_address_pool,
599       pool);
600   g_mutex_unlock (&media->lock);
601
602   if (old)
603     g_object_unref (old);
604 }
605
606 /**
607  * gst_rtsp_media_get_address_pool:
608  * @media: a #GstRTSPMedia
609  *
610  * Get the #GstRTSPAddressPool used as the address pool of @media.
611  *
612  * Returns: (transfer full): the #GstRTSPAddressPool of @media. g_object_unref() after
613  * usage.
614  */
615 GstRTSPAddressPool *
616 gst_rtsp_media_get_address_pool (GstRTSPMedia * media)
617 {
618   GstRTSPAddressPool *result;
619
620   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
621
622   g_mutex_lock (&media->lock);
623   if ((result = media->pool))
624     g_object_ref (result);
625   g_mutex_unlock (&media->lock);
626
627   return result;
628 }
629
630 /**
631  * gst_rtsp_media_collect_streams:
632  * @media: a #GstRTSPMedia
633  *
634  * Find all payloader elements, they should be named pay%d in the
635  * element of @media, and create #GstRTSPStreams for them.
636  *
637  * Collect all dynamic elements, named dynpay%d, and add them to
638  * the list of dynamic elements.
639  */
640 void
641 gst_rtsp_media_collect_streams (GstRTSPMedia * media)
642 {
643   GstElement *element, *elem;
644   GstPad *pad;
645   gint i;
646   gboolean have_elem;
647
648   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
649
650   element = media->element;
651
652   have_elem = TRUE;
653   for (i = 0; have_elem; i++) {
654     gchar *name;
655
656     have_elem = FALSE;
657
658     name = g_strdup_printf ("pay%d", i);
659     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
660       GST_INFO ("found stream %d with payloader %p", i, elem);
661
662       /* take the pad of the payloader */
663       pad = gst_element_get_static_pad (elem, "src");
664       /* create the stream */
665       gst_rtsp_media_create_stream (media, elem, pad);
666       g_object_unref (pad);
667
668       gst_object_unref (elem);
669
670       have_elem = TRUE;
671     }
672     g_free (name);
673
674     name = g_strdup_printf ("dynpay%d", i);
675     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
676       /* a stream that will dynamically create pads to provide RTP packets */
677
678       GST_INFO ("found dynamic element %d, %p", i, elem);
679
680       g_mutex_lock (&media->lock);
681       media->dynamic = g_list_prepend (media->dynamic, elem);
682       g_mutex_unlock (&media->lock);
683
684       have_elem = TRUE;
685     }
686     g_free (name);
687   }
688 }
689
690 /**
691  * gst_rtsp_media_create_stream:
692  * @media: a #GstRTSPMedia
693  * @payloader: a #GstElement
694  * @srcpad: a source #GstPad
695  *
696  * Create a new stream in @media that provides RTP data on @srcpad.
697  * @srcpad should be a pad of an element inside @media->element.
698  *
699  * Returns: (transfer none): a new #GstRTSPStream that remains valid for as long
700  *          as @media exists.
701  */
702 GstRTSPStream *
703 gst_rtsp_media_create_stream (GstRTSPMedia * media, GstElement * payloader,
704     GstPad * pad)
705 {
706   GstRTSPStream *stream;
707   GstPad *srcpad;
708   gchar *name;
709   gint idx;
710
711   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
712   g_return_val_if_fail (GST_IS_ELEMENT (payloader), NULL);
713   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
714   g_return_val_if_fail (GST_PAD_IS_SRC (pad), NULL);
715
716   g_mutex_lock (&media->lock);
717   idx = media->streams->len;
718
719   name = g_strdup_printf ("src_%u", idx);
720   srcpad = gst_ghost_pad_new (name, pad);
721   gst_pad_set_active (srcpad, TRUE);
722   gst_element_add_pad (media->element, srcpad);
723   g_free (name);
724
725   stream = gst_rtsp_stream_new (idx, payloader, srcpad);
726   if (media->pool)
727     gst_rtsp_stream_set_address_pool (stream, media->pool);
728
729   g_ptr_array_add (media->streams, stream);
730   g_mutex_unlock (&media->lock);
731
732   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STREAM], 0, stream,
733       NULL);
734
735   return stream;
736 }
737
738 /**
739  * gst_rtsp_media_n_streams:
740  * @media: a #GstRTSPMedia
741  *
742  * Get the number of streams in this media.
743  *
744  * Returns: The number of streams.
745  */
746 guint
747 gst_rtsp_media_n_streams (GstRTSPMedia * media)
748 {
749   guint res;
750
751   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), 0);
752
753   g_mutex_lock (&media->lock);
754   res = media->streams->len;
755   g_mutex_unlock (&media->lock);
756
757   return res;
758 }
759
760 /**
761  * gst_rtsp_media_get_stream:
762  * @media: a #GstRTSPMedia
763  * @idx: the stream index
764  *
765  * Retrieve the stream with index @idx from @media.
766  *
767  * Returns: (transfer none): the #GstRTSPStream at index @idx or %NULL when a stream with
768  * that index did not exist.
769  */
770 GstRTSPStream *
771 gst_rtsp_media_get_stream (GstRTSPMedia * media, guint idx)
772 {
773   GstRTSPStream *res;
774
775   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
776
777   g_mutex_lock (&media->lock);
778   if (idx < media->streams->len)
779     res = g_ptr_array_index (media->streams, idx);
780   else
781     res = NULL;
782   g_mutex_unlock (&media->lock);
783
784   return res;
785 }
786
787 /**
788  * gst_rtsp_media_get_range_string:
789  * @media: a #GstRTSPMedia
790  * @play: for the PLAY request
791  *
792  * Get the current range as a string.
793  *
794  * Returns: The range as a string, g_free() after usage.
795  */
796 gchar *
797 gst_rtsp_media_get_range_string (GstRTSPMedia * media, gboolean play)
798 {
799   gchar *result;
800   GstRTSPTimeRange range;
801
802   g_mutex_lock (&media->lock);
803   /* make copy */
804   range = media->range;
805
806   if (!play && media->n_active > 0) {
807     range.min.type = GST_RTSP_TIME_NOW;
808     range.min.seconds = -1;
809   }
810   g_mutex_unlock (&media->lock);
811
812   result = gst_rtsp_range_to_string (&range);
813
814   return result;
815 }
816
817 /**
818  * gst_rtsp_media_seek:
819  * @media: a #GstRTSPMedia
820  * @range: a #GstRTSPTimeRange
821  *
822  * Seek the pipeline to @range.
823  *
824  * Returns: %TRUE on success.
825  */
826 gboolean
827 gst_rtsp_media_seek (GstRTSPMedia * media, GstRTSPTimeRange * range)
828 {
829   GstSeekFlags flags;
830   gboolean res;
831   gint64 start, stop;
832   GstSeekType start_type, stop_type;
833
834   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
835   g_return_val_if_fail (range != NULL, FALSE);
836
837   g_rec_mutex_lock (&media->state_lock);
838   if (!media->seekable)
839     goto not_seekable;
840
841   if (range->unit != GST_RTSP_RANGE_NPT)
842     goto not_supported;
843
844   /* depends on the current playing state of the pipeline. We might need to
845    * queue this until we get EOS. */
846   flags = GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE | GST_SEEK_FLAG_KEY_UNIT;
847
848   start_type = stop_type = GST_SEEK_TYPE_NONE;
849
850   switch (range->min.type) {
851     case GST_RTSP_TIME_NOW:
852       start = -1;
853       break;
854     case GST_RTSP_TIME_SECONDS:
855       /* only seek when something changed */
856       if (media->range.min.seconds == range->min.seconds) {
857         start = -1;
858       } else {
859         start = range->min.seconds * GST_SECOND;
860         start_type = GST_SEEK_TYPE_SET;
861       }
862       break;
863     case GST_RTSP_TIME_END:
864     default:
865       goto weird_type;
866   }
867   switch (range->max.type) {
868     case GST_RTSP_TIME_SECONDS:
869       /* only seek when something changed */
870       if (media->range.max.seconds == range->max.seconds) {
871         stop = -1;
872       } else {
873         stop = range->max.seconds * GST_SECOND;
874         stop_type = GST_SEEK_TYPE_SET;
875       }
876       break;
877     case GST_RTSP_TIME_END:
878       stop = -1;
879       stop_type = GST_SEEK_TYPE_SET;
880       break;
881     case GST_RTSP_TIME_NOW:
882     default:
883       goto weird_type;
884   }
885
886   if (start != -1 || stop != -1) {
887     GST_INFO ("seeking to %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
888         GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
889
890     res = gst_element_seek (media->pipeline, 1.0, GST_FORMAT_TIME,
891         flags, start_type, start, stop_type, stop);
892
893     /* and block for the seek to complete */
894     GST_INFO ("done seeking %d", res);
895     gst_element_get_state (media->pipeline, NULL, NULL, -1);
896     GST_INFO ("prerolled again");
897
898     collect_media_stats (media);
899   } else {
900     GST_INFO ("no seek needed");
901     res = TRUE;
902   }
903   g_rec_mutex_unlock (&media->state_lock);
904
905   return res;
906
907   /* ERRORS */
908 not_seekable:
909   {
910     g_rec_mutex_unlock (&media->state_lock);
911     GST_INFO ("pipeline is not seekable");
912     return TRUE;
913   }
914 not_supported:
915   {
916     g_rec_mutex_unlock (&media->state_lock);
917     GST_WARNING ("seek unit %d not supported", range->unit);
918     return FALSE;
919   }
920 weird_type:
921   {
922     g_rec_mutex_unlock (&media->state_lock);
923     GST_WARNING ("weird range type %d not supported", range->min.type);
924     return FALSE;
925   }
926 }
927
928 static void
929 gst_rtsp_media_set_status (GstRTSPMedia * media, GstRTSPMediaStatus status)
930 {
931   g_mutex_lock (&media->lock);
932   /* never overwrite the error status */
933   if (media->status != GST_RTSP_MEDIA_STATUS_ERROR)
934     media->status = status;
935   GST_DEBUG ("setting new status to %d", status);
936   g_cond_broadcast (&media->cond);
937   g_mutex_unlock (&media->lock);
938 }
939
940 static GstRTSPMediaStatus
941 gst_rtsp_media_get_status (GstRTSPMedia * media)
942 {
943   GstRTSPMediaStatus result;
944   gint64 end_time;
945
946   g_mutex_lock (&media->lock);
947   end_time = g_get_monotonic_time () + 20 * G_TIME_SPAN_SECOND;
948   /* while we are preparing, wait */
949   while (media->status == GST_RTSP_MEDIA_STATUS_PREPARING) {
950     GST_DEBUG ("waiting for status change");
951     if (!g_cond_wait_until (&media->cond, &media->lock, end_time)) {
952       GST_DEBUG ("timeout, assuming error status");
953       media->status = GST_RTSP_MEDIA_STATUS_ERROR;
954     }
955   }
956   /* could be success or error */
957   result = media->status;
958   GST_DEBUG ("got status %d", result);
959   g_mutex_unlock (&media->lock);
960
961   return result;
962 }
963
964 /* called with state-lock */
965 static gboolean
966 default_handle_message (GstRTSPMedia * media, GstMessage * message)
967 {
968   GstMessageType type;
969
970   type = GST_MESSAGE_TYPE (message);
971
972   switch (type) {
973     case GST_MESSAGE_STATE_CHANGED:
974       break;
975     case GST_MESSAGE_BUFFERING:
976     {
977       gint percent;
978
979       gst_message_parse_buffering (message, &percent);
980
981       /* no state management needed for live pipelines */
982       if (media->is_live)
983         break;
984
985       if (percent == 100) {
986         /* a 100% message means buffering is done */
987         media->buffering = FALSE;
988         /* if the desired state is playing, go back */
989         if (media->target_state == GST_STATE_PLAYING) {
990           GST_INFO ("Buffering done, setting pipeline to PLAYING");
991           gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
992         } else {
993           GST_INFO ("Buffering done");
994         }
995       } else {
996         /* buffering busy */
997         if (media->buffering == FALSE) {
998           if (media->target_state == GST_STATE_PLAYING) {
999             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
1000             GST_INFO ("Buffering, setting pipeline to PAUSED ...");
1001             gst_element_set_state (media->pipeline, GST_STATE_PAUSED);
1002           } else {
1003             GST_INFO ("Buffering ...");
1004           }
1005         }
1006         media->buffering = TRUE;
1007       }
1008       break;
1009     }
1010     case GST_MESSAGE_LATENCY:
1011     {
1012       gst_bin_recalculate_latency (GST_BIN_CAST (media->pipeline));
1013       break;
1014     }
1015     case GST_MESSAGE_ERROR:
1016     {
1017       GError *gerror;
1018       gchar *debug;
1019
1020       gst_message_parse_error (message, &gerror, &debug);
1021       GST_WARNING ("%p: got error %s (%s)", media, gerror->message, debug);
1022       g_error_free (gerror);
1023       g_free (debug);
1024
1025       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
1026       break;
1027     }
1028     case GST_MESSAGE_WARNING:
1029     {
1030       GError *gerror;
1031       gchar *debug;
1032
1033       gst_message_parse_warning (message, &gerror, &debug);
1034       GST_WARNING ("%p: got warning %s (%s)", media, gerror->message, debug);
1035       g_error_free (gerror);
1036       g_free (debug);
1037       break;
1038     }
1039     case GST_MESSAGE_ELEMENT:
1040       break;
1041     case GST_MESSAGE_STREAM_STATUS:
1042       break;
1043     case GST_MESSAGE_ASYNC_DONE:
1044       if (!media->adding) {
1045         /* when we are dynamically adding pads, the addition of the udpsrc will
1046          * temporarily produce ASYNC_DONE messages. We have to ignore them and
1047          * wait for the final ASYNC_DONE after everything prerolled */
1048         GST_INFO ("%p: got ASYNC_DONE", media);
1049         collect_media_stats (media);
1050
1051         gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
1052       } else {
1053         GST_INFO ("%p: ignoring ASYNC_DONE", media);
1054       }
1055       break;
1056     case GST_MESSAGE_EOS:
1057       GST_INFO ("%p: got EOS", media);
1058
1059       if (media->status == GST_RTSP_MEDIA_STATUS_UNPREPARING) {
1060         GST_DEBUG ("shutting down after EOS");
1061         finish_unprepare (media);
1062         g_object_unref (media);
1063       }
1064       break;
1065     default:
1066       GST_INFO ("%p: got message type %s", media,
1067           gst_message_type_get_name (type));
1068       break;
1069   }
1070   return TRUE;
1071 }
1072
1073 static gboolean
1074 bus_message (GstBus * bus, GstMessage * message, GstRTSPMedia * media)
1075 {
1076   GstRTSPMediaClass *klass;
1077   gboolean ret;
1078
1079   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1080
1081   g_rec_mutex_lock (&media->state_lock);
1082   if (klass->handle_message)
1083     ret = klass->handle_message (media, message);
1084   else
1085     ret = FALSE;
1086   g_rec_mutex_unlock (&media->state_lock);
1087
1088   return ret;
1089 }
1090
1091 /* called from streaming threads */
1092 static void
1093 pad_added_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
1094 {
1095   GstRTSPStream *stream;
1096
1097   /* FIXME, element is likely not a payloader, find the payloader here */
1098   stream = gst_rtsp_media_create_stream (media, element, pad);
1099
1100   GST_INFO ("pad added %s:%s, stream %d", GST_DEBUG_PAD_NAME (pad),
1101       stream->idx);
1102
1103   g_rec_mutex_lock (&media->state_lock);
1104   /* we will be adding elements below that will cause ASYNC_DONE to be
1105    * posted in the bus. We want to ignore those messages until the
1106    * pipeline really prerolled. */
1107   media->adding = TRUE;
1108
1109   /* join the element in the PAUSED state because this callback is
1110    * called from the streaming thread and it is PAUSED */
1111   gst_rtsp_stream_join_bin (stream, GST_BIN (media->pipeline),
1112       media->rtpbin, GST_STATE_PAUSED);
1113
1114   media->adding = FALSE;
1115   g_rec_mutex_unlock (&media->state_lock);
1116 }
1117
1118 static void
1119 no_more_pads_cb (GstElement * element, GstRTSPMedia * media)
1120 {
1121   GstElement *fakesink;
1122
1123   g_mutex_lock (&media->lock);
1124   GST_INFO ("no more pads");
1125   if ((fakesink = media->fakesink)) {
1126     gst_object_ref (fakesink);
1127     media->fakesink = NULL;
1128     g_mutex_unlock (&media->lock);
1129
1130     gst_bin_remove (GST_BIN (media->pipeline), fakesink);
1131     gst_element_set_state (fakesink, GST_STATE_NULL);
1132     gst_object_unref (fakesink);
1133     GST_INFO ("removed fakesink");
1134   }
1135 }
1136
1137 /**
1138  * gst_rtsp_media_prepare:
1139  * @media: a #GstRTSPMedia
1140  *
1141  * Prepare @media for streaming. This function will create the pipeline and
1142  * other objects to manage the streaming.
1143  *
1144  * It will preroll the pipeline and collect vital information about the streams
1145  * such as the duration.
1146  *
1147  * Returns: %TRUE on success.
1148  */
1149 gboolean
1150 gst_rtsp_media_prepare (GstRTSPMedia * media)
1151 {
1152   GstStateChangeReturn ret;
1153   GstRTSPMediaStatus status;
1154   guint i;
1155   GstRTSPMediaClass *klass;
1156   GstBus *bus;
1157   GList *walk;
1158
1159   g_rec_mutex_lock (&media->state_lock);
1160   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARED)
1161     goto was_prepared;
1162
1163   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARING)
1164     goto wait_status;
1165
1166   if (media->status != GST_RTSP_MEDIA_STATUS_UNPREPARED)
1167     goto not_unprepared;
1168
1169   if (!media->reusable && media->reused)
1170     goto is_reused;
1171
1172   media->rtpbin = gst_element_factory_make ("rtpbin", NULL);
1173   if (media->rtpbin == NULL)
1174     goto no_rtpbin;
1175
1176   GST_INFO ("preparing media %p", media);
1177
1178   /* reset some variables */
1179   media->is_live = FALSE;
1180   media->seekable = FALSE;
1181   media->buffering = FALSE;
1182   /* we're preparing now */
1183   media->status = GST_RTSP_MEDIA_STATUS_PREPARING;
1184
1185   bus = gst_pipeline_get_bus (GST_PIPELINE_CAST (media->pipeline));
1186
1187   /* add the pipeline bus to our custom mainloop */
1188   media->source = gst_bus_create_watch (bus);
1189   gst_object_unref (bus);
1190
1191   g_source_set_callback (media->source, (GSourceFunc) bus_message, media, NULL);
1192
1193   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1194   media->id = g_source_attach (media->source, klass->context);
1195
1196   /* add stuff to the bin */
1197   gst_bin_add (GST_BIN (media->pipeline), media->rtpbin);
1198
1199   /* link streams we already have, other streams might appear when we have
1200    * dynamic elements */
1201   for (i = 0; i < media->streams->len; i++) {
1202     GstRTSPStream *stream;
1203
1204     stream = g_ptr_array_index (media->streams, i);
1205
1206     gst_rtsp_stream_join_bin (stream, GST_BIN (media->pipeline),
1207         media->rtpbin, GST_STATE_NULL);
1208   }
1209
1210   for (walk = media->dynamic; walk; walk = g_list_next (walk)) {
1211     GstElement *elem = walk->data;
1212
1213     GST_INFO ("adding callbacks for dynamic element %p", elem);
1214
1215     g_signal_connect (elem, "pad-added", (GCallback) pad_added_cb, media);
1216     g_signal_connect (elem, "no-more-pads", (GCallback) no_more_pads_cb, media);
1217
1218     /* we add a fakesink here in order to make the state change async. We remove
1219      * the fakesink again in the no-more-pads callback. */
1220     media->fakesink = gst_element_factory_make ("fakesink", "fakesink");
1221     gst_bin_add (GST_BIN (media->pipeline), media->fakesink);
1222   }
1223
1224   GST_INFO ("setting pipeline to PAUSED for media %p", media);
1225   /* first go to PAUSED */
1226   ret = gst_element_set_state (media->pipeline, GST_STATE_PAUSED);
1227   media->target_state = GST_STATE_PAUSED;
1228
1229   switch (ret) {
1230     case GST_STATE_CHANGE_SUCCESS:
1231       GST_INFO ("SUCCESS state change for media %p", media);
1232       media->seekable = TRUE;
1233       break;
1234     case GST_STATE_CHANGE_ASYNC:
1235       GST_INFO ("ASYNC state change for media %p", media);
1236       media->seekable = TRUE;
1237       break;
1238     case GST_STATE_CHANGE_NO_PREROLL:
1239       /* we need to go to PLAYING */
1240       GST_INFO ("NO_PREROLL state change: live media %p", media);
1241       /* FIXME we disable seeking for live streams for now. We should perform a
1242        * seeking query in preroll instead */
1243       media->seekable = FALSE;
1244       media->is_live = TRUE;
1245       ret = gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
1246       if (ret == GST_STATE_CHANGE_FAILURE)
1247         goto state_failed;
1248       break;
1249     case GST_STATE_CHANGE_FAILURE:
1250       goto state_failed;
1251   }
1252 wait_status:
1253   g_rec_mutex_unlock (&media->state_lock);
1254
1255   /* now wait for all pads to be prerolled, FIXME, we should somehow be
1256    * able to do this async so that we don't block the server thread. */
1257   status = gst_rtsp_media_get_status (media);
1258   if (status == GST_RTSP_MEDIA_STATUS_ERROR)
1259     goto state_failed;
1260
1261   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_PREPARED], 0, NULL);
1262
1263   GST_INFO ("object %p is prerolled", media);
1264
1265   return TRUE;
1266
1267   /* OK */
1268 was_prepared:
1269   {
1270     GST_LOG ("media %p was prepared", media);
1271     g_rec_mutex_unlock (&media->state_lock);
1272     return TRUE;
1273   }
1274   /* ERRORS */
1275 not_unprepared:
1276   {
1277     GST_WARNING ("media %p was not unprepared", media);
1278     g_rec_mutex_unlock (&media->state_lock);
1279     return FALSE;
1280   }
1281 is_reused:
1282   {
1283     g_rec_mutex_unlock (&media->state_lock);
1284     GST_WARNING ("can not reuse media %p", media);
1285     return FALSE;
1286   }
1287 no_rtpbin:
1288   {
1289     g_rec_mutex_unlock (&media->state_lock);
1290     GST_WARNING ("no rtpbin element");
1291     g_warning ("failed to create element 'rtpbin', check your installation");
1292     return FALSE;
1293   }
1294 state_failed:
1295   {
1296     GST_WARNING ("failed to preroll pipeline");
1297     gst_rtsp_media_unprepare (media);
1298     g_rec_mutex_unlock (&media->state_lock);
1299     return FALSE;
1300   }
1301 }
1302
1303 /* must be called with state-lock */
1304 static void
1305 finish_unprepare (GstRTSPMedia * media)
1306 {
1307   gint i;
1308
1309   GST_DEBUG ("shutting down");
1310
1311   gst_element_set_state (media->pipeline, GST_STATE_NULL);
1312
1313   for (i = 0; i < media->streams->len; i++) {
1314     GstRTSPStream *stream;
1315
1316     GST_INFO ("Removing elements of stream %d from pipeline", i);
1317
1318     stream = g_ptr_array_index (media->streams, i);
1319
1320     gst_rtsp_stream_leave_bin (stream, GST_BIN (media->pipeline),
1321         media->rtpbin);
1322   }
1323   g_ptr_array_set_size (media->streams, 0);
1324
1325   gst_bin_remove (GST_BIN (media->pipeline), media->rtpbin);
1326   media->rtpbin = NULL;
1327
1328   gst_object_unref (media->pipeline);
1329   media->pipeline = NULL;
1330
1331   media->reused = TRUE;
1332   media->status = GST_RTSP_MEDIA_STATUS_UNPREPARED;
1333
1334   /* when the media is not reusable, this will effectively unref the media and
1335    * recreate it */
1336   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_UNPREPARED], 0, NULL);
1337 }
1338
1339 /* called with state-lock */
1340 static gboolean
1341 default_unprepare (GstRTSPMedia * media)
1342 {
1343   if (media->eos_shutdown) {
1344     GST_DEBUG ("sending EOS for shutdown");
1345     /* ref so that we don't disappear */
1346     g_object_ref (media);
1347     gst_element_send_event (media->pipeline, gst_event_new_eos ());
1348     /* we need to go to playing again for the EOS to propagate, normally in this
1349      * state, nothing is receiving data from us anymore so this is ok. */
1350     gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
1351     media->status = GST_RTSP_MEDIA_STATUS_UNPREPARING;
1352   } else {
1353     finish_unprepare (media);
1354   }
1355   return TRUE;
1356 }
1357
1358 /**
1359  * gst_rtsp_media_unprepare:
1360  * @media: a #GstRTSPMedia
1361  *
1362  * Unprepare @media. After this call, the media should be prepared again before
1363  * it can be used again. If the media is set to be non-reusable, a new instance
1364  * must be created.
1365  *
1366  * Returns: %TRUE on success.
1367  */
1368 gboolean
1369 gst_rtsp_media_unprepare (GstRTSPMedia * media)
1370 {
1371   gboolean success;
1372
1373   g_rec_mutex_lock (&media->state_lock);
1374   if (media->status == GST_RTSP_MEDIA_STATUS_UNPREPARED)
1375     goto was_unprepared;
1376
1377   GST_INFO ("unprepare media %p", media);
1378   media->target_state = GST_STATE_NULL;
1379   success = TRUE;
1380
1381   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARED) {
1382     GstRTSPMediaClass *klass;
1383
1384     klass = GST_RTSP_MEDIA_GET_CLASS (media);
1385     if (klass->unprepare)
1386       success = klass->unprepare (media);
1387   } else {
1388     finish_unprepare (media);
1389   }
1390   g_rec_mutex_unlock (&media->state_lock);
1391
1392   return success;
1393
1394 was_unprepared:
1395   {
1396     g_rec_mutex_unlock (&media->state_lock);
1397     GST_INFO ("media %p was already unprepared", media);
1398     return TRUE;
1399   }
1400 }
1401
1402 /**
1403  * gst_rtsp_media_set_state:
1404  * @media: a #GstRTSPMedia
1405  * @state: the target state of the media
1406  * @transports: a #GPtrArray of #GstRTSPStreamTransport pointers
1407  *
1408  * Set the state of @media to @state and for the transports in @transports.
1409  *
1410  * Returns: %TRUE on success.
1411  */
1412 gboolean
1413 gst_rtsp_media_set_state (GstRTSPMedia * media, GstState state,
1414     GPtrArray * transports)
1415 {
1416   gint i;
1417   gboolean add, remove, do_state;
1418   gint old_active;
1419
1420   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1421   g_return_val_if_fail (transports != NULL, FALSE);
1422
1423   g_rec_mutex_lock (&media->state_lock);
1424
1425   /* NULL and READY are the same */
1426   if (state == GST_STATE_READY)
1427     state = GST_STATE_NULL;
1428
1429   add = remove = FALSE;
1430
1431   GST_INFO ("going to state %s media %p", gst_element_state_get_name (state),
1432       media);
1433
1434   switch (state) {
1435     case GST_STATE_NULL:
1436     case GST_STATE_PAUSED:
1437       /* we're going from PLAYING to PAUSED, READY or NULL, remove */
1438       if (media->target_state == GST_STATE_PLAYING)
1439         remove = TRUE;
1440       break;
1441     case GST_STATE_PLAYING:
1442       /* we're going to PLAYING, add */
1443       add = TRUE;
1444       break;
1445     default:
1446       break;
1447   }
1448   old_active = media->n_active;
1449
1450   for (i = 0; i < transports->len; i++) {
1451     GstRTSPStreamTransport *trans;
1452
1453     /* we need a non-NULL entry in the array */
1454     trans = g_ptr_array_index (transports, i);
1455     if (trans == NULL)
1456       continue;
1457
1458     /* we need a transport */
1459     if (!trans->transport)
1460       continue;
1461
1462     if (add) {
1463       if (gst_rtsp_stream_add_transport (trans->stream, trans))
1464         media->n_active++;
1465     } else if (remove) {
1466       if (gst_rtsp_stream_remove_transport (trans->stream, trans))
1467         media->n_active--;
1468     }
1469   }
1470
1471   /* we just added the first media, do the playing state change */
1472   if (old_active == 0 && add)
1473     do_state = TRUE;
1474   /* if we have no more active media, do the downward state changes */
1475   else if (media->n_active == 0)
1476     do_state = TRUE;
1477   else
1478     do_state = FALSE;
1479
1480   GST_INFO ("state %d active %d media %p do_state %d", state, media->n_active,
1481       media, do_state);
1482
1483   if (media->target_state != state) {
1484     if (do_state) {
1485       if (state == GST_STATE_NULL) {
1486         gst_rtsp_media_unprepare (media);
1487       } else {
1488         GST_INFO ("state %s media %p", gst_element_state_get_name (state),
1489             media);
1490         media->target_state = state;
1491         gst_element_set_state (media->pipeline, state);
1492       }
1493     }
1494     g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STATE], 0, state,
1495         NULL);
1496   }
1497
1498   /* remember where we are */
1499   if (state != GST_STATE_NULL && (state == GST_STATE_PAUSED ||
1500           old_active != media->n_active))
1501     collect_media_stats (media);
1502
1503   g_rec_mutex_unlock (&media->state_lock);
1504
1505   return TRUE;
1506 }