rtsp-stream: fix get_rates raciness
[platform/upstream/gstreamer.git] / subprojects / gst-rtsp-server / gst / rtsp-server / rtsp-stream.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  * Copyright (C) 2015 Centricular Ltd
4  *     Author: Sebastian Dröge <sebastian@centricular.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /**
22  * SECTION:rtsp-stream
23  * @short_description: A media stream
24  * @see_also: #GstRTSPMedia
25  *
26  * The #GstRTSPStream object manages the data transport for one stream. It
27  * is created from a payloader element and a source pad that produce the RTP
28  * packets for the stream.
29  *
30  * With gst_rtsp_stream_join_bin() the streaming elements are added to the bin
31  * and rtpbin. gst_rtsp_stream_leave_bin() removes the elements again.
32  *
33  * The #GstRTSPStream will use the configured addresspool, as set with
34  * gst_rtsp_stream_set_address_pool(), to allocate multicast addresses for the
35  * stream. With gst_rtsp_stream_get_multicast_address() you can get the
36  * configured address.
37  *
38  * With gst_rtsp_stream_get_server_port () you can get the port that the server
39  * will use to receive RTCP. This is the part that the clients will use to send
40  * RTCP to.
41  *
42  * With gst_rtsp_stream_add_transport() destinations can be added where the
43  * stream should be sent to. Use gst_rtsp_stream_remove_transport() to remove
44  * the destination again.
45  *
46  * Each #GstRTSPStreamTransport spawns one queue that will serve as a backlog of a
47  * controllable maximum size when the reflux from the TCP connection's backpressure
48  * starts spilling all over.
49  *
50  * Unlike the backlog in rtspconnection, which we have decided should only contain
51  * at most one RTP and one RTCP data message in order to allow control messages to
52  * go through unobstructed, this backlog only consists of data messages, allowing
53  * us to fill it up without concern.
54  *
55  * When multiple TCP transports exist, for example in the context of a shared media,
56  * we only pop samples from our appsinks when at least one of the transports doesn't
57  * experience back pressure: this allows us to pace our sample popping to the speed
58  * of the fastest client.
59  *
60  * When a sample is popped, it is either sent directly on transports that don't
61  * experience backpressure, or queued on the transport's backlog otherwise. Samples
62  * are then popped from that backlog when the transport reports it has sent the message.
63  *
64  * Once the backlog reaches an overly large duration, the transport is dropped as
65  * the client was deemed too slow.
66  */
67 #ifdef HAVE_CONFIG_H
68 #include "config.h"
69 #endif
70
71 #include <stdlib.h>
72 #include <stdio.h>
73 #include <string.h>
74
75 #include <gio/gio.h>
76
77 #include <gst/app/gstappsrc.h>
78 #include <gst/app/gstappsink.h>
79
80 #include <gst/rtp/gstrtpbuffer.h>
81
82 #include "rtsp-stream.h"
83 #include "rtsp-server-internal.h"
84
85 struct _GstRTSPStreamPrivate
86 {
87   GMutex lock;
88   guint idx;
89   /* Only one pad is ever set */
90   GstPad *srcpad, *sinkpad;
91   GstElement *payloader;
92   guint buffer_size;
93   GstBin *joined_bin;
94
95   /* TRUE if this stream is running on
96    * the client side of an RTSP link (for RECORD) */
97   gboolean client_side;
98   gchar *control;
99
100   /* TRUE if stream is complete. This means that the receiver and the sender
101    * parts are present in the stream. */
102   gboolean is_complete;
103   GstRTSPProfile profiles;
104   GstRTSPLowerTrans allowed_protocols;
105   GstRTSPLowerTrans configured_protocols;
106
107   /* pads on the rtpbin */
108   GstPad *send_rtp_sink;
109   GstPad *recv_rtp_src;
110   GstPad *recv_sink[2];
111   GstPad *send_src[2];
112
113   /* the RTPSession object */
114   GObject *session;
115
116   /* SRTP encoder/decoder */
117   GstElement *srtpenc;
118   GstElement *srtpdec;
119   GHashTable *keys;
120
121   /* for UDP unicast */
122   GstElement *udpsrc_v4[2];
123   GstElement *udpsrc_v6[2];
124   GstElement *udpqueue[2];
125   GstElement *udpsink[2];
126   GSocket *socket_v4[2];
127   GSocket *socket_v6[2];
128
129   /* for UDP multicast */
130   GstElement *mcast_udpsrc_v4[2];
131   GstElement *mcast_udpsrc_v6[2];
132   GstElement *mcast_udpqueue[2];
133   GstElement *mcast_udpsink[2];
134   GSocket *mcast_socket_v4[2];
135   GSocket *mcast_socket_v6[2];
136   GList *mcast_clients;
137
138   /* for TCP transport */
139   GstElement *appsrc[2];
140   GstClockTime appsrc_base_time[2];
141   GstElement *appqueue[2];
142   GstElement *appsink[2];
143
144   GstElement *tee[2];
145   GstElement *funnel[2];
146
147   /* retransmission */
148   GstElement *rtxsend;
149   GstElement *rtxreceive;
150   guint rtx_pt;
151   GstClockTime rtx_time;
152
153   /* rate control */
154   gboolean do_rate_control;
155
156   /* Forward Error Correction with RFC 5109 */
157   GstElement *ulpfec_decoder;
158   GstElement *ulpfec_encoder;
159   guint ulpfec_pt;
160   gboolean ulpfec_enabled;
161   guint ulpfec_percentage;
162
163   /* pool used to manage unicast and multicast addresses */
164   GstRTSPAddressPool *pool;
165
166   /* unicast server addr/port */
167   GstRTSPAddress *server_addr_v4;
168   GstRTSPAddress *server_addr_v6;
169
170   /* multicast addresses */
171   GstRTSPAddress *mcast_addr_v4;
172   GstRTSPAddress *mcast_addr_v6;
173
174   gchar *multicast_iface;
175   guint max_mcast_ttl;
176   gboolean bind_mcast_address;
177
178   /* the caps of the stream */
179   gulong caps_sig;
180   GstCaps *caps;
181
182   /* transports we stream to */
183   guint n_active;
184   GList *transports;
185   guint transports_cookie;
186   GPtrArray *tr_cache;
187   guint tr_cache_cookie;
188   guint n_tcp_transports;
189   gboolean have_buffer[2];
190
191   gint dscp_qos;
192
193   /* Sending logic for TCP */
194   GThread *send_thread;
195   GCond send_cond;
196   GMutex send_lock;
197   /* @send_lock is released when pushing data out, we use
198    * a cookie to decide whether we should wait on @send_cond
199    * before checking the transports' backlogs again
200    */
201   guint send_cookie;
202   /* Used to control shutdown of @send_thread */
203   gboolean continue_sending;
204
205   /* stream blocking */
206   gulong blocked_id[2];
207   gboolean blocking;
208
209   /* current stream postion */
210   GstClockTime position;
211
212   /* pt->caps map for RECORD streams */
213   GHashTable *ptmap;
214
215   GstRTSPPublishClockMode publish_clock_mode;
216   GThreadPool *send_pool;
217
218   /* Used to provide accurate rtpinfo when the stream is blocking */
219   gboolean blocked_buffer;
220   guint32 blocked_seqnum;
221   guint32 blocked_rtptime;
222   GstClockTime blocked_running_time;
223   gint blocked_clock_rate;
224
225   /* Whether we should send and receive RTCP */
226   gboolean enable_rtcp;
227
228   /* blocking early rtcp packets */
229   GstPad *block_early_rtcp_pad;
230   gulong block_early_rtcp_probe;
231   GstPad *block_early_rtcp_pad_ipv6;
232   gulong block_early_rtcp_probe_ipv6;
233 };
234
235 #define DEFAULT_CONTROL         NULL
236 #define DEFAULT_PROFILES        GST_RTSP_PROFILE_AVP
237 #define DEFAULT_PROTOCOLS       GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | \
238                                         GST_RTSP_LOWER_TRANS_TCP
239 #define DEFAULT_MAX_MCAST_TTL   255
240 #define DEFAULT_BIND_MCAST_ADDRESS FALSE
241 #define DEFAULT_DO_RATE_CONTROL TRUE
242 #define DEFAULT_ENABLE_RTCP TRUE
243
244 enum
245 {
246   PROP_0,
247   PROP_CONTROL,
248   PROP_PROFILES,
249   PROP_PROTOCOLS,
250   PROP_LAST
251 };
252
253 enum
254 {
255   SIGNAL_NEW_RTP_ENCODER,
256   SIGNAL_NEW_RTCP_ENCODER,
257   SIGNAL_NEW_RTP_RTCP_DECODER,
258   SIGNAL_LAST
259 };
260
261 GST_DEBUG_CATEGORY_STATIC (rtsp_stream_debug);
262 #define GST_CAT_DEFAULT rtsp_stream_debug
263
264 static GQuark ssrc_stream_map_key;
265
266 static void gst_rtsp_stream_get_property (GObject * object, guint propid,
267     GValue * value, GParamSpec * pspec);
268 static void gst_rtsp_stream_set_property (GObject * object, guint propid,
269     const GValue * value, GParamSpec * pspec);
270
271 static void gst_rtsp_stream_finalize (GObject * obj);
272
273 static gboolean
274 update_transport (GstRTSPStream * stream, GstRTSPStreamTransport * trans,
275     gboolean add);
276
277 static guint gst_rtsp_stream_signals[SIGNAL_LAST] = { 0 };
278
279 G_DEFINE_TYPE_WITH_PRIVATE (GstRTSPStream, gst_rtsp_stream, G_TYPE_OBJECT);
280
281 static void
282 gst_rtsp_stream_class_init (GstRTSPStreamClass * klass)
283 {
284   GObjectClass *gobject_class;
285
286   gobject_class = G_OBJECT_CLASS (klass);
287
288   gobject_class->get_property = gst_rtsp_stream_get_property;
289   gobject_class->set_property = gst_rtsp_stream_set_property;
290   gobject_class->finalize = gst_rtsp_stream_finalize;
291
292   g_object_class_install_property (gobject_class, PROP_CONTROL,
293       g_param_spec_string ("control", "Control",
294           "The control string for this stream", DEFAULT_CONTROL,
295           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
296
297   g_object_class_install_property (gobject_class, PROP_PROFILES,
298       g_param_spec_flags ("profiles", "Profiles",
299           "Allowed transfer profiles", GST_TYPE_RTSP_PROFILE,
300           DEFAULT_PROFILES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
301
302   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
303       g_param_spec_flags ("protocols", "Protocols",
304           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
305           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306
307   gst_rtsp_stream_signals[SIGNAL_NEW_RTP_ENCODER] =
308       g_signal_new ("new-rtp-encoder", G_TYPE_FROM_CLASS (klass),
309       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
310
311   gst_rtsp_stream_signals[SIGNAL_NEW_RTCP_ENCODER] =
312       g_signal_new ("new-rtcp-encoder", G_TYPE_FROM_CLASS (klass),
313       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
314
315   gst_rtsp_stream_signals[SIGNAL_NEW_RTP_RTCP_DECODER] =
316       g_signal_new ("new-rtp-rtcp-decoder", G_TYPE_FROM_CLASS (klass),
317       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
318
319   GST_DEBUG_CATEGORY_INIT (rtsp_stream_debug, "rtspstream", 0, "GstRTSPStream");
320
321   ssrc_stream_map_key = g_quark_from_static_string ("GstRTSPServer.stream");
322 }
323
324 static void
325 gst_rtsp_stream_init (GstRTSPStream * stream)
326 {
327   GstRTSPStreamPrivate *priv = gst_rtsp_stream_get_instance_private (stream);
328
329   GST_DEBUG ("new stream %p", stream);
330
331   stream->priv = priv;
332
333   priv->dscp_qos = -1;
334   priv->control = g_strdup (DEFAULT_CONTROL);
335   priv->profiles = DEFAULT_PROFILES;
336   priv->allowed_protocols = DEFAULT_PROTOCOLS;
337   priv->configured_protocols = 0;
338   priv->publish_clock_mode = GST_RTSP_PUBLISH_CLOCK_MODE_CLOCK;
339   priv->max_mcast_ttl = DEFAULT_MAX_MCAST_TTL;
340   priv->bind_mcast_address = DEFAULT_BIND_MCAST_ADDRESS;
341   priv->do_rate_control = DEFAULT_DO_RATE_CONTROL;
342   priv->enable_rtcp = DEFAULT_ENABLE_RTCP;
343
344   g_mutex_init (&priv->lock);
345
346   priv->continue_sending = TRUE;
347   priv->send_cookie = 0;
348   g_cond_init (&priv->send_cond);
349   g_mutex_init (&priv->send_lock);
350
351   priv->keys = g_hash_table_new_full (g_direct_hash, g_direct_equal,
352       NULL, (GDestroyNotify) gst_caps_unref);
353   priv->ptmap = g_hash_table_new_full (NULL, NULL, NULL,
354       (GDestroyNotify) gst_caps_unref);
355   priv->send_pool = NULL;
356   priv->block_early_rtcp_pad = NULL;
357   priv->block_early_rtcp_probe = 0;
358   priv->block_early_rtcp_pad_ipv6 = NULL;
359   priv->block_early_rtcp_probe_ipv6 = 0;
360 }
361
362 typedef struct _UdpClientAddrInfo UdpClientAddrInfo;
363
364 struct _UdpClientAddrInfo
365 {
366   gchar *address;
367   guint rtp_port;
368   guint add_count;              /* how often this address has been added */
369 };
370
371 static void
372 free_mcast_client (gpointer data)
373 {
374   UdpClientAddrInfo *client = data;
375
376   g_free (client->address);
377   g_free (client);
378 }
379
380 static void
381 gst_rtsp_stream_finalize (GObject * obj)
382 {
383   GstRTSPStream *stream;
384   GstRTSPStreamPrivate *priv;
385   guint i;
386
387   stream = GST_RTSP_STREAM (obj);
388   priv = stream->priv;
389
390   GST_DEBUG ("finalize stream %p", stream);
391
392   /* we really need to be unjoined now */
393   g_return_if_fail (priv->joined_bin == NULL);
394
395   if (priv->send_pool)
396     g_thread_pool_free (priv->send_pool, TRUE, TRUE);
397   if (priv->mcast_addr_v4)
398     gst_rtsp_address_free (priv->mcast_addr_v4);
399   if (priv->mcast_addr_v6)
400     gst_rtsp_address_free (priv->mcast_addr_v6);
401   if (priv->server_addr_v4)
402     gst_rtsp_address_free (priv->server_addr_v4);
403   if (priv->server_addr_v6)
404     gst_rtsp_address_free (priv->server_addr_v6);
405   if (priv->pool)
406     g_object_unref (priv->pool);
407   if (priv->rtxsend)
408     g_object_unref (priv->rtxsend);
409   if (priv->rtxreceive)
410     g_object_unref (priv->rtxreceive);
411   if (priv->ulpfec_encoder)
412     gst_object_unref (priv->ulpfec_encoder);
413   if (priv->ulpfec_decoder)
414     gst_object_unref (priv->ulpfec_decoder);
415
416   for (i = 0; i < 2; i++) {
417     if (priv->socket_v4[i])
418       g_object_unref (priv->socket_v4[i]);
419     if (priv->socket_v6[i])
420       g_object_unref (priv->socket_v6[i]);
421     if (priv->mcast_socket_v4[i])
422       g_object_unref (priv->mcast_socket_v4[i]);
423     if (priv->mcast_socket_v6[i])
424       g_object_unref (priv->mcast_socket_v6[i]);
425   }
426
427   g_free (priv->multicast_iface);
428   g_list_free_full (priv->mcast_clients, (GDestroyNotify) free_mcast_client);
429
430   gst_object_unref (priv->payloader);
431   if (priv->srcpad)
432     gst_object_unref (priv->srcpad);
433   if (priv->sinkpad)
434     gst_object_unref (priv->sinkpad);
435   g_free (priv->control);
436   g_mutex_clear (&priv->lock);
437
438   g_hash_table_unref (priv->keys);
439   g_hash_table_destroy (priv->ptmap);
440
441   g_mutex_clear (&priv->send_lock);
442   g_cond_clear (&priv->send_cond);
443
444   if (priv->block_early_rtcp_probe != 0) {
445     gst_pad_remove_probe
446         (priv->block_early_rtcp_pad, priv->block_early_rtcp_probe);
447     gst_object_unref (priv->block_early_rtcp_pad);
448   }
449
450   if (priv->block_early_rtcp_probe_ipv6 != 0) {
451     gst_pad_remove_probe
452         (priv->block_early_rtcp_pad_ipv6, priv->block_early_rtcp_probe_ipv6);
453     gst_object_unref (priv->block_early_rtcp_pad_ipv6);
454   }
455
456   G_OBJECT_CLASS (gst_rtsp_stream_parent_class)->finalize (obj);
457 }
458
459 static void
460 gst_rtsp_stream_get_property (GObject * object, guint propid,
461     GValue * value, GParamSpec * pspec)
462 {
463   GstRTSPStream *stream = GST_RTSP_STREAM (object);
464
465   switch (propid) {
466     case PROP_CONTROL:
467       g_value_take_string (value, gst_rtsp_stream_get_control (stream));
468       break;
469     case PROP_PROFILES:
470       g_value_set_flags (value, gst_rtsp_stream_get_profiles (stream));
471       break;
472     case PROP_PROTOCOLS:
473       g_value_set_flags (value, gst_rtsp_stream_get_protocols (stream));
474       break;
475     default:
476       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
477   }
478 }
479
480 static void
481 gst_rtsp_stream_set_property (GObject * object, guint propid,
482     const GValue * value, GParamSpec * pspec)
483 {
484   GstRTSPStream *stream = GST_RTSP_STREAM (object);
485
486   switch (propid) {
487     case PROP_CONTROL:
488       gst_rtsp_stream_set_control (stream, g_value_get_string (value));
489       break;
490     case PROP_PROFILES:
491       gst_rtsp_stream_set_profiles (stream, g_value_get_flags (value));
492       break;
493     case PROP_PROTOCOLS:
494       gst_rtsp_stream_set_protocols (stream, g_value_get_flags (value));
495       break;
496     default:
497       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
498   }
499 }
500
501 /**
502  * gst_rtsp_stream_new:
503  * @idx: an index
504  * @pad: a #GstPad
505  * @payloader: a #GstElement
506  *
507  * Create a new media stream with index @idx that handles RTP data on
508  * @pad and has a payloader element @payloader if @pad is a source pad
509  * or a depayloader element @payloader if @pad is a sink pad.
510  *
511  * Returns: (transfer full): a new #GstRTSPStream
512  */
513 GstRTSPStream *
514 gst_rtsp_stream_new (guint idx, GstElement * payloader, GstPad * pad)
515 {
516   GstRTSPStreamPrivate *priv;
517   GstRTSPStream *stream;
518
519   g_return_val_if_fail (GST_IS_ELEMENT (payloader), NULL);
520   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
521
522   stream = g_object_new (GST_TYPE_RTSP_STREAM, NULL);
523   priv = stream->priv;
524   priv->idx = idx;
525   priv->payloader = gst_object_ref (payloader);
526   if (GST_PAD_IS_SRC (pad))
527     priv->srcpad = gst_object_ref (pad);
528   else
529     priv->sinkpad = gst_object_ref (pad);
530
531   return stream;
532 }
533
534 /**
535  * gst_rtsp_stream_get_index:
536  * @stream: a #GstRTSPStream
537  *
538  * Get the stream index.
539  *
540  * Return: the stream index.
541  */
542 guint
543 gst_rtsp_stream_get_index (GstRTSPStream * stream)
544 {
545   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), -1);
546
547   return stream->priv->idx;
548 }
549
550 /**
551  * gst_rtsp_stream_get_pt:
552  * @stream: a #GstRTSPStream
553  *
554  * Get the stream payload type.
555  *
556  * Return: the stream payload type.
557  */
558 guint
559 gst_rtsp_stream_get_pt (GstRTSPStream * stream)
560 {
561   GstRTSPStreamPrivate *priv;
562   guint pt;
563
564   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), -1);
565
566   priv = stream->priv;
567
568   g_object_get (G_OBJECT (priv->payloader), "pt", &pt, NULL);
569
570   return pt;
571 }
572
573 /**
574  * gst_rtsp_stream_get_srcpad:
575  * @stream: a #GstRTSPStream
576  *
577  * Get the srcpad associated with @stream.
578  *
579  * Returns: (transfer full) (nullable): the srcpad. Unref after usage.
580  */
581 GstPad *
582 gst_rtsp_stream_get_srcpad (GstRTSPStream * stream)
583 {
584   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
585
586   if (!stream->priv->srcpad)
587     return NULL;
588
589   return gst_object_ref (stream->priv->srcpad);
590 }
591
592 /**
593  * gst_rtsp_stream_get_sinkpad:
594  * @stream: a #GstRTSPStream
595  *
596  * Get the sinkpad associated with @stream.
597  *
598  * Returns: (transfer full) (nullable): the sinkpad. Unref after usage.
599  */
600 GstPad *
601 gst_rtsp_stream_get_sinkpad (GstRTSPStream * stream)
602 {
603   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
604
605   if (!stream->priv->sinkpad)
606     return NULL;
607
608   return gst_object_ref (stream->priv->sinkpad);
609 }
610
611 /**
612  * gst_rtsp_stream_get_control:
613  * @stream: a #GstRTSPStream
614  *
615  * Get the control string to identify this stream.
616  *
617  * Returns: (transfer full) (nullable): the control string. g_free() after usage.
618  */
619 gchar *
620 gst_rtsp_stream_get_control (GstRTSPStream * stream)
621 {
622   GstRTSPStreamPrivate *priv;
623   gchar *result;
624
625   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
626
627   priv = stream->priv;
628
629   g_mutex_lock (&priv->lock);
630   if ((result = g_strdup (priv->control)) == NULL)
631     result = g_strdup_printf ("stream=%u", priv->idx);
632   g_mutex_unlock (&priv->lock);
633
634   return result;
635 }
636
637 /**
638  * gst_rtsp_stream_set_control:
639  * @stream: a #GstRTSPStream
640  * @control: (nullable): a control string
641  *
642  * Set the control string in @stream.
643  */
644 void
645 gst_rtsp_stream_set_control (GstRTSPStream * stream, const gchar * control)
646 {
647   GstRTSPStreamPrivate *priv;
648
649   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
650
651   priv = stream->priv;
652
653   g_mutex_lock (&priv->lock);
654   g_free (priv->control);
655   priv->control = g_strdup (control);
656   g_mutex_unlock (&priv->lock);
657 }
658
659 /**
660  * gst_rtsp_stream_has_control:
661  * @stream: a #GstRTSPStream
662  * @control: (nullable): a control string
663  *
664  * Check if @stream has the control string @control.
665  *
666  * Returns: %TRUE is @stream has @control as the control string
667  */
668 gboolean
669 gst_rtsp_stream_has_control (GstRTSPStream * stream, const gchar * control)
670 {
671   GstRTSPStreamPrivate *priv;
672   gboolean res;
673
674   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
675
676   priv = stream->priv;
677
678   g_mutex_lock (&priv->lock);
679   if (priv->control)
680     res = (g_strcmp0 (priv->control, control) == 0);
681   else {
682     guint streamid;
683
684     if (sscanf (control, "stream=%u", &streamid) > 0)
685       res = (streamid == priv->idx);
686     else
687       res = FALSE;
688   }
689   g_mutex_unlock (&priv->lock);
690
691   return res;
692 }
693
694 /**
695  * gst_rtsp_stream_set_mtu:
696  * @stream: a #GstRTSPStream
697  * @mtu: a new MTU
698  *
699  * Configure the mtu in the payloader of @stream to @mtu.
700  */
701 void
702 gst_rtsp_stream_set_mtu (GstRTSPStream * stream, guint mtu)
703 {
704   GstRTSPStreamPrivate *priv;
705
706   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
707
708   priv = stream->priv;
709
710   GST_LOG_OBJECT (stream, "set MTU %u", mtu);
711
712   g_object_set (G_OBJECT (priv->payloader), "mtu", mtu, NULL);
713 }
714
715 /**
716  * gst_rtsp_stream_get_mtu:
717  * @stream: a #GstRTSPStream
718  *
719  * Get the configured MTU in the payloader of @stream.
720  *
721  * Returns: the MTU of the payloader.
722  */
723 guint
724 gst_rtsp_stream_get_mtu (GstRTSPStream * stream)
725 {
726   GstRTSPStreamPrivate *priv;
727   guint mtu;
728
729   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);
730
731   priv = stream->priv;
732
733   g_object_get (G_OBJECT (priv->payloader), "mtu", &mtu, NULL);
734
735   return mtu;
736 }
737
738 /* Update the dscp qos property on the udp sinks */
739 static void
740 update_dscp_qos (GstRTSPStream * stream, GstElement ** udpsink)
741 {
742   GstRTSPStreamPrivate *priv;
743
744   priv = stream->priv;
745
746   if (*udpsink) {
747     g_object_set (G_OBJECT (*udpsink), "qos-dscp", priv->dscp_qos, NULL);
748   }
749 }
750
751 /**
752  * gst_rtsp_stream_set_dscp_qos:
753  * @stream: a #GstRTSPStream
754  * @dscp_qos: a new dscp qos value (0-63, or -1 to disable)
755  *
756  * Configure the dscp qos of the outgoing sockets to @dscp_qos.
757  */
758 void
759 gst_rtsp_stream_set_dscp_qos (GstRTSPStream * stream, gint dscp_qos)
760 {
761   GstRTSPStreamPrivate *priv;
762
763   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
764
765   priv = stream->priv;
766
767   GST_LOG_OBJECT (stream, "set DSCP QoS %d", dscp_qos);
768
769   if (dscp_qos < -1 || dscp_qos > 63) {
770     GST_WARNING_OBJECT (stream, "trying to set illegal dscp qos %d", dscp_qos);
771     return;
772   }
773
774   priv->dscp_qos = dscp_qos;
775
776   update_dscp_qos (stream, priv->udpsink);
777 }
778
779 /**
780  * gst_rtsp_stream_get_dscp_qos:
781  * @stream: a #GstRTSPStream
782  *
783  * Get the configured DSCP QoS in of the outgoing sockets.
784  *
785  * Returns: the DSCP QoS value of the outgoing sockets, or -1 if disbled.
786  */
787 gint
788 gst_rtsp_stream_get_dscp_qos (GstRTSPStream * stream)
789 {
790   GstRTSPStreamPrivate *priv;
791
792   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), -1);
793
794   priv = stream->priv;
795
796   return priv->dscp_qos;
797 }
798
799 /**
800  * gst_rtsp_stream_is_transport_supported:
801  * @stream: a #GstRTSPStream
802  * @transport: (transfer none): a #GstRTSPTransport
803  *
804  * Check if @transport can be handled by stream
805  *
806  * Returns: %TRUE if @transport can be handled by @stream.
807  */
808 gboolean
809 gst_rtsp_stream_is_transport_supported (GstRTSPStream * stream,
810     GstRTSPTransport * transport)
811 {
812   GstRTSPStreamPrivate *priv;
813
814   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
815   g_return_val_if_fail (transport != NULL, FALSE);
816
817   priv = stream->priv;
818
819   g_mutex_lock (&priv->lock);
820   if (transport->trans != GST_RTSP_TRANS_RTP)
821     goto unsupported_transmode;
822
823   if (!(transport->profile & priv->profiles))
824     goto unsupported_profile;
825
826   if (!(transport->lower_transport & priv->allowed_protocols))
827     goto unsupported_ltrans;
828
829   g_mutex_unlock (&priv->lock);
830
831   return TRUE;
832
833   /* ERRORS */
834 unsupported_transmode:
835   {
836     GST_DEBUG ("unsupported transport mode %d", transport->trans);
837     g_mutex_unlock (&priv->lock);
838     return FALSE;
839   }
840 unsupported_profile:
841   {
842     GST_DEBUG ("unsupported profile %d", transport->profile);
843     g_mutex_unlock (&priv->lock);
844     return FALSE;
845   }
846 unsupported_ltrans:
847   {
848     GST_DEBUG ("unsupported lower transport %d", transport->lower_transport);
849     g_mutex_unlock (&priv->lock);
850     return FALSE;
851   }
852 }
853
854 /**
855  * gst_rtsp_stream_set_profiles:
856  * @stream: a #GstRTSPStream
857  * @profiles: the new profiles
858  *
859  * Configure the allowed profiles for @stream.
860  */
861 void
862 gst_rtsp_stream_set_profiles (GstRTSPStream * stream, GstRTSPProfile profiles)
863 {
864   GstRTSPStreamPrivate *priv;
865
866   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
867
868   priv = stream->priv;
869
870   g_mutex_lock (&priv->lock);
871   priv->profiles = profiles;
872   g_mutex_unlock (&priv->lock);
873 }
874
875 /**
876  * gst_rtsp_stream_get_profiles:
877  * @stream: a #GstRTSPStream
878  *
879  * Get the allowed profiles of @stream.
880  *
881  * Returns: a #GstRTSPProfile
882  */
883 GstRTSPProfile
884 gst_rtsp_stream_get_profiles (GstRTSPStream * stream)
885 {
886   GstRTSPStreamPrivate *priv;
887   GstRTSPProfile res;
888
889   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), GST_RTSP_PROFILE_UNKNOWN);
890
891   priv = stream->priv;
892
893   g_mutex_lock (&priv->lock);
894   res = priv->profiles;
895   g_mutex_unlock (&priv->lock);
896
897   return res;
898 }
899
900 /**
901  * gst_rtsp_stream_set_protocols:
902  * @stream: a #GstRTSPStream
903  * @protocols: the new flags
904  *
905  * Configure the allowed lower transport for @stream.
906  */
907 void
908 gst_rtsp_stream_set_protocols (GstRTSPStream * stream,
909     GstRTSPLowerTrans protocols)
910 {
911   GstRTSPStreamPrivate *priv;
912
913   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
914
915   priv = stream->priv;
916
917   g_mutex_lock (&priv->lock);
918   priv->allowed_protocols = protocols;
919   g_mutex_unlock (&priv->lock);
920 }
921
922 /**
923  * gst_rtsp_stream_get_protocols:
924  * @stream: a #GstRTSPStream
925  *
926  * Get the allowed protocols of @stream.
927  *
928  * Returns: a #GstRTSPLowerTrans
929  */
930 GstRTSPLowerTrans
931 gst_rtsp_stream_get_protocols (GstRTSPStream * stream)
932 {
933   GstRTSPStreamPrivate *priv;
934   GstRTSPLowerTrans res;
935
936   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream),
937       GST_RTSP_LOWER_TRANS_UNKNOWN);
938
939   priv = stream->priv;
940
941   g_mutex_lock (&priv->lock);
942   res = priv->allowed_protocols;
943   g_mutex_unlock (&priv->lock);
944
945   return res;
946 }
947
948 /**
949  * gst_rtsp_stream_set_address_pool:
950  * @stream: a #GstRTSPStream
951  * @pool: (transfer none) (nullable): a #GstRTSPAddressPool
952  *
953  * configure @pool to be used as the address pool of @stream.
954  */
955 void
956 gst_rtsp_stream_set_address_pool (GstRTSPStream * stream,
957     GstRTSPAddressPool * pool)
958 {
959   GstRTSPStreamPrivate *priv;
960   GstRTSPAddressPool *old;
961
962   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
963
964   priv = stream->priv;
965
966   GST_LOG_OBJECT (stream, "set address pool %p", pool);
967
968   g_mutex_lock (&priv->lock);
969   if ((old = priv->pool) != pool)
970     priv->pool = pool ? g_object_ref (pool) : NULL;
971   else
972     old = NULL;
973   g_mutex_unlock (&priv->lock);
974
975   if (old)
976     g_object_unref (old);
977 }
978
979 /**
980  * gst_rtsp_stream_get_address_pool:
981  * @stream: a #GstRTSPStream
982  *
983  * Get the #GstRTSPAddressPool used as the address pool of @stream.
984  *
985  * Returns: (transfer full) (nullable): the #GstRTSPAddressPool of @stream.
986  * g_object_unref() after usage.
987  */
988 GstRTSPAddressPool *
989 gst_rtsp_stream_get_address_pool (GstRTSPStream * stream)
990 {
991   GstRTSPStreamPrivate *priv;
992   GstRTSPAddressPool *result;
993
994   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
995
996   priv = stream->priv;
997
998   g_mutex_lock (&priv->lock);
999   if ((result = priv->pool))
1000     g_object_ref (result);
1001   g_mutex_unlock (&priv->lock);
1002
1003   return result;
1004 }
1005
1006 /**
1007  * gst_rtsp_stream_set_multicast_iface:
1008  * @stream: a #GstRTSPStream
1009  * @multicast_iface: (transfer none) (nullable): a multicast interface name
1010  *
1011  * configure @multicast_iface to be used for @stream.
1012  */
1013 void
1014 gst_rtsp_stream_set_multicast_iface (GstRTSPStream * stream,
1015     const gchar * multicast_iface)
1016 {
1017   GstRTSPStreamPrivate *priv;
1018   gchar *old;
1019
1020   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
1021
1022   priv = stream->priv;
1023
1024   GST_LOG_OBJECT (stream, "set multicast iface %s",
1025       GST_STR_NULL (multicast_iface));
1026
1027   g_mutex_lock (&priv->lock);
1028   if ((old = priv->multicast_iface) != multicast_iface)
1029     priv->multicast_iface = multicast_iface ? g_strdup (multicast_iface) : NULL;
1030   else
1031     old = NULL;
1032   g_mutex_unlock (&priv->lock);
1033
1034   if (old)
1035     g_free (old);
1036 }
1037
1038 /**
1039  * gst_rtsp_stream_get_multicast_iface:
1040  * @stream: a #GstRTSPStream
1041  *
1042  * Get the multicast interface used for @stream.
1043  *
1044  * Returns: (transfer full) (nullable): the multicast interface for @stream.
1045  * g_free() after usage.
1046  */
1047 gchar *
1048 gst_rtsp_stream_get_multicast_iface (GstRTSPStream * stream)
1049 {
1050   GstRTSPStreamPrivate *priv;
1051   gchar *result;
1052
1053   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
1054
1055   priv = stream->priv;
1056
1057   g_mutex_lock (&priv->lock);
1058   if ((result = priv->multicast_iface))
1059     result = g_strdup (result);
1060   g_mutex_unlock (&priv->lock);
1061
1062   return result;
1063 }
1064
1065 /**
1066  * gst_rtsp_stream_get_multicast_address:
1067  * @stream: a #GstRTSPStream
1068  * @family: the #GSocketFamily
1069  *
1070  * Get the multicast address of @stream for @family. The original
1071  * #GstRTSPAddress is cached and copy is returned, so freeing the return value
1072  * won't release the address from the pool.
1073  *
1074  * Returns: (transfer full) (nullable): the #GstRTSPAddress of @stream
1075  * or %NULL when no address could be allocated. gst_rtsp_address_free()
1076  * after usage.
1077  */
1078 GstRTSPAddress *
1079 gst_rtsp_stream_get_multicast_address (GstRTSPStream * stream,
1080     GSocketFamily family)
1081 {
1082   GstRTSPStreamPrivate *priv;
1083   GstRTSPAddress *result;
1084   GstRTSPAddress **addrp;
1085   GstRTSPAddressFlags flags;
1086
1087   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
1088
1089   priv = stream->priv;
1090
1091   g_mutex_lock (&stream->priv->lock);
1092
1093   if (family == G_SOCKET_FAMILY_IPV6) {
1094     flags = GST_RTSP_ADDRESS_FLAG_IPV6;
1095     addrp = &priv->mcast_addr_v6;
1096   } else {
1097     flags = GST_RTSP_ADDRESS_FLAG_IPV4;
1098     addrp = &priv->mcast_addr_v4;
1099   }
1100
1101   if (*addrp == NULL) {
1102     if (priv->pool == NULL)
1103       goto no_pool;
1104
1105     flags |= GST_RTSP_ADDRESS_FLAG_EVEN_PORT | GST_RTSP_ADDRESS_FLAG_MULTICAST;
1106
1107     *addrp = gst_rtsp_address_pool_acquire_address (priv->pool, flags, 2);
1108     if (*addrp == NULL)
1109       goto no_address;
1110
1111     /* FIXME: Also reserve the same port with unicast ANY address, since that's
1112      * where we are going to bind our socket. Probably loop until we find a port
1113      * available in both mcast and unicast pools. Maybe GstRTSPAddressPool
1114      * should do it for us when both GST_RTSP_ADDRESS_FLAG_MULTICAST and
1115      * GST_RTSP_ADDRESS_FLAG_UNICAST are givent. */
1116   }
1117   result = gst_rtsp_address_copy (*addrp);
1118
1119   g_mutex_unlock (&stream->priv->lock);
1120
1121   return result;
1122
1123   /* ERRORS */
1124 no_pool:
1125   {
1126     GST_ERROR_OBJECT (stream, "no address pool specified");
1127     g_mutex_unlock (&stream->priv->lock);
1128     return NULL;
1129   }
1130 no_address:
1131   {
1132     GST_ERROR_OBJECT (stream, "failed to acquire address from pool");
1133     g_mutex_unlock (&stream->priv->lock);
1134     return NULL;
1135   }
1136 }
1137
1138 /**
1139  * gst_rtsp_stream_reserve_address:
1140  * @stream: a #GstRTSPStream
1141  * @address: an address
1142  * @port: a port
1143  * @n_ports: n_ports
1144  * @ttl: a TTL
1145  *
1146  * Reserve @address and @port as the address and port of @stream. The original
1147  * #GstRTSPAddress is cached and copy is returned, so freeing the return value
1148  * won't release the address from the pool.
1149  *
1150  * Returns: (nullable): the #GstRTSPAddress of @stream or %NULL when
1151  * the address could not be reserved. gst_rtsp_address_free() after
1152  * usage.
1153  */
1154 GstRTSPAddress *
1155 gst_rtsp_stream_reserve_address (GstRTSPStream * stream,
1156     const gchar * address, guint port, guint n_ports, guint ttl)
1157 {
1158   GstRTSPStreamPrivate *priv;
1159   GstRTSPAddress *result;
1160   GInetAddress *addr;
1161   GSocketFamily family;
1162   GstRTSPAddress **addrp;
1163
1164   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
1165   g_return_val_if_fail (address != NULL, NULL);
1166   g_return_val_if_fail (port > 0, NULL);
1167   g_return_val_if_fail (n_ports > 0, NULL);
1168   g_return_val_if_fail (ttl > 0, NULL);
1169
1170   priv = stream->priv;
1171
1172   addr = g_inet_address_new_from_string (address);
1173   if (!addr) {
1174     GST_ERROR ("failed to get inet addr from %s", address);
1175     family = G_SOCKET_FAMILY_IPV4;
1176   } else {
1177     family = g_inet_address_get_family (addr);
1178     g_object_unref (addr);
1179   }
1180
1181   if (family == G_SOCKET_FAMILY_IPV6)
1182     addrp = &priv->mcast_addr_v6;
1183   else
1184     addrp = &priv->mcast_addr_v4;
1185
1186   g_mutex_lock (&priv->lock);
1187   if (*addrp == NULL) {
1188     GstRTSPAddressPoolResult res;
1189
1190     if (priv->pool == NULL)
1191       goto no_pool;
1192
1193     res = gst_rtsp_address_pool_reserve_address (priv->pool, address,
1194         port, n_ports, ttl, addrp);
1195     if (res != GST_RTSP_ADDRESS_POOL_OK)
1196       goto no_address;
1197
1198     /* FIXME: Also reserve the same port with unicast ANY address, since that's
1199      * where we are going to bind our socket. */
1200   } else {
1201     if (g_ascii_strcasecmp ((*addrp)->address, address) ||
1202         (*addrp)->port != port || (*addrp)->n_ports != n_ports ||
1203         (*addrp)->ttl != ttl)
1204       goto different_address;
1205   }
1206   result = gst_rtsp_address_copy (*addrp);
1207   g_mutex_unlock (&priv->lock);
1208
1209   return result;
1210
1211   /* ERRORS */
1212 no_pool:
1213   {
1214     GST_ERROR_OBJECT (stream, "no address pool specified");
1215     g_mutex_unlock (&priv->lock);
1216     return NULL;
1217   }
1218 no_address:
1219   {
1220     GST_ERROR_OBJECT (stream, "failed to acquire address %s from pool",
1221         address);
1222     g_mutex_unlock (&priv->lock);
1223     return NULL;
1224   }
1225 different_address:
1226   {
1227     GST_ERROR_OBJECT (stream,
1228         "address %s is not the same as %s that was already reserved",
1229         address, (*addrp)->address);
1230     g_mutex_unlock (&priv->lock);
1231     return NULL;
1232   }
1233 }
1234
1235 /* must be called with lock */
1236 static void
1237 set_socket_for_udpsink (GstElement * udpsink, GSocket * socket,
1238     GSocketFamily family)
1239 {
1240   const gchar *multisink_socket;
1241
1242   if (family == G_SOCKET_FAMILY_IPV6)
1243     multisink_socket = "socket-v6";
1244   else
1245     multisink_socket = "socket";
1246
1247   g_object_set (G_OBJECT (udpsink), multisink_socket, socket, NULL);
1248 }
1249
1250 /* must be called with lock */
1251 static void
1252 set_multicast_socket_for_udpsink (GstElement * udpsink, GSocket * socket,
1253     GSocketFamily family, const gchar * multicast_iface,
1254     const gchar * addr_str, gint port, gint mcast_ttl)
1255 {
1256   set_socket_for_udpsink (udpsink, socket, family);
1257
1258   if (multicast_iface) {
1259     GST_INFO ("setting multicast-iface %s", multicast_iface);
1260     g_object_set (G_OBJECT (udpsink), "multicast-iface", multicast_iface, NULL);
1261   }
1262
1263   if (mcast_ttl > 0) {
1264     GST_INFO ("setting ttl-mc %d", mcast_ttl);
1265     g_object_set (G_OBJECT (udpsink), "ttl-mc", mcast_ttl, NULL);
1266   }
1267 }
1268
1269
1270 /* must be called with lock */
1271 static void
1272 set_unicast_socket_for_udpsink (GstElement * udpsink, GSocket * socket,
1273     GSocketFamily family)
1274 {
1275   set_socket_for_udpsink (udpsink, socket, family);
1276 }
1277
1278 static guint16
1279 get_port_from_socket (GSocket * socket)
1280 {
1281   guint16 port;
1282   GSocketAddress *sockaddr;
1283   GError *err;
1284
1285   GST_DEBUG ("socket: %p", socket);
1286   sockaddr = g_socket_get_local_address (socket, &err);
1287   if (sockaddr == NULL || !G_IS_INET_SOCKET_ADDRESS (sockaddr)) {
1288     g_clear_object (&sockaddr);
1289     GST_ERROR ("failed to get sockaddr: %s", err->message);
1290     g_error_free (err);
1291     return 0;
1292   }
1293
1294   port = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (sockaddr));
1295   g_object_unref (sockaddr);
1296
1297   return port;
1298 }
1299
1300
1301 static gboolean
1302 create_and_configure_udpsink (GstRTSPStream * stream, GstElement ** udpsink,
1303     GSocket * socket_v4, GSocket * socket_v6, gboolean multicast,
1304     gboolean is_rtp, gint mcast_ttl)
1305 {
1306   GstRTSPStreamPrivate *priv = stream->priv;
1307
1308   *udpsink = gst_element_factory_make ("multiudpsink", NULL);
1309
1310   if (!*udpsink)
1311     goto no_udp_protocol;
1312
1313   /* configure sinks */
1314
1315   g_object_set (G_OBJECT (*udpsink), "close-socket", FALSE, NULL);
1316
1317   g_object_set (G_OBJECT (*udpsink), "send-duplicates", FALSE, NULL);
1318
1319   if (is_rtp)
1320     g_object_set (G_OBJECT (*udpsink), "buffer-size", priv->buffer_size, NULL);
1321   else
1322     g_object_set (G_OBJECT (*udpsink), "sync", FALSE, NULL);
1323
1324   /* Needs to be async for RECORD streams, otherwise we will never go to
1325    * PLAYING because the sinks will wait for data while the udpsrc can't
1326    * provide data with timestamps in PAUSED. */
1327   if (!is_rtp || priv->sinkpad)
1328     g_object_set (G_OBJECT (*udpsink), "async", FALSE, NULL);
1329
1330   if (multicast) {
1331     /* join multicast group when adding clients, so we'll start receiving from it.
1332      * We cannot rely on the udpsrc to join the group since its socket is always a
1333      * local unicast one. */
1334     g_object_set (G_OBJECT (*udpsink), "auto-multicast", TRUE, NULL);
1335
1336     g_object_set (G_OBJECT (*udpsink), "loop", FALSE, NULL);
1337   }
1338
1339   /* update the dscp qos field in the sinks */
1340   update_dscp_qos (stream, udpsink);
1341
1342   if (priv->server_addr_v4) {
1343     GST_DEBUG_OBJECT (stream, "udp IPv4, configure udpsinks");
1344     set_unicast_socket_for_udpsink (*udpsink, socket_v4, G_SOCKET_FAMILY_IPV4);
1345   }
1346
1347   if (priv->server_addr_v6) {
1348     GST_DEBUG_OBJECT (stream, "udp IPv6, configure udpsinks");
1349     set_unicast_socket_for_udpsink (*udpsink, socket_v6, G_SOCKET_FAMILY_IPV6);
1350   }
1351
1352   if (multicast) {
1353     gint port;
1354     if (priv->mcast_addr_v4) {
1355       GST_DEBUG_OBJECT (stream, "mcast IPv4, configure udpsinks");
1356       port = get_port_from_socket (socket_v4);
1357       if (!port)
1358         goto get_port_failed;
1359       set_multicast_socket_for_udpsink (*udpsink, socket_v4,
1360           G_SOCKET_FAMILY_IPV4, priv->multicast_iface,
1361           priv->mcast_addr_v4->address, port, mcast_ttl);
1362     }
1363
1364     if (priv->mcast_addr_v6) {
1365       GST_DEBUG_OBJECT (stream, "mcast IPv6, configure udpsinks");
1366       port = get_port_from_socket (socket_v6);
1367       if (!port)
1368         goto get_port_failed;
1369       set_multicast_socket_for_udpsink (*udpsink, socket_v6,
1370           G_SOCKET_FAMILY_IPV6, priv->multicast_iface,
1371           priv->mcast_addr_v6->address, port, mcast_ttl);
1372     }
1373
1374   }
1375
1376   return TRUE;
1377
1378   /* ERRORS */
1379 no_udp_protocol:
1380   {
1381     GST_ERROR_OBJECT (stream, "failed to create udpsink element");
1382     return FALSE;
1383   }
1384 get_port_failed:
1385   {
1386     GST_ERROR_OBJECT (stream, "failed to get udp port");
1387     return FALSE;
1388   }
1389 }
1390
1391 /* must be called with lock */
1392 static gboolean
1393 create_and_configure_udpsource (GstElement ** udpsrc, GSocket * socket)
1394 {
1395   GstStateChangeReturn ret;
1396
1397   g_assert (socket != NULL);
1398
1399   *udpsrc = gst_element_factory_make ("udpsrc", NULL);
1400   if (*udpsrc == NULL)
1401     goto error;
1402
1403   g_object_set (G_OBJECT (*udpsrc), "socket", socket, NULL);
1404
1405   /* The udpsrc cannot do the join because its socket is always a local unicast
1406    * one. The udpsink sharing the same socket will do it for us. */
1407   g_object_set (G_OBJECT (*udpsrc), "auto-multicast", FALSE, NULL);
1408
1409   g_object_set (G_OBJECT (*udpsrc), "loop", FALSE, NULL);
1410
1411   g_object_set (G_OBJECT (*udpsrc), "close-socket", FALSE, NULL);
1412
1413   ret = gst_element_set_state (*udpsrc, GST_STATE_READY);
1414   if (ret == GST_STATE_CHANGE_FAILURE)
1415     goto error;
1416
1417   return TRUE;
1418
1419   /* ERRORS */
1420 error:
1421   {
1422     if (*udpsrc) {
1423       gst_element_set_state (*udpsrc, GST_STATE_NULL);
1424       g_clear_object (udpsrc);
1425     }
1426     return FALSE;
1427   }
1428 }
1429
1430 static gboolean
1431 alloc_ports_one_family (GstRTSPStream * stream, GSocketFamily family,
1432     GSocket * socket_out[2], GstRTSPAddress ** server_addr_out,
1433     gboolean multicast, GstRTSPTransport * ct, gboolean use_transport_settings)
1434 {
1435   GstRTSPStreamPrivate *priv = stream->priv;
1436   GSocket *rtp_socket = NULL;
1437   GSocket *rtcp_socket = NULL;
1438   gint tmp_rtp, tmp_rtcp;
1439   guint count;
1440   GList *rejected_addresses = NULL;
1441   GstRTSPAddress *addr = NULL;
1442   GInetAddress *inetaddr = NULL;
1443   GSocketAddress *rtp_sockaddr = NULL;
1444   GSocketAddress *rtcp_sockaddr = NULL;
1445   GstRTSPAddressPool *pool;
1446   gboolean transport_settings_defined = FALSE;
1447
1448   pool = priv->pool;
1449   count = 0;
1450
1451   /* Start with random port */
1452   tmp_rtp = 0;
1453   tmp_rtcp = 0;
1454
1455   if (use_transport_settings) {
1456     if (!multicast)
1457       goto no_mcast;
1458
1459     if (ct == NULL)
1460       goto no_transport;
1461
1462     /* multicast and transport specific case */
1463     if (ct->destination != NULL) {
1464       tmp_rtp = ct->port.min;
1465       tmp_rtcp = ct->port.max;
1466
1467       /* check if the provided address is a multicast address */
1468       inetaddr = g_inet_address_new_from_string (ct->destination);
1469       if (inetaddr == NULL)
1470         goto destination_error;
1471       if (!g_inet_address_get_is_multicast (inetaddr))
1472         goto destination_no_mcast;
1473
1474
1475       if (!priv->bind_mcast_address) {
1476         g_clear_object (&inetaddr);
1477         inetaddr = g_inet_address_new_any (family);
1478       }
1479
1480       GST_DEBUG_OBJECT (stream, "use transport settings");
1481       transport_settings_defined = TRUE;
1482     }
1483   }
1484
1485   if (priv->enable_rtcp) {
1486     rtcp_socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
1487         G_SOCKET_PROTOCOL_UDP, NULL);
1488     if (!rtcp_socket)
1489       goto no_udp_protocol;
1490     g_socket_set_multicast_loopback (rtcp_socket, FALSE);
1491   }
1492
1493   /* try to allocate UDP ports, the RTP port should be an even
1494    * number and the RTCP port (if enabled) should be the next (uneven) port */
1495 again:
1496
1497   if (rtp_socket == NULL) {
1498     rtp_socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
1499         G_SOCKET_PROTOCOL_UDP, NULL);
1500     if (!rtp_socket)
1501       goto no_udp_protocol;
1502     g_socket_set_multicast_loopback (rtp_socket, FALSE);
1503   }
1504
1505   if (!transport_settings_defined) {
1506     if ((pool && gst_rtsp_address_pool_has_unicast_addresses (pool))
1507         || multicast) {
1508       GstRTSPAddressFlags flags;
1509
1510       if (addr)
1511         rejected_addresses = g_list_prepend (rejected_addresses, addr);
1512
1513       if (!pool)
1514         goto no_pool;
1515
1516       flags = GST_RTSP_ADDRESS_FLAG_EVEN_PORT;
1517       if (multicast)
1518         flags |= GST_RTSP_ADDRESS_FLAG_MULTICAST;
1519       else
1520         flags |= GST_RTSP_ADDRESS_FLAG_UNICAST;
1521
1522       if (family == G_SOCKET_FAMILY_IPV6)
1523         flags |= GST_RTSP_ADDRESS_FLAG_IPV6;
1524       else
1525         flags |= GST_RTSP_ADDRESS_FLAG_IPV4;
1526
1527       if (*server_addr_out)
1528         addr = *server_addr_out;
1529       else
1530         addr = gst_rtsp_address_pool_acquire_address (pool, flags,
1531             priv->enable_rtcp ? 2 : 1);
1532
1533       if (addr == NULL)
1534         goto no_address;
1535
1536       tmp_rtp = addr->port;
1537
1538       g_clear_object (&inetaddr);
1539       /* FIXME: Does it really work with the IP_MULTICAST_ALL socket option and
1540        * socket control message set in udpsrc? */
1541       if (priv->bind_mcast_address || !multicast)
1542         inetaddr = g_inet_address_new_from_string (addr->address);
1543       else
1544         inetaddr = g_inet_address_new_any (family);
1545     } else {
1546       if (tmp_rtp != 0) {
1547         tmp_rtp += 2;
1548         if (++count > 20)
1549           goto no_ports;
1550       }
1551
1552       if (inetaddr == NULL)
1553         inetaddr = g_inet_address_new_any (family);
1554     }
1555   }
1556
1557   rtp_sockaddr = g_inet_socket_address_new (inetaddr, tmp_rtp);
1558   if (!g_socket_bind (rtp_socket, rtp_sockaddr, FALSE, NULL)) {
1559     GST_DEBUG_OBJECT (stream, "rtp bind() failed, will try again");
1560     g_object_unref (rtp_sockaddr);
1561     if (transport_settings_defined)
1562       goto transport_settings_error;
1563     goto again;
1564   }
1565   g_object_unref (rtp_sockaddr);
1566
1567   rtp_sockaddr = g_socket_get_local_address (rtp_socket, NULL);
1568   if (rtp_sockaddr == NULL || !G_IS_INET_SOCKET_ADDRESS (rtp_sockaddr)) {
1569     g_clear_object (&rtp_sockaddr);
1570     goto socket_error;
1571   }
1572
1573   if (!transport_settings_defined) {
1574     tmp_rtp =
1575         g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (rtp_sockaddr));
1576
1577     /* check if port is even. RFC 3550 encorages the use of an even/odd port
1578      * pair, however it's not a strict requirement so this check is not done
1579      * for the client selected ports. */
1580     if ((tmp_rtp & 1) != 0) {
1581       /* port not even, close and allocate another */
1582       tmp_rtp++;
1583       g_object_unref (rtp_sockaddr);
1584       g_clear_object (&rtp_socket);
1585       goto again;
1586     }
1587   }
1588   g_object_unref (rtp_sockaddr);
1589
1590   /* set port */
1591   if (priv->enable_rtcp) {
1592     tmp_rtcp = tmp_rtp + 1;
1593
1594     rtcp_sockaddr = g_inet_socket_address_new (inetaddr, tmp_rtcp);
1595     if (!g_socket_bind (rtcp_socket, rtcp_sockaddr, FALSE, NULL)) {
1596       GST_DEBUG_OBJECT (stream, "rctp bind() failed, will try again");
1597       g_object_unref (rtcp_sockaddr);
1598       g_clear_object (&rtp_socket);
1599       if (transport_settings_defined)
1600         goto transport_settings_error;
1601       goto again;
1602     }
1603     g_object_unref (rtcp_sockaddr);
1604   }
1605
1606   if (!addr) {
1607     addr = g_slice_new0 (GstRTSPAddress);
1608     addr->port = tmp_rtp;
1609     addr->n_ports = 2;
1610     if (transport_settings_defined)
1611       addr->address = g_strdup (ct->destination);
1612     else
1613       addr->address = g_inet_address_to_string (inetaddr);
1614     addr->ttl = ct->ttl;
1615   }
1616
1617   g_clear_object (&inetaddr);
1618
1619   if (multicast && (ct->ttl > 0) && (ct->ttl <= priv->max_mcast_ttl)) {
1620     GST_DEBUG ("setting mcast ttl to %d", ct->ttl);
1621     g_socket_set_multicast_ttl (rtp_socket, ct->ttl);
1622     if (rtcp_socket)
1623       g_socket_set_multicast_ttl (rtcp_socket, ct->ttl);
1624   }
1625
1626   socket_out[0] = rtp_socket;
1627   socket_out[1] = rtcp_socket;
1628   *server_addr_out = addr;
1629
1630   if (priv->enable_rtcp) {
1631     GST_DEBUG_OBJECT (stream, "allocated address: %s and ports: %d, %d",
1632         addr->address, tmp_rtp, tmp_rtcp);
1633   } else {
1634     GST_DEBUG_OBJECT (stream, "allocated address: %s and port: %d",
1635         addr->address, tmp_rtp);
1636   }
1637
1638   g_list_free_full (rejected_addresses, (GDestroyNotify) gst_rtsp_address_free);
1639
1640   return TRUE;
1641
1642   /* ERRORS */
1643 no_mcast:
1644   {
1645     GST_ERROR_OBJECT (stream, "failed to allocate UDP ports: wrong transport");
1646     goto cleanup;
1647   }
1648 no_transport:
1649   {
1650     GST_ERROR_OBJECT (stream, "failed to allocate UDP ports: no transport");
1651     goto cleanup;
1652   }
1653 destination_error:
1654   {
1655     GST_ERROR_OBJECT (stream,
1656         "failed to allocate UDP ports: destination error");
1657     goto cleanup;
1658   }
1659 destination_no_mcast:
1660   {
1661     GST_ERROR_OBJECT (stream,
1662         "failed to allocate UDP ports: destination not multicast address");
1663     goto cleanup;
1664   }
1665 no_udp_protocol:
1666   {
1667     GST_WARNING_OBJECT (stream, "failed to allocate UDP ports: protocol error");
1668     goto cleanup;
1669   }
1670 no_pool:
1671   {
1672     GST_WARNING_OBJECT (stream,
1673         "failed to allocate UDP ports: no address pool specified");
1674     goto cleanup;
1675   }
1676 no_address:
1677   {
1678     GST_WARNING_OBJECT (stream, "failed to acquire address from pool");
1679     goto cleanup;
1680   }
1681 no_ports:
1682   {
1683     GST_WARNING_OBJECT (stream, "failed to allocate UDP ports: no ports");
1684     goto cleanup;
1685   }
1686 transport_settings_error:
1687   {
1688     GST_ERROR_OBJECT (stream,
1689         "failed to allocate UDP ports with requested transport settings");
1690     goto cleanup;
1691   }
1692 socket_error:
1693   {
1694     GST_WARNING_OBJECT (stream, "failed to allocate UDP ports: socket error");
1695     goto cleanup;
1696   }
1697 cleanup:
1698   {
1699     if (inetaddr)
1700       g_object_unref (inetaddr);
1701     g_list_free_full (rejected_addresses,
1702         (GDestroyNotify) gst_rtsp_address_free);
1703     if (addr)
1704       gst_rtsp_address_free (addr);
1705     if (rtp_socket)
1706       g_object_unref (rtp_socket);
1707     if (rtcp_socket)
1708       g_object_unref (rtcp_socket);
1709     return FALSE;
1710   }
1711 }
1712
1713 /* must be called with lock */
1714 static gboolean
1715 add_mcast_client_addr (GstRTSPStream * stream, const gchar * destination,
1716     guint rtp_port, guint rtcp_port)
1717 {
1718   GstRTSPStreamPrivate *priv;
1719   GList *walk;
1720   UdpClientAddrInfo *client;
1721   GInetAddress *inet;
1722
1723   priv = stream->priv;
1724
1725   if (destination == NULL)
1726     return FALSE;
1727
1728   inet = g_inet_address_new_from_string (destination);
1729   if (inet == NULL)
1730     goto invalid_address;
1731
1732   if (!g_inet_address_get_is_multicast (inet)) {
1733     g_object_unref (inet);
1734     goto invalid_address;
1735   }
1736   g_object_unref (inet);
1737
1738   for (walk = priv->mcast_clients; walk; walk = g_list_next (walk)) {
1739     UdpClientAddrInfo *cli = walk->data;
1740
1741     if ((g_strcmp0 (cli->address, destination) == 0) &&
1742         (cli->rtp_port == rtp_port)) {
1743       GST_DEBUG ("requested destination already exists: %s:%u-%u",
1744           destination, rtp_port, rtcp_port);
1745       cli->add_count++;
1746       return TRUE;
1747     }
1748   }
1749
1750   client = g_new0 (UdpClientAddrInfo, 1);
1751   client->address = g_strdup (destination);
1752   client->rtp_port = rtp_port;
1753   client->add_count = 1;
1754   priv->mcast_clients = g_list_prepend (priv->mcast_clients, client);
1755
1756   GST_DEBUG ("added mcast client %s:%u-%u", destination, rtp_port, rtcp_port);
1757
1758   return TRUE;
1759
1760 invalid_address:
1761   {
1762     GST_WARNING_OBJECT (stream, "Multicast address is invalid: %s",
1763         destination);
1764     return FALSE;
1765   }
1766 }
1767
1768 /* must be called with lock */
1769 static gboolean
1770 remove_mcast_client_addr (GstRTSPStream * stream, const gchar * destination,
1771     guint rtp_port, guint rtcp_port)
1772 {
1773   GstRTSPStreamPrivate *priv;
1774   GList *walk;
1775
1776   priv = stream->priv;
1777
1778   if (destination == NULL)
1779     goto no_destination;
1780
1781   for (walk = priv->mcast_clients; walk; walk = g_list_next (walk)) {
1782     UdpClientAddrInfo *cli = walk->data;
1783
1784     if ((g_strcmp0 (cli->address, destination) == 0) &&
1785         (cli->rtp_port == rtp_port)) {
1786       cli->add_count--;
1787
1788       if (!cli->add_count) {
1789         priv->mcast_clients = g_list_remove (priv->mcast_clients, cli);
1790         free_mcast_client (cli);
1791       }
1792       return TRUE;
1793     }
1794   }
1795
1796   GST_WARNING_OBJECT (stream, "Address not found");
1797   return FALSE;
1798
1799 no_destination:
1800   {
1801     GST_WARNING_OBJECT (stream, "No destination has been provided");
1802     return FALSE;
1803   }
1804 }
1805
1806
1807 /**
1808  * gst_rtsp_stream_allocate_udp_sockets:
1809  * @stream: a #GstRTSPStream
1810  * @family: protocol family
1811  * @transport: transport method
1812  * @use_client_settings: Whether to use client settings or not
1813  *
1814  * Allocates RTP and RTCP ports.
1815  *
1816  * Returns: %TRUE if the RTP and RTCP sockets have been succeccully allocated.
1817  */
1818 gboolean
1819 gst_rtsp_stream_allocate_udp_sockets (GstRTSPStream * stream,
1820     GSocketFamily family, GstRTSPTransport * ct,
1821     gboolean use_transport_settings)
1822 {
1823   GstRTSPStreamPrivate *priv;
1824   gboolean ret = FALSE;
1825   GstRTSPLowerTrans transport;
1826   gboolean allocated = FALSE;
1827
1828   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
1829   g_return_val_if_fail (ct != NULL, FALSE);
1830   priv = stream->priv;
1831
1832   transport = ct->lower_transport;
1833
1834   g_mutex_lock (&priv->lock);
1835
1836   if (transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1837     if (family == G_SOCKET_FAMILY_IPV4 && priv->mcast_socket_v4[0])
1838       allocated = TRUE;
1839     else if (family == G_SOCKET_FAMILY_IPV6 && priv->mcast_socket_v6[0])
1840       allocated = TRUE;
1841   } else if (transport == GST_RTSP_LOWER_TRANS_UDP) {
1842     if (family == G_SOCKET_FAMILY_IPV4 && priv->socket_v4[0])
1843       allocated = TRUE;
1844     else if (family == G_SOCKET_FAMILY_IPV6 && priv->socket_v6[0])
1845       allocated = TRUE;
1846   }
1847
1848   if (allocated) {
1849     GST_DEBUG_OBJECT (stream, "Allocated already");
1850     g_mutex_unlock (&priv->lock);
1851     return TRUE;
1852   }
1853
1854   if (family == G_SOCKET_FAMILY_IPV4) {
1855     /* IPv4 */
1856     if (transport == GST_RTSP_LOWER_TRANS_UDP) {
1857       /* UDP unicast */
1858       GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_UDP, ipv4");
1859       ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV4,
1860           priv->socket_v4, &priv->server_addr_v4, FALSE, ct, FALSE);
1861     } else {
1862       /* multicast */
1863       GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_MCAST_UDP, ipv4");
1864       ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV4,
1865           priv->mcast_socket_v4, &priv->mcast_addr_v4, TRUE, ct,
1866           use_transport_settings);
1867     }
1868   } else {
1869     /* IPv6 */
1870     if (transport == GST_RTSP_LOWER_TRANS_UDP) {
1871       /* unicast */
1872       GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_UDP, ipv6");
1873       ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV6,
1874           priv->socket_v6, &priv->server_addr_v6, FALSE, ct, FALSE);
1875
1876     } else {
1877       /* multicast */
1878       GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_MCAST_UDP, ipv6");
1879       ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV6,
1880           priv->mcast_socket_v6, &priv->mcast_addr_v6, TRUE, ct,
1881           use_transport_settings);
1882     }
1883   }
1884   g_mutex_unlock (&priv->lock);
1885
1886   return ret;
1887 }
1888
1889 /**
1890  * gst_rtsp_stream_set_client_side:
1891  * @stream: a #GstRTSPStream
1892  * @client_side: TRUE if this #GstRTSPStream is running on the 'client' side of
1893  * an RTSP connection.
1894  *
1895  * Sets the #GstRTSPStream as a 'client side' stream - used for sending
1896  * streams to an RTSP server via RECORD. This has the practical effect
1897  * of changing which UDP port numbers are used when setting up the local
1898  * side of the stream sending to be either the 'server' or 'client' pair
1899  * of a configured UDP transport.
1900  */
1901 void
1902 gst_rtsp_stream_set_client_side (GstRTSPStream * stream, gboolean client_side)
1903 {
1904   GstRTSPStreamPrivate *priv;
1905
1906   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
1907   priv = stream->priv;
1908   g_mutex_lock (&priv->lock);
1909   priv->client_side = client_side;
1910   g_mutex_unlock (&priv->lock);
1911 }
1912
1913 /**
1914  * gst_rtsp_stream_is_client_side:
1915  * @stream: a #GstRTSPStream
1916  *
1917  * See gst_rtsp_stream_set_client_side()
1918  *
1919  * Returns: TRUE if this #GstRTSPStream is client-side.
1920  */
1921 gboolean
1922 gst_rtsp_stream_is_client_side (GstRTSPStream * stream)
1923 {
1924   GstRTSPStreamPrivate *priv;
1925   gboolean ret;
1926
1927   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
1928
1929   priv = stream->priv;
1930   g_mutex_lock (&priv->lock);
1931   ret = priv->client_side;
1932   g_mutex_unlock (&priv->lock);
1933
1934   return ret;
1935 }
1936
1937 /**
1938  * gst_rtsp_stream_get_server_port:
1939  * @stream: a #GstRTSPStream
1940  * @server_port: (out): result server port
1941  * @family: the port family to get
1942  *
1943  * Fill @server_port with the port pair used by the server. This function can
1944  * only be called when @stream has been joined.
1945  */
1946 void
1947 gst_rtsp_stream_get_server_port (GstRTSPStream * stream,
1948     GstRTSPRange * server_port, GSocketFamily family)
1949 {
1950   GstRTSPStreamPrivate *priv;
1951
1952   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
1953   priv = stream->priv;
1954   g_return_if_fail (priv->joined_bin != NULL);
1955
1956   if (server_port) {
1957     server_port->min = 0;
1958     server_port->max = 0;
1959   }
1960
1961   g_mutex_lock (&priv->lock);
1962   if (family == G_SOCKET_FAMILY_IPV4) {
1963     if (server_port && priv->server_addr_v4) {
1964       server_port->min = priv->server_addr_v4->port;
1965       if (priv->enable_rtcp) {
1966         server_port->max =
1967             priv->server_addr_v4->port + priv->server_addr_v4->n_ports - 1;
1968       }
1969     }
1970   } else {
1971     if (server_port && priv->server_addr_v6) {
1972       server_port->min = priv->server_addr_v6->port;
1973       if (priv->enable_rtcp) {
1974         server_port->max =
1975             priv->server_addr_v6->port + priv->server_addr_v6->n_ports - 1;
1976       }
1977     }
1978   }
1979   g_mutex_unlock (&priv->lock);
1980 }
1981
1982 /**
1983  * gst_rtsp_stream_get_rtpsession:
1984  * @stream: a #GstRTSPStream
1985  *
1986  * Get the RTP session of this stream.
1987  *
1988  * Returns: (transfer full): The RTP session of this stream. Unref after usage.
1989  */
1990 GObject *
1991 gst_rtsp_stream_get_rtpsession (GstRTSPStream * stream)
1992 {
1993   GstRTSPStreamPrivate *priv;
1994   GObject *session;
1995
1996   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
1997
1998   priv = stream->priv;
1999
2000   g_mutex_lock (&priv->lock);
2001   if ((session = priv->session))
2002     g_object_ref (session);
2003   g_mutex_unlock (&priv->lock);
2004
2005   return session;
2006 }
2007
2008 /**
2009  * gst_rtsp_stream_get_srtp_encoder:
2010  * @stream: a #GstRTSPStream
2011  *
2012  * Get the SRTP encoder for this stream.
2013  *
2014  * Returns: (transfer full): The SRTP encoder for this stream. Unref after usage.
2015  */
2016 GstElement *
2017 gst_rtsp_stream_get_srtp_encoder (GstRTSPStream * stream)
2018 {
2019   GstRTSPStreamPrivate *priv;
2020   GstElement *encoder;
2021
2022   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
2023
2024   priv = stream->priv;
2025
2026   g_mutex_lock (&priv->lock);
2027   if ((encoder = priv->srtpenc))
2028     g_object_ref (encoder);
2029   g_mutex_unlock (&priv->lock);
2030
2031   return encoder;
2032 }
2033
2034 /**
2035  * gst_rtsp_stream_get_ssrc:
2036  * @stream: a #GstRTSPStream
2037  * @ssrc: (out): result ssrc
2038  *
2039  * Get the SSRC used by the RTP session of this stream. This function can only
2040  * be called when @stream has been joined.
2041  */
2042 void
2043 gst_rtsp_stream_get_ssrc (GstRTSPStream * stream, guint * ssrc)
2044 {
2045   GstRTSPStreamPrivate *priv;
2046
2047   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
2048   priv = stream->priv;
2049   g_return_if_fail (priv->joined_bin != NULL);
2050
2051   g_mutex_lock (&priv->lock);
2052   if (ssrc && priv->session)
2053     g_object_get (priv->session, "internal-ssrc", ssrc, NULL);
2054   g_mutex_unlock (&priv->lock);
2055 }
2056
2057 /**
2058  * gst_rtsp_stream_set_retransmission_time:
2059  * @stream: a #GstRTSPStream
2060  * @time: a #GstClockTime
2061  *
2062  * Set the amount of time to store retransmission packets.
2063  */
2064 void
2065 gst_rtsp_stream_set_retransmission_time (GstRTSPStream * stream,
2066     GstClockTime time)
2067 {
2068   GST_DEBUG_OBJECT (stream, "set retransmission time %" G_GUINT64_FORMAT, time);
2069
2070   g_mutex_lock (&stream->priv->lock);
2071   stream->priv->rtx_time = time;
2072   if (stream->priv->rtxsend)
2073     g_object_set (stream->priv->rtxsend, "max-size-time",
2074         GST_TIME_AS_MSECONDS (time), NULL);
2075   g_mutex_unlock (&stream->priv->lock);
2076 }
2077
2078 /**
2079  * gst_rtsp_stream_get_retransmission_time:
2080  * @stream: a #GstRTSPStream
2081  *
2082  * Get the amount of time to store retransmission data.
2083  *
2084  * Returns: the amount of time to store retransmission data.
2085  */
2086 GstClockTime
2087 gst_rtsp_stream_get_retransmission_time (GstRTSPStream * stream)
2088 {
2089   GstClockTime ret;
2090
2091   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);
2092
2093   g_mutex_lock (&stream->priv->lock);
2094   ret = stream->priv->rtx_time;
2095   g_mutex_unlock (&stream->priv->lock);
2096
2097   return ret;
2098 }
2099
2100 /**
2101  * gst_rtsp_stream_set_retransmission_pt:
2102  * @stream: a #GstRTSPStream
2103  * @rtx_pt: a #guint
2104  *
2105  * Set the payload type (pt) for retransmission of this stream.
2106  */
2107 void
2108 gst_rtsp_stream_set_retransmission_pt (GstRTSPStream * stream, guint rtx_pt)
2109 {
2110   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
2111
2112   GST_DEBUG_OBJECT (stream, "set retransmission pt %u", rtx_pt);
2113
2114   g_mutex_lock (&stream->priv->lock);
2115   stream->priv->rtx_pt = rtx_pt;
2116   if (stream->priv->rtxsend) {
2117     guint pt = gst_rtsp_stream_get_pt (stream);
2118     gchar *pt_s = g_strdup_printf ("%d", pt);
2119     GstStructure *rtx_pt_map = gst_structure_new ("application/x-rtp-pt-map",
2120         pt_s, G_TYPE_UINT, rtx_pt, NULL);
2121     g_object_set (stream->priv->rtxsend, "payload-type-map", rtx_pt_map, NULL);
2122     g_free (pt_s);
2123     gst_structure_free (rtx_pt_map);
2124   }
2125   g_mutex_unlock (&stream->priv->lock);
2126 }
2127
2128 /**
2129  * gst_rtsp_stream_get_retransmission_pt:
2130  * @stream: a #GstRTSPStream
2131  *
2132  * Get the payload-type used for retransmission of this stream
2133  *
2134  * Returns: The retransmission PT.
2135  */
2136 guint
2137 gst_rtsp_stream_get_retransmission_pt (GstRTSPStream * stream)
2138 {
2139   guint rtx_pt;
2140
2141   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);
2142
2143   g_mutex_lock (&stream->priv->lock);
2144   rtx_pt = stream->priv->rtx_pt;
2145   g_mutex_unlock (&stream->priv->lock);
2146
2147   return rtx_pt;
2148 }
2149
2150 /**
2151  * gst_rtsp_stream_set_buffer_size:
2152  * @stream: a #GstRTSPStream
2153  * @size: the buffer size
2154  *
2155  * Set the size of the UDP transmission buffer (in bytes)
2156  * Needs to be set before the stream is joined to a bin.
2157  *
2158  * Since: 1.6
2159  */
2160 void
2161 gst_rtsp_stream_set_buffer_size (GstRTSPStream * stream, guint size)
2162 {
2163   g_mutex_lock (&stream->priv->lock);
2164   stream->priv->buffer_size = size;
2165   g_mutex_unlock (&stream->priv->lock);
2166 }
2167
2168 /**
2169  * gst_rtsp_stream_get_buffer_size:
2170  * @stream: a #GstRTSPStream
2171  *
2172  * Get the size of the UDP transmission buffer (in bytes)
2173  *
2174  * Returns: the size of the UDP TX buffer
2175  *
2176  * Since: 1.6
2177  */
2178 guint
2179 gst_rtsp_stream_get_buffer_size (GstRTSPStream * stream)
2180 {
2181   guint buffer_size;
2182
2183   g_mutex_lock (&stream->priv->lock);
2184   buffer_size = stream->priv->buffer_size;
2185   g_mutex_unlock (&stream->priv->lock);
2186
2187   return buffer_size;
2188 }
2189
2190 /**
2191  * gst_rtsp_stream_set_max_mcast_ttl:
2192  * @stream: a #GstRTSPStream
2193  * @ttl: the new multicast ttl value
2194  *
2195  * Set the maximum time-to-live value of outgoing multicast packets.
2196  *
2197  * Returns: %TRUE if the requested ttl has been set successfully.
2198  *
2199  * Since: 1.16
2200  */
2201 gboolean
2202 gst_rtsp_stream_set_max_mcast_ttl (GstRTSPStream * stream, guint ttl)
2203 {
2204   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
2205
2206   g_mutex_lock (&stream->priv->lock);
2207   if (ttl == 0 || ttl > DEFAULT_MAX_MCAST_TTL) {
2208     GST_WARNING_OBJECT (stream, "The reqested mcast TTL value is not valid.");
2209     g_mutex_unlock (&stream->priv->lock);
2210     return FALSE;
2211   }
2212   stream->priv->max_mcast_ttl = ttl;
2213   g_mutex_unlock (&stream->priv->lock);
2214
2215   return TRUE;
2216 }
2217
2218 /**
2219  * gst_rtsp_stream_get_max_mcast_ttl:
2220  * @stream: a #GstRTSPStream
2221  *
2222  * Get the the maximum time-to-live value of outgoing multicast packets.
2223  *
2224  * Returns: the maximum time-to-live value of outgoing multicast packets.
2225  *
2226  * Since: 1.16
2227  */
2228 guint
2229 gst_rtsp_stream_get_max_mcast_ttl (GstRTSPStream * stream)
2230 {
2231   guint ttl;
2232
2233   g_mutex_lock (&stream->priv->lock);
2234   ttl = stream->priv->max_mcast_ttl;
2235   g_mutex_unlock (&stream->priv->lock);
2236
2237   return ttl;
2238 }
2239
2240 /**
2241  * gst_rtsp_stream_verify_mcast_ttl:
2242  * @stream: a #GstRTSPStream
2243  * @ttl: a requested multicast ttl
2244  *
2245  * Check if the requested multicast ttl value is allowed.
2246  *
2247  * Returns: TRUE if the requested ttl value is allowed.
2248  *
2249  * Since: 1.16
2250  */
2251 gboolean
2252 gst_rtsp_stream_verify_mcast_ttl (GstRTSPStream * stream, guint ttl)
2253 {
2254   gboolean res = FALSE;
2255
2256   g_mutex_lock (&stream->priv->lock);
2257   if ((ttl > 0) && (ttl <= stream->priv->max_mcast_ttl))
2258     res = TRUE;
2259   g_mutex_unlock (&stream->priv->lock);
2260
2261   return res;
2262 }
2263
2264 /**
2265  * gst_rtsp_stream_set_bind_mcast_address:
2266  * @stream: a #GstRTSPStream,
2267  * @bind_mcast_addr: the new value
2268  *
2269  * Decide whether the multicast socket should be bound to a multicast address or
2270  * INADDR_ANY.
2271  *
2272  * Since: 1.16
2273  */
2274 void
2275 gst_rtsp_stream_set_bind_mcast_address (GstRTSPStream * stream,
2276     gboolean bind_mcast_addr)
2277 {
2278   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
2279
2280   g_mutex_lock (&stream->priv->lock);
2281   stream->priv->bind_mcast_address = bind_mcast_addr;
2282   g_mutex_unlock (&stream->priv->lock);
2283 }
2284
2285 /**
2286  * gst_rtsp_stream_is_bind_mcast_address:
2287  * @stream: a #GstRTSPStream
2288  *
2289  * Check if multicast sockets are configured to be bound to multicast addresses.
2290  *
2291  * Returns: %TRUE if multicast sockets are configured to be bound to multicast addresses.
2292  *
2293  * Since: 1.16
2294  */
2295 gboolean
2296 gst_rtsp_stream_is_bind_mcast_address (GstRTSPStream * stream)
2297 {
2298   gboolean result;
2299
2300   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
2301
2302   g_mutex_lock (&stream->priv->lock);
2303   result = stream->priv->bind_mcast_address;
2304   g_mutex_unlock (&stream->priv->lock);
2305
2306   return result;
2307 }
2308
2309 void
2310 gst_rtsp_stream_set_enable_rtcp (GstRTSPStream * stream, gboolean enable)
2311 {
2312   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
2313
2314   g_mutex_lock (&stream->priv->lock);
2315   stream->priv->enable_rtcp = enable;
2316   g_mutex_unlock (&stream->priv->lock);
2317 }
2318
2319 /* executed from streaming thread */
2320 static void
2321 caps_notify (GstPad * pad, GParamSpec * unused, GstRTSPStream * stream)
2322 {
2323   GstRTSPStreamPrivate *priv = stream->priv;
2324   GstCaps *newcaps, *oldcaps;
2325
2326   newcaps = gst_pad_get_current_caps (pad);
2327
2328   GST_INFO ("stream %p received caps %p, %" GST_PTR_FORMAT, stream, newcaps,
2329       newcaps);
2330
2331   g_mutex_lock (&priv->lock);
2332   oldcaps = priv->caps;
2333   priv->caps = newcaps;
2334   g_mutex_unlock (&priv->lock);
2335
2336   if (oldcaps)
2337     gst_caps_unref (oldcaps);
2338 }
2339
2340 static void
2341 dump_structure (const GstStructure * s)
2342 {
2343   gchar *sstr;
2344
2345   sstr = gst_structure_to_string (s);
2346   GST_INFO ("structure: %s", sstr);
2347   g_free (sstr);
2348 }
2349
2350 static GstRTSPStreamTransport *
2351 find_transport (GstRTSPStream * stream, const gchar * rtcp_from)
2352 {
2353   GstRTSPStreamPrivate *priv = stream->priv;
2354   GList *walk;
2355   GstRTSPStreamTransport *result = NULL;
2356   const gchar *tmp;
2357   gchar *dest;
2358   guint port;
2359
2360   if (rtcp_from == NULL)
2361     return NULL;
2362
2363   tmp = g_strrstr (rtcp_from, ":");
2364   if (tmp == NULL)
2365     return NULL;
2366
2367   port = atoi (tmp + 1);
2368   dest = g_strndup (rtcp_from, tmp - rtcp_from);
2369
2370   g_mutex_lock (&priv->lock);
2371   GST_INFO ("finding %s:%d in %d transports", dest, port,
2372       g_list_length (priv->transports));
2373
2374   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
2375     GstRTSPStreamTransport *trans = walk->data;
2376     const GstRTSPTransport *tr;
2377     gint min, max;
2378
2379     tr = gst_rtsp_stream_transport_get_transport (trans);
2380
2381     if (priv->client_side) {
2382       /* In client side mode the 'destination' is the RTSP server, so send
2383        * to those ports */
2384       min = tr->server_port.min;
2385       max = tr->server_port.max;
2386     } else {
2387       min = tr->client_port.min;
2388       max = tr->client_port.max;
2389     }
2390
2391     if ((g_ascii_strcasecmp (tr->destination, dest) == 0) &&
2392         (min == port || max == port)) {
2393       result = trans;
2394       break;
2395     }
2396   }
2397   if (result)
2398     g_object_ref (result);
2399   g_mutex_unlock (&priv->lock);
2400
2401   g_free (dest);
2402
2403   return result;
2404 }
2405
2406 static GstRTSPStreamTransport *
2407 check_transport (GObject * source, GstRTSPStream * stream)
2408 {
2409   GstStructure *stats;
2410   GstRTSPStreamTransport *trans;
2411
2412   /* see if we have a stream to match with the origin of the RTCP packet */
2413   trans = g_object_get_qdata (source, ssrc_stream_map_key);
2414   if (trans == NULL) {
2415     g_object_get (source, "stats", &stats, NULL);
2416     if (stats) {
2417       const gchar *rtcp_from;
2418
2419       dump_structure (stats);
2420
2421       rtcp_from = gst_structure_get_string (stats, "rtcp-from");
2422       if ((trans = find_transport (stream, rtcp_from))) {
2423         GST_INFO ("%p: found transport %p for source  %p", stream, trans,
2424             source);
2425         g_object_set_qdata_full (source, ssrc_stream_map_key, trans,
2426             g_object_unref);
2427       }
2428       gst_structure_free (stats);
2429     }
2430   }
2431   return trans;
2432 }
2433
2434
2435 static void
2436 on_new_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2437 {
2438   GstRTSPStreamTransport *trans;
2439
2440   GST_INFO ("%p: new source %p", stream, source);
2441
2442   trans = check_transport (source, stream);
2443
2444   if (trans)
2445     GST_INFO ("%p: source %p for transport %p", stream, source, trans);
2446 }
2447
2448 static void
2449 on_ssrc_sdes (GObject * session, GObject * source, GstRTSPStream * stream)
2450 {
2451   GST_INFO ("%p: new SDES %p", stream, source);
2452 }
2453
2454 static void
2455 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2456 {
2457   GstRTSPStreamTransport *trans;
2458
2459   trans = check_transport (source, stream);
2460
2461   if (trans) {
2462     GST_INFO ("%p: source %p in transport %p is active", stream, source, trans);
2463     gst_rtsp_stream_transport_keep_alive (trans);
2464   }
2465 #ifdef DUMP_STATS
2466   {
2467     GstStructure *stats;
2468     g_object_get (source, "stats", &stats, NULL);
2469     if (stats) {
2470       dump_structure (stats);
2471       gst_structure_free (stats);
2472     }
2473   }
2474 #endif
2475 }
2476
2477 static void
2478 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2479 {
2480   GST_INFO ("%p: source %p bye", stream, source);
2481 }
2482
2483 static void
2484 on_bye_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2485 {
2486   GstRTSPStreamTransport *trans;
2487
2488   GST_INFO ("%p: source %p bye timeout", stream, source);
2489
2490   if ((trans = g_object_get_qdata (source, ssrc_stream_map_key))) {
2491     gst_rtsp_stream_transport_set_timed_out (trans, TRUE);
2492     g_object_set_qdata (source, ssrc_stream_map_key, NULL);
2493   }
2494 }
2495
2496 static void
2497 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2498 {
2499   GstRTSPStreamTransport *trans;
2500
2501   GST_INFO ("%p: source %p timeout", stream, source);
2502
2503   if ((trans = g_object_get_qdata (source, ssrc_stream_map_key))) {
2504     gst_rtsp_stream_transport_set_timed_out (trans, TRUE);
2505     g_object_set_qdata (source, ssrc_stream_map_key, NULL);
2506   }
2507 }
2508
2509 static void
2510 on_new_sender_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2511 {
2512   GST_INFO ("%p: new sender source %p", stream, source);
2513 #ifndef DUMP_STATS
2514   {
2515     GstStructure *stats;
2516     g_object_get (source, "stats", &stats, NULL);
2517     if (stats) {
2518       dump_structure (stats);
2519       gst_structure_free (stats);
2520     }
2521   }
2522 #endif
2523 }
2524
2525 static void
2526 on_sender_ssrc_active (GObject * session, GObject * source,
2527     GstRTSPStream * stream)
2528 {
2529 #ifndef DUMP_STATS
2530   {
2531     GstStructure *stats;
2532     g_object_get (source, "stats", &stats, NULL);
2533     if (stats) {
2534       dump_structure (stats);
2535       gst_structure_free (stats);
2536     }
2537   }
2538 #endif
2539 }
2540
2541 static void
2542 clear_tr_cache (GstRTSPStreamPrivate * priv)
2543 {
2544   if (priv->tr_cache)
2545     g_ptr_array_unref (priv->tr_cache);
2546   priv->tr_cache = NULL;
2547 }
2548
2549 /* With lock taken */
2550 static gboolean
2551 any_transport_ready (GstRTSPStream * stream, gboolean is_rtp)
2552 {
2553   gboolean ret = TRUE;
2554   GstRTSPStreamPrivate *priv = stream->priv;
2555   GPtrArray *transports;
2556   gint index;
2557
2558   transports = priv->tr_cache;
2559
2560   if (!transports)
2561     goto done;
2562
2563   for (index = 0; index < transports->len; index++) {
2564     GstRTSPStreamTransport *tr = g_ptr_array_index (transports, index);
2565     if (!gst_rtsp_stream_transport_check_back_pressure (tr, is_rtp)) {
2566       ret = TRUE;
2567       break;
2568     } else {
2569       ret = FALSE;
2570     }
2571   }
2572
2573 done:
2574   return ret;
2575 }
2576
2577 /* Must be called *without* priv->lock */
2578 static gboolean
2579 push_data (GstRTSPStream * stream, GstRTSPStreamTransport * trans,
2580     GstBuffer * buffer, GstBufferList * buffer_list, gboolean is_rtp)
2581 {
2582   gboolean send_ret = TRUE;
2583
2584   if (is_rtp) {
2585     if (buffer)
2586       send_ret = gst_rtsp_stream_transport_send_rtp (trans, buffer);
2587     if (buffer_list)
2588       send_ret = gst_rtsp_stream_transport_send_rtp_list (trans, buffer_list);
2589   } else {
2590     if (buffer)
2591       send_ret = gst_rtsp_stream_transport_send_rtcp (trans, buffer);
2592     if (buffer_list)
2593       send_ret = gst_rtsp_stream_transport_send_rtcp_list (trans, buffer_list);
2594   }
2595
2596   return send_ret;
2597 }
2598
2599 /* With priv->lock */
2600 static void
2601 ensure_cached_transports (GstRTSPStream * stream)
2602 {
2603   GstRTSPStreamPrivate *priv = stream->priv;
2604   GList *walk;
2605
2606   if (priv->tr_cache_cookie != priv->transports_cookie) {
2607     clear_tr_cache (priv);
2608     priv->tr_cache =
2609         g_ptr_array_new_full (priv->n_tcp_transports, g_object_unref);
2610
2611     for (walk = priv->transports; walk; walk = g_list_next (walk)) {
2612       GstRTSPStreamTransport *tr = (GstRTSPStreamTransport *) walk->data;
2613       const GstRTSPTransport *t = gst_rtsp_stream_transport_get_transport (tr);
2614
2615       if (t->lower_transport != GST_RTSP_LOWER_TRANS_TCP)
2616         continue;
2617
2618       g_ptr_array_add (priv->tr_cache, g_object_ref (tr));
2619     }
2620     priv->tr_cache_cookie = priv->transports_cookie;
2621   }
2622 }
2623
2624 /* Must be called *without* priv->lock */
2625 static void
2626 check_transport_backlog (GstRTSPStream * stream, GstRTSPStreamTransport * trans)
2627 {
2628   GstRTSPStreamPrivate *priv = stream->priv;
2629   gboolean send_ret = TRUE;
2630
2631   gst_rtsp_stream_transport_lock_backlog (trans);
2632
2633   if (!gst_rtsp_stream_transport_backlog_is_empty (trans)) {
2634     GstBuffer *buffer;
2635     GstBufferList *buffer_list;
2636     gboolean is_rtp;
2637     gboolean popped;
2638
2639     popped =
2640         gst_rtsp_stream_transport_backlog_pop (trans, &buffer, &buffer_list,
2641         &is_rtp);
2642
2643     g_assert (popped == TRUE);
2644
2645     send_ret = push_data (stream, trans, buffer, buffer_list, is_rtp);
2646
2647     gst_clear_buffer (&buffer);
2648     gst_clear_buffer_list (&buffer_list);
2649   }
2650
2651   gst_rtsp_stream_transport_unlock_backlog (trans);
2652
2653   if (!send_ret) {
2654     /* remove transport on send error */
2655     g_mutex_lock (&priv->lock);
2656     update_transport (stream, trans, FALSE);
2657     g_mutex_unlock (&priv->lock);
2658   }
2659 }
2660
2661 /* Must be called with priv->lock */
2662 static void
2663 send_tcp_message (GstRTSPStream * stream, gint idx)
2664 {
2665   GstRTSPStreamPrivate *priv = stream->priv;
2666   GstAppSink *sink;
2667   GstSample *sample;
2668   GstBuffer *buffer;
2669   GstBufferList *buffer_list;
2670   guint n_messages = 0;
2671   gboolean is_rtp;
2672   GPtrArray *transports;
2673
2674   if (!priv->have_buffer[idx])
2675     return;
2676
2677   ensure_cached_transports (stream);
2678
2679   is_rtp = (idx == 0);
2680
2681   if (!any_transport_ready (stream, is_rtp))
2682     return;
2683
2684   priv->have_buffer[idx] = FALSE;
2685
2686   if (priv->appsink[idx] == NULL) {
2687     /* session expired */
2688     return;
2689   }
2690
2691   sink = GST_APP_SINK (priv->appsink[idx]);
2692   sample = gst_app_sink_pull_sample (sink);
2693   if (!sample) {
2694     return;
2695   }
2696
2697   buffer = gst_sample_get_buffer (sample);
2698   buffer_list = gst_sample_get_buffer_list (sample);
2699
2700   /* We will get one message-sent notification per buffer or
2701    * complete buffer-list. We handle each buffer-list as a unit */
2702   if (buffer)
2703     n_messages += 1;
2704   if (buffer_list)
2705     n_messages += 1;
2706
2707   transports = priv->tr_cache;
2708   if (transports)
2709     g_ptr_array_ref (transports);
2710
2711   if (transports) {
2712     gint index;
2713
2714     for (index = 0; index < transports->len; index++) {
2715       GstRTSPStreamTransport *tr = g_ptr_array_index (transports, index);
2716       GstBuffer *buf_ref = NULL;
2717       GstBufferList *buflist_ref = NULL;
2718
2719       gst_rtsp_stream_transport_lock_backlog (tr);
2720
2721       if (buffer)
2722         buf_ref = gst_buffer_ref (buffer);
2723       if (buffer_list)
2724         buflist_ref = gst_buffer_list_ref (buffer_list);
2725
2726       if (!gst_rtsp_stream_transport_backlog_push (tr,
2727               buf_ref, buflist_ref, is_rtp)) {
2728         GST_ERROR_OBJECT (stream,
2729             "Dropping slow transport %" GST_PTR_FORMAT, tr);
2730         update_transport (stream, tr, FALSE);
2731       }
2732
2733       gst_rtsp_stream_transport_unlock_backlog (tr);
2734     }
2735   }
2736   gst_sample_unref (sample);
2737
2738   g_mutex_unlock (&priv->lock);
2739
2740   if (transports) {
2741     gint index;
2742
2743     for (index = 0; index < transports->len; index++) {
2744       GstRTSPStreamTransport *tr = g_ptr_array_index (transports, index);
2745
2746       check_transport_backlog (stream, tr);
2747     }
2748     g_ptr_array_unref (transports);
2749   }
2750
2751   g_mutex_lock (&priv->lock);
2752 }
2753
2754 static gpointer
2755 send_func (GstRTSPStream * stream)
2756 {
2757   GstRTSPStreamPrivate *priv = stream->priv;
2758
2759   g_mutex_lock (&priv->send_lock);
2760
2761   while (priv->continue_sending) {
2762     int i;
2763     int idx = -1;
2764     guint cookie;
2765
2766     cookie = priv->send_cookie;
2767     g_mutex_unlock (&priv->send_lock);
2768
2769     g_mutex_lock (&priv->lock);
2770
2771     /* iterate from 1 and down, so we prioritize RTCP over RTP */
2772     for (i = 1; i >= 0; i--) {
2773       if (priv->have_buffer[i]) {
2774         /* send message */
2775         idx = i;
2776         break;
2777       }
2778     }
2779
2780     if (idx != -1) {
2781       send_tcp_message (stream, idx);
2782     }
2783
2784     g_mutex_unlock (&priv->lock);
2785
2786     g_mutex_lock (&priv->send_lock);
2787     while (cookie == priv->send_cookie && priv->continue_sending) {
2788       g_cond_wait (&priv->send_cond, &priv->send_lock);
2789     }
2790   }
2791
2792   g_mutex_unlock (&priv->send_lock);
2793
2794   return NULL;
2795 }
2796
2797 static GstFlowReturn
2798 handle_new_sample (GstAppSink * sink, gpointer user_data)
2799 {
2800   GstRTSPStream *stream = user_data;
2801   GstRTSPStreamPrivate *priv = stream->priv;
2802   int i;
2803
2804   g_mutex_lock (&priv->lock);
2805
2806   for (i = 0; i < 2; i++) {
2807     if (GST_ELEMENT_CAST (sink) == priv->appsink[i]) {
2808       priv->have_buffer[i] = TRUE;
2809       break;
2810     }
2811   }
2812
2813   if (priv->send_thread == NULL) {
2814     priv->send_thread = g_thread_new (NULL, (GThreadFunc) send_func, user_data);
2815   }
2816
2817   g_mutex_unlock (&priv->lock);
2818
2819   g_mutex_lock (&priv->send_lock);
2820   priv->send_cookie++;
2821   g_cond_signal (&priv->send_cond);
2822   g_mutex_unlock (&priv->send_lock);
2823
2824   return GST_FLOW_OK;
2825 }
2826
2827 static GstAppSinkCallbacks sink_cb = {
2828   NULL,                         /* not interested in EOS */
2829   NULL,                         /* not interested in preroll samples */
2830   handle_new_sample,
2831 };
2832
2833 static GstElement *
2834 get_rtp_encoder (GstRTSPStream * stream, guint session)
2835 {
2836   GstRTSPStreamPrivate *priv = stream->priv;
2837
2838   if (priv->srtpenc == NULL) {
2839     gchar *name;
2840
2841     name = g_strdup_printf ("srtpenc_%u", session);
2842     priv->srtpenc = gst_element_factory_make ("srtpenc", name);
2843     g_free (name);
2844
2845     g_object_set (priv->srtpenc, "random-key", TRUE, NULL);
2846   }
2847   return gst_object_ref (priv->srtpenc);
2848 }
2849
2850 static GstElement *
2851 request_rtp_encoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
2852 {
2853   GstRTSPStreamPrivate *priv = stream->priv;
2854   GstElement *oldenc, *enc;
2855   GstPad *pad;
2856   gchar *name;
2857
2858   if (priv->idx != session)
2859     return NULL;
2860
2861   GST_DEBUG_OBJECT (stream, "make RTP encoder for session %u", session);
2862
2863   oldenc = priv->srtpenc;
2864   enc = get_rtp_encoder (stream, session);
2865   name = g_strdup_printf ("rtp_sink_%d", session);
2866   pad = gst_element_request_pad_simple (enc, name);
2867   g_free (name);
2868   gst_object_unref (pad);
2869
2870   if (oldenc == NULL)
2871     g_signal_emit (stream, gst_rtsp_stream_signals[SIGNAL_NEW_RTP_ENCODER], 0,
2872         enc);
2873
2874   return enc;
2875 }
2876
2877 static GstElement *
2878 request_rtcp_encoder (GstElement * rtpbin, guint session,
2879     GstRTSPStream * stream)
2880 {
2881   GstRTSPStreamPrivate *priv = stream->priv;
2882   GstElement *oldenc, *enc;
2883   GstPad *pad;
2884   gchar *name;
2885
2886   if (priv->idx != session)
2887     return NULL;
2888
2889   GST_DEBUG_OBJECT (stream, "make RTCP encoder for session %u", session);
2890
2891   oldenc = priv->srtpenc;
2892   enc = get_rtp_encoder (stream, session);
2893   name = g_strdup_printf ("rtcp_sink_%d", session);
2894   pad = gst_element_request_pad_simple (enc, name);
2895   g_free (name);
2896   gst_object_unref (pad);
2897
2898   if (oldenc == NULL)
2899     g_signal_emit (stream, gst_rtsp_stream_signals[SIGNAL_NEW_RTCP_ENCODER], 0,
2900         enc);
2901
2902   return enc;
2903 }
2904
2905 static GstCaps *
2906 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
2907 {
2908   GstRTSPStreamPrivate *priv = stream->priv;
2909   GstCaps *caps;
2910
2911   GST_DEBUG ("request key %08x", ssrc);
2912
2913   g_mutex_lock (&priv->lock);
2914   if ((caps = g_hash_table_lookup (priv->keys, GINT_TO_POINTER (ssrc))))
2915     gst_caps_ref (caps);
2916   g_mutex_unlock (&priv->lock);
2917
2918   return caps;
2919 }
2920
2921 static GstElement *
2922 request_rtp_rtcp_decoder (GstElement * rtpbin, guint session,
2923     GstRTSPStream * stream)
2924 {
2925   GstRTSPStreamPrivate *priv = stream->priv;
2926
2927   if (priv->idx != session)
2928     return NULL;
2929
2930   if (priv->srtpdec == NULL) {
2931     gchar *name;
2932
2933     name = g_strdup_printf ("srtpdec_%u", session);
2934     priv->srtpdec = gst_element_factory_make ("srtpdec", name);
2935     g_free (name);
2936
2937     g_signal_connect (priv->srtpdec, "request-key",
2938         (GCallback) request_key, stream);
2939
2940     g_signal_emit (stream, gst_rtsp_stream_signals[SIGNAL_NEW_RTP_RTCP_DECODER],
2941         0, priv->srtpdec);
2942
2943   }
2944   return gst_object_ref (priv->srtpdec);
2945 }
2946
2947 /**
2948  * gst_rtsp_stream_request_aux_sender:
2949  * @stream: a #GstRTSPStream
2950  * @sessid: the session id
2951  *
2952  * Creating a rtxsend bin
2953  *
2954  * Returns: (transfer full) (nullable): a #GstElement.
2955  *
2956  * Since: 1.6
2957  */
2958 GstElement *
2959 gst_rtsp_stream_request_aux_sender (GstRTSPStream * stream, guint sessid)
2960 {
2961   GstElement *bin;
2962   GstPad *pad;
2963   GstStructure *pt_map;
2964   gchar *name;
2965   guint pt, rtx_pt;
2966   gchar *pt_s;
2967
2968   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
2969
2970   pt = gst_rtsp_stream_get_pt (stream);
2971   pt_s = g_strdup_printf ("%u", pt);
2972   rtx_pt = stream->priv->rtx_pt;
2973
2974   GST_INFO ("creating rtxsend with pt %u to %u", pt, rtx_pt);
2975
2976   bin = gst_bin_new (NULL);
2977   stream->priv->rtxsend = gst_element_factory_make ("rtprtxsend", NULL);
2978   pt_map = gst_structure_new ("application/x-rtp-pt-map",
2979       pt_s, G_TYPE_UINT, rtx_pt, NULL);
2980   g_object_set (stream->priv->rtxsend, "payload-type-map", pt_map,
2981       "max-size-time", GST_TIME_AS_MSECONDS (stream->priv->rtx_time), NULL);
2982   g_free (pt_s);
2983   gst_structure_free (pt_map);
2984   gst_bin_add (GST_BIN (bin), gst_object_ref (stream->priv->rtxsend));
2985
2986   pad = gst_element_get_static_pad (stream->priv->rtxsend, "src");
2987   name = g_strdup_printf ("src_%u", sessid);
2988   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
2989   g_free (name);
2990   gst_object_unref (pad);
2991
2992   pad = gst_element_get_static_pad (stream->priv->rtxsend, "sink");
2993   name = g_strdup_printf ("sink_%u", sessid);
2994   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
2995   g_free (name);
2996   gst_object_unref (pad);
2997
2998   return bin;
2999 }
3000
3001 static void
3002 add_rtx_pt (gpointer key, GstCaps * caps, GstStructure * pt_map)
3003 {
3004   guint pt = GPOINTER_TO_INT (key);
3005   const GstStructure *s = gst_caps_get_structure (caps, 0);
3006   const gchar *apt;
3007
3008   if (!g_strcmp0 (gst_structure_get_string (s, "encoding-name"), "RTX") &&
3009       (apt = gst_structure_get_string (s, "apt"))) {
3010     gst_structure_set (pt_map, apt, G_TYPE_UINT, pt, NULL);
3011   }
3012 }
3013
3014 /* Call with priv->lock taken */
3015 static void
3016 update_rtx_receive_pt_map (GstRTSPStream * stream)
3017 {
3018   GstStructure *pt_map;
3019
3020   if (!stream->priv->rtxreceive)
3021     goto done;
3022
3023   pt_map = gst_structure_new_empty ("application/x-rtp-pt-map");
3024   g_hash_table_foreach (stream->priv->ptmap, (GHFunc) add_rtx_pt, pt_map);
3025   g_object_set (stream->priv->rtxreceive, "payload-type-map", pt_map, NULL);
3026   gst_structure_free (pt_map);
3027
3028 done:
3029   return;
3030 }
3031
3032 static void
3033 retrieve_ulpfec_pt (gpointer key, GstCaps * caps, GstElement * ulpfec_decoder)
3034 {
3035   guint pt = GPOINTER_TO_INT (key);
3036   const GstStructure *s = gst_caps_get_structure (caps, 0);
3037
3038   if (!g_strcmp0 (gst_structure_get_string (s, "encoding-name"), "ULPFEC"))
3039     g_object_set (ulpfec_decoder, "pt", pt, NULL);
3040 }
3041
3042 static void
3043 update_ulpfec_decoder_pt (GstRTSPStream * stream)
3044 {
3045   if (!stream->priv->ulpfec_decoder)
3046     goto done;
3047
3048   g_hash_table_foreach (stream->priv->ptmap, (GHFunc) retrieve_ulpfec_pt,
3049       stream->priv->ulpfec_decoder);
3050
3051 done:
3052   return;
3053 }
3054
3055 /**
3056  * gst_rtsp_stream_request_aux_receiver:
3057  * @stream: a #GstRTSPStream
3058  * @sessid: the session id
3059  *
3060  * Creating a rtxreceive bin
3061  *
3062  * Returns: (transfer full) (nullable): a #GstElement.
3063  *
3064  * Since: 1.16
3065  */
3066 GstElement *
3067 gst_rtsp_stream_request_aux_receiver (GstRTSPStream * stream, guint sessid)
3068 {
3069   GstElement *bin;
3070   GstPad *pad;
3071   gchar *name;
3072
3073   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
3074
3075   bin = gst_bin_new (NULL);
3076   stream->priv->rtxreceive = gst_element_factory_make ("rtprtxreceive", NULL);
3077   update_rtx_receive_pt_map (stream);
3078   update_ulpfec_decoder_pt (stream);
3079   gst_bin_add (GST_BIN (bin), gst_object_ref (stream->priv->rtxreceive));
3080
3081   pad = gst_element_get_static_pad (stream->priv->rtxreceive, "src");
3082   name = g_strdup_printf ("src_%u", sessid);
3083   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3084   g_free (name);
3085   gst_object_unref (pad);
3086
3087   pad = gst_element_get_static_pad (stream->priv->rtxreceive, "sink");
3088   name = g_strdup_printf ("sink_%u", sessid);
3089   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3090   g_free (name);
3091   gst_object_unref (pad);
3092
3093   return bin;
3094 }
3095
3096 /**
3097  * gst_rtsp_stream_set_pt_map:
3098  * @stream: a #GstRTSPStream
3099  * @pt: the pt
3100  * @caps: a #GstCaps
3101  *
3102  * Configure a pt map between @pt and @caps.
3103  */
3104 void
3105 gst_rtsp_stream_set_pt_map (GstRTSPStream * stream, guint pt, GstCaps * caps)
3106 {
3107   GstRTSPStreamPrivate *priv = stream->priv;
3108
3109   if (!GST_IS_CAPS (caps))
3110     return;
3111
3112   g_mutex_lock (&priv->lock);
3113   g_hash_table_insert (priv->ptmap, GINT_TO_POINTER (pt), gst_caps_ref (caps));
3114   update_rtx_receive_pt_map (stream);
3115   g_mutex_unlock (&priv->lock);
3116 }
3117
3118 /**
3119  * gst_rtsp_stream_set_publish_clock_mode:
3120  * @stream: a #GstRTSPStream
3121  * @mode: the clock publish mode
3122  *
3123  * Sets if and how the stream clock should be published according to RFC7273.
3124  *
3125  * Since: 1.8
3126  */
3127 void
3128 gst_rtsp_stream_set_publish_clock_mode (GstRTSPStream * stream,
3129     GstRTSPPublishClockMode mode)
3130 {
3131   GstRTSPStreamPrivate *priv;
3132
3133   priv = stream->priv;
3134   g_mutex_lock (&priv->lock);
3135   priv->publish_clock_mode = mode;
3136   g_mutex_unlock (&priv->lock);
3137 }
3138
3139 /**
3140  * gst_rtsp_stream_get_publish_clock_mode:
3141  * @stream: a #GstRTSPStream
3142  *
3143  * Gets if and how the stream clock should be published according to RFC7273.
3144  *
3145  * Returns: The GstRTSPPublishClockMode
3146  *
3147  * Since: 1.8
3148  */
3149 GstRTSPPublishClockMode
3150 gst_rtsp_stream_get_publish_clock_mode (GstRTSPStream * stream)
3151 {
3152   GstRTSPStreamPrivate *priv;
3153   GstRTSPPublishClockMode ret;
3154
3155   priv = stream->priv;
3156   g_mutex_lock (&priv->lock);
3157   ret = priv->publish_clock_mode;
3158   g_mutex_unlock (&priv->lock);
3159
3160   return ret;
3161 }
3162
3163 static GstCaps *
3164 request_pt_map (GstElement * rtpbin, guint session, guint pt,
3165     GstRTSPStream * stream)
3166 {
3167   GstRTSPStreamPrivate *priv = stream->priv;
3168   GstCaps *caps = NULL;
3169
3170   g_mutex_lock (&priv->lock);
3171
3172   if (priv->idx == session) {
3173     caps = g_hash_table_lookup (priv->ptmap, GINT_TO_POINTER (pt));
3174     if (caps) {
3175       GST_DEBUG ("Stream %p, pt %u: caps %" GST_PTR_FORMAT, stream, pt, caps);
3176       gst_caps_ref (caps);
3177     } else {
3178       GST_DEBUG ("Stream %p, pt %u: no caps", stream, pt);
3179     }
3180   }
3181
3182   g_mutex_unlock (&priv->lock);
3183
3184   return caps;
3185 }
3186
3187 static void
3188 pad_added (GstElement * rtpbin, GstPad * pad, GstRTSPStream * stream)
3189 {
3190   GstRTSPStreamPrivate *priv = stream->priv;
3191   gchar *name;
3192   GstPadLinkReturn ret;
3193   guint sessid;
3194
3195   GST_DEBUG ("Stream %p added pad %s:%s for pad %s:%s", stream,
3196       GST_DEBUG_PAD_NAME (pad), GST_DEBUG_PAD_NAME (priv->sinkpad));
3197
3198   name = gst_pad_get_name (pad);
3199   if (sscanf (name, "recv_rtp_src_%u", &sessid) != 1) {
3200     g_free (name);
3201     return;
3202   }
3203   g_free (name);
3204
3205   if (priv->idx != sessid)
3206     return;
3207
3208   if (gst_pad_is_linked (priv->sinkpad)) {
3209     GST_WARNING ("Stream %p: Pad %s:%s is linked already", stream,
3210         GST_DEBUG_PAD_NAME (priv->sinkpad));
3211     return;
3212   }
3213
3214   /* link the RTP pad to the session manager, it should not really fail unless
3215    * this is not really an RTP pad */
3216   ret = gst_pad_link (pad, priv->sinkpad);
3217   if (ret != GST_PAD_LINK_OK)
3218     goto link_failed;
3219   priv->recv_rtp_src = gst_object_ref (pad);
3220
3221   return;
3222
3223 /* ERRORS */
3224 link_failed:
3225   {
3226     GST_ERROR ("Stream %p: Failed to link pads %s:%s and %s:%s", stream,
3227         GST_DEBUG_PAD_NAME (pad), GST_DEBUG_PAD_NAME (priv->sinkpad));
3228   }
3229 }
3230
3231 static void
3232 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc,
3233     GstRTSPStream * stream)
3234 {
3235   /* TODO: What to do here other than this? */
3236   GST_DEBUG ("Stream %p: Got EOS", stream);
3237   gst_pad_send_event (stream->priv->sinkpad, gst_event_new_eos ());
3238 }
3239
3240 typedef struct _ProbeData ProbeData;
3241
3242 struct _ProbeData
3243 {
3244   GstRTSPStream *stream;
3245   /* existing sink, already linked to tee */
3246   GstElement *sink1;
3247   /* new sink, about to be linked */
3248   GstElement *sink2;
3249   /* new queue element, that will be linked to tee and sink1 */
3250   GstElement **queue1;
3251   /* new queue element, that will be linked to tee and sink2 */
3252   GstElement **queue2;
3253   GstPad *sink_pad;
3254   GstPad *tee_pad;
3255   guint index;
3256 };
3257
3258 static void
3259 free_cb_data (gpointer user_data)
3260 {
3261   ProbeData *data = user_data;
3262
3263   gst_object_unref (data->stream);
3264   gst_object_unref (data->sink1);
3265   gst_object_unref (data->sink2);
3266   gst_object_unref (data->sink_pad);
3267   gst_object_unref (data->tee_pad);
3268   g_free (data);
3269 }
3270
3271
3272 static void
3273 create_and_plug_queue_to_unlinked_stream (GstRTSPStream * stream,
3274     GstElement * tee, GstElement * sink, GstElement ** queue)
3275 {
3276   GstRTSPStreamPrivate *priv = stream->priv;
3277   GstPad *tee_pad;
3278   GstPad *queue_pad;
3279   GstPad *sink_pad;
3280
3281   /* create queue for the new stream */
3282   *queue = gst_element_factory_make ("queue", NULL);
3283   g_object_set (*queue, "max-size-buffers", 1, "max-size-bytes", 0,
3284       "max-size-time", G_GINT64_CONSTANT (0), NULL);
3285   gst_bin_add (priv->joined_bin, *queue);
3286
3287   /* link tee to queue */
3288   tee_pad = gst_element_request_pad_simple (tee, "src_%u");
3289   queue_pad = gst_element_get_static_pad (*queue, "sink");
3290   gst_pad_link (tee_pad, queue_pad);
3291   gst_object_unref (queue_pad);
3292   gst_object_unref (tee_pad);
3293
3294   /* link queue to sink */
3295   queue_pad = gst_element_get_static_pad (*queue, "src");
3296   sink_pad = gst_element_get_static_pad (sink, "sink");
3297   gst_pad_link (queue_pad, sink_pad);
3298   gst_object_unref (queue_pad);
3299   gst_object_unref (sink_pad);
3300
3301   gst_element_sync_state_with_parent (sink);
3302   gst_element_sync_state_with_parent (*queue);
3303 }
3304
3305 static GstPadProbeReturn
3306 create_and_plug_queue_to_linked_stream_probe_cb (GstPad * inpad,
3307     GstPadProbeInfo * info, gpointer user_data)
3308 {
3309   GstRTSPStreamPrivate *priv;
3310   ProbeData *data = user_data;
3311   GstRTSPStream *stream;
3312   GstElement **queue1;
3313   GstElement **queue2;
3314   GstPad *sink_pad;
3315   GstPad *tee_pad;
3316   GstPad *queue_pad;
3317   guint index;
3318
3319   stream = data->stream;
3320   priv = stream->priv;
3321   queue1 = data->queue1;
3322   queue2 = data->queue2;
3323   sink_pad = data->sink_pad;
3324   tee_pad = data->tee_pad;
3325   index = data->index;
3326
3327   /* unlink tee and the existing sink:
3328    *   .-----.    .---------.
3329    *   | tee |    |  sink1  |
3330    * sink   src->sink       |
3331    *   '-----'    '---------'
3332    */
3333   g_assert (gst_pad_unlink (tee_pad, sink_pad));
3334
3335   /* add queue to the already existing stream */
3336   *queue1 = gst_element_factory_make ("queue", NULL);
3337   g_object_set (*queue1, "max-size-buffers", 1, "max-size-bytes", 0,
3338       "max-size-time", G_GINT64_CONSTANT (0), NULL);
3339   gst_bin_add (priv->joined_bin, *queue1);
3340
3341   /* link tee, queue and sink:
3342    *   .-----.    .---------.    .---------.
3343    *   | tee |    |  queue1 |    | sink1   |
3344    * sink   src->sink      src->sink       |
3345    *   '-----'    '---------'    '---------'
3346    */
3347   queue_pad = gst_element_get_static_pad (*queue1, "sink");
3348   gst_pad_link (tee_pad, queue_pad);
3349   gst_object_unref (queue_pad);
3350   queue_pad = gst_element_get_static_pad (*queue1, "src");
3351   gst_pad_link (queue_pad, sink_pad);
3352   gst_object_unref (queue_pad);
3353
3354   gst_element_sync_state_with_parent (*queue1);
3355
3356   /* create queue and link it to tee and the new sink */
3357   create_and_plug_queue_to_unlinked_stream (stream,
3358       priv->tee[index], data->sink2, queue2);
3359
3360   /* the final stream:
3361    *
3362    *    .-----.    .---------.    .---------.
3363    *    | tee |    |  queue1 |    | sink1   |
3364    *  sink   src->sink      src->sink       |
3365    *    |     |    '---------'    '---------'
3366    *    |     |    .---------.    .---------.
3367    *    |     |    |  queue2 |    | sink2   |
3368    *    |    src->sink      src->sink       |
3369    *    '-----'    '---------'    '---------'
3370    */
3371
3372   return GST_PAD_PROBE_REMOVE;
3373 }
3374
3375 static void
3376 create_and_plug_queue_to_linked_stream (GstRTSPStream * stream,
3377     GstElement * sink1, GstElement * sink2, guint index, GstElement ** queue1,
3378     GstElement ** queue2)
3379 {
3380   ProbeData *data;
3381
3382   data = g_new0 (ProbeData, 1);
3383   data->stream = gst_object_ref (stream);
3384   data->sink1 = gst_object_ref (sink1);
3385   data->sink2 = gst_object_ref (sink2);
3386   data->queue1 = queue1;
3387   data->queue2 = queue2;
3388   data->index = index;
3389
3390   data->sink_pad = gst_element_get_static_pad (sink1, "sink");
3391   g_assert (data->sink_pad);
3392   data->tee_pad = gst_pad_get_peer (data->sink_pad);
3393   g_assert (data->tee_pad);
3394
3395   gst_pad_add_probe (data->tee_pad, GST_PAD_PROBE_TYPE_IDLE,
3396       create_and_plug_queue_to_linked_stream_probe_cb, data, free_cb_data);
3397 }
3398
3399 static void
3400 plug_udp_sink (GstRTSPStream * stream, GstElement * sink_to_plug,
3401     GstElement ** queue_to_plug, guint index, gboolean is_mcast)
3402 {
3403   GstRTSPStreamPrivate *priv = stream->priv;
3404   GstElement *existing_sink;
3405
3406   if (is_mcast)
3407     existing_sink = priv->udpsink[index];
3408   else
3409     existing_sink = priv->mcast_udpsink[index];
3410
3411   GST_DEBUG_OBJECT (stream, "plug %s sink", is_mcast ? "mcast" : "udp");
3412
3413   /* add sink to the bin */
3414   gst_bin_add (priv->joined_bin, sink_to_plug);
3415
3416   if (priv->appsink[index] && existing_sink) {
3417
3418     /* queues are already added for the existing stream, add one for
3419        the newly added udp stream */
3420     create_and_plug_queue_to_unlinked_stream (stream, priv->tee[index],
3421         sink_to_plug, queue_to_plug);
3422
3423   } else if (priv->appsink[index] || existing_sink) {
3424     GstElement **queue;
3425     GstElement *element;
3426
3427     /* add queue to the already existing stream plus the newly created udp
3428        stream */
3429     if (priv->appsink[index]) {
3430       element = priv->appsink[index];
3431       queue = &priv->appqueue[index];
3432     } else {
3433       element = existing_sink;
3434       if (is_mcast)
3435         queue = &priv->udpqueue[index];
3436       else
3437         queue = &priv->mcast_udpqueue[index];
3438     }
3439
3440     create_and_plug_queue_to_linked_stream (stream, element, sink_to_plug,
3441         index, queue, queue_to_plug);
3442
3443   } else {
3444     GstPad *tee_pad;
3445     GstPad *sink_pad;
3446
3447     GST_DEBUG_OBJECT (stream, "creating first stream");
3448
3449     /* no need to add queues */
3450     tee_pad = gst_element_request_pad_simple (priv->tee[index], "src_%u");
3451     sink_pad = gst_element_get_static_pad (sink_to_plug, "sink");
3452     gst_pad_link (tee_pad, sink_pad);
3453     gst_object_unref (tee_pad);
3454     gst_object_unref (sink_pad);
3455   }
3456
3457   gst_element_sync_state_with_parent (sink_to_plug);
3458 }
3459
3460 static void
3461 plug_tcp_sink (GstRTSPStream * stream, guint index)
3462 {
3463   GstRTSPStreamPrivate *priv = stream->priv;
3464
3465   GST_DEBUG_OBJECT (stream, "plug tcp sink");
3466
3467   /* add sink to the bin */
3468   gst_bin_add (priv->joined_bin, priv->appsink[index]);
3469
3470   if (priv->mcast_udpsink[index] && priv->udpsink[index]) {
3471
3472     /* queues are already added for the existing stream, add one for
3473        the newly added tcp stream */
3474     create_and_plug_queue_to_unlinked_stream (stream,
3475         priv->tee[index], priv->appsink[index], &priv->appqueue[index]);
3476
3477   } else if (priv->mcast_udpsink[index] || priv->udpsink[index]) {
3478     GstElement **queue;
3479     GstElement *element;
3480
3481     /* add queue to the already existing stream plus the newly created tcp
3482        stream */
3483     if (priv->mcast_udpsink[index]) {
3484       element = priv->mcast_udpsink[index];
3485       queue = &priv->mcast_udpqueue[index];
3486     } else {
3487       element = priv->udpsink[index];
3488       queue = &priv->udpqueue[index];
3489     }
3490
3491     create_and_plug_queue_to_linked_stream (stream, element,
3492         priv->appsink[index], index, queue, &priv->appqueue[index]);
3493
3494   } else {
3495     GstPad *tee_pad;
3496     GstPad *sink_pad;
3497
3498     /* no need to add queues */
3499     tee_pad = gst_element_request_pad_simple (priv->tee[index], "src_%u");
3500     sink_pad = gst_element_get_static_pad (priv->appsink[index], "sink");
3501     gst_pad_link (tee_pad, sink_pad);
3502     gst_object_unref (tee_pad);
3503     gst_object_unref (sink_pad);
3504   }
3505
3506   gst_element_sync_state_with_parent (priv->appsink[index]);
3507 }
3508
3509 static void
3510 plug_sink (GstRTSPStream * stream, const GstRTSPTransport * transport,
3511     guint index)
3512 {
3513   GstRTSPStreamPrivate *priv;
3514   gboolean is_tcp, is_udp, is_mcast;
3515   priv = stream->priv;
3516
3517   is_tcp = transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP;
3518   is_udp = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP;
3519   is_mcast = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST;
3520
3521   if (is_udp)
3522     plug_udp_sink (stream, priv->udpsink[index],
3523         &priv->udpqueue[index], index, FALSE);
3524
3525   else if (is_mcast)
3526     plug_udp_sink (stream, priv->mcast_udpsink[index],
3527         &priv->mcast_udpqueue[index], index, TRUE);
3528
3529   else if (is_tcp)
3530     plug_tcp_sink (stream, index);
3531 }
3532
3533 /* must be called with lock */
3534 static gboolean
3535 create_sender_part (GstRTSPStream * stream, const GstRTSPTransport * transport)
3536 {
3537   GstRTSPStreamPrivate *priv;
3538   GstPad *pad;
3539   GstBin *bin;
3540   gboolean is_tcp, is_udp, is_mcast;
3541   gint mcast_ttl = 0;
3542   gint i;
3543
3544   GST_DEBUG_OBJECT (stream, "create sender part");
3545   priv = stream->priv;
3546   bin = priv->joined_bin;
3547
3548   is_tcp = transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP;
3549   is_udp = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP;
3550   is_mcast = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST;
3551
3552   if (is_mcast)
3553     mcast_ttl = transport->ttl;
3554
3555   GST_DEBUG_OBJECT (stream, "tcp: %d, udp: %d, mcast: %d (ttl: %d)", is_tcp,
3556       is_udp, is_mcast, mcast_ttl);
3557
3558   if (is_udp && !priv->server_addr_v4 && !priv->server_addr_v6) {
3559     GST_WARNING_OBJECT (stream, "no sockets assigned for UDP");
3560     return FALSE;
3561   }
3562
3563   if (is_mcast && !priv->mcast_addr_v4 && !priv->mcast_addr_v6) {
3564     GST_WARNING_OBJECT (stream, "no sockets assigned for UDP multicast");
3565     return FALSE;
3566   }
3567
3568   if (g_object_class_find_property (G_OBJECT_GET_CLASS (priv->payloader),
3569           "onvif-no-rate-control"))
3570     g_object_set (priv->payloader, "onvif-no-rate-control",
3571         !priv->do_rate_control, NULL);
3572
3573   for (i = 0; i < (priv->enable_rtcp ? 2 : 1); i++) {
3574     gboolean link_tee = FALSE;
3575     /* For the sender we create this bit of pipeline for both
3576      * RTP and RTCP (when enabled).
3577      * Initially there will be only one active transport for
3578      * the stream, so the pipeline will look like this:
3579      *
3580      * .--------.      .-----.    .---------.
3581      * | rtpbin |      | tee |    |  sink   |
3582      * |       send->sink   src->sink       |
3583      * '--------'      '-----'    '---------'
3584      *
3585      * For each new transport, the already existing branch will
3586      * be reconfigured by adding a queue element:
3587      *
3588      * .--------.      .-----.    .---------.    .---------.
3589      * | rtpbin |      | tee |    |  queue  |    | udpsink |
3590      * |       send->sink   src->sink      src->sink       |
3591      * '--------'      |     |    '---------'    '---------'
3592      *                 |     |    .---------.    .---------.
3593      *                 |     |    |  queue  |    | udpsink |
3594      *                 |    src->sink      src->sink       |
3595      *                 |     |    '---------'    '---------'
3596      *                 |     |    .---------.    .---------.
3597      *                 |     |    |  queue  |    | appsink |
3598      *                 |    src->sink      src->sink       |
3599      *                 '-----'    '---------'    '---------'
3600      */
3601
3602     /* Only link the RTP send src if we're going to send RTP, link
3603      * the RTCP send src always */
3604     if (!priv->srcpad && i == 0)
3605       continue;
3606
3607     if (!priv->tee[i]) {
3608       /* make tee for RTP/RTCP */
3609       priv->tee[i] = gst_element_factory_make ("tee", NULL);
3610       gst_bin_add (bin, priv->tee[i]);
3611       link_tee = TRUE;
3612     }
3613
3614     if (is_udp && !priv->udpsink[i]) {
3615       /* we create only one pair of udpsinks for IPv4 and IPv6 */
3616       create_and_configure_udpsink (stream, &priv->udpsink[i],
3617           priv->socket_v4[i], priv->socket_v6[i], FALSE, (i == 0), mcast_ttl);
3618       plug_sink (stream, transport, i);
3619     } else if (is_mcast && !priv->mcast_udpsink[i]) {
3620       /* we create only one pair of mcast-udpsinks for IPv4 and IPv6 */
3621       create_and_configure_udpsink (stream, &priv->mcast_udpsink[i],
3622           priv->mcast_socket_v4[i], priv->mcast_socket_v6[i], TRUE, (i == 0),
3623           mcast_ttl);
3624       plug_sink (stream, transport, i);
3625     } else if (is_tcp && !priv->appsink[i]) {
3626       /* make appsink */
3627       priv->appsink[i] = gst_element_factory_make ("appsink", NULL);
3628       g_object_set (priv->appsink[i], "emit-signals", FALSE, "buffer-list",
3629           TRUE, "max-buffers", 1, NULL);
3630
3631       if (i == 0)
3632         g_object_set (priv->appsink[i], "sync", priv->do_rate_control, NULL);
3633
3634       /* we need to set sync and preroll to FALSE for the sink to avoid
3635        * deadlock. This is only needed for sink sending RTCP data. */
3636       if (i == 1)
3637         g_object_set (priv->appsink[i], "async", FALSE, "sync", FALSE, NULL);
3638
3639       gst_app_sink_set_callbacks (GST_APP_SINK_CAST (priv->appsink[i]),
3640           &sink_cb, stream, NULL);
3641       plug_sink (stream, transport, i);
3642     }
3643
3644     if (link_tee) {
3645       /* and link to rtpbin send pad */
3646       gst_element_sync_state_with_parent (priv->tee[i]);
3647       pad = gst_element_get_static_pad (priv->tee[i], "sink");
3648       gst_pad_link (priv->send_src[i], pad);
3649       gst_object_unref (pad);
3650     }
3651   }
3652
3653   return TRUE;
3654 }
3655
3656 /* must be called with lock */
3657 static void
3658 plug_src (GstRTSPStream * stream, GstBin * bin, GstElement * src,
3659     GstElement * funnel)
3660 {
3661   GstRTSPStreamPrivate *priv;
3662   GstPad *pad, *selpad;
3663   gulong id = 0;
3664
3665   priv = stream->priv;
3666
3667   /* add src */
3668   gst_bin_add (bin, src);
3669
3670   pad = gst_element_get_static_pad (src, "src");
3671   if (priv->srcpad) {
3672     /* block pad so src can't push data while it's not yet linked */
3673     id = gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BLOCK |
3674         GST_PAD_PROBE_TYPE_BUFFER, NULL, NULL, NULL);
3675     /* we set and keep these to playing so that they don't cause NO_PREROLL return
3676      * values. This is only relevant for PLAY pipelines */
3677     gst_element_set_state (src, GST_STATE_PLAYING);
3678     gst_element_set_locked_state (src, TRUE);
3679   }
3680
3681   /* and link to the funnel */
3682   selpad = gst_element_request_pad_simple (funnel, "sink_%u");
3683   gst_pad_link (pad, selpad);
3684   if (id != 0)
3685     gst_pad_remove_probe (pad, id);
3686   gst_object_unref (pad);
3687   gst_object_unref (selpad);
3688 }
3689
3690 /* must be called with lock */
3691 static gboolean
3692 create_receiver_part (GstRTSPStream * stream, const GstRTSPTransport *
3693     transport)
3694 {
3695   gboolean ret = FALSE;
3696   GstRTSPStreamPrivate *priv;
3697   GstPad *pad;
3698   GstBin *bin;
3699   gboolean tcp;
3700   gboolean udp;
3701   gboolean mcast;
3702   gboolean secure;
3703   gint i;
3704   GstCaps *rtp_caps;
3705   GstCaps *rtcp_caps;
3706
3707   GST_DEBUG_OBJECT (stream, "create receiver part");
3708   priv = stream->priv;
3709   bin = priv->joined_bin;
3710
3711   tcp = transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP;
3712   udp = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP;
3713   mcast = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST;
3714   secure = (priv->profiles & GST_RTSP_PROFILE_SAVP)
3715       || (priv->profiles & GST_RTSP_PROFILE_SAVPF);
3716
3717   if (secure) {
3718     rtp_caps = gst_caps_new_empty_simple ("application/x-srtp");
3719     rtcp_caps = gst_caps_new_empty_simple ("application/x-srtcp");
3720   } else {
3721     rtp_caps = gst_caps_new_empty_simple ("application/x-rtp");
3722     rtcp_caps = gst_caps_new_empty_simple ("application/x-rtcp");
3723   }
3724
3725   GST_DEBUG_OBJECT (stream,
3726       "RTP caps: %" GST_PTR_FORMAT " RTCP caps: %" GST_PTR_FORMAT, rtp_caps,
3727       rtcp_caps);
3728
3729   for (i = 0; i < (priv->enable_rtcp ? 2 : 1); i++) {
3730     /* For the receiver we create this bit of pipeline for both
3731      * RTP and RTCP (when enabled). We receive RTP/RTCP on appsrc and udpsrc
3732      * and it is all funneled into the rtpbin receive pad.
3733      *
3734      *
3735      * .--------.     .--------.    .--------.
3736      * | udpsrc |     | funnel |    | rtpbin |
3737      * | RTP    src->sink      src->sink     |
3738      * '--------'     |        |    |        |
3739      * .--------.     |        |    |        |
3740      * | appsrc |     |        |    |        |
3741      * | RTP    src->sink      |    |        |
3742      * '--------'     '--------'    |        |
3743      *                              |        |
3744      * .--------.     .--------.    |        |
3745      * | udpsrc |     | funnel |    |        |
3746      * | RTCP   src->sink      src->sink     |
3747      * '--------'     |        |    '--------'
3748      * .--------.     |        |
3749      * | appsrc |     |        |
3750      * | RTCP   src->sink      |
3751      * '--------'     '--------'
3752      */
3753
3754     if (!priv->sinkpad && i == 0) {
3755       /* Only connect recv RTP sink if we expect to receive RTP. Connect recv
3756        * RTCP sink always */
3757       continue;
3758     }
3759
3760     /* make funnel for the RTP/RTCP receivers */
3761     if (!priv->funnel[i]) {
3762       priv->funnel[i] = gst_element_factory_make ("funnel", NULL);
3763       gst_bin_add (bin, priv->funnel[i]);
3764
3765       pad = gst_element_get_static_pad (priv->funnel[i], "src");
3766       gst_pad_link (pad, priv->recv_sink[i]);
3767       gst_object_unref (pad);
3768     }
3769
3770     if (udp && !priv->udpsrc_v4[i] && priv->server_addr_v4) {
3771       GST_DEBUG_OBJECT (stream, "udp IPv4, create and configure udpsources");
3772       if (!create_and_configure_udpsource (&priv->udpsrc_v4[i],
3773               priv->socket_v4[i]))
3774         goto done;
3775
3776       if (i == 0) {
3777         g_object_set (priv->udpsrc_v4[i], "caps", rtp_caps, NULL);
3778       } else {
3779         g_object_set (priv->udpsrc_v4[i], "caps", rtcp_caps, NULL);
3780
3781         /* block early rtcp packets, pipeline not ready */
3782         g_assert (priv->block_early_rtcp_pad == NULL);
3783         priv->block_early_rtcp_pad = gst_element_get_static_pad
3784             (priv->udpsrc_v4[i], "src");
3785         priv->block_early_rtcp_probe = gst_pad_add_probe
3786             (priv->block_early_rtcp_pad,
3787             GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER, NULL, NULL,
3788             NULL);
3789       }
3790
3791       plug_src (stream, bin, priv->udpsrc_v4[i], priv->funnel[i]);
3792     }
3793
3794     if (udp && !priv->udpsrc_v6[i] && priv->server_addr_v6) {
3795       GST_DEBUG_OBJECT (stream, "udp IPv6, create and configure udpsources");
3796       if (!create_and_configure_udpsource (&priv->udpsrc_v6[i],
3797               priv->socket_v6[i]))
3798         goto done;
3799
3800       if (i == 0) {
3801         g_object_set (priv->udpsrc_v6[i], "caps", rtp_caps, NULL);
3802       } else {
3803         g_object_set (priv->udpsrc_v6[i], "caps", rtcp_caps, NULL);
3804
3805         /* block early rtcp packets, pipeline not ready */
3806         g_assert (priv->block_early_rtcp_pad_ipv6 == NULL);
3807         priv->block_early_rtcp_pad_ipv6 = gst_element_get_static_pad
3808             (priv->udpsrc_v6[i], "src");
3809         priv->block_early_rtcp_probe_ipv6 = gst_pad_add_probe
3810             (priv->block_early_rtcp_pad_ipv6,
3811             GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER, NULL, NULL,
3812             NULL);
3813       }
3814
3815       plug_src (stream, bin, priv->udpsrc_v6[i], priv->funnel[i]);
3816     }
3817
3818     if (mcast && !priv->mcast_udpsrc_v4[i] && priv->mcast_addr_v4) {
3819       GST_DEBUG_OBJECT (stream, "mcast IPv4, create and configure udpsources");
3820       if (!create_and_configure_udpsource (&priv->mcast_udpsrc_v4[i],
3821               priv->mcast_socket_v4[i]))
3822         goto done;
3823
3824       if (i == 0) {
3825         g_object_set (priv->mcast_udpsrc_v4[i], "caps", rtp_caps, NULL);
3826       } else {
3827         g_object_set (priv->mcast_udpsrc_v4[i], "caps", rtcp_caps, NULL);
3828       }
3829
3830       plug_src (stream, bin, priv->mcast_udpsrc_v4[i], priv->funnel[i]);
3831     }
3832
3833     if (mcast && !priv->mcast_udpsrc_v6[i] && priv->mcast_addr_v6) {
3834       GST_DEBUG_OBJECT (stream, "mcast IPv6, create and configure udpsources");
3835       if (!create_and_configure_udpsource (&priv->mcast_udpsrc_v6[i],
3836               priv->mcast_socket_v6[i]))
3837         goto done;
3838
3839       if (i == 0) {
3840         g_object_set (priv->mcast_udpsrc_v6[i], "caps", rtp_caps, NULL);
3841       } else {
3842         g_object_set (priv->mcast_udpsrc_v6[i], "caps", rtcp_caps, NULL);
3843       }
3844
3845       plug_src (stream, bin, priv->mcast_udpsrc_v6[i], priv->funnel[i]);
3846     }
3847
3848     if (tcp && !priv->appsrc[i]) {
3849       /* make and add appsrc */
3850       priv->appsrc[i] = gst_element_factory_make ("appsrc", NULL);
3851       priv->appsrc_base_time[i] = -1;
3852       g_object_set (priv->appsrc[i], "format", GST_FORMAT_TIME, "is-live",
3853           TRUE, NULL);
3854       plug_src (stream, bin, priv->appsrc[i], priv->funnel[i]);
3855     }
3856
3857     gst_element_sync_state_with_parent (priv->funnel[i]);
3858   }
3859
3860   ret = TRUE;
3861
3862 done:
3863   gst_caps_unref (rtp_caps);
3864   gst_caps_unref (rtcp_caps);
3865   return ret;
3866 }
3867
3868 gboolean
3869 gst_rtsp_stream_is_tcp_receiver (GstRTSPStream * stream)
3870 {
3871   GstRTSPStreamPrivate *priv;
3872   gboolean ret = FALSE;
3873
3874   priv = stream->priv;
3875   g_mutex_lock (&priv->lock);
3876   ret = (priv->sinkpad != NULL && priv->appsrc[0] != NULL);
3877   g_mutex_unlock (&priv->lock);
3878
3879   return ret;
3880 }
3881
3882 static gboolean
3883 check_mcast_client_addr (GstRTSPStream * stream, const GstRTSPTransport * tr)
3884 {
3885   GstRTSPStreamPrivate *priv = stream->priv;
3886   GList *walk;
3887
3888   if (priv->mcast_clients == NULL)
3889     goto no_addr;
3890
3891   if (tr == NULL)
3892     goto no_transport;
3893
3894   if (tr->destination == NULL)
3895     goto no_destination;
3896
3897   for (walk = priv->mcast_clients; walk; walk = g_list_next (walk)) {
3898     UdpClientAddrInfo *cli = walk->data;
3899
3900     if ((g_strcmp0 (cli->address, tr->destination) == 0) &&
3901         (cli->rtp_port == tr->port.min))
3902       return TRUE;
3903   }
3904
3905   return FALSE;
3906
3907 no_addr:
3908   {
3909     GST_WARNING_OBJECT (stream, "Adding mcast transport, but no mcast address "
3910         "has been reserved");
3911     return FALSE;
3912   }
3913 no_transport:
3914   {
3915     GST_WARNING_OBJECT (stream, "Adding mcast transport, but no transport "
3916         "has been provided");
3917     return FALSE;
3918   }
3919 no_destination:
3920   {
3921     GST_WARNING_OBJECT (stream, "Adding mcast transport, but it doesn't match "
3922         "the reserved address");
3923     return FALSE;
3924   }
3925 }
3926
3927 /**
3928  * gst_rtsp_stream_join_bin:
3929  * @stream: a #GstRTSPStream
3930  * @bin: (transfer none): a #GstBin to join
3931  * @rtpbin: (transfer none): a rtpbin element in @bin
3932  * @state: the target state of the new elements
3933  *
3934  * Join the #GstBin @bin that contains the element @rtpbin.
3935  *
3936  * @stream will link to @rtpbin, which must be inside @bin. The elements
3937  * added to @bin will be set to the state given in @state.
3938  *
3939  * Returns: %TRUE on success.
3940  */
3941 gboolean
3942 gst_rtsp_stream_join_bin (GstRTSPStream * stream, GstBin * bin,
3943     GstElement * rtpbin, GstState state)
3944 {
3945   GstRTSPStreamPrivate *priv;
3946   guint idx;
3947   gchar *name;
3948   GstPadLinkReturn ret;
3949
3950   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
3951   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
3952   g_return_val_if_fail (GST_IS_ELEMENT (rtpbin), FALSE);
3953
3954   priv = stream->priv;
3955
3956   g_mutex_lock (&priv->lock);
3957   if (priv->joined_bin != NULL)
3958     goto was_joined;
3959
3960   /* create a session with the same index as the stream */
3961   idx = priv->idx;
3962
3963   GST_INFO ("stream %p joining bin as session %u", stream, idx);
3964
3965   if (priv->profiles & GST_RTSP_PROFILE_SAVP
3966       || priv->profiles & GST_RTSP_PROFILE_SAVPF) {
3967     /* For SRTP */
3968     g_signal_connect (rtpbin, "request-rtp-encoder",
3969         (GCallback) request_rtp_encoder, stream);
3970     g_signal_connect (rtpbin, "request-rtcp-encoder",
3971         (GCallback) request_rtcp_encoder, stream);
3972     g_signal_connect (rtpbin, "request-rtp-decoder",
3973         (GCallback) request_rtp_rtcp_decoder, stream);
3974     g_signal_connect (rtpbin, "request-rtcp-decoder",
3975         (GCallback) request_rtp_rtcp_decoder, stream);
3976   }
3977
3978   if (priv->sinkpad) {
3979     g_signal_connect (rtpbin, "request-pt-map",
3980         (GCallback) request_pt_map, stream);
3981   }
3982
3983   /* get pads from the RTP session element for sending and receiving
3984    * RTP/RTCP*/
3985   if (priv->srcpad) {
3986     /* get a pad for sending RTP */
3987     name = g_strdup_printf ("send_rtp_sink_%u", idx);
3988     priv->send_rtp_sink = gst_element_request_pad_simple (rtpbin, name);
3989     g_free (name);
3990
3991     /* link the RTP pad to the session manager, it should not really fail unless
3992      * this is not really an RTP pad */
3993     ret = gst_pad_link (priv->srcpad, priv->send_rtp_sink);
3994     if (ret != GST_PAD_LINK_OK)
3995       goto link_failed;
3996
3997     name = g_strdup_printf ("send_rtp_src_%u", idx);
3998     priv->send_src[0] = gst_element_get_static_pad (rtpbin, name);
3999     g_free (name);
4000   } else {
4001     /* RECORD case: need to connect our sinkpad from here */
4002     g_signal_connect (rtpbin, "pad-added", (GCallback) pad_added, stream);
4003     /* EOS */
4004     g_signal_connect (rtpbin, "on-npt-stop", (GCallback) on_npt_stop, stream);
4005
4006     name = g_strdup_printf ("recv_rtp_sink_%u", idx);
4007     priv->recv_sink[0] = gst_element_request_pad_simple (rtpbin, name);
4008     g_free (name);
4009   }
4010
4011   if (priv->enable_rtcp) {
4012     name = g_strdup_printf ("send_rtcp_src_%u", idx);
4013     priv->send_src[1] = gst_element_request_pad_simple (rtpbin, name);
4014     g_free (name);
4015
4016     name = g_strdup_printf ("recv_rtcp_sink_%u", idx);
4017     priv->recv_sink[1] = gst_element_request_pad_simple (rtpbin, name);
4018     g_free (name);
4019   }
4020
4021   /* get the session */
4022   g_signal_emit_by_name (rtpbin, "get-internal-session", idx, &priv->session);
4023
4024   g_signal_connect (priv->session, "on-new-ssrc", (GCallback) on_new_ssrc,
4025       stream);
4026   g_signal_connect (priv->session, "on-ssrc-sdes", (GCallback) on_ssrc_sdes,
4027       stream);
4028   g_signal_connect (priv->session, "on-ssrc-active",
4029       (GCallback) on_ssrc_active, stream);
4030   g_signal_connect (priv->session, "on-bye-ssrc", (GCallback) on_bye_ssrc,
4031       stream);
4032   g_signal_connect (priv->session, "on-bye-timeout",
4033       (GCallback) on_bye_timeout, stream);
4034   g_signal_connect (priv->session, "on-timeout", (GCallback) on_timeout,
4035       stream);
4036
4037   /* signal for sender ssrc */
4038   g_signal_connect (priv->session, "on-new-sender-ssrc",
4039       (GCallback) on_new_sender_ssrc, stream);
4040   g_signal_connect (priv->session, "on-sender-ssrc-active",
4041       (GCallback) on_sender_ssrc_active, stream);
4042
4043   g_object_set (priv->session, "disable-sr-timestamp", !priv->do_rate_control,
4044       NULL);
4045
4046   if (priv->srcpad) {
4047     /* be notified of caps changes */
4048     priv->caps_sig = g_signal_connect (priv->send_src[0], "notify::caps",
4049         (GCallback) caps_notify, stream);
4050     priv->caps = gst_pad_get_current_caps (priv->send_src[0]);
4051   }
4052
4053   priv->joined_bin = bin;
4054   GST_DEBUG_OBJECT (stream, "successfully joined bin");
4055   g_mutex_unlock (&priv->lock);
4056
4057   return TRUE;
4058
4059   /* ERRORS */
4060 was_joined:
4061   {
4062     g_mutex_unlock (&priv->lock);
4063     return TRUE;
4064   }
4065 link_failed:
4066   {
4067     GST_WARNING ("failed to link stream %u", idx);
4068     gst_object_unref (priv->send_rtp_sink);
4069     priv->send_rtp_sink = NULL;
4070     g_mutex_unlock (&priv->lock);
4071     return FALSE;
4072   }
4073 }
4074
4075 static void
4076 clear_element (GstBin * bin, GstElement ** elementptr)
4077 {
4078   if (*elementptr) {
4079     gst_element_set_locked_state (*elementptr, FALSE);
4080     gst_element_set_state (*elementptr, GST_STATE_NULL);
4081     if (GST_ELEMENT_PARENT (*elementptr))
4082       gst_bin_remove (bin, *elementptr);
4083     else
4084       gst_object_unref (*elementptr);
4085     *elementptr = NULL;
4086   }
4087 }
4088
4089 /**
4090  * gst_rtsp_stream_leave_bin:
4091  * @stream: a #GstRTSPStream
4092  * @bin: (transfer none): a #GstBin
4093  * @rtpbin: (transfer none): a rtpbin #GstElement
4094  *
4095  * Remove the elements of @stream from @bin.
4096  *
4097  * Return: %TRUE on success.
4098  */
4099 gboolean
4100 gst_rtsp_stream_leave_bin (GstRTSPStream * stream, GstBin * bin,
4101     GstElement * rtpbin)
4102 {
4103   GstRTSPStreamPrivate *priv;
4104   gint i;
4105
4106   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4107   g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
4108   g_return_val_if_fail (GST_IS_ELEMENT (rtpbin), FALSE);
4109
4110   priv = stream->priv;
4111
4112   g_mutex_lock (&priv->send_lock);
4113   priv->continue_sending = FALSE;
4114   priv->send_cookie++;
4115   g_cond_signal (&priv->send_cond);
4116   g_mutex_unlock (&priv->send_lock);
4117
4118   if (priv->send_thread) {
4119     g_thread_join (priv->send_thread);
4120   }
4121
4122   g_mutex_lock (&priv->lock);
4123   if (priv->joined_bin == NULL)
4124     goto was_not_joined;
4125   if (priv->joined_bin != bin)
4126     goto wrong_bin;
4127
4128   priv->joined_bin = NULL;
4129
4130   /* all transports must be removed by now */
4131   if (priv->transports != NULL)
4132     goto transports_not_removed;
4133
4134   if (priv->send_pool) {
4135     GThreadPool *slask;
4136
4137     slask = priv->send_pool;
4138     priv->send_pool = NULL;
4139     g_mutex_unlock (&priv->lock);
4140     g_thread_pool_free (slask, TRUE, TRUE);
4141     g_mutex_lock (&priv->lock);
4142   }
4143
4144   clear_tr_cache (priv);
4145
4146   GST_INFO ("stream %p leaving bin", stream);
4147
4148   if (priv->srcpad) {
4149     gst_pad_unlink (priv->srcpad, priv->send_rtp_sink);
4150
4151     g_signal_handler_disconnect (priv->send_src[0], priv->caps_sig);
4152     gst_element_release_request_pad (rtpbin, priv->send_rtp_sink);
4153     gst_object_unref (priv->send_rtp_sink);
4154     priv->send_rtp_sink = NULL;
4155   } else if (priv->recv_rtp_src) {
4156     gst_pad_unlink (priv->recv_rtp_src, priv->sinkpad);
4157     gst_object_unref (priv->recv_rtp_src);
4158     priv->recv_rtp_src = NULL;
4159   }
4160
4161   for (i = 0; i < (priv->enable_rtcp ? 2 : 1); i++) {
4162     clear_element (bin, &priv->udpsrc_v4[i]);
4163     clear_element (bin, &priv->udpsrc_v6[i]);
4164     clear_element (bin, &priv->udpqueue[i]);
4165     clear_element (bin, &priv->udpsink[i]);
4166
4167     clear_element (bin, &priv->mcast_udpsrc_v4[i]);
4168     clear_element (bin, &priv->mcast_udpsrc_v6[i]);
4169     clear_element (bin, &priv->mcast_udpqueue[i]);
4170     clear_element (bin, &priv->mcast_udpsink[i]);
4171
4172     clear_element (bin, &priv->appsrc[i]);
4173     clear_element (bin, &priv->appqueue[i]);
4174     clear_element (bin, &priv->appsink[i]);
4175
4176     clear_element (bin, &priv->tee[i]);
4177     clear_element (bin, &priv->funnel[i]);
4178
4179     if (priv->sinkpad || i == 1) {
4180       gst_element_release_request_pad (rtpbin, priv->recv_sink[i]);
4181       gst_object_unref (priv->recv_sink[i]);
4182       priv->recv_sink[i] = NULL;
4183     }
4184   }
4185
4186   if (priv->srcpad) {
4187     gst_object_unref (priv->send_src[0]);
4188     priv->send_src[0] = NULL;
4189   }
4190
4191   if (priv->enable_rtcp) {
4192     gst_element_release_request_pad (rtpbin, priv->send_src[1]);
4193     gst_object_unref (priv->send_src[1]);
4194     priv->send_src[1] = NULL;
4195   }
4196
4197   g_object_unref (priv->session);
4198   priv->session = NULL;
4199   if (priv->caps)
4200     gst_caps_unref (priv->caps);
4201   priv->caps = NULL;
4202
4203   if (priv->srtpenc)
4204     gst_object_unref (priv->srtpenc);
4205   if (priv->srtpdec)
4206     gst_object_unref (priv->srtpdec);
4207
4208   if (priv->mcast_addr_v4)
4209     gst_rtsp_address_free (priv->mcast_addr_v4);
4210   priv->mcast_addr_v4 = NULL;
4211   if (priv->mcast_addr_v6)
4212     gst_rtsp_address_free (priv->mcast_addr_v6);
4213   priv->mcast_addr_v6 = NULL;
4214   if (priv->server_addr_v4)
4215     gst_rtsp_address_free (priv->server_addr_v4);
4216   priv->server_addr_v4 = NULL;
4217   if (priv->server_addr_v6)
4218     gst_rtsp_address_free (priv->server_addr_v6);
4219   priv->server_addr_v6 = NULL;
4220
4221   g_mutex_unlock (&priv->lock);
4222
4223   return TRUE;
4224
4225 was_not_joined:
4226   {
4227     g_mutex_unlock (&priv->lock);
4228     return TRUE;
4229   }
4230 transports_not_removed:
4231   {
4232     GST_ERROR_OBJECT (stream, "can't leave bin (transports not removed)");
4233     g_mutex_unlock (&priv->lock);
4234     return FALSE;
4235   }
4236 wrong_bin:
4237   {
4238     GST_ERROR_OBJECT (stream, "leaving the wrong bin");
4239     g_mutex_unlock (&priv->lock);
4240     return FALSE;
4241   }
4242 }
4243
4244 /**
4245  * gst_rtsp_stream_get_joined_bin:
4246  * @stream: a #GstRTSPStream
4247  *
4248  * Get the previous joined bin with gst_rtsp_stream_join_bin() or NULL.
4249  *
4250  * Return: (transfer full) (nullable): the joined bin or NULL.
4251  */
4252 GstBin *
4253 gst_rtsp_stream_get_joined_bin (GstRTSPStream * stream)
4254 {
4255   GstRTSPStreamPrivate *priv;
4256   GstBin *bin = NULL;
4257
4258   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4259
4260   priv = stream->priv;
4261
4262   g_mutex_lock (&priv->lock);
4263   bin = priv->joined_bin ? gst_object_ref (priv->joined_bin) : NULL;
4264   g_mutex_unlock (&priv->lock);
4265
4266   return bin;
4267 }
4268
4269 /**
4270  * gst_rtsp_stream_get_rtpinfo:
4271  * @stream: a #GstRTSPStream
4272  * @rtptime: (allow-none) (out caller-allocates): result RTP timestamp
4273  * @seq: (allow-none) (out caller-allocates): result RTP seqnum
4274  * @clock_rate: (allow-none) (out caller-allocates): the clock rate
4275  * @running_time: (out caller-allocates): result running-time
4276  *
4277  * Retrieve the current rtptime, seq and running-time. This is used to
4278  * construct a RTPInfo reply header.
4279  *
4280  * Returns: %TRUE when rtptime, seq and running-time could be determined.
4281  */
4282 gboolean
4283 gst_rtsp_stream_get_rtpinfo (GstRTSPStream * stream,
4284     guint * rtptime, guint * seq, guint * clock_rate,
4285     GstClockTime * running_time)
4286 {
4287   GstRTSPStreamPrivate *priv;
4288   GstStructure *stats;
4289   GObjectClass *payobjclass;
4290
4291   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4292
4293   priv = stream->priv;
4294
4295   payobjclass = G_OBJECT_GET_CLASS (priv->payloader);
4296
4297   g_mutex_lock (&priv->lock);
4298
4299   /* First try to extract the information from the last buffer on the sinks.
4300    * This will have a more accurate sequence number and timestamp, as between
4301    * the payloader and the sink there can be some queues
4302    */
4303   if (priv->udpsink[0] || priv->mcast_udpsink[0] || priv->appsink[0]) {
4304     GstSample *last_sample;
4305
4306     if (priv->udpsink[0])
4307       g_object_get (priv->udpsink[0], "last-sample", &last_sample, NULL);
4308     else if (priv->mcast_udpsink[0])
4309       g_object_get (priv->mcast_udpsink[0], "last-sample", &last_sample, NULL);
4310     else
4311       g_object_get (priv->appsink[0], "last-sample", &last_sample, NULL);
4312
4313     if (last_sample) {
4314       GstCaps *caps;
4315       GstBuffer *buffer;
4316       GstSegment *segment;
4317       GstStructure *s;
4318       GstRTPBuffer rtp_buffer = GST_RTP_BUFFER_INIT;
4319
4320       caps = gst_sample_get_caps (last_sample);
4321       buffer = gst_sample_get_buffer (last_sample);
4322       segment = gst_sample_get_segment (last_sample);
4323       s = gst_caps_get_structure (caps, 0);
4324
4325       if (gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp_buffer)) {
4326         guint ssrc_buf = gst_rtp_buffer_get_ssrc (&rtp_buffer);
4327         guint ssrc_stream = 0;
4328         if (gst_structure_has_field_typed (s, "ssrc", G_TYPE_UINT) &&
4329             gst_structure_get_uint (s, "ssrc", &ssrc_stream) &&
4330             ssrc_buf != ssrc_stream) {
4331           /* Skip buffers from auxiliary streams. */
4332           GST_DEBUG_OBJECT (stream,
4333               "not a buffer from the payloader, SSRC: %08x", ssrc_buf);
4334
4335           gst_rtp_buffer_unmap (&rtp_buffer);
4336           gst_sample_unref (last_sample);
4337           goto stats;
4338         }
4339
4340         if (seq) {
4341           *seq = gst_rtp_buffer_get_seq (&rtp_buffer);
4342         }
4343
4344         if (rtptime) {
4345           *rtptime = gst_rtp_buffer_get_timestamp (&rtp_buffer);
4346         }
4347
4348         gst_rtp_buffer_unmap (&rtp_buffer);
4349
4350         if (running_time) {
4351           *running_time =
4352               gst_segment_to_running_time (segment, GST_FORMAT_TIME,
4353               GST_BUFFER_TIMESTAMP (buffer));
4354         }
4355
4356         if (clock_rate) {
4357           gst_structure_get_int (s, "clock-rate", (gint *) clock_rate);
4358
4359           if (*clock_rate == 0 && running_time)
4360             *running_time = GST_CLOCK_TIME_NONE;
4361         }
4362         gst_sample_unref (last_sample);
4363
4364         goto done;
4365       } else {
4366         gst_sample_unref (last_sample);
4367       }
4368     } else if (priv->blocking) {
4369       if (seq) {
4370         if (!priv->blocked_buffer)
4371           goto stats;
4372         *seq = priv->blocked_seqnum;
4373       }
4374
4375       if (rtptime) {
4376         if (!priv->blocked_buffer)
4377           goto stats;
4378         *rtptime = priv->blocked_rtptime;
4379       }
4380
4381       if (running_time) {
4382         if (!GST_CLOCK_TIME_IS_VALID (priv->blocked_running_time))
4383           goto stats;
4384         *running_time = priv->blocked_running_time;
4385       }
4386
4387       if (clock_rate) {
4388         *clock_rate = priv->blocked_clock_rate;
4389
4390         if (*clock_rate == 0 && running_time)
4391           *running_time = GST_CLOCK_TIME_NONE;
4392       }
4393
4394       goto done;
4395     }
4396   }
4397
4398 stats:
4399   if (g_object_class_find_property (payobjclass, "stats")) {
4400     g_object_get (priv->payloader, "stats", &stats, NULL);
4401     if (stats == NULL)
4402       goto no_stats;
4403
4404     if (seq)
4405       gst_structure_get_uint (stats, "seqnum-offset", seq);
4406
4407     if (rtptime)
4408       gst_structure_get_uint (stats, "timestamp", rtptime);
4409
4410     if (running_time)
4411       gst_structure_get_clock_time (stats, "running-time", running_time);
4412
4413     if (clock_rate) {
4414       gst_structure_get_uint (stats, "clock-rate", clock_rate);
4415       if (*clock_rate == 0 && running_time)
4416         *running_time = GST_CLOCK_TIME_NONE;
4417     }
4418     gst_structure_free (stats);
4419   } else {
4420     if (!g_object_class_find_property (payobjclass, "seqnum") ||
4421         !g_object_class_find_property (payobjclass, "timestamp"))
4422       goto no_stats;
4423
4424     if (seq)
4425       g_object_get (priv->payloader, "seqnum", seq, NULL);
4426
4427     if (rtptime)
4428       g_object_get (priv->payloader, "timestamp", rtptime, NULL);
4429
4430     if (running_time)
4431       *running_time = GST_CLOCK_TIME_NONE;
4432   }
4433
4434 done:
4435   g_mutex_unlock (&priv->lock);
4436
4437   return TRUE;
4438
4439   /* ERRORS */
4440 no_stats:
4441   {
4442     GST_WARNING ("Could not get payloader stats");
4443     g_mutex_unlock (&priv->lock);
4444     return FALSE;
4445   }
4446 }
4447
4448 /**
4449  * gst_rtsp_stream_get_rates:
4450  * @stream: a #GstRTSPStream
4451  * @rate: (optional) (out caller-allocates): the configured rate
4452  * @applied_rate: (optional) (out caller-allocates): the configured applied_rate
4453  *
4454  * Retrieve the current rate and/or applied_rate.
4455  *
4456  * Returns: %TRUE if rate and/or applied_rate could be determined.
4457  * Since: 1.18
4458  */
4459 gboolean
4460 gst_rtsp_stream_get_rates (GstRTSPStream * stream, gdouble * rate,
4461     gdouble * applied_rate)
4462 {
4463   GstRTSPStreamPrivate *priv;
4464   GstEvent *event;
4465   const GstSegment *segment;
4466
4467   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4468
4469   if (!rate && !applied_rate) {
4470     GST_WARNING_OBJECT (stream, "rate and applied_rate are both NULL");
4471     return FALSE;
4472   }
4473
4474   priv = stream->priv;
4475
4476   g_mutex_lock (&priv->lock);
4477
4478   if (!priv->send_rtp_sink)
4479     goto no_rtp_sink_pad;
4480
4481   event = gst_pad_get_sticky_event (priv->send_rtp_sink, GST_EVENT_SEGMENT, 0);
4482   if (!event)
4483     goto no_sticky_event;
4484
4485   gst_event_parse_segment (event, &segment);
4486   if (rate)
4487     *rate = segment->rate;
4488   if (applied_rate)
4489     *applied_rate = segment->applied_rate;
4490
4491   gst_event_unref (event);
4492   g_mutex_unlock (&priv->lock);
4493
4494   return TRUE;
4495
4496 /* ERRORS */
4497 no_rtp_sink_pad:
4498   {
4499     GST_WARNING_OBJECT (stream, "no send_rtp_sink pad yet");
4500     g_mutex_unlock (&priv->lock);
4501     return FALSE;
4502   }
4503 no_sticky_event:
4504   {
4505     GST_WARNING_OBJECT (stream, "no segment event on send_rtp_sink pad");
4506     g_mutex_unlock (&priv->lock);
4507     return FALSE;
4508   }
4509
4510 }
4511
4512 /**
4513  * gst_rtsp_stream_get_caps:
4514  * @stream: a #GstRTSPStream
4515  *
4516  * Retrieve the current caps of @stream.
4517  *
4518  * Returns: (transfer full) (nullable): the #GstCaps of @stream.
4519  * use gst_caps_unref() after usage.
4520  */
4521 GstCaps *
4522 gst_rtsp_stream_get_caps (GstRTSPStream * stream)
4523 {
4524   GstRTSPStreamPrivate *priv;
4525   GstCaps *result;
4526
4527   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
4528
4529   priv = stream->priv;
4530
4531   g_mutex_lock (&priv->lock);
4532   if ((result = priv->caps))
4533     gst_caps_ref (result);
4534   g_mutex_unlock (&priv->lock);
4535
4536   return result;
4537 }
4538
4539 /**
4540  * gst_rtsp_stream_recv_rtp:
4541  * @stream: a #GstRTSPStream
4542  * @buffer: (transfer full): a #GstBuffer
4543  *
4544  * Handle an RTP buffer for the stream. This method is usually called when a
4545  * message has been received from a client using the TCP transport.
4546  *
4547  * This function takes ownership of @buffer.
4548  *
4549  * Returns: a GstFlowReturn.
4550  */
4551 GstFlowReturn
4552 gst_rtsp_stream_recv_rtp (GstRTSPStream * stream, GstBuffer * buffer)
4553 {
4554   GstRTSPStreamPrivate *priv;
4555   GstFlowReturn ret;
4556   GstElement *element;
4557
4558   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), GST_FLOW_ERROR);
4559   priv = stream->priv;
4560   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
4561   g_return_val_if_fail (priv->joined_bin != NULL, FALSE);
4562
4563   g_mutex_lock (&priv->lock);
4564   if (priv->appsrc[0])
4565     element = gst_object_ref (priv->appsrc[0]);
4566   else
4567     element = NULL;
4568   g_mutex_unlock (&priv->lock);
4569
4570   if (element) {
4571     if (priv->appsrc_base_time[0] == -1) {
4572       /* Take current running_time. This timestamp will be put on
4573        * the first buffer of each stream because we are a live source and so we
4574        * timestamp with the running_time. When we are dealing with TCP, we also
4575        * only timestamp the first buffer (using the DISCONT flag) because a server
4576        * typically bursts data, for which we don't want to compensate by speeding
4577        * up the media. The other timestamps will be interpollated from this one
4578        * using the RTP timestamps. */
4579       GST_OBJECT_LOCK (element);
4580       if (GST_ELEMENT_CLOCK (element)) {
4581         GstClockTime now;
4582         GstClockTime base_time;
4583
4584         now = gst_clock_get_time (GST_ELEMENT_CLOCK (element));
4585         base_time = GST_ELEMENT_CAST (element)->base_time;
4586
4587         priv->appsrc_base_time[0] = now - base_time;
4588         GST_BUFFER_TIMESTAMP (buffer) = priv->appsrc_base_time[0];
4589         GST_DEBUG ("stream %p: first buffer at time %" GST_TIME_FORMAT
4590             ", base %" GST_TIME_FORMAT, stream, GST_TIME_ARGS (now),
4591             GST_TIME_ARGS (base_time));
4592       }
4593       GST_OBJECT_UNLOCK (element);
4594     }
4595
4596     ret = gst_app_src_push_buffer (GST_APP_SRC_CAST (element), buffer);
4597     gst_object_unref (element);
4598   } else {
4599     ret = GST_FLOW_OK;
4600   }
4601   return ret;
4602 }
4603
4604 /**
4605  * gst_rtsp_stream_recv_rtcp:
4606  * @stream: a #GstRTSPStream
4607  * @buffer: (transfer full): a #GstBuffer
4608  *
4609  * Handle an RTCP buffer for the stream. This method is usually called when a
4610  * message has been received from a client using the TCP transport.
4611  *
4612  * This function takes ownership of @buffer.
4613  *
4614  * Returns: a GstFlowReturn.
4615  */
4616 GstFlowReturn
4617 gst_rtsp_stream_recv_rtcp (GstRTSPStream * stream, GstBuffer * buffer)
4618 {
4619   GstRTSPStreamPrivate *priv;
4620   GstFlowReturn ret;
4621   GstElement *element;
4622
4623   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), GST_FLOW_ERROR);
4624   priv = stream->priv;
4625   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
4626
4627   if (priv->joined_bin == NULL) {
4628     gst_buffer_unref (buffer);
4629     return GST_FLOW_NOT_LINKED;
4630   }
4631   g_mutex_lock (&priv->lock);
4632   if (priv->appsrc[1])
4633     element = gst_object_ref (priv->appsrc[1]);
4634   else
4635     element = NULL;
4636   g_mutex_unlock (&priv->lock);
4637
4638   if (element) {
4639     if (priv->appsrc_base_time[1] == -1) {
4640       /* Take current running_time. This timestamp will be put on
4641        * the first buffer of each stream because we are a live source and so we
4642        * timestamp with the running_time. When we are dealing with TCP, we also
4643        * only timestamp the first buffer (using the DISCONT flag) because a server
4644        * typically bursts data, for which we don't want to compensate by speeding
4645        * up the media. The other timestamps will be interpollated from this one
4646        * using the RTP timestamps. */
4647       GST_OBJECT_LOCK (element);
4648       if (GST_ELEMENT_CLOCK (element)) {
4649         GstClockTime now;
4650         GstClockTime base_time;
4651
4652         now = gst_clock_get_time (GST_ELEMENT_CLOCK (element));
4653         base_time = GST_ELEMENT_CAST (element)->base_time;
4654
4655         priv->appsrc_base_time[1] = now - base_time;
4656         GST_BUFFER_TIMESTAMP (buffer) = priv->appsrc_base_time[1];
4657         GST_DEBUG ("stream %p: first buffer at time %" GST_TIME_FORMAT
4658             ", base %" GST_TIME_FORMAT, stream, GST_TIME_ARGS (now),
4659             GST_TIME_ARGS (base_time));
4660       }
4661       GST_OBJECT_UNLOCK (element);
4662     }
4663
4664     ret = gst_app_src_push_buffer (GST_APP_SRC_CAST (element), buffer);
4665     gst_object_unref (element);
4666   } else {
4667     ret = GST_FLOW_OK;
4668     gst_buffer_unref (buffer);
4669   }
4670   return ret;
4671 }
4672
4673 /* must be called with lock */
4674 static inline void
4675 add_client (GstElement * rtp_sink, GstElement * rtcp_sink, const gchar * host,
4676     gint rtp_port, gint rtcp_port)
4677 {
4678   if (rtp_sink != NULL)
4679     g_signal_emit_by_name (rtp_sink, "add", host, rtp_port, NULL);
4680   if (rtcp_sink != NULL)
4681     g_signal_emit_by_name (rtcp_sink, "add", host, rtcp_port, NULL);
4682 }
4683
4684 /* must be called with lock */
4685 static void
4686 remove_client (GstElement * rtp_sink, GstElement * rtcp_sink,
4687     const gchar * host, gint rtp_port, gint rtcp_port)
4688 {
4689   if (rtp_sink != NULL)
4690     g_signal_emit_by_name (rtp_sink, "remove", host, rtp_port, NULL);
4691   if (rtcp_sink != NULL)
4692     g_signal_emit_by_name (rtcp_sink, "remove", host, rtcp_port, NULL);
4693 }
4694
4695 /* must be called with lock */
4696 static gboolean
4697 update_transport (GstRTSPStream * stream, GstRTSPStreamTransport * trans,
4698     gboolean add)
4699 {
4700   GstRTSPStreamPrivate *priv = stream->priv;
4701   const GstRTSPTransport *tr;
4702   gchar *dest;
4703   gint min, max;
4704   GList *tr_element;
4705
4706   tr = gst_rtsp_stream_transport_get_transport (trans);
4707   dest = tr->destination;
4708
4709   tr_element = g_list_find (priv->transports, trans);
4710
4711   if (add && tr_element)
4712     return TRUE;
4713   else if (!add && !tr_element)
4714     return FALSE;
4715
4716   switch (tr->lower_transport) {
4717     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
4718     {
4719       min = tr->port.min;
4720       max = tr->port.max;
4721
4722       if (add) {
4723         GST_INFO ("adding %s:%d-%d", dest, min, max);
4724         if (!check_mcast_client_addr (stream, tr))
4725           goto mcast_error;
4726         add_client (priv->mcast_udpsink[0], priv->mcast_udpsink[1], dest, min,
4727             max);
4728
4729         if (tr->ttl > 0) {
4730           GST_INFO ("setting ttl-mc %d", tr->ttl);
4731           if (priv->mcast_udpsink[0])
4732             g_object_set (G_OBJECT (priv->mcast_udpsink[0]), "ttl-mc", tr->ttl,
4733                 NULL);
4734           if (priv->mcast_udpsink[1])
4735             g_object_set (G_OBJECT (priv->mcast_udpsink[1]), "ttl-mc", tr->ttl,
4736                 NULL);
4737         }
4738         priv->transports = g_list_prepend (priv->transports, trans);
4739       } else {
4740         GST_INFO ("removing %s:%d-%d", dest, min, max);
4741         if (!remove_mcast_client_addr (stream, dest, min, max))
4742           GST_WARNING_OBJECT (stream,
4743               "Failed to remove multicast address: %s:%d-%d", dest, min, max);
4744         priv->transports = g_list_delete_link (priv->transports, tr_element);
4745         remove_client (priv->mcast_udpsink[0], priv->mcast_udpsink[1], dest,
4746             min, max);
4747       }
4748       break;
4749     }
4750     case GST_RTSP_LOWER_TRANS_UDP:
4751     {
4752       if (priv->client_side) {
4753         /* In client side mode the 'destination' is the RTSP server, so send
4754          * to those ports */
4755         min = tr->server_port.min;
4756         max = tr->server_port.max;
4757       } else {
4758         min = tr->client_port.min;
4759         max = tr->client_port.max;
4760       }
4761
4762       if (add) {
4763         GST_INFO ("adding %s:%d-%d", dest, min, max);
4764         add_client (priv->udpsink[0], priv->udpsink[1], dest, min, max);
4765         priv->transports = g_list_prepend (priv->transports, trans);
4766       } else {
4767         GST_INFO ("removing %s:%d-%d", dest, min, max);
4768         priv->transports = g_list_delete_link (priv->transports, tr_element);
4769         remove_client (priv->udpsink[0], priv->udpsink[1], dest, min, max);
4770       }
4771       priv->transports_cookie++;
4772       break;
4773     }
4774     case GST_RTSP_LOWER_TRANS_TCP:
4775       if (add) {
4776         GST_INFO ("adding TCP %s", tr->destination);
4777         priv->transports = g_list_prepend (priv->transports, trans);
4778         priv->n_tcp_transports++;
4779       } else {
4780         GST_INFO ("removing TCP %s", tr->destination);
4781         priv->transports = g_list_delete_link (priv->transports, tr_element);
4782
4783         gst_rtsp_stream_transport_lock_backlog (trans);
4784         gst_rtsp_stream_transport_clear_backlog (trans);
4785         gst_rtsp_stream_transport_unlock_backlog (trans);
4786
4787         priv->n_tcp_transports--;
4788       }
4789       priv->transports_cookie++;
4790       break;
4791     default:
4792       goto unknown_transport;
4793   }
4794   return TRUE;
4795
4796   /* ERRORS */
4797 unknown_transport:
4798   {
4799     GST_INFO ("Unknown transport %d", tr->lower_transport);
4800     return FALSE;
4801   }
4802 mcast_error:
4803   {
4804     return FALSE;
4805   }
4806 }
4807
4808 static void
4809 on_message_sent (GstRTSPStreamTransport * trans, gpointer user_data)
4810 {
4811   GstRTSPStream *stream = GST_RTSP_STREAM (user_data);
4812   GstRTSPStreamPrivate *priv = stream->priv;
4813
4814   GST_DEBUG_OBJECT (stream, "message send complete");
4815
4816   check_transport_backlog (stream, trans);
4817
4818   g_mutex_lock (&priv->send_lock);
4819   priv->send_cookie++;
4820   g_cond_signal (&priv->send_cond);
4821   g_mutex_unlock (&priv->send_lock);
4822 }
4823
4824 /**
4825  * gst_rtsp_stream_add_transport:
4826  * @stream: a #GstRTSPStream
4827  * @trans: (transfer none): a #GstRTSPStreamTransport
4828  *
4829  * Add the transport in @trans to @stream. The media of @stream will
4830  * then also be send to the values configured in @trans. Adding the
4831  * same transport twice will not add it a second time.
4832  *
4833  * @stream must be joined to a bin.
4834  *
4835  * @trans must contain a valid #GstRTSPTransport.
4836  *
4837  * Returns: %TRUE if @trans was added
4838  */
4839 gboolean
4840 gst_rtsp_stream_add_transport (GstRTSPStream * stream,
4841     GstRTSPStreamTransport * trans)
4842 {
4843   GstRTSPStreamPrivate *priv;
4844   gboolean res;
4845
4846   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4847   priv = stream->priv;
4848   g_return_val_if_fail (GST_IS_RTSP_STREAM_TRANSPORT (trans), FALSE);
4849   g_return_val_if_fail (priv->joined_bin != NULL, FALSE);
4850
4851   g_mutex_lock (&priv->lock);
4852   res = update_transport (stream, trans, TRUE);
4853   if (res)
4854     gst_rtsp_stream_transport_set_message_sent_full (trans, on_message_sent,
4855         stream, NULL);
4856   g_mutex_unlock (&priv->lock);
4857
4858   return res;
4859 }
4860
4861 /**
4862  * gst_rtsp_stream_remove_transport:
4863  * @stream: a #GstRTSPStream
4864  * @trans: (transfer none): a #GstRTSPStreamTransport
4865  *
4866  * Remove the transport in @trans from @stream. The media of @stream will
4867  * not be sent to the values configured in @trans.
4868  *
4869  * @stream must be joined to a bin.
4870  *
4871  * @trans must contain a valid #GstRTSPTransport.
4872  *
4873  * Returns: %TRUE if @trans was removed
4874  */
4875 gboolean
4876 gst_rtsp_stream_remove_transport (GstRTSPStream * stream,
4877     GstRTSPStreamTransport * trans)
4878 {
4879   GstRTSPStreamPrivate *priv;
4880   gboolean res;
4881
4882   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4883   priv = stream->priv;
4884   g_return_val_if_fail (GST_IS_RTSP_STREAM_TRANSPORT (trans), FALSE);
4885   g_return_val_if_fail (priv->joined_bin != NULL, FALSE);
4886
4887   g_mutex_lock (&priv->lock);
4888   res = update_transport (stream, trans, FALSE);
4889   g_mutex_unlock (&priv->lock);
4890
4891   return res;
4892 }
4893
4894 /**
4895  * gst_rtsp_stream_update_crypto:
4896  * @stream: a #GstRTSPStream
4897  * @ssrc: the SSRC
4898  * @crypto: (transfer none) (allow-none): a #GstCaps with crypto info
4899  *
4900  * Update the new crypto information for @ssrc in @stream. If information
4901  * for @ssrc did not exist, it will be added. If information
4902  * for @ssrc existed, it will be replaced. If @crypto is %NULL, it will
4903  * be removed from @stream.
4904  *
4905  * Returns: %TRUE if @crypto could be updated
4906  */
4907 gboolean
4908 gst_rtsp_stream_update_crypto (GstRTSPStream * stream,
4909     guint ssrc, GstCaps * crypto)
4910 {
4911   GstRTSPStreamPrivate *priv;
4912
4913   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
4914   g_return_val_if_fail (crypto == NULL || GST_IS_CAPS (crypto), FALSE);
4915
4916   priv = stream->priv;
4917
4918   GST_DEBUG_OBJECT (stream, "update key for %08x", ssrc);
4919
4920   g_mutex_lock (&priv->lock);
4921   if (crypto)
4922     g_hash_table_insert (priv->keys, GINT_TO_POINTER (ssrc),
4923         gst_caps_ref (crypto));
4924   else
4925     g_hash_table_remove (priv->keys, GINT_TO_POINTER (ssrc));
4926   g_mutex_unlock (&priv->lock);
4927
4928   return TRUE;
4929 }
4930
4931 /**
4932  * gst_rtsp_stream_get_rtp_socket:
4933  * @stream: a #GstRTSPStream
4934  * @family: the socket family
4935  *
4936  * Get the RTP socket from @stream for a @family.
4937  *
4938  * @stream must be joined to a bin.
4939  *
4940  * Returns: (transfer full) (nullable): the RTP socket or %NULL if no
4941  * socket could be allocated for @family. Unref after usage
4942  */
4943 GSocket *
4944 gst_rtsp_stream_get_rtp_socket (GstRTSPStream * stream, GSocketFamily family)
4945 {
4946   GstRTSPStreamPrivate *priv = stream->priv;
4947   GSocket *socket;
4948
4949   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
4950   g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
4951       family == G_SOCKET_FAMILY_IPV6, NULL);
4952
4953   g_mutex_lock (&priv->lock);
4954   if (family == G_SOCKET_FAMILY_IPV6)
4955     socket = priv->socket_v6[0];
4956   else
4957     socket = priv->socket_v4[0];
4958
4959   if (socket != NULL)
4960     socket = g_object_ref (socket);
4961   g_mutex_unlock (&priv->lock);
4962
4963   return socket;
4964 }
4965
4966 /**
4967  * gst_rtsp_stream_get_rtcp_socket:
4968  * @stream: a #GstRTSPStream
4969  * @family: the socket family
4970  *
4971  * Get the RTCP socket from @stream for a @family.
4972  *
4973  * @stream must be joined to a bin.
4974  *
4975  * Returns: (transfer full) (nullable): the RTCP socket or %NULL if no
4976  * socket could be allocated for @family. Unref after usage
4977  */
4978 GSocket *
4979 gst_rtsp_stream_get_rtcp_socket (GstRTSPStream * stream, GSocketFamily family)
4980 {
4981   GstRTSPStreamPrivate *priv = stream->priv;
4982   GSocket *socket;
4983
4984   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
4985   g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
4986       family == G_SOCKET_FAMILY_IPV6, NULL);
4987
4988   g_mutex_lock (&priv->lock);
4989   if (family == G_SOCKET_FAMILY_IPV6)
4990     socket = priv->socket_v6[1];
4991   else
4992     socket = priv->socket_v4[1];
4993
4994   if (socket != NULL)
4995     socket = g_object_ref (socket);
4996   g_mutex_unlock (&priv->lock);
4997
4998   return socket;
4999 }
5000
5001 /**
5002  * gst_rtsp_stream_get_rtp_multicast_socket:
5003  * @stream: a #GstRTSPStream
5004  * @family: the socket family
5005  *
5006  * Get the multicast RTP socket from @stream for a @family.
5007  *
5008  * Returns: (transfer full) (nullable): the multicast RTP socket or %NULL if no
5009  *
5010  * socket could be allocated for @family. Unref after usage
5011  */
5012 GSocket *
5013 gst_rtsp_stream_get_rtp_multicast_socket (GstRTSPStream * stream,
5014     GSocketFamily family)
5015 {
5016   GstRTSPStreamPrivate *priv = stream->priv;
5017   GSocket *socket;
5018
5019   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
5020   g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
5021       family == G_SOCKET_FAMILY_IPV6, NULL);
5022
5023   g_mutex_lock (&priv->lock);
5024   if (family == G_SOCKET_FAMILY_IPV6)
5025     socket = priv->mcast_socket_v6[0];
5026   else
5027     socket = priv->mcast_socket_v4[0];
5028
5029   if (socket != NULL)
5030     socket = g_object_ref (socket);
5031   g_mutex_unlock (&priv->lock);
5032
5033   return socket;
5034 }
5035
5036 /**
5037  * gst_rtsp_stream_get_rtcp_multicast_socket:
5038  * @stream: a #GstRTSPStream
5039  * @family: the socket family
5040  *
5041  * Get the multicast RTCP socket from @stream for a @family.
5042  *
5043  * Returns: (transfer full) (nullable): the multicast RTCP socket or %NULL if no
5044  * socket could be allocated for @family. Unref after usage
5045  *
5046  * Since: 1.14
5047  */
5048 GSocket *
5049 gst_rtsp_stream_get_rtcp_multicast_socket (GstRTSPStream * stream,
5050     GSocketFamily family)
5051 {
5052   GstRTSPStreamPrivate *priv = stream->priv;
5053   GSocket *socket;
5054
5055   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
5056   g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
5057       family == G_SOCKET_FAMILY_IPV6, NULL);
5058
5059   g_mutex_lock (&priv->lock);
5060   if (family == G_SOCKET_FAMILY_IPV6)
5061     socket = priv->mcast_socket_v6[1];
5062   else
5063     socket = priv->mcast_socket_v4[1];
5064
5065   if (socket != NULL)
5066     socket = g_object_ref (socket);
5067   g_mutex_unlock (&priv->lock);
5068
5069   return socket;
5070 }
5071
5072 /**
5073  * gst_rtsp_stream_add_multicast_client_address:
5074  * @stream: a #GstRTSPStream
5075  * @destination: (transfer none): a multicast address to add
5076  * @rtp_port: RTP port
5077  * @rtcp_port: RTCP port
5078  * @family: socket family
5079  *
5080  * Add multicast client address to stream. At this point, the sockets that
5081  * will stream RTP and RTCP data to @destination are supposed to be
5082  * allocated.
5083  *
5084  * Returns: %TRUE if @destination can be addedd and handled by @stream.
5085  *
5086  * Since: 1.16
5087  */
5088 gboolean
5089 gst_rtsp_stream_add_multicast_client_address (GstRTSPStream * stream,
5090     const gchar * destination, guint rtp_port, guint rtcp_port,
5091     GSocketFamily family)
5092 {
5093   GstRTSPStreamPrivate *priv;
5094
5095   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5096   g_return_val_if_fail (destination != NULL, FALSE);
5097
5098   priv = stream->priv;
5099   g_mutex_lock (&priv->lock);
5100   if ((family == G_SOCKET_FAMILY_IPV4) && (priv->mcast_socket_v4[0] == NULL))
5101     goto socket_error;
5102   else if ((family == G_SOCKET_FAMILY_IPV6) &&
5103       (priv->mcast_socket_v6[0] == NULL))
5104     goto socket_error;
5105
5106   if (!add_mcast_client_addr (stream, destination, rtp_port, rtcp_port))
5107     goto add_addr_error;
5108   g_mutex_unlock (&priv->lock);
5109
5110   return TRUE;
5111
5112 socket_error:
5113   {
5114     GST_WARNING_OBJECT (stream,
5115         "Failed to add multicast address: no udp socket");
5116     g_mutex_unlock (&priv->lock);
5117     return FALSE;
5118   }
5119 add_addr_error:
5120   {
5121     GST_WARNING_OBJECT (stream,
5122         "Failed to add multicast address: invalid address");
5123     g_mutex_unlock (&priv->lock);
5124     return FALSE;
5125   }
5126 }
5127
5128 /**
5129  * gst_rtsp_stream_get_multicast_client_addresses
5130  * @stream: a #GstRTSPStream
5131  *
5132  * Get all multicast client addresses that RTP data will be sent to
5133  *
5134  * Returns: A comma separated list of host:port pairs with destinations
5135  *
5136  * Since: 1.16
5137  */
5138 gchar *
5139 gst_rtsp_stream_get_multicast_client_addresses (GstRTSPStream * stream)
5140 {
5141   GstRTSPStreamPrivate *priv;
5142   GString *str;
5143   GList *clients;
5144
5145   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
5146
5147   priv = stream->priv;
5148   str = g_string_new ("");
5149
5150   g_mutex_lock (&priv->lock);
5151   clients = priv->mcast_clients;
5152   while (clients != NULL) {
5153     UdpClientAddrInfo *client;
5154
5155     client = (UdpClientAddrInfo *) clients->data;
5156     clients = g_list_next (clients);
5157     g_string_append_printf (str, "%s:%d%s", client->address, client->rtp_port,
5158         (clients != NULL ? "," : ""));
5159   }
5160   g_mutex_unlock (&priv->lock);
5161
5162   return g_string_free (str, FALSE);
5163 }
5164
5165 /**
5166  * gst_rtsp_stream_set_seqnum:
5167  * @stream: a #GstRTSPStream
5168  * @seqnum: a new sequence number
5169  *
5170  * Configure the sequence number in the payloader of @stream to @seqnum.
5171  */
5172 void
5173 gst_rtsp_stream_set_seqnum_offset (GstRTSPStream * stream, guint16 seqnum)
5174 {
5175   GstRTSPStreamPrivate *priv;
5176
5177   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
5178
5179   priv = stream->priv;
5180
5181   g_object_set (G_OBJECT (priv->payloader), "seqnum-offset", seqnum, NULL);
5182 }
5183
5184 /**
5185  * gst_rtsp_stream_get_seqnum:
5186  * @stream: a #GstRTSPStream
5187  *
5188  * Get the configured sequence number in the payloader of @stream.
5189  *
5190  * Returns: the sequence number of the payloader.
5191  */
5192 guint16
5193 gst_rtsp_stream_get_current_seqnum (GstRTSPStream * stream)
5194 {
5195   GstRTSPStreamPrivate *priv;
5196   guint seqnum;
5197
5198   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);
5199
5200   priv = stream->priv;
5201
5202   g_object_get (G_OBJECT (priv->payloader), "seqnum", &seqnum, NULL);
5203
5204   return seqnum;
5205 }
5206
5207 /**
5208  * gst_rtsp_stream_transport_filter:
5209  * @stream: a #GstRTSPStream
5210  * @func: (scope call) (allow-none): a callback
5211  * @user_data: (closure): user data passed to @func
5212  *
5213  * Call @func for each transport managed by @stream. The result value of @func
5214  * determines what happens to the transport. @func will be called with @stream
5215  * locked so no further actions on @stream can be performed from @func.
5216  *
5217  * If @func returns #GST_RTSP_FILTER_REMOVE, the transport will be removed from
5218  * @stream.
5219  *
5220  * If @func returns #GST_RTSP_FILTER_KEEP, the transport will remain in @stream.
5221  *
5222  * If @func returns #GST_RTSP_FILTER_REF, the transport will remain in @stream but
5223  * will also be added with an additional ref to the result #GList of this
5224  * function..
5225  *
5226  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each transport.
5227  *
5228  * Returns: (element-type GstRTSPStreamTransport) (transfer full): a #GList with all
5229  * transports for which @func returned #GST_RTSP_FILTER_REF. After usage, each
5230  * element in the #GList should be unreffed before the list is freed.
5231  */
5232 GList *
5233 gst_rtsp_stream_transport_filter (GstRTSPStream * stream,
5234     GstRTSPStreamTransportFilterFunc func, gpointer user_data)
5235 {
5236   GstRTSPStreamPrivate *priv;
5237   GList *result, *walk, *next;
5238   GHashTable *visited = NULL;
5239   guint cookie;
5240
5241   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
5242
5243   priv = stream->priv;
5244
5245   result = NULL;
5246   if (func)
5247     visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);
5248
5249   g_mutex_lock (&priv->lock);
5250 restart:
5251   cookie = priv->transports_cookie;
5252   for (walk = priv->transports; walk; walk = next) {
5253     GstRTSPStreamTransport *trans = walk->data;
5254     GstRTSPFilterResult res;
5255     gboolean changed;
5256
5257     next = g_list_next (walk);
5258
5259     if (func) {
5260       /* only visit each transport once */
5261       if (g_hash_table_contains (visited, trans))
5262         continue;
5263
5264       g_hash_table_add (visited, g_object_ref (trans));
5265       g_mutex_unlock (&priv->lock);
5266
5267       res = func (stream, trans, user_data);
5268
5269       g_mutex_lock (&priv->lock);
5270     } else
5271       res = GST_RTSP_FILTER_REF;
5272
5273     changed = (cookie != priv->transports_cookie);
5274
5275     switch (res) {
5276       case GST_RTSP_FILTER_REMOVE:
5277         update_transport (stream, trans, FALSE);
5278         break;
5279       case GST_RTSP_FILTER_REF:
5280         result = g_list_prepend (result, g_object_ref (trans));
5281         break;
5282       case GST_RTSP_FILTER_KEEP:
5283       default:
5284         break;
5285     }
5286     if (changed)
5287       goto restart;
5288   }
5289   g_mutex_unlock (&priv->lock);
5290
5291   if (func)
5292     g_hash_table_unref (visited);
5293
5294   return result;
5295 }
5296
5297 static GstPadProbeReturn
5298 rtp_pad_blocking (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
5299 {
5300   GstRTSPStreamPrivate *priv;
5301   GstRTSPStream *stream;
5302   GstBuffer *buffer = NULL;
5303   GstPadProbeReturn ret = GST_PAD_PROBE_OK;
5304   GstEvent *event;
5305
5306   stream = user_data;
5307   priv = stream->priv;
5308
5309   g_mutex_lock (&priv->lock);
5310
5311   if ((info->type & GST_PAD_PROBE_TYPE_BUFFER)) {
5312     GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
5313
5314     buffer = gst_pad_probe_info_get_buffer (info);
5315     if (gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)) {
5316       priv->blocked_buffer = TRUE;
5317       priv->blocked_seqnum = gst_rtp_buffer_get_seq (&rtp);
5318       priv->blocked_rtptime = gst_rtp_buffer_get_timestamp (&rtp);
5319       gst_rtp_buffer_unmap (&rtp);
5320     }
5321     priv->position = GST_BUFFER_TIMESTAMP (buffer);
5322   } else if ((info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST)) {
5323     GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
5324
5325     GstBufferList *list = gst_pad_probe_info_get_buffer_list (info);
5326     buffer = gst_buffer_list_get (list, 0);
5327     if (gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)) {
5328       priv->blocked_buffer = TRUE;
5329       priv->blocked_seqnum = gst_rtp_buffer_get_seq (&rtp);
5330       priv->blocked_rtptime = gst_rtp_buffer_get_timestamp (&rtp);
5331       gst_rtp_buffer_unmap (&rtp);
5332     }
5333     priv->position = GST_BUFFER_TIMESTAMP (buffer);
5334   } else if ((info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM)) {
5335     if (GST_EVENT_TYPE (info->data) == GST_EVENT_GAP) {
5336       gst_event_parse_gap (info->data, &priv->position, NULL);
5337     } else {
5338       ret = GST_PAD_PROBE_PASS;
5339       g_mutex_unlock (&priv->lock);
5340       goto done;
5341     }
5342   } else {
5343     g_assert_not_reached ();
5344   }
5345
5346   event = gst_pad_get_sticky_event (pad, GST_EVENT_SEGMENT, 0);
5347   if (event) {
5348     const GstSegment *segment;
5349
5350     gst_event_parse_segment (event, &segment);
5351     priv->blocked_running_time =
5352         gst_segment_to_stream_time (segment, GST_FORMAT_TIME, priv->position);
5353     gst_event_unref (event);
5354   }
5355
5356   event = gst_pad_get_sticky_event (pad, GST_EVENT_CAPS, 0);
5357   if (event) {
5358     GstCaps *caps;
5359     GstStructure *s;
5360
5361     gst_event_parse_caps (event, &caps);
5362     s = gst_caps_get_structure (caps, 0);
5363     gst_structure_get_int (s, "clock-rate", &priv->blocked_clock_rate);
5364     gst_event_unref (event);
5365   }
5366
5367   priv->blocking = TRUE;
5368
5369   GST_DEBUG_OBJECT (pad, "Now blocking");
5370
5371   GST_DEBUG_OBJECT (stream, "position: %" GST_TIME_FORMAT,
5372       GST_TIME_ARGS (priv->position));
5373
5374   g_mutex_unlock (&priv->lock);
5375
5376   gst_element_post_message (priv->payloader,
5377       gst_message_new_element (GST_OBJECT_CAST (priv->payloader),
5378           gst_structure_new ("GstRTSPStreamBlocking", "is_complete",
5379               G_TYPE_BOOLEAN, priv->is_complete, NULL)));
5380
5381 done:
5382   return ret;
5383 }
5384
5385 static GstPadProbeReturn
5386 rtcp_pad_blocking (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
5387 {
5388   GstRTSPStreamPrivate *priv;
5389   GstRTSPStream *stream;
5390   GstPadProbeReturn ret = GST_PAD_PROBE_OK;
5391
5392   stream = user_data;
5393   priv = stream->priv;
5394
5395   g_mutex_lock (&priv->lock);
5396
5397   if ((info->type & GST_PAD_PROBE_TYPE_BUFFER) ||
5398       (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST)) {
5399     GST_DEBUG_OBJECT (pad, "Now blocking on buffer");
5400   } else if ((info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM)) {
5401     if (GST_EVENT_TYPE (info->data) == GST_EVENT_GAP) {
5402       GST_DEBUG_OBJECT (pad, "Now blocking on gap event");
5403       ret = GST_PAD_PROBE_OK;
5404     } else {
5405       ret = GST_PAD_PROBE_PASS;
5406       g_mutex_unlock (&priv->lock);
5407       goto done;
5408     }
5409   } else {
5410     g_assert_not_reached ();
5411   }
5412
5413   g_mutex_unlock (&priv->lock);
5414
5415 done:
5416   return ret;
5417 }
5418
5419
5420 static void
5421 set_blocked (GstRTSPStream * stream, gboolean blocked)
5422 {
5423   GstRTSPStreamPrivate *priv;
5424   int i;
5425
5426   GST_DEBUG_OBJECT (stream, "blocked: %d", blocked);
5427
5428   priv = stream->priv;
5429
5430   if (blocked) {
5431     /* if receiver */
5432     if (priv->sinkpad) {
5433       priv->blocking = TRUE;
5434       return;
5435     }
5436     for (i = 0; i < 2; i++) {
5437       if (priv->blocked_id[i] != 0)
5438         continue;
5439       if (priv->send_src[i]) {
5440         priv->blocking = FALSE;
5441         priv->blocked_buffer = FALSE;
5442         priv->blocked_running_time = GST_CLOCK_TIME_NONE;
5443         priv->blocked_clock_rate = 0;
5444
5445         if (i == 0) {
5446           priv->blocked_id[i] = gst_pad_add_probe (priv->send_src[i],
5447               GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
5448               GST_PAD_PROBE_TYPE_BUFFER_LIST |
5449               GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, rtp_pad_blocking,
5450               g_object_ref (stream), g_object_unref);
5451         } else {
5452           priv->blocked_id[i] = gst_pad_add_probe (priv->send_src[i],
5453               GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
5454               GST_PAD_PROBE_TYPE_BUFFER_LIST |
5455               GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, rtcp_pad_blocking,
5456               g_object_ref (stream), g_object_unref);
5457         }
5458       }
5459     }
5460   } else {
5461     for (i = 0; i < 2; i++) {
5462       if (priv->blocked_id[i] != 0) {
5463         gst_pad_remove_probe (priv->send_src[i], priv->blocked_id[i]);
5464         priv->blocked_id[i] = 0;
5465       }
5466     }
5467     priv->blocking = FALSE;
5468   }
5469 }
5470
5471 /**
5472  * gst_rtsp_stream_set_blocked:
5473  * @stream: a #GstRTSPStream
5474  * @blocked: boolean indicating we should block or unblock
5475  *
5476  * Blocks or unblocks the dataflow on @stream.
5477  *
5478  * Returns: %TRUE on success
5479  */
5480 gboolean
5481 gst_rtsp_stream_set_blocked (GstRTSPStream * stream, gboolean blocked)
5482 {
5483   GstRTSPStreamPrivate *priv;
5484
5485   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5486
5487   priv = stream->priv;
5488   g_mutex_lock (&priv->lock);
5489   set_blocked (stream, blocked);
5490   g_mutex_unlock (&priv->lock);
5491
5492   return TRUE;
5493 }
5494
5495 /**
5496  * gst_rtsp_stream_ublock_linked:
5497  * @stream: a #GstRTSPStream
5498  *
5499  * Unblocks the dataflow on @stream if it is linked.
5500  *
5501  * Returns: %TRUE on success
5502  *
5503  * Since: 1.14
5504  */
5505 gboolean
5506 gst_rtsp_stream_unblock_linked (GstRTSPStream * stream)
5507 {
5508   GstRTSPStreamPrivate *priv;
5509
5510   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5511
5512   priv = stream->priv;
5513   g_mutex_lock (&priv->lock);
5514   if (priv->send_src[0] && gst_pad_is_linked (priv->send_src[0]))
5515     set_blocked (stream, FALSE);
5516   g_mutex_unlock (&priv->lock);
5517
5518   return TRUE;
5519 }
5520
5521 /**
5522  * gst_rtsp_stream_is_blocking:
5523  * @stream: a #GstRTSPStream
5524  *
5525  * Check if @stream is blocking on a #GstBuffer.
5526  *
5527  * Returns: %TRUE if @stream is blocking
5528  */
5529 gboolean
5530 gst_rtsp_stream_is_blocking (GstRTSPStream * stream)
5531 {
5532   GstRTSPStreamPrivate *priv;
5533   gboolean result;
5534
5535   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5536
5537   priv = stream->priv;
5538
5539   g_mutex_lock (&priv->lock);
5540   result = priv->blocking;
5541   g_mutex_unlock (&priv->lock);
5542
5543   return result;
5544 }
5545
5546 /**
5547  * gst_rtsp_stream_query_position:
5548  * @stream: a #GstRTSPStream
5549  * @position: (out): current position of a #GstRTSPStream
5550  *
5551  * Query the position of the stream in %GST_FORMAT_TIME. This only considers
5552  * the RTP parts of the pipeline and not the RTCP parts.
5553  *
5554  * Returns: %TRUE if the position could be queried
5555  */
5556 gboolean
5557 gst_rtsp_stream_query_position (GstRTSPStream * stream, gint64 * position)
5558 {
5559   GstRTSPStreamPrivate *priv;
5560   GstElement *sink;
5561   GstPad *pad = NULL;
5562
5563   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5564
5565   /* query position: if no sinks have been added yet,
5566    * we obtain the position from the pad otherwise we query the sinks */
5567
5568   priv = stream->priv;
5569
5570   g_mutex_lock (&priv->lock);
5571
5572   if (priv->blocking && GST_CLOCK_TIME_IS_VALID (priv->blocked_running_time)) {
5573     *position = priv->blocked_running_time;
5574     g_mutex_unlock (&priv->lock);
5575     return TRUE;
5576   }
5577
5578   /* depending on the transport type, it should query corresponding sink */
5579   if (priv->configured_protocols & GST_RTSP_LOWER_TRANS_UDP)
5580     sink = priv->udpsink[0];
5581   else if (priv->configured_protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST)
5582     sink = priv->mcast_udpsink[0];
5583   else
5584     sink = priv->appsink[0];
5585
5586   if (sink) {
5587     gst_object_ref (sink);
5588   } else if (priv->send_src[0]) {
5589     pad = gst_object_ref (priv->send_src[0]);
5590   } else {
5591     g_mutex_unlock (&priv->lock);
5592     GST_WARNING_OBJECT (stream, "Couldn't obtain postion: erroneous pipeline");
5593     return FALSE;
5594   }
5595   g_mutex_unlock (&priv->lock);
5596
5597   if (sink) {
5598     if (!gst_element_query_position (sink, GST_FORMAT_TIME, position)) {
5599       GST_WARNING_OBJECT (stream,
5600           "Couldn't obtain postion: position query failed");
5601       gst_object_unref (sink);
5602       return FALSE;
5603     }
5604     gst_object_unref (sink);
5605   } else if (pad) {
5606     GstEvent *event;
5607     const GstSegment *segment;
5608
5609     event = gst_pad_get_sticky_event (pad, GST_EVENT_SEGMENT, 0);
5610     if (!event) {
5611       GST_WARNING_OBJECT (stream, "Couldn't obtain postion: no segment event");
5612       gst_object_unref (pad);
5613       return FALSE;
5614     }
5615
5616     gst_event_parse_segment (event, &segment);
5617     if (segment->format != GST_FORMAT_TIME) {
5618       *position = -1;
5619     } else {
5620       g_mutex_lock (&priv->lock);
5621       *position = priv->position;
5622       g_mutex_unlock (&priv->lock);
5623       *position =
5624           gst_segment_to_stream_time (segment, GST_FORMAT_TIME, *position);
5625     }
5626     gst_event_unref (event);
5627     gst_object_unref (pad);
5628   }
5629
5630   return TRUE;
5631 }
5632
5633 /**
5634  * gst_rtsp_stream_query_stop:
5635  * @stream: a #GstRTSPStream
5636  * @stop: (out): current stop of a #GstRTSPStream
5637  *
5638  * Query the stop of the stream in %GST_FORMAT_TIME. This only considers
5639  * the RTP parts of the pipeline and not the RTCP parts.
5640  *
5641  * Returns: %TRUE if the stop could be queried
5642  */
5643 gboolean
5644 gst_rtsp_stream_query_stop (GstRTSPStream * stream, gint64 * stop)
5645 {
5646   GstRTSPStreamPrivate *priv;
5647   GstElement *sink;
5648   GstPad *pad = NULL;
5649
5650   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5651
5652   /* query stop position: if no sinks have been added yet,
5653    * we obtain the stop position from the pad otherwise we query the sinks */
5654
5655   priv = stream->priv;
5656
5657   g_mutex_lock (&priv->lock);
5658   /* depending on the transport type, it should query corresponding sink */
5659   if (priv->configured_protocols & GST_RTSP_LOWER_TRANS_UDP)
5660     sink = priv->udpsink[0];
5661   else if (priv->configured_protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST)
5662     sink = priv->mcast_udpsink[0];
5663   else
5664     sink = priv->appsink[0];
5665
5666   if (sink) {
5667     gst_object_ref (sink);
5668   } else if (priv->send_src[0]) {
5669     pad = gst_object_ref (priv->send_src[0]);
5670   } else {
5671     g_mutex_unlock (&priv->lock);
5672     GST_WARNING_OBJECT (stream, "Couldn't obtain stop: erroneous pipeline");
5673     return FALSE;
5674   }
5675   g_mutex_unlock (&priv->lock);
5676
5677   if (sink) {
5678     GstQuery *query;
5679     GstFormat format;
5680     gdouble rate;
5681     gint64 start_value;
5682     gint64 stop_value;
5683
5684     query = gst_query_new_segment (GST_FORMAT_TIME);
5685     if (!gst_element_query (sink, query)) {
5686       GST_WARNING_OBJECT (stream, "Couldn't obtain stop: element query failed");
5687       gst_query_unref (query);
5688       gst_object_unref (sink);
5689       return FALSE;
5690     }
5691     gst_query_parse_segment (query, &rate, &format, &start_value, &stop_value);
5692     if (format != GST_FORMAT_TIME)
5693       *stop = -1;
5694     else
5695       *stop = rate > 0.0 ? stop_value : start_value;
5696     gst_query_unref (query);
5697     gst_object_unref (sink);
5698   } else if (pad) {
5699     GstEvent *event;
5700     const GstSegment *segment;
5701
5702     event = gst_pad_get_sticky_event (pad, GST_EVENT_SEGMENT, 0);
5703     if (!event) {
5704       GST_WARNING_OBJECT (stream, "Couldn't obtain stop: no segment event");
5705       gst_object_unref (pad);
5706       return FALSE;
5707     }
5708     gst_event_parse_segment (event, &segment);
5709     if (segment->format != GST_FORMAT_TIME) {
5710       *stop = -1;
5711     } else {
5712       *stop = segment->stop;
5713       if (*stop == -1)
5714         *stop = segment->duration;
5715       else
5716         *stop = gst_segment_to_stream_time (segment, GST_FORMAT_TIME, *stop);
5717     }
5718     gst_event_unref (event);
5719     gst_object_unref (pad);
5720   }
5721
5722   return TRUE;
5723 }
5724
5725 /**
5726  * gst_rtsp_stream_seekable:
5727  * @stream: a #GstRTSPStream
5728  *
5729  * Checks whether the individual @stream is seekable.
5730  *
5731  * Returns: %TRUE if @stream is seekable, else %FALSE.
5732  *
5733  * Since: 1.14
5734  */
5735 gboolean
5736 gst_rtsp_stream_seekable (GstRTSPStream * stream)
5737 {
5738   GstRTSPStreamPrivate *priv;
5739   GstPad *pad = NULL;
5740   GstQuery *query = NULL;
5741   gboolean seekable = FALSE;
5742
5743   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5744
5745   /* query stop position: if no sinks have been added yet,
5746    * we obtain the stop position from the pad otherwise we query the sinks */
5747
5748   priv = stream->priv;
5749
5750   g_mutex_lock (&priv->lock);
5751   /* depending on the transport type, it should query corresponding sink */
5752   if (priv->srcpad) {
5753     pad = gst_object_ref (priv->srcpad);
5754   } else {
5755     g_mutex_unlock (&priv->lock);
5756     GST_WARNING_OBJECT (stream, "Pad not available, can't query seekability");
5757     goto beach;
5758   }
5759   g_mutex_unlock (&priv->lock);
5760
5761   query = gst_query_new_seeking (GST_FORMAT_TIME);
5762   if (!gst_pad_query (pad, query)) {
5763     GST_WARNING_OBJECT (stream, "seeking query failed");
5764     goto beach;
5765   }
5766   gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
5767
5768 beach:
5769   if (pad)
5770     gst_object_unref (pad);
5771   if (query)
5772     gst_query_unref (query);
5773
5774   GST_DEBUG_OBJECT (stream, "Returning %d", seekable);
5775
5776   return seekable;
5777 }
5778
5779 /**
5780  * gst_rtsp_stream_complete_stream:
5781  * @stream: a #GstRTSPStream
5782  * @transport: a #GstRTSPTransport
5783  *
5784  * Add a receiver and sender part to the pipeline based on the transport from
5785  * SETUP.
5786  *
5787  * Returns: %TRUE if the stream has been sucessfully updated.
5788  *
5789  * Since: 1.14
5790  */
5791 gboolean
5792 gst_rtsp_stream_complete_stream (GstRTSPStream * stream,
5793     const GstRTSPTransport * transport)
5794 {
5795   GstRTSPStreamPrivate *priv;
5796
5797   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5798
5799   priv = stream->priv;
5800   GST_DEBUG_OBJECT (stream, "complete stream");
5801
5802   g_mutex_lock (&priv->lock);
5803
5804   if (!(priv->allowed_protocols & transport->lower_transport))
5805     goto unallowed_transport;
5806
5807   if (!create_receiver_part (stream, transport))
5808     goto create_receiver_error;
5809
5810   /* in the RECORD case, we only add RTCP sender part */
5811   if (!create_sender_part (stream, transport))
5812     goto create_sender_error;
5813
5814   priv->configured_protocols |= transport->lower_transport;
5815
5816   priv->is_complete = TRUE;
5817   g_mutex_unlock (&priv->lock);
5818
5819   GST_DEBUG_OBJECT (stream, "pipeline sucsessfully updated");
5820   return TRUE;
5821
5822 create_receiver_error:
5823 create_sender_error:
5824 unallowed_transport:
5825   {
5826     g_mutex_unlock (&priv->lock);
5827     return FALSE;
5828   }
5829 }
5830
5831 /**
5832  * gst_rtsp_stream_is_complete:
5833  * @stream: a #GstRTSPStream
5834  *
5835  * Checks whether the stream is complete, contains the receiver and the sender
5836  * parts. As the stream contains sink(s) element(s), it's possible to perform
5837  * seek operations on it.
5838  *
5839  * Returns: %TRUE if the stream contains at least one sink element.
5840  *
5841  * Since: 1.14
5842  */
5843 gboolean
5844 gst_rtsp_stream_is_complete (GstRTSPStream * stream)
5845 {
5846   GstRTSPStreamPrivate *priv;
5847   gboolean ret = FALSE;
5848
5849   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5850
5851   priv = stream->priv;
5852   g_mutex_lock (&priv->lock);
5853   ret = priv->is_complete;
5854   g_mutex_unlock (&priv->lock);
5855
5856   return ret;
5857 }
5858
5859 /**
5860  * gst_rtsp_stream_is_sender:
5861  * @stream: a #GstRTSPStream
5862  *
5863  * Checks whether the stream is a sender.
5864  *
5865  * Returns: %TRUE if the stream is a sender and %FALSE otherwise.
5866  *
5867  * Since: 1.14
5868  */
5869 gboolean
5870 gst_rtsp_stream_is_sender (GstRTSPStream * stream)
5871 {
5872   GstRTSPStreamPrivate *priv;
5873   gboolean ret = FALSE;
5874
5875   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5876
5877   priv = stream->priv;
5878   g_mutex_lock (&priv->lock);
5879   ret = (priv->srcpad != NULL);
5880   g_mutex_unlock (&priv->lock);
5881
5882   return ret;
5883 }
5884
5885 /**
5886  * gst_rtsp_stream_is_receiver:
5887  * @stream: a #GstRTSPStream
5888  *
5889  * Checks whether the stream is a receiver.
5890  *
5891  * Returns: %TRUE if the stream is a receiver and %FALSE otherwise.
5892  *
5893  * Since: 1.14
5894  */
5895 gboolean
5896 gst_rtsp_stream_is_receiver (GstRTSPStream * stream)
5897 {
5898   GstRTSPStreamPrivate *priv;
5899   gboolean ret = FALSE;
5900
5901   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
5902
5903   priv = stream->priv;
5904   g_mutex_lock (&priv->lock);
5905   ret = (priv->sinkpad != NULL);
5906   g_mutex_unlock (&priv->lock);
5907
5908   return ret;
5909 }
5910
5911 #define AES_128_KEY_LEN 16
5912 #define AES_256_KEY_LEN 32
5913
5914 #define HMAC_32_KEY_LEN 4
5915 #define HMAC_80_KEY_LEN 10
5916
5917 static gboolean
5918 mikey_apply_policy (GstCaps * caps, GstMIKEYMessage * msg, guint8 policy)
5919 {
5920   const gchar *srtp_cipher;
5921   const gchar *srtp_auth;
5922   const GstMIKEYPayload *sp;
5923   guint i;
5924
5925   /* loop over Security policy until we find one containing policy */
5926   for (i = 0;; i++) {
5927     if ((sp = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, i)) == NULL)
5928       break;
5929
5930     if (((GstMIKEYPayloadSP *) sp)->policy == policy)
5931       break;
5932   }
5933
5934   /* the default ciphers */
5935   srtp_cipher = "aes-128-icm";
5936   srtp_auth = "hmac-sha1-80";
5937
5938   /* now override the defaults with what is in the Security Policy */
5939   if (sp != NULL) {
5940     guint len;
5941     guint enc_alg = GST_MIKEY_ENC_AES_CM_128;
5942
5943     /* collect all the params and go over them */
5944     len = gst_mikey_payload_sp_get_n_params (sp);
5945     for (i = 0; i < len; i++) {
5946       const GstMIKEYPayloadSPParam *param =
5947           gst_mikey_payload_sp_get_param (sp, i);
5948
5949       switch (param->type) {
5950         case GST_MIKEY_SP_SRTP_ENC_ALG:
5951           enc_alg = param->val[0];
5952           switch (param->val[0]) {
5953             case GST_MIKEY_ENC_NULL:
5954               srtp_cipher = "null";
5955               break;
5956             case GST_MIKEY_ENC_AES_CM_128:
5957             case GST_MIKEY_ENC_AES_KW_128:
5958               srtp_cipher = "aes-128-icm";
5959               break;
5960             case GST_MIKEY_ENC_AES_GCM_128:
5961               srtp_cipher = "aes-128-gcm";
5962               break;
5963             default:
5964               break;
5965           }
5966           break;
5967         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
5968           switch (param->val[0]) {
5969             case AES_128_KEY_LEN:
5970               if (enc_alg == GST_MIKEY_ENC_AES_CM_128 ||
5971                   enc_alg == GST_MIKEY_ENC_AES_KW_128) {
5972                 srtp_cipher = "aes-128-icm";
5973               } else if (enc_alg == GST_MIKEY_ENC_AES_GCM_128) {
5974                 srtp_cipher = "aes-128-gcm";
5975               }
5976               break;
5977             case AES_256_KEY_LEN:
5978               if (enc_alg == GST_MIKEY_ENC_AES_CM_128 ||
5979                   enc_alg == GST_MIKEY_ENC_AES_KW_128) {
5980                 srtp_cipher = "aes-256-icm";
5981               } else if (enc_alg == GST_MIKEY_ENC_AES_GCM_128) {
5982                 srtp_cipher = "aes-256-gcm";
5983               }
5984               break;
5985             default:
5986               break;
5987           }
5988           break;
5989         case GST_MIKEY_SP_SRTP_AUTH_ALG:
5990           switch (param->val[0]) {
5991             case GST_MIKEY_MAC_NULL:
5992               srtp_auth = "null";
5993               break;
5994             case GST_MIKEY_MAC_HMAC_SHA_1_160:
5995               srtp_auth = "hmac-sha1-80";
5996               break;
5997             default:
5998               break;
5999           }
6000           break;
6001         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
6002           switch (param->val[0]) {
6003             case HMAC_32_KEY_LEN:
6004               srtp_auth = "hmac-sha1-32";
6005               break;
6006             case HMAC_80_KEY_LEN:
6007               srtp_auth = "hmac-sha1-80";
6008               break;
6009             default:
6010               break;
6011           }
6012           break;
6013         case GST_MIKEY_SP_SRTP_SRTP_ENC:
6014           break;
6015         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
6016           break;
6017         default:
6018           break;
6019       }
6020     }
6021   }
6022   /* now configure the SRTP parameters */
6023   gst_caps_set_simple (caps,
6024       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
6025       "srtp-auth", G_TYPE_STRING, srtp_auth,
6026       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
6027       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
6028
6029   return TRUE;
6030 }
6031
6032 static gboolean
6033 handle_mikey_data (GstRTSPStream * stream, guint8 * data, gsize size)
6034 {
6035   GstMIKEYMessage *msg;
6036   guint i, n_cs;
6037   GstCaps *caps = NULL;
6038   GstMIKEYPayloadKEMAC *kemac;
6039   const GstMIKEYPayloadKeyData *pkd;
6040   GstBuffer *key;
6041
6042   /* the MIKEY message contains a CSB or crypto session bundle. It is a
6043    * set of Crypto Sessions protected with the same master key.
6044    * In the context of SRTP, an RTP and its RTCP stream is part of a
6045    * crypto session */
6046   if ((msg = gst_mikey_message_new_from_data (data, size, NULL, NULL)) == NULL)
6047     goto parse_failed;
6048
6049   /* we can only handle SRTP crypto sessions for now */
6050   if (msg->map_type != GST_MIKEY_MAP_TYPE_SRTP)
6051     goto invalid_map_type;
6052
6053   /* get the number of crypto sessions. This maps SSRC to its
6054    * security parameters */
6055   n_cs = gst_mikey_message_get_n_cs (msg);
6056   if (n_cs == 0)
6057     goto no_crypto_sessions;
6058
6059   /* we also need keys */
6060   if (!(kemac = (GstMIKEYPayloadKEMAC *) gst_mikey_message_find_payload
6061           (msg, GST_MIKEY_PT_KEMAC, 0)))
6062     goto no_keys;
6063
6064   /* we don't support encrypted keys */
6065   if (kemac->enc_alg != GST_MIKEY_ENC_NULL
6066       || kemac->mac_alg != GST_MIKEY_MAC_NULL)
6067     goto unsupported_encryption;
6068
6069   /* get Key data sub-payload */
6070   pkd = (const GstMIKEYPayloadKeyData *)
6071       gst_mikey_payload_kemac_get_sub (&kemac->pt, 0);
6072
6073   key = gst_buffer_new_memdup (pkd->key_data, pkd->key_len);
6074
6075   /* go over all crypto sessions and create the security policy for each
6076    * SSRC */
6077   for (i = 0; i < n_cs; i++) {
6078     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
6079
6080     caps = gst_caps_new_simple ("application/x-srtp",
6081         "ssrc", G_TYPE_UINT, map->ssrc,
6082         "roc", G_TYPE_UINT, map->roc, "srtp-key", GST_TYPE_BUFFER, key, NULL);
6083     mikey_apply_policy (caps, msg, map->policy);
6084
6085     gst_rtsp_stream_update_crypto (stream, map->ssrc, caps);
6086     gst_caps_unref (caps);
6087   }
6088   gst_mikey_message_unref (msg);
6089   gst_buffer_unref (key);
6090
6091   return TRUE;
6092
6093   /* ERRORS */
6094 parse_failed:
6095   {
6096     GST_DEBUG_OBJECT (stream, "failed to parse MIKEY message");
6097     return FALSE;
6098   }
6099 invalid_map_type:
6100   {
6101     GST_DEBUG_OBJECT (stream, "invalid map type %d", msg->map_type);
6102     goto cleanup_message;
6103   }
6104 no_crypto_sessions:
6105   {
6106     GST_DEBUG_OBJECT (stream, "no crypto sessions");
6107     goto cleanup_message;
6108   }
6109 no_keys:
6110   {
6111     GST_DEBUG_OBJECT (stream, "no keys found");
6112     goto cleanup_message;
6113   }
6114 unsupported_encryption:
6115   {
6116     GST_DEBUG_OBJECT (stream, "unsupported key encryption");
6117     goto cleanup_message;
6118   }
6119 cleanup_message:
6120   {
6121     gst_mikey_message_unref (msg);
6122     return FALSE;
6123   }
6124 }
6125
6126 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
6127
6128 static void
6129 strip_chars (gchar * str)
6130 {
6131   gchar *s;
6132   gsize len;
6133
6134   len = strlen (str);
6135   while (len--) {
6136     if (!IS_STRIP_CHAR (str[len]))
6137       break;
6138     str[len] = '\0';
6139   }
6140   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
6141   memmove (str, s, len + 1);
6142 }
6143
6144 /**
6145  * gst_rtsp_stream_handle_keymgmt:
6146  * @stream: a #GstRTSPStream
6147  * @keymgmt: a keymgmt header
6148  *
6149  * Parse and handle a KeyMgmt header.
6150  *
6151  * Since: 1.16
6152  */
6153 /* KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
6154  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
6155  */
6156 gboolean
6157 gst_rtsp_stream_handle_keymgmt (GstRTSPStream * stream, const gchar * keymgmt)
6158 {
6159   gchar **specs;
6160   gint i, j;
6161
6162   specs = g_strsplit (keymgmt, ",", 0);
6163   for (i = 0; specs[i]; i++) {
6164     gchar **split;
6165
6166     split = g_strsplit (specs[i], ";", 0);
6167     for (j = 0; split[j]; j++) {
6168       g_strstrip (split[j]);
6169       if (g_str_has_prefix (split[j], "prot=")) {
6170         g_strstrip (split[j] + 5);
6171         if (!g_str_equal (split[j] + 5, "mikey"))
6172           break;
6173         GST_DEBUG ("found mikey");
6174       } else if (g_str_has_prefix (split[j], "uri=")) {
6175         strip_chars (split[j] + 4);
6176         GST_DEBUG ("found uri '%s'", split[j] + 4);
6177       } else if (g_str_has_prefix (split[j], "data=")) {
6178         guchar *data;
6179         gsize size;
6180         strip_chars (split[j] + 5);
6181         GST_DEBUG ("found data '%s'", split[j] + 5);
6182         data = g_base64_decode_inplace (split[j] + 5, &size);
6183         handle_mikey_data (stream, data, size);
6184       }
6185     }
6186     g_strfreev (split);
6187   }
6188   g_strfreev (specs);
6189   return TRUE;
6190 }
6191
6192
6193 /**
6194  * gst_rtsp_stream_get_ulpfec_pt:
6195  *
6196  * Returns: the payload type used for ULPFEC protection packets
6197  *
6198  * Since: 1.16
6199  */
6200 guint
6201 gst_rtsp_stream_get_ulpfec_pt (GstRTSPStream * stream)
6202 {
6203   guint res;
6204
6205   g_mutex_lock (&stream->priv->lock);
6206   res = stream->priv->ulpfec_pt;
6207   g_mutex_unlock (&stream->priv->lock);
6208
6209   return res;
6210 }
6211
6212 /**
6213  * gst_rtsp_stream_set_ulpfec_pt:
6214  *
6215  * Set the payload type to be used for ULPFEC protection packets
6216  *
6217  * Since: 1.16
6218  */
6219 void
6220 gst_rtsp_stream_set_ulpfec_pt (GstRTSPStream * stream, guint pt)
6221 {
6222   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
6223
6224   g_mutex_lock (&stream->priv->lock);
6225   stream->priv->ulpfec_pt = pt;
6226   if (stream->priv->ulpfec_encoder) {
6227     g_object_set (stream->priv->ulpfec_encoder, "pt", pt, NULL);
6228   }
6229   g_mutex_unlock (&stream->priv->lock);
6230 }
6231
6232 /**
6233  * gst_rtsp_stream_request_ulpfec_decoder:
6234  *
6235  * Creating a rtpulpfecdec element
6236  *
6237  * Returns: (transfer full) (nullable): a #GstElement.
6238  *
6239  * Since: 1.16
6240  */
6241 GstElement *
6242 gst_rtsp_stream_request_ulpfec_decoder (GstRTSPStream * stream,
6243     GstElement * rtpbin, guint sessid)
6244 {
6245   GObject *internal_storage = NULL;
6246
6247   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
6248   stream->priv->ulpfec_decoder =
6249       gst_object_ref (gst_element_factory_make ("rtpulpfecdec", NULL));
6250
6251   g_signal_emit_by_name (G_OBJECT (rtpbin), "get-internal-storage", sessid,
6252       &internal_storage);
6253   g_object_set (stream->priv->ulpfec_decoder, "storage", internal_storage,
6254       NULL);
6255   g_object_unref (internal_storage);
6256   update_ulpfec_decoder_pt (stream);
6257
6258   return stream->priv->ulpfec_decoder;
6259 }
6260
6261 /**
6262  * gst_rtsp_stream_request_ulpfec_encoder:
6263  *
6264  * Creating a rtpulpfecenc element
6265  *
6266  * Returns: (transfer full) (nullable): a #GstElement.
6267  *
6268  * Since: 1.16
6269  */
6270 GstElement *
6271 gst_rtsp_stream_request_ulpfec_encoder (GstRTSPStream * stream, guint sessid)
6272 {
6273   g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
6274
6275   if (!stream->priv->ulpfec_percentage)
6276     return NULL;
6277
6278   stream->priv->ulpfec_encoder =
6279       gst_object_ref (gst_element_factory_make ("rtpulpfecenc", NULL));
6280
6281   g_object_set (stream->priv->ulpfec_encoder, "pt", stream->priv->ulpfec_pt,
6282       "percentage", stream->priv->ulpfec_percentage, NULL);
6283
6284   return stream->priv->ulpfec_encoder;
6285 }
6286
6287 /**
6288  * gst_rtsp_stream_set_ulpfec_percentage:
6289  *
6290  * Sets the amount of redundancy to apply when creating ULPFEC
6291  * protection packets.
6292  *
6293  * Since: 1.16
6294  */
6295 void
6296 gst_rtsp_stream_set_ulpfec_percentage (GstRTSPStream * stream, guint percentage)
6297 {
6298   g_return_if_fail (GST_IS_RTSP_STREAM (stream));
6299
6300   g_mutex_lock (&stream->priv->lock);
6301   stream->priv->ulpfec_percentage = percentage;
6302   if (stream->priv->ulpfec_encoder) {
6303     g_object_set (stream->priv->ulpfec_encoder, "percentage", percentage, NULL);
6304   }
6305   g_mutex_unlock (&stream->priv->lock);
6306 }
6307
6308 /**
6309  * gst_rtsp_stream_get_ulpfec_percentage:
6310  *
6311  * Returns: the amount of redundancy applied when creating ULPFEC
6312  * protection packets.
6313  *
6314  * Since: 1.16
6315  */
6316 guint
6317 gst_rtsp_stream_get_ulpfec_percentage (GstRTSPStream * stream)
6318 {
6319   guint res;
6320
6321   g_mutex_lock (&stream->priv->lock);
6322   res = stream->priv->ulpfec_percentage;
6323   g_mutex_unlock (&stream->priv->lock);
6324
6325   return res;
6326 }
6327
6328 /**
6329  * gst_rtsp_stream_set_rate_control:
6330  *
6331  * Define whether @stream will follow the Rate-Control=no behaviour as specified
6332  * in the ONVIF replay spec.
6333  *
6334  * Since: 1.18
6335  */
6336 void
6337 gst_rtsp_stream_set_rate_control (GstRTSPStream * stream, gboolean enabled)
6338 {
6339   GST_DEBUG_OBJECT (stream, "%s rate control",
6340       enabled ? "Enabling" : "Disabling");
6341
6342   g_mutex_lock (&stream->priv->lock);
6343   stream->priv->do_rate_control = enabled;
6344   if (stream->priv->appsink[0])
6345     g_object_set (stream->priv->appsink[0], "sync", enabled, NULL);
6346   if (stream->priv->payloader
6347       && g_object_class_find_property (G_OBJECT_GET_CLASS (stream->
6348               priv->payloader), "onvif-no-rate-control"))
6349     g_object_set (stream->priv->payloader, "onvif-no-rate-control", !enabled,
6350         NULL);
6351   if (stream->priv->session) {
6352     g_object_set (stream->priv->session, "disable-sr-timestamp", !enabled,
6353         NULL);
6354   }
6355   g_mutex_unlock (&stream->priv->lock);
6356 }
6357
6358 /**
6359  * gst_rtsp_stream_get_rate_control:
6360  *
6361  * Returns: whether @stream will follow the Rate-Control=no behaviour as specified
6362  * in the ONVIF replay spec.
6363  *
6364  * Since: 1.18
6365  */
6366 gboolean
6367 gst_rtsp_stream_get_rate_control (GstRTSPStream * stream)
6368 {
6369   gboolean ret;
6370
6371   g_mutex_lock (&stream->priv->lock);
6372   ret = stream->priv->do_rate_control;
6373   g_mutex_unlock (&stream->priv->lock);
6374
6375   return ret;
6376 }
6377
6378 /**
6379  * gst_rtsp_stream_unblock_rtcp:
6380  *
6381  * Remove blocking probe from the RTCP source. When creating an UDP source for
6382  * RTCP it is initially blocked until this function is called.
6383  * This functions should be called once the pipeline is ready for handling RTCP
6384  * packets.
6385  *
6386  * Since: 1.20
6387  */
6388 void
6389 gst_rtsp_stream_unblock_rtcp (GstRTSPStream * stream)
6390 {
6391   GstRTSPStreamPrivate *priv;
6392
6393   priv = stream->priv;
6394   g_mutex_lock (&priv->lock);
6395   if (priv->block_early_rtcp_probe != 0) {
6396     gst_pad_remove_probe
6397         (priv->block_early_rtcp_pad, priv->block_early_rtcp_probe);
6398     priv->block_early_rtcp_probe = 0;
6399     gst_object_unref (priv->block_early_rtcp_pad);
6400     priv->block_early_rtcp_pad = NULL;
6401   }
6402   if (priv->block_early_rtcp_probe_ipv6 != 0) {
6403     gst_pad_remove_probe
6404         (priv->block_early_rtcp_pad_ipv6, priv->block_early_rtcp_probe_ipv6);
6405     priv->block_early_rtcp_probe_ipv6 = 0;
6406     gst_object_unref (priv->block_early_rtcp_pad_ipv6);
6407     priv->block_early_rtcp_pad_ipv6 = NULL;
6408   }
6409   g_mutex_unlock (&priv->lock);
6410 }