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