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