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