Merge branch 'master' into 0.11-fdo
[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   GstMetaNetAddress *meta;
1604
1605   /* get time of arrival */
1606   arrival->current_time = current_time;
1607   arrival->running_time = running_time;
1608   arrival->ntpnstime = ntpnstime;
1609
1610   /* get packet size including header overhead */
1611   arrival->bytes = GST_BUFFER_SIZE (buffer) + sess->header_len;
1612
1613   if (rtp) {
1614     arrival->payload_len = gst_rtp_buffer_get_payload_len (buffer);
1615   } else {
1616     arrival->payload_len = 0;
1617   }
1618
1619   /* for netbuffer we can store the IP address to check for collisions */
1620   meta = gst_buffer_get_meta_net_address (buffer);
1621   if (meta) {
1622     arrival->have_address = TRUE;
1623     memcpy (&arrival->address, &meta->naddr, sizeof (GstNetAddress));
1624   } else {
1625     arrival->have_address = FALSE;
1626   }
1627 }
1628
1629 /**
1630  * rtp_session_process_rtp:
1631  * @sess: and #RTPSession
1632  * @buffer: an RTP buffer
1633  * @current_time: the current system time
1634  * @running_time: the running_time of @buffer
1635  *
1636  * Process an RTP buffer in the session manager. This function takes ownership
1637  * of @buffer.
1638  *
1639  * Returns: a #GstFlowReturn.
1640  */
1641 GstFlowReturn
1642 rtp_session_process_rtp (RTPSession * sess, GstBuffer * buffer,
1643     GstClockTime current_time, GstClockTime running_time)
1644 {
1645   GstFlowReturn result;
1646   guint32 ssrc;
1647   RTPSource *source;
1648   gboolean created;
1649   gboolean prevsender, prevactive;
1650   RTPArrivalStats arrival;
1651   guint32 csrcs[16];
1652   guint8 i, count;
1653   guint64 oldrate;
1654
1655   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
1656   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
1657
1658   if (!gst_rtp_buffer_validate (buffer))
1659     goto invalid_packet;
1660
1661   RTP_SESSION_LOCK (sess);
1662   /* update arrival stats */
1663   update_arrival_stats (sess, &arrival, TRUE, buffer, current_time,
1664       running_time, -1);
1665
1666   /* ignore more RTP packets when we left the session */
1667   if (sess->source->received_bye)
1668     goto ignore;
1669
1670   /* get SSRC and look up in session database */
1671   ssrc = gst_rtp_buffer_get_ssrc (buffer);
1672   source = obtain_source (sess, ssrc, &created, &arrival, TRUE);
1673   if (!source)
1674     goto collision;
1675
1676   prevsender = RTP_SOURCE_IS_SENDER (source);
1677   prevactive = RTP_SOURCE_IS_ACTIVE (source);
1678   oldrate = source->bitrate;
1679
1680   /* copy available csrc for later */
1681   count = gst_rtp_buffer_get_csrc_count (buffer);
1682   /* make sure to not overflow our array. An RTP buffer can maximally contain
1683    * 16 CSRCs */
1684   count = MIN (count, 16);
1685
1686   for (i = 0; i < count; i++)
1687     csrcs[i] = gst_rtp_buffer_get_csrc (buffer, i);
1688
1689   /* let source process the packet */
1690   result = rtp_source_process_rtp (source, buffer, &arrival);
1691
1692   /* source became active */
1693   if (prevactive != RTP_SOURCE_IS_ACTIVE (source)) {
1694     sess->stats.active_sources++;
1695     GST_DEBUG ("source: %08x became active, %d active sources", ssrc,
1696         sess->stats.active_sources);
1697     on_ssrc_validated (sess, source);
1698   }
1699   if (prevsender != RTP_SOURCE_IS_SENDER (source)) {
1700     sess->stats.sender_sources++;
1701     GST_DEBUG ("source: %08x became sender, %d sender sources", ssrc,
1702         sess->stats.sender_sources);
1703   }
1704   if (oldrate != source->bitrate)
1705     sess->recalc_bandwidth = TRUE;
1706
1707   if (created)
1708     on_new_ssrc (sess, source);
1709
1710   if (source->validated) {
1711     gboolean created;
1712
1713     /* for validated sources, we add the CSRCs as well */
1714     for (i = 0; i < count; i++) {
1715       guint32 csrc;
1716       RTPSource *csrc_src;
1717
1718       csrc = csrcs[i];
1719
1720       /* get source */
1721       csrc_src = obtain_source (sess, csrc, &created, &arrival, TRUE);
1722       if (!csrc_src)
1723         continue;
1724
1725       if (created) {
1726         GST_DEBUG ("created new CSRC: %08x", csrc);
1727         rtp_source_set_as_csrc (csrc_src);
1728         if (RTP_SOURCE_IS_ACTIVE (csrc_src))
1729           sess->stats.active_sources++;
1730         on_new_ssrc (sess, csrc_src);
1731       }
1732       g_object_unref (csrc_src);
1733     }
1734   }
1735   g_object_unref (source);
1736
1737   RTP_SESSION_UNLOCK (sess);
1738
1739   return result;
1740
1741   /* ERRORS */
1742 invalid_packet:
1743   {
1744     gst_buffer_unref (buffer);
1745     GST_DEBUG ("invalid RTP packet received");
1746     return GST_FLOW_OK;
1747   }
1748 ignore:
1749   {
1750     gst_buffer_unref (buffer);
1751     RTP_SESSION_UNLOCK (sess);
1752     GST_DEBUG ("ignoring RTP packet because we are leaving");
1753     return GST_FLOW_OK;
1754   }
1755 collision:
1756   {
1757     gst_buffer_unref (buffer);
1758     RTP_SESSION_UNLOCK (sess);
1759     GST_DEBUG ("ignoring packet because its collisioning");
1760     return GST_FLOW_OK;
1761   }
1762 }
1763
1764 static void
1765 rtp_session_process_rb (RTPSession * sess, RTPSource * source,
1766     GstRTCPPacket * packet, RTPArrivalStats * arrival)
1767 {
1768   guint count, i;
1769
1770   count = gst_rtcp_packet_get_rb_count (packet);
1771   for (i = 0; i < count; i++) {
1772     guint32 ssrc, exthighestseq, jitter, lsr, dlsr;
1773     guint8 fractionlost;
1774     gint32 packetslost;
1775
1776     gst_rtcp_packet_get_rb (packet, i, &ssrc, &fractionlost,
1777         &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
1778
1779     GST_DEBUG ("RB %d: SSRC %08x, jitter %" G_GUINT32_FORMAT, i, ssrc, jitter);
1780
1781     if (ssrc == sess->source->ssrc) {
1782       /* only deal with report blocks for our session, we update the stats of
1783        * the sender of the RTCP message. We could also compare our stats against
1784        * the other sender to see if we are better or worse. */
1785       rtp_source_process_rb (source, arrival->ntpnstime, fractionlost,
1786           packetslost, exthighestseq, jitter, lsr, dlsr);
1787     }
1788   }
1789   on_ssrc_active (sess, source);
1790 }
1791
1792 /* A Sender report contains statistics about how the sender is doing. This
1793  * includes timing informataion such as the relation between RTP and NTP
1794  * timestamps and the number of packets/bytes it sent to us.
1795  *
1796  * In this report is also included a set of report blocks related to how this
1797  * sender is receiving data (in case we (or somebody else) is also sending stuff
1798  * to it). This info includes the packet loss, jitter and seqnum. It also
1799  * contains information to calculate the round trip time (LSR/DLSR).
1800  */
1801 static void
1802 rtp_session_process_sr (RTPSession * sess, GstRTCPPacket * packet,
1803     RTPArrivalStats * arrival, gboolean * do_sync)
1804 {
1805   guint32 senderssrc, rtptime, packet_count, octet_count;
1806   guint64 ntptime;
1807   RTPSource *source;
1808   gboolean created, prevsender;
1809
1810   gst_rtcp_packet_sr_get_sender_info (packet, &senderssrc, &ntptime, &rtptime,
1811       &packet_count, &octet_count);
1812
1813   GST_DEBUG ("got SR packet: SSRC %08x, time %" GST_TIME_FORMAT,
1814       senderssrc, GST_TIME_ARGS (arrival->current_time));
1815
1816   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1817   if (!source)
1818     return;
1819
1820   /* don't try to do lip-sync for sources that sent a BYE */
1821   if (rtp_source_received_bye (source))
1822     *do_sync = FALSE;
1823   else
1824     *do_sync = TRUE;
1825
1826   prevsender = RTP_SOURCE_IS_SENDER (source);
1827
1828   /* first update the source */
1829   rtp_source_process_sr (source, arrival->current_time, ntptime, rtptime,
1830       packet_count, octet_count);
1831
1832   if (prevsender != RTP_SOURCE_IS_SENDER (source)) {
1833     sess->stats.sender_sources++;
1834     GST_DEBUG ("source: %08x became sender, %d sender sources", senderssrc,
1835         sess->stats.sender_sources);
1836   }
1837
1838   if (created)
1839     on_new_ssrc (sess, source);
1840
1841   rtp_session_process_rb (sess, source, packet, arrival);
1842   g_object_unref (source);
1843 }
1844
1845 /* A receiver report contains statistics about how a receiver is doing. It
1846  * includes stuff like packet loss, jitter and the seqnum it received last. It
1847  * also contains info to calculate the round trip time.
1848  *
1849  * We are only interested in how the sender of this report is doing wrt to us.
1850  */
1851 static void
1852 rtp_session_process_rr (RTPSession * sess, GstRTCPPacket * packet,
1853     RTPArrivalStats * arrival)
1854 {
1855   guint32 senderssrc;
1856   RTPSource *source;
1857   gboolean created;
1858
1859   senderssrc = gst_rtcp_packet_rr_get_ssrc (packet);
1860
1861   GST_DEBUG ("got RR packet: SSRC %08x", senderssrc);
1862
1863   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1864   if (!source)
1865     return;
1866
1867   if (created)
1868     on_new_ssrc (sess, source);
1869
1870   rtp_session_process_rb (sess, source, packet, arrival);
1871   g_object_unref (source);
1872 }
1873
1874 /* Get SDES items and store them in the SSRC */
1875 static void
1876 rtp_session_process_sdes (RTPSession * sess, GstRTCPPacket * packet,
1877     RTPArrivalStats * arrival)
1878 {
1879   guint items, i, j;
1880   gboolean more_items, more_entries;
1881
1882   items = gst_rtcp_packet_sdes_get_item_count (packet);
1883   GST_DEBUG ("got SDES packet with %d items", items);
1884
1885   more_items = gst_rtcp_packet_sdes_first_item (packet);
1886   i = 0;
1887   while (more_items) {
1888     guint32 ssrc;
1889     gboolean changed, created, validated;
1890     RTPSource *source;
1891     GstStructure *sdes;
1892
1893     ssrc = gst_rtcp_packet_sdes_get_ssrc (packet);
1894
1895     GST_DEBUG ("item %d, SSRC %08x", i, ssrc);
1896
1897     changed = FALSE;
1898
1899     /* find src, no probation when dealing with RTCP */
1900     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1901     if (!source)
1902       return;
1903
1904     sdes = gst_structure_new ("application/x-rtp-source-sdes", NULL);
1905
1906     more_entries = gst_rtcp_packet_sdes_first_entry (packet);
1907     j = 0;
1908     while (more_entries) {
1909       GstRTCPSDESType type;
1910       guint8 len;
1911       guint8 *data;
1912       gchar *name;
1913       gchar *value;
1914
1915       gst_rtcp_packet_sdes_get_entry (packet, &type, &len, &data);
1916
1917       GST_DEBUG ("entry %d, type %d, len %d, data %.*s", j, type, len, len,
1918           data);
1919
1920       if (type == GST_RTCP_SDES_PRIV) {
1921         name = g_strndup ((const gchar *) &data[1], data[0]);
1922         len -= data[0] + 1;
1923         data += data[0] + 1;
1924       } else {
1925         name = g_strdup (gst_rtcp_sdes_type_to_name (type));
1926       }
1927
1928       value = g_strndup ((const gchar *) data, len);
1929
1930       gst_structure_set (sdes, name, G_TYPE_STRING, value, NULL);
1931
1932       g_free (name);
1933       g_free (value);
1934
1935       more_entries = gst_rtcp_packet_sdes_next_entry (packet);
1936       j++;
1937     }
1938
1939     /* takes ownership of sdes */
1940     changed = rtp_source_set_sdes_struct (source, sdes);
1941
1942     validated = !RTP_SOURCE_IS_ACTIVE (source);
1943     source->validated = TRUE;
1944
1945     if (created)
1946       on_new_ssrc (sess, source);
1947     if (validated)
1948       on_ssrc_validated (sess, source);
1949     if (changed)
1950       on_ssrc_sdes (sess, source);
1951
1952     g_object_unref (source);
1953
1954     more_items = gst_rtcp_packet_sdes_next_item (packet);
1955     i++;
1956   }
1957 }
1958
1959 /* BYE is sent when a client leaves the session
1960  */
1961 static void
1962 rtp_session_process_bye (RTPSession * sess, GstRTCPPacket * packet,
1963     RTPArrivalStats * arrival)
1964 {
1965   guint count, i;
1966   gchar *reason;
1967   gboolean reconsider = FALSE;
1968
1969   reason = gst_rtcp_packet_bye_get_reason (packet);
1970   GST_DEBUG ("got BYE packet (reason: %s)", GST_STR_NULL (reason));
1971
1972   count = gst_rtcp_packet_bye_get_ssrc_count (packet);
1973   for (i = 0; i < count; i++) {
1974     guint32 ssrc;
1975     RTPSource *source;
1976     gboolean created, prevactive, prevsender;
1977     guint pmembers, members;
1978
1979     ssrc = gst_rtcp_packet_bye_get_nth_ssrc (packet, i);
1980     GST_DEBUG ("SSRC: %08x", ssrc);
1981
1982     /* find src and mark bye, no probation when dealing with RTCP */
1983     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1984     if (!source)
1985       return;
1986
1987     /* store time for when we need to time out this source */
1988     source->bye_time = arrival->current_time;
1989
1990     prevactive = RTP_SOURCE_IS_ACTIVE (source);
1991     prevsender = RTP_SOURCE_IS_SENDER (source);
1992
1993     /* let the source handle the rest */
1994     rtp_source_process_bye (source, reason);
1995
1996     pmembers = sess->stats.active_sources;
1997
1998     if (prevactive && !RTP_SOURCE_IS_ACTIVE (source)) {
1999       sess->stats.active_sources--;
2000       GST_DEBUG ("source: %08x became inactive, %d active sources", ssrc,
2001           sess->stats.active_sources);
2002     }
2003     if (prevsender && !RTP_SOURCE_IS_SENDER (source)) {
2004       sess->stats.sender_sources--;
2005       GST_DEBUG ("source: %08x became non sender, %d sender sources", ssrc,
2006           sess->stats.sender_sources);
2007     }
2008     members = sess->stats.active_sources;
2009
2010     if (!sess->source->received_bye && members < pmembers) {
2011       /* some members went away since the previous timeout estimate.
2012        * Perform reverse reconsideration but only when we are not scheduling a
2013        * BYE ourselves. */
2014       if (arrival->current_time < sess->next_rtcp_check_time) {
2015         GstClockTime time_remaining;
2016
2017         time_remaining = sess->next_rtcp_check_time - arrival->current_time;
2018         sess->next_rtcp_check_time =
2019             gst_util_uint64_scale (time_remaining, members, pmembers);
2020
2021         GST_DEBUG ("reverse reconsideration %" GST_TIME_FORMAT,
2022             GST_TIME_ARGS (sess->next_rtcp_check_time));
2023
2024         sess->next_rtcp_check_time += arrival->current_time;
2025
2026         /* mark pending reconsider. We only want to signal the reconsideration
2027          * once after we handled all the source in the bye packet */
2028         reconsider = TRUE;
2029       }
2030     }
2031
2032     if (created)
2033       on_new_ssrc (sess, source);
2034
2035     on_bye_ssrc (sess, source);
2036
2037     g_object_unref (source);
2038   }
2039   if (reconsider) {
2040     RTP_SESSION_UNLOCK (sess);
2041     /* notify app of reconsideration */
2042     if (sess->callbacks.reconsider)
2043       sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2044     RTP_SESSION_LOCK (sess);
2045   }
2046   g_free (reason);
2047 }
2048
2049 static void
2050 rtp_session_process_app (RTPSession * sess, GstRTCPPacket * packet,
2051     RTPArrivalStats * arrival)
2052 {
2053   GST_DEBUG ("received APP");
2054 }
2055
2056 static void
2057 rtp_session_process_pli (RTPSession * sess, guint32 sender_ssrc,
2058     guint32 media_ssrc, GstClockTime current_time)
2059 {
2060   RTPSource *src;
2061   guint32 round_trip = 0;
2062
2063   if (!sess->callbacks.request_key_unit)
2064     return;
2065
2066   src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2067       GINT_TO_POINTER (sender_ssrc));
2068
2069   if (!src)
2070     return;
2071
2072   if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2073       rtp_source_get_last_rb (src, NULL, NULL, NULL, NULL, NULL, NULL,
2074           &round_trip)) {
2075     GstClockTime round_trip_in_ns = gst_util_uint64_scale (round_trip,
2076         GST_SECOND, 65536);
2077
2078     if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2079         current_time - sess->last_keyframe_request < round_trip_in_ns) {
2080       GST_DEBUG ("Ignoring PLI because one was send without one RTT (%"
2081           GST_TIME_FORMAT " < %" GST_TIME_FORMAT ")",
2082           GST_TIME_ARGS (current_time - sess->last_keyframe_request),
2083           GST_TIME_ARGS (round_trip_in_ns));;
2084       return;
2085     }
2086   }
2087
2088   sess->last_keyframe_request = current_time;
2089
2090   GST_LOG ("received PLI from %X %p(%p)", sender_ssrc,
2091       sess->callbacks.process_rtp, sess->callbacks.request_key_unit);
2092
2093   sess->callbacks.request_key_unit (sess, FALSE,
2094       sess->request_key_unit_user_data);
2095 }
2096
2097 static void
2098 rtp_session_process_feedback (RTPSession * sess, GstRTCPPacket * packet,
2099     RTPArrivalStats * arrival, GstClockTime current_time)
2100 {
2101   GstRTCPType type = gst_rtcp_packet_get_type (packet);
2102   GstRTCPFBType fbtype = gst_rtcp_packet_fb_get_type (packet);
2103   guint32 sender_ssrc = gst_rtcp_packet_fb_get_sender_ssrc (packet);
2104   guint32 media_ssrc = gst_rtcp_packet_fb_get_media_ssrc (packet);
2105   guint length = 4 * (gst_rtcp_packet_get_length (packet) - 2);
2106
2107   GST_DEBUG ("received feedback %d:%d from %08X about %08X"
2108       " with FCI of length %d", type, fbtype, sender_ssrc, media_ssrc, length);
2109
2110   if (g_signal_has_handler_pending (sess,
2111           rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0, TRUE)) {
2112     GstBuffer *fci = NULL;
2113
2114     if (length) {
2115       fci = gst_buffer_create_sub (packet->buffer, packet->offset + 72, length);
2116       GST_BUFFER_TIMESTAMP (fci) = arrival->running_time;
2117     }
2118
2119     RTP_SESSION_UNLOCK (sess);
2120     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0,
2121         type, fbtype, sender_ssrc, media_ssrc, fci);
2122     RTP_SESSION_LOCK (sess);
2123
2124     if (fci)
2125       gst_buffer_unref (fci);
2126   }
2127
2128   if (sess->rtcp_feedback_retention_window) {
2129     RTPSource *src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2130         GINT_TO_POINTER (media_ssrc));
2131
2132     if (src)
2133       rtp_source_retain_rtcp_packet (src, packet, arrival->running_time);
2134   }
2135
2136   if (rtp_source_get_ssrc (sess->source) == media_ssrc) {
2137     switch (type) {
2138       case GST_RTCP_TYPE_PSFB:
2139         switch (fbtype) {
2140           case GST_RTCP_PSFB_TYPE_PLI:
2141             rtp_session_process_pli (sess, sender_ssrc, media_ssrc,
2142                 current_time);
2143             break;
2144           default:
2145             break;
2146         }
2147         break;
2148       case GST_RTCP_TYPE_RTPFB:
2149       default:
2150         break;
2151     }
2152   }
2153 }
2154
2155 /**
2156  * rtp_session_process_rtcp:
2157  * @sess: and #RTPSession
2158  * @buffer: an RTCP buffer
2159  * @current_time: the current system time
2160  * @ntpnstime: the current NTP time in nanoseconds
2161  *
2162  * Process an RTCP buffer in the session manager. This function takes ownership
2163  * of @buffer.
2164  *
2165  * Returns: a #GstFlowReturn.
2166  */
2167 GstFlowReturn
2168 rtp_session_process_rtcp (RTPSession * sess, GstBuffer * buffer,
2169     GstClockTime current_time, guint64 ntpnstime)
2170 {
2171   GstRTCPPacket packet;
2172   gboolean more, is_bye = FALSE, do_sync = FALSE;
2173   RTPArrivalStats arrival;
2174   GstFlowReturn result = GST_FLOW_OK;
2175
2176   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2177   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
2178
2179   if (!gst_rtcp_buffer_validate (buffer))
2180     goto invalid_packet;
2181
2182   GST_DEBUG ("received RTCP packet");
2183
2184   RTP_SESSION_LOCK (sess);
2185   /* update arrival stats */
2186   update_arrival_stats (sess, &arrival, FALSE, buffer, current_time, -1,
2187       ntpnstime);
2188
2189   if (sess->sent_bye)
2190     goto ignore;
2191
2192   /* start processing the compound packet */
2193   more = gst_rtcp_buffer_get_first_packet (buffer, &packet);
2194   while (more) {
2195     GstRTCPType type;
2196
2197     type = gst_rtcp_packet_get_type (&packet);
2198
2199     /* when we are leaving the session, we should ignore all non-BYE messages */
2200     if (sess->source->received_bye && type != GST_RTCP_TYPE_BYE) {
2201       GST_DEBUG ("ignoring non-BYE RTCP packet because we are leaving");
2202       goto next;
2203     }
2204
2205     switch (type) {
2206       case GST_RTCP_TYPE_SR:
2207         rtp_session_process_sr (sess, &packet, &arrival, &do_sync);
2208         break;
2209       case GST_RTCP_TYPE_RR:
2210         rtp_session_process_rr (sess, &packet, &arrival);
2211         break;
2212       case GST_RTCP_TYPE_SDES:
2213         rtp_session_process_sdes (sess, &packet, &arrival);
2214         break;
2215       case GST_RTCP_TYPE_BYE:
2216         is_bye = TRUE;
2217         /* don't try to attempt lip-sync anymore for streams with a BYE */
2218         do_sync = FALSE;
2219         rtp_session_process_bye (sess, &packet, &arrival);
2220         break;
2221       case GST_RTCP_TYPE_APP:
2222         rtp_session_process_app (sess, &packet, &arrival);
2223         break;
2224       case GST_RTCP_TYPE_RTPFB:
2225       case GST_RTCP_TYPE_PSFB:
2226         rtp_session_process_feedback (sess, &packet, &arrival, current_time);
2227         break;
2228       default:
2229         GST_WARNING ("got unknown RTCP packet");
2230         break;
2231     }
2232   next:
2233     more = gst_rtcp_packet_move_to_next (&packet);
2234   }
2235
2236   /* if we are scheduling a BYE, we only want to count bye packets, else we
2237    * count everything */
2238   if (sess->source->received_bye) {
2239     if (is_bye) {
2240       sess->stats.bye_members++;
2241       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2242     }
2243   } else {
2244     /* keep track of average packet size */
2245     UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2246   }
2247   GST_DEBUG ("%p, received RTCP packet, avg size %u, %u", &sess->stats,
2248       sess->stats.avg_rtcp_packet_size, arrival.bytes);
2249   RTP_SESSION_UNLOCK (sess);
2250
2251   /* notify caller of sr packets in the callback */
2252   if (do_sync && sess->callbacks.sync_rtcp) {
2253     /* make writable, we might want to change the buffer */
2254     buffer = gst_buffer_make_metadata_writable (buffer);
2255
2256     result = sess->callbacks.sync_rtcp (sess, sess->source, buffer,
2257         sess->sync_rtcp_user_data);
2258   } else
2259     gst_buffer_unref (buffer);
2260
2261   return result;
2262
2263   /* ERRORS */
2264 invalid_packet:
2265   {
2266     GST_DEBUG ("invalid RTCP packet received");
2267     gst_buffer_unref (buffer);
2268     return GST_FLOW_OK;
2269   }
2270 ignore:
2271   {
2272     gst_buffer_unref (buffer);
2273     RTP_SESSION_UNLOCK (sess);
2274     GST_DEBUG ("ignoring RTP packet because we left");
2275     return GST_FLOW_OK;
2276   }
2277 }
2278
2279 /**
2280  * rtp_session_send_rtp:
2281  * @sess: an #RTPSession
2282  * @data: pointer to either an RTP buffer or a list of RTP buffers
2283  * @is_list: TRUE when @data is a buffer list
2284  * @current_time: the current system time
2285  * @running_time: the running time of @data
2286  *
2287  * Send the RTP buffer in the session manager. This function takes ownership of
2288  * @buffer.
2289  *
2290  * Returns: a #GstFlowReturn.
2291  */
2292 GstFlowReturn
2293 rtp_session_send_rtp (RTPSession * sess, gpointer data, gboolean is_list,
2294     GstClockTime current_time, GstClockTime running_time)
2295 {
2296   GstFlowReturn result;
2297   RTPSource *source;
2298   gboolean prevsender;
2299   gboolean valid_packet;
2300   guint64 oldrate;
2301
2302   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2303   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
2304
2305   if (is_list) {
2306     valid_packet = gst_rtp_buffer_list_validate (GST_BUFFER_LIST_CAST (data));
2307   } else {
2308     valid_packet = gst_rtp_buffer_validate (GST_BUFFER_CAST (data));
2309   }
2310
2311   if (!valid_packet)
2312     goto invalid_packet;
2313
2314   GST_LOG ("received RTP %s for sending", is_list ? "list" : "packet");
2315
2316   RTP_SESSION_LOCK (sess);
2317   source = sess->source;
2318
2319   /* update last activity */
2320   source->last_rtp_activity = current_time;
2321
2322   prevsender = RTP_SOURCE_IS_SENDER (source);
2323   oldrate = source->bitrate;
2324
2325   /* we use our own source to send */
2326   result = rtp_source_send_rtp (source, data, is_list, running_time);
2327
2328   if (RTP_SOURCE_IS_SENDER (source) && !prevsender)
2329     sess->stats.sender_sources++;
2330   if (oldrate != source->bitrate)
2331     sess->recalc_bandwidth = TRUE;
2332   RTP_SESSION_UNLOCK (sess);
2333
2334   return result;
2335
2336   /* ERRORS */
2337 invalid_packet:
2338   {
2339     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
2340     GST_DEBUG ("invalid RTP packet received");
2341     return GST_FLOW_OK;
2342   }
2343 }
2344
2345 static void
2346 add_bitrates (gpointer key, RTPSource * source, gdouble * bandwidth)
2347 {
2348   *bandwidth += source->bitrate;
2349 }
2350
2351 static GstClockTime
2352 calculate_rtcp_interval (RTPSession * sess, gboolean deterministic,
2353     gboolean first)
2354 {
2355   GstClockTime result;
2356
2357   /* recalculate bandwidth when it changed */
2358   if (sess->recalc_bandwidth) {
2359     gdouble bandwidth;
2360
2361     if (sess->bandwidth > 0)
2362       bandwidth = sess->bandwidth;
2363     else {
2364       /* If it is <= 0, then try to estimate the actual bandwidth */
2365       bandwidth = sess->source->bitrate;
2366
2367       g_hash_table_foreach (sess->cnames, (GHFunc) add_bitrates, &bandwidth);
2368       bandwidth /= 8.0;
2369     }
2370     if (bandwidth == 0)
2371       bandwidth = RTP_STATS_BANDWIDTH;
2372
2373     rtp_stats_set_bandwidths (&sess->stats, bandwidth,
2374         sess->rtcp_bandwidth, sess->rtcp_rs_bandwidth, sess->rtcp_rr_bandwidth);
2375
2376     sess->recalc_bandwidth = FALSE;
2377   }
2378
2379   if (sess->source->received_bye) {
2380     result = rtp_stats_calculate_bye_interval (&sess->stats);
2381   } else {
2382     result = rtp_stats_calculate_rtcp_interval (&sess->stats,
2383         RTP_SOURCE_IS_SENDER (sess->source), first);
2384   }
2385
2386   GST_DEBUG ("next deterministic interval: %" GST_TIME_FORMAT ", first %d",
2387       GST_TIME_ARGS (result), first);
2388
2389   if (!deterministic && result != GST_CLOCK_TIME_NONE)
2390     result = rtp_stats_add_rtcp_jitter (&sess->stats, result);
2391
2392   GST_DEBUG ("next interval: %" GST_TIME_FORMAT, GST_TIME_ARGS (result));
2393
2394   return result;
2395 }
2396
2397 /* Stop the current @sess and schedule a BYE message for the other members.
2398  * One must have the session lock to call this function
2399  */
2400 static GstFlowReturn
2401 rtp_session_schedule_bye_locked (RTPSession * sess, const gchar * reason,
2402     GstClockTime current_time)
2403 {
2404   GstFlowReturn result = GST_FLOW_OK;
2405   RTPSource *source;
2406   GstClockTime interval;
2407
2408   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2409
2410   source = sess->source;
2411
2412   /* ignore more BYEs */
2413   if (source->received_bye)
2414     goto done;
2415
2416   /* we have BYE now */
2417   source->received_bye = TRUE;
2418   /* at least one member wants to send a BYE */
2419   g_free (sess->bye_reason);
2420   sess->bye_reason = g_strdup (reason);
2421   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
2422   sess->stats.bye_members = 1;
2423   sess->first_rtcp = TRUE;
2424   sess->sent_bye = FALSE;
2425   sess->allow_early = TRUE;
2426
2427   /* reschedule transmission */
2428   sess->last_rtcp_send_time = current_time;
2429   interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2430   sess->next_rtcp_check_time = current_time + interval;
2431
2432   GST_DEBUG ("Schedule BYE for %" GST_TIME_FORMAT ", %" GST_TIME_FORMAT,
2433       GST_TIME_ARGS (interval), GST_TIME_ARGS (sess->next_rtcp_check_time));
2434
2435   RTP_SESSION_UNLOCK (sess);
2436   /* notify app of reconsideration */
2437   if (sess->callbacks.reconsider)
2438     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2439   RTP_SESSION_LOCK (sess);
2440 done:
2441
2442   return result;
2443 }
2444
2445 /**
2446  * rtp_session_schedule_bye:
2447  * @sess: an #RTPSession
2448  * @reason: a reason or NULL
2449  * @current_time: the current system time
2450  *
2451  * Stop the current @sess and schedule a BYE message for the other members.
2452  *
2453  * Returns: a #GstFlowReturn.
2454  */
2455 GstFlowReturn
2456 rtp_session_schedule_bye (RTPSession * sess, const gchar * reason,
2457     GstClockTime current_time)
2458 {
2459   GstFlowReturn result = GST_FLOW_OK;
2460
2461   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2462
2463   RTP_SESSION_LOCK (sess);
2464   result = rtp_session_schedule_bye_locked (sess, reason, current_time);
2465   RTP_SESSION_UNLOCK (sess);
2466
2467   return result;
2468 }
2469
2470 /**
2471  * rtp_session_next_timeout:
2472  * @sess: an #RTPSession
2473  * @current_time: the current system time
2474  *
2475  * Get the next time we should perform session maintenance tasks.
2476  *
2477  * Returns: a time when rtp_session_on_timeout() should be called with the
2478  * current system time.
2479  */
2480 GstClockTime
2481 rtp_session_next_timeout (RTPSession * sess, GstClockTime current_time)
2482 {
2483   GstClockTime result, interval = 0;
2484
2485   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_CLOCK_TIME_NONE);
2486
2487   RTP_SESSION_LOCK (sess);
2488
2489   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
2490     result = sess->next_early_rtcp_time;
2491     goto early_exit;
2492   }
2493
2494   result = sess->next_rtcp_check_time;
2495
2496   GST_DEBUG ("current time: %" GST_TIME_FORMAT ", next :%" GST_TIME_FORMAT,
2497       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2498
2499   if (result < current_time) {
2500     GST_DEBUG ("take current time as base");
2501     /* our previous check time expired, start counting from the current time
2502      * again. */
2503     result = current_time;
2504   }
2505
2506   if (sess->source->received_bye) {
2507     if (sess->sent_bye) {
2508       GST_DEBUG ("we sent BYE already");
2509       interval = GST_CLOCK_TIME_NONE;
2510     } else if (sess->stats.active_sources >= 50) {
2511       GST_DEBUG ("reconsider BYE, more than 50 sources");
2512       /* reconsider BYE if members >= 50 */
2513       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2514     }
2515   } else {
2516     if (sess->first_rtcp) {
2517       GST_DEBUG ("first RTCP packet");
2518       /* we are called for the first time */
2519       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2520     } else if (sess->next_rtcp_check_time < current_time) {
2521       GST_DEBUG ("old check time expired, getting new timeout");
2522       /* get a new timeout when we need to */
2523       interval = calculate_rtcp_interval (sess, FALSE, FALSE);
2524     }
2525   }
2526
2527   if (interval != GST_CLOCK_TIME_NONE)
2528     result += interval;
2529   else
2530     result = GST_CLOCK_TIME_NONE;
2531
2532   sess->next_rtcp_check_time = result;
2533
2534 early_exit:
2535
2536   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2537       ", next time: %" GST_TIME_FORMAT,
2538       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2539   RTP_SESSION_UNLOCK (sess);
2540
2541   return result;
2542 }
2543
2544 typedef struct
2545 {
2546   RTPSession *sess;
2547   GstBuffer *rtcp;
2548   GstClockTime current_time;
2549   guint64 ntpnstime;
2550   GstClockTime running_time;
2551   GstClockTime interval;
2552   GstRTCPPacket packet;
2553   gboolean is_bye;
2554   gboolean has_sdes;
2555   gboolean is_early;
2556   gboolean may_suppress;
2557 } ReportData;
2558
2559 static void
2560 session_start_rtcp (RTPSession * sess, ReportData * data)
2561 {
2562   GstRTCPPacket *packet = &data->packet;
2563   RTPSource *own = sess->source;
2564
2565   data->rtcp = gst_rtcp_buffer_new (sess->mtu);
2566
2567   if (RTP_SOURCE_IS_SENDER (own)) {
2568     guint64 ntptime;
2569     guint32 rtptime;
2570     guint32 packet_count, octet_count;
2571
2572     /* we are a sender, create SR */
2573     GST_DEBUG ("create SR for SSRC %08x", own->ssrc);
2574     gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_SR, packet);
2575
2576     /* get latest stats */
2577     rtp_source_get_new_sr (own, data->ntpnstime, data->running_time,
2578         &ntptime, &rtptime, &packet_count, &octet_count);
2579     /* store stats */
2580     rtp_source_process_sr (own, data->current_time, ntptime, rtptime,
2581         packet_count, octet_count);
2582
2583     /* fill in sender report info */
2584     gst_rtcp_packet_sr_set_sender_info (packet, own->ssrc,
2585         ntptime, rtptime, packet_count, octet_count);
2586   } else {
2587     /* we are only receiver, create RR */
2588     GST_DEBUG ("create RR for SSRC %08x", own->ssrc);
2589     gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_RR, packet);
2590     gst_rtcp_packet_rr_set_ssrc (packet, own->ssrc);
2591   }
2592 }
2593
2594 /* construct a Sender or Receiver Report */
2595 static void
2596 session_report_blocks (const gchar * key, RTPSource * source, ReportData * data)
2597 {
2598   RTPSession *sess = data->sess;
2599   GstRTCPPacket *packet = &data->packet;
2600
2601   /* create a new buffer if needed */
2602   if (data->rtcp == NULL) {
2603     session_start_rtcp (sess, data);
2604   } else if (data->is_early) {
2605     /* Put a single RR or SR in minimal compound packets */
2606     return;
2607   }
2608   if (gst_rtcp_packet_get_rb_count (packet) < GST_RTCP_MAX_RB_COUNT) {
2609     /* only report about other sender sources */
2610     if (source != sess->source && RTP_SOURCE_IS_SENDER (source)) {
2611       guint8 fractionlost;
2612       gint32 packetslost;
2613       guint32 exthighestseq, jitter;
2614       guint32 lsr, dlsr;
2615
2616       /* get new stats */
2617       rtp_source_get_new_rb (source, data->current_time, &fractionlost,
2618           &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
2619
2620       /* store last generated RR packet */
2621       source->last_rr.is_valid = TRUE;
2622       source->last_rr.fractionlost = fractionlost;
2623       source->last_rr.packetslost = packetslost;
2624       source->last_rr.exthighestseq = exthighestseq;
2625       source->last_rr.jitter = jitter;
2626       source->last_rr.lsr = lsr;
2627       source->last_rr.dlsr = dlsr;
2628
2629       /* packet is not yet filled, add report block for this source. */
2630       gst_rtcp_packet_add_rb (packet, source->ssrc, fractionlost, packetslost,
2631           exthighestseq, jitter, lsr, dlsr);
2632     }
2633   }
2634 }
2635
2636 /* perform cleanup of sources that timed out */
2637 static void
2638 session_cleanup (const gchar * key, RTPSource * source, ReportData * data)
2639 {
2640   gboolean remove = FALSE;
2641   gboolean byetimeout = FALSE;
2642   gboolean sendertimeout = FALSE;
2643   gboolean is_sender, is_active;
2644   RTPSession *sess = data->sess;
2645   GstClockTime interval;
2646
2647   is_sender = RTP_SOURCE_IS_SENDER (source);
2648   is_active = RTP_SOURCE_IS_ACTIVE (source);
2649
2650   /* check for our own source, we don't want to delete our own source. */
2651   if (!(source == sess->source)) {
2652     if (source->received_bye) {
2653       /* if we received a BYE from the source, remove the source after some
2654        * time. */
2655       if (data->current_time > source->bye_time &&
2656           data->current_time - source->bye_time > sess->stats.bye_timeout) {
2657         GST_DEBUG ("removing BYE source %08x", source->ssrc);
2658         remove = TRUE;
2659         byetimeout = TRUE;
2660       }
2661     }
2662     /* sources that were inactive for more than 5 times the deterministic reporting
2663      * interval get timed out. the min timeout is 5 seconds. */
2664     if (data->current_time > source->last_activity) {
2665       interval = MAX (data->interval * 5, 5 * GST_SECOND);
2666       if (data->current_time - source->last_activity > interval) {
2667         GST_DEBUG ("removing timeout source %08x, last %" GST_TIME_FORMAT,
2668             source->ssrc, GST_TIME_ARGS (source->last_activity));
2669         remove = TRUE;
2670       }
2671     }
2672   }
2673
2674   /* senders that did not send for a long time become a receiver, this also
2675    * holds for our own source. */
2676   if (is_sender) {
2677     if (data->current_time > source->last_rtp_activity) {
2678       interval = MAX (data->interval * 2, 5 * GST_SECOND);
2679       if (data->current_time - source->last_rtp_activity > interval) {
2680         GST_DEBUG ("sender source %08x timed out and became receiver, last %"
2681             GST_TIME_FORMAT, source->ssrc,
2682             GST_TIME_ARGS (source->last_rtp_activity));
2683         source->is_sender = FALSE;
2684         sess->stats.sender_sources--;
2685         sendertimeout = TRUE;
2686       }
2687     }
2688   }
2689
2690   if (remove) {
2691     sess->total_sources--;
2692     if (is_sender)
2693       sess->stats.sender_sources--;
2694     if (is_active)
2695       sess->stats.active_sources--;
2696
2697     if (byetimeout)
2698       on_bye_timeout (sess, source);
2699     else
2700       on_timeout (sess, source);
2701   } else {
2702     if (sendertimeout)
2703       on_sender_timeout (sess, source);
2704   }
2705
2706   source->closing = remove;
2707 }
2708
2709 static void
2710 session_sdes (RTPSession * sess, ReportData * data)
2711 {
2712   GstRTCPPacket *packet = &data->packet;
2713   const GstStructure *sdes;
2714   gint i, n_fields;
2715
2716   /* add SDES packet */
2717   gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_SDES, packet);
2718
2719   gst_rtcp_packet_sdes_add_item (packet, sess->source->ssrc);
2720
2721   sdes = rtp_source_get_sdes_struct (sess->source);
2722
2723   /* add all fields in the structure, the order is not important. */
2724   n_fields = gst_structure_n_fields (sdes);
2725   for (i = 0; i < n_fields; ++i) {
2726     const gchar *field;
2727     const gchar *value;
2728     GstRTCPSDESType type;
2729
2730     field = gst_structure_nth_field_name (sdes, i);
2731     if (field == NULL)
2732       continue;
2733     value = gst_structure_get_string (sdes, field);
2734     if (value == NULL)
2735       continue;
2736     type = gst_rtcp_sdes_name_to_type (field);
2737
2738     /* Early packets are minimal and only include the CNAME */
2739     if (data->is_early && type != GST_RTCP_SDES_CNAME)
2740       continue;
2741
2742     if (type > GST_RTCP_SDES_END && type < GST_RTCP_SDES_PRIV) {
2743       gst_rtcp_packet_sdes_add_entry (packet, type, strlen (value),
2744           (const guint8 *) value);
2745     } else if (type == GST_RTCP_SDES_PRIV) {
2746       gsize prefix_len;
2747       gsize value_len;
2748       gsize data_len;
2749       guint8 data[256];
2750
2751       /* don't accept entries that are too big */
2752       prefix_len = strlen (field);
2753       if (prefix_len > 255)
2754         continue;
2755       value_len = strlen (value);
2756       if (value_len > 255)
2757         continue;
2758       data_len = 1 + prefix_len + value_len;
2759       if (data_len > 255)
2760         continue;
2761
2762       data[0] = prefix_len;
2763       memcpy (&data[1], field, prefix_len);
2764       memcpy (&data[1 + prefix_len], value, value_len);
2765
2766       gst_rtcp_packet_sdes_add_entry (packet, type, data_len, data);
2767     }
2768   }
2769
2770   data->has_sdes = TRUE;
2771 }
2772
2773 /* schedule a BYE packet */
2774 static void
2775 session_bye (RTPSession * sess, ReportData * data)
2776 {
2777   GstRTCPPacket *packet = &data->packet;
2778
2779   /* open packet */
2780   session_start_rtcp (sess, data);
2781
2782   /* add SDES */
2783   session_sdes (sess, data);
2784
2785   /* add a BYE packet */
2786   gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_BYE, packet);
2787   gst_rtcp_packet_bye_add_ssrc (packet, sess->source->ssrc);
2788   if (sess->bye_reason)
2789     gst_rtcp_packet_bye_set_reason (packet, sess->bye_reason);
2790
2791   /* we have a BYE packet now */
2792   data->is_bye = TRUE;
2793 }
2794
2795 static gboolean
2796 is_rtcp_time (RTPSession * sess, GstClockTime current_time, ReportData * data)
2797 {
2798   GstClockTime new_send_time, elapsed;
2799
2800   if (data->is_early && sess->next_early_rtcp_time < current_time)
2801     goto early;
2802
2803   /* no need to check yet */
2804   if (sess->next_rtcp_check_time > current_time) {
2805     GST_DEBUG ("no check time yet, next %" GST_TIME_FORMAT " > now %"
2806         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_rtcp_check_time),
2807         GST_TIME_ARGS (current_time));
2808     return FALSE;
2809   }
2810
2811   /* get elapsed time since we last reported */
2812   elapsed = current_time - sess->last_rtcp_send_time;
2813
2814   /* perform forward reconsideration */
2815   new_send_time = rtp_stats_add_rtcp_jitter (&sess->stats, data->interval);
2816
2817   GST_DEBUG ("forward reconsideration %" GST_TIME_FORMAT ", elapsed %"
2818       GST_TIME_FORMAT, GST_TIME_ARGS (new_send_time), GST_TIME_ARGS (elapsed));
2819
2820   new_send_time += sess->last_rtcp_send_time;
2821
2822   /* check if reconsideration */
2823   if (current_time < new_send_time) {
2824     GST_DEBUG ("reconsider RTCP for %" GST_TIME_FORMAT,
2825         GST_TIME_ARGS (new_send_time));
2826     /* store new check time */
2827     sess->next_rtcp_check_time = new_send_time;
2828     return FALSE;
2829   }
2830
2831 early:
2832
2833   new_send_time = calculate_rtcp_interval (sess, FALSE, FALSE);
2834
2835   GST_DEBUG ("can send RTCP now, next interval %" GST_TIME_FORMAT,
2836       GST_TIME_ARGS (new_send_time));
2837   sess->next_rtcp_check_time = current_time + new_send_time;
2838
2839   /* Apply the rules from RFC 4585 section 3.5.3 */
2840   if (sess->stats.min_interval != 0 && !sess->first_rtcp) {
2841     GstClockTimeDiff T_rr_current_interval = g_random_double_range (0.5, 1.5) *
2842         sess->stats.min_interval;
2843
2844     /* This will caused the RTCP to be suppressed if no FB packets are added */
2845     if (sess->last_rtcp_send_time + T_rr_current_interval >
2846         sess->next_rtcp_check_time) {
2847       GST_DEBUG ("RTCP packet could be suppressed min: %" GST_TIME_FORMAT
2848           " last: %" GST_TIME_FORMAT
2849           " + T_rr_current_interval: %" GST_TIME_FORMAT
2850           " >  sess->next_rtcp_check_time: %" GST_TIME_FORMAT,
2851           GST_TIME_ARGS (sess->stats.min_interval),
2852           GST_TIME_ARGS (sess->last_rtcp_send_time),
2853           GST_TIME_ARGS (T_rr_current_interval),
2854           GST_TIME_ARGS (sess->next_rtcp_check_time));
2855       data->may_suppress = TRUE;
2856     }
2857   }
2858
2859   return TRUE;
2860 }
2861
2862 static void
2863 clone_ssrcs_hashtable (gchar * key, RTPSource * source, GHashTable * hash_table)
2864 {
2865   g_hash_table_insert (hash_table, key, g_object_ref (source));
2866 }
2867
2868 static gboolean
2869 remove_closing_sources (const gchar * key, RTPSource * source, gpointer * data)
2870 {
2871   return source->closing;
2872 }
2873
2874 /**
2875  * rtp_session_on_timeout:
2876  * @sess: an #RTPSession
2877  * @current_time: the current system time
2878  * @ntpnstime: the current NTP time in nanoseconds
2879  * @running_time: the current running_time of the pipeline
2880  *
2881  * Perform maintenance actions after the timeout obtained with
2882  * rtp_session_next_timeout() expired.
2883  *
2884  * This function will perform timeouts of receivers and senders, send a BYE
2885  * packet or generate RTCP packets with current session stats.
2886  *
2887  * This function can call the #RTPSessionSendRTCP callback, possibly multiple
2888  * times, for each packet that should be processed.
2889  *
2890  * Returns: a #GstFlowReturn.
2891  */
2892 GstFlowReturn
2893 rtp_session_on_timeout (RTPSession * sess, GstClockTime current_time,
2894     guint64 ntpnstime, GstClockTime running_time)
2895 {
2896   GstFlowReturn result = GST_FLOW_OK;
2897   ReportData data;
2898   RTPSource *own;
2899   GHashTable *table_copy;
2900   gboolean notify = FALSE;
2901
2902   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2903
2904   GST_DEBUG ("reporting at %" GST_TIME_FORMAT ", NTP time %" GST_TIME_FORMAT,
2905       GST_TIME_ARGS (current_time), GST_TIME_ARGS (ntpnstime));
2906
2907   data.sess = sess;
2908   data.rtcp = NULL;
2909   data.current_time = current_time;
2910   data.ntpnstime = ntpnstime;
2911   data.is_bye = FALSE;
2912   data.has_sdes = FALSE;
2913   data.may_suppress = FALSE;
2914   data.running_time = running_time;
2915
2916   own = sess->source;
2917
2918   RTP_SESSION_LOCK (sess);
2919   /* get a new interval, we need this for various cleanups etc */
2920   data.interval = calculate_rtcp_interval (sess, TRUE, sess->first_rtcp);
2921
2922   /* Make a local copy of the hashtable. We need to do this because the
2923    * cleanup stage below releases the session lock. */
2924   table_copy = g_hash_table_new_full (NULL, NULL, NULL,
2925       (GDestroyNotify) g_object_unref);
2926   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2927       (GHFunc) clone_ssrcs_hashtable, table_copy);
2928
2929   /* Clean up the session, mark the source for removing, this might release the
2930    * session lock. */
2931   g_hash_table_foreach (table_copy, (GHFunc) session_cleanup, &data);
2932   g_hash_table_destroy (table_copy);
2933
2934   /* Now remove the marked sources */
2935   g_hash_table_foreach_remove (sess->ssrcs[sess->mask_idx],
2936       (GHRFunc) remove_closing_sources, NULL);
2937
2938   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
2939     data.is_early = TRUE;
2940   else
2941     data.is_early = FALSE;
2942
2943   /* see if we need to generate SR or RR packets */
2944   if (is_rtcp_time (sess, current_time, &data)) {
2945     if (own->received_bye) {
2946       /* generate BYE instead */
2947       GST_DEBUG ("generating BYE message");
2948       session_bye (sess, &data);
2949       sess->sent_bye = TRUE;
2950     } else {
2951       /* loop over all known sources and do something */
2952       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2953           (GHFunc) session_report_blocks, &data);
2954     }
2955   }
2956
2957   if (data.rtcp) {
2958     /* we keep track of the last report time in order to timeout inactive
2959      * receivers or senders */
2960     if (!data.is_early && !data.may_suppress)
2961       sess->last_rtcp_send_time = data.current_time;
2962     sess->first_rtcp = FALSE;
2963     sess->next_early_rtcp_time = GST_CLOCK_TIME_NONE;
2964
2965     /* add SDES for this source when not already added */
2966     if (!data.has_sdes)
2967       session_sdes (sess, &data);
2968   }
2969
2970   /* check for outdated collisions */
2971   GST_DEBUG ("Timing out collisions");
2972   rtp_source_timeout (sess->source, current_time,
2973       data.interval * RTCP_INTERVAL_COLLISION_TIMEOUT,
2974       running_time - sess->rtcp_feedback_retention_window);
2975
2976   if (sess->change_ssrc) {
2977     GST_DEBUG ("need to change our SSRC (%08x)", own->ssrc);
2978     g_hash_table_steal (sess->ssrcs[sess->mask_idx],
2979         GINT_TO_POINTER (own->ssrc));
2980
2981     own->ssrc = rtp_session_create_new_ssrc (sess);
2982     rtp_source_reset (own);
2983
2984     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
2985         GINT_TO_POINTER (own->ssrc), own);
2986
2987     g_free (sess->bye_reason);
2988     sess->bye_reason = NULL;
2989     sess->sent_bye = FALSE;
2990     sess->change_ssrc = FALSE;
2991     notify = TRUE;
2992     GST_DEBUG ("changed our SSRC to %08x", own->ssrc);
2993   }
2994
2995   sess->allow_early = TRUE;
2996
2997   RTP_SESSION_UNLOCK (sess);
2998
2999   if (notify)
3000     g_object_notify (G_OBJECT (sess), "internal-ssrc");
3001
3002   /* push out the RTCP packet */
3003   if (data.rtcp) {
3004     gboolean do_not_suppress;
3005
3006     /* Give the user a change to add its own packet */
3007     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_RTCP], 0,
3008         data.rtcp, data.is_early, &do_not_suppress);
3009
3010     if (sess->callbacks.send_rtcp && (do_not_suppress || !data.may_suppress)) {
3011       guint packet_size;
3012
3013       /* close the RTCP packet */
3014       gst_rtcp_buffer_end (data.rtcp);
3015
3016       packet_size = GST_BUFFER_SIZE (data.rtcp) + sess->header_len;
3017
3018       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, packet_size);
3019       GST_DEBUG ("%p, sending RTCP packet, avg size %u, %u", &sess->stats,
3020           sess->stats.avg_rtcp_packet_size, packet_size);
3021       result =
3022           sess->callbacks.send_rtcp (sess, own, data.rtcp, sess->sent_bye,
3023           sess->send_rtcp_user_data);
3024     } else {
3025       GST_DEBUG ("freeing packet callback: %p"
3026           " do_not_suppress: %d may_suppress: %d",
3027           sess->callbacks.send_rtcp, do_not_suppress, data.may_suppress);
3028       gst_buffer_unref (data.rtcp);
3029     }
3030   }
3031
3032   return result;
3033 }
3034
3035 void
3036 rtp_session_request_early_rtcp (RTPSession * sess, GstClockTime current_time,
3037     GstClockTimeDiff max_delay)
3038 {
3039   GstClockTime T_dither_max;
3040
3041   /* Implements the algorithm described in RFC 4585 section 3.5.2 */
3042
3043   RTP_SESSION_LOCK (sess);
3044
3045   /* Check if already requested */
3046   /*  RFC 4585 section 3.5.2 step 2 */
3047   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3048     goto dont_send;
3049
3050   /* Ignore the request a scheduled packet will be in time anyway */
3051   if (current_time + max_delay > sess->next_rtcp_check_time)
3052     goto dont_send;
3053
3054   /*  RFC 4585 section 3.5.2 step 2b */
3055   /* If the total sources is <=2, then there is only us and one peer */
3056   if (sess->total_sources <= 2) {
3057     T_dither_max = 0;
3058   } else {
3059     /* Divide by 2 because l = 0.5 */
3060     T_dither_max = sess->next_rtcp_check_time - sess->last_rtcp_send_time;
3061     T_dither_max /= 2;
3062   }
3063
3064   /*  RFC 4585 section 3.5.2 step 3 */
3065   if (current_time + T_dither_max > sess->next_rtcp_check_time)
3066     goto dont_send;
3067
3068   /*  RFC 4585 section 3.5.2 step 4 */
3069   if (sess->allow_early == FALSE)
3070     goto dont_send;
3071
3072   if (T_dither_max) {
3073     /* Schedule an early transmission later */
3074     sess->next_early_rtcp_time = g_random_double () * T_dither_max +
3075         current_time;
3076   } else {
3077     /* If no dithering, schedule it for NOW */
3078     sess->next_early_rtcp_time = current_time;
3079   }
3080
3081   RTP_SESSION_UNLOCK (sess);
3082
3083   /* notify app of need to send packet early
3084    * and therefore of timeout change */
3085   if (sess->callbacks.reconsider)
3086     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
3087
3088   return;
3089
3090 dont_send:
3091
3092   RTP_SESSION_UNLOCK (sess);
3093
3094 }
3095
3096 void
3097 rtp_session_request_key_unit (RTPSession * sess, guint32 ssrc, gboolean fir)
3098 {
3099   guint i;
3100
3101   if (fir)
3102     return;
3103
3104   for (i = 0; i < sess->rtcp_pli_requests->len; i++)
3105     if (ssrc == g_array_index (sess->rtcp_pli_requests, guint32, i))
3106       return;
3107
3108   g_array_append_val (sess->rtcp_pli_requests, ssrc);
3109 }
3110
3111 static gboolean
3112 has_pli_compare_func (gconstpointer a, gconstpointer ignored)
3113 {
3114   GstRTCPPacket packet;
3115
3116   packet.buffer = (GstBuffer *) a;
3117   packet.offset = 0;
3118
3119   if (gst_rtcp_packet_get_type (&packet) == GST_RTCP_TYPE_PSFB &&
3120       gst_rtcp_packet_fb_get_type (&packet) == GST_RTCP_PSFB_TYPE_PLI)
3121     return TRUE;
3122   else
3123     return FALSE;
3124 }
3125
3126 static gboolean
3127 rtp_session_on_sending_rtcp (RTPSession * sess, GstBuffer * buffer,
3128     gboolean early)
3129 {
3130   gboolean ret = FALSE;
3131
3132   RTP_SESSION_LOCK (sess);
3133
3134   while (sess->rtcp_pli_requests->len) {
3135     GstRTCPPacket rtcppacket;
3136     guint media_ssrc = g_array_index (sess->rtcp_pli_requests, guint32, 0);
3137     RTPSource *media_src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
3138         GUINT_TO_POINTER (media_ssrc));
3139
3140     if (media_src && !rtp_source_has_retained (media_src,
3141             has_pli_compare_func, NULL)) {
3142       if (gst_rtcp_buffer_add_packet (buffer, GST_RTCP_TYPE_PSFB, &rtcppacket)) {
3143         gst_rtcp_packet_fb_set_type (&rtcppacket, GST_RTCP_PSFB_TYPE_PLI);
3144         gst_rtcp_packet_fb_set_sender_ssrc (&rtcppacket,
3145             rtp_source_get_ssrc (sess->source));
3146         gst_rtcp_packet_fb_set_media_ssrc (&rtcppacket, media_ssrc);
3147         ret = TRUE;
3148       } else {
3149         /* Break because the packet is full, will put next request in a
3150          * further packet
3151          */
3152         break;
3153       }
3154     }
3155
3156     g_array_remove_index (sess->rtcp_pli_requests, 0);
3157   }
3158
3159   RTP_SESSION_UNLOCK (sess);
3160
3161   return ret;
3162 }
3163
3164 static void
3165 rtp_session_send_rtcp (RTPSession * sess, GstClockTimeDiff max_delay)
3166 {
3167   GstClockTime now;
3168
3169   if (!sess->callbacks.send_rtcp)
3170     return;
3171
3172   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
3173
3174   rtp_session_request_early_rtcp (sess, now, max_delay);
3175 }