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