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