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