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