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