jitterbuffer: signal timestamp discont
[platform/upstream/gstreamer.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     RTPSource * src, 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
1112   stream_id =
1113       g_strdup_printf ("%08x%08x%08x%08x", g_random_int (), g_random_int (),
1114       g_random_int (), g_random_int ());
1115
1116   event = gst_event_new_stream_start (stream_id);
1117   gst_pad_push_event (srcpad, event);
1118   g_free (stream_id);
1119
1120   caps = gst_caps_new_empty_simple ("application/x-rtcp");
1121   gst_pad_set_caps (srcpad, caps);
1122   gst_caps_unref (caps);
1123
1124   gst_segment_init (&seg, GST_FORMAT_TIME);
1125   event = gst_event_new_segment (&seg);
1126   gst_pad_push_event (srcpad, event);
1127 }
1128
1129 /* called when the session manager has an RTCP packet ready for further
1130  * sending. The eos flag is set when an EOS event should be sent downstream as
1131  * well. */
1132 static GstFlowReturn
1133 gst_rtp_session_send_rtcp (RTPSession * sess, RTPSource * src,
1134     GstBuffer * buffer, gboolean eos, gpointer user_data)
1135 {
1136   GstFlowReturn result;
1137   GstRtpSession *rtpsession;
1138   GstPad *rtcp_src;
1139
1140   rtpsession = GST_RTP_SESSION (user_data);
1141
1142   GST_RTP_SESSION_LOCK (rtpsession);
1143   if (rtpsession->priv->stop_thread)
1144     goto stopping;
1145
1146   if ((rtcp_src = rtpsession->send_rtcp_src)) {
1147     gst_object_ref (rtcp_src);
1148     GST_RTP_SESSION_UNLOCK (rtpsession);
1149
1150     /* set rtcp caps on output pad */
1151     if (!gst_pad_has_current_caps (rtcp_src))
1152       do_rtcp_events (rtpsession, rtcp_src);
1153
1154     GST_LOG_OBJECT (rtpsession, "sending RTCP");
1155     result = gst_pad_push (rtcp_src, buffer);
1156
1157     /* we have to send EOS after this packet */
1158     if (eos) {
1159       GST_LOG_OBJECT (rtpsession, "sending EOS");
1160       gst_pad_push_event (rtcp_src, gst_event_new_eos ());
1161     }
1162     gst_object_unref (rtcp_src);
1163   } else {
1164     GST_RTP_SESSION_UNLOCK (rtpsession);
1165
1166     GST_DEBUG_OBJECT (rtpsession, "not sending RTCP, no output pad");
1167     gst_buffer_unref (buffer);
1168     result = GST_FLOW_OK;
1169   }
1170   return result;
1171
1172   /* ERRORS */
1173 stopping:
1174   {
1175     GST_DEBUG_OBJECT (rtpsession, "we are stopping");
1176     gst_buffer_unref (buffer);
1177     GST_RTP_SESSION_UNLOCK (rtpsession);
1178     return GST_FLOW_OK;
1179   }
1180 }
1181
1182 /* called when the session manager has an SR RTCP packet ready for handling
1183  * inter stream synchronisation */
1184 static GstFlowReturn
1185 gst_rtp_session_sync_rtcp (RTPSession * sess, RTPSource * src,
1186     GstBuffer * buffer, gpointer user_data)
1187 {
1188   GstFlowReturn result;
1189   GstRtpSession *rtpsession;
1190   GstPad *sync_src;
1191
1192   rtpsession = GST_RTP_SESSION (user_data);
1193
1194   GST_RTP_SESSION_LOCK (rtpsession);
1195   if (rtpsession->priv->stop_thread)
1196     goto stopping;
1197
1198   if ((sync_src = rtpsession->sync_src)) {
1199     gst_object_ref (sync_src);
1200     GST_RTP_SESSION_UNLOCK (rtpsession);
1201
1202     GST_LOG_OBJECT (rtpsession, "sending Sync RTCP");
1203     result = gst_pad_push (sync_src, buffer);
1204     gst_object_unref (sync_src);
1205   } else {
1206     GST_RTP_SESSION_UNLOCK (rtpsession);
1207
1208     GST_DEBUG_OBJECT (rtpsession, "not sending Sync RTCP, no output pad");
1209     gst_buffer_unref (buffer);
1210     result = GST_FLOW_OK;
1211   }
1212   return result;
1213
1214   /* ERRORS */
1215 stopping:
1216   {
1217     GST_DEBUG_OBJECT (rtpsession, "we are stopping");
1218     gst_buffer_unref (buffer);
1219     GST_RTP_SESSION_UNLOCK (rtpsession);
1220     return GST_FLOW_OK;
1221   }
1222 }
1223
1224 static void
1225 gst_rtp_session_cache_caps (GstRtpSession * rtpsession, GstCaps * caps)
1226 {
1227   GstRtpSessionPrivate *priv;
1228   const GstStructure *s;
1229   gint payload;
1230
1231   priv = rtpsession->priv;
1232
1233   GST_DEBUG_OBJECT (rtpsession, "parsing caps");
1234
1235   s = gst_caps_get_structure (caps, 0);
1236   if (!gst_structure_get_int (s, "payload", &payload))
1237     return;
1238
1239   if (g_hash_table_lookup (priv->ptmap, GINT_TO_POINTER (payload)))
1240     return;
1241
1242   g_hash_table_insert (priv->ptmap, GINT_TO_POINTER (payload),
1243       gst_caps_ref (caps));
1244 }
1245
1246 static GstCaps *
1247 gst_rtp_session_get_caps_for_pt (GstRtpSession * rtpsession, guint payload)
1248 {
1249   GstCaps *caps = NULL;
1250   GValue args[2] = { {0}, {0} };
1251   GValue ret = { 0 };
1252
1253   GST_RTP_SESSION_LOCK (rtpsession);
1254   caps = g_hash_table_lookup (rtpsession->priv->ptmap,
1255       GINT_TO_POINTER (payload));
1256   if (caps) {
1257     gst_caps_ref (caps);
1258     goto done;
1259   }
1260
1261   /* not found in the cache, try to get it with a signal */
1262   g_value_init (&args[0], GST_TYPE_ELEMENT);
1263   g_value_set_object (&args[0], rtpsession);
1264   g_value_init (&args[1], G_TYPE_UINT);
1265   g_value_set_uint (&args[1], payload);
1266
1267   g_value_init (&ret, GST_TYPE_CAPS);
1268   g_value_set_boxed (&ret, NULL);
1269
1270   GST_RTP_SESSION_UNLOCK (rtpsession);
1271
1272   g_signal_emitv (args, gst_rtp_session_signals[SIGNAL_REQUEST_PT_MAP], 0,
1273       &ret);
1274
1275   GST_RTP_SESSION_LOCK (rtpsession);
1276
1277   g_value_unset (&args[0]);
1278   g_value_unset (&args[1]);
1279   caps = (GstCaps *) g_value_dup_boxed (&ret);
1280   g_value_unset (&ret);
1281   if (!caps)
1282     goto no_caps;
1283
1284   gst_rtp_session_cache_caps (rtpsession, caps);
1285
1286 done:
1287   GST_RTP_SESSION_UNLOCK (rtpsession);
1288
1289   return caps;
1290
1291 no_caps:
1292   {
1293     GST_DEBUG_OBJECT (rtpsession, "could not get caps");
1294     goto done;
1295   }
1296 }
1297
1298 /* called when the session manager needs the clock rate */
1299 static gint
1300 gst_rtp_session_clock_rate (RTPSession * sess, guint8 payload,
1301     gpointer user_data)
1302 {
1303   gint result = -1;
1304   GstRtpSession *rtpsession;
1305   GstCaps *caps;
1306   const GstStructure *s;
1307
1308   rtpsession = GST_RTP_SESSION_CAST (user_data);
1309
1310   caps = gst_rtp_session_get_caps_for_pt (rtpsession, payload);
1311
1312   if (!caps)
1313     goto done;
1314
1315   s = gst_caps_get_structure (caps, 0);
1316   if (!gst_structure_get_int (s, "clock-rate", &result))
1317     goto no_clock_rate;
1318
1319   gst_caps_unref (caps);
1320
1321   GST_DEBUG_OBJECT (rtpsession, "parsed clock-rate %d", result);
1322
1323 done:
1324
1325   return result;
1326
1327   /* ERRORS */
1328 no_clock_rate:
1329   {
1330     gst_caps_unref (caps);
1331     GST_DEBUG_OBJECT (rtpsession, "No clock-rate in caps!");
1332     goto done;
1333   }
1334 }
1335
1336 /* called when the session manager asks us to reconsider the timeout */
1337 static void
1338 gst_rtp_session_reconsider (RTPSession * sess, gpointer user_data)
1339 {
1340   GstRtpSession *rtpsession;
1341
1342   rtpsession = GST_RTP_SESSION_CAST (user_data);
1343
1344   GST_RTP_SESSION_LOCK (rtpsession);
1345   GST_DEBUG_OBJECT (rtpsession, "unlock timer for reconsideration");
1346   if (rtpsession->priv->id)
1347     gst_clock_id_unschedule (rtpsession->priv->id);
1348   GST_RTP_SESSION_UNLOCK (rtpsession);
1349 }
1350
1351 static gboolean
1352 gst_rtp_session_event_recv_rtp_sink (GstPad * pad, GstObject * parent,
1353     GstEvent * event)
1354 {
1355   GstRtpSession *rtpsession;
1356   gboolean ret = FALSE;
1357
1358   rtpsession = GST_RTP_SESSION (parent);
1359
1360   GST_DEBUG_OBJECT (rtpsession, "received event %s",
1361       GST_EVENT_TYPE_NAME (event));
1362
1363   switch (GST_EVENT_TYPE (event)) {
1364     case GST_EVENT_CAPS:
1365     {
1366       GstCaps *caps;
1367
1368       /* process */
1369       gst_event_parse_caps (event, &caps);
1370       gst_rtp_session_sink_setcaps (pad, rtpsession, caps);
1371       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1372       break;
1373     }
1374     case GST_EVENT_FLUSH_STOP:
1375       gst_segment_init (&rtpsession->recv_rtp_seg, GST_FORMAT_UNDEFINED);
1376       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1377       break;
1378     case GST_EVENT_SEGMENT:
1379     {
1380       GstSegment *segment, in_segment;
1381
1382       segment = &rtpsession->recv_rtp_seg;
1383
1384       /* the newsegment event is needed to convert the RTP timestamp to
1385        * running_time, which is needed to generate a mapping from RTP to NTP
1386        * timestamps in SR reports */
1387       gst_event_copy_segment (event, &in_segment);
1388       GST_DEBUG_OBJECT (rtpsession, "received segment %" GST_SEGMENT_FORMAT,
1389           &in_segment);
1390
1391       /* accept upstream */
1392       gst_segment_copy_into (&in_segment, segment);
1393
1394       /* push event forward */
1395       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1396       break;
1397     }
1398     default:
1399       ret = gst_pad_push_event (rtpsession->recv_rtp_src, event);
1400       break;
1401   }
1402
1403   return ret;
1404
1405 }
1406
1407 static gboolean
1408 gst_rtp_session_request_remote_key_unit (GstRtpSession * rtpsession,
1409     guint32 ssrc, guint payload, gboolean all_headers, gint count)
1410 {
1411   GstCaps *caps;
1412
1413   caps = gst_rtp_session_get_caps_for_pt (rtpsession, payload);
1414
1415   if (caps) {
1416     const GstStructure *s = gst_caps_get_structure (caps, 0);
1417     gboolean pli;
1418     gboolean fir;
1419
1420     pli = gst_structure_has_field (s, "rtcp-fb-nack-pli");
1421     fir = gst_structure_has_field (s, "rtcp-fb-ccm-fir") && all_headers;
1422
1423     /* Google Talk uses FIR for repair, so send it even if we just want a
1424      * regular PLI */
1425     if (!pli &&
1426         gst_structure_has_field (s, "rtcp-fb-x-gstreamer-fir-as-repair"))
1427       fir = TRUE;
1428
1429     gst_caps_unref (caps);
1430
1431     if (pli || fir)
1432       return rtp_session_request_key_unit (rtpsession->priv->session, ssrc,
1433           gst_clock_get_time (rtpsession->priv->sysclock), fir, count);
1434   }
1435
1436   return FALSE;
1437 }
1438
1439 static gboolean
1440 gst_rtp_session_event_recv_rtp_src (GstPad * pad, GstObject * parent,
1441     GstEvent * event)
1442 {
1443   GstRtpSession *rtpsession;
1444   gboolean forward = TRUE;
1445   gboolean ret = TRUE;
1446   const GstStructure *s;
1447   guint32 ssrc;
1448   guint pt;
1449
1450   rtpsession = GST_RTP_SESSION (parent);
1451
1452   switch (GST_EVENT_TYPE (event)) {
1453     case GST_EVENT_CUSTOM_UPSTREAM:
1454       s = gst_event_get_structure (event);
1455       if (gst_structure_has_name (s, "GstForceKeyUnit") &&
1456           gst_structure_get_uint (s, "ssrc", &ssrc) &&
1457           gst_structure_get_uint (s, "payload", &pt)) {
1458         gboolean all_headers = FALSE;
1459         gint count = -1;
1460
1461         gst_structure_get_boolean (s, "all-headers", &all_headers);
1462         if (gst_structure_get_int (s, "count", &count) && count < 0)
1463           count += G_MAXINT;    /* Make sure count is positive if present */
1464         if (gst_rtp_session_request_remote_key_unit (rtpsession, ssrc, pt,
1465                 all_headers, count))
1466           forward = FALSE;
1467       }
1468       break;
1469     default:
1470       break;
1471   }
1472
1473   if (forward) {
1474     GstPad *recv_rtp_sink;
1475
1476     GST_RTP_SESSION_LOCK (rtpsession);
1477     if ((recv_rtp_sink = rtpsession->recv_rtp_sink))
1478       gst_object_ref (recv_rtp_sink);
1479     GST_RTP_SESSION_UNLOCK (rtpsession);
1480
1481     if (recv_rtp_sink) {
1482       ret = gst_pad_push_event (recv_rtp_sink, event);
1483       gst_object_unref (recv_rtp_sink);
1484     } else
1485       gst_event_unref (event);
1486   } else {
1487     gst_event_unref (event);
1488   }
1489
1490   return ret;
1491 }
1492
1493
1494 static GstIterator *
1495 gst_rtp_session_iterate_internal_links (GstPad * pad, GstObject * parent)
1496 {
1497   GstRtpSession *rtpsession;
1498   GstPad *otherpad = NULL;
1499   GstIterator *it = NULL;
1500
1501   rtpsession = GST_RTP_SESSION (parent);
1502
1503   GST_RTP_SESSION_LOCK (rtpsession);
1504   if (pad == rtpsession->recv_rtp_src) {
1505     otherpad = gst_object_ref (rtpsession->recv_rtp_sink);
1506   } else if (pad == rtpsession->recv_rtp_sink) {
1507     otherpad = gst_object_ref (rtpsession->recv_rtp_src);
1508   } else if (pad == rtpsession->send_rtp_src) {
1509     otherpad = gst_object_ref (rtpsession->send_rtp_sink);
1510   } else if (pad == rtpsession->send_rtp_sink) {
1511     otherpad = gst_object_ref (rtpsession->send_rtp_src);
1512   }
1513   GST_RTP_SESSION_UNLOCK (rtpsession);
1514
1515   if (otherpad) {
1516     GValue val = { 0, };
1517
1518     g_value_init (&val, GST_TYPE_PAD);
1519     g_value_set_object (&val, otherpad);
1520     it = gst_iterator_new_single (GST_TYPE_PAD, &val);
1521     g_value_unset (&val);
1522     gst_object_unref (otherpad);
1523   }
1524
1525   return it;
1526 }
1527
1528 static gboolean
1529 gst_rtp_session_sink_setcaps (GstPad * pad, GstRtpSession * rtpsession,
1530     GstCaps * caps)
1531 {
1532   GST_RTP_SESSION_LOCK (rtpsession);
1533   gst_rtp_session_cache_caps (rtpsession, caps);
1534   GST_RTP_SESSION_UNLOCK (rtpsession);
1535
1536   return TRUE;
1537 }
1538
1539 /* receive a packet from a sender, send it to the RTP session manager and
1540  * forward the packet on the rtp_src pad
1541  */
1542 static GstFlowReturn
1543 gst_rtp_session_chain_recv_rtp (GstPad * pad, GstObject * parent,
1544     GstBuffer * buffer)
1545 {
1546   GstRtpSession *rtpsession;
1547   GstRtpSessionPrivate *priv;
1548   GstFlowReturn ret;
1549   GstClockTime current_time, running_time;
1550   GstClockTime timestamp;
1551
1552   rtpsession = GST_RTP_SESSION (parent);
1553   priv = rtpsession->priv;
1554
1555   GST_LOG_OBJECT (rtpsession, "received RTP packet");
1556
1557   /* get NTP time when this packet was captured, this depends on the timestamp. */
1558   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1559   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1560     /* convert to running time using the segment values */
1561     running_time =
1562         gst_segment_to_running_time (&rtpsession->recv_rtp_seg, GST_FORMAT_TIME,
1563         timestamp);
1564   } else {
1565     get_current_times (rtpsession, &running_time, NULL);
1566   }
1567   current_time = gst_clock_get_time (priv->sysclock);
1568
1569   ret = rtp_session_process_rtp (priv->session, buffer, current_time,
1570       running_time);
1571   if (ret != GST_FLOW_OK)
1572     goto push_error;
1573
1574 done:
1575
1576   return ret;
1577
1578   /* ERRORS */
1579 push_error:
1580   {
1581     GST_DEBUG_OBJECT (rtpsession, "process returned %s",
1582         gst_flow_get_name (ret));
1583     goto done;
1584   }
1585 }
1586
1587 static gboolean
1588 gst_rtp_session_event_recv_rtcp_sink (GstPad * pad, GstObject * parent,
1589     GstEvent * event)
1590 {
1591   GstRtpSession *rtpsession;
1592   gboolean ret = FALSE;
1593
1594   rtpsession = GST_RTP_SESSION (parent);
1595
1596   GST_DEBUG_OBJECT (rtpsession, "received event %s",
1597       GST_EVENT_TYPE_NAME (event));
1598
1599   switch (GST_EVENT_TYPE (event)) {
1600     default:
1601       ret = gst_pad_push_event (rtpsession->sync_src, event);
1602       break;
1603   }
1604
1605   return ret;
1606 }
1607
1608 /* Receive an RTCP packet from a sender, send it to the RTP session manager and
1609  * forward the SR packets to the sync_src pad.
1610  */
1611 static GstFlowReturn
1612 gst_rtp_session_chain_recv_rtcp (GstPad * pad, GstObject * parent,
1613     GstBuffer * buffer)
1614 {
1615   GstRtpSession *rtpsession;
1616   GstRtpSessionPrivate *priv;
1617   GstClockTime current_time;
1618   guint64 ntpnstime;
1619
1620   rtpsession = GST_RTP_SESSION (parent);
1621   priv = rtpsession->priv;
1622
1623   GST_LOG_OBJECT (rtpsession, "received RTCP packet");
1624
1625   current_time = gst_clock_get_time (priv->sysclock);
1626   get_current_times (rtpsession, NULL, &ntpnstime);
1627
1628   rtp_session_process_rtcp (priv->session, buffer, current_time, ntpnstime);
1629
1630   return GST_FLOW_OK;           /* always return OK */
1631 }
1632
1633 static gboolean
1634 gst_rtp_session_query_send_rtcp_src (GstPad * pad, GstObject * parent,
1635     GstQuery * query)
1636 {
1637   GstRtpSession *rtpsession;
1638   gboolean ret = FALSE;
1639
1640   rtpsession = GST_RTP_SESSION (parent);
1641
1642   GST_DEBUG_OBJECT (rtpsession, "received QUERY %s",
1643       GST_QUERY_TYPE_NAME (query));
1644
1645   switch (GST_QUERY_TYPE (query)) {
1646     case GST_QUERY_LATENCY:
1647       ret = TRUE;
1648       /* use the defaults for the latency query. */
1649       gst_query_set_latency (query, FALSE, 0, -1);
1650       break;
1651     default:
1652       /* other queries simply fail for now */
1653       break;
1654   }
1655
1656   return ret;
1657 }
1658
1659 static gboolean
1660 gst_rtp_session_event_send_rtcp_src (GstPad * pad, GstObject * parent,
1661     GstEvent * event)
1662 {
1663   GstRtpSession *rtpsession;
1664   gboolean ret = TRUE;
1665
1666   rtpsession = GST_RTP_SESSION (parent);
1667   GST_DEBUG_OBJECT (rtpsession, "received EVENT %s",
1668       GST_EVENT_TYPE_NAME (event));
1669
1670   switch (GST_EVENT_TYPE (event)) {
1671     case GST_EVENT_SEEK:
1672     case GST_EVENT_LATENCY:
1673       gst_event_unref (event);
1674       ret = TRUE;
1675       break;
1676     default:
1677       /* other events simply fail for now */
1678       gst_event_unref (event);
1679       ret = FALSE;
1680       break;
1681   }
1682
1683   return ret;
1684 }
1685
1686
1687 static gboolean
1688 gst_rtp_session_event_send_rtp_sink (GstPad * pad, GstObject * parent,
1689     GstEvent * event)
1690 {
1691   GstRtpSession *rtpsession;
1692   gboolean ret = FALSE;
1693
1694   rtpsession = GST_RTP_SESSION (parent);
1695
1696   GST_DEBUG_OBJECT (rtpsession, "received EVENT %s",
1697       GST_EVENT_TYPE_NAME (event));
1698
1699   switch (GST_EVENT_TYPE (event)) {
1700     case GST_EVENT_CAPS:
1701     {
1702       GstCaps *caps;
1703
1704       /* process */
1705       gst_event_parse_caps (event, &caps);
1706       gst_rtp_session_setcaps_send_rtp (pad, rtpsession, caps);
1707       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1708       break;
1709     }
1710     case GST_EVENT_FLUSH_STOP:
1711       gst_segment_init (&rtpsession->send_rtp_seg, GST_FORMAT_UNDEFINED);
1712       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1713       break;
1714     case GST_EVENT_SEGMENT:{
1715       GstSegment *segment, in_segment;
1716
1717       segment = &rtpsession->send_rtp_seg;
1718
1719       /* the newsegment event is needed to convert the RTP timestamp to
1720        * running_time, which is needed to generate a mapping from RTP to NTP
1721        * timestamps in SR reports */
1722       gst_event_copy_segment (event, &in_segment);
1723       GST_DEBUG_OBJECT (rtpsession, "received segment %" GST_SEGMENT_FORMAT,
1724           &in_segment);
1725
1726       /* accept upstream */
1727       gst_segment_copy_into (&in_segment, segment);
1728
1729       /* push event forward */
1730       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1731       break;
1732     }
1733     case GST_EVENT_EOS:{
1734       GstClockTime current_time;
1735
1736       /* push downstream FIXME, we are not supposed to leave the session just
1737        * because we stop sending. */
1738       ret = gst_pad_push_event (rtpsession->send_rtp_src, event);
1739       current_time = gst_clock_get_time (rtpsession->priv->sysclock);
1740       GST_DEBUG_OBJECT (rtpsession, "scheduling BYE message");
1741       rtp_session_schedule_bye (rtpsession->priv->session, "End of stream",
1742           current_time);
1743       break;
1744     }
1745     default:{
1746       GstPad *send_rtp_src;
1747
1748       GST_RTP_SESSION_LOCK (rtpsession);
1749       if ((send_rtp_src = rtpsession->send_rtp_src))
1750         gst_object_ref (send_rtp_src);
1751       GST_RTP_SESSION_UNLOCK (rtpsession);
1752
1753       if (send_rtp_src) {
1754         ret = gst_pad_push_event (send_rtp_src, event);
1755         gst_object_unref (send_rtp_src);
1756       } else
1757         gst_event_unref (event);
1758
1759       break;
1760     }
1761   }
1762
1763   return ret;
1764 }
1765
1766 static gboolean
1767 gst_rtp_session_event_send_rtp_src (GstPad * pad, GstObject * parent,
1768     GstEvent * event)
1769 {
1770   GstRtpSession *rtpsession;
1771   gboolean ret = FALSE;
1772
1773   rtpsession = GST_RTP_SESSION (parent);
1774
1775   GST_DEBUG_OBJECT (rtpsession, "received EVENT %s",
1776       GST_EVENT_TYPE_NAME (event));
1777
1778   switch (GST_EVENT_TYPE (event)) {
1779     case GST_EVENT_LATENCY:
1780       /* save the latency, we need this to know when an RTP packet will be
1781        * rendered by the sink */
1782       gst_event_parse_latency (event, &rtpsession->priv->send_latency);
1783
1784       ret = gst_pad_event_default (pad, parent, event);
1785       break;
1786     default:
1787       ret = gst_pad_event_default (pad, parent, event);
1788       break;
1789   }
1790   return ret;
1791 }
1792
1793 static GstCaps *
1794 gst_rtp_session_getcaps_send_rtp (GstPad * pad, GstRtpSession * rtpsession,
1795     GstCaps * filter)
1796 {
1797   GstRtpSessionPrivate *priv;
1798   GstCaps *result;
1799   GstStructure *s1, *s2;
1800   guint ssrc;
1801
1802   priv = rtpsession->priv;
1803
1804   ssrc = rtp_session_get_internal_ssrc (priv->session);
1805
1806   /* we can basically accept anything but we prefer to receive packets with our
1807    * internal SSRC so that we don't have to patch it. Create a structure with
1808    * the SSRC and another one without. */
1809   s1 = gst_structure_new ("application/x-rtp", "ssrc", G_TYPE_UINT, ssrc, NULL);
1810   s2 = gst_structure_new_empty ("application/x-rtp");
1811
1812   result = gst_caps_new_full (s1, s2, NULL);
1813
1814   if (filter) {
1815     GstCaps *caps = result;
1816
1817     result = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
1818     gst_caps_unref (caps);
1819   }
1820
1821   GST_DEBUG_OBJECT (rtpsession, "getting caps %" GST_PTR_FORMAT, result);
1822
1823   return result;
1824 }
1825
1826 static gboolean
1827 gst_rtp_session_query_send_rtp (GstPad * pad, GstObject * parent,
1828     GstQuery * query)
1829 {
1830   gboolean res = FALSE;
1831   GstRtpSession *rtpsession;
1832
1833   rtpsession = GST_RTP_SESSION (parent);
1834
1835   switch (GST_QUERY_TYPE (query)) {
1836     case GST_QUERY_CAPS:
1837     {
1838       GstCaps *filter, *caps;
1839
1840       gst_query_parse_caps (query, &filter);
1841       caps = gst_rtp_session_getcaps_send_rtp (pad, rtpsession, filter);
1842       gst_query_set_caps_result (query, caps);
1843       gst_caps_unref (caps);
1844       res = TRUE;
1845       break;
1846     }
1847     default:
1848       res = gst_pad_query_default (pad, parent, query);
1849       break;
1850   }
1851
1852   return res;
1853 }
1854
1855 static gboolean
1856 gst_rtp_session_setcaps_send_rtp (GstPad * pad, GstRtpSession * rtpsession,
1857     GstCaps * caps)
1858 {
1859   GstRtpSessionPrivate *priv;
1860   GstStructure *s = gst_caps_get_structure (caps, 0);
1861   guint ssrc;
1862
1863   priv = rtpsession->priv;
1864
1865   if (gst_structure_get_uint (s, "ssrc", &ssrc)) {
1866     GST_DEBUG_OBJECT (rtpsession, "setting internal SSRC to %08x", ssrc);
1867     rtp_session_set_internal_ssrc (priv->session, ssrc);
1868   }
1869   rtp_session_update_send_caps (priv->session, caps);
1870
1871   return TRUE;
1872 }
1873
1874 /* Recieve an RTP packet or a list of packets to be send to the receivers,
1875  * send to RTP session manager and forward to send_rtp_src.
1876  */
1877 static GstFlowReturn
1878 gst_rtp_session_chain_send_rtp_common (GstRtpSession * rtpsession,
1879     gpointer data, gboolean is_list)
1880 {
1881   GstRtpSessionPrivate *priv;
1882   GstFlowReturn ret;
1883   GstClockTime timestamp, running_time;
1884   GstClockTime current_time;
1885
1886   priv = rtpsession->priv;
1887
1888   GST_LOG_OBJECT (rtpsession, "received RTP %s", is_list ? "list" : "packet");
1889
1890   /* get NTP time when this packet was captured, this depends on the timestamp. */
1891   if (is_list) {
1892     GstBuffer *buffer = NULL;
1893
1894     /* All groups in an list have the same timestamp.
1895      * So, just take it from the first group. */
1896     buffer = gst_buffer_list_get (GST_BUFFER_LIST_CAST (data), 0);
1897     if (buffer)
1898       timestamp = GST_BUFFER_TIMESTAMP (buffer);
1899     else
1900       timestamp = -1;
1901   } else {
1902     timestamp = GST_BUFFER_TIMESTAMP (GST_BUFFER_CAST (data));
1903   }
1904
1905   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1906     /* convert to running time using the segment start value. */
1907     running_time =
1908         gst_segment_to_running_time (&rtpsession->send_rtp_seg, GST_FORMAT_TIME,
1909         timestamp);
1910     running_time += priv->send_latency;
1911   } else {
1912     /* no timestamp. */
1913     running_time = -1;
1914   }
1915
1916   current_time = gst_clock_get_time (priv->sysclock);
1917   ret = rtp_session_send_rtp (priv->session, data, is_list, current_time,
1918       running_time);
1919   if (ret != GST_FLOW_OK)
1920     goto push_error;
1921
1922 done:
1923
1924   return ret;
1925
1926   /* ERRORS */
1927 push_error:
1928   {
1929     GST_DEBUG_OBJECT (rtpsession, "process returned %s",
1930         gst_flow_get_name (ret));
1931     goto done;
1932   }
1933 }
1934
1935 static GstFlowReturn
1936 gst_rtp_session_chain_send_rtp (GstPad * pad, GstObject * parent,
1937     GstBuffer * buffer)
1938 {
1939   GstRtpSession *rtpsession = GST_RTP_SESSION (parent);
1940
1941   return gst_rtp_session_chain_send_rtp_common (rtpsession, buffer, FALSE);
1942 }
1943
1944 static GstFlowReturn
1945 gst_rtp_session_chain_send_rtp_list (GstPad * pad, GstObject * parent,
1946     GstBufferList * list)
1947 {
1948   GstRtpSession *rtpsession = GST_RTP_SESSION (parent);
1949
1950   return gst_rtp_session_chain_send_rtp_common (rtpsession, list, TRUE);
1951 }
1952
1953 /* Create sinkpad to receive RTP packets from senders. This will also create a
1954  * srcpad for the RTP packets.
1955  */
1956 static GstPad *
1957 create_recv_rtp_sink (GstRtpSession * rtpsession)
1958 {
1959   GST_DEBUG_OBJECT (rtpsession, "creating RTP sink pad");
1960
1961   rtpsession->recv_rtp_sink =
1962       gst_pad_new_from_static_template (&rtpsession_recv_rtp_sink_template,
1963       "recv_rtp_sink");
1964   gst_pad_set_chain_function (rtpsession->recv_rtp_sink,
1965       gst_rtp_session_chain_recv_rtp);
1966   gst_pad_set_event_function (rtpsession->recv_rtp_sink,
1967       gst_rtp_session_event_recv_rtp_sink);
1968   gst_pad_set_iterate_internal_links_function (rtpsession->recv_rtp_sink,
1969       gst_rtp_session_iterate_internal_links);
1970   gst_pad_set_active (rtpsession->recv_rtp_sink, TRUE);
1971   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
1972       rtpsession->recv_rtp_sink);
1973
1974   GST_DEBUG_OBJECT (rtpsession, "creating RTP src pad");
1975   rtpsession->recv_rtp_src =
1976       gst_pad_new_from_static_template (&rtpsession_recv_rtp_src_template,
1977       "recv_rtp_src");
1978   gst_pad_set_event_function (rtpsession->recv_rtp_src,
1979       gst_rtp_session_event_recv_rtp_src);
1980   gst_pad_set_iterate_internal_links_function (rtpsession->recv_rtp_src,
1981       gst_rtp_session_iterate_internal_links);
1982   gst_pad_use_fixed_caps (rtpsession->recv_rtp_src);
1983   gst_pad_set_active (rtpsession->recv_rtp_src, TRUE);
1984   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->recv_rtp_src);
1985
1986   return rtpsession->recv_rtp_sink;
1987 }
1988
1989 /* Remove sinkpad to receive RTP packets from senders. This will also remove
1990  * the srcpad for the RTP packets.
1991  */
1992 static void
1993 remove_recv_rtp_sink (GstRtpSession * rtpsession)
1994 {
1995   GST_DEBUG_OBJECT (rtpsession, "removing RTP sink pad");
1996
1997   /* deactivate from source to sink */
1998   gst_pad_set_active (rtpsession->recv_rtp_src, FALSE);
1999   gst_pad_set_active (rtpsession->recv_rtp_sink, FALSE);
2000
2001   /* remove pads */
2002   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2003       rtpsession->recv_rtp_sink);
2004   rtpsession->recv_rtp_sink = NULL;
2005
2006   GST_DEBUG_OBJECT (rtpsession, "removing RTP src pad");
2007   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2008       rtpsession->recv_rtp_src);
2009   rtpsession->recv_rtp_src = NULL;
2010 }
2011
2012 /* Create a sinkpad to receive RTCP messages from senders, this will also create a
2013  * sync_src pad for the SR packets.
2014  */
2015 static GstPad *
2016 create_recv_rtcp_sink (GstRtpSession * rtpsession)
2017 {
2018   GST_DEBUG_OBJECT (rtpsession, "creating RTCP sink pad");
2019
2020   rtpsession->recv_rtcp_sink =
2021       gst_pad_new_from_static_template (&rtpsession_recv_rtcp_sink_template,
2022       "recv_rtcp_sink");
2023   gst_pad_set_chain_function (rtpsession->recv_rtcp_sink,
2024       gst_rtp_session_chain_recv_rtcp);
2025   gst_pad_set_event_function (rtpsession->recv_rtcp_sink,
2026       gst_rtp_session_event_recv_rtcp_sink);
2027   gst_pad_set_iterate_internal_links_function (rtpsession->recv_rtcp_sink,
2028       gst_rtp_session_iterate_internal_links);
2029   gst_pad_set_active (rtpsession->recv_rtcp_sink, TRUE);
2030   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
2031       rtpsession->recv_rtcp_sink);
2032
2033   GST_DEBUG_OBJECT (rtpsession, "creating sync src pad");
2034   rtpsession->sync_src =
2035       gst_pad_new_from_static_template (&rtpsession_sync_src_template,
2036       "sync_src");
2037   gst_pad_set_iterate_internal_links_function (rtpsession->sync_src,
2038       gst_rtp_session_iterate_internal_links);
2039   gst_pad_use_fixed_caps (rtpsession->sync_src);
2040   gst_pad_set_active (rtpsession->sync_src, TRUE);
2041   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->sync_src);
2042
2043   return rtpsession->recv_rtcp_sink;
2044 }
2045
2046 static void
2047 remove_recv_rtcp_sink (GstRtpSession * rtpsession)
2048 {
2049   GST_DEBUG_OBJECT (rtpsession, "removing RTCP sink pad");
2050
2051   gst_pad_set_active (rtpsession->sync_src, FALSE);
2052   gst_pad_set_active (rtpsession->recv_rtcp_sink, FALSE);
2053
2054   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2055       rtpsession->recv_rtcp_sink);
2056   rtpsession->recv_rtcp_sink = NULL;
2057
2058   GST_DEBUG_OBJECT (rtpsession, "removing sync src pad");
2059   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->sync_src);
2060   rtpsession->sync_src = NULL;
2061 }
2062
2063 /* Create a sinkpad to receive RTP packets for receivers. This will also create a
2064  * send_rtp_src pad.
2065  */
2066 static GstPad *
2067 create_send_rtp_sink (GstRtpSession * rtpsession)
2068 {
2069   GST_DEBUG_OBJECT (rtpsession, "creating pad");
2070
2071   rtpsession->send_rtp_sink =
2072       gst_pad_new_from_static_template (&rtpsession_send_rtp_sink_template,
2073       "send_rtp_sink");
2074   gst_pad_set_chain_function (rtpsession->send_rtp_sink,
2075       gst_rtp_session_chain_send_rtp);
2076   gst_pad_set_chain_list_function (rtpsession->send_rtp_sink,
2077       gst_rtp_session_chain_send_rtp_list);
2078   gst_pad_set_query_function (rtpsession->send_rtp_sink,
2079       gst_rtp_session_query_send_rtp);
2080   gst_pad_set_event_function (rtpsession->send_rtp_sink,
2081       gst_rtp_session_event_send_rtp_sink);
2082   gst_pad_set_iterate_internal_links_function (rtpsession->send_rtp_sink,
2083       gst_rtp_session_iterate_internal_links);
2084   gst_pad_set_active (rtpsession->send_rtp_sink, TRUE);
2085   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
2086       rtpsession->send_rtp_sink);
2087
2088   rtpsession->send_rtp_src =
2089       gst_pad_new_from_static_template (&rtpsession_send_rtp_src_template,
2090       "send_rtp_src");
2091   gst_pad_set_iterate_internal_links_function (rtpsession->send_rtp_src,
2092       gst_rtp_session_iterate_internal_links);
2093   gst_pad_set_event_function (rtpsession->send_rtp_src,
2094       gst_rtp_session_event_send_rtp_src);
2095   gst_pad_set_active (rtpsession->send_rtp_src, TRUE);
2096   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession), rtpsession->send_rtp_src);
2097
2098   return rtpsession->send_rtp_sink;
2099 }
2100
2101 static void
2102 remove_send_rtp_sink (GstRtpSession * rtpsession)
2103 {
2104   GST_DEBUG_OBJECT (rtpsession, "removing pad");
2105
2106   gst_pad_set_active (rtpsession->send_rtp_src, FALSE);
2107   gst_pad_set_active (rtpsession->send_rtp_sink, FALSE);
2108
2109   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2110       rtpsession->send_rtp_sink);
2111   rtpsession->send_rtp_sink = NULL;
2112
2113   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2114       rtpsession->send_rtp_src);
2115   rtpsession->send_rtp_src = NULL;
2116 }
2117
2118 /* Create a srcpad with the RTCP packets to send out.
2119  * This pad will be driven by the RTP session manager when it wants to send out
2120  * RTCP packets.
2121  */
2122 static GstPad *
2123 create_send_rtcp_src (GstRtpSession * rtpsession)
2124 {
2125   GST_DEBUG_OBJECT (rtpsession, "creating pad");
2126
2127   rtpsession->send_rtcp_src =
2128       gst_pad_new_from_static_template (&rtpsession_send_rtcp_src_template,
2129       "send_rtcp_src");
2130   gst_pad_use_fixed_caps (rtpsession->send_rtcp_src);
2131   gst_pad_set_active (rtpsession->send_rtcp_src, TRUE);
2132   gst_pad_set_iterate_internal_links_function (rtpsession->send_rtcp_src,
2133       gst_rtp_session_iterate_internal_links);
2134   gst_pad_set_query_function (rtpsession->send_rtcp_src,
2135       gst_rtp_session_query_send_rtcp_src);
2136   gst_pad_set_event_function (rtpsession->send_rtcp_src,
2137       gst_rtp_session_event_send_rtcp_src);
2138   gst_element_add_pad (GST_ELEMENT_CAST (rtpsession),
2139       rtpsession->send_rtcp_src);
2140
2141   return rtpsession->send_rtcp_src;
2142 }
2143
2144 static void
2145 remove_send_rtcp_src (GstRtpSession * rtpsession)
2146 {
2147   GST_DEBUG_OBJECT (rtpsession, "removing pad");
2148
2149   gst_pad_set_active (rtpsession->send_rtcp_src, FALSE);
2150
2151   gst_element_remove_pad (GST_ELEMENT_CAST (rtpsession),
2152       rtpsession->send_rtcp_src);
2153   rtpsession->send_rtcp_src = NULL;
2154 }
2155
2156 static GstPad *
2157 gst_rtp_session_request_new_pad (GstElement * element,
2158     GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
2159 {
2160   GstRtpSession *rtpsession;
2161   GstElementClass *klass;
2162   GstPad *result;
2163
2164   g_return_val_if_fail (templ != NULL, NULL);
2165   g_return_val_if_fail (GST_IS_RTP_SESSION (element), NULL);
2166
2167   rtpsession = GST_RTP_SESSION (element);
2168   klass = GST_ELEMENT_GET_CLASS (element);
2169
2170   GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
2171
2172   GST_RTP_SESSION_LOCK (rtpsession);
2173
2174   /* figure out the template */
2175   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink")) {
2176     if (rtpsession->recv_rtp_sink != NULL)
2177       goto exists;
2178
2179     result = create_recv_rtp_sink (rtpsession);
2180   } else if (templ == gst_element_class_get_pad_template (klass,
2181           "recv_rtcp_sink")) {
2182     if (rtpsession->recv_rtcp_sink != NULL)
2183       goto exists;
2184
2185     result = create_recv_rtcp_sink (rtpsession);
2186   } else if (templ == gst_element_class_get_pad_template (klass,
2187           "send_rtp_sink")) {
2188     if (rtpsession->send_rtp_sink != NULL)
2189       goto exists;
2190
2191     result = create_send_rtp_sink (rtpsession);
2192   } else if (templ == gst_element_class_get_pad_template (klass,
2193           "send_rtcp_src")) {
2194     if (rtpsession->send_rtcp_src != NULL)
2195       goto exists;
2196
2197     result = create_send_rtcp_src (rtpsession);
2198   } else
2199     goto wrong_template;
2200
2201   GST_RTP_SESSION_UNLOCK (rtpsession);
2202
2203   return result;
2204
2205   /* ERRORS */
2206 wrong_template:
2207   {
2208     GST_RTP_SESSION_UNLOCK (rtpsession);
2209     g_warning ("gstrtpsession: this is not our template");
2210     return NULL;
2211   }
2212 exists:
2213   {
2214     GST_RTP_SESSION_UNLOCK (rtpsession);
2215     g_warning ("gstrtpsession: pad already requested");
2216     return NULL;
2217   }
2218 }
2219
2220 static void
2221 gst_rtp_session_release_pad (GstElement * element, GstPad * pad)
2222 {
2223   GstRtpSession *rtpsession;
2224
2225   g_return_if_fail (GST_IS_RTP_SESSION (element));
2226   g_return_if_fail (GST_IS_PAD (pad));
2227
2228   rtpsession = GST_RTP_SESSION (element);
2229
2230   GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2231
2232   GST_RTP_SESSION_LOCK (rtpsession);
2233
2234   if (rtpsession->recv_rtp_sink == pad) {
2235     remove_recv_rtp_sink (rtpsession);
2236   } else if (rtpsession->recv_rtcp_sink == pad) {
2237     remove_recv_rtcp_sink (rtpsession);
2238   } else if (rtpsession->send_rtp_sink == pad) {
2239     remove_send_rtp_sink (rtpsession);
2240   } else if (rtpsession->send_rtcp_src == pad) {
2241     remove_send_rtcp_src (rtpsession);
2242   } else
2243     goto wrong_pad;
2244
2245   GST_RTP_SESSION_UNLOCK (rtpsession);
2246
2247   return;
2248
2249   /* ERRORS */
2250 wrong_pad:
2251   {
2252     GST_RTP_SESSION_UNLOCK (rtpsession);
2253     g_warning ("gstrtpsession: asked to release an unknown pad");
2254     return;
2255   }
2256 }
2257
2258 static void
2259 gst_rtp_session_request_key_unit (RTPSession * sess,
2260     gboolean all_headers, gpointer user_data)
2261 {
2262   GstRtpSession *rtpsession = GST_RTP_SESSION (user_data);
2263   GstEvent *event;
2264   GstPad *send_rtp_sink;
2265
2266   GST_RTP_SESSION_LOCK (rtpsession);
2267   if ((send_rtp_sink = rtpsession->send_rtp_sink))
2268     gst_object_ref (send_rtp_sink);
2269   GST_RTP_SESSION_UNLOCK (rtpsession);
2270
2271   if (send_rtp_sink) {
2272     event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
2273         gst_structure_new ("GstForceKeyUnit",
2274             "all-headers", G_TYPE_BOOLEAN, all_headers, NULL));
2275     gst_pad_push_event (send_rtp_sink, event);
2276     gst_object_unref (send_rtp_sink);
2277   }
2278 }
2279
2280 static GstClockTime
2281 gst_rtp_session_request_time (RTPSession * session, gpointer user_data)
2282 {
2283   GstRtpSession *rtpsession = GST_RTP_SESSION (user_data);
2284
2285   return gst_clock_get_time (rtpsession->priv->sysclock);
2286 }