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