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