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