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