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