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