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