rtpmanager: Update codes based on 1.18.4
[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, 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, &round_trip);
2738
2739   if (src->last_keyframe_request != GST_CLOCK_TIME_NONE && round_trip) {
2740     GstClockTime round_trip_in_ns = gst_util_uint64_scale (round_trip,
2741         GST_SECOND, 65536);
2742
2743     /* Sanity check to avoid always ignoring PLI/FIR if we receive RTCP
2744      * packets with erroneous values resulting in crazy high RTT. */
2745     if (round_trip_in_ns > 5 * GST_SECOND)
2746       round_trip_in_ns = GST_SECOND / 2;
2747
2748     if (current_time - src->last_keyframe_request < 2 * round_trip_in_ns) {
2749       GST_DEBUG ("Ignoring %s request from %X because one was send without one "
2750           "RTT (%" GST_TIME_FORMAT " < %" GST_TIME_FORMAT ")",
2751           fir ? "FIR" : "PLI", rtp_source_get_ssrc (src),
2752           GST_TIME_ARGS (current_time - src->last_keyframe_request),
2753           GST_TIME_ARGS (round_trip_in_ns));
2754       return FALSE;
2755     }
2756   }
2757
2758   src->last_keyframe_request = current_time;
2759
2760   GST_LOG ("received %s request from %X about %X %p(%p)", fir ? "FIR" : "PLI",
2761       rtp_source_get_ssrc (src), media_ssrc, sess->callbacks.process_rtp,
2762       sess->callbacks.request_key_unit);
2763
2764   RTP_SESSION_UNLOCK (sess);
2765   sess->callbacks.request_key_unit (sess, media_ssrc, fir,
2766       sess->request_key_unit_user_data);
2767   RTP_SESSION_LOCK (sess);
2768
2769   return TRUE;
2770 }
2771
2772 static void
2773 rtp_session_process_pli (RTPSession * sess, guint32 sender_ssrc,
2774     guint32 media_ssrc, GstClockTime current_time)
2775 {
2776   RTPSource *src;
2777
2778   if (!sess->callbacks.request_key_unit)
2779     return;
2780
2781   src = find_source (sess, sender_ssrc);
2782   if (src == NULL) {
2783     /* try to find a src with media_ssrc instead */
2784     src = find_source (sess, media_ssrc);
2785     if (src == NULL)
2786       return;
2787   }
2788
2789   rtp_session_request_local_key_unit (sess, src, media_ssrc, FALSE,
2790       current_time);
2791 }
2792
2793 static void
2794 rtp_session_process_fir (RTPSession * sess, guint32 sender_ssrc,
2795     guint32 media_ssrc, guint8 * fci_data, guint fci_length,
2796     GstClockTime current_time)
2797 {
2798   RTPSource *src;
2799   guint32 ssrc;
2800   guint position = 0;
2801   gboolean our_request = FALSE;
2802
2803   if (!sess->callbacks.request_key_unit)
2804     return;
2805
2806   if (fci_length < 8)
2807     return;
2808
2809   src = find_source (sess, sender_ssrc);
2810
2811   /* Hack because Google fails to set the sender_ssrc correctly */
2812   if (!src && sender_ssrc == 1) {
2813     GHashTableIter iter;
2814
2815     /* we can't find the source if there are multiple */
2816     if (sess->stats.sender_sources > sess->stats.internal_sender_sources + 1)
2817       return;
2818
2819     g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
2820     while (g_hash_table_iter_next (&iter, NULL, (gpointer *) & src)) {
2821       if (!src->internal && rtp_source_is_sender (src))
2822         break;
2823       src = NULL;
2824     }
2825   }
2826   if (!src)
2827     return;
2828
2829   for (position = 0; position < fci_length; position += 8) {
2830     guint8 *data = fci_data + position;
2831     RTPSource *own;
2832
2833     ssrc = GST_READ_UINT32_BE (data);
2834
2835     own = find_source (sess, ssrc);
2836     if (own == NULL)
2837       continue;
2838
2839     if (own->internal) {
2840       our_request = TRUE;
2841       break;
2842     }
2843   }
2844   if (!our_request)
2845     return;
2846
2847   rtp_session_request_local_key_unit (sess, src, media_ssrc, TRUE,
2848       current_time);
2849 }
2850
2851 static void
2852 rtp_session_process_nack (RTPSession * sess, guint32 sender_ssrc,
2853     guint32 media_ssrc, guint8 * fci_data, guint fci_length,
2854     GstClockTime current_time)
2855 {
2856   sess->stats.nacks_received++;
2857
2858   if (!sess->callbacks.notify_nack)
2859     return;
2860
2861   while (fci_length > 0) {
2862     guint16 seqnum, blp;
2863
2864     seqnum = GST_READ_UINT16_BE (fci_data);
2865     blp = GST_READ_UINT16_BE (fci_data + 2);
2866
2867     GST_DEBUG ("NACK #%u, blp %04x, SSRC 0x%08x", seqnum, blp, media_ssrc);
2868
2869     RTP_SESSION_UNLOCK (sess);
2870     sess->callbacks.notify_nack (sess, seqnum, blp, media_ssrc,
2871         sess->notify_nack_user_data);
2872     RTP_SESSION_LOCK (sess);
2873
2874     fci_data += 4;
2875     fci_length -= 4;
2876   }
2877 }
2878
2879 static void
2880 rtp_session_process_twcc (RTPSession * sess, guint32 sender_ssrc,
2881     guint32 media_ssrc, guint8 * fci_data, guint fci_length)
2882 {
2883   GArray *twcc_packets;
2884   GstStructure *twcc_packets_s;
2885   GstStructure *twcc_stats_s;
2886
2887   twcc_packets = rtp_twcc_manager_parse_fci (sess->twcc,
2888       fci_data, fci_length * sizeof (guint32));
2889   if (twcc_packets == NULL)
2890     return;
2891
2892   twcc_packets_s = rtp_twcc_stats_get_packets_structure (twcc_packets);
2893   twcc_stats_s =
2894       rtp_twcc_stats_process_packets (sess->twcc_stats, twcc_packets);
2895
2896   GST_DEBUG_OBJECT (sess, "Parsed TWCC: %" GST_PTR_FORMAT, twcc_packets_s);
2897   GST_INFO_OBJECT (sess, "Current TWCC stats %" GST_PTR_FORMAT, twcc_stats_s);
2898
2899   g_array_unref (twcc_packets);
2900
2901   RTP_SESSION_UNLOCK (sess);
2902   if (sess->callbacks.notify_twcc)
2903     sess->callbacks.notify_twcc (sess, twcc_packets_s, twcc_stats_s,
2904         sess->notify_twcc_user_data);
2905   RTP_SESSION_LOCK (sess);
2906 }
2907
2908 static void
2909 rtp_session_process_feedback (RTPSession * sess, GstRTCPPacket * packet,
2910     RTPPacketInfo * pinfo, GstClockTime current_time)
2911 {
2912   GstRTCPType type;
2913   GstRTCPFBType fbtype;
2914   guint32 sender_ssrc, media_ssrc;
2915   guint8 *fci_data;
2916   guint fci_length;
2917   RTPSource *src;
2918
2919   /* The feedback packet must include both sender SSRC and media SSRC */
2920   if (packet->length < 2)
2921     return;
2922
2923   type = gst_rtcp_packet_get_type (packet);
2924   fbtype = gst_rtcp_packet_fb_get_type (packet);
2925   sender_ssrc = gst_rtcp_packet_fb_get_sender_ssrc (packet);
2926   media_ssrc = gst_rtcp_packet_fb_get_media_ssrc (packet);
2927
2928   src = find_source (sess, media_ssrc);
2929
2930   /* skip non-bye packets for sources that are marked BYE */
2931   if (sess->scheduled_bye && src && RTP_SOURCE_IS_MARKED_BYE (src))
2932     return;
2933
2934   if (src)
2935     g_object_ref (src);
2936
2937   fci_data = gst_rtcp_packet_fb_get_fci (packet);
2938   fci_length = gst_rtcp_packet_fb_get_fci_length (packet) * sizeof (guint32);
2939
2940   GST_DEBUG ("received feedback %d:%d from %08X about %08X with FCI of "
2941       "length %d", type, fbtype, sender_ssrc, media_ssrc, fci_length);
2942
2943   if (g_signal_has_handler_pending (sess,
2944           rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0, TRUE)) {
2945     GstBuffer *fci_buffer = NULL;
2946
2947     if (fci_length > 0) {
2948       fci_buffer = gst_buffer_copy_region (packet->rtcp->buffer,
2949           GST_BUFFER_COPY_MEMORY, fci_data - packet->rtcp->map.data,
2950           fci_length);
2951       GST_BUFFER_PTS (fci_buffer) = pinfo->running_time;
2952     }
2953
2954     RTP_SESSION_UNLOCK (sess);
2955     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0,
2956         type, fbtype, sender_ssrc, media_ssrc, fci_buffer);
2957     RTP_SESSION_LOCK (sess);
2958
2959     if (fci_buffer)
2960       gst_buffer_unref (fci_buffer);
2961   }
2962
2963   if (src && sess->rtcp_feedback_retention_window != GST_CLOCK_TIME_NONE) {
2964     rtp_source_retain_rtcp_packet (src, packet, pinfo->running_time);
2965   }
2966
2967   if ((src && src->internal) ||
2968       /* PSFB FIR puts the media ssrc inside the FCI */
2969       (type == GST_RTCP_TYPE_PSFB && fbtype == GST_RTCP_PSFB_TYPE_FIR) ||
2970       /* TWCC is for all sources, so a single media-ssrc is not enough */
2971       (type == GST_RTCP_TYPE_RTPFB && fbtype == GST_RTCP_RTPFB_TYPE_TWCC)) {
2972     switch (type) {
2973       case GST_RTCP_TYPE_PSFB:
2974         switch (fbtype) {
2975           case GST_RTCP_PSFB_TYPE_PLI:
2976             if (src)
2977               src->stats.recv_pli_count++;
2978             rtp_session_process_pli (sess, sender_ssrc, media_ssrc,
2979                 current_time);
2980             break;
2981           case GST_RTCP_PSFB_TYPE_FIR:
2982             if (src)
2983               src->stats.recv_fir_count++;
2984             rtp_session_process_fir (sess, sender_ssrc, media_ssrc, fci_data,
2985                 fci_length, current_time);
2986             break;
2987           default:
2988             break;
2989         }
2990         break;
2991       case GST_RTCP_TYPE_RTPFB:
2992         switch (fbtype) {
2993           case GST_RTCP_RTPFB_TYPE_NACK:
2994             if (src)
2995               src->stats.recv_nack_count++;
2996             rtp_session_process_nack (sess, sender_ssrc, media_ssrc,
2997                 fci_data, fci_length, current_time);
2998             break;
2999           case GST_RTCP_RTPFB_TYPE_TWCC:
3000             rtp_session_process_twcc (sess, sender_ssrc, media_ssrc,
3001                 fci_data, fci_length);
3002             break;
3003           default:
3004             break;
3005         }
3006       default:
3007         break;
3008     }
3009   }
3010
3011   if (src)
3012     g_object_unref (src);
3013 }
3014
3015 /**
3016  * rtp_session_process_rtcp:
3017  * @sess: and #RTPSession
3018  * @buffer: an RTCP buffer
3019  * @current_time: the current system time
3020  * @ntpnstime: the current NTP time in nanoseconds
3021  *
3022  * Process an RTCP buffer in the session manager. This function takes ownership
3023  * of @buffer.
3024  *
3025  * Returns: a #GstFlowReturn.
3026  */
3027 GstFlowReturn
3028 rtp_session_process_rtcp (RTPSession * sess, GstBuffer * buffer,
3029     GstClockTime current_time, GstClockTime running_time, guint64 ntpnstime)
3030 {
3031   GstRTCPPacket packet;
3032   gboolean more, is_bye = FALSE, do_sync = FALSE;
3033   RTPPacketInfo pinfo = { 0, };
3034   GstFlowReturn result = GST_FLOW_OK;
3035   GstRTCPBuffer rtcp = { NULL, };
3036
3037   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
3038   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
3039
3040   if (!gst_rtcp_buffer_validate_reduced (buffer))
3041     goto invalid_packet;
3042
3043   GST_DEBUG ("received RTCP packet");
3044
3045   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_RECEIVING_RTCP], 0,
3046       buffer);
3047
3048   RTP_SESSION_LOCK (sess);
3049   /* update pinfo stats */
3050   update_packet_info (sess, &pinfo, FALSE, FALSE, FALSE, buffer, current_time,
3051       running_time, ntpnstime);
3052
3053   /* start processing the compound packet */
3054   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
3055   more = gst_rtcp_buffer_get_first_packet (&rtcp, &packet);
3056   while (more) {
3057     GstRTCPType type;
3058
3059     type = gst_rtcp_packet_get_type (&packet);
3060
3061     switch (type) {
3062       case GST_RTCP_TYPE_SR:
3063         rtp_session_process_sr (sess, &packet, &pinfo, &do_sync);
3064         break;
3065       case GST_RTCP_TYPE_RR:
3066         rtp_session_process_rr (sess, &packet, &pinfo);
3067         break;
3068       case GST_RTCP_TYPE_SDES:
3069         rtp_session_process_sdes (sess, &packet, &pinfo);
3070         break;
3071       case GST_RTCP_TYPE_BYE:
3072         is_bye = TRUE;
3073         /* don't try to attempt lip-sync anymore for streams with a BYE */
3074         do_sync = FALSE;
3075         rtp_session_process_bye (sess, &packet, &pinfo);
3076         break;
3077       case GST_RTCP_TYPE_APP:
3078         rtp_session_process_app (sess, &packet, &pinfo);
3079         break;
3080       case GST_RTCP_TYPE_RTPFB:
3081       case GST_RTCP_TYPE_PSFB:
3082         rtp_session_process_feedback (sess, &packet, &pinfo, current_time);
3083         break;
3084       case GST_RTCP_TYPE_XR:
3085         /* FIXME: This block is added to downgrade warning level.
3086          * Once the parser is implemented, it should be replaced with
3087          * a proper process function. */
3088         GST_DEBUG ("got RTCP XR packet, but ignored");
3089         break;
3090       default:
3091         GST_WARNING ("got unknown RTCP packet type: %d", type);
3092         break;
3093     }
3094     more = gst_rtcp_packet_move_to_next (&packet);
3095   }
3096
3097   gst_rtcp_buffer_unmap (&rtcp);
3098
3099   /* if we are scheduling a BYE, we only want to count bye packets, else we
3100    * count everything */
3101   if (sess->scheduled_bye && is_bye) {
3102     sess->bye_stats.bye_members++;
3103     UPDATE_AVG (sess->bye_stats.avg_rtcp_packet_size, pinfo.bytes);
3104   }
3105
3106   /* keep track of average packet size */
3107   UPDATE_AVG (sess->stats.avg_rtcp_packet_size, pinfo.bytes);
3108
3109   GST_DEBUG ("%p, received RTCP packet, avg size %u, %u", &sess->stats,
3110       sess->stats.avg_rtcp_packet_size, pinfo.bytes);
3111   RTP_SESSION_UNLOCK (sess);
3112
3113   pinfo.data = NULL;
3114   clean_packet_info (&pinfo);
3115
3116   /* notify caller of sr packets in the callback */
3117   if (do_sync && sess->callbacks.sync_rtcp) {
3118     result = sess->callbacks.sync_rtcp (sess, buffer,
3119         sess->sync_rtcp_user_data);
3120   } else
3121     gst_buffer_unref (buffer);
3122
3123   return result;
3124
3125   /* ERRORS */
3126 invalid_packet:
3127   {
3128     GST_DEBUG ("invalid RTCP packet received");
3129     gst_buffer_unref (buffer);
3130     return GST_FLOW_OK;
3131   }
3132 }
3133
3134 static guint8
3135 _get_extmap_id_for_attribute (const GstStructure * s, const gchar * ext_name)
3136 {
3137   guint i;
3138   guint8 extmap_id = 0;
3139   guint n_fields = gst_structure_n_fields (s);
3140
3141   for (i = 0; i < n_fields; i++) {
3142     const gchar *field_name = gst_structure_nth_field_name (s, i);
3143     if (g_str_has_prefix (field_name, "extmap-")) {
3144       const gchar *str = gst_structure_get_string (s, field_name);
3145       if (str && g_strcmp0 (str, ext_name) == 0) {
3146         gint64 id = g_ascii_strtoll (field_name + 7, NULL, 10);
3147         if (id > 0 && id < 15) {
3148           extmap_id = id;
3149           break;
3150         }
3151       }
3152     }
3153   }
3154   return extmap_id;
3155 }
3156
3157 /**
3158  * rtp_session_update_send_caps:
3159  * @sess: an #RTPSession
3160  * @caps: a #GstCaps
3161  *
3162  * Update the caps of the sender in the rtp session.
3163  */
3164 void
3165 rtp_session_update_send_caps (RTPSession * sess, GstCaps * caps)
3166 {
3167   GstStructure *s;
3168   guint ssrc;
3169
3170   g_return_if_fail (RTP_IS_SESSION (sess));
3171   g_return_if_fail (GST_IS_CAPS (caps));
3172
3173   GST_LOG ("received caps %" GST_PTR_FORMAT, caps);
3174
3175   s = gst_caps_get_structure (caps, 0);
3176
3177   if (gst_structure_get_uint (s, "ssrc", &ssrc)) {
3178     RTPSource *source;
3179     gboolean created;
3180
3181     RTP_SESSION_LOCK (sess);
3182     source = obtain_internal_source (sess, ssrc, &created, GST_CLOCK_TIME_NONE);
3183     sess->suggested_ssrc = ssrc;
3184     sess->internal_ssrc_set = TRUE;
3185     sess->internal_ssrc_from_caps_or_property = TRUE;
3186     if (source) {
3187       rtp_source_update_caps (source, caps);
3188
3189       if (created)
3190         on_new_sender_ssrc (sess, source);
3191
3192       g_object_unref (source);
3193     }
3194
3195     if (gst_structure_get_uint (s, "rtx-ssrc", &ssrc)) {
3196       source =
3197           obtain_internal_source (sess, ssrc, &created, GST_CLOCK_TIME_NONE);
3198       if (source) {
3199         rtp_source_update_caps (source, caps);
3200
3201         if (created)
3202           on_new_sender_ssrc (sess, source);
3203
3204         g_object_unref (source);
3205       }
3206     }
3207     RTP_SESSION_UNLOCK (sess);
3208   } else {
3209     sess->internal_ssrc_from_caps_or_property = FALSE;
3210   }
3211
3212   sess->twcc_send_ext_id = _get_extmap_id_for_attribute (s, TWCC_EXTMAP_STR);
3213   if (sess->twcc_send_ext_id > 0) {
3214     GST_INFO ("TWCC enabled for send using extension id: %u",
3215         sess->twcc_send_ext_id);
3216   }
3217 }
3218
3219 static void
3220 send_twcc_packet (RTPSession * sess, RTPPacketInfo * pinfo)
3221 {
3222   gint32 twcc_seqnum;
3223
3224   if (sess->twcc_send_ext_id == 0)
3225     return;
3226
3227   twcc_seqnum = packet_info_get_twcc_seqnum (pinfo, sess->twcc_send_ext_id);
3228   if (twcc_seqnum == -1)
3229     return;
3230
3231   rtp_twcc_manager_send_packet (sess->twcc, twcc_seqnum, pinfo);
3232 }
3233
3234
3235 /**
3236  * rtp_session_send_rtp:
3237  * @sess: an #RTPSession
3238  * @data: pointer to either an RTP buffer or a list of RTP buffers
3239  * @is_list: TRUE when @data is a buffer list
3240  * @current_time: the current system time
3241  * @running_time: the running time of @data
3242  *
3243  * Send the RTP data (a buffer or buffer list) in the session manager. This
3244  * function takes ownership of @data.
3245  *
3246  * Returns: a #GstFlowReturn.
3247  */
3248 GstFlowReturn
3249 rtp_session_send_rtp (RTPSession * sess, gpointer data, gboolean is_list,
3250     GstClockTime current_time, GstClockTime running_time)
3251 {
3252   GstFlowReturn result;
3253   RTPSource *source;
3254   gboolean prevsender;
3255   guint64 oldrate;
3256   RTPPacketInfo pinfo = { 0, };
3257   gboolean created;
3258
3259   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
3260   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
3261
3262   GST_LOG ("received RTP %s for sending", is_list ? "list" : "packet");
3263
3264   RTP_SESSION_LOCK (sess);
3265   if (!update_packet_info (sess, &pinfo, TRUE, TRUE, is_list, data,
3266           current_time, running_time, -1))
3267     goto invalid_packet;
3268
3269   send_twcc_packet (sess, &pinfo);
3270
3271   source = obtain_internal_source (sess, pinfo.ssrc, &created, current_time);
3272   if (created)
3273     on_new_sender_ssrc (sess, source);
3274
3275   if (!source->internal) {
3276     GSocketAddress *from;
3277
3278     if (source->rtp_from)
3279       from = source->rtp_from;
3280     else
3281       from = source->rtcp_from;
3282     if (from) {
3283       if (rtp_session_find_conflicting_address (sess, from, current_time)) {
3284         /* Its a known conflict, its probably a loop, not a collision
3285          * lets just drop the incoming packet
3286          */
3287         GST_LOG ("Our packets are being looped back to us, ignoring collision");
3288       } else {
3289         GST_DEBUG ("Collision for SSRC %x, change our sender ssrc", pinfo.ssrc);
3290
3291         rtp_session_have_conflict (sess, source, from, current_time);
3292
3293         goto collision;
3294       }
3295     } else {
3296       GST_LOG ("Ignoring collision on sent SSRC %x because remote source"
3297           " doesn't have an address", pinfo.ssrc);
3298     }
3299   }
3300
3301   prevsender = RTP_SOURCE_IS_SENDER (source);
3302   oldrate = source->bitrate;
3303
3304   /* we use our own source to send */
3305   result = rtp_source_send_rtp (source, &pinfo);
3306
3307   source_update_sender (sess, source, prevsender);
3308
3309   if (oldrate != source->bitrate)
3310     sess->recalc_bandwidth = TRUE;
3311   RTP_SESSION_UNLOCK (sess);
3312
3313   g_object_unref (source);
3314   clean_packet_info (&pinfo);
3315
3316   return result;
3317
3318 invalid_packet:
3319   {
3320     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
3321     RTP_SESSION_UNLOCK (sess);
3322     GST_DEBUG ("invalid RTP packet received");
3323     return GST_FLOW_OK;
3324   }
3325 collision:
3326   {
3327     g_object_unref (source);
3328     clean_packet_info (&pinfo);
3329     RTP_SESSION_UNLOCK (sess);
3330     GST_WARNING ("non-internal source with same ssrc %08x, drop packet",
3331         pinfo.ssrc);
3332     return GST_FLOW_OK;
3333   }
3334 }
3335
3336 static void
3337 add_bitrates (gpointer key, RTPSource * source, gdouble * bandwidth)
3338 {
3339   *bandwidth += source->bitrate;
3340 }
3341
3342 /* must be called with session lock */
3343 static GstClockTime
3344 calculate_rtcp_interval (RTPSession * sess, gboolean deterministic,
3345     gboolean first)
3346 {
3347   GstClockTime result;
3348   RTPSessionStats *stats;
3349
3350   /* recalculate bandwidth when it changed */
3351   if (sess->recalc_bandwidth) {
3352     gdouble bandwidth;
3353
3354     if (sess->bandwidth > 0)
3355       bandwidth = sess->bandwidth;
3356     else {
3357       /* If it is <= 0, then try to estimate the actual bandwidth */
3358       bandwidth = 0;
3359
3360       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3361           (GHFunc) add_bitrates, &bandwidth);
3362     }
3363     if (bandwidth < RTP_STATS_BANDWIDTH)
3364       bandwidth = RTP_STATS_BANDWIDTH;
3365
3366     rtp_stats_set_bandwidths (&sess->stats, bandwidth,
3367         sess->rtcp_bandwidth, sess->rtcp_rs_bandwidth, sess->rtcp_rr_bandwidth);
3368
3369     sess->recalc_bandwidth = FALSE;
3370   }
3371
3372   if (sess->scheduled_bye) {
3373     stats = &sess->bye_stats;
3374     result = rtp_stats_calculate_bye_interval (stats);
3375   } else {
3376     session_update_ptp (sess);
3377
3378     stats = &sess->stats;
3379     result = rtp_stats_calculate_rtcp_interval (stats,
3380         stats->internal_sender_sources > 0, sess->rtp_profile,
3381         sess->is_doing_ptp, first);
3382   }
3383
3384   GST_DEBUG ("next deterministic interval: %" GST_TIME_FORMAT ", first %d",
3385       GST_TIME_ARGS (result), first);
3386
3387   if (!deterministic && result != GST_CLOCK_TIME_NONE)
3388     result = rtp_stats_add_rtcp_jitter (stats, result);
3389
3390   GST_DEBUG ("next interval: %" GST_TIME_FORMAT, GST_TIME_ARGS (result));
3391
3392   return result;
3393 }
3394
3395 static void
3396 source_mark_bye (const gchar * key, RTPSource * source, const gchar * reason)
3397 {
3398   if (source->internal)
3399     rtp_source_mark_bye (source, reason);
3400 }
3401
3402 /**
3403  * rtp_session_mark_all_bye:
3404  * @sess: an #RTPSession
3405  * @reason: a reason
3406  *
3407  * Mark all internal sources of the session as BYE with @reason.
3408  */
3409 void
3410 rtp_session_mark_all_bye (RTPSession * sess, const gchar * reason)
3411 {
3412   g_return_if_fail (RTP_IS_SESSION (sess));
3413
3414   RTP_SESSION_LOCK (sess);
3415   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3416       (GHFunc) source_mark_bye, (gpointer) reason);
3417   RTP_SESSION_UNLOCK (sess);
3418 }
3419
3420 /* Stop the current @sess and schedule a BYE message for the other members.
3421  * One must have the session lock to call this function
3422  */
3423 static GstFlowReturn
3424 rtp_session_schedule_bye_locked (RTPSession * sess, GstClockTime current_time)
3425 {
3426   GstFlowReturn result = GST_FLOW_OK;
3427   GstClockTime interval;
3428
3429   /* nothing to do it we already scheduled bye */
3430   if (sess->scheduled_bye)
3431     goto done;
3432
3433   /* we schedule BYE now */
3434   sess->scheduled_bye = TRUE;
3435   /* at least one member wants to send a BYE */
3436   memcpy (&sess->bye_stats, &sess->stats, sizeof (RTPSessionStats));
3437   INIT_AVG (sess->bye_stats.avg_rtcp_packet_size, 100);
3438   sess->bye_stats.bye_members = 1;
3439   sess->first_rtcp = TRUE;
3440
3441   /* reschedule transmission */
3442   sess->last_rtcp_send_time = current_time;
3443   sess->last_rtcp_check_time = current_time;
3444   interval = calculate_rtcp_interval (sess, FALSE, TRUE);
3445
3446   if (interval != GST_CLOCK_TIME_NONE)
3447     sess->next_rtcp_check_time = current_time + interval;
3448   else
3449     sess->next_rtcp_check_time = GST_CLOCK_TIME_NONE;
3450   sess->last_rtcp_interval = interval;
3451
3452   GST_DEBUG ("Schedule BYE for %" GST_TIME_FORMAT ", %" GST_TIME_FORMAT,
3453       GST_TIME_ARGS (interval), GST_TIME_ARGS (sess->next_rtcp_check_time));
3454
3455   RTP_SESSION_UNLOCK (sess);
3456   /* notify app of reconsideration */
3457   if (sess->callbacks.reconsider)
3458     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
3459   RTP_SESSION_LOCK (sess);
3460 done:
3461
3462   return result;
3463 }
3464
3465 /**
3466  * rtp_session_schedule_bye:
3467  * @sess: an #RTPSession
3468  * @current_time: the current system time
3469  *
3470  * Schedule a BYE message for all sources marked as BYE in @sess.
3471  *
3472  * Returns: a #GstFlowReturn.
3473  */
3474 GstFlowReturn
3475 rtp_session_schedule_bye (RTPSession * sess, GstClockTime current_time)
3476 {
3477   GstFlowReturn result;
3478
3479   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
3480
3481   RTP_SESSION_LOCK (sess);
3482   result = rtp_session_schedule_bye_locked (sess, current_time);
3483   RTP_SESSION_UNLOCK (sess);
3484
3485   return result;
3486 }
3487
3488 /**
3489  * rtp_session_next_timeout:
3490  * @sess: an #RTPSession
3491  * @current_time: the current system time
3492  *
3493  * Get the next time we should perform session maintenance tasks.
3494  *
3495  * Returns: a time when rtp_session_on_timeout() should be called with the
3496  * current system time.
3497  */
3498 GstClockTime
3499 rtp_session_next_timeout (RTPSession * sess, GstClockTime current_time)
3500 {
3501   GstClockTime result, interval = 0;
3502
3503   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_CLOCK_TIME_NONE);
3504
3505   RTP_SESSION_LOCK (sess);
3506
3507   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
3508     GST_DEBUG ("have early rtcp time");
3509     result = sess->next_early_rtcp_time;
3510     goto early_exit;
3511   }
3512
3513   result = sess->next_rtcp_check_time;
3514
3515   GST_DEBUG ("current time: %" GST_TIME_FORMAT
3516       ", next time: %" GST_TIME_FORMAT,
3517       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
3518
3519   if (result == GST_CLOCK_TIME_NONE || result < current_time) {
3520     GST_DEBUG ("take current time as base");
3521     /* our previous check time expired, start counting from the current time
3522      * again. */
3523     result = current_time;
3524   }
3525
3526   if (sess->scheduled_bye) {
3527     if (sess->bye_stats.active_sources >= 50) {
3528       GST_DEBUG ("reconsider BYE, more than 50 sources");
3529       /* reconsider BYE if members >= 50 */
3530       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
3531       sess->last_rtcp_interval = interval;
3532     }
3533   } else {
3534     if (sess->first_rtcp) {
3535       GST_DEBUG ("first RTCP packet");
3536       /* we are called for the first time */
3537       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
3538       sess->last_rtcp_interval = interval;
3539     } else if (sess->next_rtcp_check_time < current_time) {
3540       GST_DEBUG ("old check time expired, getting new timeout");
3541       /* get a new timeout when we need to */
3542       interval = calculate_rtcp_interval (sess, FALSE, FALSE);
3543       sess->last_rtcp_interval = interval;
3544
3545       if ((sess->rtp_profile == GST_RTP_PROFILE_AVPF
3546               || sess->rtp_profile == GST_RTP_PROFILE_SAVPF)
3547           && interval != GST_CLOCK_TIME_NONE) {
3548         /* Apply the rules from RFC 4585 section 3.5.3 */
3549         if (sess->stats.min_interval != 0) {
3550           GstClockTime T_rr_current_interval = g_random_double_range (0.5,
3551               1.5) * sess->stats.min_interval * GST_SECOND;
3552
3553           if (T_rr_current_interval > interval) {
3554             GST_DEBUG ("Adjusting interval for t-rr-interval: %" GST_TIME_FORMAT
3555                 " > %" GST_TIME_FORMAT, GST_TIME_ARGS (T_rr_current_interval),
3556                 GST_TIME_ARGS (interval));
3557             interval = T_rr_current_interval;
3558           }
3559         }
3560       }
3561     }
3562   }
3563
3564   if (interval != GST_CLOCK_TIME_NONE)
3565     result += interval;
3566   else
3567     result = GST_CLOCK_TIME_NONE;
3568
3569   sess->next_rtcp_check_time = result;
3570
3571 early_exit:
3572
3573   GST_DEBUG ("current time: %" GST_TIME_FORMAT
3574       ", next time: %" GST_TIME_FORMAT,
3575       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
3576   RTP_SESSION_UNLOCK (sess);
3577
3578   return result;
3579 }
3580
3581 typedef struct
3582 {
3583   RTPSource *source;
3584   gboolean is_bye;
3585   GstBuffer *buffer;
3586 } ReportOutput;
3587
3588 typedef struct
3589 {
3590   GstRTCPBuffer rtcpbuf;
3591   RTPSession *sess;
3592   RTPSource *source;
3593   guint num_to_report;
3594   gboolean have_fir;
3595   gboolean have_pli;
3596   gboolean have_nack;
3597   GstBuffer *rtcp;
3598   GstClockTime current_time;
3599   guint64 ntpnstime;
3600   GstClockTime running_time;
3601   GstClockTime interval;
3602   GstRTCPPacket packet;
3603   gboolean has_sdes;
3604   gboolean is_early;
3605   gboolean may_suppress;
3606   GQueue output;
3607   guint nacked_seqnums;
3608 } ReportData;
3609
3610 static void
3611 session_start_rtcp (RTPSession * sess, ReportData * data)
3612 {
3613   GstRTCPPacket *packet = &data->packet;
3614   RTPSource *own = data->source;
3615   GstRTCPBuffer *rtcp = &data->rtcpbuf;
3616
3617   data->rtcp = gst_rtcp_buffer_new (sess->mtu);
3618   data->has_sdes = FALSE;
3619
3620   gst_rtcp_buffer_map (data->rtcp, GST_MAP_READWRITE, rtcp);
3621
3622   if (data->is_early && sess->reduced_size_rtcp)
3623     return;
3624
3625   if (RTP_SOURCE_IS_SENDER (own)) {
3626     guint64 ntptime;
3627     guint32 rtptime;
3628     guint32 packet_count, octet_count;
3629
3630     /* we are a sender, create SR */
3631     GST_DEBUG ("create SR for SSRC %08x", own->ssrc);
3632     gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_SR, packet);
3633
3634     /* get latest stats */
3635     rtp_source_get_new_sr (own, data->ntpnstime, data->running_time,
3636         &ntptime, &rtptime, &packet_count, &octet_count);
3637     /* store stats */
3638     rtp_source_process_sr (own, data->current_time, ntptime, rtptime,
3639         packet_count, octet_count);
3640
3641     /* fill in sender report info */
3642     gst_rtcp_packet_sr_set_sender_info (packet, own->ssrc,
3643         sess->timestamp_sender_reports ? ntptime : 0,
3644         sess->timestamp_sender_reports ? rtptime : 0,
3645         packet_count, octet_count);
3646   } else {
3647     /* we are only receiver, create RR */
3648     GST_DEBUG ("create RR for SSRC %08x", own->ssrc);
3649     gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_RR, packet);
3650     gst_rtcp_packet_rr_set_ssrc (packet, own->ssrc);
3651   }
3652 }
3653
3654 /* construct a Sender or Receiver Report */
3655 static void
3656 session_report_blocks (const gchar * key, RTPSource * source, ReportData * data)
3657 {
3658   RTPSession *sess = data->sess;
3659   GstRTCPPacket *packet = &data->packet;
3660   guint8 fractionlost;
3661   gint32 packetslost;
3662   guint32 exthighestseq, jitter;
3663   guint32 lsr, dlsr;
3664
3665   /* don't report for sources in future generations */
3666   if (((gint16) (source->generation - sess->generation)) > 0) {
3667     GST_DEBUG ("source %08x generation %u > %u", source->ssrc,
3668         source->generation, sess->generation);
3669     return;
3670   }
3671
3672   if (g_hash_table_contains (source->reported_in_sr_of,
3673           GUINT_TO_POINTER (data->source->ssrc))) {
3674     GST_DEBUG ("source %08x already reported in this generation", source->ssrc);
3675     return;
3676   }
3677
3678   if (gst_rtcp_packet_get_rb_count (packet) == GST_RTCP_MAX_RB_COUNT) {
3679     GST_DEBUG ("max RB count reached");
3680     return;
3681   }
3682
3683   /* only report about remote sources */
3684   if (source->internal)
3685     goto reported;
3686
3687   if (!RTP_SOURCE_IS_SENDER (source)) {
3688     GST_DEBUG ("source %08x not sender", source->ssrc);
3689     goto reported;
3690   }
3691
3692   if (source->disable_rtcp) {
3693     GST_DEBUG ("source %08x has RTCP disabled", source->ssrc);
3694     goto reported;
3695   }
3696
3697   GST_DEBUG ("create RB for SSRC %08x", source->ssrc);
3698
3699   /* get new stats */
3700   rtp_source_get_new_rb (source, data->current_time, &fractionlost,
3701       &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
3702
3703   /* store last generated RR packet */
3704   source->last_rr.is_valid = TRUE;
3705   source->last_rr.fractionlost = fractionlost;
3706   source->last_rr.packetslost = packetslost;
3707   source->last_rr.exthighestseq = exthighestseq;
3708   source->last_rr.jitter = jitter;
3709   source->last_rr.lsr = lsr;
3710   source->last_rr.dlsr = dlsr;
3711
3712   /* packet is not yet filled, add report block for this source. */
3713   gst_rtcp_packet_add_rb (packet, source->ssrc, fractionlost, packetslost,
3714       exthighestseq, jitter, lsr, dlsr);
3715
3716 reported:
3717   g_hash_table_add (source->reported_in_sr_of,
3718       GUINT_TO_POINTER (data->source->ssrc));
3719 }
3720
3721 /* construct FIR */
3722 static void
3723 session_add_fir (const gchar * key, RTPSource * source, ReportData * data)
3724 {
3725   GstRTCPPacket *packet = &data->packet;
3726   guint16 len;
3727   guint8 *fci_data;
3728
3729   if (!source->send_fir)
3730     return;
3731
3732   len = gst_rtcp_packet_fb_get_fci_length (packet);
3733   if (!gst_rtcp_packet_fb_set_fci_length (packet, len + 2))
3734     /* exit because the packet is full, will put next request in a
3735      * further packet */
3736     return;
3737
3738   fci_data = gst_rtcp_packet_fb_get_fci (packet) + (len * 4);
3739
3740   GST_WRITE_UINT32_BE (fci_data, source->ssrc);
3741   fci_data += 4;
3742   fci_data[0] = source->current_send_fir_seqnum;
3743   fci_data[1] = fci_data[2] = fci_data[3] = 0;
3744
3745   source->send_fir = FALSE;
3746   source->stats.sent_fir_count++;
3747 }
3748
3749 static void
3750 session_fir (RTPSession * sess, ReportData * data)
3751 {
3752   GstRTCPBuffer *rtcp = &data->rtcpbuf;
3753   GstRTCPPacket *packet = &data->packet;
3754
3755   if (!gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_PSFB, packet))
3756     return;
3757
3758   gst_rtcp_packet_fb_set_type (packet, GST_RTCP_PSFB_TYPE_FIR);
3759   gst_rtcp_packet_fb_set_sender_ssrc (packet, data->source->ssrc);
3760   gst_rtcp_packet_fb_set_media_ssrc (packet, 0);
3761
3762   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3763       (GHFunc) session_add_fir, data);
3764
3765   if (gst_rtcp_packet_fb_get_fci_length (packet) == 0)
3766     gst_rtcp_packet_remove (packet);
3767   else
3768     data->may_suppress = FALSE;
3769 }
3770
3771 static gboolean
3772 has_pli_compare_func (gconstpointer a, gconstpointer ignored)
3773 {
3774   GstRTCPPacket packet;
3775   GstRTCPBuffer rtcp = { NULL, };
3776   gboolean ret = FALSE;
3777
3778   gst_rtcp_buffer_map ((GstBuffer *) a, GST_MAP_READ, &rtcp);
3779
3780   if (gst_rtcp_buffer_get_first_packet (&rtcp, &packet)) {
3781     if (gst_rtcp_packet_get_type (&packet) == GST_RTCP_TYPE_PSFB &&
3782         gst_rtcp_packet_fb_get_type (&packet) == GST_RTCP_PSFB_TYPE_PLI)
3783       ret = TRUE;
3784   }
3785
3786   gst_rtcp_buffer_unmap (&rtcp);
3787
3788   return ret;
3789 }
3790
3791 /* construct PLI */
3792 static void
3793 session_pli (const gchar * key, RTPSource * source, ReportData * data)
3794 {
3795   GstRTCPBuffer *rtcp = &data->rtcpbuf;
3796   GstRTCPPacket *packet = &data->packet;
3797
3798   if (!source->send_pli)
3799     return;
3800
3801   if (rtp_source_has_retained (source, has_pli_compare_func, NULL))
3802     return;
3803
3804   if (!gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_PSFB, packet))
3805     /* exit because the packet is full, will put next request in a
3806      * further packet */
3807     return;
3808
3809   gst_rtcp_packet_fb_set_type (packet, GST_RTCP_PSFB_TYPE_PLI);
3810   gst_rtcp_packet_fb_set_sender_ssrc (packet, data->source->ssrc);
3811   gst_rtcp_packet_fb_set_media_ssrc (packet, source->ssrc);
3812
3813   source->send_pli = FALSE;
3814   data->may_suppress = FALSE;
3815
3816   source->stats.sent_pli_count++;
3817 }
3818
3819 /* construct NACK */
3820 static void
3821 session_nack (const gchar * key, RTPSource * source, ReportData * data)
3822 {
3823   RTPSession *sess = data->sess;
3824   GstRTCPBuffer *rtcp = &data->rtcpbuf;
3825   GstRTCPPacket *packet = &data->packet;
3826   guint16 *nacks;
3827   GstClockTime *nack_deadlines;
3828   guint n_nacks, i = 0;
3829   guint nacked_seqnums = 0;
3830   guint16 n_fb_nacks = 0;
3831   guint8 *fci_data;
3832
3833   if (!source->send_nack)
3834     return;
3835
3836   nacks = rtp_source_get_nacks (source, &n_nacks);
3837   nack_deadlines = rtp_source_get_nack_deadlines (source, NULL);
3838   GST_DEBUG ("%u NACKs current time %" GST_TIME_FORMAT, n_nacks,
3839       GST_TIME_ARGS (data->current_time));
3840
3841   /* cleanup expired nacks */
3842   for (i = 0; i < n_nacks; i++) {
3843     GST_DEBUG ("#%u deadline %" GST_TIME_FORMAT, nacks[i],
3844         GST_TIME_ARGS (nack_deadlines[i]));
3845     if (nack_deadlines[i] >= data->current_time)
3846       break;
3847   }
3848
3849   if (data->is_early) {
3850     /* don't remove them all if this is an early RTCP packet. It may happen
3851      * that the NACKs are late due to high RTT, not sending NACKs at all would
3852      * keep the RTX RTT stats high and maintain a dropping state. */
3853     i = MIN (n_nacks - 1, i);
3854   }
3855
3856   if (i) {
3857     GST_WARNING ("Removing %u expired NACKS", i);
3858     rtp_source_clear_nacks (source, i);
3859     n_nacks -= i;
3860     if (n_nacks == 0)
3861       return;
3862   }
3863
3864   /* allow overriding NACK to packet conversion */
3865   if (g_signal_has_handler_pending (sess,
3866           rtp_session_signals[SIGNAL_ON_SENDING_NACKS], 0, TRUE)) {
3867     /* this is needed as it will actually resize the buffer */
3868     gst_rtcp_buffer_unmap (rtcp);
3869
3870     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_NACKS], 0,
3871         data->source->ssrc, source->ssrc, source->nacks, data->rtcp,
3872         &nacked_seqnums);
3873
3874     /* and now remap for the remaining work */
3875     gst_rtcp_buffer_map (data->rtcp, GST_MAP_READWRITE, rtcp);
3876
3877     if (nacked_seqnums > 0)
3878       goto done;
3879   }
3880
3881   if (!gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_RTPFB, packet))
3882     /* exit because the packet is full, will put next request in a
3883      * further packet */
3884     return;
3885
3886   gst_rtcp_packet_fb_set_type (packet, GST_RTCP_RTPFB_TYPE_NACK);
3887   gst_rtcp_packet_fb_set_sender_ssrc (packet, data->source->ssrc);
3888   gst_rtcp_packet_fb_set_media_ssrc (packet, source->ssrc);
3889
3890   if (!gst_rtcp_packet_fb_set_fci_length (packet, 1)) {
3891     gst_rtcp_packet_remove (packet);
3892     GST_WARNING ("no nacks fit in the packet");
3893     return;
3894   }
3895
3896   fci_data = gst_rtcp_packet_fb_get_fci (packet);
3897   for (i = 0; i < n_nacks; i = nacked_seqnums) {
3898     guint16 seqnum = nacks[i];
3899     guint16 blp = 0;
3900     guint j;
3901
3902     if (!gst_rtcp_packet_fb_set_fci_length (packet, n_fb_nacks + 1))
3903       break;
3904
3905     n_fb_nacks++;
3906     nacked_seqnums++;
3907
3908     for (j = i + 1; j < n_nacks; j++) {
3909       gint diff;
3910
3911       diff = gst_rtp_buffer_compare_seqnum (seqnum, nacks[j]);
3912       GST_TRACE ("[%u][%u] %u %u diff %i", i, j, seqnum, nacks[j], diff);
3913       if (diff > 16)
3914         break;
3915
3916       blp |= 1 << (diff - 1);
3917       nacked_seqnums++;
3918     }
3919
3920     GST_WRITE_UINT32_BE (fci_data, seqnum << 16 | blp);
3921     fci_data += 4;
3922   }
3923
3924   GST_DEBUG ("Sent %u seqnums into %u FB NACKs", nacked_seqnums, n_fb_nacks);
3925   source->stats.sent_nack_count += n_fb_nacks;
3926
3927 done:
3928   data->nacked_seqnums += nacked_seqnums;
3929   rtp_source_clear_nacks (source, nacked_seqnums);
3930   data->may_suppress = FALSE;
3931 }
3932
3933 /* perform cleanup of sources that timed out */
3934 static void
3935 session_cleanup (const gchar * key, RTPSource * source, ReportData * data)
3936 {
3937   gboolean remove = FALSE;
3938   gboolean byetimeout = FALSE;
3939   gboolean sendertimeout = FALSE;
3940   gboolean is_sender, is_active;
3941   RTPSession *sess = data->sess;
3942   GstClockTime interval, binterval;
3943   GstClockTime btime;
3944
3945   GST_DEBUG ("look at %08x, generation %u", source->ssrc, source->generation);
3946
3947   /* check for outdated collisions */
3948   if (source->internal) {
3949     GST_DEBUG ("Timing out collisions for %x", source->ssrc);
3950     rtp_source_timeout (source, data->current_time, data->running_time,
3951         sess->rtcp_feedback_retention_window);
3952   }
3953
3954   /* nothing else to do when without RTCP */
3955   if (data->interval == GST_CLOCK_TIME_NONE)
3956     return;
3957
3958   is_sender = RTP_SOURCE_IS_SENDER (source);
3959   is_active = RTP_SOURCE_IS_ACTIVE (source);
3960
3961   /* our own rtcp interval may have been forced low by secondary configuration,
3962    * while sender side may still operate with higher interval,
3963    * so do not just take our interval to decide on timing out sender,
3964    * but take (if data->interval <= 5 * GST_SECOND):
3965    *   interval = CLAMP (sender_interval, data->interval, 5 * GST_SECOND)
3966    * where sender_interval is difference between last 2 received RTCP reports
3967    */
3968   if (data->interval >= 5 * GST_SECOND || source->internal) {
3969     binterval = data->interval;
3970   } else {
3971     GST_LOG ("prev_rtcp %" GST_TIME_FORMAT ", last_rtcp %" GST_TIME_FORMAT,
3972         GST_TIME_ARGS (source->stats.prev_rtcptime),
3973         GST_TIME_ARGS (source->stats.last_rtcptime));
3974     /* if not received enough yet, fallback to larger default */
3975     if (source->stats.last_rtcptime > source->stats.prev_rtcptime)
3976       binterval = source->stats.last_rtcptime - source->stats.prev_rtcptime;
3977     else
3978       binterval = 5 * GST_SECOND;
3979     binterval = CLAMP (binterval, data->interval, 5 * GST_SECOND);
3980   }
3981   GST_LOG ("timeout base interval %" GST_TIME_FORMAT,
3982       GST_TIME_ARGS (binterval));
3983
3984   if (!source->internal && source->marked_bye) {
3985     /* if we received a BYE from the source, remove the source after some
3986      * time. */
3987     if (data->current_time > source->bye_time &&
3988         data->current_time - source->bye_time > sess->stats.bye_timeout) {
3989       GST_DEBUG ("removing BYE source %08x", source->ssrc);
3990       remove = TRUE;
3991       byetimeout = TRUE;
3992     }
3993   }
3994
3995   if (source->internal && source->sent_bye) {
3996     GST_DEBUG ("removing internal source that has sent BYE %08x", source->ssrc);
3997     remove = TRUE;
3998   }
3999
4000   /* sources that were inactive for more than 5 times the deterministic reporting
4001    * interval get timed out. the min timeout is 5 seconds. */
4002   /* mind old time that might pre-date last time going to PLAYING */
4003   btime = MAX (source->last_activity, sess->start_time);
4004   if (data->current_time > btime) {
4005     interval = MAX (binterval * 5, 5 * GST_SECOND);
4006     if (data->current_time - btime > interval) {
4007       GST_DEBUG ("removing timeout source %08x, last %" GST_TIME_FORMAT,
4008           source->ssrc, GST_TIME_ARGS (btime));
4009       if (source->internal) {
4010         /* this is an internal source that is not using our suggested ssrc.
4011          * since there must be another source using this ssrc, we can remove
4012          * this one instead of making it a receiver forever */
4013         if (source->ssrc != sess->suggested_ssrc) {
4014           rtp_source_mark_bye (source, "timed out");
4015           /* do not schedule bye here, since we are inside the RTCP timeout
4016            * processing and scheduling bye will interfere with SR/RR sending */
4017         }
4018       } else {
4019         remove = TRUE;
4020       }
4021     }
4022   }
4023
4024   /* senders that did not send for a long time become a receiver, this also
4025    * holds for our own sources. */
4026   if (is_sender) {
4027     /* mind old time that might pre-date last time going to PLAYING */
4028     btime = MAX (source->last_rtp_activity, sess->start_time);
4029     if (data->current_time > btime) {
4030       interval = MAX (binterval * 2, 5 * GST_SECOND);
4031       if (data->current_time - btime > interval) {
4032         GST_DEBUG ("sender source %08x timed out and became receiver, last %"
4033             GST_TIME_FORMAT, source->ssrc, GST_TIME_ARGS (btime));
4034         sendertimeout = TRUE;
4035       }
4036     }
4037   }
4038
4039   if (remove) {
4040     sess->total_sources--;
4041     if (is_sender) {
4042       sess->stats.sender_sources--;
4043       if (source->internal)
4044         sess->stats.internal_sender_sources--;
4045     }
4046     if (is_active)
4047       sess->stats.active_sources--;
4048
4049     if (source->internal)
4050       sess->stats.internal_sources--;
4051
4052     if (byetimeout)
4053       on_bye_timeout (sess, source);
4054     else
4055       on_timeout (sess, source);
4056   } else {
4057     if (sendertimeout) {
4058       source->is_sender = FALSE;
4059       sess->stats.sender_sources--;
4060       if (source->internal)
4061         sess->stats.internal_sender_sources--;
4062
4063       on_sender_timeout (sess, source);
4064     }
4065     /* count how many source to report in this generation */
4066     if (((gint16) (source->generation - sess->generation)) <= 0)
4067       data->num_to_report++;
4068   }
4069   source->closing = remove;
4070 }
4071
4072 static void
4073 session_sdes (RTPSession * sess, ReportData * data)
4074 {
4075   GstRTCPPacket *packet = &data->packet;
4076   const GstStructure *sdes;
4077   gint i, n_fields;
4078   GstRTCPBuffer *rtcp = &data->rtcpbuf;
4079
4080   /* add SDES packet */
4081   gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_SDES, packet);
4082
4083   gst_rtcp_packet_sdes_add_item (packet, data->source->ssrc);
4084
4085   sdes = rtp_source_get_sdes_struct (data->source);
4086
4087   /* add all fields in the structure, the order is not important. */
4088   n_fields = gst_structure_n_fields (sdes);
4089   for (i = 0; i < n_fields; ++i) {
4090     const gchar *field;
4091     const gchar *value;
4092     GstRTCPSDESType type;
4093
4094     field = gst_structure_nth_field_name (sdes, i);
4095     if (field == NULL)
4096       continue;
4097     value = gst_structure_get_string (sdes, field);
4098     if (value == NULL)
4099       continue;
4100     type = gst_rtcp_sdes_name_to_type (field);
4101
4102     /* Early packets are minimal and only include the CNAME */
4103     if (data->is_early && type != GST_RTCP_SDES_CNAME)
4104       continue;
4105
4106     if (type > GST_RTCP_SDES_END && type < GST_RTCP_SDES_PRIV) {
4107       gst_rtcp_packet_sdes_add_entry (packet, type, strlen (value),
4108           (const guint8 *) value);
4109     } else if (type == GST_RTCP_SDES_PRIV) {
4110       gsize prefix_len;
4111       gsize value_len;
4112       gsize data_len;
4113       guint8 data[256];
4114
4115       /* don't accept entries that are too big */
4116       prefix_len = strlen (field);
4117       if (prefix_len > 255)
4118         continue;
4119       value_len = strlen (value);
4120       if (value_len > 255)
4121         continue;
4122       data_len = 1 + prefix_len + value_len;
4123       if (data_len > 255)
4124         continue;
4125
4126       data[0] = prefix_len;
4127       memcpy (&data[1], field, prefix_len);
4128       memcpy (&data[1 + prefix_len], value, value_len);
4129
4130       gst_rtcp_packet_sdes_add_entry (packet, type, data_len, data);
4131     }
4132   }
4133
4134   data->has_sdes = TRUE;
4135 }
4136
4137 /* schedule a BYE packet */
4138 static void
4139 make_source_bye (RTPSession * sess, RTPSource * source, ReportData * data)
4140 {
4141   GstRTCPPacket *packet = &data->packet;
4142   GstRTCPBuffer *rtcp = &data->rtcpbuf;
4143
4144   /* add SDES */
4145   session_sdes (sess, data);
4146   /* add a BYE packet */
4147   gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_BYE, packet);
4148   gst_rtcp_packet_bye_add_ssrc (packet, source->ssrc);
4149   if (source->bye_reason)
4150     gst_rtcp_packet_bye_set_reason (packet, source->bye_reason);
4151
4152   /* we have a BYE packet now */
4153   source->sent_bye = TRUE;
4154 }
4155
4156 static gboolean
4157 is_rtcp_time (RTPSession * sess, GstClockTime current_time, ReportData * data)
4158 {
4159   GstClockTime new_send_time;
4160   GstClockTime interval;
4161   RTPSessionStats *stats;
4162
4163   if (sess->scheduled_bye)
4164     stats = &sess->bye_stats;
4165   else
4166     stats = &sess->stats;
4167
4168   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
4169     data->is_early = TRUE;
4170   else
4171     data->is_early = FALSE;
4172
4173   if (data->is_early && sess->next_early_rtcp_time <= current_time) {
4174     GST_DEBUG ("early feedback %" GST_TIME_FORMAT " <= now %"
4175         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_early_rtcp_time),
4176         GST_TIME_ARGS (current_time));
4177   } else if (sess->next_rtcp_check_time == GST_CLOCK_TIME_NONE ||
4178       sess->next_rtcp_check_time > current_time) {
4179     GST_DEBUG ("no check time yet, next %" GST_TIME_FORMAT " > now %"
4180         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_rtcp_check_time),
4181         GST_TIME_ARGS (current_time));
4182     return FALSE;
4183   }
4184
4185   /* take interval and add jitter */
4186   interval = data->interval;
4187   if (interval != GST_CLOCK_TIME_NONE)
4188     interval = rtp_stats_add_rtcp_jitter (stats, interval);
4189
4190   if (sess->last_rtcp_check_time != GST_CLOCK_TIME_NONE) {
4191     /* perform forward reconsideration */
4192     if (interval != GST_CLOCK_TIME_NONE) {
4193       GstClockTime elapsed;
4194
4195       /* get elapsed time since we last reported */
4196       elapsed = current_time - sess->last_rtcp_check_time;
4197
4198       GST_DEBUG ("forward reconsideration %" GST_TIME_FORMAT ", elapsed %"
4199           GST_TIME_FORMAT, GST_TIME_ARGS (interval), GST_TIME_ARGS (elapsed));
4200       new_send_time = interval + sess->last_rtcp_check_time;
4201     } else {
4202       new_send_time = sess->last_rtcp_check_time;
4203     }
4204   } else {
4205     /* If this is the first RTCP packet, we can reconsider anything based
4206      * on the last RTCP send time because there was none.
4207      */
4208     g_warn_if_fail (!data->is_early);
4209     data->is_early = FALSE;
4210     new_send_time = current_time;
4211   }
4212
4213   if (!data->is_early) {
4214     /* check if reconsideration */
4215     if (new_send_time == GST_CLOCK_TIME_NONE || current_time < new_send_time) {
4216       GST_DEBUG ("reconsider RTCP for %" GST_TIME_FORMAT,
4217           GST_TIME_ARGS (new_send_time));
4218       /* store new check time */
4219       sess->next_rtcp_check_time = new_send_time;
4220       sess->last_rtcp_interval = interval;
4221       return FALSE;
4222     }
4223
4224     sess->last_rtcp_interval = interval;
4225     if ((sess->rtp_profile == GST_RTP_PROFILE_AVPF
4226             || sess->rtp_profile == GST_RTP_PROFILE_SAVPF)
4227         && interval != GST_CLOCK_TIME_NONE) {
4228       /* Apply the rules from RFC 4585 section 3.5.3 */
4229       if (stats->min_interval != 0 && !sess->first_rtcp) {
4230         GstClockTime T_rr_current_interval =
4231             g_random_double_range (0.5, 1.5) * stats->min_interval * GST_SECOND;
4232
4233         if (T_rr_current_interval > interval) {
4234           GST_DEBUG ("Adjusting interval for t-rr-interval: %" GST_TIME_FORMAT
4235               " > %" GST_TIME_FORMAT, GST_TIME_ARGS (T_rr_current_interval),
4236               GST_TIME_ARGS (interval));
4237           interval = T_rr_current_interval;
4238         }
4239       }
4240     }
4241     sess->next_rtcp_check_time = current_time + interval;
4242   }
4243
4244
4245   GST_DEBUG ("can send RTCP now, next %" GST_TIME_FORMAT,
4246       GST_TIME_ARGS (sess->next_rtcp_check_time));
4247
4248   return TRUE;
4249 }
4250
4251 static void
4252 clone_ssrcs_hashtable (gchar * key, RTPSource * source, GHashTable * hash_table)
4253 {
4254   g_hash_table_insert (hash_table, key, g_object_ref (source));
4255 }
4256
4257 static gboolean
4258 remove_closing_sources (const gchar * key, RTPSource * source,
4259     ReportData * data)
4260 {
4261   if (source->closing)
4262     return TRUE;
4263
4264   if (source->send_fir)
4265     data->have_fir = TRUE;
4266   if (source->send_pli)
4267     data->have_pli = TRUE;
4268   if (source->send_nack)
4269     data->have_nack = TRUE;
4270
4271   return FALSE;
4272 }
4273
4274 static void
4275 generate_twcc (const gchar * key, RTPSource * source, ReportData * data)
4276 {
4277   RTPSession *sess = data->sess;
4278   GstBuffer *buf;
4279
4280   /* only generate RTCP for active internal sources */
4281   if (!source->internal || source->sent_bye)
4282     return;
4283
4284   /* ignore other sources when we do the timeout after a scheduled BYE */
4285   if (sess->scheduled_bye && !source->marked_bye)
4286     return;
4287
4288   /* skip if RTCP is disabled */
4289   if (source->disable_rtcp) {
4290     GST_DEBUG ("source %08x has RTCP disabled", source->ssrc);
4291     return;
4292   }
4293
4294   while ((buf = rtp_twcc_manager_get_feedback (sess->twcc, source->ssrc))) {
4295     ReportOutput *output = g_slice_new (ReportOutput);
4296     output->source = g_object_ref (source);
4297     output->is_bye = FALSE;
4298     output->buffer = buf;
4299     /* queue the RTCP packet to push later */
4300     g_queue_push_tail (&data->output, output);
4301   }
4302 }
4303
4304
4305 static void
4306 generate_rtcp (const gchar * key, RTPSource * source, ReportData * data)
4307 {
4308   RTPSession *sess = data->sess;
4309   gboolean is_bye = FALSE;
4310   ReportOutput *output;
4311
4312   /* only generate RTCP for active internal sources */
4313   if (!source->internal || source->sent_bye)
4314     return;
4315
4316   /* ignore other sources when we do the timeout after a scheduled BYE */
4317   if (sess->scheduled_bye && !source->marked_bye)
4318     return;
4319
4320   /* skip if RTCP is disabled */
4321   if (source->disable_rtcp) {
4322     GST_DEBUG ("source %08x has RTCP disabled", source->ssrc);
4323     return;
4324   }
4325
4326   data->source = source;
4327
4328   /* open packet */
4329   session_start_rtcp (sess, data);
4330
4331   if (source->marked_bye) {
4332     /* send BYE */
4333     make_source_bye (sess, source, data);
4334     is_bye = TRUE;
4335   } else if (!data->is_early) {
4336     /* loop over all known sources and add report blocks. If we are early, we
4337      * just make a minimal RTCP packet and skip this step */
4338     g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4339         (GHFunc) session_report_blocks, data);
4340   }
4341   if (!data->has_sdes && (!data->is_early || !sess->reduced_size_rtcp))
4342     session_sdes (sess, data);
4343
4344   if (data->have_fir)
4345     session_fir (sess, data);
4346
4347   if (data->have_pli)
4348     g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4349         (GHFunc) session_pli, data);
4350
4351   if (data->have_nack)
4352     g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4353         (GHFunc) session_nack, data);
4354
4355   gst_rtcp_buffer_unmap (&data->rtcpbuf);
4356
4357   output = g_slice_new (ReportOutput);
4358   output->source = g_object_ref (source);
4359   output->is_bye = is_bye;
4360   output->buffer = data->rtcp;
4361   /* queue the RTCP packet to push later */
4362   g_queue_push_tail (&data->output, output);
4363 }
4364
4365 static void
4366 update_generation (const gchar * key, RTPSource * source, ReportData * data)
4367 {
4368   RTPSession *sess = data->sess;
4369
4370   if (g_hash_table_size (source->reported_in_sr_of) >=
4371       sess->stats.internal_sources) {
4372     /* source is reported, move to next generation */
4373     source->generation = sess->generation + 1;
4374     g_hash_table_remove_all (source->reported_in_sr_of);
4375
4376     GST_LOG ("reported source %x, new generation: %d", source->ssrc,
4377         source->generation);
4378
4379     /* if we reported all sources in this generation, move to next */
4380     if (--data->num_to_report == 0) {
4381       sess->generation++;
4382       GST_DEBUG ("all reported, generation now %u", sess->generation);
4383     }
4384   }
4385 }
4386
4387 static void
4388 schedule_remaining_nacks (const gchar * key, RTPSource * source,
4389     ReportData * data)
4390 {
4391   RTPSession *sess = data->sess;
4392   GstClockTime *nack_deadlines;
4393   GstClockTime deadline;
4394   guint n_nacks;
4395
4396   if (!source->send_nack)
4397     return;
4398
4399   /* the scheduling is entirely based on available bandwidth, just take the
4400    * biggest seqnum, which will have the largest deadline to request early
4401    * RTCP. */
4402   nack_deadlines = rtp_source_get_nack_deadlines (source, &n_nacks);
4403   deadline = nack_deadlines[n_nacks - 1];
4404   RTP_SESSION_UNLOCK (sess);
4405   rtp_session_send_rtcp_with_deadline (sess, deadline);
4406   RTP_SESSION_LOCK (sess);
4407 }
4408
4409 static gboolean
4410 rtp_session_are_all_sources_bye (RTPSession * sess)
4411 {
4412   GHashTableIter iter;
4413   RTPSource *src;
4414
4415   RTP_SESSION_LOCK (sess);
4416   g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
4417   while (g_hash_table_iter_next (&iter, NULL, (gpointer *) & src)) {
4418     if (src->internal && !src->sent_bye) {
4419       RTP_SESSION_UNLOCK (sess);
4420       return FALSE;
4421     }
4422   }
4423   RTP_SESSION_UNLOCK (sess);
4424
4425   return TRUE;
4426 }
4427
4428 /**
4429  * rtp_session_on_timeout:
4430  * @sess: an #RTPSession
4431  * @current_time: the current system time
4432  * @ntpnstime: the current NTP time in nanoseconds
4433  * @running_time: the current running_time of the pipeline
4434  *
4435  * Perform maintenance actions after the timeout obtained with
4436  * rtp_session_next_timeout() expired.
4437  *
4438  * This function will perform timeouts of receivers and senders, send a BYE
4439  * packet or generate RTCP packets with current session stats.
4440  *
4441  * This function can call the #RTPSessionSendRTCP callback, possibly multiple
4442  * times, for each packet that should be processed.
4443  *
4444  * Returns: a #GstFlowReturn.
4445  */
4446 GstFlowReturn
4447 rtp_session_on_timeout (RTPSession * sess, GstClockTime current_time,
4448     guint64 ntpnstime, GstClockTime running_time)
4449 {
4450   GstFlowReturn result = GST_FLOW_OK;
4451   ReportData data = { GST_RTCP_BUFFER_INIT };
4452   GHashTable *table_copy;
4453   ReportOutput *output;
4454   gboolean all_empty = FALSE;
4455
4456   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
4457
4458   GST_DEBUG ("reporting at %" GST_TIME_FORMAT ", NTP time %" GST_TIME_FORMAT
4459       ", running-time %" GST_TIME_FORMAT, GST_TIME_ARGS (current_time),
4460       GST_TIME_ARGS (ntpnstime), GST_TIME_ARGS (running_time));
4461
4462   data.sess = sess;
4463   data.current_time = current_time;
4464   data.ntpnstime = ntpnstime;
4465   data.running_time = running_time;
4466   data.num_to_report = 0;
4467   data.may_suppress = FALSE;
4468   data.nacked_seqnums = 0;
4469   g_queue_init (&data.output);
4470
4471   RTP_SESSION_LOCK (sess);
4472   /* get a new interval, we need this for various cleanups etc */
4473   data.interval = calculate_rtcp_interval (sess, TRUE, sess->first_rtcp);
4474
4475   GST_DEBUG ("interval %" GST_TIME_FORMAT, GST_TIME_ARGS (data.interval));
4476
4477   /* we need an internal source now */
4478   if (sess->stats.internal_sources == 0) {
4479     RTPSource *source;
4480     gboolean created;
4481
4482     source = obtain_internal_source (sess, sess->suggested_ssrc, &created,
4483         current_time);
4484     sess->internal_ssrc_set = TRUE;
4485
4486     if (created)
4487       on_new_sender_ssrc (sess, source);
4488
4489     g_object_unref (source);
4490   }
4491
4492   sess->conflicting_addresses =
4493       timeout_conflicting_addresses (sess->conflicting_addresses, current_time);
4494
4495   /* Make a local copy of the hashtable. We need to do this because the
4496    * cleanup stage below releases the session lock. */
4497   table_copy = g_hash_table_new_full (NULL, NULL, NULL,
4498       (GDestroyNotify) g_object_unref);
4499   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4500       (GHFunc) clone_ssrcs_hashtable, table_copy);
4501
4502   /* Clean up the session, mark the source for removing, this might release the
4503    * session lock. */
4504   g_hash_table_foreach (table_copy, (GHFunc) session_cleanup, &data);
4505   g_hash_table_destroy (table_copy);
4506
4507   /* Now remove the marked sources */
4508   g_hash_table_foreach_remove (sess->ssrcs[sess->mask_idx],
4509       (GHRFunc) remove_closing_sources, &data);
4510
4511   /* update point-to-point status */
4512   session_update_ptp (sess);
4513
4514   /* see if we need to generate SR or RR packets */
4515   if (!is_rtcp_time (sess, current_time, &data))
4516     goto done;
4517
4518   /* check if all the buffers are empty after generation */
4519   all_empty = TRUE;
4520
4521   GST_DEBUG
4522       ("doing RTCP generation %u for %u sources, early %d, may suppress %d",
4523       sess->generation, data.num_to_report, data.is_early, data.may_suppress);
4524
4525   /* generate RTCP for all internal sources */
4526   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4527       (GHFunc) generate_rtcp, &data);
4528
4529   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4530       (GHFunc) generate_twcc, &data);
4531
4532   /* update the generation for all the sources that have been reported */
4533   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4534       (GHFunc) update_generation, &data);
4535
4536   /* we keep track of the last report time in order to timeout inactive
4537    * receivers or senders */
4538   if (!data.is_early) {
4539     GST_DEBUG ("Time since last regular RTCP: %" GST_TIME_FORMAT " - %"
4540         GST_TIME_FORMAT " = %" GST_TIME_FORMAT,
4541         GST_TIME_ARGS (data.current_time),
4542         GST_TIME_ARGS (sess->last_rtcp_send_time),
4543         GST_TIME_ARGS (data.current_time - sess->last_rtcp_send_time));
4544     sess->last_rtcp_send_time = data.current_time;
4545   }
4546
4547   GST_DEBUG ("Time since last RTCP: %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT
4548       " = %" GST_TIME_FORMAT, GST_TIME_ARGS (data.current_time),
4549       GST_TIME_ARGS (sess->last_rtcp_check_time),
4550       GST_TIME_ARGS (data.current_time - sess->last_rtcp_check_time));
4551   sess->last_rtcp_check_time = data.current_time;
4552   sess->first_rtcp = FALSE;
4553   sess->next_early_rtcp_time = GST_CLOCK_TIME_NONE;
4554   sess->scheduled_bye = FALSE;
4555
4556 done:
4557   RTP_SESSION_UNLOCK (sess);
4558
4559   /* notify about updated statistics */
4560   g_object_notify (G_OBJECT (sess), "stats");
4561
4562   /* push out the RTCP packets */
4563   while ((output = g_queue_pop_head (&data.output))) {
4564     gboolean do_not_suppress, empty_buffer;
4565     GstBuffer *buffer = output->buffer;
4566     RTPSource *source = output->source;
4567
4568     /* Give the user a change to add its own packet */
4569     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_RTCP], 0,
4570         buffer, data.is_early, &do_not_suppress);
4571
4572     empty_buffer = gst_buffer_get_size (buffer) == 0;
4573
4574     if (!empty_buffer)
4575       all_empty = FALSE;
4576
4577     if (sess->callbacks.send_rtcp &&
4578         !empty_buffer && (do_not_suppress || !data.may_suppress)) {
4579       guint packet_size;
4580
4581       packet_size = gst_buffer_get_size (buffer) + sess->header_len;
4582
4583       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, packet_size);
4584       GST_DEBUG ("%p, sending RTCP packet, avg size %u, %u", &sess->stats,
4585           sess->stats.avg_rtcp_packet_size, packet_size);
4586       result =
4587           sess->callbacks.send_rtcp (sess, source, buffer,
4588           rtp_session_are_all_sources_bye (sess), sess->send_rtcp_user_data);
4589
4590       RTP_SESSION_LOCK (sess);
4591       sess->stats.nacks_sent += data.nacked_seqnums;
4592       on_sender_ssrc_active (sess, source);
4593       RTP_SESSION_UNLOCK (sess);
4594     } else {
4595       GST_DEBUG ("freeing packet callback: %p"
4596           " empty_buffer: %d, "
4597           " do_not_suppress: %d may_suppress: %d", sess->callbacks.send_rtcp,
4598           empty_buffer, do_not_suppress, data.may_suppress);
4599       if (!empty_buffer) {
4600         RTP_SESSION_LOCK (sess);
4601         sess->stats.nacks_dropped += data.nacked_seqnums;
4602         RTP_SESSION_UNLOCK (sess);
4603       }
4604       gst_buffer_unref (buffer);
4605     }
4606     g_object_unref (source);
4607     g_slice_free (ReportOutput, output);
4608   }
4609
4610   if (all_empty)
4611     GST_ERROR ("generated empty RTCP messages for all the sources");
4612
4613   /* schedule remaining nacks */
4614   RTP_SESSION_LOCK (sess);
4615   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
4616       (GHFunc) schedule_remaining_nacks, &data);
4617   RTP_SESSION_UNLOCK (sess);
4618
4619   return result;
4620 }
4621
4622 /**
4623  * rtp_session_request_early_rtcp:
4624  * @sess: an #RTPSession
4625  * @current_time: the current system time
4626  * @max_delay: maximum delay
4627  *
4628  * Request transmission of early RTCP
4629  *
4630  * Returns: %TRUE if the related RTCP can be scheduled.
4631  */
4632 gboolean
4633 rtp_session_request_early_rtcp (RTPSession * sess, GstClockTime current_time,
4634     GstClockTime max_delay)
4635 {
4636   GstClockTime T_dither_max, T_rr, offset = 0;
4637   gboolean ret;
4638   gboolean allow_early;
4639
4640   /* Implements the algorithm described in RFC 4585 section 3.5.2 */
4641
4642   RTP_SESSION_LOCK (sess);
4643
4644   /* We assume a feedback profile if something is requesting RTCP
4645    * to be sent */
4646   sess->rtp_profile = GST_RTP_PROFILE_AVPF;
4647
4648   /* Check if already requested */
4649   /*  RFC 4585 section 3.5.2 step 2 */
4650   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
4651     GST_LOG_OBJECT (sess, "already have next early rtcp time");
4652     ret = (current_time + max_delay > sess->next_early_rtcp_time);
4653     goto end;
4654   }
4655
4656   if (!GST_CLOCK_TIME_IS_VALID (sess->next_rtcp_check_time)) {
4657     GST_LOG_OBJECT (sess, "no next RTCP check time");
4658     ret = FALSE;
4659     goto end;
4660   }
4661
4662   /* RFC 4585 section 3.5.3 step 1
4663    * If no regular RTCP packet has been sent before, then a regular
4664    * RTCP packet has to be scheduled first and FB messages might be
4665    * included there
4666    */
4667   if (!GST_CLOCK_TIME_IS_VALID (sess->last_rtcp_send_time)) {
4668     GST_LOG_OBJECT (sess, "no RTCP sent yet");
4669
4670     if (current_time + max_delay > sess->next_rtcp_check_time) {
4671       GST_LOG_OBJECT (sess,
4672           "next scheduled time is soon %" GST_TIME_FORMAT " + %" GST_TIME_FORMAT
4673           " > %" GST_TIME_FORMAT, GST_TIME_ARGS (current_time),
4674           GST_TIME_ARGS (max_delay),
4675           GST_TIME_ARGS (sess->next_rtcp_check_time));
4676       ret = TRUE;
4677     } else {
4678       GST_LOG_OBJECT (sess,
4679           "can't allow early feedback, next scheduled time is too late %"
4680           GST_TIME_FORMAT " + %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4681           GST_TIME_ARGS (current_time), GST_TIME_ARGS (max_delay),
4682           GST_TIME_ARGS (sess->next_rtcp_check_time));
4683       ret = FALSE;
4684     }
4685     goto end;
4686   }
4687
4688   T_rr = sess->last_rtcp_interval;
4689
4690   /*  RFC 4585 section 3.5.2 step 2b */
4691   /* If the total sources is <=2, then there is only us and one peer */
4692   /* When there is one auxiliary stream the session can still do point
4693    * to point.
4694    */
4695   if (sess->is_doing_ptp) {
4696     T_dither_max = 0;
4697   } else {
4698     /* Divide by 2 because l = 0.5 */
4699     T_dither_max = T_rr;
4700     T_dither_max /= 2;
4701   }
4702
4703   /*  RFC 4585 section 3.5.2 step 3 */
4704   if (current_time + T_dither_max > sess->next_rtcp_check_time) {
4705     GST_LOG_OBJECT (sess,
4706         "don't send because of dither, next scheduled time is too soon %"
4707         GST_TIME_FORMAT " + %" GST_TIME_FORMAT " > %" GST_TIME_FORMAT,
4708         GST_TIME_ARGS (current_time), GST_TIME_ARGS (T_dither_max),
4709         GST_TIME_ARGS (sess->next_rtcp_check_time));
4710     ret = T_dither_max <= max_delay;
4711     goto end;
4712   }
4713
4714   /*  RFC 4585 section 3.5.2 step 4a and
4715    *  RFC 4585 section 3.5.2 step 6 */
4716   allow_early = FALSE;
4717   if (sess->last_rtcp_check_time == sess->last_rtcp_send_time) {
4718     /* Last time we sent a full RTCP packet, we can now immediately
4719      * send an early one as allow_early was reset to TRUE */
4720     allow_early = TRUE;
4721   } else if (sess->last_rtcp_check_time + T_rr <= current_time + max_delay) {
4722     /* Last packet we sent was an early RTCP packet and more than
4723      * T_rr has passed since then, meaning we would have suppressed
4724      * a regular RTCP packet already and reset allow_early to TRUE */
4725     allow_early = TRUE;
4726
4727     /* We have to offset a bit as T_rr has not passed yet, but will before
4728      * max_delay */
4729     if (sess->last_rtcp_check_time + T_rr > current_time)
4730       offset = (sess->last_rtcp_check_time + T_rr) - current_time;
4731   } else {
4732     GST_DEBUG_OBJECT (sess,
4733         "can't allow early RTCP yet: last regular %" GST_TIME_FORMAT ", %"
4734         GST_TIME_FORMAT " + %" GST_TIME_FORMAT " > %" GST_TIME_FORMAT " + %"
4735         GST_TIME_FORMAT, GST_TIME_ARGS (sess->last_rtcp_send_time),
4736         GST_TIME_ARGS (sess->last_rtcp_check_time), GST_TIME_ARGS (T_rr),
4737         GST_TIME_ARGS (current_time), GST_TIME_ARGS (max_delay));
4738   }
4739
4740   if (!allow_early) {
4741     /* Ignore the request a scheduled packet will be in time anyway */
4742     if (current_time + max_delay > sess->next_rtcp_check_time) {
4743       GST_LOG_OBJECT (sess,
4744           "next scheduled time is soon %" GST_TIME_FORMAT " + %" GST_TIME_FORMAT
4745           " > %" GST_TIME_FORMAT, GST_TIME_ARGS (current_time),
4746           GST_TIME_ARGS (max_delay),
4747           GST_TIME_ARGS (sess->next_rtcp_check_time));
4748       ret = TRUE;
4749     } else {
4750       GST_LOG_OBJECT (sess,
4751           "can't allow early feedback and next scheduled time is too late %"
4752           GST_TIME_FORMAT " + %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4753           GST_TIME_ARGS (current_time), GST_TIME_ARGS (max_delay),
4754           GST_TIME_ARGS (sess->next_rtcp_check_time));
4755       ret = FALSE;
4756     }
4757     goto end;
4758   }
4759
4760   /*  RFC 4585 section 3.5.2 step 4b */
4761   if (T_dither_max) {
4762     /* Schedule an early transmission later */
4763     sess->next_early_rtcp_time = g_random_double () * T_dither_max +
4764         current_time + offset;
4765   } else {
4766     /* If no dithering, schedule it for NOW */
4767     sess->next_early_rtcp_time = current_time + offset;
4768   }
4769
4770   GST_LOG_OBJECT (sess, "next early RTCP time %" GST_TIME_FORMAT
4771       ", next regular RTCP time %" GST_TIME_FORMAT,
4772       GST_TIME_ARGS (sess->next_early_rtcp_time),
4773       GST_TIME_ARGS (sess->next_rtcp_check_time));
4774   RTP_SESSION_UNLOCK (sess);
4775
4776   /* notify app of need to send packet early
4777    * and therefore of timeout change */
4778   if (sess->callbacks.reconsider)
4779     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
4780
4781   return TRUE;
4782
4783 end:
4784
4785   RTP_SESSION_UNLOCK (sess);
4786
4787   return ret;
4788 }
4789
4790 static gboolean
4791 rtp_session_send_rtcp_internal (RTPSession * sess, GstClockTime now,
4792     GstClockTime max_delay)
4793 {
4794   /* notify the application that we intend to send early RTCP */
4795   if (sess->callbacks.notify_early_rtcp)
4796     sess->callbacks.notify_early_rtcp (sess, sess->notify_early_rtcp_user_data);
4797
4798   return rtp_session_request_early_rtcp (sess, now, max_delay);
4799 }
4800
4801 static gboolean
4802 rtp_session_send_rtcp_with_deadline (RTPSession * sess, GstClockTime deadline)
4803 {
4804   GstClockTime now, max_delay;
4805
4806   if (!sess->callbacks.send_rtcp)
4807     return FALSE;
4808
4809   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
4810
4811   if (deadline < now)
4812     return FALSE;
4813
4814   max_delay = deadline - now;
4815
4816   return rtp_session_send_rtcp_internal (sess, now, max_delay);
4817 }
4818
4819 static gboolean
4820 rtp_session_send_rtcp (RTPSession * sess, GstClockTime max_delay)
4821 {
4822   GstClockTime now;
4823
4824   if (!sess->callbacks.send_rtcp)
4825     return FALSE;
4826
4827   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
4828
4829   return rtp_session_send_rtcp_internal (sess, now, max_delay);
4830 }
4831
4832 gboolean
4833 rtp_session_request_key_unit (RTPSession * sess, guint32 ssrc,
4834     gboolean fir, gint count)
4835 {
4836   RTPSource *src;
4837
4838   RTP_SESSION_LOCK (sess);
4839   src = find_source (sess, ssrc);
4840   if (src == NULL)
4841     goto no_source;
4842
4843   if (fir) {
4844     src->send_pli = FALSE;
4845     src->send_fir = TRUE;
4846
4847     if (count == -1 || count != src->last_fir_count)
4848       src->current_send_fir_seqnum++;
4849     src->last_fir_count = count;
4850   } else if (!src->send_fir) {
4851     src->send_pli = TRUE;
4852   }
4853   RTP_SESSION_UNLOCK (sess);
4854
4855   if (!rtp_session_send_rtcp (sess, 5 * GST_SECOND)) {
4856     GST_DEBUG ("FIR/PLI not sent early, sending with next regular RTCP");
4857   }
4858
4859   return TRUE;
4860
4861   /* ERRORS */
4862 no_source:
4863   {
4864     RTP_SESSION_UNLOCK (sess);
4865     return FALSE;
4866   }
4867 }
4868
4869 /**
4870  * rtp_session_request_nack:
4871  * @sess: a #RTPSession
4872  * @ssrc: the SSRC
4873  * @seqnum: the missing seqnum
4874  * @max_delay: max delay to request NACK
4875  *
4876  * Request scheduling of a NACK feedback packet for @seqnum in @ssrc.
4877  *
4878  * Returns: %TRUE if the NACK feedback could be scheduled
4879  */
4880 gboolean
4881 rtp_session_request_nack (RTPSession * sess, guint32 ssrc, guint16 seqnum,
4882     GstClockTime max_delay)
4883 {
4884   RTPSource *source;
4885   GstClockTime now;
4886
4887   if (!sess->callbacks.send_rtcp)
4888     return FALSE;
4889
4890   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
4891
4892   RTP_SESSION_LOCK (sess);
4893   source = find_source (sess, ssrc);
4894   if (source == NULL)
4895     goto no_source;
4896
4897   GST_DEBUG ("request NACK for SSRC %08x, #%u, deadline %" GST_TIME_FORMAT,
4898       ssrc, seqnum, GST_TIME_ARGS (now + max_delay));
4899   rtp_source_register_nack (source, seqnum, now + max_delay);
4900   RTP_SESSION_UNLOCK (sess);
4901
4902   if (!rtp_session_send_rtcp_internal (sess, now, max_delay)) {
4903     GST_DEBUG ("NACK not sent early, sending with next regular RTCP");
4904   }
4905
4906   return TRUE;
4907
4908   /* ERRORS */
4909 no_source:
4910   {
4911     RTP_SESSION_UNLOCK (sess);
4912     return FALSE;
4913   }
4914 }
4915
4916 /**
4917  * rtp_session_update_recv_caps_structure:
4918  * @sess: an #RTPSession
4919  * @s: a #GstStructure from a #GstCaps
4920  *
4921  * Update the caps of the receiver in the rtp session.
4922  */
4923 void
4924 rtp_session_update_recv_caps_structure (RTPSession * sess,
4925     const GstStructure * s)
4926 {
4927   guint8 ext_id = _get_extmap_id_for_attribute (s, TWCC_EXTMAP_STR);
4928   if (ext_id > 0) {
4929     sess->twcc_recv_ext_id = ext_id;
4930     GST_INFO ("TWCC enabled for recv using extension id: %u",
4931         sess->twcc_recv_ext_id);
4932   }
4933 }