Merge ad-hoc release branch '0.10.28'
[platform/upstream/gstreamer.git] / gst / rtpmanager / rtpsession.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #include <string.h>
21
22 #include <gst/rtp/gstrtpbuffer.h>
23 #include <gst/rtp/gstrtcpbuffer.h>
24 #include <gst/netbuffer/gstnetbuffer.h>
25
26 #include "gstrtpbin-marshal.h"
27 #include "rtpsession.h"
28
29 GST_DEBUG_CATEGORY_STATIC (rtp_session_debug);
30 #define GST_CAT_DEFAULT rtp_session_debug
31
32 /* signals and args */
33 enum
34 {
35   SIGNAL_GET_SOURCE_BY_SSRC,
36   SIGNAL_ON_NEW_SSRC,
37   SIGNAL_ON_SSRC_COLLISION,
38   SIGNAL_ON_SSRC_VALIDATED,
39   SIGNAL_ON_SSRC_ACTIVE,
40   SIGNAL_ON_SSRC_SDES,
41   SIGNAL_ON_BYE_SSRC,
42   SIGNAL_ON_BYE_TIMEOUT,
43   SIGNAL_ON_TIMEOUT,
44   SIGNAL_ON_SENDER_TIMEOUT,
45   SIGNAL_ON_SENDING_RTCP,
46   SIGNAL_ON_FEEDBACK_RTCP,
47   SIGNAL_SEND_RTCP,
48   LAST_SIGNAL
49 };
50
51 #define DEFAULT_INTERNAL_SOURCE      NULL
52 #define DEFAULT_BANDWIDTH            RTP_STATS_BANDWIDTH
53 #define DEFAULT_RTCP_FRACTION        (RTP_STATS_RTCP_FRACTION * RTP_STATS_BANDWIDTH)
54 #define DEFAULT_RTCP_RR_BANDWIDTH    -1
55 #define DEFAULT_RTCP_RS_BANDWIDTH    -1
56 #define DEFAULT_RTCP_MTU             1400
57 #define DEFAULT_SDES                 NULL
58 #define DEFAULT_NUM_SOURCES          0
59 #define DEFAULT_NUM_ACTIVE_SOURCES   0
60 #define DEFAULT_SOURCES              NULL
61 #define DEFAULT_RTCP_MIN_INTERVAL    (RTP_STATS_MIN_INTERVAL * GST_SECOND)
62 #define DEFAULT_RTCP_FEEDBACK_RETENTION_WINDOW (2 * GST_SECOND)
63
64 enum
65 {
66   PROP_0,
67   PROP_INTERNAL_SSRC,
68   PROP_INTERNAL_SOURCE,
69   PROP_BANDWIDTH,
70   PROP_RTCP_FRACTION,
71   PROP_RTCP_RR_BANDWIDTH,
72   PROP_RTCP_RS_BANDWIDTH,
73   PROP_RTCP_MTU,
74   PROP_SDES,
75   PROP_NUM_SOURCES,
76   PROP_NUM_ACTIVE_SOURCES,
77   PROP_SOURCES,
78   PROP_FAVOR_NEW,
79   PROP_RTCP_MIN_INTERVAL,
80   PROP_RTCP_FEEDBACK_RETENTION_WINDOW,
81   PROP_LAST
82 };
83
84 /* update average packet size */
85 #define INIT_AVG(avg, val) \
86    (avg) = (val);
87 #define UPDATE_AVG(avg, val)            \
88   if ((avg) == 0)                       \
89    (avg) = (val);                       \
90   else                                  \
91    (avg) = ((val) + (15 * (avg))) >> 4;
92
93
94 /* The number RTCP intervals after which to timeout entries in the
95  * collision table
96  */
97 #define RTCP_INTERVAL_COLLISION_TIMEOUT 10
98
99 /* GObject vmethods */
100 static void rtp_session_finalize (GObject * object);
101 static void rtp_session_set_property (GObject * object, guint prop_id,
102     const GValue * value, GParamSpec * pspec);
103 static void rtp_session_get_property (GObject * object, guint prop_id,
104     GValue * value, GParamSpec * pspec);
105
106 static gboolean rtp_session_on_sending_rtcp (RTPSession * sess,
107     GstBuffer * buffer, gboolean early);
108 static void rtp_session_send_rtcp (RTPSession * sess,
109     GstClockTimeDiff max_delay);
110
111
112 static guint rtp_session_signals[LAST_SIGNAL] = { 0 };
113
114 G_DEFINE_TYPE (RTPSession, rtp_session, G_TYPE_OBJECT);
115
116 static RTPSource *obtain_source (RTPSession * sess, guint32 ssrc,
117     gboolean * created, RTPArrivalStats * arrival, gboolean rtp);
118 static GstFlowReturn rtp_session_schedule_bye_locked (RTPSession * sess,
119     const gchar * reason, GstClockTime current_time);
120 static GstClockTime calculate_rtcp_interval (RTPSession * sess,
121     gboolean deterministic, gboolean first);
122
123 static gboolean
124 accumulate_trues (GSignalInvocationHint * ihint, GValue * return_accu,
125     const GValue * handler_return, gpointer data)
126 {
127   if (g_value_get_boolean (handler_return))
128     g_value_set_boolean (return_accu, TRUE);
129
130   return TRUE;
131 }
132
133 static void
134 rtp_session_class_init (RTPSessionClass * klass)
135 {
136   GObjectClass *gobject_class;
137
138   gobject_class = (GObjectClass *) klass;
139
140   gobject_class->finalize = rtp_session_finalize;
141   gobject_class->set_property = rtp_session_set_property;
142   gobject_class->get_property = rtp_session_get_property;
143
144   /**
145    * RTPSession::get-source-by-ssrc:
146    * @session: the object which received the signal
147    * @ssrc: the SSRC of the RTPSource
148    *
149    * Request the #RTPSource object with SSRC @ssrc in @session.
150    */
151   rtp_session_signals[SIGNAL_GET_SOURCE_BY_SSRC] =
152       g_signal_new ("get-source-by-ssrc", G_TYPE_FROM_CLASS (klass),
153       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (RTPSessionClass,
154           get_source_by_ssrc), NULL, NULL, gst_rtp_bin_marshal_OBJECT__UINT,
155       RTP_TYPE_SOURCE, 1, G_TYPE_UINT);
156
157   /**
158    * RTPSession::on-new-ssrc:
159    * @session: the object which received the signal
160    * @src: the new RTPSource
161    *
162    * Notify of a new SSRC that entered @session.
163    */
164   rtp_session_signals[SIGNAL_ON_NEW_SSRC] =
165       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
166       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_new_ssrc),
167       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
168       RTP_TYPE_SOURCE);
169   /**
170    * RTPSession::on-ssrc-collision:
171    * @session: the object which received the signal
172    * @src: the #RTPSource that caused a collision
173    *
174    * Notify when we have an SSRC collision
175    */
176   rtp_session_signals[SIGNAL_ON_SSRC_COLLISION] =
177       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
178       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_collision),
179       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
180       RTP_TYPE_SOURCE);
181   /**
182    * RTPSession::on-ssrc-validated:
183    * @session: the object which received the signal
184    * @src: the new validated RTPSource
185    *
186    * Notify of a new SSRC that became validated.
187    */
188   rtp_session_signals[SIGNAL_ON_SSRC_VALIDATED] =
189       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
190       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_validated),
191       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
192       RTP_TYPE_SOURCE);
193   /**
194    * RTPSession::on-ssrc-active:
195    * @session: the object which received the signal
196    * @src: the active RTPSource
197    *
198    * Notify of a SSRC that is active, i.e., sending RTCP.
199    */
200   rtp_session_signals[SIGNAL_ON_SSRC_ACTIVE] =
201       g_signal_new ("on-ssrc-active", G_TYPE_FROM_CLASS (klass),
202       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_active),
203       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
204       RTP_TYPE_SOURCE);
205   /**
206    * RTPSession::on-ssrc-sdes:
207    * @session: the object which received the signal
208    * @src: the RTPSource
209    *
210    * Notify that a new SDES was received for SSRC.
211    */
212   rtp_session_signals[SIGNAL_ON_SSRC_SDES] =
213       g_signal_new ("on-ssrc-sdes", G_TYPE_FROM_CLASS (klass),
214       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_sdes),
215       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
216       RTP_TYPE_SOURCE);
217   /**
218    * RTPSession::on-bye-ssrc:
219    * @session: the object which received the signal
220    * @src: the RTPSource that went away
221    *
222    * Notify of an SSRC that became inactive because of a BYE packet.
223    */
224   rtp_session_signals[SIGNAL_ON_BYE_SSRC] =
225       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
226       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_bye_ssrc),
227       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
228       RTP_TYPE_SOURCE);
229   /**
230    * RTPSession::on-bye-timeout:
231    * @session: the object which received the signal
232    * @src: the RTPSource that timed out
233    *
234    * Notify of an SSRC that has timed out because of BYE
235    */
236   rtp_session_signals[SIGNAL_ON_BYE_TIMEOUT] =
237       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
238       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_bye_timeout),
239       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
240       RTP_TYPE_SOURCE);
241   /**
242    * RTPSession::on-timeout:
243    * @session: the object which received the signal
244    * @src: the RTPSource that timed out
245    *
246    * Notify of an SSRC that has timed out
247    */
248   rtp_session_signals[SIGNAL_ON_TIMEOUT] =
249       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
250       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_timeout),
251       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
252       RTP_TYPE_SOURCE);
253   /**
254    * RTPSession::on-sender-timeout:
255    * @session: the object which received the signal
256    * @src: the RTPSource that timed out
257    *
258    * Notify of an SSRC that was a sender but timed out and became a receiver.
259    */
260   rtp_session_signals[SIGNAL_ON_SENDER_TIMEOUT] =
261       g_signal_new ("on-sender-timeout", G_TYPE_FROM_CLASS (klass),
262       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_sender_timeout),
263       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
264       RTP_TYPE_SOURCE);
265
266   /**
267    * RTPSession::on-sending-rtcp
268    * @session: the object which received the signal
269    * @buffer: the #GstBuffer containing the RTCP packet about to be sent
270    * @early: %TRUE if the packet is early, %FALSE if it is regular
271    *
272    * This signal is emitted before sending an RTCP packet, it can be used
273    * to add extra RTCP Packets.
274    *
275    * Returns: %TRUE if the RTCP buffer should NOT be suppressed, %FALSE
276    * if suppressing it is acceptable
277    */
278   rtp_session_signals[SIGNAL_ON_SENDING_RTCP] =
279       g_signal_new ("on-sending-rtcp", G_TYPE_FROM_CLASS (klass),
280       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_sending_rtcp),
281       accumulate_trues, NULL, gst_rtp_bin_marshal_BOOLEAN__POINTER_BOOLEAN,
282       G_TYPE_BOOLEAN, 2, G_TYPE_POINTER, G_TYPE_BOOLEAN);
283
284   /**
285    * RTPSession::on-feedback-rtcp:
286    * @session: the object which received the signal
287    * @type: Type of RTCP packet, will be %GST_RTCP_TYPE_RTPFB or
288    *  %GST_RTCP_TYPE_RTPFB
289    * @fbtype: The type of RTCP FB packet, probably part of #GstRTCPFBType
290    * @sender_ssrc: The SSRC of the sender
291    * @media_ssrc: The SSRC of the media this refers to
292    * @fci: a #GstBuffer with the FCI data from the FB packet or %NULL if
293    * there was no FCI
294    *
295    * Notify that a RTCP feedback packet has been received
296    */
297
298   rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP] =
299       g_signal_new ("on-feedback-rtcp", G_TYPE_FROM_CLASS (klass),
300       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_feedback_rtcp),
301       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT_UINT_UINT_POINTER,
302       G_TYPE_NONE, 4, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT,
303       G_TYPE_POINTER);
304
305   /**
306    * RTPSession::send-rtcp:
307    * @session: the object which received the signal
308    * @max_delay: The maximum delay after which the feedback will not be useful
309    *  anymore
310    *
311    * Requests that the #RTPSession initiate a new RTCP packet as soon as
312    * possible within the requested delay.
313    */
314
315   rtp_session_signals[SIGNAL_SEND_RTCP] =
316       g_signal_new ("send-rtcp", G_TYPE_FROM_CLASS (klass),
317       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
318       G_STRUCT_OFFSET (RTPSessionClass, send_rtcp), NULL, NULL,
319       gst_rtp_bin_marshal_VOID__UINT64, G_TYPE_NONE, 1, G_TYPE_UINT64);
320
321   g_object_class_install_property (gobject_class, PROP_INTERNAL_SSRC,
322       g_param_spec_uint ("internal-ssrc", "Internal SSRC",
323           "The internal SSRC used for the session",
324           0, G_MAXUINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
325
326   g_object_class_install_property (gobject_class, PROP_INTERNAL_SOURCE,
327       g_param_spec_object ("internal-source", "Internal Source",
328           "The internal source element of the session",
329           RTP_TYPE_SOURCE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
330
331   g_object_class_install_property (gobject_class, PROP_BANDWIDTH,
332       g_param_spec_double ("bandwidth", "Bandwidth",
333           "The bandwidth of the session (0 for auto-discover)",
334           0.0, G_MAXDOUBLE, DEFAULT_BANDWIDTH,
335           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
336
337   g_object_class_install_property (gobject_class, PROP_RTCP_FRACTION,
338       g_param_spec_double ("rtcp-fraction", "RTCP Fraction",
339           "The fraction of the bandwidth used for RTCP (or as a real fraction of the RTP bandwidth if < 1)",
340           0.0, G_MAXDOUBLE, DEFAULT_RTCP_FRACTION,
341           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
342
343   g_object_class_install_property (gobject_class, PROP_RTCP_RR_BANDWIDTH,
344       g_param_spec_int ("rtcp-rr-bandwidth", "RTCP RR bandwidth",
345           "The RTCP bandwidth used for receivers in bytes per second (-1 = default)",
346           -1, G_MAXINT, DEFAULT_RTCP_RR_BANDWIDTH,
347           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348
349   g_object_class_install_property (gobject_class, PROP_RTCP_RS_BANDWIDTH,
350       g_param_spec_int ("rtcp-rs-bandwidth", "RTCP RS bandwidth",
351           "The RTCP bandwidth used for senders in bytes per second (-1 = default)",
352           -1, G_MAXINT, DEFAULT_RTCP_RS_BANDWIDTH,
353           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
354
355   g_object_class_install_property (gobject_class, PROP_RTCP_MTU,
356       g_param_spec_uint ("rtcp-mtu", "RTCP MTU",
357           "The maximum size of the RTCP packets",
358           16, G_MAXINT16, DEFAULT_RTCP_MTU,
359           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
360
361   g_object_class_install_property (gobject_class, PROP_SDES,
362       g_param_spec_boxed ("sdes", "SDES",
363           "The SDES items of this session",
364           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
365
366   g_object_class_install_property (gobject_class, PROP_NUM_SOURCES,
367       g_param_spec_uint ("num-sources", "Num Sources",
368           "The number of sources in the session", 0, G_MAXUINT,
369           DEFAULT_NUM_SOURCES, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
370
371   g_object_class_install_property (gobject_class, PROP_NUM_ACTIVE_SOURCES,
372       g_param_spec_uint ("num-active-sources", "Num Active Sources",
373           "The number of active sources in the session", 0, G_MAXUINT,
374           DEFAULT_NUM_ACTIVE_SOURCES,
375           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
376   /**
377    * RTPSource::sources
378    *
379    * Get a GValue Array of all sources in the session.
380    *
381    * <example>
382    * <title>Getting the #RTPSources of a session
383    * <programlisting>
384    * {
385    *   GValueArray *arr;
386    *   GValue *val;
387    *   guint i;
388    *
389    *   g_object_get (sess, "sources", &arr, NULL);
390    *
391    *   for (i = 0; i < arr->n_values; i++) {
392    *     RTPSource *source;
393    *
394    *     val = g_value_array_get_nth (arr, i);
395    *     source = g_value_get_object (val);
396    *   }
397    *   g_value_array_free (arr);
398    * }
399    * </programlisting>
400    * </example>
401    */
402   g_object_class_install_property (gobject_class, PROP_SOURCES,
403       g_param_spec_boxed ("sources", "Sources",
404           "An array of all known sources in the session",
405           G_TYPE_VALUE_ARRAY, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
406
407   g_object_class_install_property (gobject_class, PROP_FAVOR_NEW,
408       g_param_spec_boolean ("favor-new", "Favor new sources",
409           "Resolve SSRC conflict in favor of new sources", FALSE,
410           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
411
412   g_object_class_install_property (gobject_class, PROP_RTCP_MIN_INTERVAL,
413       g_param_spec_uint64 ("rtcp-min-interval", "Minimum RTCP interval",
414           "Minimum interval between Regular RTCP packet (in ns)",
415           0, G_MAXUINT64, DEFAULT_RTCP_MIN_INTERVAL,
416           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
417
418   g_object_class_install_property (gobject_class,
419       PROP_RTCP_FEEDBACK_RETENTION_WINDOW,
420       g_param_spec_uint64 ("rtcp-feedback-retention-window",
421           "RTCP Feedback retention window",
422           "Duration during which RTCP Feedback packets are retained (in ns)",
423           0, G_MAXUINT64, DEFAULT_RTCP_FEEDBACK_RETENTION_WINDOW,
424           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
425
426
427   klass->get_source_by_ssrc =
428       GST_DEBUG_FUNCPTR (rtp_session_get_source_by_ssrc);
429   klass->on_sending_rtcp = GST_DEBUG_FUNCPTR (rtp_session_on_sending_rtcp);
430   klass->send_rtcp = GST_DEBUG_FUNCPTR (rtp_session_send_rtcp);
431
432   GST_DEBUG_CATEGORY_INIT (rtp_session_debug, "rtpsession", 0, "RTP Session");
433 }
434
435 static void
436 rtp_session_init (RTPSession * sess)
437 {
438   gint i;
439   gchar *str;
440
441   sess->lock = g_mutex_new ();
442   sess->key = g_random_int ();
443   sess->mask_idx = 0;
444   sess->mask = 0;
445
446   for (i = 0; i < 32; i++) {
447     sess->ssrcs[i] =
448         g_hash_table_new_full (NULL, NULL, NULL,
449         (GDestroyNotify) g_object_unref);
450   }
451   sess->cnames = g_hash_table_new_full (NULL, NULL, g_free, NULL);
452
453   rtp_stats_init_defaults (&sess->stats);
454
455   sess->recalc_bandwidth = TRUE;
456   sess->bandwidth = DEFAULT_BANDWIDTH;
457   sess->rtcp_bandwidth = DEFAULT_RTCP_FRACTION;
458   sess->rtcp_rr_bandwidth = DEFAULT_RTCP_RR_BANDWIDTH;
459   sess->rtcp_rs_bandwidth = DEFAULT_RTCP_RS_BANDWIDTH;
460
461   /* create an active SSRC for this session manager */
462   sess->source = rtp_session_create_source (sess);
463   sess->source->validated = TRUE;
464   sess->source->internal = TRUE;
465   sess->stats.active_sources++;
466   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
467
468   /* default UDP header length */
469   sess->header_len = 28;
470   sess->mtu = DEFAULT_RTCP_MTU;
471
472   /* some default SDES entries */
473   str = g_strdup_printf ("%s@%s", g_get_user_name (), g_get_host_name ());
474   rtp_source_set_sdes_string (sess->source, GST_RTCP_SDES_CNAME, str);
475   g_free (str);
476
477   rtp_source_set_sdes_string (sess->source, GST_RTCP_SDES_NAME,
478       g_get_real_name ());
479   rtp_source_set_sdes_string (sess->source, GST_RTCP_SDES_TOOL, "GStreamer");
480
481   sess->first_rtcp = TRUE;
482   sess->allow_early = TRUE;
483   sess->rtcp_feedback_retention_window = DEFAULT_RTCP_FEEDBACK_RETENTION_WINDOW;
484
485   sess->rtcp_pli_requests = g_array_new (FALSE, FALSE, sizeof (guint32));
486
487   GST_DEBUG ("%p: session using SSRC: %08x", sess, sess->source->ssrc);
488 }
489
490 static void
491 rtp_session_finalize (GObject * object)
492 {
493   RTPSession *sess;
494   gint i;
495
496   sess = RTP_SESSION_CAST (object);
497
498   g_mutex_free (sess->lock);
499   for (i = 0; i < 32; i++)
500     g_hash_table_destroy (sess->ssrcs[i]);
501
502   g_free (sess->bye_reason);
503
504   g_hash_table_destroy (sess->cnames);
505   g_object_unref (sess->source);
506
507   g_array_free (sess->rtcp_pli_requests, TRUE);
508
509   G_OBJECT_CLASS (rtp_session_parent_class)->finalize (object);
510 }
511
512 static void
513 copy_source (gpointer key, RTPSource * source, GValueArray * arr)
514 {
515   GValue value = { 0 };
516
517   g_value_init (&value, RTP_TYPE_SOURCE);
518   g_value_take_object (&value, source);
519   /* copies the value */
520   g_value_array_append (arr, &value);
521 }
522
523 static GValueArray *
524 rtp_session_create_sources (RTPSession * sess)
525 {
526   GValueArray *res;
527   guint size;
528
529   RTP_SESSION_LOCK (sess);
530   /* get number of elements in the table */
531   size = g_hash_table_size (sess->ssrcs[sess->mask_idx]);
532   /* create the result value array */
533   res = g_value_array_new (size);
534
535   /* and copy all values into the array */
536   g_hash_table_foreach (sess->ssrcs[sess->mask_idx], (GHFunc) copy_source, res);
537   RTP_SESSION_UNLOCK (sess);
538
539   return res;
540 }
541
542 static void
543 rtp_session_set_property (GObject * object, guint prop_id,
544     const GValue * value, GParamSpec * pspec)
545 {
546   RTPSession *sess;
547
548   sess = RTP_SESSION (object);
549
550   switch (prop_id) {
551     case PROP_INTERNAL_SSRC:
552       rtp_session_set_internal_ssrc (sess, g_value_get_uint (value));
553       break;
554     case PROP_BANDWIDTH:
555       sess->bandwidth = g_value_get_double (value);
556       sess->recalc_bandwidth = TRUE;
557       break;
558     case PROP_RTCP_FRACTION:
559       sess->rtcp_bandwidth = g_value_get_double (value);
560       sess->recalc_bandwidth = TRUE;
561       break;
562     case PROP_RTCP_RR_BANDWIDTH:
563       sess->rtcp_rr_bandwidth = g_value_get_int (value);
564       sess->recalc_bandwidth = TRUE;
565       break;
566     case PROP_RTCP_RS_BANDWIDTH:
567       sess->rtcp_rs_bandwidth = g_value_get_int (value);
568       sess->recalc_bandwidth = TRUE;
569       break;
570     case PROP_RTCP_MTU:
571       sess->mtu = g_value_get_uint (value);
572       break;
573     case PROP_SDES:
574       rtp_session_set_sdes_struct (sess, g_value_get_boxed (value));
575       break;
576     case PROP_FAVOR_NEW:
577       sess->favor_new = g_value_get_boolean (value);
578       break;
579     case PROP_RTCP_MIN_INTERVAL:
580       rtp_stats_set_min_interval (&sess->stats,
581           (gdouble) g_value_get_uint64 (value) / GST_SECOND);
582       break;
583     default:
584       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
585       break;
586   }
587 }
588
589 static void
590 rtp_session_get_property (GObject * object, guint prop_id,
591     GValue * value, GParamSpec * pspec)
592 {
593   RTPSession *sess;
594
595   sess = RTP_SESSION (object);
596
597   switch (prop_id) {
598     case PROP_INTERNAL_SSRC:
599       g_value_set_uint (value, rtp_session_get_internal_ssrc (sess));
600       break;
601     case PROP_INTERNAL_SOURCE:
602       g_value_take_object (value, rtp_session_get_internal_source (sess));
603       break;
604     case PROP_BANDWIDTH:
605       g_value_set_double (value, sess->bandwidth);
606       break;
607     case PROP_RTCP_FRACTION:
608       g_value_set_double (value, sess->rtcp_bandwidth);
609       break;
610     case PROP_RTCP_RR_BANDWIDTH:
611       g_value_set_int (value, sess->rtcp_rr_bandwidth);
612       break;
613     case PROP_RTCP_RS_BANDWIDTH:
614       g_value_set_int (value, sess->rtcp_rs_bandwidth);
615       break;
616     case PROP_RTCP_MTU:
617       g_value_set_uint (value, sess->mtu);
618       break;
619     case PROP_SDES:
620       g_value_take_boxed (value, rtp_session_get_sdes_struct (sess));
621       break;
622     case PROP_NUM_SOURCES:
623       g_value_set_uint (value, rtp_session_get_num_sources (sess));
624       break;
625     case PROP_NUM_ACTIVE_SOURCES:
626       g_value_set_uint (value, rtp_session_get_num_active_sources (sess));
627       break;
628     case PROP_SOURCES:
629       g_value_take_boxed (value, rtp_session_create_sources (sess));
630       break;
631     case PROP_FAVOR_NEW:
632       g_value_set_boolean (value, sess->favor_new);
633       break;
634     case PROP_RTCP_MIN_INTERVAL:
635       g_value_set_uint64 (value, sess->stats.min_interval * GST_SECOND);
636       break;
637     default:
638       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
639       break;
640   }
641 }
642
643 static void
644 on_new_ssrc (RTPSession * sess, RTPSource * source)
645 {
646   g_object_ref (source);
647   RTP_SESSION_UNLOCK (sess);
648   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_NEW_SSRC], 0, source);
649   RTP_SESSION_LOCK (sess);
650   g_object_unref (source);
651 }
652
653 static void
654 on_ssrc_collision (RTPSession * sess, RTPSource * source)
655 {
656   g_object_ref (source);
657   RTP_SESSION_UNLOCK (sess);
658   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_COLLISION], 0,
659       source);
660   RTP_SESSION_LOCK (sess);
661   g_object_unref (source);
662 }
663
664 static void
665 on_ssrc_validated (RTPSession * sess, RTPSource * source)
666 {
667   g_object_ref (source);
668   RTP_SESSION_UNLOCK (sess);
669   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
670       source);
671   RTP_SESSION_LOCK (sess);
672   g_object_unref (source);
673 }
674
675 static void
676 on_ssrc_active (RTPSession * sess, RTPSource * source)
677 {
678   g_object_ref (source);
679   RTP_SESSION_UNLOCK (sess);
680   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_ACTIVE], 0, source);
681   RTP_SESSION_LOCK (sess);
682   g_object_unref (source);
683 }
684
685 static void
686 on_ssrc_sdes (RTPSession * sess, RTPSource * source)
687 {
688   g_object_ref (source);
689   GST_DEBUG ("SDES changed for SSRC %08x", source->ssrc);
690   RTP_SESSION_UNLOCK (sess);
691   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_SDES], 0, source);
692   RTP_SESSION_LOCK (sess);
693   g_object_unref (source);
694 }
695
696 static void
697 on_bye_ssrc (RTPSession * sess, RTPSource * source)
698 {
699   g_object_ref (source);
700   RTP_SESSION_UNLOCK (sess);
701   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_BYE_SSRC], 0, source);
702   RTP_SESSION_LOCK (sess);
703   g_object_unref (source);
704 }
705
706 static void
707 on_bye_timeout (RTPSession * sess, RTPSource * source)
708 {
709   g_object_ref (source);
710   RTP_SESSION_UNLOCK (sess);
711   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_BYE_TIMEOUT], 0, source);
712   RTP_SESSION_LOCK (sess);
713   g_object_unref (source);
714 }
715
716 static void
717 on_timeout (RTPSession * sess, RTPSource * source)
718 {
719   g_object_ref (source);
720   RTP_SESSION_UNLOCK (sess);
721   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_TIMEOUT], 0, source);
722   RTP_SESSION_LOCK (sess);
723   g_object_unref (source);
724 }
725
726 static void
727 on_sender_timeout (RTPSession * sess, RTPSource * source)
728 {
729   g_object_ref (source);
730   RTP_SESSION_UNLOCK (sess);
731   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDER_TIMEOUT], 0,
732       source);
733   RTP_SESSION_LOCK (sess);
734   g_object_unref (source);
735 }
736
737 /**
738  * rtp_session_new:
739  *
740  * Create a new session object.
741  *
742  * Returns: a new #RTPSession. g_object_unref() after usage.
743  */
744 RTPSession *
745 rtp_session_new (void)
746 {
747   RTPSession *sess;
748
749   sess = g_object_new (RTP_TYPE_SESSION, NULL);
750
751   return sess;
752 }
753
754 /**
755  * rtp_session_set_callbacks:
756  * @sess: an #RTPSession
757  * @callbacks: callbacks to configure
758  * @user_data: user data passed in the callbacks
759  *
760  * Configure a set of callbacks to be notified of actions.
761  */
762 void
763 rtp_session_set_callbacks (RTPSession * sess, RTPSessionCallbacks * callbacks,
764     gpointer user_data)
765 {
766   g_return_if_fail (RTP_IS_SESSION (sess));
767
768   if (callbacks->process_rtp) {
769     sess->callbacks.process_rtp = callbacks->process_rtp;
770     sess->process_rtp_user_data = user_data;
771   }
772   if (callbacks->send_rtp) {
773     sess->callbacks.send_rtp = callbacks->send_rtp;
774     sess->send_rtp_user_data = user_data;
775   }
776   if (callbacks->send_rtcp) {
777     sess->callbacks.send_rtcp = callbacks->send_rtcp;
778     sess->send_rtcp_user_data = user_data;
779   }
780   if (callbacks->sync_rtcp) {
781     sess->callbacks.sync_rtcp = callbacks->sync_rtcp;
782     sess->sync_rtcp_user_data = user_data;
783   }
784   if (callbacks->clock_rate) {
785     sess->callbacks.clock_rate = callbacks->clock_rate;
786     sess->clock_rate_user_data = user_data;
787   }
788   if (callbacks->reconsider) {
789     sess->callbacks.reconsider = callbacks->reconsider;
790     sess->reconsider_user_data = user_data;
791   }
792   if (callbacks->request_key_unit) {
793     sess->callbacks.request_key_unit = callbacks->request_key_unit;
794     sess->request_key_unit_user_data = user_data;
795   }
796   if (callbacks->request_time) {
797     sess->callbacks.request_time = callbacks->request_time;
798     sess->request_time_user_data = user_data;
799   }
800 }
801
802 /**
803  * rtp_session_set_process_rtp_callback:
804  * @sess: an #RTPSession
805  * @callback: callback to set
806  * @user_data: user data passed in the callback
807  *
808  * Configure only the process_rtp callback to be notified of the process_rtp action.
809  */
810 void
811 rtp_session_set_process_rtp_callback (RTPSession * sess,
812     RTPSessionProcessRTP callback, gpointer user_data)
813 {
814   g_return_if_fail (RTP_IS_SESSION (sess));
815
816   sess->callbacks.process_rtp = callback;
817   sess->process_rtp_user_data = user_data;
818 }
819
820 /**
821  * rtp_session_set_send_rtp_callback:
822  * @sess: an #RTPSession
823  * @callback: callback to set
824  * @user_data: user data passed in the callback
825  *
826  * Configure only the send_rtp callback to be notified of the send_rtp action.
827  */
828 void
829 rtp_session_set_send_rtp_callback (RTPSession * sess,
830     RTPSessionSendRTP callback, gpointer user_data)
831 {
832   g_return_if_fail (RTP_IS_SESSION (sess));
833
834   sess->callbacks.send_rtp = callback;
835   sess->send_rtp_user_data = user_data;
836 }
837
838 /**
839  * rtp_session_set_send_rtcp_callback:
840  * @sess: an #RTPSession
841  * @callback: callback to set
842  * @user_data: user data passed in the callback
843  *
844  * Configure only the send_rtcp callback to be notified of the send_rtcp action.
845  */
846 void
847 rtp_session_set_send_rtcp_callback (RTPSession * sess,
848     RTPSessionSendRTCP callback, gpointer user_data)
849 {
850   g_return_if_fail (RTP_IS_SESSION (sess));
851
852   sess->callbacks.send_rtcp = callback;
853   sess->send_rtcp_user_data = user_data;
854 }
855
856 /**
857  * rtp_session_set_sync_rtcp_callback:
858  * @sess: an #RTPSession
859  * @callback: callback to set
860  * @user_data: user data passed in the callback
861  *
862  * Configure only the sync_rtcp callback to be notified of the sync_rtcp action.
863  */
864 void
865 rtp_session_set_sync_rtcp_callback (RTPSession * sess,
866     RTPSessionSyncRTCP callback, gpointer user_data)
867 {
868   g_return_if_fail (RTP_IS_SESSION (sess));
869
870   sess->callbacks.sync_rtcp = callback;
871   sess->sync_rtcp_user_data = user_data;
872 }
873
874 /**
875  * rtp_session_set_clock_rate_callback:
876  * @sess: an #RTPSession
877  * @callback: callback to set
878  * @user_data: user data passed in the callback
879  *
880  * Configure only the clock_rate callback to be notified of the clock_rate action.
881  */
882 void
883 rtp_session_set_clock_rate_callback (RTPSession * sess,
884     RTPSessionClockRate callback, gpointer user_data)
885 {
886   g_return_if_fail (RTP_IS_SESSION (sess));
887
888   sess->callbacks.clock_rate = callback;
889   sess->clock_rate_user_data = user_data;
890 }
891
892 /**
893  * rtp_session_set_reconsider_callback:
894  * @sess: an #RTPSession
895  * @callback: callback to set
896  * @user_data: user data passed in the callback
897  *
898  * Configure only the reconsider callback to be notified of the reconsider action.
899  */
900 void
901 rtp_session_set_reconsider_callback (RTPSession * sess,
902     RTPSessionReconsider callback, gpointer user_data)
903 {
904   g_return_if_fail (RTP_IS_SESSION (sess));
905
906   sess->callbacks.reconsider = callback;
907   sess->reconsider_user_data = user_data;
908 }
909
910 /**
911  * rtp_session_set_request_time_callback:
912  * @sess: an #RTPSession
913  * @callback: callback to set
914  * @user_data: user data passed in the callback
915  *
916  * Configure only the request_time callback
917  */
918 void
919 rtp_session_set_request_time_callback (RTPSession * sess,
920     RTPSessionRequestTime callback, gpointer user_data)
921 {
922   g_return_if_fail (RTP_IS_SESSION (sess));
923
924   sess->callbacks.request_time = callback;
925   sess->request_time_user_data = user_data;
926 }
927
928 /**
929  * rtp_session_set_bandwidth:
930  * @sess: an #RTPSession
931  * @bandwidth: the bandwidth allocated
932  *
933  * Set the session bandwidth in bytes per second.
934  */
935 void
936 rtp_session_set_bandwidth (RTPSession * sess, gdouble bandwidth)
937 {
938   g_return_if_fail (RTP_IS_SESSION (sess));
939
940   RTP_SESSION_LOCK (sess);
941   sess->stats.bandwidth = bandwidth;
942   RTP_SESSION_UNLOCK (sess);
943 }
944
945 /**
946  * rtp_session_get_bandwidth:
947  * @sess: an #RTPSession
948  *
949  * Get the session bandwidth.
950  *
951  * Returns: the session bandwidth.
952  */
953 gdouble
954 rtp_session_get_bandwidth (RTPSession * sess)
955 {
956   gdouble result;
957
958   g_return_val_if_fail (RTP_IS_SESSION (sess), 0);
959
960   RTP_SESSION_LOCK (sess);
961   result = sess->stats.bandwidth;
962   RTP_SESSION_UNLOCK (sess);
963
964   return result;
965 }
966
967 /**
968  * rtp_session_set_rtcp_fraction:
969  * @sess: an #RTPSession
970  * @bandwidth: the RTCP bandwidth
971  *
972  * Set the bandwidth in bytes per second that should be used for RTCP
973  * messages.
974  */
975 void
976 rtp_session_set_rtcp_fraction (RTPSession * sess, gdouble bandwidth)
977 {
978   g_return_if_fail (RTP_IS_SESSION (sess));
979
980   RTP_SESSION_LOCK (sess);
981   sess->stats.rtcp_bandwidth = bandwidth;
982   RTP_SESSION_UNLOCK (sess);
983 }
984
985 /**
986  * rtp_session_get_rtcp_fraction:
987  * @sess: an #RTPSession
988  *
989  * Get the session bandwidth used for RTCP.
990  *
991  * Returns: The bandwidth used for RTCP messages.
992  */
993 gdouble
994 rtp_session_get_rtcp_fraction (RTPSession * sess)
995 {
996   gdouble result;
997
998   g_return_val_if_fail (RTP_IS_SESSION (sess), 0.0);
999
1000   RTP_SESSION_LOCK (sess);
1001   result = sess->stats.rtcp_bandwidth;
1002   RTP_SESSION_UNLOCK (sess);
1003
1004   return result;
1005 }
1006
1007 /**
1008  * rtp_session_set_sdes_string:
1009  * @sess: an #RTPSession
1010  * @type: the type of the SDES item
1011  * @item: a null-terminated string to set.
1012  *
1013  * Store an SDES item of @type in @sess.
1014  *
1015  * Returns: %FALSE if the data was unchanged @type is invalid.
1016  */
1017 gboolean
1018 rtp_session_set_sdes_string (RTPSession * sess, GstRTCPSDESType type,
1019     const gchar * item)
1020 {
1021   gboolean result;
1022
1023   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1024
1025   RTP_SESSION_LOCK (sess);
1026   result = rtp_source_set_sdes_string (sess->source, type, item);
1027   RTP_SESSION_UNLOCK (sess);
1028
1029   return result;
1030 }
1031
1032 /**
1033  * rtp_session_get_sdes_string:
1034  * @sess: an #RTPSession
1035  * @type: the type of the SDES item
1036  *
1037  * Get the SDES item of @type from @sess.
1038  *
1039  * Returns: a null-terminated copy of the SDES item or NULL when @type was not
1040  * valid. g_free() after usage.
1041  */
1042 gchar *
1043 rtp_session_get_sdes_string (RTPSession * sess, GstRTCPSDESType type)
1044 {
1045   gchar *result;
1046
1047   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1048
1049   RTP_SESSION_LOCK (sess);
1050   result = rtp_source_get_sdes_string (sess->source, type);
1051   RTP_SESSION_UNLOCK (sess);
1052
1053   return result;
1054 }
1055
1056 /**
1057  * rtp_session_get_sdes_struct:
1058  * @sess: an #RTSPSession
1059  *
1060  * Get the SDES data as a #GstStructure
1061  *
1062  * Returns: a GstStructure with SDES items for @sess. This function returns a
1063  * copy of the SDES structure, use gst_structure_free() after usage.
1064  */
1065 GstStructure *
1066 rtp_session_get_sdes_struct (RTPSession * sess)
1067 {
1068   const GstStructure *sdes;
1069   GstStructure *result = NULL;
1070
1071   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1072
1073   RTP_SESSION_LOCK (sess);
1074   sdes = rtp_source_get_sdes_struct (sess->source);
1075   if (sdes)
1076     result = gst_structure_copy (sdes);
1077   RTP_SESSION_UNLOCK (sess);
1078
1079   return result;
1080 }
1081
1082 /**
1083  * rtp_session_set_sdes_struct:
1084  * @sess: an #RTSPSession
1085  * @sdes: a #GstStructure
1086  *
1087  * Set the SDES data as a #GstStructure. This function makes a copy of @sdes.
1088  */
1089 void
1090 rtp_session_set_sdes_struct (RTPSession * sess, const GstStructure * sdes)
1091 {
1092   g_return_if_fail (sdes);
1093   g_return_if_fail (RTP_IS_SESSION (sess));
1094
1095   RTP_SESSION_LOCK (sess);
1096   rtp_source_set_sdes_struct (sess->source, gst_structure_copy (sdes));
1097   RTP_SESSION_UNLOCK (sess);
1098 }
1099
1100 static GstFlowReturn
1101 source_push_rtp (RTPSource * source, gpointer data, RTPSession * session)
1102 {
1103   GstFlowReturn result = GST_FLOW_OK;
1104
1105   if (source == session->source) {
1106     GST_LOG ("source %08x pushed sender RTP packet", source->ssrc);
1107
1108     RTP_SESSION_UNLOCK (session);
1109
1110     if (session->callbacks.send_rtp)
1111       result =
1112           session->callbacks.send_rtp (session, source, data,
1113           session->send_rtp_user_data);
1114     else {
1115       gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1116     }
1117   } else {
1118     GST_LOG ("source %08x pushed receiver RTP packet", source->ssrc);
1119     RTP_SESSION_UNLOCK (session);
1120
1121     if (session->callbacks.process_rtp)
1122       result =
1123           session->callbacks.process_rtp (session, source,
1124           GST_BUFFER_CAST (data), session->process_rtp_user_data);
1125     else
1126       gst_buffer_unref (GST_BUFFER_CAST (data));
1127   }
1128   RTP_SESSION_LOCK (session);
1129
1130   return result;
1131 }
1132
1133 static gint
1134 source_clock_rate (RTPSource * source, guint8 pt, RTPSession * session)
1135 {
1136   gint result;
1137
1138   RTP_SESSION_UNLOCK (session);
1139
1140   if (session->callbacks.clock_rate)
1141     result =
1142         session->callbacks.clock_rate (session, pt,
1143         session->clock_rate_user_data);
1144   else
1145     result = -1;
1146
1147   RTP_SESSION_LOCK (session);
1148
1149   GST_DEBUG ("got clock-rate %d for pt %d", result, pt);
1150
1151   return result;
1152 }
1153
1154 static RTPSourceCallbacks callbacks = {
1155   (RTPSourcePushRTP) source_push_rtp,
1156   (RTPSourceClockRate) source_clock_rate,
1157 };
1158
1159 static gboolean
1160 check_collision (RTPSession * sess, RTPSource * source,
1161     RTPArrivalStats * arrival, gboolean rtp)
1162 {
1163   /* If we have no arrival address, we can't do collision checking */
1164   if (!arrival->have_address)
1165     return FALSE;
1166
1167   if (sess->source != source) {
1168     GstNetAddress *from;
1169     gboolean have_from;
1170
1171     /* This is not our local source, but lets check if two remote
1172      * source collide
1173      */
1174
1175     if (rtp) {
1176       from = &source->rtp_from;
1177       have_from = source->have_rtp_from;
1178     } else {
1179       from = &source->rtcp_from;
1180       have_from = source->have_rtcp_from;
1181     }
1182
1183     if (have_from) {
1184       if (gst_netaddress_equal (from, &arrival->address)) {
1185         /* Address is the same */
1186         return FALSE;
1187       } else {
1188         GST_LOG ("we have a third-party collision or loop ssrc:%x",
1189             rtp_source_get_ssrc (source));
1190         if (sess->favor_new) {
1191           if (rtp_source_find_conflicting_address (source,
1192                   &arrival->address, arrival->current_time)) {
1193             gchar buf1[40];
1194             gst_netaddress_to_string (&arrival->address, buf1, 40);
1195             GST_LOG ("Known conflict on %x for %s, dropping packet",
1196                 rtp_source_get_ssrc (source), buf1);
1197             return TRUE;
1198           } else {
1199             gchar buf1[40], buf2[40];
1200
1201             /* Current address is not a known conflict, lets assume this is
1202              * a new source. Save old address in possible conflict list
1203              */
1204             rtp_source_add_conflicting_address (source, from,
1205                 arrival->current_time);
1206
1207             gst_netaddress_to_string (from, buf1, 40);
1208             gst_netaddress_to_string (&arrival->address, buf2, 40);
1209             GST_DEBUG ("New conflict for ssrc %x, replacing %s with %s,"
1210                 " saving old as known conflict",
1211                 rtp_source_get_ssrc (source), buf1, buf2);
1212
1213             if (rtp)
1214               rtp_source_set_rtp_from (source, &arrival->address);
1215             else
1216               rtp_source_set_rtcp_from (source, &arrival->address);
1217             return FALSE;
1218           }
1219         } else {
1220           /* Don't need to save old addresses, we ignore new sources */
1221           return TRUE;
1222         }
1223       }
1224     } else {
1225       /* We don't already have a from address for RTP, just set it */
1226       if (rtp)
1227         rtp_source_set_rtp_from (source, &arrival->address);
1228       else
1229         rtp_source_set_rtcp_from (source, &arrival->address);
1230       return FALSE;
1231     }
1232
1233     /* FIXME: Log 3rd party collision somehow
1234      * Maybe should be done in upper layer, only the SDES can tell us
1235      * if its a collision or a loop
1236      */
1237
1238     /* If the source has been inactive for some time, we assume that it has
1239      * simply changed its transport source address. Hence, there is no true
1240      * third-party collision - only a simulated one. */
1241     if (arrival->current_time > source->last_activity) {
1242       GstClockTime inactivity_period =
1243           arrival->current_time - source->last_activity;
1244       if (inactivity_period > 1 * GST_SECOND) {
1245         /* Use new network address */
1246         if (rtp) {
1247           g_assert (source->have_rtp_from);
1248           rtp_source_set_rtp_from (source, &arrival->address);
1249         } else {
1250           g_assert (source->have_rtcp_from);
1251           rtp_source_set_rtcp_from (source, &arrival->address);
1252         }
1253         return FALSE;
1254       }
1255     }
1256   } else {
1257     /* This is sending with our ssrc, is it an address we already know */
1258
1259     if (rtp_source_find_conflicting_address (source, &arrival->address,
1260             arrival->current_time)) {
1261       /* Its a known conflict, its probably a loop, not a collision
1262        * lets just drop the incoming packet
1263        */
1264       GST_DEBUG ("Our packets are being looped back to us, dropping");
1265     } else {
1266       /* Its a new collision, lets change our SSRC */
1267
1268       rtp_source_add_conflicting_address (source, &arrival->address,
1269           arrival->current_time);
1270
1271       GST_DEBUG ("Collision for SSRC %x", rtp_source_get_ssrc (source));
1272       on_ssrc_collision (sess, source);
1273
1274       rtp_session_schedule_bye_locked (sess, "SSRC Collision",
1275           arrival->current_time);
1276
1277       sess->change_ssrc = TRUE;
1278     }
1279   }
1280
1281   return TRUE;
1282 }
1283
1284
1285 /* must be called with the session lock, the returned source needs to be
1286  * unreffed after usage. */
1287 static RTPSource *
1288 obtain_source (RTPSession * sess, guint32 ssrc, gboolean * created,
1289     RTPArrivalStats * arrival, gboolean rtp)
1290 {
1291   RTPSource *source;
1292
1293   source =
1294       g_hash_table_lookup (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc));
1295   if (source == NULL) {
1296     /* make new Source in probation and insert */
1297     source = rtp_source_new (ssrc);
1298
1299     /* for RTP packets we need to set the source in probation. Receiving RTCP
1300      * packets of an SSRC, on the other hand, is a strong indication that we
1301      * are dealing with a valid source. */
1302     if (rtp)
1303       source->probation = RTP_DEFAULT_PROBATION;
1304     else
1305       source->probation = 0;
1306
1307     /* store from address, if any */
1308     if (arrival->have_address) {
1309       if (rtp)
1310         rtp_source_set_rtp_from (source, &arrival->address);
1311       else
1312         rtp_source_set_rtcp_from (source, &arrival->address);
1313     }
1314
1315     /* configure a callback on the source */
1316     rtp_source_set_callbacks (source, &callbacks, sess);
1317
1318     g_hash_table_insert (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc),
1319         source);
1320
1321     /* we have one more source now */
1322     sess->total_sources++;
1323     *created = TRUE;
1324   } else {
1325     *created = FALSE;
1326     /* check for collision, this updates the address when not previously set */
1327     if (check_collision (sess, source, arrival, rtp)) {
1328       return NULL;
1329     }
1330   }
1331   /* update last activity */
1332   source->last_activity = arrival->current_time;
1333   if (rtp)
1334     source->last_rtp_activity = arrival->current_time;
1335   g_object_ref (source);
1336
1337   return source;
1338 }
1339
1340 /**
1341  * rtp_session_get_internal_source:
1342  * @sess: a #RTPSession
1343  *
1344  * Get the internal #RTPSource of @sess.
1345  *
1346  * Returns: The internal #RTPSource. g_object_unref() after usage.
1347  */
1348 RTPSource *
1349 rtp_session_get_internal_source (RTPSession * sess)
1350 {
1351   RTPSource *result;
1352
1353   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1354
1355   result = g_object_ref (sess->source);
1356
1357   return result;
1358 }
1359
1360 /**
1361  * rtp_session_set_internal_ssrc:
1362  * @sess: a #RTPSession
1363  * @ssrc: an SSRC
1364  *
1365  * Set the SSRC of @sess to @ssrc.
1366  */
1367 void
1368 rtp_session_set_internal_ssrc (RTPSession * sess, guint32 ssrc)
1369 {
1370   RTP_SESSION_LOCK (sess);
1371   if (ssrc != sess->source->ssrc) {
1372     g_hash_table_steal (sess->ssrcs[sess->mask_idx],
1373         GINT_TO_POINTER (sess->source->ssrc));
1374
1375     GST_DEBUG ("setting internal SSRC to %08x", ssrc);
1376     /* After this call, any receiver of the old SSRC either in RTP or RTCP
1377      * packets will timeout on the old SSRC, we could potentially schedule a
1378      * BYE RTCP for the old SSRC... */
1379     sess->source->ssrc = ssrc;
1380     rtp_source_reset (sess->source);
1381
1382     /* rehash with the new SSRC */
1383     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
1384         GINT_TO_POINTER (sess->source->ssrc), sess->source);
1385   }
1386   RTP_SESSION_UNLOCK (sess);
1387
1388   g_object_notify (G_OBJECT (sess), "internal-ssrc");
1389 }
1390
1391 /**
1392  * rtp_session_get_internal_ssrc:
1393  * @sess: a #RTPSession
1394  *
1395  * Get the internal SSRC of @sess.
1396  *
1397  * Returns: The SSRC of the session.
1398  */
1399 guint32
1400 rtp_session_get_internal_ssrc (RTPSession * sess)
1401 {
1402   guint32 ssrc;
1403
1404   RTP_SESSION_LOCK (sess);
1405   ssrc = sess->source->ssrc;
1406   RTP_SESSION_UNLOCK (sess);
1407
1408   return ssrc;
1409 }
1410
1411 /**
1412  * rtp_session_add_source:
1413  * @sess: a #RTPSession
1414  * @src: #RTPSource to add
1415  *
1416  * Add @src to @session.
1417  *
1418  * Returns: %TRUE on success, %FALSE if a source with the same SSRC already
1419  * existed in the session.
1420  */
1421 gboolean
1422 rtp_session_add_source (RTPSession * sess, RTPSource * src)
1423 {
1424   gboolean result = FALSE;
1425   RTPSource *find;
1426
1427   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1428   g_return_val_if_fail (src != NULL, FALSE);
1429
1430   RTP_SESSION_LOCK (sess);
1431   find =
1432       g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
1433       GINT_TO_POINTER (src->ssrc));
1434   if (find == NULL) {
1435     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
1436         GINT_TO_POINTER (src->ssrc), src);
1437     /* we have one more source now */
1438     sess->total_sources++;
1439     result = TRUE;
1440   }
1441   RTP_SESSION_UNLOCK (sess);
1442
1443   return result;
1444 }
1445
1446 /**
1447  * rtp_session_get_num_sources:
1448  * @sess: an #RTPSession
1449  *
1450  * Get the number of sources in @sess.
1451  *
1452  * Returns: The number of sources in @sess.
1453  */
1454 guint
1455 rtp_session_get_num_sources (RTPSession * sess)
1456 {
1457   guint result;
1458
1459   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1460
1461   RTP_SESSION_LOCK (sess);
1462   result = sess->total_sources;
1463   RTP_SESSION_UNLOCK (sess);
1464
1465   return result;
1466 }
1467
1468 /**
1469  * rtp_session_get_num_active_sources:
1470  * @sess: an #RTPSession
1471  *
1472  * Get the number of active sources in @sess. A source is considered active when
1473  * it has been validated and has not yet received a BYE RTCP message.
1474  *
1475  * Returns: The number of active sources in @sess.
1476  */
1477 guint
1478 rtp_session_get_num_active_sources (RTPSession * sess)
1479 {
1480   guint result;
1481
1482   g_return_val_if_fail (RTP_IS_SESSION (sess), 0);
1483
1484   RTP_SESSION_LOCK (sess);
1485   result = sess->stats.active_sources;
1486   RTP_SESSION_UNLOCK (sess);
1487
1488   return result;
1489 }
1490
1491 /**
1492  * rtp_session_get_source_by_ssrc:
1493  * @sess: an #RTPSession
1494  * @ssrc: an SSRC
1495  *
1496  * Find the source with @ssrc in @sess.
1497  *
1498  * Returns: a #RTPSource with SSRC @ssrc or NULL if the source was not found.
1499  * g_object_unref() after usage.
1500  */
1501 RTPSource *
1502 rtp_session_get_source_by_ssrc (RTPSession * sess, guint32 ssrc)
1503 {
1504   RTPSource *result;
1505
1506   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1507
1508   RTP_SESSION_LOCK (sess);
1509   result =
1510       g_hash_table_lookup (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc));
1511   if (result)
1512     g_object_ref (result);
1513   RTP_SESSION_UNLOCK (sess);
1514
1515   return result;
1516 }
1517
1518 /**
1519  * rtp_session_get_source_by_cname:
1520  * @sess: a #RTPSession
1521  * @cname: an CNAME
1522  *
1523  * Find the source with @cname in @sess.
1524  *
1525  * Returns: a #RTPSource with CNAME @cname or NULL if the source was not found.
1526  * g_object_unref() after usage.
1527  */
1528 RTPSource *
1529 rtp_session_get_source_by_cname (RTPSession * sess, const gchar * cname)
1530 {
1531   RTPSource *result;
1532
1533   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1534   g_return_val_if_fail (cname != NULL, NULL);
1535
1536   RTP_SESSION_LOCK (sess);
1537   result = g_hash_table_lookup (sess->cnames, cname);
1538   if (result)
1539     g_object_ref (result);
1540   RTP_SESSION_UNLOCK (sess);
1541
1542   return result;
1543 }
1544
1545 /* should be called with the SESSION lock */
1546 static guint32
1547 rtp_session_create_new_ssrc (RTPSession * sess)
1548 {
1549   guint32 ssrc;
1550
1551   while (TRUE) {
1552     ssrc = g_random_int ();
1553
1554     /* see if it exists in the session, we're done if it doesn't */
1555     if (g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
1556             GINT_TO_POINTER (ssrc)) == NULL)
1557       break;
1558   }
1559   return ssrc;
1560 }
1561
1562
1563 /**
1564  * rtp_session_create_source:
1565  * @sess: an #RTPSession
1566  *
1567  * Create an #RTPSource for use in @sess. This function will create a source
1568  * with an ssrc that is currently not used by any participants in the session.
1569  *
1570  * Returns: an #RTPSource.
1571  */
1572 RTPSource *
1573 rtp_session_create_source (RTPSession * sess)
1574 {
1575   guint32 ssrc;
1576   RTPSource *source;
1577
1578   RTP_SESSION_LOCK (sess);
1579   ssrc = rtp_session_create_new_ssrc (sess);
1580   source = rtp_source_new (ssrc);
1581   rtp_source_set_callbacks (source, &callbacks, sess);
1582   /* we need an additional ref for the source in the hashtable */
1583   g_object_ref (source);
1584   g_hash_table_insert (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc),
1585       source);
1586   /* we have one more source now */
1587   sess->total_sources++;
1588   RTP_SESSION_UNLOCK (sess);
1589
1590   return source;
1591 }
1592
1593 /* update the RTPArrivalStats structure with the current time and other bits
1594  * about the current buffer we are handling.
1595  * This function is typically called when a validated packet is received.
1596  * This function should be called with the SESSION_LOCK
1597  */
1598 static void
1599 update_arrival_stats (RTPSession * sess, RTPArrivalStats * arrival,
1600     gboolean rtp, GstBuffer * buffer, GstClockTime current_time,
1601     GstClockTime running_time, guint64 ntpnstime)
1602 {
1603   /* get time of arrival */
1604   arrival->current_time = current_time;
1605   arrival->running_time = running_time;
1606   arrival->ntpnstime = ntpnstime;
1607
1608   /* get packet size including header overhead */
1609   arrival->bytes = GST_BUFFER_SIZE (buffer) + sess->header_len;
1610
1611   if (rtp) {
1612     arrival->payload_len = gst_rtp_buffer_get_payload_len (buffer);
1613   } else {
1614     arrival->payload_len = 0;
1615   }
1616
1617   /* for netbuffer we can store the IP address to check for collisions */
1618   arrival->have_address = GST_IS_NETBUFFER (buffer);
1619   if (arrival->have_address) {
1620     GstNetBuffer *netbuf = (GstNetBuffer *) buffer;
1621
1622     memcpy (&arrival->address, &netbuf->from, sizeof (GstNetAddress));
1623   }
1624 }
1625
1626 /**
1627  * rtp_session_process_rtp:
1628  * @sess: and #RTPSession
1629  * @buffer: an RTP buffer
1630  * @current_time: the current system time
1631  * @running_time: the running_time of @buffer
1632  *
1633  * Process an RTP buffer in the session manager. This function takes ownership
1634  * of @buffer.
1635  *
1636  * Returns: a #GstFlowReturn.
1637  */
1638 GstFlowReturn
1639 rtp_session_process_rtp (RTPSession * sess, GstBuffer * buffer,
1640     GstClockTime current_time, GstClockTime running_time)
1641 {
1642   GstFlowReturn result;
1643   guint32 ssrc;
1644   RTPSource *source;
1645   gboolean created;
1646   gboolean prevsender, prevactive;
1647   RTPArrivalStats arrival;
1648   guint32 csrcs[16];
1649   guint8 i, count;
1650   guint64 oldrate;
1651
1652   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
1653   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
1654
1655   if (!gst_rtp_buffer_validate (buffer))
1656     goto invalid_packet;
1657
1658   RTP_SESSION_LOCK (sess);
1659   /* update arrival stats */
1660   update_arrival_stats (sess, &arrival, TRUE, buffer, current_time,
1661       running_time, -1);
1662
1663   /* ignore more RTP packets when we left the session */
1664   if (sess->source->received_bye)
1665     goto ignore;
1666
1667   /* get SSRC and look up in session database */
1668   ssrc = gst_rtp_buffer_get_ssrc (buffer);
1669   source = obtain_source (sess, ssrc, &created, &arrival, TRUE);
1670   if (!source)
1671     goto collision;
1672
1673   prevsender = RTP_SOURCE_IS_SENDER (source);
1674   prevactive = RTP_SOURCE_IS_ACTIVE (source);
1675   oldrate = source->bitrate;
1676
1677   /* copy available csrc for later */
1678   count = gst_rtp_buffer_get_csrc_count (buffer);
1679   /* make sure to not overflow our array. An RTP buffer can maximally contain
1680    * 16 CSRCs */
1681   count = MIN (count, 16);
1682
1683   for (i = 0; i < count; i++)
1684     csrcs[i] = gst_rtp_buffer_get_csrc (buffer, i);
1685
1686   /* let source process the packet */
1687   result = rtp_source_process_rtp (source, buffer, &arrival);
1688
1689   /* source became active */
1690   if (prevactive != RTP_SOURCE_IS_ACTIVE (source)) {
1691     sess->stats.active_sources++;
1692     GST_DEBUG ("source: %08x became active, %d active sources", ssrc,
1693         sess->stats.active_sources);
1694     on_ssrc_validated (sess, source);
1695   }
1696   if (prevsender != RTP_SOURCE_IS_SENDER (source)) {
1697     sess->stats.sender_sources++;
1698     GST_DEBUG ("source: %08x became sender, %d sender sources", ssrc,
1699         sess->stats.sender_sources);
1700   }
1701   if (oldrate != source->bitrate)
1702     sess->recalc_bandwidth = TRUE;
1703
1704   if (created)
1705     on_new_ssrc (sess, source);
1706
1707   if (source->validated) {
1708     gboolean created;
1709
1710     /* for validated sources, we add the CSRCs as well */
1711     for (i = 0; i < count; i++) {
1712       guint32 csrc;
1713       RTPSource *csrc_src;
1714
1715       csrc = csrcs[i];
1716
1717       /* get source */
1718       csrc_src = obtain_source (sess, csrc, &created, &arrival, TRUE);
1719       if (!csrc_src)
1720         continue;
1721
1722       if (created) {
1723         GST_DEBUG ("created new CSRC: %08x", csrc);
1724         rtp_source_set_as_csrc (csrc_src);
1725         if (RTP_SOURCE_IS_ACTIVE (csrc_src))
1726           sess->stats.active_sources++;
1727         on_new_ssrc (sess, csrc_src);
1728       }
1729       g_object_unref (csrc_src);
1730     }
1731   }
1732   g_object_unref (source);
1733
1734   RTP_SESSION_UNLOCK (sess);
1735
1736   return result;
1737
1738   /* ERRORS */
1739 invalid_packet:
1740   {
1741     gst_buffer_unref (buffer);
1742     GST_DEBUG ("invalid RTP packet received");
1743     return GST_FLOW_OK;
1744   }
1745 ignore:
1746   {
1747     gst_buffer_unref (buffer);
1748     RTP_SESSION_UNLOCK (sess);
1749     GST_DEBUG ("ignoring RTP packet because we are leaving");
1750     return GST_FLOW_OK;
1751   }
1752 collision:
1753   {
1754     gst_buffer_unref (buffer);
1755     RTP_SESSION_UNLOCK (sess);
1756     GST_DEBUG ("ignoring packet because its collisioning");
1757     return GST_FLOW_OK;
1758   }
1759 }
1760
1761 static void
1762 rtp_session_process_rb (RTPSession * sess, RTPSource * source,
1763     GstRTCPPacket * packet, RTPArrivalStats * arrival)
1764 {
1765   guint count, i;
1766
1767   count = gst_rtcp_packet_get_rb_count (packet);
1768   for (i = 0; i < count; i++) {
1769     guint32 ssrc, exthighestseq, jitter, lsr, dlsr;
1770     guint8 fractionlost;
1771     gint32 packetslost;
1772
1773     gst_rtcp_packet_get_rb (packet, i, &ssrc, &fractionlost,
1774         &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
1775
1776     GST_DEBUG ("RB %d: SSRC %08x, jitter %" G_GUINT32_FORMAT, i, ssrc, jitter);
1777
1778     if (ssrc == sess->source->ssrc) {
1779       /* only deal with report blocks for our session, we update the stats of
1780        * the sender of the RTCP message. We could also compare our stats against
1781        * the other sender to see if we are better or worse. */
1782       rtp_source_process_rb (source, arrival->ntpnstime, fractionlost,
1783           packetslost, exthighestseq, jitter, lsr, dlsr);
1784     }
1785   }
1786   on_ssrc_active (sess, source);
1787 }
1788
1789 /* A Sender report contains statistics about how the sender is doing. This
1790  * includes timing informataion such as the relation between RTP and NTP
1791  * timestamps and the number of packets/bytes it sent to us.
1792  *
1793  * In this report is also included a set of report blocks related to how this
1794  * sender is receiving data (in case we (or somebody else) is also sending stuff
1795  * to it). This info includes the packet loss, jitter and seqnum. It also
1796  * contains information to calculate the round trip time (LSR/DLSR).
1797  */
1798 static void
1799 rtp_session_process_sr (RTPSession * sess, GstRTCPPacket * packet,
1800     RTPArrivalStats * arrival, gboolean * do_sync)
1801 {
1802   guint32 senderssrc, rtptime, packet_count, octet_count;
1803   guint64 ntptime;
1804   RTPSource *source;
1805   gboolean created, prevsender;
1806
1807   gst_rtcp_packet_sr_get_sender_info (packet, &senderssrc, &ntptime, &rtptime,
1808       &packet_count, &octet_count);
1809
1810   GST_DEBUG ("got SR packet: SSRC %08x, time %" GST_TIME_FORMAT,
1811       senderssrc, GST_TIME_ARGS (arrival->current_time));
1812
1813   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1814   if (!source)
1815     return;
1816
1817   /* don't try to do lip-sync for sources that sent a BYE */
1818   if (rtp_source_received_bye (source))
1819     *do_sync = FALSE;
1820   else
1821     *do_sync = TRUE;
1822
1823   prevsender = RTP_SOURCE_IS_SENDER (source);
1824
1825   /* first update the source */
1826   rtp_source_process_sr (source, arrival->current_time, ntptime, rtptime,
1827       packet_count, octet_count);
1828
1829   if (prevsender != RTP_SOURCE_IS_SENDER (source)) {
1830     sess->stats.sender_sources++;
1831     GST_DEBUG ("source: %08x became sender, %d sender sources", senderssrc,
1832         sess->stats.sender_sources);
1833   }
1834
1835   if (created)
1836     on_new_ssrc (sess, source);
1837
1838   rtp_session_process_rb (sess, source, packet, arrival);
1839   g_object_unref (source);
1840 }
1841
1842 /* A receiver report contains statistics about how a receiver is doing. It
1843  * includes stuff like packet loss, jitter and the seqnum it received last. It
1844  * also contains info to calculate the round trip time.
1845  *
1846  * We are only interested in how the sender of this report is doing wrt to us.
1847  */
1848 static void
1849 rtp_session_process_rr (RTPSession * sess, GstRTCPPacket * packet,
1850     RTPArrivalStats * arrival)
1851 {
1852   guint32 senderssrc;
1853   RTPSource *source;
1854   gboolean created;
1855
1856   senderssrc = gst_rtcp_packet_rr_get_ssrc (packet);
1857
1858   GST_DEBUG ("got RR packet: SSRC %08x", senderssrc);
1859
1860   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1861   if (!source)
1862     return;
1863
1864   if (created)
1865     on_new_ssrc (sess, source);
1866
1867   rtp_session_process_rb (sess, source, packet, arrival);
1868   g_object_unref (source);
1869 }
1870
1871 /* Get SDES items and store them in the SSRC */
1872 static void
1873 rtp_session_process_sdes (RTPSession * sess, GstRTCPPacket * packet,
1874     RTPArrivalStats * arrival)
1875 {
1876   guint items, i, j;
1877   gboolean more_items, more_entries;
1878
1879   items = gst_rtcp_packet_sdes_get_item_count (packet);
1880   GST_DEBUG ("got SDES packet with %d items", items);
1881
1882   more_items = gst_rtcp_packet_sdes_first_item (packet);
1883   i = 0;
1884   while (more_items) {
1885     guint32 ssrc;
1886     gboolean changed, created, validated;
1887     RTPSource *source;
1888     GstStructure *sdes;
1889
1890     ssrc = gst_rtcp_packet_sdes_get_ssrc (packet);
1891
1892     GST_DEBUG ("item %d, SSRC %08x", i, ssrc);
1893
1894     changed = FALSE;
1895
1896     /* find src, no probation when dealing with RTCP */
1897     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1898     if (!source)
1899       return;
1900
1901     sdes = gst_structure_new ("application/x-rtp-source-sdes", NULL);
1902
1903     more_entries = gst_rtcp_packet_sdes_first_entry (packet);
1904     j = 0;
1905     while (more_entries) {
1906       GstRTCPSDESType type;
1907       guint8 len;
1908       guint8 *data;
1909       gchar *name;
1910       gchar *value;
1911
1912       gst_rtcp_packet_sdes_get_entry (packet, &type, &len, &data);
1913
1914       GST_DEBUG ("entry %d, type %d, len %d, data %.*s", j, type, len, len,
1915           data);
1916
1917       if (type == GST_RTCP_SDES_PRIV) {
1918         name = g_strndup ((const gchar *) &data[1], data[0]);
1919         len -= data[0] + 1;
1920         data += data[0] + 1;
1921       } else {
1922         name = g_strdup (gst_rtcp_sdes_type_to_name (type));
1923       }
1924
1925       value = g_strndup ((const gchar *) data, len);
1926
1927       gst_structure_set (sdes, name, G_TYPE_STRING, value, NULL);
1928
1929       g_free (name);
1930       g_free (value);
1931
1932       more_entries = gst_rtcp_packet_sdes_next_entry (packet);
1933       j++;
1934     }
1935
1936     /* takes ownership of sdes */
1937     changed = rtp_source_set_sdes_struct (source, sdes);
1938
1939     validated = !RTP_SOURCE_IS_ACTIVE (source);
1940     source->validated = TRUE;
1941
1942     if (created)
1943       on_new_ssrc (sess, source);
1944     if (validated)
1945       on_ssrc_validated (sess, source);
1946     if (changed)
1947       on_ssrc_sdes (sess, source);
1948
1949     g_object_unref (source);
1950
1951     more_items = gst_rtcp_packet_sdes_next_item (packet);
1952     i++;
1953   }
1954 }
1955
1956 /* BYE is sent when a client leaves the session
1957  */
1958 static void
1959 rtp_session_process_bye (RTPSession * sess, GstRTCPPacket * packet,
1960     RTPArrivalStats * arrival)
1961 {
1962   guint count, i;
1963   gchar *reason;
1964   gboolean reconsider = FALSE;
1965
1966   reason = gst_rtcp_packet_bye_get_reason (packet);
1967   GST_DEBUG ("got BYE packet (reason: %s)", GST_STR_NULL (reason));
1968
1969   count = gst_rtcp_packet_bye_get_ssrc_count (packet);
1970   for (i = 0; i < count; i++) {
1971     guint32 ssrc;
1972     RTPSource *source;
1973     gboolean created, prevactive, prevsender;
1974     guint pmembers, members;
1975
1976     ssrc = gst_rtcp_packet_bye_get_nth_ssrc (packet, i);
1977     GST_DEBUG ("SSRC: %08x", ssrc);
1978
1979     /* find src and mark bye, no probation when dealing with RTCP */
1980     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1981     if (!source)
1982       return;
1983
1984     /* store time for when we need to time out this source */
1985     source->bye_time = arrival->current_time;
1986
1987     prevactive = RTP_SOURCE_IS_ACTIVE (source);
1988     prevsender = RTP_SOURCE_IS_SENDER (source);
1989
1990     /* let the source handle the rest */
1991     rtp_source_process_bye (source, reason);
1992
1993     pmembers = sess->stats.active_sources;
1994
1995     if (prevactive && !RTP_SOURCE_IS_ACTIVE (source)) {
1996       sess->stats.active_sources--;
1997       GST_DEBUG ("source: %08x became inactive, %d active sources", ssrc,
1998           sess->stats.active_sources);
1999     }
2000     if (prevsender && !RTP_SOURCE_IS_SENDER (source)) {
2001       sess->stats.sender_sources--;
2002       GST_DEBUG ("source: %08x became non sender, %d sender sources", ssrc,
2003           sess->stats.sender_sources);
2004     }
2005     members = sess->stats.active_sources;
2006
2007     if (!sess->source->received_bye && members < pmembers) {
2008       /* some members went away since the previous timeout estimate.
2009        * Perform reverse reconsideration but only when we are not scheduling a
2010        * BYE ourselves. */
2011       if (arrival->current_time < sess->next_rtcp_check_time) {
2012         GstClockTime time_remaining;
2013
2014         time_remaining = sess->next_rtcp_check_time - arrival->current_time;
2015         sess->next_rtcp_check_time =
2016             gst_util_uint64_scale (time_remaining, members, pmembers);
2017
2018         GST_DEBUG ("reverse reconsideration %" GST_TIME_FORMAT,
2019             GST_TIME_ARGS (sess->next_rtcp_check_time));
2020
2021         sess->next_rtcp_check_time += arrival->current_time;
2022
2023         /* mark pending reconsider. We only want to signal the reconsideration
2024          * once after we handled all the source in the bye packet */
2025         reconsider = TRUE;
2026       }
2027     }
2028
2029     if (created)
2030       on_new_ssrc (sess, source);
2031
2032     on_bye_ssrc (sess, source);
2033
2034     g_object_unref (source);
2035   }
2036   if (reconsider) {
2037     RTP_SESSION_UNLOCK (sess);
2038     /* notify app of reconsideration */
2039     if (sess->callbacks.reconsider)
2040       sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2041     RTP_SESSION_LOCK (sess);
2042   }
2043   g_free (reason);
2044 }
2045
2046 static void
2047 rtp_session_process_app (RTPSession * sess, GstRTCPPacket * packet,
2048     RTPArrivalStats * arrival)
2049 {
2050   GST_DEBUG ("received APP");
2051 }
2052
2053 static void
2054 rtp_session_process_pli (RTPSession * sess, guint32 sender_ssrc,
2055     guint32 media_ssrc, GstClockTime current_time)
2056 {
2057   RTPSource *src;
2058   guint32 round_trip = 0;
2059
2060   if (!sess->callbacks.request_key_unit)
2061     return;
2062
2063   src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2064       GINT_TO_POINTER (sender_ssrc));
2065
2066   if (!src)
2067     return;
2068
2069   if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2070       rtp_source_get_last_rb (src, NULL, NULL, NULL, NULL, NULL, NULL,
2071           &round_trip)) {
2072     GstClockTime round_trip_in_ns = gst_util_uint64_scale (round_trip,
2073         GST_SECOND, 65536);
2074
2075     if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2076         current_time - sess->last_keyframe_request < round_trip_in_ns) {
2077       GST_DEBUG ("Ignoring PLI because one was send without one RTT (%"
2078           GST_TIME_FORMAT " < %" GST_TIME_FORMAT ")",
2079           GST_TIME_ARGS (current_time - sess->last_keyframe_request),
2080           GST_TIME_ARGS (round_trip_in_ns));;
2081       return;
2082     }
2083   }
2084
2085   sess->last_keyframe_request = current_time;
2086
2087   GST_LOG ("received PLI from %X %p(%p)", sender_ssrc,
2088       sess->callbacks.process_rtp, sess->callbacks.request_key_unit);
2089
2090   sess->callbacks.request_key_unit (sess, FALSE,
2091       sess->request_key_unit_user_data);
2092 }
2093
2094 static void
2095 rtp_session_process_feedback (RTPSession * sess, GstRTCPPacket * packet,
2096     RTPArrivalStats * arrival, GstClockTime current_time)
2097 {
2098   GstRTCPType type = gst_rtcp_packet_get_type (packet);
2099   GstRTCPFBType fbtype = gst_rtcp_packet_fb_get_type (packet);
2100   guint32 sender_ssrc = gst_rtcp_packet_fb_get_sender_ssrc (packet);
2101   guint32 media_ssrc = gst_rtcp_packet_fb_get_media_ssrc (packet);
2102   guint length = 4 * (gst_rtcp_packet_get_length (packet) - 2);
2103
2104   GST_DEBUG ("received feedback %d:%d from %08X about %08X"
2105       " with FCI of length %d", type, fbtype, sender_ssrc, media_ssrc, length);
2106
2107   if (g_signal_has_handler_pending (sess,
2108           rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0, TRUE)) {
2109     GstBuffer *fci = NULL;
2110
2111     if (length) {
2112       fci = gst_buffer_create_sub (packet->buffer, packet->offset + 72, length);
2113       GST_BUFFER_TIMESTAMP (fci) = arrival->running_time;
2114     }
2115
2116     RTP_SESSION_UNLOCK (sess);
2117     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0,
2118         type, fbtype, sender_ssrc, media_ssrc, fci);
2119     RTP_SESSION_LOCK (sess);
2120
2121     if (fci)
2122       gst_buffer_unref (fci);
2123   }
2124
2125   if (sess->rtcp_feedback_retention_window) {
2126     RTPSource *src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2127         GINT_TO_POINTER (media_ssrc));
2128
2129     if (src)
2130       rtp_source_retain_rtcp_packet (src, packet, arrival->running_time);
2131   }
2132
2133   if (rtp_source_get_ssrc (sess->source) == media_ssrc) {
2134     switch (type) {
2135       case GST_RTCP_TYPE_PSFB:
2136         switch (fbtype) {
2137           case GST_RTCP_PSFB_TYPE_PLI:
2138             rtp_session_process_pli (sess, sender_ssrc, media_ssrc,
2139                 current_time);
2140             break;
2141           default:
2142             break;
2143         }
2144         break;
2145       case GST_RTCP_TYPE_RTPFB:
2146       default:
2147         break;
2148     }
2149   }
2150 }
2151
2152 /**
2153  * rtp_session_process_rtcp:
2154  * @sess: and #RTPSession
2155  * @buffer: an RTCP buffer
2156  * @current_time: the current system time
2157  * @ntpnstime: the current NTP time in nanoseconds
2158  *
2159  * Process an RTCP buffer in the session manager. This function takes ownership
2160  * of @buffer.
2161  *
2162  * Returns: a #GstFlowReturn.
2163  */
2164 GstFlowReturn
2165 rtp_session_process_rtcp (RTPSession * sess, GstBuffer * buffer,
2166     GstClockTime current_time, guint64 ntpnstime)
2167 {
2168   GstRTCPPacket packet;
2169   gboolean more, is_bye = FALSE, do_sync = FALSE;
2170   RTPArrivalStats arrival;
2171   GstFlowReturn result = GST_FLOW_OK;
2172
2173   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2174   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
2175
2176   if (!gst_rtcp_buffer_validate (buffer))
2177     goto invalid_packet;
2178
2179   GST_DEBUG ("received RTCP packet");
2180
2181   RTP_SESSION_LOCK (sess);
2182   /* update arrival stats */
2183   update_arrival_stats (sess, &arrival, FALSE, buffer, current_time, -1,
2184       ntpnstime);
2185
2186   if (sess->sent_bye)
2187     goto ignore;
2188
2189   /* start processing the compound packet */
2190   more = gst_rtcp_buffer_get_first_packet (buffer, &packet);
2191   while (more) {
2192     GstRTCPType type;
2193
2194     type = gst_rtcp_packet_get_type (&packet);
2195
2196     /* when we are leaving the session, we should ignore all non-BYE messages */
2197     if (sess->source->received_bye && type != GST_RTCP_TYPE_BYE) {
2198       GST_DEBUG ("ignoring non-BYE RTCP packet because we are leaving");
2199       goto next;
2200     }
2201
2202     switch (type) {
2203       case GST_RTCP_TYPE_SR:
2204         rtp_session_process_sr (sess, &packet, &arrival, &do_sync);
2205         break;
2206       case GST_RTCP_TYPE_RR:
2207         rtp_session_process_rr (sess, &packet, &arrival);
2208         break;
2209       case GST_RTCP_TYPE_SDES:
2210         rtp_session_process_sdes (sess, &packet, &arrival);
2211         break;
2212       case GST_RTCP_TYPE_BYE:
2213         is_bye = TRUE;
2214         /* don't try to attempt lip-sync anymore for streams with a BYE */
2215         do_sync = FALSE;
2216         rtp_session_process_bye (sess, &packet, &arrival);
2217         break;
2218       case GST_RTCP_TYPE_APP:
2219         rtp_session_process_app (sess, &packet, &arrival);
2220         break;
2221       case GST_RTCP_TYPE_RTPFB:
2222       case GST_RTCP_TYPE_PSFB:
2223         rtp_session_process_feedback (sess, &packet, &arrival, current_time);
2224         break;
2225       default:
2226         GST_WARNING ("got unknown RTCP packet");
2227         break;
2228     }
2229   next:
2230     more = gst_rtcp_packet_move_to_next (&packet);
2231   }
2232
2233   /* if we are scheduling a BYE, we only want to count bye packets, else we
2234    * count everything */
2235   if (sess->source->received_bye) {
2236     if (is_bye) {
2237       sess->stats.bye_members++;
2238       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2239     }
2240   } else {
2241     /* keep track of average packet size */
2242     UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2243   }
2244   GST_DEBUG ("%p, received RTCP packet, avg size %u, %u", &sess->stats,
2245       sess->stats.avg_rtcp_packet_size, arrival.bytes);
2246   RTP_SESSION_UNLOCK (sess);
2247
2248   /* notify caller of sr packets in the callback */
2249   if (do_sync && sess->callbacks.sync_rtcp) {
2250     /* make writable, we might want to change the buffer */
2251     buffer = gst_buffer_make_metadata_writable (buffer);
2252
2253     result = sess->callbacks.sync_rtcp (sess, sess->source, buffer,
2254         sess->sync_rtcp_user_data);
2255   } else
2256     gst_buffer_unref (buffer);
2257
2258   return result;
2259
2260   /* ERRORS */
2261 invalid_packet:
2262   {
2263     GST_DEBUG ("invalid RTCP packet received");
2264     gst_buffer_unref (buffer);
2265     return GST_FLOW_OK;
2266   }
2267 ignore:
2268   {
2269     gst_buffer_unref (buffer);
2270     RTP_SESSION_UNLOCK (sess);
2271     GST_DEBUG ("ignoring RTP packet because we left");
2272     return GST_FLOW_OK;
2273   }
2274 }
2275
2276 /**
2277  * rtp_session_send_rtp:
2278  * @sess: an #RTPSession
2279  * @data: pointer to either an RTP buffer or a list of RTP buffers
2280  * @is_list: TRUE when @data is a buffer list
2281  * @current_time: the current system time
2282  * @running_time: the running time of @data
2283  *
2284  * Send the RTP buffer in the session manager. This function takes ownership of
2285  * @buffer.
2286  *
2287  * Returns: a #GstFlowReturn.
2288  */
2289 GstFlowReturn
2290 rtp_session_send_rtp (RTPSession * sess, gpointer data, gboolean is_list,
2291     GstClockTime current_time, GstClockTime running_time)
2292 {
2293   GstFlowReturn result;
2294   RTPSource *source;
2295   gboolean prevsender;
2296   gboolean valid_packet;
2297   guint64 oldrate;
2298
2299   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2300   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
2301
2302   if (is_list) {
2303     valid_packet = gst_rtp_buffer_list_validate (GST_BUFFER_LIST_CAST (data));
2304   } else {
2305     valid_packet = gst_rtp_buffer_validate (GST_BUFFER_CAST (data));
2306   }
2307
2308   if (!valid_packet)
2309     goto invalid_packet;
2310
2311   GST_LOG ("received RTP %s for sending", is_list ? "list" : "packet");
2312
2313   RTP_SESSION_LOCK (sess);
2314   source = sess->source;
2315
2316   /* update last activity */
2317   source->last_rtp_activity = current_time;
2318
2319   prevsender = RTP_SOURCE_IS_SENDER (source);
2320   oldrate = source->bitrate;
2321
2322   /* we use our own source to send */
2323   result = rtp_source_send_rtp (source, data, is_list, running_time);
2324
2325   if (RTP_SOURCE_IS_SENDER (source) && !prevsender)
2326     sess->stats.sender_sources++;
2327   if (oldrate != source->bitrate)
2328     sess->recalc_bandwidth = TRUE;
2329   RTP_SESSION_UNLOCK (sess);
2330
2331   return result;
2332
2333   /* ERRORS */
2334 invalid_packet:
2335   {
2336     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
2337     GST_DEBUG ("invalid RTP packet received");
2338     return GST_FLOW_OK;
2339   }
2340 }
2341
2342 static void
2343 add_bitrates (gpointer key, RTPSource * source, gdouble * bandwidth)
2344 {
2345   *bandwidth += source->bitrate;
2346 }
2347
2348 static GstClockTime
2349 calculate_rtcp_interval (RTPSession * sess, gboolean deterministic,
2350     gboolean first)
2351 {
2352   GstClockTime result;
2353
2354   /* recalculate bandwidth when it changed */
2355   if (sess->recalc_bandwidth) {
2356     gdouble bandwidth;
2357
2358     if (sess->bandwidth > 0)
2359       bandwidth = sess->bandwidth;
2360     else {
2361       /* If it is <= 0, then try to estimate the actual bandwidth */
2362       bandwidth = sess->source->bitrate;
2363
2364       g_hash_table_foreach (sess->cnames, (GHFunc) add_bitrates, &bandwidth);
2365       bandwidth /= 8.0;
2366     }
2367     if (bandwidth == 0)
2368       bandwidth = RTP_STATS_BANDWIDTH;
2369
2370     rtp_stats_set_bandwidths (&sess->stats, bandwidth,
2371         sess->rtcp_bandwidth, sess->rtcp_rs_bandwidth, sess->rtcp_rr_bandwidth);
2372
2373     sess->recalc_bandwidth = FALSE;
2374   }
2375
2376   if (sess->source->received_bye) {
2377     result = rtp_stats_calculate_bye_interval (&sess->stats);
2378   } else {
2379     result = rtp_stats_calculate_rtcp_interval (&sess->stats,
2380         RTP_SOURCE_IS_SENDER (sess->source), first);
2381   }
2382
2383   GST_DEBUG ("next deterministic interval: %" GST_TIME_FORMAT ", first %d",
2384       GST_TIME_ARGS (result), first);
2385
2386   if (!deterministic && result != GST_CLOCK_TIME_NONE)
2387     result = rtp_stats_add_rtcp_jitter (&sess->stats, result);
2388
2389   GST_DEBUG ("next interval: %" GST_TIME_FORMAT, GST_TIME_ARGS (result));
2390
2391   return result;
2392 }
2393
2394 /* Stop the current @sess and schedule a BYE message for the other members.
2395  * One must have the session lock to call this function
2396  */
2397 static GstFlowReturn
2398 rtp_session_schedule_bye_locked (RTPSession * sess, const gchar * reason,
2399     GstClockTime current_time)
2400 {
2401   GstFlowReturn result = GST_FLOW_OK;
2402   RTPSource *source;
2403   GstClockTime interval;
2404
2405   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2406
2407   source = sess->source;
2408
2409   /* ignore more BYEs */
2410   if (source->received_bye)
2411     goto done;
2412
2413   /* we have BYE now */
2414   source->received_bye = TRUE;
2415   /* at least one member wants to send a BYE */
2416   g_free (sess->bye_reason);
2417   sess->bye_reason = g_strdup (reason);
2418   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
2419   sess->stats.bye_members = 1;
2420   sess->first_rtcp = TRUE;
2421   sess->sent_bye = FALSE;
2422   sess->allow_early = TRUE;
2423
2424   /* reschedule transmission */
2425   sess->last_rtcp_send_time = current_time;
2426   interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2427   sess->next_rtcp_check_time = current_time + interval;
2428
2429   GST_DEBUG ("Schedule BYE for %" GST_TIME_FORMAT ", %" GST_TIME_FORMAT,
2430       GST_TIME_ARGS (interval), GST_TIME_ARGS (sess->next_rtcp_check_time));
2431
2432   RTP_SESSION_UNLOCK (sess);
2433   /* notify app of reconsideration */
2434   if (sess->callbacks.reconsider)
2435     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2436   RTP_SESSION_LOCK (sess);
2437 done:
2438
2439   return result;
2440 }
2441
2442 /**
2443  * rtp_session_schedule_bye:
2444  * @sess: an #RTPSession
2445  * @reason: a reason or NULL
2446  * @current_time: the current system time
2447  *
2448  * Stop the current @sess and schedule a BYE message for the other members.
2449  *
2450  * Returns: a #GstFlowReturn.
2451  */
2452 GstFlowReturn
2453 rtp_session_schedule_bye (RTPSession * sess, const gchar * reason,
2454     GstClockTime current_time)
2455 {
2456   GstFlowReturn result = GST_FLOW_OK;
2457
2458   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2459
2460   RTP_SESSION_LOCK (sess);
2461   result = rtp_session_schedule_bye_locked (sess, reason, current_time);
2462   RTP_SESSION_UNLOCK (sess);
2463
2464   return result;
2465 }
2466
2467 /**
2468  * rtp_session_next_timeout:
2469  * @sess: an #RTPSession
2470  * @current_time: the current system time
2471  *
2472  * Get the next time we should perform session maintenance tasks.
2473  *
2474  * Returns: a time when rtp_session_on_timeout() should be called with the
2475  * current system time.
2476  */
2477 GstClockTime
2478 rtp_session_next_timeout (RTPSession * sess, GstClockTime current_time)
2479 {
2480   GstClockTime result, interval = 0;
2481
2482   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_CLOCK_TIME_NONE);
2483
2484   RTP_SESSION_LOCK (sess);
2485
2486   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
2487     result = sess->next_early_rtcp_time;
2488     goto early_exit;
2489   }
2490
2491   result = sess->next_rtcp_check_time;
2492
2493   GST_DEBUG ("current time: %" GST_TIME_FORMAT ", next :%" GST_TIME_FORMAT,
2494       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2495
2496   if (result < current_time) {
2497     GST_DEBUG ("take current time as base");
2498     /* our previous check time expired, start counting from the current time
2499      * again. */
2500     result = current_time;
2501   }
2502
2503   if (sess->source->received_bye) {
2504     if (sess->sent_bye) {
2505       GST_DEBUG ("we sent BYE already");
2506       interval = GST_CLOCK_TIME_NONE;
2507     } else if (sess->stats.active_sources >= 50) {
2508       GST_DEBUG ("reconsider BYE, more than 50 sources");
2509       /* reconsider BYE if members >= 50 */
2510       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2511     }
2512   } else {
2513     if (sess->first_rtcp) {
2514       GST_DEBUG ("first RTCP packet");
2515       /* we are called for the first time */
2516       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2517     } else if (sess->next_rtcp_check_time < current_time) {
2518       GST_DEBUG ("old check time expired, getting new timeout");
2519       /* get a new timeout when we need to */
2520       interval = calculate_rtcp_interval (sess, FALSE, FALSE);
2521     }
2522   }
2523
2524   if (interval != GST_CLOCK_TIME_NONE)
2525     result += interval;
2526   else
2527     result = GST_CLOCK_TIME_NONE;
2528
2529   sess->next_rtcp_check_time = result;
2530
2531 early_exit:
2532
2533   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2534       ", next time: %" GST_TIME_FORMAT,
2535       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2536   RTP_SESSION_UNLOCK (sess);
2537
2538   return result;
2539 }
2540
2541 typedef struct
2542 {
2543   RTPSession *sess;
2544   GstBuffer *rtcp;
2545   GstClockTime current_time;
2546   guint64 ntpnstime;
2547   GstClockTime running_time;
2548   GstClockTime interval;
2549   GstRTCPPacket packet;
2550   gboolean is_bye;
2551   gboolean has_sdes;
2552   gboolean is_early;
2553   gboolean may_suppress;
2554 } ReportData;
2555
2556 static void
2557 session_start_rtcp (RTPSession * sess, ReportData * data)
2558 {
2559   GstRTCPPacket *packet = &data->packet;
2560   RTPSource *own = sess->source;
2561
2562   data->rtcp = gst_rtcp_buffer_new (sess->mtu);
2563
2564   if (RTP_SOURCE_IS_SENDER (own)) {
2565     guint64 ntptime;
2566     guint32 rtptime;
2567     guint32 packet_count, octet_count;
2568
2569     /* we are a sender, create SR */
2570     GST_DEBUG ("create SR for SSRC %08x", own->ssrc);
2571     gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_SR, packet);
2572
2573     /* get latest stats */
2574     rtp_source_get_new_sr (own, data->ntpnstime, data->running_time,
2575         &ntptime, &rtptime, &packet_count, &octet_count);
2576     /* store stats */
2577     rtp_source_process_sr (own, data->current_time, ntptime, rtptime,
2578         packet_count, octet_count);
2579
2580     /* fill in sender report info */
2581     gst_rtcp_packet_sr_set_sender_info (packet, own->ssrc,
2582         ntptime, rtptime, packet_count, octet_count);
2583   } else {
2584     /* we are only receiver, create RR */
2585     GST_DEBUG ("create RR for SSRC %08x", own->ssrc);
2586     gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_RR, packet);
2587     gst_rtcp_packet_rr_set_ssrc (packet, own->ssrc);
2588   }
2589 }
2590
2591 /* construct a Sender or Receiver Report */
2592 static void
2593 session_report_blocks (const gchar * key, RTPSource * source, ReportData * data)
2594 {
2595   RTPSession *sess = data->sess;
2596   GstRTCPPacket *packet = &data->packet;
2597
2598   /* create a new buffer if needed */
2599   if (data->rtcp == NULL) {
2600     session_start_rtcp (sess, data);
2601   } else if (data->is_early) {
2602     /* Put a single RR or SR in minimal compound packets */
2603     return;
2604   }
2605   if (gst_rtcp_packet_get_rb_count (packet) < GST_RTCP_MAX_RB_COUNT) {
2606     /* only report about other sender sources */
2607     if (source != sess->source && RTP_SOURCE_IS_SENDER (source)) {
2608       guint8 fractionlost;
2609       gint32 packetslost;
2610       guint32 exthighestseq, jitter;
2611       guint32 lsr, dlsr;
2612
2613       /* get new stats */
2614       rtp_source_get_new_rb (source, data->current_time, &fractionlost,
2615           &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
2616
2617       /* store last generated RR packet */
2618       source->last_rr.is_valid = TRUE;
2619       source->last_rr.fractionlost = fractionlost;
2620       source->last_rr.packetslost = packetslost;
2621       source->last_rr.exthighestseq = exthighestseq;
2622       source->last_rr.jitter = jitter;
2623       source->last_rr.lsr = lsr;
2624       source->last_rr.dlsr = dlsr;
2625
2626       /* packet is not yet filled, add report block for this source. */
2627       gst_rtcp_packet_add_rb (packet, source->ssrc, fractionlost, packetslost,
2628           exthighestseq, jitter, lsr, dlsr);
2629     }
2630   }
2631 }
2632
2633 /* perform cleanup of sources that timed out */
2634 static void
2635 session_cleanup (const gchar * key, RTPSource * source, ReportData * data)
2636 {
2637   gboolean remove = FALSE;
2638   gboolean byetimeout = FALSE;
2639   gboolean sendertimeout = FALSE;
2640   gboolean is_sender, is_active;
2641   RTPSession *sess = data->sess;
2642   GstClockTime interval;
2643
2644   is_sender = RTP_SOURCE_IS_SENDER (source);
2645   is_active = RTP_SOURCE_IS_ACTIVE (source);
2646
2647   /* check for our own source, we don't want to delete our own source. */
2648   if (!(source == sess->source)) {
2649     if (source->received_bye) {
2650       /* if we received a BYE from the source, remove the source after some
2651        * time. */
2652       if (data->current_time > source->bye_time &&
2653           data->current_time - source->bye_time > sess->stats.bye_timeout) {
2654         GST_DEBUG ("removing BYE source %08x", source->ssrc);
2655         remove = TRUE;
2656         byetimeout = TRUE;
2657       }
2658     }
2659     /* sources that were inactive for more than 5 times the deterministic reporting
2660      * interval get timed out. the min timeout is 5 seconds. */
2661     if (data->current_time > source->last_activity) {
2662       interval = MAX (data->interval * 5, 5 * GST_SECOND);
2663       if (data->current_time - source->last_activity > interval) {
2664         GST_DEBUG ("removing timeout source %08x, last %" GST_TIME_FORMAT,
2665             source->ssrc, GST_TIME_ARGS (source->last_activity));
2666         remove = TRUE;
2667       }
2668     }
2669   }
2670
2671   /* senders that did not send for a long time become a receiver, this also
2672    * holds for our own source. */
2673   if (is_sender) {
2674     if (data->current_time > source->last_rtp_activity) {
2675       interval = MAX (data->interval * 2, 5 * GST_SECOND);
2676       if (data->current_time - source->last_rtp_activity > interval) {
2677         GST_DEBUG ("sender source %08x timed out and became receiver, last %"
2678             GST_TIME_FORMAT, source->ssrc,
2679             GST_TIME_ARGS (source->last_rtp_activity));
2680         source->is_sender = FALSE;
2681         sess->stats.sender_sources--;
2682         sendertimeout = TRUE;
2683       }
2684     }
2685   }
2686
2687   if (remove) {
2688     sess->total_sources--;
2689     if (is_sender)
2690       sess->stats.sender_sources--;
2691     if (is_active)
2692       sess->stats.active_sources--;
2693
2694     if (byetimeout)
2695       on_bye_timeout (sess, source);
2696     else
2697       on_timeout (sess, source);
2698   } else {
2699     if (sendertimeout)
2700       on_sender_timeout (sess, source);
2701   }
2702
2703   source->closing = remove;
2704 }
2705
2706 static void
2707 session_sdes (RTPSession * sess, ReportData * data)
2708 {
2709   GstRTCPPacket *packet = &data->packet;
2710   const GstStructure *sdes;
2711   gint i, n_fields;
2712
2713   /* add SDES packet */
2714   gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_SDES, packet);
2715
2716   gst_rtcp_packet_sdes_add_item (packet, sess->source->ssrc);
2717
2718   sdes = rtp_source_get_sdes_struct (sess->source);
2719
2720   /* add all fields in the structure, the order is not important. */
2721   n_fields = gst_structure_n_fields (sdes);
2722   for (i = 0; i < n_fields; ++i) {
2723     const gchar *field;
2724     const gchar *value;
2725     GstRTCPSDESType type;
2726
2727     field = gst_structure_nth_field_name (sdes, i);
2728     if (field == NULL)
2729       continue;
2730     value = gst_structure_get_string (sdes, field);
2731     if (value == NULL)
2732       continue;
2733     type = gst_rtcp_sdes_name_to_type (field);
2734
2735     /* Early packets are minimal and only include the CNAME */
2736     if (data->is_early && type != GST_RTCP_SDES_CNAME)
2737       continue;
2738
2739     if (type > GST_RTCP_SDES_END && type < GST_RTCP_SDES_PRIV) {
2740       gst_rtcp_packet_sdes_add_entry (packet, type, strlen (value),
2741           (const guint8 *) value);
2742     } else if (type == GST_RTCP_SDES_PRIV) {
2743       gsize prefix_len;
2744       gsize value_len;
2745       gsize data_len;
2746       guint8 data[256];
2747
2748       /* don't accept entries that are too big */
2749       prefix_len = strlen (field);
2750       if (prefix_len > 255)
2751         continue;
2752       value_len = strlen (value);
2753       if (value_len > 255)
2754         continue;
2755       data_len = 1 + prefix_len + value_len;
2756       if (data_len > 255)
2757         continue;
2758
2759       data[0] = prefix_len;
2760       memcpy (&data[1], field, prefix_len);
2761       memcpy (&data[1 + prefix_len], value, value_len);
2762
2763       gst_rtcp_packet_sdes_add_entry (packet, type, data_len, data);
2764     }
2765   }
2766
2767   data->has_sdes = TRUE;
2768 }
2769
2770 /* schedule a BYE packet */
2771 static void
2772 session_bye (RTPSession * sess, ReportData * data)
2773 {
2774   GstRTCPPacket *packet = &data->packet;
2775
2776   /* open packet */
2777   session_start_rtcp (sess, data);
2778
2779   /* add SDES */
2780   session_sdes (sess, data);
2781
2782   /* add a BYE packet */
2783   gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_BYE, packet);
2784   gst_rtcp_packet_bye_add_ssrc (packet, sess->source->ssrc);
2785   if (sess->bye_reason)
2786     gst_rtcp_packet_bye_set_reason (packet, sess->bye_reason);
2787
2788   /* we have a BYE packet now */
2789   data->is_bye = TRUE;
2790 }
2791
2792 static gboolean
2793 is_rtcp_time (RTPSession * sess, GstClockTime current_time, ReportData * data)
2794 {
2795   GstClockTime new_send_time, elapsed;
2796
2797   if (data->is_early && sess->next_early_rtcp_time < current_time)
2798     goto early;
2799
2800   /* no need to check yet */
2801   if (sess->next_rtcp_check_time > current_time) {
2802     GST_DEBUG ("no check time yet, next %" GST_TIME_FORMAT " > now %"
2803         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_rtcp_check_time),
2804         GST_TIME_ARGS (current_time));
2805     return FALSE;
2806   }
2807
2808   /* get elapsed time since we last reported */
2809   elapsed = current_time - sess->last_rtcp_send_time;
2810
2811   /* perform forward reconsideration */
2812   new_send_time = rtp_stats_add_rtcp_jitter (&sess->stats, data->interval);
2813
2814   GST_DEBUG ("forward reconsideration %" GST_TIME_FORMAT ", elapsed %"
2815       GST_TIME_FORMAT, GST_TIME_ARGS (new_send_time), GST_TIME_ARGS (elapsed));
2816
2817   new_send_time += sess->last_rtcp_send_time;
2818
2819   /* check if reconsideration */
2820   if (current_time < new_send_time) {
2821     GST_DEBUG ("reconsider RTCP for %" GST_TIME_FORMAT,
2822         GST_TIME_ARGS (new_send_time));
2823     /* store new check time */
2824     sess->next_rtcp_check_time = new_send_time;
2825     return FALSE;
2826   }
2827
2828 early:
2829
2830   new_send_time = calculate_rtcp_interval (sess, FALSE, FALSE);
2831
2832   GST_DEBUG ("can send RTCP now, next interval %" GST_TIME_FORMAT,
2833       GST_TIME_ARGS (new_send_time));
2834   sess->next_rtcp_check_time = current_time + new_send_time;
2835
2836   /* Apply the rules from RFC 4585 section 3.5.3 */
2837   if (sess->stats.min_interval != 0 && !sess->first_rtcp) {
2838     GstClockTimeDiff T_rr_current_interval = g_random_double_range (0.5, 1.5) *
2839         sess->stats.min_interval;
2840
2841     /* This will caused the RTCP to be suppressed if no FB packets are added */
2842     if (sess->last_rtcp_send_time + T_rr_current_interval >
2843         sess->next_rtcp_check_time) {
2844       GST_DEBUG ("RTCP packet could be suppressed min: %" GST_TIME_FORMAT
2845           " last: %" GST_TIME_FORMAT
2846           " + T_rr_current_interval: %" GST_TIME_FORMAT
2847           " >  sess->next_rtcp_check_time: %" GST_TIME_FORMAT,
2848           GST_TIME_ARGS (sess->stats.min_interval),
2849           GST_TIME_ARGS (sess->last_rtcp_send_time),
2850           GST_TIME_ARGS (T_rr_current_interval),
2851           GST_TIME_ARGS (sess->next_rtcp_check_time));
2852       data->may_suppress = TRUE;
2853     }
2854   }
2855
2856   return TRUE;
2857 }
2858
2859 static void
2860 clone_ssrcs_hashtable (gchar * key, RTPSource * source, GHashTable * hash_table)
2861 {
2862   g_hash_table_insert (hash_table, key, g_object_ref (source));
2863 }
2864
2865 static gboolean
2866 remove_closing_sources (const gchar * key, RTPSource * source, gpointer * data)
2867 {
2868   return source->closing;
2869 }
2870
2871 /**
2872  * rtp_session_on_timeout:
2873  * @sess: an #RTPSession
2874  * @current_time: the current system time
2875  * @ntpnstime: the current NTP time in nanoseconds
2876  * @running_time: the current running_time of the pipeline
2877  *
2878  * Perform maintenance actions after the timeout obtained with
2879  * rtp_session_next_timeout() expired.
2880  *
2881  * This function will perform timeouts of receivers and senders, send a BYE
2882  * packet or generate RTCP packets with current session stats.
2883  *
2884  * This function can call the #RTPSessionSendRTCP callback, possibly multiple
2885  * times, for each packet that should be processed.
2886  *
2887  * Returns: a #GstFlowReturn.
2888  */
2889 GstFlowReturn
2890 rtp_session_on_timeout (RTPSession * sess, GstClockTime current_time,
2891     guint64 ntpnstime, GstClockTime running_time)
2892 {
2893   GstFlowReturn result = GST_FLOW_OK;
2894   ReportData data;
2895   RTPSource *own;
2896   GHashTable *table_copy;
2897   gboolean notify = FALSE;
2898
2899   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2900
2901   GST_DEBUG ("reporting at %" GST_TIME_FORMAT ", NTP time %" GST_TIME_FORMAT,
2902       GST_TIME_ARGS (current_time), GST_TIME_ARGS (ntpnstime));
2903
2904   data.sess = sess;
2905   data.rtcp = NULL;
2906   data.current_time = current_time;
2907   data.ntpnstime = ntpnstime;
2908   data.is_bye = FALSE;
2909   data.has_sdes = FALSE;
2910   data.may_suppress = FALSE;
2911   data.running_time = running_time;
2912
2913   own = sess->source;
2914
2915   RTP_SESSION_LOCK (sess);
2916   /* get a new interval, we need this for various cleanups etc */
2917   data.interval = calculate_rtcp_interval (sess, TRUE, sess->first_rtcp);
2918
2919   /* Make a local copy of the hashtable. We need to do this because the
2920    * cleanup stage below releases the session lock. */
2921   table_copy = g_hash_table_new_full (NULL, NULL, NULL,
2922       (GDestroyNotify) g_object_unref);
2923   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2924       (GHFunc) clone_ssrcs_hashtable, table_copy);
2925
2926   /* Clean up the session, mark the source for removing, this might release the
2927    * session lock. */
2928   g_hash_table_foreach (table_copy, (GHFunc) session_cleanup, &data);
2929   g_hash_table_destroy (table_copy);
2930
2931   /* Now remove the marked sources */
2932   g_hash_table_foreach_remove (sess->ssrcs[sess->mask_idx],
2933       (GHRFunc) remove_closing_sources, NULL);
2934
2935   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
2936     data.is_early = TRUE;
2937   else
2938     data.is_early = FALSE;
2939
2940   /* see if we need to generate SR or RR packets */
2941   if (is_rtcp_time (sess, current_time, &data)) {
2942     if (own->received_bye) {
2943       /* generate BYE instead */
2944       GST_DEBUG ("generating BYE message");
2945       session_bye (sess, &data);
2946       sess->sent_bye = TRUE;
2947     } else {
2948       /* loop over all known sources and do something */
2949       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2950           (GHFunc) session_report_blocks, &data);
2951     }
2952   }
2953
2954   if (data.rtcp) {
2955     /* we keep track of the last report time in order to timeout inactive
2956      * receivers or senders */
2957     if (!data.is_early && !data.may_suppress)
2958       sess->last_rtcp_send_time = data.current_time;
2959     sess->first_rtcp = FALSE;
2960     sess->next_early_rtcp_time = GST_CLOCK_TIME_NONE;
2961
2962     /* add SDES for this source when not already added */
2963     if (!data.has_sdes)
2964       session_sdes (sess, &data);
2965   }
2966
2967   /* check for outdated collisions */
2968   GST_DEBUG ("Timing out collisions");
2969   rtp_source_timeout (sess->source, current_time,
2970       data.interval * RTCP_INTERVAL_COLLISION_TIMEOUT,
2971       running_time - sess->rtcp_feedback_retention_window);
2972
2973   if (sess->change_ssrc) {
2974     GST_DEBUG ("need to change our SSRC (%08x)", own->ssrc);
2975     g_hash_table_steal (sess->ssrcs[sess->mask_idx],
2976         GINT_TO_POINTER (own->ssrc));
2977
2978     own->ssrc = rtp_session_create_new_ssrc (sess);
2979     rtp_source_reset (own);
2980
2981     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
2982         GINT_TO_POINTER (own->ssrc), own);
2983
2984     g_free (sess->bye_reason);
2985     sess->bye_reason = NULL;
2986     sess->sent_bye = FALSE;
2987     sess->change_ssrc = FALSE;
2988     notify = TRUE;
2989     GST_DEBUG ("changed our SSRC to %08x", own->ssrc);
2990   }
2991
2992   sess->allow_early = TRUE;
2993
2994   RTP_SESSION_UNLOCK (sess);
2995
2996   if (notify)
2997     g_object_notify (G_OBJECT (sess), "internal-ssrc");
2998
2999   /* push out the RTCP packet */
3000   if (data.rtcp) {
3001     gboolean do_not_suppress;
3002
3003     /* Give the user a change to add its own packet */
3004     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_RTCP], 0,
3005         data.rtcp, data.is_early, &do_not_suppress);
3006
3007     if (sess->callbacks.send_rtcp && (do_not_suppress || !data.may_suppress)) {
3008       guint packet_size;
3009
3010       /* close the RTCP packet */
3011       gst_rtcp_buffer_end (data.rtcp);
3012
3013       packet_size = GST_BUFFER_SIZE (data.rtcp) + sess->header_len;
3014
3015       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, packet_size);
3016       GST_DEBUG ("%p, sending RTCP packet, avg size %u, %u", &sess->stats,
3017           sess->stats.avg_rtcp_packet_size, packet_size);
3018       result =
3019           sess->callbacks.send_rtcp (sess, own, data.rtcp, sess->sent_bye,
3020           sess->send_rtcp_user_data);
3021     } else {
3022       GST_DEBUG ("freeing packet callback: %p"
3023           " do_not_suppress: %d may_suppress: %d",
3024           sess->callbacks.send_rtcp, do_not_suppress, data.may_suppress);
3025       gst_buffer_unref (data.rtcp);
3026     }
3027   }
3028
3029   return result;
3030 }
3031
3032 void
3033 rtp_session_request_early_rtcp (RTPSession * sess, GstClockTime current_time,
3034     GstClockTimeDiff max_delay)
3035 {
3036   GstClockTime T_dither_max;
3037
3038   /* Implements the algorithm described in RFC 4585 section 3.5.2 */
3039
3040   RTP_SESSION_LOCK (sess);
3041
3042   /* Check if already requested */
3043   /*  RFC 4585 section 3.5.2 step 2 */
3044   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3045     goto dont_send;
3046
3047   /* Ignore the request a scheduled packet will be in time anyway */
3048   if (current_time + max_delay > sess->next_rtcp_check_time)
3049     goto dont_send;
3050
3051   /*  RFC 4585 section 3.5.2 step 2b */
3052   /* If the total sources is <=2, then there is only us and one peer */
3053   if (sess->total_sources <= 2) {
3054     T_dither_max = 0;
3055   } else {
3056     /* Divide by 2 because l = 0.5 */
3057     T_dither_max = sess->next_rtcp_check_time - sess->last_rtcp_send_time;
3058     T_dither_max /= 2;
3059   }
3060
3061   /*  RFC 4585 section 3.5.2 step 3 */
3062   if (current_time + T_dither_max > sess->next_rtcp_check_time)
3063     goto dont_send;
3064
3065   /*  RFC 4585 section 3.5.2 step 4 */
3066   if (sess->allow_early == FALSE)
3067     goto dont_send;
3068
3069   if (T_dither_max) {
3070     /* Schedule an early transmission later */
3071     sess->next_early_rtcp_time = g_random_double () * T_dither_max +
3072         current_time;
3073   } else {
3074     /* If no dithering, schedule it for NOW */
3075     sess->next_early_rtcp_time = current_time;
3076   }
3077
3078   RTP_SESSION_UNLOCK (sess);
3079
3080   /* notify app of need to send packet early
3081    * and therefore of timeout change */
3082   if (sess->callbacks.reconsider)
3083     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
3084
3085   return;
3086
3087 dont_send:
3088
3089   RTP_SESSION_UNLOCK (sess);
3090
3091 }
3092
3093 void
3094 rtp_session_request_key_unit (RTPSession * sess, guint32 ssrc, gboolean fir)
3095 {
3096   guint i;
3097
3098   if (fir)
3099     return;
3100
3101   for (i = 0; i < sess->rtcp_pli_requests->len; i++)
3102     if (ssrc == g_array_index (sess->rtcp_pli_requests, guint32, i))
3103       return;
3104
3105   g_array_append_val (sess->rtcp_pli_requests, ssrc);
3106 }
3107
3108 static gboolean
3109 has_pli_compare_func (gconstpointer a, gconstpointer ignored)
3110 {
3111   GstRTCPPacket packet;
3112
3113   packet.buffer = (GstBuffer *) a;
3114   packet.offset = 0;
3115
3116   if (gst_rtcp_packet_get_type (&packet) == GST_RTCP_TYPE_PSFB &&
3117       gst_rtcp_packet_fb_get_type (&packet) == GST_RTCP_PSFB_TYPE_PLI)
3118     return TRUE;
3119   else
3120     return FALSE;
3121 }
3122
3123 static gboolean
3124 rtp_session_on_sending_rtcp (RTPSession * sess, GstBuffer * buffer,
3125     gboolean early)
3126 {
3127   gboolean ret = FALSE;
3128
3129   RTP_SESSION_LOCK (sess);
3130
3131   while (sess->rtcp_pli_requests->len) {
3132     GstRTCPPacket rtcppacket;
3133     guint media_ssrc = g_array_index (sess->rtcp_pli_requests, guint32, 0);
3134     RTPSource *media_src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
3135         GUINT_TO_POINTER (media_ssrc));
3136
3137     if (media_src && !rtp_source_has_retained (media_src,
3138             has_pli_compare_func, NULL)) {
3139       if (gst_rtcp_buffer_add_packet (buffer, GST_RTCP_TYPE_PSFB, &rtcppacket)) {
3140         gst_rtcp_packet_fb_set_type (&rtcppacket, GST_RTCP_PSFB_TYPE_PLI);
3141         gst_rtcp_packet_fb_set_sender_ssrc (&rtcppacket,
3142             rtp_source_get_ssrc (sess->source));
3143         gst_rtcp_packet_fb_set_media_ssrc (&rtcppacket, media_ssrc);
3144         ret = TRUE;
3145       } else {
3146         /* Break because the packet is full, will put next request in a
3147          * further packet
3148          */
3149         break;
3150       }
3151     }
3152
3153     g_array_remove_index (sess->rtcp_pli_requests, 0);
3154   }
3155
3156   RTP_SESSION_UNLOCK (sess);
3157
3158   return ret;
3159 }
3160
3161 static void
3162 rtp_session_send_rtcp (RTPSession * sess, GstClockTimeDiff max_delay)
3163 {
3164   GstClockTime now;
3165
3166   if (!sess->callbacks.send_rtcp)
3167     return;
3168
3169   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
3170
3171   rtp_session_request_early_rtcp (sess, now, max_delay);
3172 }