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