rtsp-media: remove bus watch before finalizing
[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 static void
1092 watch_destroyed (GstRTSPMedia * media)
1093 {
1094   GST_DEBUG_OBJECT (media, "source destroyed");
1095   gst_object_unref (media);
1096 }
1097
1098 /* called from streaming threads */
1099 static void
1100 pad_added_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
1101 {
1102   GstRTSPStream *stream;
1103
1104   /* FIXME, element is likely not a payloader, find the payloader here */
1105   stream = gst_rtsp_media_create_stream (media, element, pad);
1106
1107   GST_INFO ("pad added %s:%s, stream %d", GST_DEBUG_PAD_NAME (pad),
1108       stream->idx);
1109
1110   g_rec_mutex_lock (&media->state_lock);
1111   /* we will be adding elements below that will cause ASYNC_DONE to be
1112    * posted in the bus. We want to ignore those messages until the
1113    * pipeline really prerolled. */
1114   media->adding = TRUE;
1115
1116   /* join the element in the PAUSED state because this callback is
1117    * called from the streaming thread and it is PAUSED */
1118   gst_rtsp_stream_join_bin (stream, GST_BIN (media->pipeline),
1119       media->rtpbin, GST_STATE_PAUSED);
1120
1121   media->adding = FALSE;
1122   g_rec_mutex_unlock (&media->state_lock);
1123 }
1124
1125 static void
1126 no_more_pads_cb (GstElement * element, GstRTSPMedia * media)
1127 {
1128   GstElement *fakesink;
1129
1130   g_mutex_lock (&media->lock);
1131   GST_INFO ("no more pads");
1132   if ((fakesink = media->fakesink)) {
1133     gst_object_ref (fakesink);
1134     media->fakesink = NULL;
1135     g_mutex_unlock (&media->lock);
1136
1137     gst_bin_remove (GST_BIN (media->pipeline), fakesink);
1138     gst_element_set_state (fakesink, GST_STATE_NULL);
1139     gst_object_unref (fakesink);
1140     GST_INFO ("removed fakesink");
1141   }
1142 }
1143
1144 /**
1145  * gst_rtsp_media_prepare:
1146  * @media: a #GstRTSPMedia
1147  *
1148  * Prepare @media for streaming. This function will create the pipeline and
1149  * other objects to manage the streaming.
1150  *
1151  * It will preroll the pipeline and collect vital information about the streams
1152  * such as the duration.
1153  *
1154  * Returns: %TRUE on success.
1155  */
1156 gboolean
1157 gst_rtsp_media_prepare (GstRTSPMedia * media)
1158 {
1159   GstStateChangeReturn ret;
1160   GstRTSPMediaStatus status;
1161   guint i;
1162   GstRTSPMediaClass *klass;
1163   GstBus *bus;
1164   GList *walk;
1165
1166   g_rec_mutex_lock (&media->state_lock);
1167   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARED)
1168     goto was_prepared;
1169
1170   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARING)
1171     goto wait_status;
1172
1173   if (media->status != GST_RTSP_MEDIA_STATUS_UNPREPARED)
1174     goto not_unprepared;
1175
1176   if (!media->reusable && media->reused)
1177     goto is_reused;
1178
1179   media->rtpbin = gst_element_factory_make ("rtpbin", NULL);
1180   if (media->rtpbin == NULL)
1181     goto no_rtpbin;
1182
1183   GST_INFO ("preparing media %p", media);
1184
1185   /* reset some variables */
1186   media->is_live = FALSE;
1187   media->seekable = FALSE;
1188   media->buffering = FALSE;
1189   /* we're preparing now */
1190   media->status = GST_RTSP_MEDIA_STATUS_PREPARING;
1191
1192   bus = gst_pipeline_get_bus (GST_PIPELINE_CAST (media->pipeline));
1193
1194   /* add the pipeline bus to our custom mainloop */
1195   media->source = gst_bus_create_watch (bus);
1196   gst_object_unref (bus);
1197
1198   g_source_set_callback (media->source, (GSourceFunc) bus_message,
1199       gst_object_ref (media), (GDestroyNotify) watch_destroyed);
1200
1201   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1202   media->id = g_source_attach (media->source, klass->context);
1203
1204   /* add stuff to the bin */
1205   gst_bin_add (GST_BIN (media->pipeline), media->rtpbin);
1206
1207   /* link streams we already have, other streams might appear when we have
1208    * dynamic elements */
1209   for (i = 0; i < media->streams->len; i++) {
1210     GstRTSPStream *stream;
1211
1212     stream = g_ptr_array_index (media->streams, i);
1213
1214     gst_rtsp_stream_join_bin (stream, GST_BIN (media->pipeline),
1215         media->rtpbin, GST_STATE_NULL);
1216   }
1217
1218   for (walk = media->dynamic; walk; walk = g_list_next (walk)) {
1219     GstElement *elem = walk->data;
1220
1221     GST_INFO ("adding callbacks for dynamic element %p", elem);
1222
1223     g_signal_connect (elem, "pad-added", (GCallback) pad_added_cb, media);
1224     g_signal_connect (elem, "no-more-pads", (GCallback) no_more_pads_cb, media);
1225
1226     /* we add a fakesink here in order to make the state change async. We remove
1227      * the fakesink again in the no-more-pads callback. */
1228     media->fakesink = gst_element_factory_make ("fakesink", "fakesink");
1229     gst_bin_add (GST_BIN (media->pipeline), media->fakesink);
1230   }
1231
1232   GST_INFO ("setting pipeline to PAUSED for media %p", media);
1233   /* first go to PAUSED */
1234   ret = gst_element_set_state (media->pipeline, GST_STATE_PAUSED);
1235   media->target_state = GST_STATE_PAUSED;
1236
1237   switch (ret) {
1238     case GST_STATE_CHANGE_SUCCESS:
1239       GST_INFO ("SUCCESS state change for media %p", media);
1240       media->seekable = TRUE;
1241       break;
1242     case GST_STATE_CHANGE_ASYNC:
1243       GST_INFO ("ASYNC state change for media %p", media);
1244       media->seekable = TRUE;
1245       break;
1246     case GST_STATE_CHANGE_NO_PREROLL:
1247       /* we need to go to PLAYING */
1248       GST_INFO ("NO_PREROLL state change: live media %p", media);
1249       /* FIXME we disable seeking for live streams for now. We should perform a
1250        * seeking query in preroll instead */
1251       media->seekable = FALSE;
1252       media->is_live = TRUE;
1253       ret = gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
1254       if (ret == GST_STATE_CHANGE_FAILURE)
1255         goto state_failed;
1256       break;
1257     case GST_STATE_CHANGE_FAILURE:
1258       goto state_failed;
1259   }
1260 wait_status:
1261   g_rec_mutex_unlock (&media->state_lock);
1262
1263   /* now wait for all pads to be prerolled, FIXME, we should somehow be
1264    * able to do this async so that we don't block the server thread. */
1265   status = gst_rtsp_media_get_status (media);
1266   if (status == GST_RTSP_MEDIA_STATUS_ERROR)
1267     goto state_failed;
1268
1269   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_PREPARED], 0, NULL);
1270
1271   GST_INFO ("object %p is prerolled", media);
1272
1273   return TRUE;
1274
1275   /* OK */
1276 was_prepared:
1277   {
1278     GST_LOG ("media %p was prepared", media);
1279     g_rec_mutex_unlock (&media->state_lock);
1280     return TRUE;
1281   }
1282   /* ERRORS */
1283 not_unprepared:
1284   {
1285     GST_WARNING ("media %p was not unprepared", media);
1286     g_rec_mutex_unlock (&media->state_lock);
1287     return FALSE;
1288   }
1289 is_reused:
1290   {
1291     g_rec_mutex_unlock (&media->state_lock);
1292     GST_WARNING ("can not reuse media %p", media);
1293     return FALSE;
1294   }
1295 no_rtpbin:
1296   {
1297     g_rec_mutex_unlock (&media->state_lock);
1298     GST_WARNING ("no rtpbin element");
1299     g_warning ("failed to create element 'rtpbin', check your installation");
1300     return FALSE;
1301   }
1302 state_failed:
1303   {
1304     GST_WARNING ("failed to preroll pipeline");
1305     gst_rtsp_media_unprepare (media);
1306     g_rec_mutex_unlock (&media->state_lock);
1307     return FALSE;
1308   }
1309 }
1310
1311 /* must be called with state-lock */
1312 static void
1313 finish_unprepare (GstRTSPMedia * media)
1314 {
1315   gint i;
1316
1317   GST_DEBUG ("shutting down");
1318
1319   gst_element_set_state (media->pipeline, GST_STATE_NULL);
1320
1321   for (i = 0; i < media->streams->len; i++) {
1322     GstRTSPStream *stream;
1323
1324     GST_INFO ("Removing elements of stream %d from pipeline", i);
1325
1326     stream = g_ptr_array_index (media->streams, i);
1327
1328     gst_rtsp_stream_leave_bin (stream, GST_BIN (media->pipeline),
1329         media->rtpbin);
1330   }
1331   g_ptr_array_set_size (media->streams, 0);
1332
1333   gst_bin_remove (GST_BIN (media->pipeline), media->rtpbin);
1334   media->rtpbin = NULL;
1335
1336   gst_object_unref (media->pipeline);
1337   media->pipeline = NULL;
1338
1339   media->reused = TRUE;
1340   media->status = GST_RTSP_MEDIA_STATUS_UNPREPARED;
1341
1342   /* when the media is not reusable, this will effectively unref the media and
1343    * recreate it */
1344   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_UNPREPARED], 0, NULL);
1345 }
1346
1347 /* called with state-lock */
1348 static gboolean
1349 default_unprepare (GstRTSPMedia * media)
1350 {
1351   if (media->eos_shutdown) {
1352     GST_DEBUG ("sending EOS for shutdown");
1353     /* ref so that we don't disappear */
1354     g_object_ref (media);
1355     gst_element_send_event (media->pipeline, gst_event_new_eos ());
1356     /* we need to go to playing again for the EOS to propagate, normally in this
1357      * state, nothing is receiving data from us anymore so this is ok. */
1358     gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
1359     media->status = GST_RTSP_MEDIA_STATUS_UNPREPARING;
1360   } else {
1361     finish_unprepare (media);
1362   }
1363   return TRUE;
1364 }
1365
1366 /**
1367  * gst_rtsp_media_unprepare:
1368  * @media: a #GstRTSPMedia
1369  *
1370  * Unprepare @media. After this call, the media should be prepared again before
1371  * it can be used again. If the media is set to be non-reusable, a new instance
1372  * must be created.
1373  *
1374  * Returns: %TRUE on success.
1375  */
1376 gboolean
1377 gst_rtsp_media_unprepare (GstRTSPMedia * media)
1378 {
1379   gboolean success;
1380
1381   g_rec_mutex_lock (&media->state_lock);
1382   if (media->status == GST_RTSP_MEDIA_STATUS_UNPREPARED)
1383     goto was_unprepared;
1384
1385   GST_INFO ("unprepare media %p", media);
1386   media->target_state = GST_STATE_NULL;
1387   success = TRUE;
1388
1389   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARED) {
1390     GstRTSPMediaClass *klass;
1391
1392     klass = GST_RTSP_MEDIA_GET_CLASS (media);
1393     if (klass->unprepare)
1394       success = klass->unprepare (media);
1395   } else {
1396     finish_unprepare (media);
1397   }
1398   if (media->source) {
1399     g_source_destroy (media->source);
1400     g_source_unref (media->source);
1401     media->source = NULL;
1402   }
1403   g_rec_mutex_unlock (&media->state_lock);
1404
1405   return success;
1406
1407 was_unprepared:
1408   {
1409     g_rec_mutex_unlock (&media->state_lock);
1410     GST_INFO ("media %p was already unprepared", media);
1411     return TRUE;
1412   }
1413 }
1414
1415 /**
1416  * gst_rtsp_media_set_state:
1417  * @media: a #GstRTSPMedia
1418  * @state: the target state of the media
1419  * @transports: a #GPtrArray of #GstRTSPStreamTransport pointers
1420  *
1421  * Set the state of @media to @state and for the transports in @transports.
1422  *
1423  * Returns: %TRUE on success.
1424  */
1425 gboolean
1426 gst_rtsp_media_set_state (GstRTSPMedia * media, GstState state,
1427     GPtrArray * transports)
1428 {
1429   gint i;
1430   gboolean add, remove, do_state;
1431   gint old_active;
1432
1433   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1434   g_return_val_if_fail (transports != NULL, FALSE);
1435
1436   g_rec_mutex_lock (&media->state_lock);
1437
1438   /* NULL and READY are the same */
1439   if (state == GST_STATE_READY)
1440     state = GST_STATE_NULL;
1441
1442   add = remove = FALSE;
1443
1444   GST_INFO ("going to state %s media %p", gst_element_state_get_name (state),
1445       media);
1446
1447   switch (state) {
1448     case GST_STATE_NULL:
1449     case GST_STATE_PAUSED:
1450       /* we're going from PLAYING to PAUSED, READY or NULL, remove */
1451       if (media->target_state == GST_STATE_PLAYING)
1452         remove = TRUE;
1453       break;
1454     case GST_STATE_PLAYING:
1455       /* we're going to PLAYING, add */
1456       add = TRUE;
1457       break;
1458     default:
1459       break;
1460   }
1461   old_active = media->n_active;
1462
1463   for (i = 0; i < transports->len; i++) {
1464     GstRTSPStreamTransport *trans;
1465
1466     /* we need a non-NULL entry in the array */
1467     trans = g_ptr_array_index (transports, i);
1468     if (trans == NULL)
1469       continue;
1470
1471     /* we need a transport */
1472     if (!trans->transport)
1473       continue;
1474
1475     if (add) {
1476       if (gst_rtsp_stream_add_transport (trans->stream, trans))
1477         media->n_active++;
1478     } else if (remove) {
1479       if (gst_rtsp_stream_remove_transport (trans->stream, trans))
1480         media->n_active--;
1481     }
1482   }
1483
1484   /* we just added the first media, do the playing state change */
1485   if (old_active == 0 && add)
1486     do_state = TRUE;
1487   /* if we have no more active media, do the downward state changes */
1488   else if (media->n_active == 0)
1489     do_state = TRUE;
1490   else
1491     do_state = FALSE;
1492
1493   GST_INFO ("state %d active %d media %p do_state %d", state, media->n_active,
1494       media, do_state);
1495
1496   if (media->target_state != state) {
1497     if (do_state) {
1498       if (state == GST_STATE_NULL) {
1499         gst_rtsp_media_unprepare (media);
1500       } else {
1501         GST_INFO ("state %s media %p", gst_element_state_get_name (state),
1502             media);
1503         media->target_state = state;
1504         gst_element_set_state (media->pipeline, state);
1505       }
1506     }
1507     g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STATE], 0, state,
1508         NULL);
1509   }
1510
1511   /* remember where we are */
1512   if (state != GST_STATE_NULL && (state == GST_STATE_PAUSED ||
1513           old_active != media->n_active))
1514     collect_media_stats (media);
1515
1516   g_rec_mutex_unlock (&media->state_lock);
1517
1518   return TRUE;
1519 }