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