rtsp: improve debug
[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_mutex_unlock (&media->lock);
599
600   if (old)
601     g_object_unref (old);
602 }
603
604 /**
605  * gst_rtsp_media_get_address_pool:
606  * @media: a #GstRTSPMedia
607  *
608  * Get the #GstRTSPAddressPool used as the address pool of @media.
609  *
610  * Returns: (transfer full): the #GstRTSPAddressPool of @media. g_object_unref() after
611  * usage.
612  */
613 GstRTSPAddressPool *
614 gst_rtsp_media_get_address_pool (GstRTSPMedia * media)
615 {
616   GstRTSPAddressPool *result;
617
618   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
619
620   g_mutex_lock (&media->lock);
621   if ((result = media->pool))
622     g_object_ref (result);
623   g_mutex_unlock (&media->lock);
624
625   return result;
626 }
627
628 /**
629  * gst_rtsp_media_collect_streams:
630  * @media: a #GstRTSPMedia
631  *
632  * Find all payloader elements, they should be named pay%d in the
633  * element of @media, and create #GstRTSPStreams for them.
634  *
635  * Collect all dynamic elements, named dynpay%d, and add them to
636  * the list of dynamic elements.
637  */
638 void
639 gst_rtsp_media_collect_streams (GstRTSPMedia * media)
640 {
641   GstElement *element, *elem;
642   GstPad *pad;
643   gint i;
644   gboolean have_elem;
645
646   g_return_if_fail (GST_IS_RTSP_MEDIA (media));
647
648   element = media->element;
649
650   have_elem = TRUE;
651   for (i = 0; have_elem; i++) {
652     gchar *name;
653
654     have_elem = FALSE;
655
656     name = g_strdup_printf ("pay%d", i);
657     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
658       GST_INFO ("found stream %d with payloader %p", i, elem);
659
660       /* take the pad of the payloader */
661       pad = gst_element_get_static_pad (elem, "src");
662       /* create the stream */
663       gst_rtsp_media_create_stream (media, elem, pad);
664       g_object_unref (pad);
665
666       gst_object_unref (elem);
667
668       have_elem = TRUE;
669     }
670     g_free (name);
671
672     name = g_strdup_printf ("dynpay%d", i);
673     if ((elem = gst_bin_get_by_name (GST_BIN (element), name))) {
674       /* a stream that will dynamically create pads to provide RTP packets */
675
676       GST_INFO ("found dynamic element %d, %p", i, elem);
677
678       g_mutex_lock (&media->lock);
679       media->dynamic = g_list_prepend (media->dynamic, elem);
680       g_mutex_unlock (&media->lock);
681
682       have_elem = TRUE;
683     }
684     g_free (name);
685   }
686 }
687
688 /**
689  * gst_rtsp_media_create_stream:
690  * @media: a #GstRTSPMedia
691  * @payloader: a #GstElement
692  * @srcpad: a source #GstPad
693  *
694  * Create a new stream in @media that provides RTP data on @srcpad.
695  * @srcpad should be a pad of an element inside @media->element.
696  *
697  * Returns: (transfer none): a new #GstRTSPStream that remains valid for as long
698  *          as @media exists.
699  */
700 GstRTSPStream *
701 gst_rtsp_media_create_stream (GstRTSPMedia * media, GstElement * payloader,
702     GstPad * pad)
703 {
704   GstRTSPStream *stream;
705   GstPad *srcpad;
706   gchar *name;
707   gint idx;
708
709   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
710   g_return_val_if_fail (GST_IS_ELEMENT (payloader), NULL);
711   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
712   g_return_val_if_fail (GST_PAD_IS_SRC (pad), NULL);
713
714   g_mutex_lock (&media->lock);
715   idx = media->streams->len;
716
717   name = g_strdup_printf ("src_%u", idx);
718   srcpad = gst_ghost_pad_new (name, pad);
719   gst_pad_set_active (srcpad, TRUE);
720   gst_element_add_pad (media->element, srcpad);
721   g_free (name);
722
723   stream = gst_rtsp_stream_new (idx, payloader, srcpad);
724   if (media->pool)
725     gst_rtsp_stream_set_address_pool (stream, media->pool);
726
727   g_ptr_array_add (media->streams, stream);
728   g_mutex_unlock (&media->lock);
729
730   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STREAM], 0, stream,
731       NULL);
732
733   return stream;
734 }
735
736 /**
737  * gst_rtsp_media_n_streams:
738  * @media: a #GstRTSPMedia
739  *
740  * Get the number of streams in this media.
741  *
742  * Returns: The number of streams.
743  */
744 guint
745 gst_rtsp_media_n_streams (GstRTSPMedia * media)
746 {
747   guint res;
748
749   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), 0);
750
751   g_mutex_lock (&media->lock);
752   res = media->streams->len;
753   g_mutex_unlock (&media->lock);
754
755   return res;
756 }
757
758 /**
759  * gst_rtsp_media_get_stream:
760  * @media: a #GstRTSPMedia
761  * @idx: the stream index
762  *
763  * Retrieve the stream with index @idx from @media.
764  *
765  * Returns: (transfer none): the #GstRTSPStream at index @idx or %NULL when a stream with
766  * that index did not exist.
767  */
768 GstRTSPStream *
769 gst_rtsp_media_get_stream (GstRTSPMedia * media, guint idx)
770 {
771   GstRTSPStream *res;
772
773   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), NULL);
774
775   g_mutex_lock (&media->lock);
776   if (idx < media->streams->len)
777     res = g_ptr_array_index (media->streams, idx);
778   else
779     res = NULL;
780   g_mutex_unlock (&media->lock);
781
782   return res;
783 }
784
785 /**
786  * gst_rtsp_media_get_range_string:
787  * @media: a #GstRTSPMedia
788  * @play: for the PLAY request
789  *
790  * Get the current range as a string.
791  *
792  * Returns: The range as a string, g_free() after usage.
793  */
794 gchar *
795 gst_rtsp_media_get_range_string (GstRTSPMedia * media, gboolean play)
796 {
797   gchar *result;
798   GstRTSPTimeRange range;
799
800   g_mutex_lock (&media->lock);
801   /* make copy */
802   range = media->range;
803
804   if (!play && media->n_active > 0) {
805     range.min.type = GST_RTSP_TIME_NOW;
806     range.min.seconds = -1;
807   }
808   g_mutex_unlock (&media->lock);
809
810   result = gst_rtsp_range_to_string (&range);
811
812   return result;
813 }
814
815 /**
816  * gst_rtsp_media_seek:
817  * @media: a #GstRTSPMedia
818  * @range: a #GstRTSPTimeRange
819  *
820  * Seek the pipeline to @range.
821  *
822  * Returns: %TRUE on success.
823  */
824 gboolean
825 gst_rtsp_media_seek (GstRTSPMedia * media, GstRTSPTimeRange * range)
826 {
827   GstSeekFlags flags;
828   gboolean res;
829   gint64 start, stop;
830   GstSeekType start_type, stop_type;
831
832   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
833   g_return_val_if_fail (range != NULL, FALSE);
834
835   g_rec_mutex_lock (&media->state_lock);
836   if (!media->seekable)
837     goto not_seekable;
838
839   if (range->unit != GST_RTSP_RANGE_NPT)
840     goto not_supported;
841
842   /* depends on the current playing state of the pipeline. We might need to
843    * queue this until we get EOS. */
844   flags = GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE | GST_SEEK_FLAG_KEY_UNIT;
845
846   start_type = stop_type = GST_SEEK_TYPE_NONE;
847
848   switch (range->min.type) {
849     case GST_RTSP_TIME_NOW:
850       start = -1;
851       break;
852     case GST_RTSP_TIME_SECONDS:
853       /* only seek when something changed */
854       if (media->range.min.seconds == range->min.seconds) {
855         start = -1;
856       } else {
857         start = range->min.seconds * GST_SECOND;
858         start_type = GST_SEEK_TYPE_SET;
859       }
860       break;
861     case GST_RTSP_TIME_END:
862     default:
863       goto weird_type;
864   }
865   switch (range->max.type) {
866     case GST_RTSP_TIME_SECONDS:
867       /* only seek when something changed */
868       if (media->range.max.seconds == range->max.seconds) {
869         stop = -1;
870       } else {
871         stop = range->max.seconds * GST_SECOND;
872         stop_type = GST_SEEK_TYPE_SET;
873       }
874       break;
875     case GST_RTSP_TIME_END:
876       stop = -1;
877       stop_type = GST_SEEK_TYPE_SET;
878       break;
879     case GST_RTSP_TIME_NOW:
880     default:
881       goto weird_type;
882   }
883
884   if (start != -1 || stop != -1) {
885     GST_INFO ("seeking to %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
886         GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
887
888     res = gst_element_seek (media->pipeline, 1.0, GST_FORMAT_TIME,
889         flags, start_type, start, stop_type, stop);
890
891     /* and block for the seek to complete */
892     GST_INFO ("done seeking %d", res);
893     gst_element_get_state (media->pipeline, NULL, NULL, -1);
894     GST_INFO ("prerolled again");
895
896     collect_media_stats (media);
897   } else {
898     GST_INFO ("no seek needed");
899     res = TRUE;
900   }
901   g_rec_mutex_unlock (&media->state_lock);
902
903   return res;
904
905   /* ERRORS */
906 not_seekable:
907   {
908     g_rec_mutex_unlock (&media->state_lock);
909     GST_INFO ("pipeline is not seekable");
910     return TRUE;
911   }
912 not_supported:
913   {
914     g_rec_mutex_unlock (&media->state_lock);
915     GST_WARNING ("seek unit %d not supported", range->unit);
916     return FALSE;
917   }
918 weird_type:
919   {
920     g_rec_mutex_unlock (&media->state_lock);
921     GST_WARNING ("weird range type %d not supported", range->min.type);
922     return FALSE;
923   }
924 }
925
926 static void
927 gst_rtsp_media_set_status (GstRTSPMedia * media, GstRTSPMediaStatus status)
928 {
929   g_mutex_lock (&media->lock);
930   /* never overwrite the error status */
931   if (media->status != GST_RTSP_MEDIA_STATUS_ERROR)
932     media->status = status;
933   GST_DEBUG ("setting new status to %d", status);
934   g_cond_broadcast (&media->cond);
935   g_mutex_unlock (&media->lock);
936 }
937
938 static GstRTSPMediaStatus
939 gst_rtsp_media_get_status (GstRTSPMedia * media)
940 {
941   GstRTSPMediaStatus result;
942   gint64 end_time;
943
944   g_mutex_lock (&media->lock);
945   end_time = g_get_monotonic_time () + 20 * G_TIME_SPAN_SECOND;
946   /* while we are preparing, wait */
947   while (media->status == GST_RTSP_MEDIA_STATUS_PREPARING) {
948     GST_DEBUG ("waiting for status change");
949     if (!g_cond_wait_until (&media->cond, &media->lock, end_time)) {
950       GST_DEBUG ("timeout, assuming error status");
951       media->status = GST_RTSP_MEDIA_STATUS_ERROR;
952     }
953   }
954   /* could be success or error */
955   result = media->status;
956   GST_DEBUG ("got status %d", result);
957   g_mutex_unlock (&media->lock);
958
959   return result;
960 }
961
962 /* called with state-lock */
963 static gboolean
964 default_handle_message (GstRTSPMedia * media, GstMessage * message)
965 {
966   GstMessageType type;
967
968   type = GST_MESSAGE_TYPE (message);
969
970   switch (type) {
971     case GST_MESSAGE_STATE_CHANGED:
972       break;
973     case GST_MESSAGE_BUFFERING:
974     {
975       gint percent;
976
977       gst_message_parse_buffering (message, &percent);
978
979       /* no state management needed for live pipelines */
980       if (media->is_live)
981         break;
982
983       if (percent == 100) {
984         /* a 100% message means buffering is done */
985         media->buffering = FALSE;
986         /* if the desired state is playing, go back */
987         if (media->target_state == GST_STATE_PLAYING) {
988           GST_INFO ("Buffering done, setting pipeline to PLAYING");
989           gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
990         } else {
991           GST_INFO ("Buffering done");
992         }
993       } else {
994         /* buffering busy */
995         if (media->buffering == FALSE) {
996           if (media->target_state == GST_STATE_PLAYING) {
997             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
998             GST_INFO ("Buffering, setting pipeline to PAUSED ...");
999             gst_element_set_state (media->pipeline, GST_STATE_PAUSED);
1000           } else {
1001             GST_INFO ("Buffering ...");
1002           }
1003         }
1004         media->buffering = TRUE;
1005       }
1006       break;
1007     }
1008     case GST_MESSAGE_LATENCY:
1009     {
1010       gst_bin_recalculate_latency (GST_BIN_CAST (media->pipeline));
1011       break;
1012     }
1013     case GST_MESSAGE_ERROR:
1014     {
1015       GError *gerror;
1016       gchar *debug;
1017
1018       gst_message_parse_error (message, &gerror, &debug);
1019       GST_WARNING ("%p: got error %s (%s)", media, gerror->message, debug);
1020       g_error_free (gerror);
1021       g_free (debug);
1022
1023       gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_ERROR);
1024       break;
1025     }
1026     case GST_MESSAGE_WARNING:
1027     {
1028       GError *gerror;
1029       gchar *debug;
1030
1031       gst_message_parse_warning (message, &gerror, &debug);
1032       GST_WARNING ("%p: got warning %s (%s)", media, gerror->message, debug);
1033       g_error_free (gerror);
1034       g_free (debug);
1035       break;
1036     }
1037     case GST_MESSAGE_ELEMENT:
1038       break;
1039     case GST_MESSAGE_STREAM_STATUS:
1040       break;
1041     case GST_MESSAGE_ASYNC_DONE:
1042       if (!media->adding) {
1043         /* when we are dynamically adding pads, the addition of the udpsrc will
1044          * temporarily produce ASYNC_DONE messages. We have to ignore them and
1045          * wait for the final ASYNC_DONE after everything prerolled */
1046         GST_INFO ("%p: got ASYNC_DONE", media);
1047         collect_media_stats (media);
1048
1049         gst_rtsp_media_set_status (media, GST_RTSP_MEDIA_STATUS_PREPARED);
1050       } else {
1051         GST_INFO ("%p: ignoring ASYNC_DONE", media);
1052       }
1053       break;
1054     case GST_MESSAGE_EOS:
1055       GST_INFO ("%p: got EOS", media);
1056
1057       if (media->status == GST_RTSP_MEDIA_STATUS_UNPREPARING) {
1058         GST_DEBUG ("shutting down after EOS");
1059         finish_unprepare (media);
1060         g_object_unref (media);
1061       }
1062       break;
1063     default:
1064       GST_INFO ("%p: got message type %s", media,
1065           gst_message_type_get_name (type));
1066       break;
1067   }
1068   return TRUE;
1069 }
1070
1071 static gboolean
1072 bus_message (GstBus * bus, GstMessage * message, GstRTSPMedia * media)
1073 {
1074   GstRTSPMediaClass *klass;
1075   gboolean ret;
1076
1077   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1078
1079   g_rec_mutex_lock (&media->state_lock);
1080   if (klass->handle_message)
1081     ret = klass->handle_message (media, message);
1082   else
1083     ret = FALSE;
1084   g_rec_mutex_unlock (&media->state_lock);
1085
1086   return ret;
1087 }
1088
1089 /* called from streaming threads */
1090 static void
1091 pad_added_cb (GstElement * element, GstPad * pad, GstRTSPMedia * media)
1092 {
1093   GstRTSPStream *stream;
1094
1095   /* FIXME, element is likely not a payloader, find the payloader here */
1096   stream = gst_rtsp_media_create_stream (media, element, pad);
1097
1098   GST_INFO ("pad added %s:%s, stream %d", GST_DEBUG_PAD_NAME (pad),
1099       stream->idx);
1100
1101   g_rec_mutex_lock (&media->state_lock);
1102   /* we will be adding elements below that will cause ASYNC_DONE to be
1103    * posted in the bus. We want to ignore those messages until the
1104    * pipeline really prerolled. */
1105   media->adding = TRUE;
1106
1107   /* join the element in the PAUSED state because this callback is
1108    * called from the streaming thread and it is PAUSED */
1109   gst_rtsp_stream_join_bin (stream, GST_BIN (media->pipeline),
1110       media->rtpbin, GST_STATE_PAUSED);
1111
1112   media->adding = FALSE;
1113   g_rec_mutex_unlock (&media->state_lock);
1114 }
1115
1116 static void
1117 no_more_pads_cb (GstElement * element, GstRTSPMedia * media)
1118 {
1119   GstElement *fakesink;
1120
1121   g_mutex_lock (&media->lock);
1122   GST_INFO ("no more pads");
1123   if ((fakesink = media->fakesink)) {
1124     gst_object_ref (fakesink);
1125     media->fakesink = NULL;
1126     g_mutex_unlock (&media->lock);
1127
1128     gst_bin_remove (GST_BIN (media->pipeline), fakesink);
1129     gst_element_set_state (fakesink, GST_STATE_NULL);
1130     gst_object_unref (fakesink);
1131     GST_INFO ("removed fakesink");
1132   }
1133 }
1134
1135 /**
1136  * gst_rtsp_media_prepare:
1137  * @media: a #GstRTSPMedia
1138  *
1139  * Prepare @media for streaming. This function will create the pipeline and
1140  * other objects to manage the streaming.
1141  *
1142  * It will preroll the pipeline and collect vital information about the streams
1143  * such as the duration.
1144  *
1145  * Returns: %TRUE on success.
1146  */
1147 gboolean
1148 gst_rtsp_media_prepare (GstRTSPMedia * media)
1149 {
1150   GstStateChangeReturn ret;
1151   GstRTSPMediaStatus status;
1152   guint i;
1153   GstRTSPMediaClass *klass;
1154   GstBus *bus;
1155   GList *walk;
1156
1157   g_rec_mutex_lock (&media->state_lock);
1158   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARED)
1159     goto was_prepared;
1160
1161   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARING)
1162     goto wait_status;
1163
1164   if (media->status != GST_RTSP_MEDIA_STATUS_UNPREPARED)
1165     goto not_unprepared;
1166
1167   if (!media->reusable && media->reused)
1168     goto is_reused;
1169
1170   media->rtpbin = gst_element_factory_make ("rtpbin", NULL);
1171   if (media->rtpbin == NULL)
1172     goto no_rtpbin;
1173
1174   GST_INFO ("preparing media %p", media);
1175
1176   /* reset some variables */
1177   media->is_live = FALSE;
1178   media->seekable = FALSE;
1179   media->buffering = FALSE;
1180   /* we're preparing now */
1181   media->status = GST_RTSP_MEDIA_STATUS_PREPARING;
1182
1183   bus = gst_pipeline_get_bus (GST_PIPELINE_CAST (media->pipeline));
1184
1185   /* add the pipeline bus to our custom mainloop */
1186   media->source = gst_bus_create_watch (bus);
1187   gst_object_unref (bus);
1188
1189   g_source_set_callback (media->source, (GSourceFunc) bus_message, media, NULL);
1190
1191   klass = GST_RTSP_MEDIA_GET_CLASS (media);
1192   media->id = g_source_attach (media->source, klass->context);
1193
1194   /* add stuff to the bin */
1195   gst_bin_add (GST_BIN (media->pipeline), media->rtpbin);
1196
1197   /* link streams we already have, other streams might appear when we have
1198    * dynamic elements */
1199   for (i = 0; i < media->streams->len; i++) {
1200     GstRTSPStream *stream;
1201
1202     stream = g_ptr_array_index (media->streams, i);
1203
1204     gst_rtsp_stream_join_bin (stream, GST_BIN (media->pipeline),
1205         media->rtpbin, GST_STATE_NULL);
1206   }
1207
1208   for (walk = media->dynamic; walk; walk = g_list_next (walk)) {
1209     GstElement *elem = walk->data;
1210
1211     GST_INFO ("adding callbacks for dynamic element %p", elem);
1212
1213     g_signal_connect (elem, "pad-added", (GCallback) pad_added_cb, media);
1214     g_signal_connect (elem, "no-more-pads", (GCallback) no_more_pads_cb, media);
1215
1216     /* we add a fakesink here in order to make the state change async. We remove
1217      * the fakesink again in the no-more-pads callback. */
1218     media->fakesink = gst_element_factory_make ("fakesink", "fakesink");
1219     gst_bin_add (GST_BIN (media->pipeline), media->fakesink);
1220   }
1221
1222   GST_INFO ("setting pipeline to PAUSED for media %p", media);
1223   /* first go to PAUSED */
1224   ret = gst_element_set_state (media->pipeline, GST_STATE_PAUSED);
1225   media->target_state = GST_STATE_PAUSED;
1226
1227   switch (ret) {
1228     case GST_STATE_CHANGE_SUCCESS:
1229       GST_INFO ("SUCCESS state change for media %p", media);
1230       media->seekable = TRUE;
1231       break;
1232     case GST_STATE_CHANGE_ASYNC:
1233       GST_INFO ("ASYNC state change for media %p", media);
1234       media->seekable = TRUE;
1235       break;
1236     case GST_STATE_CHANGE_NO_PREROLL:
1237       /* we need to go to PLAYING */
1238       GST_INFO ("NO_PREROLL state change: live media %p", media);
1239       /* FIXME we disable seeking for live streams for now. We should perform a
1240        * seeking query in preroll instead */
1241       media->seekable = FALSE;
1242       media->is_live = TRUE;
1243       ret = gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
1244       if (ret == GST_STATE_CHANGE_FAILURE)
1245         goto state_failed;
1246       break;
1247     case GST_STATE_CHANGE_FAILURE:
1248       goto state_failed;
1249   }
1250 wait_status:
1251   g_rec_mutex_unlock (&media->state_lock);
1252
1253   /* now wait for all pads to be prerolled, FIXME, we should somehow be
1254    * able to do this async so that we don't block the server thread. */
1255   status = gst_rtsp_media_get_status (media);
1256   if (status == GST_RTSP_MEDIA_STATUS_ERROR)
1257     goto state_failed;
1258
1259   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_PREPARED], 0, NULL);
1260
1261   GST_INFO ("object %p is prerolled", media);
1262
1263   return TRUE;
1264
1265   /* OK */
1266 was_prepared:
1267   {
1268     GST_LOG ("media %p was prepared", media);
1269     g_rec_mutex_unlock (&media->state_lock);
1270     return TRUE;
1271   }
1272   /* ERRORS */
1273 not_unprepared:
1274   {
1275     GST_WARNING ("media %p was not unprepared", media);
1276     g_rec_mutex_unlock (&media->state_lock);
1277     return FALSE;
1278   }
1279 is_reused:
1280   {
1281     g_rec_mutex_unlock (&media->state_lock);
1282     GST_WARNING ("can not reuse media %p", media);
1283     return FALSE;
1284   }
1285 no_rtpbin:
1286   {
1287     g_rec_mutex_unlock (&media->state_lock);
1288     GST_WARNING ("no rtpbin element");
1289     g_warning ("failed to create element 'rtpbin', check your installation");
1290     return FALSE;
1291   }
1292 state_failed:
1293   {
1294     GST_WARNING ("failed to preroll pipeline");
1295     gst_rtsp_media_unprepare (media);
1296     g_rec_mutex_unlock (&media->state_lock);
1297     return FALSE;
1298   }
1299 }
1300
1301 /* must be called with state-lock */
1302 static void
1303 finish_unprepare (GstRTSPMedia * media)
1304 {
1305   gint i;
1306
1307   GST_DEBUG ("shutting down");
1308
1309   gst_element_set_state (media->pipeline, GST_STATE_NULL);
1310
1311   for (i = 0; i < media->streams->len; i++) {
1312     GstRTSPStream *stream;
1313
1314     GST_INFO ("Removing elements of stream %d from pipeline", i);
1315
1316     stream = g_ptr_array_index (media->streams, i);
1317
1318     gst_rtsp_stream_leave_bin (stream, GST_BIN (media->pipeline),
1319         media->rtpbin);
1320   }
1321   g_ptr_array_set_size (media->streams, 0);
1322
1323   gst_bin_remove (GST_BIN (media->pipeline), media->rtpbin);
1324   media->rtpbin = NULL;
1325
1326   gst_object_unref (media->pipeline);
1327   media->pipeline = NULL;
1328
1329   media->reused = TRUE;
1330   media->status = GST_RTSP_MEDIA_STATUS_UNPREPARED;
1331
1332   /* when the media is not reusable, this will effectively unref the media and
1333    * recreate it */
1334   g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_UNPREPARED], 0, NULL);
1335 }
1336
1337 /* called with state-lock */
1338 static gboolean
1339 default_unprepare (GstRTSPMedia * media)
1340 {
1341   if (media->eos_shutdown) {
1342     GST_DEBUG ("sending EOS for shutdown");
1343     /* ref so that we don't disappear */
1344     g_object_ref (media);
1345     gst_element_send_event (media->pipeline, gst_event_new_eos ());
1346     /* we need to go to playing again for the EOS to propagate, normally in this
1347      * state, nothing is receiving data from us anymore so this is ok. */
1348     gst_element_set_state (media->pipeline, GST_STATE_PLAYING);
1349     media->status = GST_RTSP_MEDIA_STATUS_UNPREPARING;
1350   } else {
1351     finish_unprepare (media);
1352   }
1353   return TRUE;
1354 }
1355
1356 /**
1357  * gst_rtsp_media_unprepare:
1358  * @media: a #GstRTSPMedia
1359  *
1360  * Unprepare @media. After this call, the media should be prepared again before
1361  * it can be used again. If the media is set to be non-reusable, a new instance
1362  * must be created.
1363  *
1364  * Returns: %TRUE on success.
1365  */
1366 gboolean
1367 gst_rtsp_media_unprepare (GstRTSPMedia * media)
1368 {
1369   gboolean success;
1370
1371   g_rec_mutex_lock (&media->state_lock);
1372   if (media->status == GST_RTSP_MEDIA_STATUS_UNPREPARED)
1373     goto was_unprepared;
1374
1375   GST_INFO ("unprepare media %p", media);
1376   media->target_state = GST_STATE_NULL;
1377   success = TRUE;
1378
1379   if (media->status == GST_RTSP_MEDIA_STATUS_PREPARED) {
1380     GstRTSPMediaClass *klass;
1381
1382     klass = GST_RTSP_MEDIA_GET_CLASS (media);
1383     if (klass->unprepare)
1384       success = klass->unprepare (media);
1385   } else {
1386     finish_unprepare (media);
1387   }
1388   g_rec_mutex_unlock (&media->state_lock);
1389
1390   return success;
1391
1392 was_unprepared:
1393   {
1394     g_rec_mutex_unlock (&media->state_lock);
1395     GST_INFO ("media %p was already unprepared", media);
1396     return TRUE;
1397   }
1398 }
1399
1400 /**
1401  * gst_rtsp_media_set_state:
1402  * @media: a #GstRTSPMedia
1403  * @state: the target state of the media
1404  * @transports: a #GPtrArray of #GstRTSPStreamTransport pointers
1405  *
1406  * Set the state of @media to @state and for the transports in @transports.
1407  *
1408  * Returns: %TRUE on success.
1409  */
1410 gboolean
1411 gst_rtsp_media_set_state (GstRTSPMedia * media, GstState state,
1412     GPtrArray * transports)
1413 {
1414   gint i;
1415   gboolean add, remove, do_state;
1416   gint old_active;
1417
1418   g_return_val_if_fail (GST_IS_RTSP_MEDIA (media), FALSE);
1419   g_return_val_if_fail (transports != NULL, FALSE);
1420
1421   g_rec_mutex_lock (&media->state_lock);
1422
1423   /* NULL and READY are the same */
1424   if (state == GST_STATE_READY)
1425     state = GST_STATE_NULL;
1426
1427   add = remove = FALSE;
1428
1429   GST_INFO ("going to state %s media %p", gst_element_state_get_name (state),
1430       media);
1431
1432   switch (state) {
1433     case GST_STATE_NULL:
1434     case GST_STATE_PAUSED:
1435       /* we're going from PLAYING to PAUSED, READY or NULL, remove */
1436       if (media->target_state == GST_STATE_PLAYING)
1437         remove = TRUE;
1438       break;
1439     case GST_STATE_PLAYING:
1440       /* we're going to PLAYING, add */
1441       add = TRUE;
1442       break;
1443     default:
1444       break;
1445   }
1446   old_active = media->n_active;
1447
1448   for (i = 0; i < transports->len; i++) {
1449     GstRTSPStreamTransport *trans;
1450
1451     /* we need a non-NULL entry in the array */
1452     trans = g_ptr_array_index (transports, i);
1453     if (trans == NULL)
1454       continue;
1455
1456     /* we need a transport */
1457     if (!trans->transport)
1458       continue;
1459
1460     if (add) {
1461       if (gst_rtsp_stream_add_transport (trans->stream, trans))
1462         media->n_active++;
1463     } else if (remove) {
1464       if (gst_rtsp_stream_remove_transport (trans->stream, trans))
1465         media->n_active--;
1466     }
1467   }
1468
1469   /* we just added the first media, do the playing state change */
1470   if (old_active == 0 && add)
1471     do_state = TRUE;
1472   /* if we have no more active media, do the downward state changes */
1473   else if (media->n_active == 0)
1474     do_state = TRUE;
1475   else
1476     do_state = FALSE;
1477
1478   GST_INFO ("state %d active %d media %p do_state %d", state, media->n_active,
1479       media, do_state);
1480
1481   if (media->target_state != state) {
1482     if (do_state) {
1483       if (state == GST_STATE_NULL) {
1484         gst_rtsp_media_unprepare (media);
1485       } else {
1486         GST_INFO ("state %s media %p", gst_element_state_get_name (state),
1487             media);
1488         media->target_state = state;
1489         gst_element_set_state (media->pipeline, state);
1490       }
1491     }
1492     g_signal_emit (media, gst_rtsp_media_signals[SIGNAL_NEW_STATE], 0, state,
1493         NULL);
1494   }
1495
1496   /* remember where we are */
1497   if (state != GST_STATE_NULL && (state == GST_STATE_PAUSED ||
1498           old_active != media->n_active))
1499     collect_media_stats (media);
1500
1501   g_rec_mutex_unlock (&media->state_lock);
1502
1503   return TRUE;
1504 }