session: small cleanup
[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   /* report the new source ASAP */
1293   src->generation = sess->generation;
1294   /* we have one more source now */
1295   sess->total_sources++;
1296   if (RTP_SOURCE_IS_ACTIVE (src))
1297     sess->stats.active_sources++;
1298   if (src->internal) {
1299     sess->stats.internal_sources++;
1300     if (sess->suggested_ssrc != src->ssrc)
1301       sess->suggested_ssrc = src->ssrc;
1302   }
1303 }
1304
1305 /* must be called with the session lock, the returned source needs to be
1306  * unreffed after usage. */
1307 static RTPSource *
1308 obtain_source (RTPSession * sess, guint32 ssrc, gboolean * created,
1309     RTPArrivalStats * arrival, gboolean rtp)
1310 {
1311   RTPSource *source;
1312
1313   source = find_source (sess, ssrc);
1314   if (source == NULL) {
1315     /* make new Source in probation and insert */
1316     source = rtp_source_new (ssrc);
1317
1318     GST_DEBUG ("creating new source %08x %p", ssrc, source);
1319
1320     /* for RTP packets we need to set the source in probation. Receiving RTCP
1321      * packets of an SSRC, on the other hand, is a strong indication that we
1322      * are dealing with a valid source. */
1323     if (rtp)
1324       g_object_set (source, "probation", sess->probation, NULL);
1325     else
1326       g_object_set (source, "probation", 0, NULL);
1327
1328     /* store from address, if any */
1329     if (arrival->address) {
1330       if (rtp)
1331         rtp_source_set_rtp_from (source, arrival->address);
1332       else
1333         rtp_source_set_rtcp_from (source, arrival->address);
1334     }
1335
1336     /* configure a callback on the source */
1337     rtp_source_set_callbacks (source, &callbacks, sess);
1338
1339     add_source (sess, source);
1340     *created = TRUE;
1341   } else {
1342     *created = FALSE;
1343     /* check for collision, this updates the address when not previously set */
1344     if (check_collision (sess, source, arrival, rtp)) {
1345       return NULL;
1346     }
1347     /* Receiving RTCP packets of an SSRC is a strong indication that we
1348      * are dealing with a valid source. */
1349     if (!rtp)
1350       g_object_set (source, "probation", 0, NULL);
1351   }
1352   /* update last activity */
1353   source->last_activity = arrival->current_time;
1354   if (rtp)
1355     source->last_rtp_activity = arrival->current_time;
1356   g_object_ref (source);
1357
1358   return source;
1359 }
1360
1361 /* must be called with the session lock, the returned source needs to be
1362  * unreffed after usage. */
1363 static RTPSource *
1364 obtain_internal_source (RTPSession * sess, guint32 ssrc, gboolean * created)
1365 {
1366   RTPSource *source;
1367
1368   source = find_source (sess, ssrc);
1369   if (source == NULL) {
1370     /* make new internal Source and insert */
1371     source = rtp_source_new (ssrc);
1372
1373     GST_DEBUG ("creating new internal source %08x %p", ssrc, source);
1374
1375     source->validated = TRUE;
1376     source->internal = TRUE;
1377     rtp_source_set_sdes_struct (source, gst_structure_copy (sess->sdes));
1378     rtp_source_set_callbacks (source, &callbacks, sess);
1379
1380     add_source (sess, source);
1381     *created = TRUE;
1382   } else {
1383     *created = FALSE;
1384   }
1385   g_object_ref (source);
1386
1387   return source;
1388 }
1389
1390 /**
1391  * rtp_session_suggest_ssrc:
1392  * @sess: a #RTPSession
1393  *
1394  * Suggest an unused SSRC in @sess.
1395  *
1396  * Returns: a free unused SSRC
1397  */
1398 guint32
1399 rtp_session_suggest_ssrc (RTPSession * sess)
1400 {
1401   guint32 result;
1402
1403   g_return_val_if_fail (RTP_IS_SESSION (sess), 0);
1404
1405   RTP_SESSION_LOCK (sess);
1406   result = sess->suggested_ssrc;
1407   RTP_SESSION_UNLOCK (sess);
1408
1409   return result;
1410 }
1411
1412 /**
1413  * rtp_session_add_source:
1414  * @sess: a #RTPSession
1415  * @src: #RTPSource to add
1416  *
1417  * Add @src to @session.
1418  *
1419  * Returns: %TRUE on success, %FALSE if a source with the same SSRC already
1420  * existed in the session.
1421  */
1422 gboolean
1423 rtp_session_add_source (RTPSession * sess, RTPSource * src)
1424 {
1425   gboolean result = FALSE;
1426   RTPSource *find;
1427
1428   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1429   g_return_val_if_fail (src != NULL, FALSE);
1430
1431   RTP_SESSION_LOCK (sess);
1432   find = find_source (sess, src->ssrc);
1433   if (find == NULL) {
1434     add_source (sess, src);
1435     result = TRUE;
1436   }
1437   RTP_SESSION_UNLOCK (sess);
1438
1439   return result;
1440 }
1441
1442 /**
1443  * rtp_session_get_num_sources:
1444  * @sess: an #RTPSession
1445  *
1446  * Get the number of sources in @sess.
1447  *
1448  * Returns: The number of sources in @sess.
1449  */
1450 guint
1451 rtp_session_get_num_sources (RTPSession * sess)
1452 {
1453   guint result;
1454
1455   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1456
1457   RTP_SESSION_LOCK (sess);
1458   result = sess->total_sources;
1459   RTP_SESSION_UNLOCK (sess);
1460
1461   return result;
1462 }
1463
1464 /**
1465  * rtp_session_get_num_active_sources:
1466  * @sess: an #RTPSession
1467  *
1468  * Get the number of active sources in @sess. A source is considered active when
1469  * it has been validated and has not yet received a BYE RTCP message.
1470  *
1471  * Returns: The number of active sources in @sess.
1472  */
1473 guint
1474 rtp_session_get_num_active_sources (RTPSession * sess)
1475 {
1476   guint result;
1477
1478   g_return_val_if_fail (RTP_IS_SESSION (sess), 0);
1479
1480   RTP_SESSION_LOCK (sess);
1481   result = sess->stats.active_sources;
1482   RTP_SESSION_UNLOCK (sess);
1483
1484   return result;
1485 }
1486
1487 /**
1488  * rtp_session_get_source_by_ssrc:
1489  * @sess: an #RTPSession
1490  * @ssrc: an SSRC
1491  *
1492  * Find the source with @ssrc in @sess.
1493  *
1494  * Returns: a #RTPSource with SSRC @ssrc or NULL if the source was not found.
1495  * g_object_unref() after usage.
1496  */
1497 RTPSource *
1498 rtp_session_get_source_by_ssrc (RTPSession * sess, guint32 ssrc)
1499 {
1500   RTPSource *result;
1501
1502   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1503
1504   RTP_SESSION_LOCK (sess);
1505   result = find_source (sess, ssrc);
1506   if (result)
1507     g_object_ref (result);
1508   RTP_SESSION_UNLOCK (sess);
1509
1510   return result;
1511 }
1512
1513 /* should be called with the SESSION lock */
1514 static guint32
1515 rtp_session_create_new_ssrc (RTPSession * sess)
1516 {
1517   guint32 ssrc;
1518
1519   while (TRUE) {
1520     ssrc = g_random_int ();
1521
1522     /* see if it exists in the session, we're done if it doesn't */
1523     if (find_source (sess, ssrc) == NULL)
1524       break;
1525   }
1526   return ssrc;
1527 }
1528
1529
1530 /**
1531  * rtp_session_create_source:
1532  * @sess: an #RTPSession
1533  *
1534  * Create an #RTPSource for use in @sess. This function will create a source
1535  * with an ssrc that is currently not used by any participants in the session.
1536  *
1537  * Returns: an #RTPSource.
1538  */
1539 RTPSource *
1540 rtp_session_create_source (RTPSession * sess)
1541 {
1542   guint32 ssrc;
1543   RTPSource *source;
1544
1545   RTP_SESSION_LOCK (sess);
1546   ssrc = rtp_session_create_new_ssrc (sess);
1547   source = rtp_source_new (ssrc);
1548   rtp_source_set_callbacks (source, &callbacks, sess);
1549   /* we need an additional ref for the source in the hashtable */
1550   g_object_ref (source);
1551   add_source (sess, source);
1552   RTP_SESSION_UNLOCK (sess);
1553
1554   return source;
1555 }
1556
1557 /* update the RTPArrivalStats structure with the current time and other bits
1558  * about the current buffer we are handling.
1559  * This function is typically called when a validated packet is received.
1560  * This function should be called with the SESSION_LOCK
1561  */
1562 static void
1563 update_arrival_stats (RTPSession * sess, RTPArrivalStats * arrival,
1564     gboolean rtp, GstBuffer * buffer, GstClockTime current_time,
1565     GstClockTime running_time, guint64 ntpnstime)
1566 {
1567   GstNetAddressMeta *meta;
1568   GstRTPBuffer rtpb = { NULL };
1569
1570   /* get time of arrival */
1571   arrival->current_time = current_time;
1572   arrival->running_time = running_time;
1573   arrival->ntpnstime = ntpnstime;
1574
1575   /* get packet size including header overhead */
1576   arrival->bytes = gst_buffer_get_size (buffer) + sess->header_len;
1577
1578   if (rtp) {
1579     gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtpb);
1580     arrival->payload_len = gst_rtp_buffer_get_payload_len (&rtpb);
1581     gst_rtp_buffer_unmap (&rtpb);
1582   } else {
1583     arrival->payload_len = 0;
1584   }
1585
1586   /* for netbuffer we can store the IP address to check for collisions */
1587   meta = gst_buffer_get_net_address_meta (buffer);
1588   if (arrival->address)
1589     g_object_unref (arrival->address);
1590   if (meta) {
1591     arrival->address = G_SOCKET_ADDRESS (g_object_ref (meta->addr));
1592   } else {
1593     arrival->address = NULL;
1594   }
1595 }
1596
1597 static void
1598 clean_arrival_stats (RTPArrivalStats * arrival)
1599 {
1600   if (arrival->address)
1601     g_object_unref (arrival->address);
1602 }
1603
1604 static gboolean
1605 source_update_active (RTPSession * sess, RTPSource * source,
1606     gboolean prevactive)
1607 {
1608   gboolean active = RTP_SOURCE_IS_ACTIVE (source);
1609   guint32 ssrc = source->ssrc;
1610
1611   if (prevactive == active)
1612     return FALSE;
1613
1614   if (active) {
1615     sess->stats.active_sources++;
1616     GST_DEBUG ("source: %08x became active, %d active sources", ssrc,
1617         sess->stats.active_sources);
1618   } else {
1619     sess->stats.active_sources--;
1620     GST_DEBUG ("source: %08x became inactive, %d active sources", ssrc,
1621         sess->stats.active_sources);
1622   }
1623   return TRUE;
1624 }
1625
1626 static gboolean
1627 source_update_sender (RTPSession * sess, RTPSource * source,
1628     gboolean prevsender)
1629 {
1630   gboolean sender = RTP_SOURCE_IS_SENDER (source);
1631   guint32 ssrc = source->ssrc;
1632
1633   if (prevsender == sender)
1634     return FALSE;
1635
1636   if (sender) {
1637     sess->stats.sender_sources++;
1638     if (source->internal)
1639       sess->stats.internal_sender_sources++;
1640     GST_DEBUG ("source: %08x became sender, %d sender sources", ssrc,
1641         sess->stats.sender_sources);
1642   } else {
1643     sess->stats.sender_sources--;
1644     if (source->internal)
1645       sess->stats.internal_sender_sources--;
1646     GST_DEBUG ("source: %08x became non sender, %d sender sources", ssrc,
1647         sess->stats.sender_sources);
1648   }
1649   return TRUE;
1650 }
1651
1652 /**
1653  * rtp_session_process_rtp:
1654  * @sess: and #RTPSession
1655  * @buffer: an RTP buffer
1656  * @current_time: the current system time
1657  * @running_time: the running_time of @buffer
1658  *
1659  * Process an RTP buffer in the session manager. This function takes ownership
1660  * of @buffer.
1661  *
1662  * Returns: a #GstFlowReturn.
1663  */
1664 GstFlowReturn
1665 rtp_session_process_rtp (RTPSession * sess, GstBuffer * buffer,
1666     GstClockTime current_time, GstClockTime running_time)
1667 {
1668   GstFlowReturn result;
1669   guint32 ssrc;
1670   RTPSource *source;
1671   gboolean created;
1672   gboolean prevsender, prevactive;
1673   RTPArrivalStats arrival = { NULL, };
1674   guint32 csrcs[16];
1675   guint8 i, count;
1676   guint64 oldrate;
1677   GstRTPBuffer rtp = { NULL };
1678
1679   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
1680   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
1681
1682   if (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp))
1683     goto invalid_packet;
1684
1685   /* get SSRC to look up in session database */
1686   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
1687   /* copy available csrc for later */
1688   count = gst_rtp_buffer_get_csrc_count (&rtp);
1689   /* make sure to not overflow our array. An RTP buffer can maximally contain
1690    * 16 CSRCs */
1691   count = MIN (count, 16);
1692
1693   for (i = 0; i < count; i++)
1694     csrcs[i] = gst_rtp_buffer_get_csrc (&rtp, i);
1695
1696   gst_rtp_buffer_unmap (&rtp);
1697
1698   RTP_SESSION_LOCK (sess);
1699 #if 0
1700   /* FIXME, we should simply not update any stats on the BYE
1701    * internal sources */
1702   /* ignore more RTP packets when we left the session */
1703   if (sess->source->marked_bye)
1704     goto ignore;
1705 #endif
1706
1707   /* update arrival stats */
1708   update_arrival_stats (sess, &arrival, TRUE, buffer, current_time,
1709       running_time, -1);
1710
1711   source = obtain_source (sess, ssrc, &created, &arrival, TRUE);
1712   if (!source)
1713     goto collision;
1714
1715   prevsender = RTP_SOURCE_IS_SENDER (source);
1716   prevactive = RTP_SOURCE_IS_ACTIVE (source);
1717   oldrate = source->bitrate;
1718
1719   /* let source process the packet */
1720   result = rtp_source_process_rtp (source, buffer, &arrival);
1721
1722   /* source became active */
1723   if (source_update_active (sess, source, prevactive))
1724     on_ssrc_validated (sess, source);
1725
1726   source_update_sender (sess, source, prevsender);
1727
1728   if (oldrate != source->bitrate)
1729     sess->recalc_bandwidth = TRUE;
1730
1731   if (created)
1732     on_new_ssrc (sess, source);
1733
1734   if (source->validated) {
1735     gboolean created;
1736
1737     /* for validated sources, we add the CSRCs as well */
1738     for (i = 0; i < count; i++) {
1739       guint32 csrc;
1740       RTPSource *csrc_src;
1741
1742       csrc = csrcs[i];
1743
1744       /* get source */
1745       csrc_src = obtain_source (sess, csrc, &created, &arrival, TRUE);
1746       if (!csrc_src)
1747         continue;
1748
1749       if (created) {
1750         GST_DEBUG ("created new CSRC: %08x", csrc);
1751         rtp_source_set_as_csrc (csrc_src);
1752         source_update_active (sess, csrc_src, FALSE);
1753         on_new_ssrc (sess, csrc_src);
1754       }
1755       g_object_unref (csrc_src);
1756     }
1757   }
1758   g_object_unref (source);
1759
1760   RTP_SESSION_UNLOCK (sess);
1761
1762   clean_arrival_stats (&arrival);
1763
1764   return result;
1765
1766   /* ERRORS */
1767 invalid_packet:
1768   {
1769     gst_buffer_unref (buffer);
1770     GST_DEBUG ("invalid RTP packet received");
1771     return GST_FLOW_OK;
1772   }
1773 #if 0
1774 ignore:
1775   {
1776     RTP_SESSION_UNLOCK (sess);
1777     gst_buffer_unref (buffer);
1778     GST_DEBUG ("ignoring RTP packet because we are leaving");
1779     return GST_FLOW_OK;
1780   }
1781 #endif
1782 collision:
1783   {
1784     RTP_SESSION_UNLOCK (sess);
1785     gst_buffer_unref (buffer);
1786     clean_arrival_stats (&arrival);
1787     GST_DEBUG ("ignoring packet because its collisioning");
1788     return GST_FLOW_OK;
1789   }
1790 }
1791
1792 static void
1793 rtp_session_process_rb (RTPSession * sess, RTPSource * source,
1794     GstRTCPPacket * packet, RTPArrivalStats * arrival)
1795 {
1796   guint count, i;
1797
1798   count = gst_rtcp_packet_get_rb_count (packet);
1799   for (i = 0; i < count; i++) {
1800     guint32 ssrc, exthighestseq, jitter, lsr, dlsr;
1801     guint8 fractionlost;
1802     gint32 packetslost;
1803     RTPSource *src;
1804
1805     gst_rtcp_packet_get_rb (packet, i, &ssrc, &fractionlost,
1806         &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
1807
1808     GST_DEBUG ("RB %d: SSRC %08x, jitter %" G_GUINT32_FORMAT, i, ssrc, jitter);
1809
1810     /* find our own source */
1811     src = find_source (sess, ssrc);
1812     if (src == NULL)
1813       continue;
1814
1815     if (src->internal) {
1816       /* only deal with report blocks for our session, we update the stats of
1817        * the sender of the RTCP message. We could also compare our stats against
1818        * the other sender to see if we are better or worse. */
1819       /* FIXME, need to keep track who the RB block is from */
1820       rtp_source_process_rb (source, arrival->ntpnstime, fractionlost,
1821           packetslost, exthighestseq, jitter, lsr, dlsr);
1822     }
1823   }
1824   on_ssrc_active (sess, source);
1825 }
1826
1827 /* A Sender report contains statistics about how the sender is doing. This
1828  * includes timing informataion such as the relation between RTP and NTP
1829  * timestamps and the number of packets/bytes it sent to us.
1830  *
1831  * In this report is also included a set of report blocks related to how this
1832  * sender is receiving data (in case we (or somebody else) is also sending stuff
1833  * to it). This info includes the packet loss, jitter and seqnum. It also
1834  * contains information to calculate the round trip time (LSR/DLSR).
1835  */
1836 static void
1837 rtp_session_process_sr (RTPSession * sess, GstRTCPPacket * packet,
1838     RTPArrivalStats * arrival, gboolean * do_sync)
1839 {
1840   guint32 senderssrc, rtptime, packet_count, octet_count;
1841   guint64 ntptime;
1842   RTPSource *source;
1843   gboolean created, prevsender;
1844
1845   gst_rtcp_packet_sr_get_sender_info (packet, &senderssrc, &ntptime, &rtptime,
1846       &packet_count, &octet_count);
1847
1848   GST_DEBUG ("got SR packet: SSRC %08x, time %" GST_TIME_FORMAT,
1849       senderssrc, GST_TIME_ARGS (arrival->current_time));
1850
1851   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1852   if (!source)
1853     return;
1854
1855   /* don't try to do lip-sync for sources that sent a BYE */
1856   if (RTP_SOURCE_IS_MARKED_BYE (source))
1857     *do_sync = FALSE;
1858   else
1859     *do_sync = TRUE;
1860
1861   prevsender = RTP_SOURCE_IS_SENDER (source);
1862
1863   /* first update the source */
1864   rtp_source_process_sr (source, arrival->current_time, ntptime, rtptime,
1865       packet_count, octet_count);
1866
1867   source_update_sender (sess, source, prevsender);
1868
1869   if (created)
1870     on_new_ssrc (sess, source);
1871
1872   rtp_session_process_rb (sess, source, packet, arrival);
1873   g_object_unref (source);
1874 }
1875
1876 /* A receiver report contains statistics about how a receiver is doing. It
1877  * includes stuff like packet loss, jitter and the seqnum it received last. It
1878  * also contains info to calculate the round trip time.
1879  *
1880  * We are only interested in how the sender of this report is doing wrt to us.
1881  */
1882 static void
1883 rtp_session_process_rr (RTPSession * sess, GstRTCPPacket * packet,
1884     RTPArrivalStats * arrival)
1885 {
1886   guint32 senderssrc;
1887   RTPSource *source;
1888   gboolean created;
1889
1890   senderssrc = gst_rtcp_packet_rr_get_ssrc (packet);
1891
1892   GST_DEBUG ("got RR packet: SSRC %08x", senderssrc);
1893
1894   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1895   if (!source)
1896     return;
1897
1898   if (created)
1899     on_new_ssrc (sess, source);
1900
1901   rtp_session_process_rb (sess, source, packet, arrival);
1902   g_object_unref (source);
1903 }
1904
1905 /* Get SDES items and store them in the SSRC */
1906 static void
1907 rtp_session_process_sdes (RTPSession * sess, GstRTCPPacket * packet,
1908     RTPArrivalStats * arrival)
1909 {
1910   guint items, i, j;
1911   gboolean more_items, more_entries;
1912
1913   items = gst_rtcp_packet_sdes_get_item_count (packet);
1914   GST_DEBUG ("got SDES packet with %d items", items);
1915
1916   more_items = gst_rtcp_packet_sdes_first_item (packet);
1917   i = 0;
1918   while (more_items) {
1919     guint32 ssrc;
1920     gboolean changed, created, prevactive;
1921     RTPSource *source;
1922     GstStructure *sdes;
1923
1924     ssrc = gst_rtcp_packet_sdes_get_ssrc (packet);
1925
1926     GST_DEBUG ("item %d, SSRC %08x", i, ssrc);
1927
1928     changed = FALSE;
1929
1930     /* find src, no probation when dealing with RTCP */
1931     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1932     if (!source)
1933       return;
1934
1935     sdes = gst_structure_new_empty ("application/x-rtp-source-sdes");
1936
1937     more_entries = gst_rtcp_packet_sdes_first_entry (packet);
1938     j = 0;
1939     while (more_entries) {
1940       GstRTCPSDESType type;
1941       guint8 len;
1942       guint8 *data;
1943       gchar *name;
1944       gchar *value;
1945
1946       gst_rtcp_packet_sdes_get_entry (packet, &type, &len, &data);
1947
1948       GST_DEBUG ("entry %d, type %d, len %d, data %.*s", j, type, len, len,
1949           data);
1950
1951       if (type == GST_RTCP_SDES_PRIV) {
1952         name = g_strndup ((const gchar *) &data[1], data[0]);
1953         len -= data[0] + 1;
1954         data += data[0] + 1;
1955       } else {
1956         name = g_strdup (gst_rtcp_sdes_type_to_name (type));
1957       }
1958
1959       value = g_strndup ((const gchar *) data, len);
1960
1961       gst_structure_set (sdes, name, G_TYPE_STRING, value, NULL);
1962
1963       g_free (name);
1964       g_free (value);
1965
1966       more_entries = gst_rtcp_packet_sdes_next_entry (packet);
1967       j++;
1968     }
1969
1970     /* takes ownership of sdes */
1971     changed = rtp_source_set_sdes_struct (source, sdes);
1972
1973     prevactive = RTP_SOURCE_IS_ACTIVE (source);
1974     source->validated = TRUE;
1975
1976     if (created)
1977       on_new_ssrc (sess, source);
1978
1979     /* source became active */
1980     if (source_update_active (sess, source, prevactive))
1981       on_ssrc_validated (sess, source);
1982
1983     if (changed)
1984       on_ssrc_sdes (sess, source);
1985
1986     g_object_unref (source);
1987
1988     more_items = gst_rtcp_packet_sdes_next_item (packet);
1989     i++;
1990   }
1991 }
1992
1993 /* BYE is sent when a client leaves the session
1994  */
1995 static void
1996 rtp_session_process_bye (RTPSession * sess, GstRTCPPacket * packet,
1997     RTPArrivalStats * arrival)
1998 {
1999   guint count, i;
2000   gchar *reason;
2001   gboolean reconsider = FALSE;
2002
2003   reason = gst_rtcp_packet_bye_get_reason (packet);
2004   GST_DEBUG ("got BYE packet (reason: %s)", GST_STR_NULL (reason));
2005
2006   count = gst_rtcp_packet_bye_get_ssrc_count (packet);
2007   for (i = 0; i < count; i++) {
2008     guint32 ssrc;
2009     RTPSource *source;
2010     gboolean created, prevactive, prevsender;
2011     guint pmembers, members;
2012
2013     ssrc = gst_rtcp_packet_bye_get_nth_ssrc (packet, i);
2014     GST_DEBUG ("SSRC: %08x", ssrc);
2015
2016     /* find src and mark bye, no probation when dealing with RTCP */
2017     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
2018     if (!source)
2019       return;
2020
2021     if (source->internal) {
2022       /* our own source, something weird with this packet */
2023       g_object_unref (source);
2024       continue;
2025     }
2026
2027     /* store time for when we need to time out this source */
2028     source->bye_time = arrival->current_time;
2029
2030     prevactive = RTP_SOURCE_IS_ACTIVE (source);
2031     prevsender = RTP_SOURCE_IS_SENDER (source);
2032
2033     /* mark the source BYE */
2034     rtp_source_mark_bye (source, reason);
2035
2036     pmembers = sess->stats.active_sources;
2037
2038     source_update_active (sess, source, prevactive);
2039     source_update_sender (sess, source, prevsender);
2040
2041     members = sess->stats.active_sources;
2042
2043     if (!sess->scheduled_bye && members < pmembers) {
2044       /* some members went away since the previous timeout estimate.
2045        * Perform reverse reconsideration but only when we are not scheduling a
2046        * BYE ourselves. */
2047       if (sess->next_rtcp_check_time != GST_CLOCK_TIME_NONE &&
2048           arrival->current_time < sess->next_rtcp_check_time) {
2049         GstClockTime time_remaining;
2050
2051         time_remaining = sess->next_rtcp_check_time - arrival->current_time;
2052         sess->next_rtcp_check_time =
2053             gst_util_uint64_scale (time_remaining, members, pmembers);
2054
2055         GST_DEBUG ("reverse reconsideration %" GST_TIME_FORMAT,
2056             GST_TIME_ARGS (sess->next_rtcp_check_time));
2057
2058         sess->next_rtcp_check_time += arrival->current_time;
2059
2060         /* mark pending reconsider. We only want to signal the reconsideration
2061          * once after we handled all the source in the bye packet */
2062         reconsider = TRUE;
2063       }
2064     }
2065
2066     if (created)
2067       on_new_ssrc (sess, source);
2068
2069     on_bye_ssrc (sess, source);
2070
2071     g_object_unref (source);
2072   }
2073   if (reconsider) {
2074     RTP_SESSION_UNLOCK (sess);
2075     /* notify app of reconsideration */
2076     if (sess->callbacks.reconsider)
2077       sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2078     RTP_SESSION_LOCK (sess);
2079   }
2080   g_free (reason);
2081 }
2082
2083 static void
2084 rtp_session_process_app (RTPSession * sess, GstRTCPPacket * packet,
2085     RTPArrivalStats * arrival)
2086 {
2087   GST_DEBUG ("received APP");
2088 }
2089
2090 static gboolean
2091 rtp_session_request_local_key_unit (RTPSession * sess, RTPSource * src,
2092     gboolean fir, GstClockTime current_time)
2093 {
2094   guint32 round_trip = 0;
2095
2096   rtp_source_get_last_rb (src, NULL, NULL, NULL, NULL, NULL, NULL, &round_trip);
2097
2098   if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE && round_trip) {
2099     GstClockTime round_trip_in_ns = gst_util_uint64_scale (round_trip,
2100         GST_SECOND, 65536);
2101
2102     if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2103         current_time - sess->last_keyframe_request < 2 * round_trip_in_ns) {
2104       GST_DEBUG ("Ignoring %s request because one was send without one "
2105           "RTT (%" GST_TIME_FORMAT " < %" GST_TIME_FORMAT ")",
2106           fir ? "FIR" : "PLI",
2107           GST_TIME_ARGS (current_time - sess->last_keyframe_request),
2108           GST_TIME_ARGS (round_trip_in_ns));;
2109       return FALSE;
2110     }
2111   }
2112
2113   sess->last_keyframe_request = current_time;
2114
2115   GST_LOG ("received %s request from %X %p(%p)", fir ? "FIR" : "PLI",
2116       rtp_source_get_ssrc (src), sess->callbacks.process_rtp,
2117       sess->callbacks.request_key_unit);
2118
2119   RTP_SESSION_UNLOCK (sess);
2120   sess->callbacks.request_key_unit (sess, fir,
2121       sess->request_key_unit_user_data);
2122   RTP_SESSION_LOCK (sess);
2123
2124   return TRUE;
2125 }
2126
2127 static void
2128 rtp_session_process_pli (RTPSession * sess, guint32 sender_ssrc,
2129     guint32 media_ssrc, GstClockTime current_time)
2130 {
2131   RTPSource *src;
2132
2133   if (!sess->callbacks.request_key_unit)
2134     return;
2135
2136   src = find_source (sess, sender_ssrc);
2137   if (!src)
2138     return;
2139
2140   rtp_session_request_local_key_unit (sess, src, FALSE, current_time);
2141 }
2142
2143 static void
2144 rtp_session_process_fir (RTPSession * sess, guint32 sender_ssrc,
2145     guint8 * fci_data, guint fci_length, GstClockTime current_time)
2146 {
2147   RTPSource *src;
2148   guint32 ssrc;
2149   guint position = 0;
2150   gboolean our_request = FALSE;
2151
2152   if (!sess->callbacks.request_key_unit)
2153     return;
2154
2155   if (fci_length < 8)
2156     return;
2157
2158   src = find_source (sess, sender_ssrc);
2159
2160   /* Hack because Google fails to set the sender_ssrc correctly */
2161   if (!src && sender_ssrc == 1) {
2162     GHashTableIter iter;
2163
2164     /* we can't find the source if there are multiple */
2165     if (sess->stats.sender_sources > sess->stats.internal_sender_sources + 1)
2166       return;
2167
2168     g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
2169     while (g_hash_table_iter_next (&iter, NULL, (gpointer *) & src)) {
2170       if (!src->internal && rtp_source_is_sender (src))
2171         break;
2172       src = NULL;
2173     }
2174   }
2175   if (!src)
2176     return;
2177
2178   for (position = 0; position < fci_length; position += 8) {
2179     guint8 *data = fci_data + position;
2180     RTPSource *own;
2181
2182     ssrc = GST_READ_UINT32_BE (data);
2183
2184     own = find_source (sess, ssrc);
2185     if (own->internal) {
2186       our_request = TRUE;
2187       break;
2188     }
2189   }
2190   if (!our_request)
2191     return;
2192
2193   rtp_session_request_local_key_unit (sess, src, TRUE, current_time);
2194 }
2195
2196 static void
2197 rtp_session_process_feedback (RTPSession * sess, GstRTCPPacket * packet,
2198     RTPArrivalStats * arrival, GstClockTime current_time)
2199 {
2200   GstRTCPType type = gst_rtcp_packet_get_type (packet);
2201   GstRTCPFBType fbtype = gst_rtcp_packet_fb_get_type (packet);
2202   guint32 sender_ssrc = gst_rtcp_packet_fb_get_sender_ssrc (packet);
2203   guint32 media_ssrc = gst_rtcp_packet_fb_get_media_ssrc (packet);
2204   guint8 *fci_data = gst_rtcp_packet_fb_get_fci (packet);
2205   guint fci_length = 4 * gst_rtcp_packet_fb_get_fci_length (packet);
2206   RTPSource *src;
2207
2208   GST_DEBUG ("received feedback %d:%d from %08X about %08X with FCI of "
2209       "length %d", type, fbtype, sender_ssrc, media_ssrc, fci_length);
2210
2211   if (g_signal_has_handler_pending (sess,
2212           rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0, TRUE)) {
2213     GstBuffer *fci_buffer = NULL;
2214
2215     if (fci_length > 0) {
2216       fci_buffer = gst_buffer_copy_region (packet->rtcp->buffer,
2217           GST_BUFFER_COPY_MEMORY, fci_data - packet->rtcp->map.data,
2218           fci_length);
2219       GST_BUFFER_TIMESTAMP (fci_buffer) = arrival->running_time;
2220     }
2221
2222     RTP_SESSION_UNLOCK (sess);
2223     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0,
2224         type, fbtype, sender_ssrc, media_ssrc, fci_buffer);
2225     RTP_SESSION_LOCK (sess);
2226
2227     if (fci_buffer)
2228       gst_buffer_unref (fci_buffer);
2229   }
2230
2231   src = find_source (sess, media_ssrc);
2232   if (!src)
2233     return;
2234
2235   if (sess->rtcp_feedback_retention_window) {
2236     rtp_source_retain_rtcp_packet (src, packet, arrival->running_time);
2237   }
2238
2239   if (src->internal ||
2240       /* PSFB FIR puts the media ssrc inside the FCI */
2241       (type == GST_RTCP_TYPE_PSFB && fbtype == GST_RTCP_PSFB_TYPE_FIR)) {
2242     switch (type) {
2243       case GST_RTCP_TYPE_PSFB:
2244         switch (fbtype) {
2245           case GST_RTCP_PSFB_TYPE_PLI:
2246             rtp_session_process_pli (sess, sender_ssrc, media_ssrc,
2247                 current_time);
2248             break;
2249           case GST_RTCP_PSFB_TYPE_FIR:
2250             rtp_session_process_fir (sess, sender_ssrc, fci_data, fci_length,
2251                 current_time);
2252             break;
2253           default:
2254             break;
2255         }
2256         break;
2257       case GST_RTCP_TYPE_RTPFB:
2258       default:
2259         break;
2260     }
2261   }
2262 }
2263
2264 /**
2265  * rtp_session_process_rtcp:
2266  * @sess: and #RTPSession
2267  * @buffer: an RTCP buffer
2268  * @current_time: the current system time
2269  * @ntpnstime: the current NTP time in nanoseconds
2270  *
2271  * Process an RTCP buffer in the session manager. This function takes ownership
2272  * of @buffer.
2273  *
2274  * Returns: a #GstFlowReturn.
2275  */
2276 GstFlowReturn
2277 rtp_session_process_rtcp (RTPSession * sess, GstBuffer * buffer,
2278     GstClockTime current_time, guint64 ntpnstime)
2279 {
2280   GstRTCPPacket packet;
2281   gboolean more, is_bye = FALSE, do_sync = FALSE;
2282   RTPArrivalStats arrival = { NULL, };
2283   GstFlowReturn result = GST_FLOW_OK;
2284   GstRTCPBuffer rtcp = { NULL, };
2285
2286   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2287   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
2288
2289   if (!gst_rtcp_buffer_validate (buffer))
2290     goto invalid_packet;
2291
2292   GST_DEBUG ("received RTCP packet");
2293
2294   RTP_SESSION_LOCK (sess);
2295   /* update arrival stats */
2296   update_arrival_stats (sess, &arrival, FALSE, buffer, current_time, -1,
2297       ntpnstime);
2298
2299 #if 0
2300   /* FIXME, simply ignore RTCP for iternal sources with BYE */
2301   if (sess->source->sent_bye)
2302     goto ignore;
2303 #endif
2304
2305   /* start processing the compound packet */
2306   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
2307   more = gst_rtcp_buffer_get_first_packet (&rtcp, &packet);
2308   while (more) {
2309     GstRTCPType type;
2310
2311     type = gst_rtcp_packet_get_type (&packet);
2312
2313     /* when we are leaving the session, we should ignore all non-BYE messages */
2314     if (sess->scheduled_bye && type != GST_RTCP_TYPE_BYE) {
2315       GST_DEBUG ("ignoring non-BYE RTCP packet because we are leaving");
2316       goto next;
2317     }
2318
2319     switch (type) {
2320       case GST_RTCP_TYPE_SR:
2321         rtp_session_process_sr (sess, &packet, &arrival, &do_sync);
2322         break;
2323       case GST_RTCP_TYPE_RR:
2324         rtp_session_process_rr (sess, &packet, &arrival);
2325         break;
2326       case GST_RTCP_TYPE_SDES:
2327         rtp_session_process_sdes (sess, &packet, &arrival);
2328         break;
2329       case GST_RTCP_TYPE_BYE:
2330         is_bye = TRUE;
2331         /* don't try to attempt lip-sync anymore for streams with a BYE */
2332         do_sync = FALSE;
2333         rtp_session_process_bye (sess, &packet, &arrival);
2334         break;
2335       case GST_RTCP_TYPE_APP:
2336         rtp_session_process_app (sess, &packet, &arrival);
2337         break;
2338       case GST_RTCP_TYPE_RTPFB:
2339       case GST_RTCP_TYPE_PSFB:
2340         rtp_session_process_feedback (sess, &packet, &arrival, current_time);
2341         break;
2342       default:
2343         GST_WARNING ("got unknown RTCP packet");
2344         break;
2345     }
2346   next:
2347     more = gst_rtcp_packet_move_to_next (&packet);
2348   }
2349
2350   gst_rtcp_buffer_unmap (&rtcp);
2351
2352   /* if we are scheduling a BYE, we only want to count bye packets, else we
2353    * count everything */
2354   if (sess->scheduled_bye) {
2355     if (is_bye) {
2356       sess->stats.bye_members++;
2357       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2358     }
2359   } else {
2360     /* keep track of average packet size */
2361     UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2362   }
2363   GST_DEBUG ("%p, received RTCP packet, avg size %u, %u", &sess->stats,
2364       sess->stats.avg_rtcp_packet_size, arrival.bytes);
2365   RTP_SESSION_UNLOCK (sess);
2366
2367   clean_arrival_stats (&arrival);
2368
2369   /* notify caller of sr packets in the callback */
2370   if (do_sync && sess->callbacks.sync_rtcp) {
2371     /* make writable, we might want to change the buffer */
2372     buffer = gst_buffer_make_writable (buffer);
2373
2374     result = sess->callbacks.sync_rtcp (sess, buffer,
2375         sess->sync_rtcp_user_data);
2376   } else
2377     gst_buffer_unref (buffer);
2378
2379   return result;
2380
2381   /* ERRORS */
2382 invalid_packet:
2383   {
2384     GST_DEBUG ("invalid RTCP packet received");
2385     gst_buffer_unref (buffer);
2386     return GST_FLOW_OK;
2387   }
2388 #if 0
2389 ignore:
2390   {
2391     RTP_SESSION_UNLOCK (sess);
2392     gst_buffer_unref (buffer);
2393     clean_arrival_stats (&arrival);
2394     GST_DEBUG ("ignoring RTCP packet because we left");
2395     return GST_FLOW_OK;
2396   }
2397 #endif
2398 }
2399
2400 /**
2401  * rtp_session_update_send_caps:
2402  * @sess: an #RTPSession
2403  * @caps: a #GstCaps
2404  *
2405  * Update the caps of the sender in the rtp session.
2406  */
2407 void
2408 rtp_session_update_send_caps (RTPSession * sess, GstCaps * caps)
2409 {
2410   GstStructure *s;
2411   guint ssrc;
2412
2413   g_return_if_fail (RTP_IS_SESSION (sess));
2414   g_return_if_fail (GST_IS_CAPS (caps));
2415
2416   GST_LOG ("received caps %" GST_PTR_FORMAT, caps);
2417
2418   s = gst_caps_get_structure (caps, 0);
2419
2420   if (gst_structure_get_uint (s, "ssrc", &ssrc)) {
2421     RTPSource *source;
2422     gboolean created;
2423
2424     RTP_SESSION_LOCK (sess);
2425     source = obtain_internal_source (sess, ssrc, &created);
2426     if (source) {
2427       rtp_source_update_caps (source, caps);
2428       g_object_unref (source);
2429     }
2430     RTP_SESSION_UNLOCK (sess);
2431   }
2432 }
2433
2434 /**
2435  * rtp_session_send_rtp:
2436  * @sess: an #RTPSession
2437  * @data: pointer to either an RTP buffer or a list of RTP buffers
2438  * @is_list: TRUE when @data is a buffer list
2439  * @current_time: the current system time
2440  * @running_time: the running time of @data
2441  *
2442  * Send the RTP buffer in the session manager. This function takes ownership of
2443  * @buffer.
2444  *
2445  * Returns: a #GstFlowReturn.
2446  */
2447 GstFlowReturn
2448 rtp_session_send_rtp (RTPSession * sess, gpointer data, gboolean is_list,
2449     GstClockTime current_time, GstClockTime running_time)
2450 {
2451   GstFlowReturn result;
2452   RTPSource *source;
2453   gboolean prevsender;
2454   guint64 oldrate;
2455   GstBuffer *buffer;
2456   GstRTPBuffer rtp = { NULL };
2457   guint32 ssrc;
2458   gboolean created;
2459
2460   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2461   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
2462
2463   GST_LOG ("received RTP %s for sending", is_list ? "list" : "packet");
2464
2465   if (is_list) {
2466     GstBufferList *list = GST_BUFFER_LIST_CAST (data);
2467
2468     buffer = gst_buffer_list_get (list, 0);
2469     if (!buffer)
2470       goto no_buffer;
2471   } else {
2472     buffer = GST_BUFFER_CAST (data);
2473   }
2474
2475   if (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp))
2476     goto invalid_packet;
2477
2478   /* get SSRC and look up in session database */
2479   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
2480
2481   gst_rtp_buffer_unmap (&rtp);
2482
2483   RTP_SESSION_LOCK (sess);
2484   source = obtain_internal_source (sess, ssrc, &created);
2485
2486   /* update last activity */
2487   source->last_rtp_activity = current_time;
2488
2489   prevsender = RTP_SOURCE_IS_SENDER (source);
2490   oldrate = source->bitrate;
2491
2492   /* we use our own source to send */
2493   result = rtp_source_send_rtp (source, data, is_list, running_time);
2494
2495   source_update_sender (sess, source, prevsender);
2496
2497   if (oldrate != source->bitrate)
2498     sess->recalc_bandwidth = TRUE;
2499   RTP_SESSION_UNLOCK (sess);
2500
2501   g_object_unref (source);
2502
2503   return result;
2504
2505 invalid_packet:
2506   {
2507     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
2508     GST_DEBUG ("invalid RTP packet received");
2509     return GST_FLOW_OK;
2510   }
2511 no_buffer:
2512   {
2513     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
2514     GST_DEBUG ("no buffer in list");
2515     return GST_FLOW_OK;
2516   }
2517 }
2518
2519 static void
2520 add_bitrates (gpointer key, RTPSource * source, gdouble * bandwidth)
2521 {
2522   *bandwidth += source->bitrate;
2523 }
2524
2525 /* must be called with session lock */
2526 static GstClockTime
2527 calculate_rtcp_interval (RTPSession * sess, gboolean deterministic,
2528     gboolean first)
2529 {
2530   GstClockTime result;
2531
2532   /* recalculate bandwidth when it changed */
2533   if (sess->recalc_bandwidth) {
2534     gdouble bandwidth;
2535
2536     if (sess->bandwidth > 0)
2537       bandwidth = sess->bandwidth;
2538     else {
2539       /* If it is <= 0, then try to estimate the actual bandwidth */
2540       bandwidth = 0;
2541
2542       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2543           (GHFunc) add_bitrates, &bandwidth);
2544       bandwidth /= 8.0;
2545     }
2546     if (bandwidth < 8000)
2547       bandwidth = RTP_STATS_BANDWIDTH;
2548
2549     rtp_stats_set_bandwidths (&sess->stats, bandwidth,
2550         sess->rtcp_bandwidth, sess->rtcp_rs_bandwidth, sess->rtcp_rr_bandwidth);
2551
2552     sess->recalc_bandwidth = FALSE;
2553   }
2554
2555   if (sess->scheduled_bye) {
2556     result = rtp_stats_calculate_bye_interval (&sess->stats);
2557   } else {
2558     result = rtp_stats_calculate_rtcp_interval (&sess->stats,
2559         sess->stats.internal_sender_sources > 0, first);
2560   }
2561
2562   GST_DEBUG ("next deterministic interval: %" GST_TIME_FORMAT ", first %d",
2563       GST_TIME_ARGS (result), first);
2564
2565   if (!deterministic && result != GST_CLOCK_TIME_NONE)
2566     result = rtp_stats_add_rtcp_jitter (&sess->stats, result);
2567
2568   GST_DEBUG ("next interval: %" GST_TIME_FORMAT, GST_TIME_ARGS (result));
2569
2570   return result;
2571 }
2572
2573 static void
2574 source_mark_bye (const gchar * key, RTPSource * source, const gchar * reason)
2575 {
2576   if (source->internal)
2577     rtp_source_mark_bye (source, reason);
2578 }
2579
2580 /**
2581  * rtp_session_mark_all_bye:
2582  * @sess: an #RTPSession
2583  * @reason: a reason
2584  *
2585  * Mark all internal sources of the session as BYE with @reason.
2586  */
2587 void
2588 rtp_session_mark_all_bye (RTPSession * sess, const gchar * reason)
2589 {
2590   g_return_if_fail (RTP_IS_SESSION (sess));
2591
2592   RTP_SESSION_LOCK (sess);
2593   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2594       (GHFunc) source_mark_bye, (gpointer) reason);
2595   RTP_SESSION_UNLOCK (sess);
2596 }
2597
2598 /* Stop the current @sess and schedule a BYE message for the other members.
2599  * One must have the session lock to call this function
2600  */
2601 static GstFlowReturn
2602 rtp_session_schedule_bye_locked (RTPSession * sess, GstClockTime current_time)
2603 {
2604   GstFlowReturn result = GST_FLOW_OK;
2605   GstClockTime interval;
2606
2607   /* nothing to do it we already scheduled bye */
2608   if (sess->scheduled_bye)
2609     goto done;
2610
2611   /* we schedule BYE now */
2612   sess->scheduled_bye = TRUE;
2613   /* at least one member wants to send a BYE */
2614   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
2615   sess->stats.bye_members = 1;
2616   sess->first_rtcp = TRUE;
2617   sess->allow_early = TRUE;
2618
2619   /* reschedule transmission */
2620   sess->last_rtcp_send_time = current_time;
2621   interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2622
2623   if (interval != GST_CLOCK_TIME_NONE)
2624     sess->next_rtcp_check_time = current_time + interval;
2625   else
2626     sess->next_rtcp_check_time = GST_CLOCK_TIME_NONE;
2627
2628   GST_DEBUG ("Schedule BYE for %" GST_TIME_FORMAT ", %" GST_TIME_FORMAT,
2629       GST_TIME_ARGS (interval), GST_TIME_ARGS (sess->next_rtcp_check_time));
2630
2631   RTP_SESSION_UNLOCK (sess);
2632   /* notify app of reconsideration */
2633   if (sess->callbacks.reconsider)
2634     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2635   RTP_SESSION_LOCK (sess);
2636 done:
2637
2638   return result;
2639 }
2640
2641 /**
2642  * rtp_session_schedule_bye:
2643  * @sess: an #RTPSession
2644  * @current_time: the current system time
2645  *
2646  * Schedule a BYE message for all sources marked as BYE in @sess.
2647  *
2648  * Returns: a #GstFlowReturn.
2649  */
2650 GstFlowReturn
2651 rtp_session_schedule_bye (RTPSession * sess, GstClockTime current_time)
2652 {
2653   GstFlowReturn result = GST_FLOW_OK;
2654
2655   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2656
2657   RTP_SESSION_LOCK (sess);
2658   result = rtp_session_schedule_bye_locked (sess, current_time);
2659   RTP_SESSION_UNLOCK (sess);
2660
2661   return result;
2662 }
2663
2664 /**
2665  * rtp_session_next_timeout:
2666  * @sess: an #RTPSession
2667  * @current_time: the current system time
2668  *
2669  * Get the next time we should perform session maintenance tasks.
2670  *
2671  * Returns: a time when rtp_session_on_timeout() should be called with the
2672  * current system time.
2673  */
2674 GstClockTime
2675 rtp_session_next_timeout (RTPSession * sess, GstClockTime current_time)
2676 {
2677   GstClockTime result, interval = 0;
2678
2679   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_CLOCK_TIME_NONE);
2680
2681   RTP_SESSION_LOCK (sess);
2682
2683   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
2684     result = sess->next_early_rtcp_time;
2685     goto early_exit;
2686   }
2687
2688   result = sess->next_rtcp_check_time;
2689
2690   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2691       ", next time: %" GST_TIME_FORMAT,
2692       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2693
2694   if (result == GST_CLOCK_TIME_NONE || result < current_time) {
2695     GST_DEBUG ("take current time as base");
2696     /* our previous check time expired, start counting from the current time
2697      * again. */
2698     result = current_time;
2699   }
2700
2701   if (sess->scheduled_bye) {
2702     if (sess->stats.active_sources >= 50) {
2703       GST_DEBUG ("reconsider BYE, more than 50 sources");
2704       /* reconsider BYE if members >= 50 */
2705       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2706     }
2707   } else {
2708     if (sess->first_rtcp) {
2709       GST_DEBUG ("first RTCP packet");
2710       /* we are called for the first time */
2711       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2712     } else if (sess->next_rtcp_check_time < current_time) {
2713       GST_DEBUG ("old check time expired, getting new timeout");
2714       /* get a new timeout when we need to */
2715       interval = calculate_rtcp_interval (sess, FALSE, FALSE);
2716     }
2717   }
2718
2719   if (interval != GST_CLOCK_TIME_NONE)
2720     result += interval;
2721   else
2722     result = GST_CLOCK_TIME_NONE;
2723
2724   sess->next_rtcp_check_time = result;
2725
2726 early_exit:
2727
2728   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2729       ", next time: %" GST_TIME_FORMAT,
2730       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2731   RTP_SESSION_UNLOCK (sess);
2732
2733   return result;
2734 }
2735
2736 typedef struct
2737 {
2738   RTPSource *source;
2739   gboolean is_bye;
2740   GstBuffer *buffer;
2741 } ReportOutput;
2742
2743 typedef struct
2744 {
2745   GstRTCPBuffer rtcpbuf;
2746   RTPSession *sess;
2747   RTPSource *source;
2748   guint num_to_report;
2749   GstBuffer *rtcp;
2750   GstClockTime current_time;
2751   guint64 ntpnstime;
2752   GstClockTime running_time;
2753   GstClockTime interval;
2754   GstRTCPPacket packet;
2755   gboolean has_sdes;
2756   gboolean is_early;
2757   gboolean may_suppress;
2758   GQueue output;
2759 } ReportData;
2760
2761 static void
2762 session_start_rtcp (RTPSession * sess, ReportData * data)
2763 {
2764   GstRTCPPacket *packet = &data->packet;
2765   RTPSource *own = data->source;
2766   GstRTCPBuffer *rtcp = &data->rtcpbuf;
2767
2768   data->rtcp = gst_rtcp_buffer_new (sess->mtu);
2769   data->has_sdes = FALSE;
2770
2771   gst_rtcp_buffer_map (data->rtcp, GST_MAP_READWRITE, rtcp);
2772
2773   if (RTP_SOURCE_IS_SENDER (own)) {
2774     guint64 ntptime;
2775     guint32 rtptime;
2776     guint32 packet_count, octet_count;
2777
2778     /* we are a sender, create SR */
2779     GST_DEBUG ("create SR for SSRC %08x", own->ssrc);
2780     gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_SR, packet);
2781
2782     /* get latest stats */
2783     rtp_source_get_new_sr (own, data->ntpnstime, data->running_time,
2784         &ntptime, &rtptime, &packet_count, &octet_count);
2785     /* store stats */
2786     rtp_source_process_sr (own, data->current_time, ntptime, rtptime,
2787         packet_count, octet_count);
2788
2789     /* fill in sender report info */
2790     gst_rtcp_packet_sr_set_sender_info (packet, own->ssrc,
2791         ntptime, rtptime, packet_count, octet_count);
2792   } else {
2793     /* we are only receiver, create RR */
2794     GST_DEBUG ("create RR for SSRC %08x", own->ssrc);
2795     gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_RR, packet);
2796     gst_rtcp_packet_rr_set_ssrc (packet, own->ssrc);
2797   }
2798 }
2799
2800 /* construct a Sender or Receiver Report */
2801 static void
2802 session_report_blocks (const gchar * key, RTPSource * source, ReportData * data)
2803 {
2804   RTPSession *sess = data->sess;
2805   GstRTCPPacket *packet = &data->packet;
2806   guint8 fractionlost;
2807   gint32 packetslost;
2808   guint32 exthighestseq, jitter;
2809   guint32 lsr, dlsr;
2810
2811   /* don't report for sources in future generations */
2812   if (((gint16) (source->generation - sess->generation)) > 0) {
2813     GST_DEBUG ("source %08x generation %u > %u", source->ssrc,
2814         source->generation, sess->generation);
2815     return;
2816   }
2817
2818   /* only report about other sender */
2819   if (source == data->source)
2820     goto reported;
2821
2822   if (gst_rtcp_packet_get_rb_count (packet) == GST_RTCP_MAX_RB_COUNT) {
2823     GST_DEBUG ("max RB count reached");
2824     return;
2825   }
2826
2827   if (!RTP_SOURCE_IS_SENDER (source)) {
2828     GST_DEBUG ("source %08x not sender", source->ssrc);
2829     goto reported;
2830   }
2831
2832   GST_DEBUG ("create RB for SSRC %08x", source->ssrc);
2833
2834   /* get new stats */
2835   rtp_source_get_new_rb (source, data->current_time, &fractionlost,
2836       &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
2837
2838   /* store last generated RR packet */
2839   source->last_rr.is_valid = TRUE;
2840   source->last_rr.fractionlost = fractionlost;
2841   source->last_rr.packetslost = packetslost;
2842   source->last_rr.exthighestseq = exthighestseq;
2843   source->last_rr.jitter = jitter;
2844   source->last_rr.lsr = lsr;
2845   source->last_rr.dlsr = dlsr;
2846
2847   /* packet is not yet filled, add report block for this source. */
2848   gst_rtcp_packet_add_rb (packet, source->ssrc, fractionlost, packetslost,
2849       exthighestseq, jitter, lsr, dlsr);
2850
2851 reported:
2852   /* source is reported, move to next generation */
2853   source->generation = sess->generation + 1;
2854
2855   /* if we reported all sources in this generation, move to next */
2856   if (--data->num_to_report == 0) {
2857     sess->generation++;
2858     GST_DEBUG ("all reported, generation now %u", sess->generation);
2859   }
2860 }
2861
2862 /* perform cleanup of sources that timed out */
2863 static void
2864 session_cleanup (const gchar * key, RTPSource * source, ReportData * data)
2865 {
2866   gboolean remove = FALSE;
2867   gboolean byetimeout = FALSE;
2868   gboolean sendertimeout = FALSE;
2869   gboolean is_sender, is_active;
2870   RTPSession *sess = data->sess;
2871   GstClockTime interval, binterval;
2872   GstClockTime btime;
2873
2874   GST_DEBUG ("look at %08x, generation %u", source->ssrc, source->generation);
2875
2876   /* check for outdated collisions */
2877   if (source->internal) {
2878     GST_DEBUG ("Timing out collisions for %x", source->ssrc);
2879     rtp_source_timeout (source, data->current_time,
2880         /* "a relatively long time" -- RFC 3550 section 8.2 */
2881         RTP_STATS_MIN_INTERVAL * GST_SECOND * 10,
2882         data->running_time - sess->rtcp_feedback_retention_window);
2883   }
2884
2885   /* nothing else to do when without RTCP */
2886   if (data->interval == GST_CLOCK_TIME_NONE)
2887     return;
2888
2889   is_sender = RTP_SOURCE_IS_SENDER (source);
2890   is_active = RTP_SOURCE_IS_ACTIVE (source);
2891
2892   /* our own rtcp interval may have been forced low by secondary configuration,
2893    * while sender side may still operate with higher interval,
2894    * so do not just take our interval to decide on timing out sender,
2895    * but take (if data->interval <= 5 * GST_SECOND):
2896    *   interval = CLAMP (sender_interval, data->interval, 5 * GST_SECOND)
2897    * where sender_interval is difference between last 2 received RTCP reports
2898    */
2899   if (data->interval >= 5 * GST_SECOND || source->internal) {
2900     binterval = data->interval;
2901   } else {
2902     GST_LOG ("prev_rtcp %" GST_TIME_FORMAT ", last_rtcp %" GST_TIME_FORMAT,
2903         GST_TIME_ARGS (source->stats.prev_rtcptime),
2904         GST_TIME_ARGS (source->stats.last_rtcptime));
2905     /* if not received enough yet, fallback to larger default */
2906     if (source->stats.last_rtcptime > source->stats.prev_rtcptime)
2907       binterval = source->stats.last_rtcptime - source->stats.prev_rtcptime;
2908     else
2909       binterval = 5 * GST_SECOND;
2910     binterval = CLAMP (binterval, data->interval, 5 * GST_SECOND);
2911   }
2912   GST_LOG ("timeout base interval %" GST_TIME_FORMAT,
2913       GST_TIME_ARGS (binterval));
2914
2915   if (!source->internal) {
2916     if (source->marked_bye) {
2917       /* if we received a BYE from the source, remove the source after some
2918        * time. */
2919       if (data->current_time > source->bye_time &&
2920           data->current_time - source->bye_time > sess->stats.bye_timeout) {
2921         GST_DEBUG ("removing BYE source %08x", source->ssrc);
2922         remove = TRUE;
2923         byetimeout = TRUE;
2924       }
2925     }
2926     /* sources that were inactive for more than 5 times the deterministic reporting
2927      * interval get timed out. the min timeout is 5 seconds. */
2928     /* mind old time that might pre-date last time going to PLAYING */
2929     btime = MAX (source->last_activity, sess->start_time);
2930     if (data->current_time > btime) {
2931       interval = MAX (binterval * 5, 5 * GST_SECOND);
2932       if (data->current_time - btime > interval) {
2933         GST_DEBUG ("removing timeout source %08x, last %" GST_TIME_FORMAT,
2934             source->ssrc, GST_TIME_ARGS (btime));
2935         remove = TRUE;
2936       }
2937     }
2938   }
2939
2940   /* senders that did not send for a long time become a receiver, this also
2941    * holds for our own sources. */
2942   if (is_sender) {
2943     /* mind old time that might pre-date last time going to PLAYING */
2944     btime = MAX (source->last_rtp_activity, sess->start_time);
2945     if (data->current_time > btime) {
2946       interval = MAX (binterval * 2, 5 * GST_SECOND);
2947       if (data->current_time - btime > interval) {
2948         if (source->internal && source->sent_bye) {
2949           /* an internal source is BYE and stopped sending RTP, remove */
2950           GST_DEBUG ("internal BYE source %08x timed out, last %"
2951               GST_TIME_FORMAT, source->ssrc, GST_TIME_ARGS (btime));
2952           remove = TRUE;
2953         } else {
2954           GST_DEBUG ("sender source %08x timed out and became receiver, last %"
2955               GST_TIME_FORMAT, source->ssrc, GST_TIME_ARGS (btime));
2956           sendertimeout = TRUE;
2957         }
2958       }
2959     }
2960   }
2961
2962   if (remove) {
2963     sess->total_sources--;
2964     if (is_sender) {
2965       sess->stats.sender_sources--;
2966       if (source->internal)
2967         sess->stats.internal_sender_sources--;
2968     }
2969     if (is_active)
2970       sess->stats.active_sources--;
2971
2972     if (source->internal)
2973       sess->stats.internal_sources--;
2974
2975     if (byetimeout)
2976       on_bye_timeout (sess, source);
2977     else
2978       on_timeout (sess, source);
2979   } else {
2980     if (sendertimeout) {
2981       source->is_sender = FALSE;
2982       sess->stats.sender_sources--;
2983       if (source->internal)
2984         sess->stats.internal_sender_sources--;
2985
2986       on_sender_timeout (sess, source);
2987     }
2988     /* count how many source to report in this generation */
2989     if (((gint16) (source->generation - sess->generation)) <= 0)
2990       data->num_to_report++;
2991   }
2992   source->closing = remove;
2993 }
2994
2995 static void
2996 session_sdes (RTPSession * sess, ReportData * data)
2997 {
2998   GstRTCPPacket *packet = &data->packet;
2999   const GstStructure *sdes;
3000   gint i, n_fields;
3001   GstRTCPBuffer *rtcp = &data->rtcpbuf;
3002
3003   /* add SDES packet */
3004   gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_SDES, packet);
3005
3006   gst_rtcp_packet_sdes_add_item (packet, data->source->ssrc);
3007
3008   sdes = rtp_source_get_sdes_struct (data->source);
3009
3010   /* add all fields in the structure, the order is not important. */
3011   n_fields = gst_structure_n_fields (sdes);
3012   for (i = 0; i < n_fields; ++i) {
3013     const gchar *field;
3014     const gchar *value;
3015     GstRTCPSDESType type;
3016
3017     field = gst_structure_nth_field_name (sdes, i);
3018     if (field == NULL)
3019       continue;
3020     value = gst_structure_get_string (sdes, field);
3021     if (value == NULL)
3022       continue;
3023     type = gst_rtcp_sdes_name_to_type (field);
3024
3025     /* Early packets are minimal and only include the CNAME */
3026     if (data->is_early && type != GST_RTCP_SDES_CNAME)
3027       continue;
3028
3029     if (type > GST_RTCP_SDES_END && type < GST_RTCP_SDES_PRIV) {
3030       gst_rtcp_packet_sdes_add_entry (packet, type, strlen (value),
3031           (const guint8 *) value);
3032     } else if (type == GST_RTCP_SDES_PRIV) {
3033       gsize prefix_len;
3034       gsize value_len;
3035       gsize data_len;
3036       guint8 data[256];
3037
3038       /* don't accept entries that are too big */
3039       prefix_len = strlen (field);
3040       if (prefix_len > 255)
3041         continue;
3042       value_len = strlen (value);
3043       if (value_len > 255)
3044         continue;
3045       data_len = 1 + prefix_len + value_len;
3046       if (data_len > 255)
3047         continue;
3048
3049       data[0] = prefix_len;
3050       memcpy (&data[1], field, prefix_len);
3051       memcpy (&data[1 + prefix_len], value, value_len);
3052
3053       gst_rtcp_packet_sdes_add_entry (packet, type, data_len, data);
3054     }
3055   }
3056
3057   data->has_sdes = TRUE;
3058 }
3059
3060 /* schedule a BYE packet */
3061 static void
3062 make_source_bye (RTPSession * sess, RTPSource * source, ReportData * data)
3063 {
3064   GstRTCPPacket *packet = &data->packet;
3065   GstRTCPBuffer *rtcp = &data->rtcpbuf;
3066
3067   /* add SDES */
3068   session_sdes (sess, data);
3069   /* add a BYE packet */
3070   gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_BYE, packet);
3071   gst_rtcp_packet_bye_add_ssrc (packet, source->ssrc);
3072   if (source->bye_reason)
3073     gst_rtcp_packet_bye_set_reason (packet, source->bye_reason);
3074
3075   /* we have a BYE packet now */
3076   source->sent_bye = TRUE;
3077 }
3078
3079 static gboolean
3080 is_rtcp_time (RTPSession * sess, GstClockTime current_time, ReportData * data)
3081 {
3082   GstClockTime new_send_time, elapsed;
3083
3084   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3085     data->is_early = TRUE;
3086   else
3087     data->is_early = FALSE;
3088
3089   if (data->is_early && sess->next_early_rtcp_time < current_time)
3090     goto early;
3091
3092   /* no need to check yet */
3093   if (sess->next_rtcp_check_time == GST_CLOCK_TIME_NONE ||
3094       sess->next_rtcp_check_time > current_time) {
3095     GST_DEBUG ("no check time yet, next %" GST_TIME_FORMAT " > now %"
3096         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_rtcp_check_time),
3097         GST_TIME_ARGS (current_time));
3098     return FALSE;
3099   }
3100
3101   /* get elapsed time since we last reported */
3102   elapsed = current_time - sess->last_rtcp_send_time;
3103
3104   new_send_time = data->interval;
3105   /* perform forward reconsideration */
3106   if (new_send_time != GST_CLOCK_TIME_NONE) {
3107     new_send_time = rtp_stats_add_rtcp_jitter (&sess->stats, new_send_time);
3108
3109     GST_DEBUG ("forward reconsideration %" GST_TIME_FORMAT ", elapsed %"
3110         GST_TIME_FORMAT, GST_TIME_ARGS (new_send_time),
3111         GST_TIME_ARGS (elapsed));
3112
3113     new_send_time += sess->last_rtcp_send_time;
3114   }
3115
3116   /* check if reconsideration */
3117   if (new_send_time == GST_CLOCK_TIME_NONE || current_time < new_send_time) {
3118     GST_DEBUG ("reconsider RTCP for %" GST_TIME_FORMAT,
3119         GST_TIME_ARGS (new_send_time));
3120     /* store new check time */
3121     sess->next_rtcp_check_time = new_send_time;
3122     return FALSE;
3123   }
3124
3125 early:
3126
3127   new_send_time = calculate_rtcp_interval (sess, FALSE, FALSE);
3128
3129   GST_DEBUG ("can send RTCP now, next interval %" GST_TIME_FORMAT,
3130       GST_TIME_ARGS (new_send_time));
3131
3132   sess->next_rtcp_check_time = new_send_time;
3133   if (new_send_time != GST_CLOCK_TIME_NONE) {
3134     sess->next_rtcp_check_time += current_time;
3135
3136     /* Apply the rules from RFC 4585 section 3.5.3 */
3137     if (sess->stats.min_interval != 0 && !sess->first_rtcp) {
3138       GstClockTimeDiff T_rr_current_interval =
3139           g_random_double_range (0.5, 1.5) * sess->stats.min_interval;
3140
3141       /* This will caused the RTCP to be suppressed if no FB packets are added */
3142       if (sess->last_rtcp_send_time + T_rr_current_interval >
3143           sess->next_rtcp_check_time) {
3144         GST_DEBUG ("RTCP packet could be suppressed min: %" GST_TIME_FORMAT
3145             " last: %" GST_TIME_FORMAT
3146             " + T_rr_current_interval: %" GST_TIME_FORMAT
3147             " >  sess->next_rtcp_check_time: %" GST_TIME_FORMAT,
3148             GST_TIME_ARGS (sess->stats.min_interval),
3149             GST_TIME_ARGS (sess->last_rtcp_send_time),
3150             GST_TIME_ARGS (T_rr_current_interval),
3151             GST_TIME_ARGS (sess->next_rtcp_check_time));
3152         data->may_suppress = TRUE;
3153       }
3154     }
3155   }
3156
3157   return TRUE;
3158 }
3159
3160 static void
3161 clone_ssrcs_hashtable (gchar * key, RTPSource * source, GHashTable * hash_table)
3162 {
3163   g_hash_table_insert (hash_table, key, g_object_ref (source));
3164 }
3165
3166 static gboolean
3167 remove_closing_sources (const gchar * key, RTPSource * source, gpointer * data)
3168 {
3169   return source->closing;
3170 }
3171
3172 static void
3173 generate_rtcp (const gchar * key, RTPSource * source, ReportData * data)
3174 {
3175   RTPSession *sess = data->sess;
3176   gboolean is_bye = FALSE;
3177   ReportOutput *output;
3178
3179   /* only generate RTCP for active internal sources */
3180   if (!source->internal || source->sent_bye)
3181     return;
3182
3183   data->source = source;
3184
3185   /* open packet */
3186   session_start_rtcp (sess, data);
3187
3188   if (source->marked_bye) {
3189     /* send BYE */
3190     make_source_bye (sess, source, data);
3191     is_bye = TRUE;
3192   } else if (!data->is_early) {
3193     /* loop over all known sources and add report blocks. If we are early, we
3194      * just make a minimal RTCP packet and skip this step */
3195     g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3196         (GHFunc) session_report_blocks, data);
3197   }
3198   if (!data->has_sdes)
3199     session_sdes (sess, data);
3200
3201   gst_rtcp_buffer_unmap (&data->rtcpbuf);
3202
3203   output = g_slice_new (ReportOutput);
3204   output->source = g_object_ref (source);
3205   output->is_bye = is_bye;
3206   output->buffer = data->rtcp;
3207   /* queue the RTCP packet to push later */
3208   g_queue_push_tail (&data->output, output);
3209 }
3210
3211 /**
3212  * rtp_session_on_timeout:
3213  * @sess: an #RTPSession
3214  * @current_time: the current system time
3215  * @ntpnstime: the current NTP time in nanoseconds
3216  * @running_time: the current running_time of the pipeline
3217  *
3218  * Perform maintenance actions after the timeout obtained with
3219  * rtp_session_next_timeout() expired.
3220  *
3221  * This function will perform timeouts of receivers and senders, send a BYE
3222  * packet or generate RTCP packets with current session stats.
3223  *
3224  * This function can call the #RTPSessionSendRTCP callback, possibly multiple
3225  * times, for each packet that should be processed.
3226  *
3227  * Returns: a #GstFlowReturn.
3228  */
3229 GstFlowReturn
3230 rtp_session_on_timeout (RTPSession * sess, GstClockTime current_time,
3231     guint64 ntpnstime, GstClockTime running_time)
3232 {
3233   GstFlowReturn result = GST_FLOW_OK;
3234   ReportData data = { GST_RTCP_BUFFER_INIT };
3235   GHashTable *table_copy;
3236   ReportOutput *output;
3237
3238   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
3239
3240   GST_DEBUG ("reporting at %" GST_TIME_FORMAT ", NTP time %" GST_TIME_FORMAT
3241       ", running-time %" GST_TIME_FORMAT, GST_TIME_ARGS (current_time),
3242       GST_TIME_ARGS (ntpnstime), GST_TIME_ARGS (running_time));
3243
3244   data.sess = sess;
3245   data.current_time = current_time;
3246   data.ntpnstime = ntpnstime;
3247   data.running_time = running_time;
3248   data.num_to_report = 0;
3249   data.may_suppress = FALSE;
3250   g_queue_init (&data.output);
3251
3252   RTP_SESSION_LOCK (sess);
3253   /* get a new interval, we need this for various cleanups etc */
3254   data.interval = calculate_rtcp_interval (sess, TRUE, sess->first_rtcp);
3255
3256   /* we need an internal source now */
3257   if (sess->stats.internal_sources == 0) {
3258     RTPSource *source;
3259     gboolean created;
3260
3261     source = obtain_internal_source (sess, sess->suggested_ssrc, &created);
3262     g_object_unref (source);
3263   }
3264
3265   /* Make a local copy of the hashtable. We need to do this because the
3266    * cleanup stage below releases the session lock. */
3267   table_copy = g_hash_table_new_full (NULL, NULL, NULL,
3268       (GDestroyNotify) g_object_unref);
3269   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3270       (GHFunc) clone_ssrcs_hashtable, table_copy);
3271
3272   /* Clean up the session, mark the source for removing, this might release the
3273    * session lock. */
3274   g_hash_table_foreach (table_copy, (GHFunc) session_cleanup, &data);
3275   g_hash_table_destroy (table_copy);
3276
3277   /* Now remove the marked sources */
3278   g_hash_table_foreach_remove (sess->ssrcs[sess->mask_idx],
3279       (GHRFunc) remove_closing_sources, NULL);
3280
3281   /* see if we need to generate SR or RR packets */
3282   if (!is_rtcp_time (sess, current_time, &data))
3283     goto done;
3284
3285   GST_DEBUG ("doing RTCP generation %u for %u sources", sess->generation,
3286       data.num_to_report);
3287
3288   /* generate RTCP for all internal sources */
3289   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3290       (GHFunc) generate_rtcp, &data);
3291
3292   /* we keep track of the last report time in order to timeout inactive
3293    * receivers or senders */
3294   if (!data.is_early && !data.may_suppress)
3295     sess->last_rtcp_send_time = data.current_time;
3296   sess->first_rtcp = FALSE;
3297   sess->next_early_rtcp_time = GST_CLOCK_TIME_NONE;
3298
3299 done:
3300   RTP_SESSION_UNLOCK (sess);
3301
3302   /* push out the RTCP packets */
3303   while ((output = g_queue_pop_head (&data.output))) {
3304     gboolean do_not_suppress;
3305     GstBuffer *buffer = output->buffer;
3306     RTPSource *source = output->source;
3307
3308     /* Give the user a change to add its own packet */
3309     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_RTCP], 0,
3310         buffer, data.is_early, &do_not_suppress);
3311
3312     if (sess->callbacks.send_rtcp && (do_not_suppress || !data.may_suppress)) {
3313       guint packet_size;
3314
3315       packet_size = gst_buffer_get_size (buffer) + sess->header_len;
3316
3317       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, packet_size);
3318       GST_DEBUG ("%p, sending RTCP packet, avg size %u, %u", &sess->stats,
3319           sess->stats.avg_rtcp_packet_size, packet_size);
3320       result =
3321           sess->callbacks.send_rtcp (sess, source, buffer, output->is_bye,
3322           sess->send_rtcp_user_data);
3323     } else {
3324       GST_DEBUG ("freeing packet callback: %p"
3325           " do_not_suppress: %d may_suppress: %d",
3326           sess->callbacks.send_rtcp, do_not_suppress, data.may_suppress);
3327       gst_buffer_unref (buffer);
3328     }
3329     g_object_unref (source);
3330     g_slice_free (ReportOutput, output);
3331   }
3332   return result;
3333 }
3334
3335 /**
3336  * rtp_session_request_early_rtcp:
3337  * @sess: an #RTPSession
3338  * @current_time: the current system time
3339  * @max_delay: maximum delay
3340  *
3341  * Request transmission of early RTCP
3342  */
3343 void
3344 rtp_session_request_early_rtcp (RTPSession * sess, GstClockTime current_time,
3345     GstClockTimeDiff max_delay)
3346 {
3347   GstClockTime T_dither_max;
3348
3349   /* Implements the algorithm described in RFC 4585 section 3.5.2 */
3350
3351   RTP_SESSION_LOCK (sess);
3352
3353   /* Check if already requested */
3354   /*  RFC 4585 section 3.5.2 step 2 */
3355   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3356     goto dont_send;
3357
3358   if (!GST_CLOCK_TIME_IS_VALID (sess->next_rtcp_check_time))
3359     goto dont_send;
3360
3361   /* Ignore the request a scheduled packet will be in time anyway */
3362   if (current_time + max_delay > sess->next_rtcp_check_time)
3363     goto dont_send;
3364
3365   /*  RFC 4585 section 3.5.2 step 2b */
3366   /* If the total sources is <=2, then there is only us and one peer */
3367   if (sess->total_sources <= 2) {
3368     T_dither_max = 0;
3369   } else {
3370     /* Divide by 2 because l = 0.5 */
3371     T_dither_max = sess->next_rtcp_check_time - sess->last_rtcp_send_time;
3372     T_dither_max /= 2;
3373   }
3374
3375   /*  RFC 4585 section 3.5.2 step 3 */
3376   if (current_time + T_dither_max > sess->next_rtcp_check_time)
3377     goto dont_send;
3378
3379   /*  RFC 4585 section 3.5.2 step 4
3380    * Don't send if allow_early is FALSE, but not if we are in
3381    * immediate mode, meaning we are part of a group of at most the
3382    * application-specific threshold.
3383    */
3384   if (sess->total_sources > sess->rtcp_immediate_feedback_threshold &&
3385       sess->allow_early == FALSE)
3386     goto dont_send;
3387
3388   if (T_dither_max) {
3389     /* Schedule an early transmission later */
3390     sess->next_early_rtcp_time = g_random_double () * T_dither_max +
3391         current_time;
3392   } else {
3393     /* If no dithering, schedule it for NOW */
3394     sess->next_early_rtcp_time = current_time;
3395   }
3396
3397   RTP_SESSION_UNLOCK (sess);
3398
3399   /* notify app of need to send packet early
3400    * and therefore of timeout change */
3401   if (sess->callbacks.reconsider)
3402     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
3403
3404   return;
3405
3406 dont_send:
3407
3408   RTP_SESSION_UNLOCK (sess);
3409 }
3410
3411 gboolean
3412 rtp_session_request_key_unit (RTPSession * sess, guint32 ssrc, GstClockTime now,
3413     gboolean fir, gint count)
3414 {
3415   RTPSource *src = find_source (sess, ssrc);
3416
3417   if (!src)
3418     return FALSE;
3419
3420   if (fir) {
3421     src->send_pli = FALSE;
3422     src->send_fir = TRUE;
3423
3424     if (count == -1 || count != src->last_fir_count)
3425       src->current_send_fir_seqnum++;
3426     src->last_fir_count = count;
3427   } else if (!src->send_fir) {
3428     src->send_pli = TRUE;
3429   }
3430
3431   rtp_session_request_early_rtcp (sess, now, 200 * GST_MSECOND);
3432
3433   return TRUE;
3434 }
3435
3436 static gboolean
3437 has_pli_compare_func (gconstpointer a, gconstpointer ignored)
3438 {
3439   GstRTCPPacket packet;
3440   GstRTCPBuffer rtcp = { NULL, };
3441   gboolean ret = FALSE;
3442
3443   gst_rtcp_buffer_map ((GstBuffer *) a, GST_MAP_READ, &rtcp);
3444
3445   if (gst_rtcp_buffer_get_first_packet (&rtcp, &packet)) {
3446     if (gst_rtcp_packet_get_type (&packet) == GST_RTCP_TYPE_PSFB &&
3447         gst_rtcp_packet_fb_get_type (&packet) == GST_RTCP_PSFB_TYPE_PLI)
3448       ret = TRUE;
3449   }
3450
3451   gst_rtcp_buffer_unmap (&rtcp);
3452
3453   return ret;
3454 }
3455
3456 static gboolean
3457 rtp_session_on_sending_rtcp (RTPSession * sess, GstBuffer * buffer,
3458     gboolean early)
3459 {
3460   gboolean ret = FALSE;
3461   GHashTableIter iter;
3462   gpointer key, value;
3463   gboolean started_fir = FALSE;
3464   GstRTCPPacket fir_rtcppacket;
3465   GstRTCPPacket packet;
3466   GstRTCPBuffer rtcp = { NULL, };
3467   guint32 ssrc;
3468
3469   gst_rtcp_buffer_map (buffer, GST_MAP_READWRITE, &rtcp);
3470
3471   gst_rtcp_buffer_get_first_packet (&rtcp, &packet);
3472   switch (gst_rtcp_packet_get_type (&packet)) {
3473     case GST_RTCP_TYPE_SR:
3474       gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc,
3475           NULL, NULL, NULL, NULL);
3476       break;
3477     case GST_RTCP_TYPE_RR:
3478       ssrc = gst_rtcp_packet_rr_get_ssrc (&packet);
3479       break;
3480     default:
3481       goto done;
3482   }
3483
3484   RTP_SESSION_LOCK (sess);
3485   g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
3486   while (g_hash_table_iter_next (&iter, &key, &value)) {
3487     guint media_ssrc = GPOINTER_TO_UINT (key);
3488     RTPSource *media_src = value;
3489     guint8 *fci_data;
3490
3491     if (media_src->send_fir) {
3492       if (!started_fir) {
3493         if (!gst_rtcp_buffer_add_packet (&rtcp, GST_RTCP_TYPE_PSFB,
3494                 &fir_rtcppacket))
3495           break;
3496         gst_rtcp_packet_fb_set_type (&fir_rtcppacket, GST_RTCP_PSFB_TYPE_FIR);
3497         gst_rtcp_packet_fb_set_sender_ssrc (&fir_rtcppacket, ssrc);
3498         gst_rtcp_packet_fb_set_media_ssrc (&fir_rtcppacket, 0);
3499
3500         if (!gst_rtcp_packet_fb_set_fci_length (&fir_rtcppacket, 2)) {
3501           gst_rtcp_packet_remove (&fir_rtcppacket);
3502           break;
3503         }
3504         ret = TRUE;
3505         started_fir = TRUE;
3506       } else {
3507         if (!gst_rtcp_packet_fb_set_fci_length (&fir_rtcppacket,
3508                 !gst_rtcp_packet_fb_get_fci_length (&fir_rtcppacket) + 2))
3509           break;
3510       }
3511
3512       fci_data = gst_rtcp_packet_fb_get_fci (&fir_rtcppacket) -
3513           ((gst_rtcp_packet_fb_get_fci_length (&fir_rtcppacket) - 2) * 4);
3514
3515       GST_WRITE_UINT32_BE (fci_data, media_ssrc);
3516       fci_data += 4;
3517       fci_data[0] = media_src->current_send_fir_seqnum;
3518       fci_data[1] = fci_data[2] = fci_data[3] = 0;
3519       media_src->send_fir = FALSE;
3520     }
3521   }
3522
3523   g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
3524   while (g_hash_table_iter_next (&iter, &key, &value)) {
3525     guint media_ssrc = GPOINTER_TO_UINT (key);
3526     RTPSource *media_src = value;
3527     GstRTCPPacket pli_rtcppacket;
3528
3529     if (media_src->send_pli && !rtp_source_has_retained (media_src,
3530             has_pli_compare_func, NULL)) {
3531       if (!gst_rtcp_buffer_add_packet (&rtcp, GST_RTCP_TYPE_PSFB,
3532               &pli_rtcppacket))
3533         /* Break because the packet is full, will put next request in a
3534          * further packet */
3535         break;
3536       gst_rtcp_packet_fb_set_type (&pli_rtcppacket, GST_RTCP_PSFB_TYPE_PLI);
3537       gst_rtcp_packet_fb_set_sender_ssrc (&pli_rtcppacket, ssrc);
3538       gst_rtcp_packet_fb_set_media_ssrc (&pli_rtcppacket, media_ssrc);
3539       ret = TRUE;
3540     }
3541     media_src->send_pli = FALSE;
3542   }
3543   RTP_SESSION_UNLOCK (sess);
3544
3545 done:
3546   gst_rtcp_buffer_unmap (&rtcp);
3547
3548   return ret;
3549 }
3550
3551 static void
3552 rtp_session_send_rtcp (RTPSession * sess, GstClockTimeDiff max_delay)
3553 {
3554   GstClockTime now;
3555
3556   if (!sess->callbacks.send_rtcp)
3557     return;
3558
3559   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
3560
3561   rtp_session_request_early_rtcp (sess, now, max_delay);
3562 }