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