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