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