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