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