session: make method to suggest available SSRC
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / gstrtpsession.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 /**
21  * SECTION:element-gstrtpsession
22  * @see_also: gstrtpjitterbuffer, gstrtpbin, gstrtpptdemux, gstrtpssrcdemux
23  *
24  * The RTP session manager models one participant with a unique SSRC in an RTP
25  * session. This session can be used to send and receive RTP and RTCP packets.
26  * Based on what REQUEST pads are requested from the session manager, specific
27  * functionality can be activated.
28  *
29  * The session manager currently implements RFC 3550 including:
30  * <itemizedlist>
31  *   <listitem>
32  *     <para>RTP packet validation based on consecutive sequence numbers.</para>
33  *   </listitem>
34  *   <listitem>
35  *     <para>Maintainance of the SSRC participant database.</para>
36  *   </listitem>
37  *   <listitem>
38  *     <para>Keeping per participant statistics based on received RTCP packets.</para>
39  *   </listitem>
40  *   <listitem>
41  *     <para>Scheduling of RR/SR RTCP packets.</para>
42  *   </listitem>
43  * </itemizedlist>
44  *
45  * The gstrtpsession will not demux packets based on SSRC or payload type, nor will
46  * it correct for packet reordering and jitter. Use #GstRtpsSrcDemux,
47  * #GstRtpPtDemux and GstRtpJitterBuffer in addition to #GstRtpSession to
48  * perform these tasks. It is usually a good idea to use #GstRtpBin, which
49  * combines all these features in one element.
50  *
51  * To use #GstRtpSession as an RTP receiver, request a recv_rtp_sink pad, which will
52  * automatically create recv_rtp_src pad. Data received on the recv_rtp_sink pad
53  * will be processed in the session and after being validated forwarded on the
54  * recv_rtp_src pad.
55  *
56  * To also use #GstRtpSession as an RTCP receiver, request a recv_rtcp_sink pad,
57  * which will automatically create a sync_src pad. Packets received on the RTCP
58  * pad will be used by the session manager to update the stats and database of
59  * the other participants. SR packets will be forwarded on the sync_src pad
60  * so that they can be used to perform inter-stream synchronisation when needed.
61  *
62  * If you want the session manager to generate and send RTCP packets, request
63  * the send_rtcp_src pad. Packet pushed on this pad contain SR/RR RTCP reports
64  * that should be sent to all participants in the session.
65  *
66  * To use #GstRtpSession as a sender, request a send_rtp_sink pad, which will
67  * automatically create a send_rtp_src pad. The session manager will modify the
68  * SSRC in the RTP packets to its own SSRC and wil forward the packets on the
69  * send_rtp_src pad after updating its internal state.
70  *
71  * The session manager needs the clock-rate of the payload types it is handling
72  * and will signal the #GstRtpSession::request-pt-map signal when it needs such a
73  * mapping. One can clear the cached values with the #GstRtpSession::clear-pt-map
74  * signal.
75  *
76  * <refsect2>
77  * <title>Example pipelines</title>
78  * |[
79  * gst-launch-1.0 udpsrc port=5000 caps="application/x-rtp, ..." ! .recv_rtp_sink gstrtpsession .recv_rtp_src ! rtptheoradepay ! theoradec ! xvimagesink
80  * ]| Receive theora RTP packets from port 5000 and send them to the depayloader,
81  * decoder and display. Note that the application/x-rtp caps on udpsrc should be
82  * configured based on some negotiation process such as RTSP for this pipeline
83  * to work correctly.
84  * |[
85  * gst-launch-1.0 udpsrc port=5000 caps="application/x-rtp, ..." ! .recv_rtp_sink gstrtpsession name=session \
86  *        .recv_rtp_src ! rtptheoradepay ! theoradec ! xvimagesink \
87  *     udpsrc port=5001 caps="application/x-rtcp" ! session.recv_rtcp_sink
88  * ]| Receive theora RTP packets from port 5000 and send them to the depayloader,
89  * decoder and display. Receive RTCP packets from port 5001 and process them in
90  * the session manager.
91  * Note that the application/x-rtp caps on udpsrc should be
92  * configured based on some negotiation process such as RTSP for this pipeline
93  * to work correctly.
94  * |[
95  * gst-launch-1.0 videotestsrc ! theoraenc ! rtptheorapay ! .send_rtp_sink gstrtpsession .send_rtp_src ! udpsink port=5000
96  * ]| Send theora RTP packets through the session manager and out on UDP port
97  * 5000.
98  * |[
99  * gst-launch-1.0 videotestsrc ! theoraenc ! rtptheorapay ! .send_rtp_sink gstrtpsession name=session .send_rtp_src \
100  *     ! udpsink port=5000  session.send_rtcp_src ! udpsink port=5001
101  * ]| Send theora RTP packets through the session manager and out on UDP port
102  * 5000. Send RTCP packets on port 5001. Note that this pipeline will not preroll
103  * correctly because the second udpsink will not preroll correctly (no RTCP
104  * packets are sent in the PAUSED state). Applications should manually set and
105  * keep (see gst_element_set_locked_state()) the RTCP udpsink to the PLAYING state.
106  * </refsect2>
107  *
108  * Last reviewed on 2007-05-28 (0.10.5)
109  */
110
111 #ifdef HAVE_CONFIG_H
112 #include "config.h"
113 #endif
114
115 #include <gst/rtp/gstrtpbuffer.h>
116
117 #include <gst/glib-compat-private.h>
118
119 #include "gstrtpbin-marshal.h"
120 #include "gstrtpsession.h"
121 #include "rtpsession.h"
122
123 GST_DEBUG_CATEGORY_STATIC (gst_rtp_session_debug);
124 #define GST_CAT_DEFAULT gst_rtp_session_debug
125
126 /* sink pads */
127 static GstStaticPadTemplate rtpsession_recv_rtp_sink_template =
128 GST_STATIC_PAD_TEMPLATE ("recv_rtp_sink",
129     GST_PAD_SINK,
130     GST_PAD_REQUEST,
131     GST_STATIC_CAPS ("application/x-rtp")
132     );
133
134 static GstStaticPadTemplate rtpsession_recv_rtcp_sink_template =
135 GST_STATIC_PAD_TEMPLATE ("recv_rtcp_sink",
136     GST_PAD_SINK,
137     GST_PAD_REQUEST,
138     GST_STATIC_CAPS ("application/x-rtcp")
139     );
140
141 static GstStaticPadTemplate rtpsession_send_rtp_sink_template =
142 GST_STATIC_PAD_TEMPLATE ("send_rtp_sink",
143     GST_PAD_SINK,
144     GST_PAD_REQUEST,
145     GST_STATIC_CAPS ("application/x-rtp")
146     );
147
148 /* src pads */
149 static GstStaticPadTemplate rtpsession_recv_rtp_src_template =
150 GST_STATIC_PAD_TEMPLATE ("recv_rtp_src",
151     GST_PAD_SRC,
152     GST_PAD_SOMETIMES,
153     GST_STATIC_CAPS ("application/x-rtp")
154     );
155
156 static GstStaticPadTemplate rtpsession_sync_src_template =
157 GST_STATIC_PAD_TEMPLATE ("sync_src",
158     GST_PAD_SRC,
159     GST_PAD_SOMETIMES,
160     GST_STATIC_CAPS ("application/x-rtcp")
161     );
162
163 static GstStaticPadTemplate rtpsession_send_rtp_src_template =
164 GST_STATIC_PAD_TEMPLATE ("send_rtp_src",
165     GST_PAD_SRC,
166     GST_PAD_SOMETIMES,
167     GST_STATIC_CAPS ("application/x-rtp")
168     );
169
170 static GstStaticPadTemplate rtpsession_send_rtcp_src_template =
171 GST_STATIC_PAD_TEMPLATE ("send_rtcp_src",
172     GST_PAD_SRC,
173     GST_PAD_REQUEST,
174     GST_STATIC_CAPS ("application/x-rtcp")
175     );
176
177 /* signals and args */
178 enum
179 {
180   SIGNAL_REQUEST_PT_MAP,
181   SIGNAL_CLEAR_PT_MAP,
182
183   SIGNAL_ON_NEW_SSRC,
184   SIGNAL_ON_SSRC_COLLISION,
185   SIGNAL_ON_SSRC_VALIDATED,
186   SIGNAL_ON_SSRC_ACTIVE,
187   SIGNAL_ON_SSRC_SDES,
188   SIGNAL_ON_BYE_SSRC,
189   SIGNAL_ON_BYE_TIMEOUT,
190   SIGNAL_ON_TIMEOUT,
191   SIGNAL_ON_SENDER_TIMEOUT,
192   LAST_SIGNAL
193 };
194
195 #define DEFAULT_BANDWIDTH            RTP_STATS_BANDWIDTH
196 #define DEFAULT_RTCP_FRACTION        (RTP_STATS_BANDWIDTH * RTP_STATS_RTCP_FRACTION)
197 #define DEFAULT_RTCP_RR_BANDWIDTH    -1
198 #define DEFAULT_RTCP_RS_BANDWIDTH    -1
199 #define DEFAULT_SDES                 NULL
200 #define DEFAULT_NUM_SOURCES          0
201 #define DEFAULT_NUM_ACTIVE_SOURCES   0
202 #define DEFAULT_USE_PIPELINE_CLOCK   FALSE
203 #define DEFAULT_RTCP_MIN_INTERVAL    (RTP_STATS_MIN_INTERVAL * GST_SECOND)
204 #define DEFAULT_PROBATION            RTP_DEFAULT_PROBATION
205
206 enum
207 {
208   PROP_0,
209   PROP_BANDWIDTH,
210   PROP_RTCP_FRACTION,
211   PROP_RTCP_RR_BANDWIDTH,
212   PROP_RTCP_RS_BANDWIDTH,
213   PROP_SDES,
214   PROP_NUM_SOURCES,
215   PROP_NUM_ACTIVE_SOURCES,
216   PROP_INTERNAL_SESSION,
217   PROP_USE_PIPELINE_CLOCK,
218   PROP_RTCP_MIN_INTERVAL,
219   PROP_PROBATION,
220   PROP_LAST
221 };
222
223 #define GST_RTP_SESSION_GET_PRIVATE(obj)  \
224            (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTP_SESSION, GstRtpSessionPrivate))
225
226 #define GST_RTP_SESSION_LOCK(sess)   g_mutex_lock (&(sess)->priv->lock)
227 #define GST_RTP_SESSION_UNLOCK(sess) g_mutex_unlock (&(sess)->priv->lock)
228
229 #define GST_RTP_SESSION_WAIT(sess)   g_cond_wait (&(sess)->priv->cond, &(sess)->priv->lock)
230 #define GST_RTP_SESSION_SIGNAL(sess) g_cond_signal (&(sess)->priv->cond)
231
232 struct _GstRtpSessionPrivate
233 {
234   GMutex lock;
235   GCond cond;
236   GstClock *sysclock;
237
238   RTPSession *session;
239
240   /* thread for sending out RTCP */
241   GstClockID id;
242   gboolean stop_thread;
243   GThread *thread;
244   gboolean thread_stopped;
245   gboolean wait_send;
246
247   /* caps mapping */
248   GHashTable *ptmap;
249
250   GstClockTime send_latency;
251
252   gboolean use_pipeline_clock;
253 };
254
255 /* callbacks to handle actions from the session manager */
256 static GstFlowReturn gst_rtp_session_process_rtp (RTPSession * sess,
257     RTPSource * src, GstBuffer * buffer, gpointer user_data);
258 static GstFlowReturn gst_rtp_session_send_rtp (RTPSession * sess,
259     RTPSource * src, gpointer data, gpointer user_data);
260 static GstFlowReturn gst_rtp_session_send_rtcp (RTPSession * sess,
261     RTPSource * src, GstBuffer * buffer, gboolean eos, gpointer user_data);
262 static GstFlowReturn gst_rtp_session_sync_rtcp (RTPSession * sess,
263     GstBuffer * buffer, gpointer user_data);
264 static gint gst_rtp_session_clock_rate (RTPSession * sess, guint8 payload,
265     gpointer user_data);
266 static void gst_rtp_session_reconsider (RTPSession * sess, gpointer user_data);
267 static void gst_rtp_session_request_key_unit (RTPSession * sess,
268     gboolean all_headers, gpointer user_data);
269 static GstClockTime gst_rtp_session_request_time (RTPSession * session,
270     gpointer user_data);
271
272 static RTPSessionCallbacks callbacks = {
273   gst_rtp_session_process_rtp,
274   gst_rtp_session_send_rtp,
275   gst_rtp_session_sync_rtcp,
276   gst_rtp_session_send_rtcp,
277   gst_rtp_session_clock_rate,
278   gst_rtp_session_reconsider,
279   gst_rtp_session_request_key_unit,
280   gst_rtp_session_request_time
281 };
282
283 /* GObject vmethods */
284 static void gst_rtp_session_finalize (GObject * object);
285 static void gst_rtp_session_set_property (GObject * object, guint prop_id,
286     const GValue * value, GParamSpec * pspec);
287 static void gst_rtp_session_get_property (GObject * object, guint prop_id,
288     GValue * value, GParamSpec * pspec);
289
290 /* GstElement vmethods */
291 static GstStateChangeReturn gst_rtp_session_change_state (GstElement * element,
292     GstStateChange transition);
293 static GstPad *gst_rtp_session_request_new_pad (GstElement * element,
294     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
295 static void gst_rtp_session_release_pad (GstElement * element, GstPad * pad);
296
297 static gboolean gst_rtp_session_sink_setcaps (GstPad * pad,
298     GstRtpSession * rtpsession, GstCaps * caps);
299 static gboolean gst_rtp_session_setcaps_send_rtp (GstPad * pad,
300     GstRtpSession * rtpsession, GstCaps * caps);
301
302 static void gst_rtp_session_clear_pt_map (GstRtpSession * rtpsession);
303
304 static guint gst_rtp_session_signals[LAST_SIGNAL] = { 0 };
305
306 static void
307 on_new_ssrc (RTPSession * session, RTPSource * src, GstRtpSession * sess)
308 {
309   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_NEW_SSRC], 0,
310       src->ssrc);
311 }
312
313 static void
314 on_ssrc_collision (RTPSession * session, RTPSource * src, GstRtpSession * sess)
315 {
316   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_SSRC_COLLISION], 0,
317       src->ssrc);
318 }
319
320 static void
321 on_ssrc_validated (RTPSession * session, RTPSource * src, GstRtpSession * sess)
322 {
323   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
324       src->ssrc);
325 }
326
327 static void
328 on_ssrc_active (RTPSession * session, RTPSource * src, GstRtpSession * sess)
329 {
330   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_SSRC_ACTIVE], 0,
331       src->ssrc);
332 }
333
334 static void
335 on_ssrc_sdes (RTPSession * session, RTPSource * src, GstRtpSession * sess)
336 {
337   GstStructure *s;
338   GstMessage *m;
339
340   /* convert the new SDES info into a message */
341   RTP_SESSION_LOCK (session);
342   g_object_get (src, "sdes", &s, NULL);
343   RTP_SESSION_UNLOCK (session);
344
345   m = gst_message_new_custom (GST_MESSAGE_ELEMENT, GST_OBJECT (sess), s);
346   gst_element_post_message (GST_ELEMENT_CAST (sess), m);
347
348   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_SSRC_SDES], 0,
349       src->ssrc);
350 }
351
352 static void
353 on_bye_ssrc (RTPSession * session, RTPSource * src, GstRtpSession * sess)
354 {
355   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_BYE_SSRC], 0,
356       src->ssrc);
357 }
358
359 static void
360 on_bye_timeout (RTPSession * session, RTPSource * src, GstRtpSession * sess)
361 {
362   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_BYE_TIMEOUT], 0,
363       src->ssrc);
364 }
365
366 static void
367 on_timeout (RTPSession * session, RTPSource * src, GstRtpSession * sess)
368 {
369   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_TIMEOUT], 0,
370       src->ssrc);
371 }
372
373 static void
374 on_sender_timeout (RTPSession * session, RTPSource * src, GstRtpSession * sess)
375 {
376   g_signal_emit (sess, gst_rtp_session_signals[SIGNAL_ON_SENDER_TIMEOUT], 0,
377       src->ssrc);
378 }
379
380 #define gst_rtp_session_parent_class parent_class
381 G_DEFINE_TYPE (GstRtpSession, gst_rtp_session, GST_TYPE_ELEMENT);
382
383 static void
384 gst_rtp_session_class_init (GstRtpSessionClass * klass)
385 {
386   GObjectClass *gobject_class;
387   GstElementClass *gstelement_class;
388
389   gobject_class = (GObjectClass *) klass;
390   gstelement_class = (GstElementClass *) klass;
391
392   g_type_class_add_private (klass, sizeof (GstRtpSessionPrivate));
393
394   gobject_class->finalize = gst_rtp_session_finalize;
395   gobject_class->set_property = gst_rtp_session_set_property;
396   gobject_class->get_property = gst_rtp_session_get_property;
397
398   /**
399    * GstRtpSession::request-pt-map:
400    * @sess: the object which received the signal
401    * @pt: the pt
402    *
403    * Request the payload type as #GstCaps for @pt.
404    */
405   gst_rtp_session_signals[SIGNAL_REQUEST_PT_MAP] =
406       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
407       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass, request_pt_map),
408       NULL, NULL, gst_rtp_bin_marshal_BOXED__UINT, GST_TYPE_CAPS, 1,
409       G_TYPE_UINT);
410   /**
411    * GstRtpSession::clear-pt-map:
412    * @sess: the object which received the signal
413    *
414    * Clear the cached pt-maps requested with #GstRtpSession::request-pt-map.
415    */
416   gst_rtp_session_signals[SIGNAL_CLEAR_PT_MAP] =
417       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
418       G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpSessionClass, clear_pt_map),
419       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
420
421   /**
422    * GstRtpSession::on-new-ssrc:
423    * @sess: the object which received the signal
424    * @ssrc: the SSRC
425    *
426    * Notify of a new SSRC that entered @session.
427    */
428   gst_rtp_session_signals[SIGNAL_ON_NEW_SSRC] =
429       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
430       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass, on_new_ssrc),
431       NULL, NULL, g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
432   /**
433    * GstRtpSession::on-ssrc_collision:
434    * @sess: the object which received the signal
435    * @ssrc: the SSRC
436    *
437    * Notify when we have an SSRC collision
438    */
439   gst_rtp_session_signals[SIGNAL_ON_SSRC_COLLISION] =
440       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
441       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass,
442           on_ssrc_collision), NULL, NULL, g_cclosure_marshal_VOID__UINT,
443       G_TYPE_NONE, 1, G_TYPE_UINT);
444   /**
445    * GstRtpSession::on-ssrc_validated:
446    * @sess: the object which received the signal
447    * @ssrc: the SSRC
448    *
449    * Notify of a new SSRC that became validated.
450    */
451   gst_rtp_session_signals[SIGNAL_ON_SSRC_VALIDATED] =
452       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
453       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass,
454           on_ssrc_validated), NULL, NULL, g_cclosure_marshal_VOID__UINT,
455       G_TYPE_NONE, 1, G_TYPE_UINT);
456   /**
457    * GstRtpSession::on-ssrc_active:
458    * @sess: the object which received the signal
459    * @ssrc: the SSRC
460    *
461    * Notify of a SSRC that is active, i.e., sending RTCP.
462    */
463   gst_rtp_session_signals[SIGNAL_ON_SSRC_ACTIVE] =
464       g_signal_new ("on-ssrc-active", G_TYPE_FROM_CLASS (klass),
465       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass,
466           on_ssrc_active), NULL, NULL, g_cclosure_marshal_VOID__UINT,
467       G_TYPE_NONE, 1, G_TYPE_UINT);
468   /**
469    * GstRtpSession::on-ssrc-sdes:
470    * @session: the object which received the signal
471    * @src: the SSRC
472    *
473    * Notify that a new SDES was received for SSRC.
474    */
475   gst_rtp_session_signals[SIGNAL_ON_SSRC_SDES] =
476       g_signal_new ("on-ssrc-sdes", G_TYPE_FROM_CLASS (klass),
477       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass, on_ssrc_sdes),
478       NULL, NULL, g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
479
480   /**
481    * GstRtpSession::on-bye-ssrc:
482    * @sess: the object which received the signal
483    * @ssrc: the SSRC
484    *
485    * Notify of an SSRC that became inactive because of a BYE packet.
486    */
487   gst_rtp_session_signals[SIGNAL_ON_BYE_SSRC] =
488       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
489       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass, on_bye_ssrc),
490       NULL, NULL, g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
491   /**
492    * GstRtpSession::on-bye-timeout:
493    * @sess: the object which received the signal
494    * @ssrc: the SSRC
495    *
496    * Notify of an SSRC that has timed out because of BYE
497    */
498   gst_rtp_session_signals[SIGNAL_ON_BYE_TIMEOUT] =
499       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
500       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass, on_bye_timeout),
501       NULL, NULL, g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
502   /**
503    * GstRtpSession::on-timeout:
504    * @sess: the object which received the signal
505    * @ssrc: the SSRC
506    *
507    * Notify of an SSRC that has timed out
508    */
509   gst_rtp_session_signals[SIGNAL_ON_TIMEOUT] =
510       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
511       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass, on_timeout),
512       NULL, NULL, g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
513   /**
514    * GstRtpSession::on-sender-timeout:
515    * @sess: the object which received the signal
516    * @ssrc: the SSRC
517    *
518    * Notify of a sender SSRC that has timed out and became a receiver
519    */
520   gst_rtp_session_signals[SIGNAL_ON_SENDER_TIMEOUT] =
521       g_signal_new ("on-sender-timeout", G_TYPE_FROM_CLASS (klass),
522       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpSessionClass,
523           on_sender_timeout), NULL, NULL, g_cclosure_marshal_VOID__UINT,
524       G_TYPE_NONE, 1, G_TYPE_UINT);
525
526   g_object_class_install_property (gobject_class, PROP_BANDWIDTH,
527       g_param_spec_double ("bandwidth", "Bandwidth",
528           "The bandwidth of the session in bytes per second (0 for auto-discover)",
529           0.0, G_MAXDOUBLE, DEFAULT_BANDWIDTH,
530           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
531
532   g_object_class_install_property (gobject_class, PROP_RTCP_FRACTION,
533       g_param_spec_double ("rtcp-fraction", "RTCP Fraction",
534           "The RTCP bandwidth of the session in bytes per second "
535           "(or as a real fraction of the RTP bandwidth if < 1.0)",
536           0.0, G_MAXDOUBLE, DEFAULT_RTCP_FRACTION,
537           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
538
539   g_object_class_install_property (gobject_class, PROP_RTCP_RR_BANDWIDTH,
540       g_param_spec_int ("rtcp-rr-bandwidth", "RTCP RR bandwidth",
541           "The RTCP bandwidth used for receivers in bytes per second (-1 = default)",
542           -1, G_MAXINT, DEFAULT_RTCP_RR_BANDWIDTH,
543           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
544
545   g_object_class_install_property (gobject_class, PROP_RTCP_RS_BANDWIDTH,
546       g_param_spec_int ("rtcp-rs-bandwidth", "RTCP RS bandwidth",
547           "The RTCP bandwidth used for senders in bytes per second (-1 = default)",
548           -1, G_MAXINT, DEFAULT_RTCP_RS_BANDWIDTH,
549           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
550
551   g_object_class_install_property (gobject_class, PROP_SDES,
552       g_param_spec_boxed ("sdes", "SDES",
553           "The SDES items of this session",
554           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
555
556   g_object_class_install_property (gobject_class, PROP_NUM_SOURCES,
557       g_param_spec_uint ("num-sources", "Num Sources",
558           "The number of sources in the session", 0, G_MAXUINT,
559           DEFAULT_NUM_SOURCES, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
560
561   g_object_class_install_property (gobject_class, PROP_NUM_ACTIVE_SOURCES,
562       g_param_spec_uint ("num-active-sources", "Num Active Sources",
563           "The number of active sources in the session", 0, G_MAXUINT,
564           DEFAULT_NUM_ACTIVE_SOURCES,
565           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
566
567   g_object_class_install_property (gobject_class, PROP_INTERNAL_SESSION,
568       g_param_spec_object ("internal-session", "Internal Session",
569           "The internal RTPSession object", RTP_TYPE_SESSION,
570           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
571
572   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
573       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
574           "Use the pipeline running-time to set the NTP time in the RTCP SR messages",
575           DEFAULT_USE_PIPELINE_CLOCK,
576           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
577
578   g_object_class_install_property (gobject_class, PROP_RTCP_MIN_INTERVAL,
579       g_param_spec_uint64 ("rtcp-min-interval", "Minimum RTCP interval",
580           "Minimum interval between Regular RTCP packet (in ns)",
581           0, G_MAXUINT64, DEFAULT_RTCP_MIN_INTERVAL,
582           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
583
584   g_object_class_install_property (gobject_class, PROP_PROBATION,
585       g_param_spec_uint ("probation", "Number of probations",
586           "Consecutive packet sequence numbers to accept the source",
587           0, G_MAXUINT, DEFAULT_PROBATION,
588           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
589
590   gstelement_class->change_state =
591       GST_DEBUG_FUNCPTR (gst_rtp_session_change_state);
592   gstelement_class->request_new_pad =
593       GST_DEBUG_FUNCPTR (gst_rtp_session_request_new_pad);
594   gstelement_class->release_pad =
595       GST_DEBUG_FUNCPTR (gst_rtp_session_release_pad);
596
597   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_session_clear_pt_map);
598
599   /* sink pads */
600   gst_element_class_add_pad_template (gstelement_class,
601       gst_static_pad_template_get (&rtpsession_recv_rtp_sink_template));
602   gst_element_class_add_pad_template (gstelement_class,
603       gst_static_pad_template_get (&rtpsession_recv_rtcp_sink_template));
604   gst_element_class_add_pad_template (gstelement_class,
605       gst_static_pad_template_get (&rtpsession_send_rtp_sink_template));
606
607   /* src pads */
608   gst_element_class_add_pad_template (gstelement_class,
609       gst_static_pad_template_get (&rtpsession_recv_rtp_src_template));
610   gst_element_class_add_pad_template (gstelement_class,
611       gst_static_pad_template_get (&rtpsession_sync_src_template));
612   gst_element_class_add_pad_template (gstelement_class,
613       gst_static_pad_template_get (&rtpsession_send_rtp_src_template));
614   gst_element_class_add_pad_template (gstelement_class,
615       gst_static_pad_template_get (&rtpsession_send_rtcp_src_template));
616
617   gst_element_class_set_static_metadata (gstelement_class, "RTP Session",
618       "Filter/Network/RTP",
619       "Implement an RTP session", "Wim Taymans <wim.taymans@gmail.com>");
620
621   GST_DEBUG_CATEGORY_INIT (gst_rtp_session_debug,
622       "rtpsession", 0, "RTP Session");
623 }
624
625 static void
626 gst_rtp_session_init (GstRtpSession * rtpsession)
627 {
628   rtpsession->priv = GST_RTP_SESSION_GET_PRIVATE (rtpsession);
629   g_mutex_init (&rtpsession->priv->lock);
630   g_cond_init (&rtpsession->priv->cond);
631   rtpsession->priv->sysclock = gst_system_clock_obtain ();
632   rtpsession->priv->session = rtp_session_new ();
633   rtpsession->priv->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
634
635   /* configure callbacks */
636   rtp_session_set_callbacks (rtpsession->priv->session, &callbacks, rtpsession);
637   /* configure signals */
638   g_signal_connect (rtpsession->priv->session, "on-new-ssrc",
639       (GCallback) on_new_ssrc, rtpsession);
640   g_signal_connect (rtpsession->priv->session, "on-ssrc-collision",
641       (GCallback) on_ssrc_collision, rtpsession);
642   g_signal_connect (rtpsession->priv->session, "on-ssrc-validated",
643       (GCallback) on_ssrc_validated, rtpsession);
644   g_signal_connect (rtpsession->priv->session, "on-ssrc-active",
645       (GCallback) on_ssrc_active, rtpsession);
646   g_signal_connect (rtpsession->priv->session, "on-ssrc-sdes",
647       (GCallback) on_ssrc_sdes, rtpsession);
648   g_signal_connect (rtpsession->priv->session, "on-bye-ssrc",
649       (GCallback) on_bye_ssrc, rtpsession);
650   g_signal_connect (rtpsession->priv->session, "on-bye-timeout",
651       (GCallback) on_bye_timeout, rtpsession);
652   g_signal_connect (rtpsession->priv->session, "on-timeout",
653       (GCallback) on_timeout, rtpsession);
654   g_signal_connect (rtpsession->priv->session, "on-sender-timeout",
655       (GCallback) on_sender_timeout, rtpsession);
656   rtpsession->priv->ptmap = g_hash_table_new_full (NULL, NULL, NULL,
657       (GDestroyNotify) gst_caps_unref);
658
659   gst_segment_init (&rtpsession->recv_rtp_seg, GST_FORMAT_UNDEFINED);
660   gst_segment_init (&rtpsession->send_rtp_seg, GST_FORMAT_UNDEFINED);
661
662   rtpsession->priv->thread_stopped = TRUE;
663 }
664
665 static void
666 gst_rtp_session_finalize (GObject * object)
667 {
668   GstRtpSession *rtpsession;
669
670   rtpsession = GST_RTP_SESSION (object);
671
672   g_hash_table_destroy (rtpsession->priv->ptmap);
673   g_mutex_clear (&rtpsession->priv->lock);
674   g_cond_clear (&rtpsession->priv->cond);
675   g_object_unref (rtpsession->priv->sysclock);
676   g_object_unref (rtpsession->priv->session);
677
678   G_OBJECT_CLASS (parent_class)->finalize (object);
679 }
680
681 static void
682 gst_rtp_session_set_property (GObject * object, guint prop_id,
683     const GValue * value, GParamSpec * pspec)
684 {
685   GstRtpSession *rtpsession;
686   GstRtpSessionPrivate *priv;
687
688   rtpsession = GST_RTP_SESSION (object);
689   priv = rtpsession->priv;
690
691   switch (prop_id) {
692     case PROP_BANDWIDTH:
693       g_object_set_property (G_OBJECT (priv->session), "bandwidth", value);
694       break;
695     case PROP_RTCP_FRACTION:
696       g_object_set_property (G_OBJECT (priv->session), "rtcp-fraction", value);
697       break;
698     case PROP_RTCP_RR_BANDWIDTH:
699       g_object_set_property (G_OBJECT (priv->session), "rtcp-rr-bandwidth",
700           value);
701       break;
702     case PROP_RTCP_RS_BANDWIDTH:
703       g_object_set_property (G_OBJECT (priv->session), "rtcp-rs-bandwidth",
704           value);
705       break;
706     case PROP_SDES:
707       rtp_session_set_sdes_struct (priv->session, g_value_get_boxed (value));
708       break;
709     case PROP_USE_PIPELINE_CLOCK:
710       priv->use_pipeline_clock = g_value_get_boolean (value);
711       break;
712     case PROP_RTCP_MIN_INTERVAL:
713       g_object_set_property (G_OBJECT (priv->session), "rtcp-min-interval",
714           value);
715       break;
716     case PROP_PROBATION:
717       g_object_set_property (G_OBJECT (priv->session), "probation", value);
718       break;
719     default:
720       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
721       break;
722   }
723 }
724
725 static void
726 gst_rtp_session_get_property (GObject * object, guint prop_id,
727     GValue * value, GParamSpec * pspec)
728 {
729   GstRtpSession *rtpsession;
730   GstRtpSessionPrivate *priv;
731
732   rtpsession = GST_RTP_SESSION (object);
733   priv = rtpsession->priv;
734
735   switch (prop_id) {
736     case PROP_BANDWIDTH:
737       g_object_get_property (G_OBJECT (priv->session), "bandwidth", value);
738       break;
739     case PROP_RTCP_FRACTION:
740       g_object_get_property (G_OBJECT (priv->session), "rtcp-fraction", value);
741       break;
742     case PROP_RTCP_RR_BANDWIDTH:
743       g_object_get_property (G_OBJECT (priv->session), "rtcp-rr-bandwidth",
744           value);
745       break;
746     case PROP_RTCP_RS_BANDWIDTH:
747       g_object_get_property (G_OBJECT (priv->session), "rtcp-rs-bandwidth",
748           value);
749       break;
750     case PROP_SDES:
751       g_value_take_boxed (value, rtp_session_get_sdes_struct (priv->session));
752       break;
753     case PROP_NUM_SOURCES:
754       g_value_set_uint (value, rtp_session_get_num_sources (priv->session));
755       break;
756     case PROP_NUM_ACTIVE_SOURCES:
757       g_value_set_uint (value,
758           rtp_session_get_num_active_sources (priv->session));
759       break;
760     case PROP_INTERNAL_SESSION:
761       g_value_set_object (value, priv->session);
762       break;
763     case PROP_USE_PIPELINE_CLOCK:
764       g_value_set_boolean (value, priv->use_pipeline_clock);
765       break;
766     case PROP_RTCP_MIN_INTERVAL:
767       g_object_get_property (G_OBJECT (priv->session), "rtcp-min-interval",
768           value);
769       break;
770     case PROP_PROBATION:
771       g_object_get_property (G_OBJECT (priv->session), "probation", value);
772       break;
773     default:
774       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
775       break;
776   }
777 }
778
779 static void
780 get_current_times (GstRtpSession * rtpsession, GstClockTime * running_time,
781     guint64 * ntpnstime)
782 {
783   guint64 ntpns;
784   GstClock *clock;
785   GstClockTime base_time, rt, clock_time;
786
787   GST_OBJECT_LOCK (rtpsession);
788   if ((clock = GST_ELEMENT_CLOCK (rtpsession))) {
789     base_time = GST_ELEMENT_CAST (rtpsession)->base_time;
790     gst_object_ref (clock);
791     GST_OBJECT_UNLOCK (rtpsession);
792
793     /* get current clock time and convert to running time */
794     clock_time = gst_clock_get_time (clock);
795     rt = clock_time - base_time;
796
797     if (rtpsession->priv->use_pipeline_clock) {
798       ntpns = rt;
799     } else {
800       GTimeVal current;
801
802       /* get current NTP time */
803       g_get_current_time (&current);
804       ntpns = GST_TIMEVAL_TO_TIME (current);
805     }
806
807     /* add constant to convert from 1970 based time to 1900 based time */
808     ntpns += (2208988800LL * GST_SECOND);
809
810     gst_object_unref (clock);
811   } else {
812     GST_OBJECT_UNLOCK (rtpsession);
813     rt = -1;
814     ntpns = -1;
815   }
816   if (running_time)
817     *running_time = rt;
818   if (ntpnstime)
819     *ntpnstime = ntpns;
820 }
821
822 static void
823 rtcp_thread (GstRtpSession * rtpsession)
824 {
825   GstClockID id;
826   GstClockTime current_time;
827   GstClockTime next_timeout;
828   guint64 ntpnstime;
829   GstClockTime running_time;
830   RTPSession *session;
831   GstClock *sysclock;
832
833   GST_DEBUG_OBJECT (rtpsession, "entering RTCP thread");
834
835   GST_RTP_SESSION_LOCK (rtpsession);
836
837   while (rtpsession->priv->wait_send) {
838     GST_LOG_OBJECT (rtpsession, "waiting for RTP thread");
839     GST_RTP_SESSION_WAIT (rtpsession);
840     GST_LOG_OBJECT (rtpsession, "signaled...");
841   }
842
843   sysclock = rtpsession->priv->sysclock;
844   current_time = gst_clock_get_time (sysclock);
845
846   session = rtpsession->priv->session;
847
848   GST_DEBUG_OBJECT (rtpsession, "starting at %" GST_TIME_FORMAT,
849       GST_TIME_ARGS (current_time));
850   session->start_time = current_time;
851
852   while (!rtpsession->priv->stop_thread) {
853     GstClockReturn res;
854
855     /* get initial estimate */
856     next_timeout = rtp_session_next_timeout (session, current_time);
857
858     GST_DEBUG_OBJECT (rtpsession, "next check time %" GST_TIME_FORMAT,
859         GST_TIME_ARGS (next_timeout));
860
861     /* leave if no more timeouts, the session ended */
862     if (next_timeout == GST_CLOCK_TIME_NONE)
863       break;
864
865     id = rtpsession->priv->id =
866         gst_clock_new_single_shot_id (sysclock, next_timeout);
867     GST_RTP_SESSION_UNLOCK (rtpsession);
868
869     res = gst_clock_id_wait (id, NULL);
870
871     GST_RTP_SESSION_LOCK (rtpsession);
872     gst_clock_id_unref (id);
873     rtpsession->priv->id = NULL;
874
875     if (rtpsession->priv->stop_thread)
876       break;
877
878     /* update current time */
879     current_time = gst_clock_get_time (sysclock);
880
881     /* get current NTP time */
882     get_current_times (rtpsession, &running_time, &ntpnstime);
883
884     /* we get unlocked because we need to perform reconsideration, don't perform
885      * the timeout but get a new reporting estimate. */
886     GST_DEBUG_OBJECT (rtpsession, "unlocked %d, current %" GST_TIME_FORMAT,
887         res, GST_TIME_ARGS (current_time));
888
889     /* perform actions, we ignore result. Release lock because it might push. */
890     GST_RTP_SESSION_UNLOCK (rtpsession);
891     rtp_session_on_timeout (session, current_time, ntpnstime, running_time);
892     GST_RTP_SESSION_LOCK (rtpsession);
893   }
894   /* mark the thread as stopped now */
895   rtpsession->priv->thread_stopped = TRUE;
896   GST_RTP_SESSION_UNLOCK (rtpsession);
897
898   GST_DEBUG_OBJECT (rtpsession, "leaving RTCP thread");
899 }
900
901 static gboolean
902 start_rtcp_thread (GstRtpSession * rtpsession)
903 {
904   GError *error = NULL;
905   gboolean res;
906
907   GST_DEBUG_OBJECT (rtpsession, "starting RTCP thread");
908
909   GST_RTP_SESSION_LOCK (rtpsession);
910   rtpsession->priv->stop_thread = FALSE;
911   if (rtpsession->priv->thread_stopped) {
912     /* if the thread stopped, and we still have a handle to the thread, join it
913      * now. We can safely join with the lock held, the thread will not take it
914      * anymore. */
915     if (rtpsession->priv->thread)
916       g_thread_join (rtpsession->priv->thread);
917     /* only create a new thread if the old one was stopped. Otherwise we can
918      * just reuse the currently running one. */
919     rtpsession->priv->thread = g_thread_try_new ("rtpsession-rtcp-thread",
920         (GThreadFunc) rtcp_thread, rtpsession, &error);
921     rtpsession->priv->thread_stopped = FALSE;
922   }
923   GST_RTP_SESSION_UNLOCK (rtpsession);
924
925   if (error != NULL) {
926     res = FALSE;
927     GST_DEBUG_OBJECT (rtpsession, "failed to start thread, %s", error->message);
928     g_error_free (error);
929   } else {
930     res = TRUE;
931   }
932   return res;
933 }
934
935 static void
936 stop_rtcp_thread (GstRtpSession * rtpsession)
937 {
938   GST_DEBUG_OBJECT (rtpsession, "stopping RTCP thread");
939
940   GST_RTP_SESSION_LOCK (rtpsession);
941   rtpsession->priv->stop_thread = TRUE;
942   rtpsession->priv->wait_send = FALSE;
943   GST_RTP_SESSION_SIGNAL (rtpsession);
944   if (rtpsession->priv->id)
945     gst_clock_id_unschedule (rtpsession->priv->id);
946   GST_RTP_SESSION_UNLOCK (rtpsession);
947 }
948
949 static void
950 join_rtcp_thread (GstRtpSession * rtpsession)
951 {
952   GST_RTP_SESSION_LOCK (rtpsession);
953   /* don't try to join when we have no thread */
954   if (rtpsession->priv->thread != NULL) {
955     GST_DEBUG_OBJECT (rtpsession, "joining RTCP thread");
956     GST_RTP_SESSION_UNLOCK (rtpsession);
957
958     g_thread_join (rtpsession->priv->thread);
959
960     GST_RTP_SESSION_LOCK (rtpsession);
961     /* after the join, take the lock and clear the thread structure. The caller
962      * is supposed to not concurrently call start and join. */
963     rtpsession->priv->thread = NULL;
964   }
965   GST_RTP_SESSION_UNLOCK (rtpsession);
966 }
967
968 static GstStateChangeReturn
969 gst_rtp_session_change_state (GstElement * element, GstStateChange transition)
970 {
971   GstStateChangeReturn res;
972   GstRtpSession *rtpsession;
973
974   rtpsession = GST_RTP_SESSION (element);
975
976   switch (transition) {
977     case GST_STATE_CHANGE_NULL_TO_READY:
978       break;
979     case GST_STATE_CHANGE_READY_TO_PAUSED:
980       GST_RTP_SESSION_LOCK (rtpsession);
981       if (rtpsession->send_rtp_src)
982         rtpsession->priv->wait_send = TRUE;
983       GST_RTP_SESSION_UNLOCK (rtpsession);
984       break;
985     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
986       break;
987     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
988     case GST_STATE_CHANGE_PAUSED_TO_READY:
989       /* no need to join yet, we might want to continue later. Also, the
990        * dataflow could block downstream so that a join could just block
991        * forever. */
992       stop_rtcp_thread (rtpsession);
993       break;
994     default:
995       break;
996   }
997
998   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
999
1000   switch (transition) {
1001     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1002       if (!start_rtcp_thread (rtpsession))
1003         goto failed_thread;
1004       break;
1005     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1006       break;
1007     case GST_STATE_CHANGE_PAUSED_TO_READY:
1008       /* downstream is now releasing the dataflow and we can join. */
1009       join_rtcp_thread (rtpsession);
1010       break;
1011     case GST_STATE_CHANGE_READY_TO_NULL:
1012       break;
1013     default:
1014       break;
1015   }
1016   return res;
1017
1018   /* ERRORS */
1019 failed_thread:
1020   {
1021     return GST_STATE_CHANGE_FAILURE;
1022   }
1023 }
1024
1025 static gboolean
1026 return_true (gpointer key, gpointer value, gpointer user_data)
1027 {
1028   return TRUE;
1029 }
1030
1031 static void
1032 gst_rtp_session_clear_pt_map (GstRtpSession * rtpsession)
1033 {
1034   g_hash_table_foreach_remove (rtpsession->priv->ptmap, return_true, NULL);
1035 }
1036
1037 /* called when the session manager has an RTP packet or a list of packets
1038  * ready for further processing */
1039 static GstFlowReturn
1040 gst_rtp_session_process_rtp (RTPSession * sess, RTPSource * src,
1041     GstBuffer * buffer, gpointer user_data)
1042 {
1043   GstFlowReturn result;
1044   GstRtpSession *rtpsession;
1045   GstPad *rtp_src;
1046
1047   rtpsession = GST_RTP_SESSION (user_data);
1048
1049   GST_RTP_SESSION_LOCK (rtpsession);
1050   if ((rtp_src = rtpsession->recv_rtp_src))
1051     gst_object_ref (rtp_src);
1052   GST_RTP_SESSION_UNLOCK (rtpsession);
1053
1054   if (rtp_src) {
1055     GST_LOG_OBJECT (rtpsession, "pushing received RTP packet");
1056     result = gst_pad_push (rtp_src, buffer);
1057     gst_object_unref (rtp_src);
1058   } else {
1059     GST_DEBUG_OBJECT (rtpsession, "dropping received RTP packet");
1060     gst_buffer_unref (buffer);
1061     result = GST_FLOW_OK;
1062   }
1063   return result;
1064 }
1065
1066 /* called when the session manager has an RTP packet ready for further
1067  * sending */
1068 static GstFlowReturn
1069 gst_rtp_session_send_rtp (RTPSession * sess, RTPSource * src,
1070     gpointer data, gpointer user_data)
1071 {
1072   GstFlowReturn result;
1073   GstRtpSession *rtpsession;
1074   GstPad *rtp_src;
1075
1076   rtpsession = GST_RTP_SESSION (user_data);
1077
1078   GST_RTP_SESSION_LOCK (rtpsession);
1079   if ((rtp_src = rtpsession->send_rtp_src))
1080     gst_object_ref (rtp_src);
1081   if (rtpsession->priv->wait_send) {
1082     GST_LOG_OBJECT (rtpsession, "signal RTCP thread");
1083     rtpsession->priv->wait_send = FALSE;
1084     GST_RTP_SESSION_SIGNAL (rtpsession);
1085   }
1086   GST_RTP_SESSION_UNLOCK (rtpsession);
1087
1088   if (rtp_src) {
1089     if (GST_IS_BUFFER (data)) {
1090       GST_LOG_OBJECT (rtpsession, "sending RTP packet");
1091       result = gst_pad_push (rtp_src, GST_BUFFER_CAST (data));
1092     } else {
1093       GST_LOG_OBJECT (rtpsession, "sending RTP list");
1094       result = gst_pad_push_list (rtp_src, GST_BUFFER_LIST_CAST (data));
1095     }
1096     gst_object_unref (rtp_src);
1097   } else {
1098     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1099     result = GST_FLOW_OK;
1100   }
1101   return result;
1102 }
1103
1104 static void
1105 do_rtcp_events (GstRtpSession * rtpsession, GstPad * srcpad)
1106 {
1107   GstCaps *caps;
1108   GstSegment seg;
1109   GstEvent *event;
1110   gchar *stream_id;
1111   gboolean have_group_id;
1112   guint group_id;
1113
1114   stream_id =
1115       g_strdup_printf ("%08x%08x%08x%08x", g_random_int (), g_random_int (),
1116       g_random_int (), g_random_int ());
1117
1118   GST_RTP_SESSION_LOCK (rtpsession);
1119   if (rtpsession->recv_rtp_sink) {
1120     event =
1121         gst_pad_get_sticky_event (rtpsession->recv_rtp_sink,
1122         GST_EVENT_STREAM_START, 0);
1123     if (event) {
1124       if (gst_event_parse_group_id (event, &group_id))
1125         have_group_id = TRUE;
1126       else
1127         have_group_id = FALSE;
1128       gst_event_unref (event);
1129     } else {
1130       have_group_id = TRUE;
1131       group_id = gst_util_group_id_next ();
1132     }
1133   } else {
1134     have_group_id = TRUE;
1135     group_id = gst_util_group_id_next ();
1136   }
1137   GST_RTP_SESSION_UNLOCK (rtpsession);
1138
1139   event = gst_event_new_stream_start (stream_id);
1140   if (have_group_id)
1141     gst_event_set_group_id (event, group_id);
1142   gst_pad_push_event (srcpad, event);
1143   g_free (stream_id);
1144
1145   caps = gst_caps_new_empty_simple ("application/x-rtcp");
1146   gst_pad_set_caps (srcpad, caps);
1147   gst_caps_unref (caps);
1148
1149   gst_segment_init (&seg, GST_FORMAT_TIME);
1150   event = gst_event_new_segment (&seg);
1151   gst_pad_push_event (srcpad, event);
1152 }
1153
1154 /* called when the session manager has an RTCP packet ready for further
1155  * sending. The eos flag is set when an EOS event should be sent downstream as
1156  * well. */
1157 static GstFlowReturn
1158 gst_rtp_session_send_rtcp (RTPSession * sess, RTPSource * src,
1159     GstBuffer * buffer, gboolean eos, gpointer user_data)
1160 {
1161   GstFlowReturn result;
1162   GstRtpSession *rtpsession;
1163   GstPad *rtcp_src;
1164
1165   rtpsession = GST_RTP_SESSION (user_data);
1166
1167   GST_RTP_SESSION_LOCK (rtpsession);
1168   if (rtpsession->priv->stop_thread)
1169     goto stopping;
1170
1171   if ((rtcp_src = rtpsession->send_rtcp_src)) {
1172     gst_object_ref (rtcp_src);
1173     GST_RTP_SESSION_UNLOCK (rtpsession);
1174
1175     /* set rtcp caps on output pad */
1176     if (!gst_pad_has_current_caps (rtcp_src))
1177       do_rtcp_events (rtpsession, rtcp_src);
1178
1179     GST_LOG_OBJECT (rtpsession, "sending RTCP");
1180     result = gst_pad_push (rtcp_src, buffer);
1181
1182     /* we have to send EOS after this packet */
1183     if (eos) {
1184       GST_LOG_OBJECT (rtpsession, "sending EOS");
1185       gst_pad_push_event (rtcp_src, gst_event_new_eos ());
1186     }
1187     gst_object_unref (rtcp_src);
1188   } else {
1189     GST_RTP_SESSION_UNLOCK (rtpsession);
1190
1191     GST_DEBUG_OBJECT (rtpsession, "not sending RTCP, no output pad");
1192     gst_buffer_unref (buffer);
1193     result = GST_FLOW_OK;
1194   }
1195   return result;
1196
1197   /* ERRORS */
1198 stopping:
1199   {
1200     GST_DEBUG_OBJECT (rtpsession, "we are stopping");
1201     gst_buffer_unref (buffer);
1202     GST_RTP_SESSION_UNLOCK (rtpsession);
1203     return GST_FLOW_OK;
1204   }
1205 }
1206
1207 /* called when the session manager has an SR RTCP packet ready for handling
1208  * inter stream synchronisation */
1209 static GstFlowReturn
1210 gst_rtp_session_sync_rtcp (RTPSession * sess,
1211     GstBuffer * buffer, gpointer user_data)
1212 {
1213   GstFlowReturn result;
1214   GstRtpSession *rtpsession;
1215   GstPad *sync_src;
1216
1217   rtpsession = GST_RTP_SESSION (user_data);
1218
1219   GST_RTP_SESSION_LOCK (rtpsession);
1220   if (rtpsession->priv->stop_thread)
1221     goto stopping;
1222
1223   if ((sync_src = rtpsession->sync_src)) {
1224     gst_object_ref (sync_src);
1225     GST_RTP_SESSION_UNLOCK (rtpsession);
1226
1227     GST_LOG_OBJECT (rtpsession, "sending Sync RTCP");
1228     result = gst_pad_push (sync_src, buffer);
1229     gst_object_unref (sync_src);
1230   } else {
1231     GST_RTP_SESSION_UNLOCK (rtpsession);
1232
1233     GST_DEBUG_OBJECT (rtpsession, "not sending Sync RTCP, no output pad");
1234     gst_buffer_unref (buffer);
1235     result = GST_FLOW_OK;
1236   }
1237   return result;
1238
1239   /* ERRORS */
1240 stopping:
1241   {
1242     GST_DEBUG_OBJECT (rtpsession, "we are stopping");
1243     gst_buffer_unref (buffer);
1244     GST_RTP_SESSION_UNLOCK (rtpsession);
1245     return GST_FLOW_OK;
1246   }
1247 }
1248
1249 static void
1250 gst_rtp_session_cache_caps (GstRtpSession * rtpsession, GstCaps * caps)
1251 {
1252   GstRtpSessionPrivate *priv;
1253   const GstStructure *s;
1254   gint payload;
1255
1256   priv = rtpsession->priv;
1257
1258   GST_DEBUG_OBJECT (rtpsession, "parsing caps");
1259
1260   s = gst_caps_get_structure (caps, 0);
1261   if (!gst_structure_get_int (s, "payload", &payload))
1262     return;
1263
1264   if (g_hash_table_lookup (priv->ptmap, GINT_TO_POINTER (payload)))
1265     return;
1266
1267   g_hash_table_insert (priv->ptmap, GINT_TO_POINTER (payload),
1268       gst_caps_ref (caps));
1269 }
1270
1271 static GstCaps *
1272 gst_rtp_session_get_caps_for_pt (GstRtpSession * rtpsession, guint payload)
1273 {
1274   GstCaps *caps = NULL;
1275   GValue args[2] = { {0}, {0} };
1276   GValue ret = { 0 };
1277
1278   GST_RTP_SESSION_LOCK (rtpsession);
1279   caps = g_hash_table_lookup (rtpsession->priv->ptmap,
1280       GINT_TO_POINTER (payload));
1281   if (caps) {
1282     gst_caps_ref (caps);
1283     goto done;
1284   }
1285
1286   /* not found in the cache, try to get it with a signal */
1287   g_value_init (&args[0], GST_TYPE_ELEMENT);
1288   g_value_set_object (&args[0], rtpsession);
1289   g_value_init (&args[1], G_TYPE_UINT);
1290   g_value_set_uint (&args[1], payload);
1291
1292   g_value_init (&ret, GST_TYPE_CAPS);
1293   g_value_set_boxed (&ret, NULL);
1294
1295   GST_RTP_SESSION_UNLOCK (rtpsession);
1296
1297   g_signal_emitv (args, gst_rtp_session_signals[SIGNAL_REQUEST_PT_MAP], 0,
1298       &ret);
1299
1300   GST_RTP_SESSION_LOCK (rtpsession);
1301
1302   g_value_unset (&args[0]);
1303   g_value_unset (&args[1]);
1304   caps = (GstCaps *) g_value_dup_boxed (&ret);
1305   g_value_unset (&ret);
1306   if (!caps)
1307     goto no_caps;
1308
1309   gst_rtp_session_cache_caps (rtpsession, caps);
1310
1311 done:
1312   GST_RTP_SESSION_UNLOCK (rtpsession);
1313
1314   return caps;
1315
1316 no_caps:
1317   {
1318     GST_DEBUG_OBJECT (rtpsession, "could not get caps");
1319     goto done;
1320   }
1321 }
1322
1323 /* called when the session manager needs the clock rate */
1324 static gint
1325 gst_rtp_session_clock_rate (RTPSession * sess, guint8 payload,
1326     gpointer user_data)
1327 {
1328   gint result = -1;
1329   GstRtpSession *rtpsession;
1330   GstCaps *caps;
1331   const GstStructure *s;
1332
1333   rtpsession = GST_RTP_SESSION_CAST (user_data);
1334
1335   caps = gst_rtp_session_get_caps_for_pt (rtpsession, payload);
1336
1337   if (!caps)
1338     goto done;
1339
1340   s = gst_caps_get_structure (caps, 0);
1341   if (!gst_structure_get_int (s, "clock-rate", &result))
1342     goto no_clock_rate;
1343
1344   gst_caps_unref (caps);
1345
1346   GST_DEBUG_OBJECT (rtpsession, "parsed clock-rate %d", result);
1347
1348 done:
1349
1350   return result;
1351
1352   /* ERRORS */
1353 no_clock_rate:
1354   {
1355     gst_caps_unref (caps);
1356     GST_DEBUG_OBJECT (rtpsession, "No clock-rate in caps!");
1357     goto done;
1358   }
1359 }
1360
1361 /* called when the session manager asks us to reconsider the timeout */
1362 static void
1363 gst_rtp_session_reconsider (RTPSession * sess, gpointer user_data)
1364 {
1365   GstRtpSession *rtpsession;
1366
1367   rtpsession = GST_RTP_SESSION_CAST (user_data);
1368
1369   GST_RTP_SESSION_LOCK (rtpsession);
1370   GST_DEBUG_OBJECT (rtpsession, "unlock timer for reconsideration");
1371   if (rtpsession->priv->id)
1372     gst_clock_id_unschedule (rtpsession->priv->id);
1373   GST_RTP_SESSION_UNLOCK (rtpsession);
1374 }
1375
1376 static gboolean
1377 gst_rtp_session_event_recv_rtp_sink (GstPad * pad, GstObject * parent,
1378     GstEvent * event)
1379 {
1380   GstRtpSession *rtpsession;
1381   gboolean ret = FALSE;
1382
1383   rtpsession = GST_RTP_SESSION (parent);
1384
1385   GST_DEBUG_OBJECT (rtpsession, "received event %s",
1386       GST_EVENT_TYPE_NAME (event));
1387
1388   switch (GST_EVENT_TYPE (event)) {
1389     case GST_EVENT_CAPS:
1390     {
1391       GstCaps *caps;
1392
1393       /* process */
1394       gst_event_parse_caps (event, &caps);
1395       gst_rtp_session_sink_setcaps (pad, rtpsession, caps);
1396       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1397       break;
1398     }
1399     case GST_EVENT_FLUSH_STOP:
1400       gst_segment_init (&rtpsession->recv_rtp_seg, GST_FORMAT_UNDEFINED);
1401       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1402       break;
1403     case GST_EVENT_SEGMENT:
1404     {
1405       GstSegment *segment, in_segment;
1406
1407       segment = &rtpsession->recv_rtp_seg;
1408
1409       /* the newsegment event is needed to convert the RTP timestamp to
1410        * running_time, which is needed to generate a mapping from RTP to NTP
1411        * timestamps in SR reports */
1412       gst_event_copy_segment (event, &in_segment);
1413       GST_DEBUG_OBJECT (rtpsession, "received segment %" GST_SEGMENT_FORMAT,
1414           &in_segment);
1415
1416       /* accept upstream */
1417       gst_segment_copy_into (&in_segment, segment);
1418
1419       /* push event forward */
1420       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1421       break;
1422     }
1423     default:
1424       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1425       break;
1426   }
1427
1428   return ret;
1429
1430 }
1431
1432 static gboolean
1433 gst_rtp_session_request_remote_key_unit (GstRtpSession * rtpsession,
1434     guint32 ssrc, guint payload, gboolean all_headers, gint count)
1435 {
1436   GstCaps *caps;
1437
1438   caps = gst_rtp_session_get_caps_for_pt (rtpsession, payload);
1439
1440   if (caps) {
1441     const GstStructure *s = gst_caps_get_structure (caps, 0);
1442     gboolean pli;
1443     gboolean fir;
1444
1445     pli = gst_structure_has_field (s, "rtcp-fb-nack-pli");
1446     fir = gst_structure_has_field (s, "rtcp-fb-ccm-fir") && all_headers;
1447
1448     /* Google Talk uses FIR for repair, so send it even if we just want a
1449      * regular PLI */
1450     if (!pli &&
1451         gst_structure_has_field (s, "rtcp-fb-x-gstreamer-fir-as-repair"))
1452       fir = TRUE;
1453
1454     gst_caps_unref (caps);
1455
1456     if (pli || fir)
1457       return rtp_session_request_key_unit (rtpsession->priv->session, ssrc,
1458           gst_clock_get_time (rtpsession->priv->sysclock), fir, count);
1459   }
1460
1461   return FALSE;
1462 }
1463
1464 static gboolean
1465 gst_rtp_session_event_recv_rtp_src (GstPad * pad, GstObject * parent,
1466     GstEvent * event)
1467 {
1468   GstRtpSession *rtpsession;
1469   gboolean forward = TRUE;
1470   gboolean ret = TRUE;
1471   const GstStructure *s;
1472   guint32 ssrc;
1473   guint pt;
1474
1475   rtpsession = GST_RTP_SESSION (parent);
1476
1477   switch (GST_EVENT_TYPE (event)) {
1478     case GST_EVENT_CUSTOM_UPSTREAM:
1479       s = gst_event_get_structure (event);
1480       if (gst_structure_has_name (s, "GstForceKeyUnit") &&
1481           gst_structure_get_uint (s, "ssrc", &ssrc) &&
1482           gst_structure_get_uint (s, "payload", &pt)) {
1483         gboolean all_headers = FALSE;
1484         gint count = -1;
1485
1486         gst_structure_get_boolean (s, "all-headers", &all_headers);
1487         if (gst_structure_get_int (s, "count", &count) && count < 0)
1488           count += G_MAXINT;    /* Make sure count is positive if present */
1489         if (gst_rtp_session_request_remote_key_unit (rtpsession, ssrc, pt,
1490                 all_headers, count))
1491           forward = FALSE;
1492       }
1493       break;
1494     default:
1495       break;
1496   }
1497
1498   if (forward) {
1499     GstPad *recv_rtp_sink;
1500
1501     GST_RTP_SESSION_LOCK (rtpsession);
1502     if ((recv_rtp_sink = rtpsession->recv_rtp_sink))
1503       gst_object_ref (recv_rtp_sink);
1504     GST_RTP_SESSION_UNLOCK (rtpsession);
1505
1506     if (recv_rtp_sink) {
1507       ret = gst_pad_push_event (recv_rtp_sink, event);
1508       gst_object_unref (recv_rtp_sink);
1509     } else
1510       gst_event_unref (event);
1511   } else {
1512     gst_event_unref (event);
1513   }
1514
1515   return ret;
1516 }
1517
1518
1519 static GstIterator *
1520 gst_rtp_session_iterate_internal_links (GstPad * pad, GstObject * parent)
1521 {
1522   GstRtpSession *rtpsession;
1523   GstPad *otherpad = NULL;
1524   GstIterator *it = NULL;
1525
1526   rtpsession = GST_RTP_SESSION (parent);
1527
1528   GST_RTP_SESSION_LOCK (rtpsession);
1529   if (pad == rtpsession->recv_rtp_src) {
1530     otherpad = gst_object_ref (rtpsession->recv_rtp_sink);
1531   } else if (pad == rtpsession->recv_rtp_sink) {
1532     otherpad = gst_object_ref (rtpsession->recv_rtp_src);
1533   } else if (pad == rtpsession->send_rtp_src) {
1534     otherpad = gst_object_ref (rtpsession->send_rtp_sink);
1535   } else if (pad == rtpsession->send_rtp_sink) {
1536     otherpad = gst_object_ref (rtpsession->send_rtp_src);
1537   }
1538   GST_RTP_SESSION_UNLOCK (rtpsession);
1539
1540   if (otherpad) {
1541     GValue val = { 0, };
1542
1543     g_value_init (&val, GST_TYPE_PAD);
1544     g_value_set_object (&val, otherpad);
1545     it = gst_iterator_new_single (GST_TYPE_PAD, &val);
1546     g_value_unset (&val);
1547     gst_object_unref (otherpad);
1548   }
1549
1550   return it;
1551 }
1552
1553 static gboolean
1554 gst_rtp_session_sink_setcaps (GstPad * pad, GstRtpSession * rtpsession,
1555     GstCaps * caps)
1556 {
1557   GST_RTP_SESSION_LOCK (rtpsession);
1558   gst_rtp_session_cache_caps (rtpsession, caps);
1559   GST_RTP_SESSION_UNLOCK (rtpsession);
1560
1561   return TRUE;
1562 }
1563
1564 /* receive a packet from a sender, send it to the RTP session manager and
1565  * forward the packet on the rtp_src pad
1566  */
1567 static GstFlowReturn
1568 gst_rtp_session_chain_recv_rtp (GstPad * pad, GstObject * parent,
1569     GstBuffer * buffer)
1570 {
1571   GstRtpSession *rtpsession;
1572   GstRtpSessionPrivate *priv;
1573   GstFlowReturn ret;
1574   GstClockTime current_time, running_time;
1575   GstClockTime timestamp;
1576
1577   rtpsession = GST_RTP_SESSION (parent);
1578   priv = rtpsession->priv;
1579
1580   GST_LOG_OBJECT (rtpsession, "received RTP packet");
1581
1582   /* get NTP time when this packet was captured, this depends on the timestamp. */
1583   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1584   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1585     /* convert to running time using the segment values */
1586     running_time =
1587         gst_segment_to_running_time (&rtpsession->recv_rtp_seg, GST_FORMAT_TIME,
1588         timestamp);
1589   } else {
1590     get_current_times (rtpsession, &running_time, NULL);
1591   }
1592   current_time = gst_clock_get_time (priv->sysclock);
1593
1594   ret = rtp_session_process_rtp (priv->session, buffer, current_time,
1595       running_time);
1596   if (ret != GST_FLOW_OK)
1597     goto push_error;
1598
1599 done:
1600
1601   return ret;
1602
1603   /* ERRORS */
1604 push_error:
1605   {
1606     GST_DEBUG_OBJECT (rtpsession, "process returned %s",
1607         gst_flow_get_name (ret));
1608     goto done;
1609   }
1610 }
1611
1612 static gboolean
1613 gst_rtp_session_event_recv_rtcp_sink (GstPad * pad, GstObject * parent,
1614     GstEvent * event)
1615 {
1616   GstRtpSession *rtpsession;
1617   gboolean ret = FALSE;
1618
1619   rtpsession = GST_RTP_SESSION (parent);
1620
1621   GST_DEBUG_OBJECT (rtpsession, "received event %s",
1622       GST_EVENT_TYPE_NAME (event));
1623
1624   switch (GST_EVENT_TYPE (event)) {
1625     default:
1626       ret = gst_pad_push_event (rtpsession->sync_src, event);
1627       break;
1628   }
1629
1630   return ret;
1631 }
1632
1633 /* Receive an RTCP packet from a sender, send it to the RTP session manager and
1634  * forward the SR packets to the sync_src pad.
1635  */
1636 static GstFlowReturn
1637 gst_rtp_session_chain_recv_rtcp (GstPad * pad, GstObject * parent,
1638     GstBuffer * buffer)
1639 {
1640   GstRtpSession *rtpsession;
1641   GstRtpSessionPrivate *priv;
1642   GstClockTime current_time;
1643   guint64 ntpnstime;
1644
1645   rtpsession = GST_RTP_SESSION (parent);
1646   priv = rtpsession->priv;
1647
1648   GST_LOG_OBJECT (rtpsession, "received RTCP packet");
1649
1650   current_time = gst_clock_get_time (priv->sysclock);
1651   get_current_times (rtpsession, NULL, &ntpnstime);
1652
1653   rtp_session_process_rtcp (priv->session, buffer, current_time, ntpnstime);
1654
1655   return GST_FLOW_OK;           /* always return OK */
1656 }
1657
1658 static gboolean
1659 gst_rtp_session_query_send_rtcp_src (GstPad * pad, GstObject * parent,
1660     GstQuery * query)
1661 {
1662   GstRtpSession *rtpsession;
1663   gboolean ret = FALSE;
1664
1665   rtpsession = GST_RTP_SESSION (parent);
1666
1667   GST_DEBUG_OBJECT (rtpsession, "received QUERY %s",
1668       GST_QUERY_TYPE_NAME (query));
1669
1670   switch (GST_QUERY_TYPE (query)) {
1671     case GST_QUERY_LATENCY:
1672       ret = TRUE;
1673       /* use the defaults for the latency query. */
1674       gst_query_set_latency (query, FALSE, 0, -1);
1675       break;
1676     default:
1677       /* other queries simply fail for now */
1678       break;
1679   }
1680
1681   return ret;
1682 }
1683
1684 static gboolean
1685 gst_rtp_session_event_send_rtcp_src (GstPad * pad, GstObject * parent,
1686     GstEvent * event)
1687 {
1688   GstRtpSession *rtpsession;
1689   gboolean ret = TRUE;
1690
1691   rtpsession = GST_RTP_SESSION (parent);
1692   GST_DEBUG_OBJECT (rtpsession, "received EVENT %s",
1693       GST_EVENT_TYPE_NAME (event));
1694
1695   switch (GST_EVENT_TYPE (event)) {
1696     case GST_EVENT_SEEK:
1697     case GST_EVENT_LATENCY:
1698       gst_event_unref (event);
1699       ret = TRUE;
1700       break;
1701     default:
1702       /* other events simply fail for now */
1703       gst_event_unref (event);
1704       ret = FALSE;
1705       break;
1706   }
1707
1708   return ret;
1709 }
1710
1711
1712 static gboolean
1713 gst_rtp_session_event_send_rtp_sink (GstPad * pad, GstObject * parent,
1714     GstEvent * event)
1715 {
1716   GstRtpSession *rtpsession;
1717   gboolean ret = FALSE;
1718
1719   rtpsession = GST_RTP_SESSION (parent);
1720
1721   GST_DEBUG_OBJECT (rtpsession, "received EVENT %s",
1722       GST_EVENT_TYPE_NAME (event));
1723
1724   switch (GST_EVENT_TYPE (event)) {
1725     case GST_EVENT_CAPS:
1726     {
1727       GstCaps *caps;
1728
1729       /* process */
1730       gst_event_parse_caps (event, &caps);
1731       gst_rtp_session_setcaps_send_rtp (pad, rtpsession, caps);
1732       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1733       break;
1734     }
1735     case GST_EVENT_FLUSH_STOP:
1736       gst_segment_init (&rtpsession->send_rtp_seg, GST_FORMAT_UNDEFINED);
1737       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1738       break;
1739     case GST_EVENT_SEGMENT:{
1740       GstSegment *segment, in_segment;
1741
1742       segment = &rtpsession->send_rtp_seg;
1743
1744       /* the newsegment event is needed to convert the RTP timestamp to
1745        * running_time, which is needed to generate a mapping from RTP to NTP
1746        * timestamps in SR reports */
1747       gst_event_copy_segment (event, &in_segment);
1748       GST_DEBUG_OBJECT (rtpsession, "received segment %" GST_SEGMENT_FORMAT,
1749           &in_segment);
1750
1751       /* accept upstream */
1752       gst_segment_copy_into (&in_segment, segment);
1753
1754       /* push event forward */
1755       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1756       break;
1757     }
1758     case GST_EVENT_EOS:{
1759       GstClockTime current_time;
1760
1761       /* push downstream FIXME, we are not supposed to leave the session just
1762        * because we stop sending. */
1763       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1764       current_time = gst_clock_get_time (rtpsession->priv->sysclock);
1765
1766       GST_DEBUG_OBJECT (rtpsession, "scheduling BYE message");
1767       rtp_session_mark_all_bye (rtpsession->priv->session, "End Of Stream");
1768       rtp_session_schedule_bye (rtpsession->priv->session, current_time);
1769       break;
1770     }
1771     default:{
1772       GstPad *send_rtp_src;
1773
1774       GST_RTP_SESSION_LOCK (rtpsession);
1775       if ((send_rtp_src = rtpsession->send_rtp_src))
1776         gst_object_ref (send_rtp_src);
1777       GST_RTP_SESSION_UNLOCK (rtpsession);
1778
1779       if (send_rtp_src) {
1780         ret = gst_pad_push_event (send_rtp_src, event);
1781         gst_object_unref (send_rtp_src);
1782       } else
1783         gst_event_unref (event);
1784
1785       break;
1786     }
1787   }
1788
1789   return ret;
1790 }
1791
1792 static gboolean
1793 gst_rtp_session_event_send_rtp_src (GstPad * pad, GstObject * parent,
1794     GstEvent * event)
1795 {
1796   GstRtpSession *rtpsession;
1797   gboolean ret = FALSE;
1798
1799   rtpsession = GST_RTP_SESSION (parent);
1800
1801   GST_DEBUG_OBJECT (rtpsession, "received EVENT %s",
1802       GST_EVENT_TYPE_NAME (event));
1803
1804   switch (GST_EVENT_TYPE (event)) {
1805     case GST_EVENT_LATENCY:
1806       /* save the latency, we need this to know when an RTP packet will be
1807        * rendered by the sink */
1808       gst_event_parse_latency (event, &rtpsession->priv->send_latency);
1809
1810       ret = gst_pad_event_default (pad, parent, event);
1811       break;
1812     default:
1813       ret = gst_pad_event_default (pad, parent, event);
1814       break;
1815   }
1816   return ret;
1817 }
1818
1819 static GstCaps *
1820 gst_rtp_session_getcaps_send_rtp (GstPad * pad, GstRtpSession * rtpsession,
1821     GstCaps * filter)
1822 {
1823   GstRtpSessionPrivate *priv;
1824   GstCaps *result;
1825   GstStructure *s1, *s2;
1826   guint ssrc;
1827
1828   priv = rtpsession->priv;
1829
1830   ssrc = rtp_session_suggest_ssrc (priv->session);
1831
1832   /* we can basically accept anything but we prefer to receive packets with our
1833    * internal SSRC so that we don't have to patch it. Create a structure with
1834    * the SSRC and another one without. */
1835   s1 = gst_structure_new ("application/x-rtp", "ssrc", G_TYPE_UINT, ssrc, NULL);
1836   s2 = gst_structure_new_empty ("application/x-rtp");
1837
1838   result = gst_caps_new_full (s1, s2, NULL);
1839
1840   if (filter) {
1841     GstCaps *caps = result;
1842
1843     result = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
1844     gst_caps_unref (caps);
1845   }
1846
1847   GST_DEBUG_OBJECT (rtpsession, "getting caps %" GST_PTR_FORMAT, result);
1848
1849   return result;
1850 }
1851
1852 static gboolean
1853 gst_rtp_session_query_send_rtp (GstPad * pad, GstObject * parent,
1854     GstQuery * query)
1855 {
1856   gboolean res = FALSE;
1857   GstRtpSession *rtpsession;
1858
1859   rtpsession = GST_RTP_SESSION (parent);
1860
1861   switch (GST_QUERY_TYPE (query)) {
1862     case GST_QUERY_CAPS:
1863     {
1864       GstCaps *filter, *caps;
1865
1866       gst_query_parse_caps (query, &filter);
1867       caps = gst_rtp_session_getcaps_send_rtp (pad, rtpsession, filter);
1868       gst_query_set_caps_result (query, caps);
1869       gst_caps_unref (caps);
1870       res = TRUE;
1871       break;
1872     }
1873     default:
1874       res = gst_pad_query_default (pad, parent, query);
1875       break;
1876   }
1877
1878   return res;
1879 }
1880
1881 static gboolean
1882 gst_rtp_session_setcaps_send_rtp (GstPad * pad, GstRtpSession * rtpsession,
1883     GstCaps * caps)
1884 {
1885   GstRtpSessionPrivate *priv;
1886   GstStructure *s = gst_caps_get_structure (caps, 0);
1887   guint ssrc;
1888
1889   priv = rtpsession->priv;
1890
1891   if (gst_structure_get_uint (s, "ssrc", &ssrc)) {
1892     GST_DEBUG_OBJECT (rtpsession, "setting internal SSRC to %08x", ssrc);
1893     rtp_session_set_internal_ssrc (priv->session, ssrc);
1894   }
1895   rtp_session_update_send_caps (priv->session, caps);
1896
1897   return TRUE;
1898 }
1899
1900 /* Recieve an RTP packet or a list of packets to be send to the receivers,
1901  * send to RTP session manager and forward to send_rtp_src.
1902  */
1903 static GstFlowReturn
1904 gst_rtp_session_chain_send_rtp_common (GstRtpSession * rtpsession,
1905     gpointer data, gboolean is_list)
1906 {
1907   GstRtpSessionPrivate *priv;
1908   GstFlowReturn ret;
1909   GstClockTime timestamp, running_time;
1910   GstClockTime current_time;
1911
1912   priv = rtpsession->priv;
1913
1914   GST_LOG_OBJECT (rtpsession, "received RTP %s", is_list ? "list" : "packet");
1915
1916   /* get NTP time when this packet was captured, this depends on the timestamp. */
1917   if (is_list) {
1918     GstBuffer *buffer = NULL;
1919
1920     /* All groups in an list have the same timestamp.
1921      * So, just take it from the first group. */
1922     buffer = gst_buffer_list_get (GST_BUFFER_LIST_CAST (data), 0);
1923     if (buffer)
1924       timestamp = GST_BUFFER_TIMESTAMP (buffer);
1925     else
1926       timestamp = -1;
1927   } else {
1928     timestamp = GST_BUFFER_TIMESTAMP (GST_BUFFER_CAST (data));
1929   }
1930
1931   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1932     /* convert to running time using the segment start value. */
1933     running_time =
1934         gst_segment_to_running_time (&rtpsession->send_rtp_seg, GST_FORMAT_TIME,
1935         timestamp);
1936     running_time += priv->send_latency;
1937   } else {
1938     /* no timestamp. */
1939     running_time = -1;
1940   }
1941
1942   current_time = gst_clock_get_time (priv->sysclock);
1943   ret = rtp_session_send_rtp (priv->session, data, is_list, current_time,
1944       running_time);
1945   if (ret != GST_FLOW_OK)
1946     goto push_error;
1947
1948 done:
1949
1950   return ret;
1951
1952   /* ERRORS */
1953 push_error:
1954   {
1955     GST_DEBUG_OBJECT (rtpsession, "process returned %s",
1956         gst_flow_get_name (ret));
1957     goto done;
1958   }
1959 }
1960
1961 static GstFlowReturn
1962 gst_rtp_session_chain_send_rtp (GstPad * pad, GstObject * parent,
1963     GstBuffer * buffer)
1964 {
1965   GstRtpSession *rtpsession = GST_RTP_SESSION (parent);
1966
1967   return gst_rtp_session_chain_send_rtp_common (rtpsession, buffer, FALSE);
1968 }
1969
1970 static GstFlowReturn
1971 gst_rtp_session_chain_send_rtp_list (GstPad * pad, GstObject * parent,
1972     GstBufferList * list)
1973 {
1974   GstRtpSession *rtpsession = GST_RTP_SESSION (parent);
1975
1976   return gst_rtp_session_chain_send_rtp_common (rtpsession, list, TRUE);
1977 }
1978
1979 /* Create sinkpad to receive RTP packets from senders. This will also create a
1980  * srcpad for the RTP packets.
1981  */
1982 static GstPad *
1983 create_recv_rtp_sink (GstRtpSession * rtpsession)
1984 {
1985   GST_DEBUG_OBJECT (rtpsession, "creating RTP sink pad");
1986
1987   rtpsession->recv_rtp_sink =
1988       gst_pad_new_from_static_template (&rtpsession_recv_rtp_sink_template,
1989       "recv_rtp_sink");
1990   gst_pad_set_chain_function (rtpsession->recv_rtp_sink,
1991       gst_rtp_session_chain_recv_rtp);
1992   gst_pad_set_event_function (rtpsession->recv_rtp_sink,
1993       gst_rtp_session_event_recv_rtp_sink);
1994   gst_pad_set_iterate_internal_links_function (rtpsession->recv_rtp_sink,
1995       gst_rtp_session_iterate_internal_links);
1996   gst_pad_set_active (rtpsession->recv_rtp_sink, TRUE);
1997   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
1998       rtpsession->recv_rtp_sink);
1999
2000   GST_DEBUG_OBJECT (rtpsession, "creating RTP src pad");
2001   rtpsession->recv_rtp_src =
2002       gst_pad_new_from_static_template (&rtpsession_recv_rtp_src_template,
2003       "recv_rtp_src");
2004   gst_pad_set_event_function (rtpsession->recv_rtp_src,
2005       gst_rtp_session_event_recv_rtp_src);
2006   gst_pad_set_iterate_internal_links_function (rtpsession->recv_rtp_src,
2007       gst_rtp_session_iterate_internal_links);
2008   gst_pad_use_fixed_caps (rtpsession->recv_rtp_src);
2009   gst_pad_set_active (rtpsession->recv_rtp_src, TRUE);
2010   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->recv_rtp_src);
2011
2012   return rtpsession->recv_rtp_sink;
2013 }
2014
2015 /* Remove sinkpad to receive RTP packets from senders. This will also remove
2016  * the srcpad for the RTP packets.
2017  */
2018 static void
2019 remove_recv_rtp_sink (GstRtpSession * rtpsession)
2020 {
2021   GST_DEBUG_OBJECT (rtpsession, "removing RTP sink pad");
2022
2023   /* deactivate from source to sink */
2024   gst_pad_set_active (rtpsession->recv_rtp_src, FALSE);
2025   gst_pad_set_active (rtpsession->recv_rtp_sink, FALSE);
2026
2027   /* remove pads */
2028   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2029       rtpsession->recv_rtp_sink);
2030   rtpsession->recv_rtp_sink = NULL;
2031
2032   GST_DEBUG_OBJECT (rtpsession, "removing RTP src pad");
2033   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2034       rtpsession->recv_rtp_src);
2035   rtpsession->recv_rtp_src = NULL;
2036 }
2037
2038 /* Create a sinkpad to receive RTCP messages from senders, this will also create a
2039  * sync_src pad for the SR packets.
2040  */
2041 static GstPad *
2042 create_recv_rtcp_sink (GstRtpSession * rtpsession)
2043 {
2044   GST_DEBUG_OBJECT (rtpsession, "creating RTCP sink pad");
2045
2046   rtpsession->recv_rtcp_sink =
2047       gst_pad_new_from_static_template (&rtpsession_recv_rtcp_sink_template,
2048       "recv_rtcp_sink");
2049   gst_pad_set_chain_function (rtpsession->recv_rtcp_sink,
2050       gst_rtp_session_chain_recv_rtcp);
2051   gst_pad_set_event_function (rtpsession->recv_rtcp_sink,
2052       gst_rtp_session_event_recv_rtcp_sink);
2053   gst_pad_set_iterate_internal_links_function (rtpsession->recv_rtcp_sink,
2054       gst_rtp_session_iterate_internal_links);
2055   gst_pad_set_active (rtpsession->recv_rtcp_sink, TRUE);
2056   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
2057       rtpsession->recv_rtcp_sink);
2058
2059   GST_DEBUG_OBJECT (rtpsession, "creating sync src pad");
2060   rtpsession->sync_src =
2061       gst_pad_new_from_static_template (&rtpsession_sync_src_template,
2062       "sync_src");
2063   gst_pad_set_iterate_internal_links_function (rtpsession->sync_src,
2064       gst_rtp_session_iterate_internal_links);
2065   gst_pad_use_fixed_caps (rtpsession->sync_src);
2066   gst_pad_set_active (rtpsession->sync_src, TRUE);
2067   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->sync_src);
2068
2069   return rtpsession->recv_rtcp_sink;
2070 }
2071
2072 static void
2073 remove_recv_rtcp_sink (GstRtpSession * rtpsession)
2074 {
2075   GST_DEBUG_OBJECT (rtpsession, "removing RTCP sink pad");
2076
2077   gst_pad_set_active (rtpsession->sync_src, FALSE);
2078   gst_pad_set_active (rtpsession->recv_rtcp_sink, FALSE);
2079
2080   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2081       rtpsession->recv_rtcp_sink);
2082   rtpsession->recv_rtcp_sink = NULL;
2083
2084   GST_DEBUG_OBJECT (rtpsession, "removing sync src pad");
2085   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->sync_src);
2086   rtpsession->sync_src = NULL;
2087 }
2088
2089 /* Create a sinkpad to receive RTP packets for receivers. This will also create a
2090  * send_rtp_src pad.
2091  */
2092 static GstPad *
2093 create_send_rtp_sink (GstRtpSession * rtpsession)
2094 {
2095   GST_DEBUG_OBJECT (rtpsession, "creating pad");
2096
2097   rtpsession->send_rtp_sink =
2098       gst_pad_new_from_static_template (&rtpsession_send_rtp_sink_template,
2099       "send_rtp_sink");
2100   gst_pad_set_chain_function (rtpsession->send_rtp_sink,
2101       gst_rtp_session_chain_send_rtp);
2102   gst_pad_set_chain_list_function (rtpsession->send_rtp_sink,
2103       gst_rtp_session_chain_send_rtp_list);
2104   gst_pad_set_query_function (rtpsession->send_rtp_sink,
2105       gst_rtp_session_query_send_rtp);
2106   gst_pad_set_event_function (rtpsession->send_rtp_sink,
2107       gst_rtp_session_event_send_rtp_sink);
2108   gst_pad_set_iterate_internal_links_function (rtpsession->send_rtp_sink,
2109       gst_rtp_session_iterate_internal_links);
2110   gst_pad_set_active (rtpsession->send_rtp_sink, TRUE);
2111   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
2112       rtpsession->send_rtp_sink);
2113
2114   rtpsession->send_rtp_src =
2115       gst_pad_new_from_static_template (&rtpsession_send_rtp_src_template,
2116       "send_rtp_src");
2117   gst_pad_set_iterate_internal_links_function (rtpsession->send_rtp_src,
2118       gst_rtp_session_iterate_internal_links);
2119   gst_pad_set_event_function (rtpsession->send_rtp_src,
2120       gst_rtp_session_event_send_rtp_src);
2121   gst_pad_set_active (rtpsession->send_rtp_src, TRUE);
2122   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->send_rtp_src);
2123
2124   return rtpsession->send_rtp_sink;
2125 }
2126
2127 static void
2128 remove_send_rtp_sink (GstRtpSession * rtpsession)
2129 {
2130   GST_DEBUG_OBJECT (rtpsession, "removing pad");
2131
2132   gst_pad_set_active (rtpsession->send_rtp_src, FALSE);
2133   gst_pad_set_active (rtpsession->send_rtp_sink, FALSE);
2134
2135   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2136       rtpsession->send_rtp_sink);
2137   rtpsession->send_rtp_sink = NULL;
2138
2139   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2140       rtpsession->send_rtp_src);
2141   rtpsession->send_rtp_src = NULL;
2142 }
2143
2144 /* Create a srcpad with the RTCP packets to send out.
2145  * This pad will be driven by the RTP session manager when it wants to send out
2146  * RTCP packets.
2147  */
2148 static GstPad *
2149 create_send_rtcp_src (GstRtpSession * rtpsession)
2150 {
2151   GST_DEBUG_OBJECT (rtpsession, "creating pad");
2152
2153   rtpsession->send_rtcp_src =
2154       gst_pad_new_from_static_template (&rtpsession_send_rtcp_src_template,
2155       "send_rtcp_src");
2156   gst_pad_use_fixed_caps (rtpsession->send_rtcp_src);
2157   gst_pad_set_active (rtpsession->send_rtcp_src, TRUE);
2158   gst_pad_set_iterate_internal_links_function (rtpsession->send_rtcp_src,
2159       gst_rtp_session_iterate_internal_links);
2160   gst_pad_set_query_function (rtpsession->send_rtcp_src,
2161       gst_rtp_session_query_send_rtcp_src);
2162   gst_pad_set_event_function (rtpsession->send_rtcp_src,
2163       gst_rtp_session_event_send_rtcp_src);
2164   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
2165       rtpsession->send_rtcp_src);
2166
2167   return rtpsession->send_rtcp_src;
2168 }
2169
2170 static void
2171 remove_send_rtcp_src (GstRtpSession * rtpsession)
2172 {
2173   GST_DEBUG_OBJECT (rtpsession, "removing pad");
2174
2175   gst_pad_set_active (rtpsession->send_rtcp_src, FALSE);
2176
2177   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2178       rtpsession->send_rtcp_src);
2179   rtpsession->send_rtcp_src = NULL;
2180 }
2181
2182 static GstPad *
2183 gst_rtp_session_request_new_pad (GstElement * element,
2184     GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
2185 {
2186   GstRtpSession *rtpsession;
2187   GstElementClass *klass;
2188   GstPad *result;
2189
2190   g_return_val_if_fail (templ != NULL, NULL);
2191   g_return_val_if_fail (GST_IS_RTP_SESSION (element), NULL);
2192
2193   rtpsession = GST_RTP_SESSION (element);
2194   klass = GST_ELEMENT_GET_CLASS (element);
2195
2196   GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
2197
2198   GST_RTP_SESSION_LOCK (rtpsession);
2199
2200   /* figure out the template */
2201   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink")) {
2202     if (rtpsession->recv_rtp_sink != NULL)
2203       goto exists;
2204
2205     result = create_recv_rtp_sink (rtpsession);
2206   } else if (templ == gst_element_class_get_pad_template (klass,
2207           "recv_rtcp_sink")) {
2208     if (rtpsession->recv_rtcp_sink != NULL)
2209       goto exists;
2210
2211     result = create_recv_rtcp_sink (rtpsession);
2212   } else if (templ == gst_element_class_get_pad_template (klass,
2213           "send_rtp_sink")) {
2214     if (rtpsession->send_rtp_sink != NULL)
2215       goto exists;
2216
2217     result = create_send_rtp_sink (rtpsession);
2218   } else if (templ == gst_element_class_get_pad_template (klass,
2219           "send_rtcp_src")) {
2220     if (rtpsession->send_rtcp_src != NULL)
2221       goto exists;
2222
2223     result = create_send_rtcp_src (rtpsession);
2224   } else
2225     goto wrong_template;
2226
2227   GST_RTP_SESSION_UNLOCK (rtpsession);
2228
2229   return result;
2230
2231   /* ERRORS */
2232 wrong_template:
2233   {
2234     GST_RTP_SESSION_UNLOCK (rtpsession);
2235     g_warning ("gstrtpsession: this is not our template");
2236     return NULL;
2237   }
2238 exists:
2239   {
2240     GST_RTP_SESSION_UNLOCK (rtpsession);
2241     g_warning ("gstrtpsession: pad already requested");
2242     return NULL;
2243   }
2244 }
2245
2246 static void
2247 gst_rtp_session_release_pad (GstElement * element, GstPad * pad)
2248 {
2249   GstRtpSession *rtpsession;
2250
2251   g_return_if_fail (GST_IS_RTP_SESSION (element));
2252   g_return_if_fail (GST_IS_PAD (pad));
2253
2254   rtpsession = GST_RTP_SESSION (element);
2255
2256   GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2257
2258   GST_RTP_SESSION_LOCK (rtpsession);
2259
2260   if (rtpsession->recv_rtp_sink == pad) {
2261     remove_recv_rtp_sink (rtpsession);
2262   } else if (rtpsession->recv_rtcp_sink == pad) {
2263     remove_recv_rtcp_sink (rtpsession);
2264   } else if (rtpsession->send_rtp_sink == pad) {
2265     remove_send_rtp_sink (rtpsession);
2266   } else if (rtpsession->send_rtcp_src == pad) {
2267     remove_send_rtcp_src (rtpsession);
2268   } else
2269     goto wrong_pad;
2270
2271   GST_RTP_SESSION_UNLOCK (rtpsession);
2272
2273   return;
2274
2275   /* ERRORS */
2276 wrong_pad:
2277   {
2278     GST_RTP_SESSION_UNLOCK (rtpsession);
2279     g_warning ("gstrtpsession: asked to release an unknown pad");
2280     return;
2281   }
2282 }
2283
2284 static void
2285 gst_rtp_session_request_key_unit (RTPSession * sess,
2286     gboolean all_headers, gpointer user_data)
2287 {
2288   GstRtpSession *rtpsession = GST_RTP_SESSION (user_data);
2289   GstEvent *event;
2290   GstPad *send_rtp_sink;
2291
2292   GST_RTP_SESSION_LOCK (rtpsession);
2293   if ((send_rtp_sink = rtpsession->send_rtp_sink))
2294     gst_object_ref (send_rtp_sink);
2295   GST_RTP_SESSION_UNLOCK (rtpsession);
2296
2297   if (send_rtp_sink) {
2298     event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
2299         gst_structure_new ("GstForceKeyUnit",
2300             "all-headers", G_TYPE_BOOLEAN, all_headers, NULL));
2301     gst_pad_push_event (send_rtp_sink, event);
2302     gst_object_unref (send_rtp_sink);
2303   }
2304 }
2305
2306 static GstClockTime
2307 gst_rtp_session_request_time (RTPSession * session, gpointer user_data)
2308 {
2309   GstRtpSession *rtpsession = GST_RTP_SESSION (user_data);
2310
2311   return gst_clock_get_time (rtpsession->priv->sysclock);
2312 }