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