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