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