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