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