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