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