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