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