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