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