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