gst/rtpmanager/: Also keep track of the first buffer timestamp together with the...
[platform/upstream/gstreamer.git] / gst / rtpmanager / gstrtpbin.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., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-gstrtpbin
22  * @short_description: handle media from one RTP bin
23  * @see_also: gstrtpjitterbuffer, gstrtpsession, gstrtpptdemux, gstrtpssrcdemux
24  *
25  * <refsect2>
26  * <para>
27  * RTP bin combines the functions of gstrtpsession, gstrtpssrcdemux, gstrtpjitterbuffer
28  * and gstrtpptdemux in one element. It allows for multiple RTP sessions that will
29  * be synchronized together using RTCP SR packets.
30  * </para>
31  * <para>
32  * gstrtpbin is configured with a number of request pads that define the
33  * functionality that is activated, similar to the gstrtpsession element.
34  * </para>
35  * <para>
36  * To use gstrtpbin as an RTP receiver, request a recv_rtp_sink_%%d pad. The session
37  * number must be specified in the pad name. 
38  * Data received on the recv_rtp_sink_%%d pad will be processed in the gstrtpsession
39  * manager and after being validated forwarded on gstrtpssrcdemuxer element. Each
40  * RTP stream is demuxed based on the SSRC and send to a gstrtpjitterbuffer. After
41  * the packets are released from the jitterbuffer, they will be forwarded to a
42  * gstrtpptdemuxer element. The gstrtpptdemuxer element will demux the packets based
43  * on the payload type and will create a unique pad recv_rtp_src_%%d_%%d_%%d on
44  * gstrtpbin with the session number, SSRC and payload type respectively as the pad
45  * name.
46  * </para>
47  * <para>
48  * To also use gstrtpbin as an RTCP receiver, request a recv_rtcp_sink_%%d pad. The
49  * session number must be specified in the pad name.
50  * </para>
51  * <para>
52  * If you want the session manager to generate and send RTCP packets, request
53  * the send_rtcp_src_%%d pad with the session number in the pad name. Packet pushed
54  * on this pad contain SR/RR RTCP reports that should be sent to all participants
55  * in the session.
56  * </para>
57  * <para>
58  * To use gstrtpbin as a sender, request a send_rtp_sink_%%d pad, which will
59  * automatically create a send_rtp_src_%%d pad. If the session number is not provided,
60  * the pad from the lowest available session will be returned. The session manager will modify the
61  * SSRC in the RTP packets to its own SSRC and wil forward the packets on the
62  * send_rtp_src_%%d pad after updating its internal state.
63  * </para>
64  * <para>
65  * The session manager needs the clock-rate of the payload types it is handling
66  * and will signal the GstRtpSession::request-pt-map signal when it needs such a
67  * mapping. One can clear the cached values with the GstRtpSession::clear-pt-map
68  * signal.
69  * </para>
70  * <title>Example pipelines</title>
71  * <para>
72  * <programlisting>
73  * gst-launch udpsrc port=5000 caps="application/x-rtp, ..." ! .recv_rtp_sink_0 \
74  *     gstrtpbin ! rtptheoradepay ! theoradec ! xvimagesink
75  * </programlisting>
76  * Receive RTP data from port 5000 and send to the session 0 in gstrtpbin.
77  * </para>
78  * <para>
79  * <programlisting>
80  * gst-launch gstrtpbin name=rtpbin \
81  *         v4l2src ! ffmpegcolorspace ! ffenc_h263 ! rtph263ppay ! rtpbin.send_rtp_sink_0 \
82  *                   rtpbin.send_rtp_src_0 ! udpsink port=5000                            \
83  *                   rtpbin.send_rtcp_src_0 ! udpsink port=5001 sync=false async=false    \
84  *                   udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0                           \
85  *         audiotestsrc ! amrnbenc ! rtpamrpay ! rtpbin.send_rtp_sink_1                   \
86  *                   rtpbin.send_rtp_src_1 ! udpsink port=5002                            \
87  *                   rtpbin.send_rtcp_src_1 ! udpsink port=5003 sync=false async=false    \
88  *                   udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1
89  * </programlisting>
90  * Encode and payload H263 video captured from a v4l2src. Encode and payload AMR
91  * audio generated from audiotestsrc. The video is sent to session 0 in rtpbin
92  * and the audio is sent to session 1. Video packets are sent on UDP port 5000
93  * and audio packets on port 5002. The video RTCP packets for session 0 are sent
94  * on port 5001 and the audio RTCP packets for session 0 are sent on port 5003.
95  * RTCP packets for session 0 are received on port 5005 and RTCP for session 1
96  * is received on port 5007. Since RTCP packets from the sender should be sent
97  * as soon as possible and do not participate in preroll, sync=false and 
98  * async=false is configured on udpsink
99  * </para>
100  * <para>
101  * <programlisting>
102  *  gst-launch -v gstrtpbin name=rtpbin                                          \
103  *     udpsrc caps="application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)H263-1998" \
104  *             port=5000 ! rtpbin.recv_rtp_sink_0                                \
105  *         rtpbin. ! rtph263pdepay ! ffdec_h263 ! xvimagesink                    \
106  *      udpsrc port=5001 ! rtpbin.recv_rtcp_sink_0                               \
107  *      rtpbin.send_rtcp_src_0 ! udpsink port=5005 sync=false async=false        \
108  *     udpsrc caps="application/x-rtp,media=(string)audio,clock-rate=(int)8000,encoding-name=(string)AMR,encoding-params=(string)1,octet-align=(string)1" \
109  *             port=5002 ! rtpbin.recv_rtp_sink_1                                \
110  *         rtpbin. ! rtpamrdepay ! amrnbdec ! alsasink                           \
111  *      udpsrc port=5003 ! rtpbin.recv_rtcp_sink_1                               \
112  *      rtpbin.send_rtcp_src_1 ! udpsink port=5007 sync=false async=false
113  * </programlisting>
114  * Receive H263 on port 5000, send it through rtpbin in session 0, depayload,
115  * decode and display the video.
116  * Receive AMR on port 5002, send it through rtpbin in session 1, depayload,
117  * decode and play the audio.
118  * Receive server RTCP packets for session 0 on port 5001 and RTCP packets for
119  * session 1 on port 5003. These packets will be used for session management and
120  * synchronisation.
121  * Send RTCP reports for session 0 on port 5005 and RTCP reports for session 1
122  * on port 5007.
123  * </para>
124  * </refsect2>
125  *
126  * Last reviewed on 2007-08-30 (0.10.6)
127  */
128
129 #ifdef HAVE_CONFIG_H
130 #include "config.h"
131 #endif
132 #include <string.h>
133
134 #include <gst/rtp/gstrtpbuffer.h>
135 #include <gst/rtp/gstrtcpbuffer.h>
136
137 #include "gstrtpbin-marshal.h"
138 #include "gstrtpbin.h"
139
140 GST_DEBUG_CATEGORY_STATIC (gst_rtp_bin_debug);
141 #define GST_CAT_DEFAULT gst_rtp_bin_debug
142
143 /* elementfactory information */
144 static const GstElementDetails rtpbin_details = GST_ELEMENT_DETAILS ("RTP Bin",
145     "Filter/Network/RTP",
146     "Implement an RTP bin",
147     "Wim Taymans <wim.taymans@gmail.com>");
148
149 /* sink pads */
150 static GstStaticPadTemplate rtpbin_recv_rtp_sink_template =
151 GST_STATIC_PAD_TEMPLATE ("recv_rtp_sink_%d",
152     GST_PAD_SINK,
153     GST_PAD_REQUEST,
154     GST_STATIC_CAPS ("application/x-rtp")
155     );
156
157 static GstStaticPadTemplate rtpbin_recv_rtcp_sink_template =
158 GST_STATIC_PAD_TEMPLATE ("recv_rtcp_sink_%d",
159     GST_PAD_SINK,
160     GST_PAD_REQUEST,
161     GST_STATIC_CAPS ("application/x-rtcp")
162     );
163
164 static GstStaticPadTemplate rtpbin_send_rtp_sink_template =
165 GST_STATIC_PAD_TEMPLATE ("send_rtp_sink_%d",
166     GST_PAD_SINK,
167     GST_PAD_REQUEST,
168     GST_STATIC_CAPS ("application/x-rtp")
169     );
170
171 /* src pads */
172 static GstStaticPadTemplate rtpbin_recv_rtp_src_template =
173 GST_STATIC_PAD_TEMPLATE ("recv_rtp_src_%d_%d_%d",
174     GST_PAD_SRC,
175     GST_PAD_SOMETIMES,
176     GST_STATIC_CAPS ("application/x-rtp")
177     );
178
179 static GstStaticPadTemplate rtpbin_send_rtcp_src_template =
180 GST_STATIC_PAD_TEMPLATE ("send_rtcp_src_%d",
181     GST_PAD_SRC,
182     GST_PAD_REQUEST,
183     GST_STATIC_CAPS ("application/x-rtcp")
184     );
185
186 static GstStaticPadTemplate rtpbin_send_rtp_src_template =
187 GST_STATIC_PAD_TEMPLATE ("send_rtp_src_%d",
188     GST_PAD_SRC,
189     GST_PAD_SOMETIMES,
190     GST_STATIC_CAPS ("application/x-rtp")
191     );
192
193 /* padtemplate for the internal pad */
194 static GstStaticPadTemplate rtpbin_sync_sink_template =
195 GST_STATIC_PAD_TEMPLATE ("sink_%d",
196     GST_PAD_SINK,
197     GST_PAD_SOMETIMES,
198     GST_STATIC_CAPS ("application/x-rtcp")
199     );
200
201 #define GST_RTP_BIN_GET_PRIVATE(obj)  \
202    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTP_BIN, GstRtpBinPrivate))
203
204 #define GST_RTP_BIN_LOCK(bin)   g_mutex_lock ((bin)->priv->bin_lock)
205 #define GST_RTP_BIN_UNLOCK(bin) g_mutex_unlock ((bin)->priv->bin_lock)
206
207 struct _GstRtpBinPrivate
208 {
209   GMutex *bin_lock;
210
211   GstClockTime ntp_ns_base;
212 };
213
214 /* signals and args */
215 enum
216 {
217   SIGNAL_REQUEST_PT_MAP,
218   SIGNAL_CLEAR_PT_MAP,
219
220   SIGNAL_ON_NEW_SSRC,
221   SIGNAL_ON_SSRC_COLLISION,
222   SIGNAL_ON_SSRC_VALIDATED,
223   SIGNAL_ON_SSRC_ACTIVE,
224   SIGNAL_ON_SSRC_SDES,
225   SIGNAL_ON_BYE_SSRC,
226   SIGNAL_ON_BYE_TIMEOUT,
227   SIGNAL_ON_TIMEOUT,
228   LAST_SIGNAL
229 };
230
231 #define DEFAULT_LATENCY_MS      200
232 #define DEFAULT_SDES_CNAME           NULL
233 #define DEFAULT_SDES_NAME            NULL
234 #define DEFAULT_SDES_EMAIL           NULL
235 #define DEFAULT_SDES_PHONE           NULL
236 #define DEFAULT_SDES_LOCATION        NULL
237 #define DEFAULT_SDES_TOOL            NULL
238 #define DEFAULT_SDES_NOTE            NULL
239
240 enum
241 {
242   PROP_0,
243   PROP_LATENCY,
244   PROP_SDES_CNAME,
245   PROP_SDES_NAME,
246   PROP_SDES_EMAIL,
247   PROP_SDES_PHONE,
248   PROP_SDES_LOCATION,
249   PROP_SDES_TOOL,
250   PROP_SDES_NOTE,
251   PROP_LAST
252 };
253
254 /* helper objects */
255 typedef struct _GstRtpBinSession GstRtpBinSession;
256 typedef struct _GstRtpBinStream GstRtpBinStream;
257 typedef struct _GstRtpBinClient GstRtpBinClient;
258
259 static guint gst_rtp_bin_signals[LAST_SIGNAL] = { 0 };
260
261 static GstCaps *pt_map_requested (GstElement * element, guint pt,
262     GstRtpBinSession * session);
263 static const gchar *sdes_type_to_name (GstRTCPSDESType type);
264 static void gst_rtp_bin_set_sdes_string (GstRtpBin * bin,
265     GstRTCPSDESType type, const gchar * data);
266
267 static void free_stream (GstRtpBinStream * stream);
268
269 /* Manages the RTP stream for one SSRC.
270  *
271  * We pipe the stream (comming from the SSRC demuxer) into a jitterbuffer.
272  * If we see an SDES RTCP packet that links multiple SSRCs together based on a
273  * common CNAME, we create a GstRtpBinClient structure to group the SSRCs
274  * together (see below).
275  */
276 struct _GstRtpBinStream
277 {
278   /* the SSRC of this stream */
279   guint32 ssrc;
280
281   /* parent bin */
282   GstRtpBin *bin;
283
284   /* the session this SSRC belongs to */
285   GstRtpBinSession *session;
286
287   /* the jitterbuffer of the SSRC */
288   GstElement *buffer;
289
290   /* the PT demuxer of the SSRC */
291   GstElement *demux;
292   gulong demux_newpad_sig;
293   gulong demux_ptreq_sig;
294   gulong demux_pt_change_sig;
295
296   /* the internal pad we use to get RTCP sync messages */
297   GstPad *sync_pad;
298   gboolean have_sync;
299   guint64 last_unix;
300   guint64 last_extrtptime;
301
302   /* mapping to local RTP and NTP time */
303   guint64 local_rtp;
304   guint64 local_unix;
305   gint64 unix_delta;
306
307   /* for lip-sync */
308   guint64 clock_base;
309   guint64 clock_base_time;
310   gint clock_rate;
311   gint64 ts_offset;
312   gint64 prev_ts_offset;
313   gint last_pt;
314 };
315
316 #define GST_RTP_SESSION_LOCK(sess)   g_mutex_lock ((sess)->lock)
317 #define GST_RTP_SESSION_UNLOCK(sess) g_mutex_unlock ((sess)->lock)
318
319 /* Manages the receiving end of the packets.
320  *
321  * There is one such structure for each RTP session (audio/video/...).
322  * We get the RTP/RTCP packets and stuff them into the session manager. From
323  * there they are pushed into an SSRC demuxer that splits the stream based on
324  * SSRC. Each of the SSRC streams go into their own jitterbuffer (managed with
325  * the GstRtpBinStream above).
326  */
327 struct _GstRtpBinSession
328 {
329   /* session id */
330   gint id;
331   /* the parent bin */
332   GstRtpBin *bin;
333   /* the session element */
334   GstElement *session;
335   /* the SSRC demuxer */
336   GstElement *demux;
337   gulong demux_newpad_sig;
338
339   GMutex *lock;
340
341   /* list of GstRtpBinStream */
342   GSList *streams;
343
344   /* mapping of payload type to caps */
345   GHashTable *ptmap;
346
347   /* the pads of the session */
348   GstPad *recv_rtp_sink;
349   GstPad *recv_rtp_src;
350   GstPad *recv_rtcp_sink;
351   GstPad *sync_src;
352   GstPad *send_rtp_sink;
353   GstPad *send_rtp_src;
354   GstPad *send_rtcp_src;
355 };
356
357 /* Manages the RTP streams that come from one client and should therefore be
358  * synchronized.
359  */
360 struct _GstRtpBinClient
361 {
362   /* the common CNAME for the streams */
363   gchar *cname;
364   guint cname_len;
365
366   /* the streams */
367   guint nstreams;
368   GSList *streams;
369
370   gint64 min_delta;
371 };
372
373 /* find a session with the given id. Must be called with RTP_BIN_LOCK */
374 static GstRtpBinSession *
375 find_session_by_id (GstRtpBin * rtpbin, gint id)
376 {
377   GSList *walk;
378
379   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
380     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
381
382     if (sess->id == id)
383       return sess;
384   }
385   return NULL;
386 }
387
388 static void
389 on_new_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
390 {
391   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC], 0,
392       sess->id, ssrc);
393 }
394
395 static void
396 on_ssrc_collision (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
397 {
398   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION], 0,
399       sess->id, ssrc);
400 }
401
402 static void
403 on_ssrc_validated (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
404 {
405   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
406       sess->id, ssrc);
407 }
408
409 static void
410 on_ssrc_active (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
411 {
412   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_ACTIVE], 0,
413       sess->id, ssrc);
414 }
415
416 static void
417 on_ssrc_sdes (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
418 {
419   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_SDES], 0,
420       sess->id, ssrc);
421 }
422
423 static void
424 on_bye_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
425 {
426   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC], 0,
427       sess->id, ssrc);
428 }
429
430 static void
431 on_bye_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
432 {
433   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT], 0,
434       sess->id, ssrc);
435 }
436
437 static void
438 on_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
439 {
440   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT], 0,
441       sess->id, ssrc);
442 }
443
444 /* create a session with the given id.  Must be called with RTP_BIN_LOCK */
445 static GstRtpBinSession *
446 create_session (GstRtpBin * rtpbin, gint id)
447 {
448   GstRtpBinSession *sess;
449   GstElement *session, *demux;
450   gint i;
451
452   if (!(session = gst_element_factory_make ("gstrtpsession", NULL)))
453     goto no_session;
454
455   if (!(demux = gst_element_factory_make ("gstrtpssrcdemux", NULL)))
456     goto no_demux;
457
458   sess = g_new0 (GstRtpBinSession, 1);
459   sess->lock = g_mutex_new ();
460   sess->id = id;
461   sess->bin = rtpbin;
462   sess->session = session;
463   sess->demux = demux;
464   sess->ptmap = g_hash_table_new_full (NULL, NULL, NULL,
465       (GDestroyNotify) gst_caps_unref);
466   rtpbin->sessions = g_slist_prepend (rtpbin->sessions, sess);
467
468   /* set NTP base or new session */
469   g_object_set (session, "ntp-ns-base", rtpbin->priv->ntp_ns_base, NULL);
470   /* configure SDES items */
471   GST_OBJECT_LOCK (rtpbin);
472   for (i = GST_RTCP_SDES_CNAME; i < GST_RTCP_SDES_PRIV; i++) {
473     g_object_set (session, sdes_type_to_name (i), rtpbin->sdes[i], NULL);
474   }
475   GST_OBJECT_UNLOCK (rtpbin);
476
477   /* provide clock_rate to the session manager when needed */
478   g_signal_connect (session, "request-pt-map",
479       (GCallback) pt_map_requested, sess);
480
481   g_signal_connect (sess->session, "on-new-ssrc",
482       (GCallback) on_new_ssrc, sess);
483   g_signal_connect (sess->session, "on-ssrc-collision",
484       (GCallback) on_ssrc_collision, sess);
485   g_signal_connect (sess->session, "on-ssrc-validated",
486       (GCallback) on_ssrc_validated, sess);
487   g_signal_connect (sess->session, "on-ssrc-active",
488       (GCallback) on_ssrc_active, sess);
489   g_signal_connect (sess->session, "on-ssrc-sdes",
490       (GCallback) on_ssrc_sdes, sess);
491   g_signal_connect (sess->session, "on-bye-ssrc",
492       (GCallback) on_bye_ssrc, sess);
493   g_signal_connect (sess->session, "on-bye-timeout",
494       (GCallback) on_bye_timeout, sess);
495   g_signal_connect (sess->session, "on-timeout", (GCallback) on_timeout, sess);
496
497   /* FIXME, change state only to what's needed */
498   gst_bin_add (GST_BIN_CAST (rtpbin), session);
499   gst_element_set_state (session, GST_STATE_PLAYING);
500   gst_bin_add (GST_BIN_CAST (rtpbin), demux);
501   gst_element_set_state (demux, GST_STATE_PLAYING);
502
503   return sess;
504
505   /* ERRORS */
506 no_session:
507   {
508     g_warning ("gstrtpbin: could not create gstrtpsession element");
509     return NULL;
510   }
511 no_demux:
512   {
513     gst_object_unref (session);
514     g_warning ("gstrtpbin: could not create gstrtpssrcdemux element");
515     return NULL;
516   }
517 }
518
519 static void
520 free_session (GstRtpBinSession * sess)
521 {
522   GstRtpBin *bin;
523
524   bin = sess->bin;
525
526   gst_element_set_state (sess->session, GST_STATE_NULL);
527   gst_element_set_state (sess->demux, GST_STATE_NULL);
528
529   if (sess->recv_rtp_sink != NULL)
530     gst_element_release_request_pad (sess->session, sess->recv_rtp_sink);
531   if (sess->recv_rtp_src != NULL)
532     gst_object_unref (sess->recv_rtp_src);
533   if (sess->recv_rtcp_sink != NULL)
534     gst_element_release_request_pad (sess->session, sess->recv_rtcp_sink);
535   if (sess->sync_src != NULL)
536     gst_object_unref (sess->sync_src);
537   if (sess->send_rtp_sink != NULL)
538     gst_element_release_request_pad (sess->session, sess->send_rtp_sink);
539   if (sess->send_rtp_src != NULL)
540     gst_object_unref (sess->send_rtp_src);
541   if (sess->send_rtcp_src != NULL)
542     gst_element_release_request_pad (sess->session, sess->send_rtcp_src);
543
544   gst_bin_remove (GST_BIN_CAST (bin), sess->session);
545   gst_bin_remove (GST_BIN_CAST (bin), sess->demux);
546
547   g_slist_foreach (sess->streams, (GFunc) free_stream, NULL);
548   g_slist_free (sess->streams);
549
550   g_mutex_free (sess->lock);
551   g_hash_table_destroy (sess->ptmap);
552
553   bin->sessions = g_slist_remove (bin->sessions, sess);
554
555   g_free (sess);
556 }
557
558 #if 0
559 static GstRtpBinStream *
560 find_stream_by_ssrc (GstRtpBinSession * session, guint32 ssrc)
561 {
562   GSList *walk;
563
564   for (walk = session->streams; walk; walk = g_slist_next (walk)) {
565     GstRtpBinStream *stream = (GstRtpBinStream *) walk->data;
566
567     if (stream->ssrc == ssrc)
568       return stream;
569   }
570   return NULL;
571 }
572 #endif
573
574 /* get the payload type caps for the specific payload @pt in @session */
575 static GstCaps *
576 get_pt_map (GstRtpBinSession * session, guint pt)
577 {
578   GstCaps *caps = NULL;
579   GstRtpBin *bin;
580   GValue ret = { 0 };
581   GValue args[3] = { {0}, {0}, {0} };
582
583   GST_DEBUG ("searching pt %d in cache", pt);
584
585   GST_RTP_SESSION_LOCK (session);
586
587   /* first look in the cache */
588   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
589   if (caps) {
590     gst_caps_ref (caps);
591     goto done;
592   }
593
594   bin = session->bin;
595
596   GST_DEBUG ("emiting signal for pt %d in session %d", pt, session->id);
597
598   /* not in cache, send signal to request caps */
599   g_value_init (&args[0], GST_TYPE_ELEMENT);
600   g_value_set_object (&args[0], bin);
601   g_value_init (&args[1], G_TYPE_UINT);
602   g_value_set_uint (&args[1], session->id);
603   g_value_init (&args[2], G_TYPE_UINT);
604   g_value_set_uint (&args[2], pt);
605
606   g_value_init (&ret, GST_TYPE_CAPS);
607   g_value_set_boxed (&ret, NULL);
608
609   g_signal_emitv (args, gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP], 0, &ret);
610
611   g_value_unset (&args[0]);
612   g_value_unset (&args[1]);
613   g_value_unset (&args[2]);
614   caps = (GstCaps *) g_value_dup_boxed (&ret);
615   g_value_unset (&ret);
616   if (!caps)
617     goto no_caps;
618
619   GST_DEBUG ("caching pt %d as %" GST_PTR_FORMAT, pt, caps);
620
621   /* store in cache, take additional ref */
622   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (pt),
623       gst_caps_ref (caps));
624
625 done:
626   GST_RTP_SESSION_UNLOCK (session);
627
628   return caps;
629
630   /* ERRORS */
631 no_caps:
632   {
633     GST_RTP_SESSION_UNLOCK (session);
634     GST_DEBUG ("no pt map could be obtained");
635     return NULL;
636   }
637 }
638
639 static gboolean
640 return_true (gpointer key, gpointer value, gpointer user_data)
641 {
642   return TRUE;
643 }
644
645 static void
646 gst_rtp_bin_clear_pt_map (GstRtpBin * bin)
647 {
648   GSList *sessions, *streams;
649
650   GST_RTP_BIN_LOCK (bin);
651   GST_DEBUG_OBJECT (bin, "clearing pt map");
652   for (sessions = bin->sessions; sessions; sessions = g_slist_next (sessions)) {
653     GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
654
655     GST_DEBUG_OBJECT (bin, "clearing session %p", session);
656     g_signal_emit_by_name (session->session, "clear-pt-map", NULL);
657
658     GST_RTP_SESSION_LOCK (session);
659     g_hash_table_foreach_remove (session->ptmap, return_true, NULL);
660
661     for (streams = session->streams; streams; streams = g_slist_next (streams)) {
662       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
663
664       GST_DEBUG_OBJECT (bin, "clearing stream %p", stream);
665       g_signal_emit_by_name (stream->buffer, "clear-pt-map", NULL);
666       g_signal_emit_by_name (stream->demux, "clear-pt-map", NULL);
667     }
668     GST_RTP_SESSION_UNLOCK (session);
669   }
670   GST_RTP_BIN_UNLOCK (bin);
671 }
672
673 /* get a client with the given SDES name. Must be called with RTP_BIN_LOCK */
674 static GstRtpBinClient *
675 get_client (GstRtpBin * bin, guint8 len, guint8 * data, gboolean * created)
676 {
677   GstRtpBinClient *result = NULL;
678   GSList *walk;
679
680   for (walk = bin->clients; walk; walk = g_slist_next (walk)) {
681     GstRtpBinClient *client = (GstRtpBinClient *) walk->data;
682
683     if (len != client->cname_len)
684       continue;
685
686     if (!strncmp ((gchar *) data, client->cname, client->cname_len)) {
687       GST_DEBUG_OBJECT (bin, "found existing client %p with CNAME %s", client,
688           client->cname);
689       result = client;
690       break;
691     }
692   }
693
694   /* nothing found, create one */
695   if (result == NULL) {
696     result = g_new0 (GstRtpBinClient, 1);
697     result->cname = g_strndup ((gchar *) data, len);
698     result->cname_len = len;
699     result->min_delta = G_MAXINT64;
700     bin->clients = g_slist_prepend (bin->clients, result);
701     GST_DEBUG_OBJECT (bin, "created new client %p with CNAME %s", result,
702         result->cname);
703   }
704   return result;
705 }
706
707 static void
708 free_client (GstRtpBinClient * client)
709 {
710   g_slist_free (client->streams);
711   g_free (client->cname);
712   g_free (client);
713 }
714
715 /* associate a stream to the given CNAME. This will make sure all streams for
716  * that CNAME are synchronized together. */
717 static void
718 gst_rtp_bin_associate (GstRtpBin * bin, GstRtpBinStream * stream, guint8 len,
719     guint8 * data)
720 {
721   GstRtpBinClient *client;
722   gboolean created;
723   GSList *walk;
724
725   /* first find or create the CNAME */
726   GST_RTP_BIN_LOCK (bin);
727   client = get_client (bin, len, data, &created);
728
729   /* find stream in the client */
730   for (walk = client->streams; walk; walk = g_slist_next (walk)) {
731     GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
732
733     if (ostream == stream)
734       break;
735   }
736   /* not found, add it to the list */
737   if (walk == NULL) {
738     GST_DEBUG_OBJECT (bin,
739         "new association of SSRC %08x with client %p with CNAME %s",
740         stream->ssrc, client, client->cname);
741     client->streams = g_slist_prepend (client->streams, stream);
742     client->nstreams++;
743   } else {
744     GST_DEBUG_OBJECT (bin,
745         "found association of SSRC %08x with client %p with CNAME %s",
746         stream->ssrc, client, client->cname);
747   }
748
749   /* we can only continue if we know the local clock-base and clock-rate */
750   if (stream->clock_base == -1)
751     goto no_clock_base;
752
753   if (stream->clock_rate <= 0) {
754     gint pt = -1;
755     GstCaps *caps = NULL;
756     GstStructure *s = NULL;
757
758     GST_RTP_SESSION_LOCK (stream->session);
759     pt = stream->last_pt;
760     GST_RTP_SESSION_UNLOCK (stream->session);
761
762     if (pt < 0)
763       goto no_clock_rate;
764
765     caps = get_pt_map (stream->session, pt);
766     if (!caps)
767       goto no_clock_rate;
768
769     s = gst_caps_get_structure (caps, 0);
770     gst_structure_get_int (s, "clock-rate", &stream->clock_rate);
771     gst_caps_unref (caps);
772
773     if (stream->clock_rate <= 0)
774       goto no_clock_rate;
775   }
776
777   /* map last RTP time to local timeline using our clock-base */
778   stream->local_rtp = stream->last_extrtptime - stream->clock_base;
779
780   GST_DEBUG_OBJECT (bin,
781       "base %" G_GUINT64_FORMAT ", extrtptime %" G_GUINT64_FORMAT
782       ", local RTP %" G_GUINT64_FORMAT ", clock-rate %d", stream->clock_base,
783       stream->last_extrtptime, stream->local_rtp, stream->clock_rate);
784
785   /* calculate local NTP time in gstreamer timestamp */
786   stream->local_unix =
787       gst_util_uint64_scale_int (stream->local_rtp, GST_SECOND,
788       stream->clock_rate);
789   stream->local_unix += stream->clock_base_time;
790   /* calculate delta between server and receiver */
791   stream->unix_delta = stream->last_unix - stream->local_unix;
792
793   GST_DEBUG_OBJECT (bin,
794       "local UNIX %" G_GUINT64_FORMAT ", remote UNIX %" G_GUINT64_FORMAT
795       ", delta %" G_GINT64_FORMAT, stream->local_unix, stream->last_unix,
796       stream->unix_delta);
797
798   /* recalc inter stream playout offset, but only if there are more than one
799    * stream. */
800   if (client->nstreams > 1) {
801     gint64 min;
802
803     /* calculate the min of all deltas */
804     min = G_MAXINT64;
805     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
806       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
807
808       if (ostream->unix_delta && ostream->unix_delta < min)
809         min = ostream->unix_delta;
810     }
811
812     GST_DEBUG_OBJECT (bin, "client %p min delta %" G_GINT64_FORMAT, client,
813         min);
814
815     /* calculate offsets for each stream */
816     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
817       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
818
819       if (ostream->unix_delta == 0)
820         continue;
821
822       ostream->ts_offset = ostream->unix_delta - min;
823
824       /* delta changed, see how much */
825       if (ostream->prev_ts_offset != ostream->ts_offset) {
826         gint64 diff;
827
828         if (ostream->prev_ts_offset > ostream->ts_offset)
829           diff = ostream->prev_ts_offset - ostream->ts_offset;
830         else
831           diff = ostream->ts_offset - ostream->prev_ts_offset;
832
833         /* only change diff when it changed more than 1 millisecond. This
834          * compensates for rounding errors in NTP to RTP timestamp
835          * conversions */
836         if (diff > GST_MSECOND)
837           g_object_set (ostream->buffer, "ts-offset", ostream->ts_offset, NULL);
838
839         ostream->prev_ts_offset = ostream->ts_offset;
840       }
841       GST_DEBUG_OBJECT (bin, "stream SSRC %08x, delta %" G_GINT64_FORMAT,
842           ostream->ssrc, ostream->ts_offset);
843     }
844   }
845   GST_RTP_BIN_UNLOCK (bin);
846   return;
847
848 no_clock_base:
849   {
850     GST_WARNING_OBJECT (bin, "we have no clock-base");
851     GST_RTP_BIN_UNLOCK (bin);
852     return;
853   }
854 no_clock_rate:
855   {
856     GST_WARNING_OBJECT (bin, "we have no clock-rate");
857     GST_RTP_BIN_UNLOCK (bin);
858     return;
859   }
860 }
861
862 #define GST_RTCP_BUFFER_FOR_PACKETS(b,buffer,packet) \
863   for ((b) = gst_rtcp_buffer_get_first_packet ((buffer), (packet)); (b); \
864           (b) = gst_rtcp_packet_move_to_next ((packet)))
865
866 #define GST_RTCP_SDES_FOR_ITEMS(b,packet) \
867   for ((b) = gst_rtcp_packet_sdes_first_item ((packet)); (b); \
868           (b) = gst_rtcp_packet_sdes_next_item ((packet)))
869
870 #define GST_RTCP_SDES_FOR_ENTRIES(b,packet) \
871   for ((b) = gst_rtcp_packet_sdes_first_entry ((packet)); (b); \
872           (b) = gst_rtcp_packet_sdes_next_entry ((packet)))
873
874 static GstFlowReturn
875 gst_rtp_bin_sync_chain (GstPad * pad, GstBuffer * buffer)
876 {
877   GstFlowReturn ret = GST_FLOW_OK;
878   GstRtpBinStream *stream;
879   GstRtpBin *bin;
880   GstRTCPPacket packet;
881   guint32 ssrc;
882   guint64 ntptime;
883   guint32 rtptime;
884   gboolean have_sr, have_sdes;
885   gboolean more;
886
887   stream = gst_pad_get_element_private (pad);
888   bin = stream->bin;
889
890   GST_DEBUG_OBJECT (bin, "received sync packet");
891
892   if (!gst_rtcp_buffer_validate (buffer))
893     goto invalid_rtcp;
894
895   have_sr = FALSE;
896   have_sdes = FALSE;
897   GST_RTCP_BUFFER_FOR_PACKETS (more, buffer, &packet) {
898     /* first packet must be SR or RR or else the validate would have failed */
899     switch (gst_rtcp_packet_get_type (&packet)) {
900       case GST_RTCP_TYPE_SR:
901         /* only parse first. There is only supposed to be one SR in the packet
902          * but we will deal with malformed packets gracefully */
903         if (have_sr)
904           break;
905         /* get NTP and RTP times */
906         gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, &ntptime, &rtptime,
907             NULL, NULL);
908
909         GST_DEBUG_OBJECT (bin, "received sync packet from SSRC %08x", ssrc);
910         /* ignore SR that is not ours */
911         if (ssrc != stream->ssrc)
912           continue;
913
914         have_sr = TRUE;
915
916         /* store values in the stream */
917         stream->have_sync = TRUE;
918         stream->last_unix = gst_rtcp_ntp_to_unix (ntptime);
919         /* use extended timestamp */
920         gst_rtp_buffer_ext_timestamp (&stream->last_extrtptime, rtptime);
921         break;
922       case GST_RTCP_TYPE_SDES:
923       {
924         gboolean more_items, more_entries;
925
926         /* only deal with first SDES, there is only supposed to be one SDES in
927          * the RTCP packet but we deal with bad packets gracefully. Also bail
928          * out if we have not seen an SR item yet. */
929         if (have_sdes || !have_sr)
930           break;
931
932         GST_RTCP_SDES_FOR_ITEMS (more_items, &packet) {
933           /* skip items that are not about the SSRC of the sender */
934           if (gst_rtcp_packet_sdes_get_ssrc (&packet) != ssrc)
935             continue;
936
937           /* find the CNAME entry */
938           GST_RTCP_SDES_FOR_ENTRIES (more_entries, &packet) {
939             GstRTCPSDESType type;
940             guint8 len;
941             guint8 *data;
942
943             gst_rtcp_packet_sdes_get_entry (&packet, &type, &len, &data);
944
945             if (type == GST_RTCP_SDES_CNAME) {
946               stream->clock_base = GST_BUFFER_OFFSET (buffer);
947               stream->clock_base_time = GST_BUFFER_OFFSET_END (buffer);
948               /* associate the stream to CNAME */
949               gst_rtp_bin_associate (bin, stream, len, data);
950             }
951           }
952         }
953         have_sdes = TRUE;
954         break;
955       }
956       default:
957         /* we can ignore these packets */
958         break;
959     }
960   }
961
962   gst_buffer_unref (buffer);
963
964   return ret;
965
966   /* ERRORS */
967 invalid_rtcp:
968   {
969     /* this is fatal and should be filtered earlier */
970     GST_ELEMENT_ERROR (bin, STREAM, DECODE, (NULL),
971         ("invalid RTCP packet received"));
972     gst_buffer_unref (buffer);
973     return GST_FLOW_ERROR;
974   }
975 }
976
977 /* create a new stream with @ssrc in @session. Must be called with
978  * RTP_SESSION_LOCK. */
979 static GstRtpBinStream *
980 create_stream (GstRtpBinSession * session, guint32 ssrc)
981 {
982   GstElement *buffer, *demux;
983   GstRtpBinStream *stream;
984   GstPadTemplate *templ;
985   gchar *padname;
986
987   if (!(buffer = gst_element_factory_make ("gstrtpjitterbuffer", NULL)))
988     goto no_jitterbuffer;
989
990   if (!(demux = gst_element_factory_make ("gstrtpptdemux", NULL)))
991     goto no_demux;
992
993   stream = g_new0 (GstRtpBinStream, 1);
994   stream->ssrc = ssrc;
995   stream->bin = session->bin;
996   stream->session = session;
997   stream->buffer = buffer;
998   stream->demux = demux;
999   stream->last_extrtptime = -1;
1000   stream->last_pt = -1;
1001   stream->have_sync = FALSE;
1002   session->streams = g_slist_prepend (session->streams, stream);
1003
1004   /* make an internal sinkpad for RTCP sync packets. Take ownership of the
1005    * pad. We will link this pad later. */
1006   padname = g_strdup_printf ("sync_%d", ssrc);
1007   templ = gst_static_pad_template_get (&rtpbin_sync_sink_template);
1008   stream->sync_pad = gst_pad_new_from_template (templ, padname);
1009   gst_object_unref (templ);
1010   g_free (padname);
1011   gst_object_ref (stream->sync_pad);
1012   gst_object_sink (stream->sync_pad);
1013   gst_pad_set_element_private (stream->sync_pad, stream);
1014   gst_pad_set_chain_function (stream->sync_pad, gst_rtp_bin_sync_chain);
1015   gst_pad_set_active (stream->sync_pad, TRUE);
1016
1017   /* provide clock_rate to the jitterbuffer when needed */
1018   g_signal_connect (buffer, "request-pt-map",
1019       (GCallback) pt_map_requested, session);
1020
1021   /* configure latency */
1022   g_object_set (buffer, "latency", session->bin->latency, NULL);
1023
1024   gst_bin_add (GST_BIN_CAST (session->bin), buffer);
1025   gst_element_set_state (buffer, GST_STATE_PLAYING);
1026   gst_bin_add (GST_BIN_CAST (session->bin), demux);
1027   gst_element_set_state (demux, GST_STATE_PLAYING);
1028
1029   /* link stuff */
1030   gst_element_link (buffer, demux);
1031
1032   return stream;
1033
1034   /* ERRORS */
1035 no_jitterbuffer:
1036   {
1037     g_warning ("gstrtpbin: could not create gstrtpjitterbuffer element");
1038     return NULL;
1039   }
1040 no_demux:
1041   {
1042     gst_object_unref (buffer);
1043     g_warning ("gstrtpbin: could not create gstrtpptdemux element");
1044     return NULL;
1045   }
1046 }
1047
1048 static void
1049 free_stream (GstRtpBinStream * stream)
1050 {
1051   GstRtpBinSession *session;
1052
1053   session = stream->session;
1054
1055   gst_element_set_state (stream->buffer, GST_STATE_NULL);
1056   gst_element_set_state (stream->demux, GST_STATE_NULL);
1057
1058   gst_bin_remove (GST_BIN_CAST (session->bin), stream->buffer);
1059   gst_bin_remove (GST_BIN_CAST (session->bin), stream->demux);
1060
1061   gst_object_unref (stream->sync_pad);
1062
1063   session->streams = g_slist_remove (session->streams, stream);
1064
1065   g_free (stream);
1066 }
1067
1068 /* GObject vmethods */
1069 static void gst_rtp_bin_dispose (GObject * object);
1070 static void gst_rtp_bin_finalize (GObject * object);
1071 static void gst_rtp_bin_set_property (GObject * object, guint prop_id,
1072     const GValue * value, GParamSpec * pspec);
1073 static void gst_rtp_bin_get_property (GObject * object, guint prop_id,
1074     GValue * value, GParamSpec * pspec);
1075
1076 /* GstElement vmethods */
1077 static GstClock *gst_rtp_bin_provide_clock (GstElement * element);
1078 static GstStateChangeReturn gst_rtp_bin_change_state (GstElement * element,
1079     GstStateChange transition);
1080 static GstPad *gst_rtp_bin_request_new_pad (GstElement * element,
1081     GstPadTemplate * templ, const gchar * name);
1082 static void gst_rtp_bin_release_pad (GstElement * element, GstPad * pad);
1083 static void gst_rtp_bin_handle_message (GstBin * bin, GstMessage * message);
1084 static void gst_rtp_bin_clear_pt_map (GstRtpBin * bin);
1085
1086 GST_BOILERPLATE (GstRtpBin, gst_rtp_bin, GstBin, GST_TYPE_BIN);
1087
1088 static void
1089 gst_rtp_bin_base_init (gpointer klass)
1090 {
1091   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
1092
1093   /* sink pads */
1094   gst_element_class_add_pad_template (element_class,
1095       gst_static_pad_template_get (&rtpbin_recv_rtp_sink_template));
1096   gst_element_class_add_pad_template (element_class,
1097       gst_static_pad_template_get (&rtpbin_recv_rtcp_sink_template));
1098   gst_element_class_add_pad_template (element_class,
1099       gst_static_pad_template_get (&rtpbin_send_rtp_sink_template));
1100
1101   /* src pads */
1102   gst_element_class_add_pad_template (element_class,
1103       gst_static_pad_template_get (&rtpbin_recv_rtp_src_template));
1104   gst_element_class_add_pad_template (element_class,
1105       gst_static_pad_template_get (&rtpbin_send_rtcp_src_template));
1106   gst_element_class_add_pad_template (element_class,
1107       gst_static_pad_template_get (&rtpbin_send_rtp_src_template));
1108
1109   gst_element_class_set_details (element_class, &rtpbin_details);
1110 }
1111
1112 static void
1113 gst_rtp_bin_class_init (GstRtpBinClass * klass)
1114 {
1115   GObjectClass *gobject_class;
1116   GstElementClass *gstelement_class;
1117   GstBinClass *gstbin_class;
1118
1119   gobject_class = (GObjectClass *) klass;
1120   gstelement_class = (GstElementClass *) klass;
1121   gstbin_class = (GstBinClass *) klass;
1122
1123   g_type_class_add_private (klass, sizeof (GstRtpBinPrivate));
1124
1125   gobject_class->dispose = gst_rtp_bin_dispose;
1126   gobject_class->finalize = gst_rtp_bin_finalize;
1127   gobject_class->set_property = gst_rtp_bin_set_property;
1128   gobject_class->get_property = gst_rtp_bin_get_property;
1129
1130   g_object_class_install_property (gobject_class, PROP_LATENCY,
1131       g_param_spec_uint ("latency", "Buffer latency in ms",
1132           "Default amount of ms to buffer in the jitterbuffers", 0,
1133           G_MAXUINT, DEFAULT_LATENCY_MS, G_PARAM_READWRITE));
1134
1135   /**
1136    * GstRtpBin::request-pt-map:
1137    * @rtpbin: the object which received the signal
1138    * @session: the session
1139    * @pt: the pt
1140    *
1141    * Request the payload type as #GstCaps for @pt in @session.
1142    */
1143   gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP] =
1144       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
1145       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, request_pt_map),
1146       NULL, NULL, gst_rtp_bin_marshal_BOXED__UINT_UINT, GST_TYPE_CAPS, 2,
1147       G_TYPE_UINT, G_TYPE_UINT);
1148   /**
1149    * GstRtpBin::clear-pt-map:
1150    * @rtpbin: the object which received the signal
1151    *
1152    * Clear all previously cached pt-mapping obtained with
1153    * GstRtpBin::request-pt-map.
1154    */
1155   gst_rtp_bin_signals[SIGNAL_CLEAR_PT_MAP] =
1156       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
1157       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
1158           clear_pt_map), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
1159       0, G_TYPE_NONE);
1160
1161   /**
1162    * GstRtpBin::on-new-ssrc:
1163    * @rtpbin: the object which received the signal
1164    * @session: the session
1165    * @ssrc: the SSRC 
1166    *
1167    * Notify of a new SSRC that entered @session.
1168    */
1169   gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC] =
1170       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
1171       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_new_ssrc),
1172       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1173       G_TYPE_UINT, G_TYPE_UINT);
1174   /**
1175    * GstRtpBin::on-ssrc-collision:
1176    * @rtpbin: the object which received the signal
1177    * @session: the session
1178    * @ssrc: the SSRC 
1179    *
1180    * Notify when we have an SSRC collision
1181    */
1182   gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION] =
1183       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
1184       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_collision),
1185       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1186       G_TYPE_UINT, G_TYPE_UINT);
1187   /**
1188    * GstRtpBin::on-ssrc-validated:
1189    * @rtpbin: the object which received the signal
1190    * @session: the session
1191    * @ssrc: the SSRC 
1192    *
1193    * Notify of a new SSRC that became validated.
1194    */
1195   gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED] =
1196       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
1197       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_validated),
1198       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1199       G_TYPE_UINT, G_TYPE_UINT);
1200   /**
1201    * GstRtpBin::on-ssrc-active:
1202    * @rtpbin: the object which received the signal
1203    * @session: the session
1204    * @ssrc: the SSRC
1205    *
1206    * Notify of a SSRC that is active, i.e., sending RTCP.
1207    */
1208   gst_rtp_bin_signals[SIGNAL_ON_SSRC_ACTIVE] =
1209       g_signal_new ("on-ssrc-active", G_TYPE_FROM_CLASS (klass),
1210       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_active),
1211       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1212       G_TYPE_UINT, G_TYPE_UINT);
1213   /**
1214    * GstRtpBin::on-ssrc-sdes:
1215    * @rtpbin: the object which received the signal
1216    * @session: the session
1217    * @ssrc: the SSRC
1218    *
1219    * Notify of a SSRC that is active, i.e., sending RTCP.
1220    */
1221   gst_rtp_bin_signals[SIGNAL_ON_SSRC_SDES] =
1222       g_signal_new ("on-ssrc-sdes", G_TYPE_FROM_CLASS (klass),
1223       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_sdes),
1224       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1225       G_TYPE_UINT, G_TYPE_UINT);
1226
1227   /**
1228    * GstRtpBin::on-bye-ssrc:
1229    * @rtpbin: the object which received the signal
1230    * @session: the session
1231    * @ssrc: the SSRC 
1232    *
1233    * Notify of an SSRC that became inactive because of a BYE packet.
1234    */
1235   gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC] =
1236       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
1237       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_ssrc),
1238       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1239       G_TYPE_UINT, G_TYPE_UINT);
1240   /**
1241    * GstRtpBin::on-bye-timeout:
1242    * @rtpbin: the object which received the signal
1243    * @session: the session
1244    * @ssrc: the SSRC 
1245    *
1246    * Notify of an SSRC that has timed out because of BYE
1247    */
1248   gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT] =
1249       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
1250       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_timeout),
1251       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1252       G_TYPE_UINT, G_TYPE_UINT);
1253   /**
1254    * GstRtpBin::on-timeout:
1255    * @rtpbin: the object which received the signal
1256    * @session: the session
1257    * @ssrc: the SSRC 
1258    *
1259    * Notify of an SSRC that has timed out
1260    */
1261   gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT] =
1262       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
1263       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_timeout),
1264       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1265       G_TYPE_UINT, G_TYPE_UINT);
1266
1267   g_object_class_install_property (gobject_class, PROP_SDES_CNAME,
1268       g_param_spec_string ("sdes-cname", "SDES CNAME",
1269           "The CNAME to put in SDES messages of this session",
1270           DEFAULT_SDES_CNAME, G_PARAM_READWRITE));
1271
1272   g_object_class_install_property (gobject_class, PROP_SDES_NAME,
1273       g_param_spec_string ("sdes-name", "SDES NAME",
1274           "The NAME to put in SDES messages of this session",
1275           DEFAULT_SDES_NAME, G_PARAM_READWRITE));
1276
1277   g_object_class_install_property (gobject_class, PROP_SDES_EMAIL,
1278       g_param_spec_string ("sdes-email", "SDES EMAIL",
1279           "The EMAIL to put in SDES messages of this session",
1280           DEFAULT_SDES_EMAIL, G_PARAM_READWRITE));
1281
1282   g_object_class_install_property (gobject_class, PROP_SDES_PHONE,
1283       g_param_spec_string ("sdes-phone", "SDES PHONE",
1284           "The PHONE to put in SDES messages of this session",
1285           DEFAULT_SDES_PHONE, G_PARAM_READWRITE));
1286
1287   g_object_class_install_property (gobject_class, PROP_SDES_LOCATION,
1288       g_param_spec_string ("sdes-location", "SDES LOCATION",
1289           "The LOCATION to put in SDES messages of this session",
1290           DEFAULT_SDES_LOCATION, G_PARAM_READWRITE));
1291
1292   g_object_class_install_property (gobject_class, PROP_SDES_TOOL,
1293       g_param_spec_string ("sdes-tool", "SDES TOOL",
1294           "The TOOL to put in SDES messages of this session",
1295           DEFAULT_SDES_TOOL, G_PARAM_READWRITE));
1296
1297   g_object_class_install_property (gobject_class, PROP_SDES_NOTE,
1298       g_param_spec_string ("sdes-note", "SDES NOTE",
1299           "The NOTE to put in SDES messages of this session",
1300           DEFAULT_SDES_NOTE, G_PARAM_READWRITE));
1301
1302   gstelement_class->provide_clock =
1303       GST_DEBUG_FUNCPTR (gst_rtp_bin_provide_clock);
1304   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rtp_bin_change_state);
1305   gstelement_class->request_new_pad =
1306       GST_DEBUG_FUNCPTR (gst_rtp_bin_request_new_pad);
1307   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_rtp_bin_release_pad);
1308
1309   gstbin_class->handle_message = GST_DEBUG_FUNCPTR (gst_rtp_bin_handle_message);
1310
1311   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_bin_clear_pt_map);
1312
1313   GST_DEBUG_CATEGORY_INIT (gst_rtp_bin_debug, "rtpbin", 0, "RTP bin");
1314 }
1315
1316 static void
1317 gst_rtp_bin_init (GstRtpBin * rtpbin, GstRtpBinClass * klass)
1318 {
1319   gchar *str;
1320
1321   rtpbin->priv = GST_RTP_BIN_GET_PRIVATE (rtpbin);
1322   rtpbin->priv->bin_lock = g_mutex_new ();
1323   rtpbin->provided_clock = gst_system_clock_obtain ();
1324   rtpbin->latency = DEFAULT_LATENCY_MS;
1325
1326   /* some default SDES entries */
1327   str = g_strdup_printf ("%s@%s", g_get_user_name (), g_get_host_name ());
1328   gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_CNAME, str);
1329   g_free (str);
1330
1331   gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_NAME, g_get_real_name ());
1332   gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_TOOL, "GStreamer");
1333 }
1334
1335 static void
1336 gst_rtp_bin_dispose (GObject * object)
1337 {
1338   GstRtpBin *rtpbin;
1339
1340   rtpbin = GST_RTP_BIN (object);
1341
1342   g_slist_foreach (rtpbin->sessions, (GFunc) free_session, NULL);
1343   g_slist_free (rtpbin->sessions);
1344   rtpbin->sessions = NULL;
1345   g_slist_foreach (rtpbin->clients, (GFunc) free_client, NULL);
1346   g_slist_free (rtpbin->clients);
1347   rtpbin->clients = NULL;
1348
1349   G_OBJECT_CLASS (parent_class)->dispose (object);
1350 }
1351
1352 static void
1353 gst_rtp_bin_finalize (GObject * object)
1354 {
1355   GstRtpBin *rtpbin;
1356   gint i;
1357
1358   rtpbin = GST_RTP_BIN (object);
1359
1360   for (i = 0; i < 9; i++)
1361     g_free (rtpbin->sdes[i]);
1362
1363   g_mutex_free (rtpbin->priv->bin_lock);
1364   gst_object_unref (rtpbin->provided_clock);
1365
1366   G_OBJECT_CLASS (parent_class)->finalize (object);
1367 }
1368
1369 static const gchar *
1370 sdes_type_to_name (GstRTCPSDESType type)
1371 {
1372   const gchar *result;
1373
1374   switch (type) {
1375     case GST_RTCP_SDES_CNAME:
1376       result = "sdes-cname";
1377       break;
1378     case GST_RTCP_SDES_NAME:
1379       result = "sdes-name";
1380       break;
1381     case GST_RTCP_SDES_EMAIL:
1382       result = "sdes-email";
1383       break;
1384     case GST_RTCP_SDES_PHONE:
1385       result = "sdes-phone";
1386       break;
1387     case GST_RTCP_SDES_LOC:
1388       result = "sdes-location";
1389       break;
1390     case GST_RTCP_SDES_TOOL:
1391       result = "sdes-tool";
1392       break;
1393     case GST_RTCP_SDES_NOTE:
1394       result = "sdes-note";
1395       break;
1396     case GST_RTCP_SDES_PRIV:
1397       result = "sdes-priv";
1398       break;
1399     default:
1400       result = NULL;
1401       break;
1402   }
1403   return result;
1404 }
1405
1406 static void
1407 gst_rtp_bin_set_sdes_string (GstRtpBin * bin, GstRTCPSDESType type,
1408     const gchar * data)
1409 {
1410   GSList *item;
1411   const gchar *name;
1412
1413   if (type < 0 || type > 8)
1414     return;
1415
1416   GST_OBJECT_LOCK (bin);
1417   g_free (bin->sdes[type]);
1418   bin->sdes[type] = g_strdup (data);
1419   name = sdes_type_to_name (type);
1420   /* store in all sessions */
1421   for (item = bin->sessions; item; item = g_slist_next (item))
1422     g_object_set (item->data, name, bin->sdes[type], NULL);
1423   GST_OBJECT_UNLOCK (bin);
1424 }
1425
1426 static gchar *
1427 gst_rtp_bin_get_sdes_string (GstRtpBin * bin, GstRTCPSDESType type)
1428 {
1429   gchar *result;
1430
1431   if (type < 0 || type > 8)
1432     return NULL;
1433
1434   GST_OBJECT_LOCK (bin);
1435   result = g_strdup (bin->sdes[type]);
1436   GST_OBJECT_UNLOCK (bin);
1437
1438   return result;
1439 }
1440
1441 static void
1442 gst_rtp_bin_set_property (GObject * object, guint prop_id,
1443     const GValue * value, GParamSpec * pspec)
1444 {
1445   GstRtpBin *rtpbin;
1446
1447   rtpbin = GST_RTP_BIN (object);
1448
1449   switch (prop_id) {
1450     case PROP_LATENCY:
1451       GST_RTP_BIN_LOCK (rtpbin);
1452       rtpbin->latency = g_value_get_uint (value);
1453       GST_RTP_BIN_UNLOCK (rtpbin);
1454       break;
1455     case PROP_SDES_CNAME:
1456       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_CNAME,
1457           g_value_get_string (value));
1458       break;
1459     case PROP_SDES_NAME:
1460       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_NAME,
1461           g_value_get_string (value));
1462       break;
1463     case PROP_SDES_EMAIL:
1464       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_EMAIL,
1465           g_value_get_string (value));
1466       break;
1467     case PROP_SDES_PHONE:
1468       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_PHONE,
1469           g_value_get_string (value));
1470       break;
1471     case PROP_SDES_LOCATION:
1472       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_LOC,
1473           g_value_get_string (value));
1474       break;
1475     case PROP_SDES_TOOL:
1476       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_TOOL,
1477           g_value_get_string (value));
1478       break;
1479     case PROP_SDES_NOTE:
1480       gst_rtp_bin_set_sdes_string (rtpbin, GST_RTCP_SDES_NOTE,
1481           g_value_get_string (value));
1482       break;
1483     default:
1484       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1485       break;
1486   }
1487 }
1488
1489 static void
1490 gst_rtp_bin_get_property (GObject * object, guint prop_id,
1491     GValue * value, GParamSpec * pspec)
1492 {
1493   GstRtpBin *rtpbin;
1494
1495   rtpbin = GST_RTP_BIN (object);
1496
1497   switch (prop_id) {
1498     case PROP_LATENCY:
1499       GST_RTP_BIN_LOCK (rtpbin);
1500       g_value_set_uint (value, rtpbin->latency);
1501       GST_RTP_BIN_UNLOCK (rtpbin);
1502       break;
1503     case PROP_SDES_CNAME:
1504       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1505               GST_RTCP_SDES_CNAME));
1506       break;
1507     case PROP_SDES_NAME:
1508       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1509               GST_RTCP_SDES_NAME));
1510       break;
1511     case PROP_SDES_EMAIL:
1512       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1513               GST_RTCP_SDES_EMAIL));
1514       break;
1515     case PROP_SDES_PHONE:
1516       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1517               GST_RTCP_SDES_PHONE));
1518       break;
1519     case PROP_SDES_LOCATION:
1520       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1521               GST_RTCP_SDES_LOC));
1522       break;
1523     case PROP_SDES_TOOL:
1524       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1525               GST_RTCP_SDES_TOOL));
1526       break;
1527     case PROP_SDES_NOTE:
1528       g_value_take_string (value, gst_rtp_bin_get_sdes_string (rtpbin,
1529               GST_RTCP_SDES_NOTE));
1530       break;
1531     default:
1532       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1533       break;
1534   }
1535 }
1536
1537 static GstClock *
1538 gst_rtp_bin_provide_clock (GstElement * element)
1539 {
1540   GstRtpBin *rtpbin;
1541
1542   rtpbin = GST_RTP_BIN (element);
1543
1544   return GST_CLOCK_CAST (gst_object_ref (rtpbin->provided_clock));
1545 }
1546
1547 static void
1548 gst_rtp_bin_handle_message (GstBin * bin, GstMessage * message)
1549 {
1550   GstRtpBin *rtpbin;
1551
1552   rtpbin = GST_RTP_BIN (bin);
1553
1554   switch (GST_MESSAGE_TYPE (message)) {
1555     case GST_MESSAGE_ELEMENT:
1556     {
1557       const GstStructure *s = gst_message_get_structure (message);
1558
1559       /* we change the structure name and add the session ID to it */
1560       if (gst_structure_has_name (s, "GstRTPSessionSDES")) {
1561         GSList *walk;
1562
1563         /* find the session, the message source has it */
1564         for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
1565           GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
1566
1567           /* if we found the session, change message. else we exit the loop and
1568            * leave the message unchanged */
1569           if (GST_OBJECT_CAST (sess->session) == GST_MESSAGE_SRC (message)) {
1570             message = gst_message_make_writable (message);
1571             s = gst_message_get_structure (message);
1572
1573             gst_structure_set_name ((GstStructure *) s, "GstRTPBinSDES");
1574
1575             gst_structure_set ((GstStructure *) s, "session", G_TYPE_UINT,
1576                 sess->id, NULL);
1577             break;
1578           }
1579         }
1580       }
1581       /* fallthrough to forward the modified message to the parent */
1582     }
1583     default:
1584     {
1585       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
1586       break;
1587     }
1588   }
1589 }
1590
1591 static void
1592 calc_ntp_ns_base (GstRtpBin * bin)
1593 {
1594   GstClockTime now;
1595   GTimeVal current;
1596   GSList *walk;
1597
1598   /* get the current time and convert it to NTP time in nanoseconds */
1599   g_get_current_time (&current);
1600   now = GST_TIMEVAL_TO_TIME (current);
1601   now += (2208988800LL * GST_SECOND);
1602
1603   GST_RTP_BIN_LOCK (bin);
1604   bin->priv->ntp_ns_base = now;
1605   for (walk = bin->sessions; walk; walk = g_slist_next (walk)) {
1606     GstRtpBinSession *session = (GstRtpBinSession *) walk->data;
1607
1608     g_object_set (session->session, "ntp-ns-base", now, NULL);
1609   }
1610   GST_RTP_BIN_UNLOCK (bin);
1611
1612   return;
1613 }
1614
1615 static GstStateChangeReturn
1616 gst_rtp_bin_change_state (GstElement * element, GstStateChange transition)
1617 {
1618   GstStateChangeReturn res;
1619   GstRtpBin *rtpbin;
1620
1621   rtpbin = GST_RTP_BIN (element);
1622
1623   switch (transition) {
1624     case GST_STATE_CHANGE_NULL_TO_READY:
1625       break;
1626     case GST_STATE_CHANGE_READY_TO_PAUSED:
1627       break;
1628     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1629       calc_ntp_ns_base (rtpbin);
1630       break;
1631     default:
1632       break;
1633   }
1634
1635   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1636
1637   switch (transition) {
1638     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1639       break;
1640     case GST_STATE_CHANGE_PAUSED_TO_READY:
1641       break;
1642     case GST_STATE_CHANGE_READY_TO_NULL:
1643       break;
1644     default:
1645       break;
1646   }
1647   return res;
1648 }
1649
1650 /* a new pad (SSRC) was created in @session */
1651 static void
1652 new_payload_found (GstElement * element, guint pt, GstPad * pad,
1653     GstRtpBinStream * stream)
1654 {
1655   GstRtpBin *rtpbin;
1656   GstElementClass *klass;
1657   GstPadTemplate *templ;
1658   gchar *padname;
1659   GstPad *gpad;
1660
1661   rtpbin = stream->bin;
1662
1663   GST_DEBUG ("new payload pad %d", pt);
1664
1665   /* ghost the pad to the parent */
1666   klass = GST_ELEMENT_GET_CLASS (rtpbin);
1667   templ = gst_element_class_get_pad_template (klass, "recv_rtp_src_%d_%d_%d");
1668   padname = g_strdup_printf ("recv_rtp_src_%d_%u_%d",
1669       stream->session->id, stream->ssrc, pt);
1670   gpad = gst_ghost_pad_new_from_template (padname, pad, templ);
1671   g_free (padname);
1672
1673   gst_pad_set_caps (gpad, GST_PAD_CAPS (pad));
1674   gst_pad_set_active (gpad, TRUE);
1675   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), gpad);
1676 }
1677
1678 static GstCaps *
1679 pt_map_requested (GstElement * element, guint pt, GstRtpBinSession * session)
1680 {
1681   GstRtpBin *rtpbin;
1682   GstCaps *caps;
1683
1684   rtpbin = session->bin;
1685
1686   GST_DEBUG_OBJECT (rtpbin, "payload map requested for pt %d in session %d", pt,
1687       session->id);
1688
1689   caps = get_pt_map (session, pt);
1690   if (!caps)
1691     goto no_caps;
1692
1693   return caps;
1694
1695   /* ERRORS */
1696 no_caps:
1697   {
1698     GST_DEBUG_OBJECT (rtpbin, "could not get caps");
1699     return NULL;
1700   }
1701 }
1702
1703 /* emited when caps changed for the session */
1704 static void
1705 caps_changed (GstPad * pad, GParamSpec * pspec, GstRtpBinSession * session)
1706 {
1707   GstRtpBin *bin;
1708   GstCaps *caps;
1709   gint payload;
1710   const GstStructure *s;
1711
1712   bin = session->bin;
1713
1714   g_object_get (pad, "caps", &caps, NULL);
1715
1716   if (caps == NULL)
1717     return;
1718
1719   GST_DEBUG_OBJECT (bin, "got caps %" GST_PTR_FORMAT, caps);
1720
1721   s = gst_caps_get_structure (caps, 0);
1722
1723   /* get payload, finish when it's not there */
1724   if (!gst_structure_get_int (s, "payload", &payload))
1725     return;
1726
1727   GST_RTP_SESSION_LOCK (session);
1728   GST_DEBUG_OBJECT (bin, "insert caps for payload %d", payload);
1729   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (payload), caps);
1730   GST_RTP_SESSION_UNLOCK (session);
1731 }
1732
1733 /* Stores the last payload type received on a particular stream */
1734 static void
1735 payload_type_change (GstElement * element, guint pt, GstRtpBinStream * stream)
1736 {
1737   GST_RTP_SESSION_LOCK (stream->session);
1738   stream->last_pt = pt;
1739   GST_RTP_SESSION_UNLOCK (stream->session);
1740 }
1741
1742 /* a new pad (SSRC) was created in @session */
1743 static void
1744 new_ssrc_pad_found (GstElement * element, guint ssrc, GstPad * pad,
1745     GstRtpBinSession * session)
1746 {
1747   GstRtpBinStream *stream;
1748   GstPad *sinkpad, *srcpad;
1749   gchar *padname;
1750   GstCaps *caps;
1751
1752   GST_DEBUG_OBJECT (session->bin, "new SSRC pad %08x", ssrc);
1753
1754   GST_RTP_SESSION_LOCK (session);
1755
1756   /* create new stream */
1757   stream = create_stream (session, ssrc);
1758   if (!stream)
1759     goto no_stream;
1760
1761   /* get the caps of the pad, we need the clock-rate and base_time if any. */
1762   if ((caps = gst_pad_get_caps (pad))) {
1763     const GstStructure *s;
1764     guint val;
1765
1766     GST_DEBUG_OBJECT (session->bin, "pad has caps %" GST_PTR_FORMAT, caps);
1767
1768     s = gst_caps_get_structure (caps, 0);
1769
1770     if (!gst_structure_get_int (s, "clock-rate", &stream->clock_rate)) {
1771       stream->clock_rate = -1;
1772
1773       GST_WARNING_OBJECT (session->bin,
1774           "Caps have no clock rate %s from pad %s:%s",
1775           gst_caps_to_string (caps), GST_DEBUG_PAD_NAME (pad));
1776     }
1777
1778     if (gst_structure_get_uint (s, "clock-base", &val))
1779       stream->clock_base = val;
1780     else
1781       stream->clock_base = -1;
1782
1783     gst_caps_unref (caps);
1784   }
1785
1786   /* get pad and link */
1787   GST_DEBUG_OBJECT (session->bin, "linking jitterbuffer");
1788   padname = g_strdup_printf ("src_%d", ssrc);
1789   srcpad = gst_element_get_static_pad (element, padname);
1790   g_free (padname);
1791   sinkpad = gst_element_get_static_pad (stream->buffer, "sink");
1792   gst_pad_link (srcpad, sinkpad);
1793   gst_object_unref (sinkpad);
1794   gst_object_unref (srcpad);
1795
1796   /* get the RTCP sync pad */
1797   GST_DEBUG_OBJECT (session->bin, "linking sync pad");
1798   padname = g_strdup_printf ("rtcp_src_%d", ssrc);
1799   srcpad = gst_element_get_static_pad (element, padname);
1800   g_free (padname);
1801   gst_pad_link (srcpad, stream->sync_pad);
1802   gst_object_unref (srcpad);
1803
1804   /* connect to the new-pad signal of the payload demuxer, this will expose the
1805    * new pad by ghosting it. */
1806   stream->demux_newpad_sig = g_signal_connect (stream->demux,
1807       "new-payload-type", (GCallback) new_payload_found, stream);
1808   /* connect to the request-pt-map signal. This signal will be emited by the
1809    * demuxer so that it can apply a proper caps on the buffers for the
1810    * depayloaders. */
1811   stream->demux_ptreq_sig = g_signal_connect (stream->demux,
1812       "request-pt-map", (GCallback) pt_map_requested, session);
1813   /* connect to the payload-type-change signal so that we can know which
1814    * PT is the current PT so that the jitterbuffer can be matched to the right
1815    * offset. */
1816   stream->demux_pt_change_sig = g_signal_connect (stream->demux,
1817       "payload-type-change", (GCallback) payload_type_change, stream);
1818
1819   GST_RTP_SESSION_UNLOCK (session);
1820
1821   return;
1822
1823   /* ERRORS */
1824 no_stream:
1825   {
1826     GST_RTP_SESSION_UNLOCK (session);
1827     GST_DEBUG_OBJECT (session->bin, "could not create stream");
1828     return;
1829   }
1830 }
1831
1832 /* Create a pad for receiving RTP for the session in @name. Must be called with
1833  * RTP_BIN_LOCK.
1834  */
1835 static GstPad *
1836 create_recv_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1837 {
1838   GstPad *result, *sinkdpad;
1839   guint sessid;
1840   GstRtpBinSession *session;
1841   GstPadLinkReturn lres;
1842
1843   /* first get the session number */
1844   if (name == NULL || sscanf (name, "recv_rtp_sink_%d", &sessid) != 1)
1845     goto no_name;
1846
1847   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
1848
1849   /* get or create session */
1850   session = find_session_by_id (rtpbin, sessid);
1851   if (!session) {
1852     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
1853     /* create session now */
1854     session = create_session (rtpbin, sessid);
1855     if (session == NULL)
1856       goto create_error;
1857   }
1858
1859   /* check if pad was requested */
1860   if (session->recv_rtp_sink != NULL)
1861     goto existed;
1862
1863   GST_DEBUG_OBJECT (rtpbin, "getting RTP sink pad");
1864   /* get recv_rtp pad and store */
1865   session->recv_rtp_sink =
1866       gst_element_get_request_pad (session->session, "recv_rtp_sink");
1867   if (session->recv_rtp_sink == NULL)
1868     goto pad_failed;
1869
1870   g_signal_connect (session->recv_rtp_sink, "notify::caps",
1871       (GCallback) caps_changed, session);
1872
1873   GST_DEBUG_OBJECT (rtpbin, "getting RTP src pad");
1874   /* get srcpad, link to SSRCDemux */
1875   session->recv_rtp_src =
1876       gst_element_get_static_pad (session->session, "recv_rtp_src");
1877   if (session->recv_rtp_src == NULL)
1878     goto pad_failed;
1879
1880   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTP sink pad");
1881   sinkdpad = gst_element_get_static_pad (session->demux, "sink");
1882   GST_DEBUG_OBJECT (rtpbin, "linking demuxer RTP sink pad");
1883   lres = gst_pad_link (session->recv_rtp_src, sinkdpad);
1884   gst_object_unref (sinkdpad);
1885   if (lres != GST_PAD_LINK_OK)
1886     goto link_failed;
1887
1888   /* connect to the new-ssrc-pad signal of the SSRC demuxer */
1889   session->demux_newpad_sig = g_signal_connect (session->demux,
1890       "new-ssrc-pad", (GCallback) new_ssrc_pad_found, session);
1891
1892   GST_DEBUG_OBJECT (rtpbin, "ghosting session sink pad");
1893   result =
1894       gst_ghost_pad_new_from_template (name, session->recv_rtp_sink, templ);
1895   gst_pad_set_active (result, TRUE);
1896   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1897
1898   return result;
1899
1900   /* ERRORS */
1901 no_name:
1902   {
1903     g_warning ("gstrtpbin: invalid name given");
1904     return NULL;
1905   }
1906 create_error:
1907   {
1908     /* create_session already warned */
1909     return NULL;
1910   }
1911 existed:
1912   {
1913     g_warning ("gstrtpbin: recv_rtp pad already requested for session %d",
1914         sessid);
1915     return NULL;
1916   }
1917 pad_failed:
1918   {
1919     g_warning ("gstrtpbin: failed to get session pad");
1920     return NULL;
1921   }
1922 link_failed:
1923   {
1924     g_warning ("gstrtpbin: failed to link pads");
1925     return NULL;
1926   }
1927 }
1928
1929 /* Create a pad for receiving RTCP for the session in @name. Must be called with
1930  * RTP_BIN_LOCK.
1931  */
1932 static GstPad *
1933 create_recv_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ,
1934     const gchar * name)
1935 {
1936   GstPad *result;
1937   guint sessid;
1938   GstRtpBinSession *session;
1939   GstPad *sinkdpad;
1940   GstPadLinkReturn lres;
1941
1942   /* first get the session number */
1943   if (name == NULL || sscanf (name, "recv_rtcp_sink_%d", &sessid) != 1)
1944     goto no_name;
1945
1946   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
1947
1948   /* get or create the session */
1949   session = find_session_by_id (rtpbin, sessid);
1950   if (!session) {
1951     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
1952     /* create session now */
1953     session = create_session (rtpbin, sessid);
1954     if (session == NULL)
1955       goto create_error;
1956   }
1957
1958   /* check if pad was requested */
1959   if (session->recv_rtcp_sink != NULL)
1960     goto existed;
1961
1962   /* get recv_rtp pad and store */
1963   GST_DEBUG_OBJECT (rtpbin, "getting RTCP sink pad");
1964   session->recv_rtcp_sink =
1965       gst_element_get_request_pad (session->session, "recv_rtcp_sink");
1966   if (session->recv_rtcp_sink == NULL)
1967     goto pad_failed;
1968
1969   /* get srcpad, link to SSRCDemux */
1970   GST_DEBUG_OBJECT (rtpbin, "getting sync src pad");
1971   session->sync_src = gst_element_get_static_pad (session->session, "sync_src");
1972   if (session->sync_src == NULL)
1973     goto pad_failed;
1974
1975   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTCP sink pad");
1976   sinkdpad = gst_element_get_static_pad (session->demux, "rtcp_sink");
1977   lres = gst_pad_link (session->sync_src, sinkdpad);
1978   gst_object_unref (sinkdpad);
1979   if (lres != GST_PAD_LINK_OK)
1980     goto link_failed;
1981
1982   result =
1983       gst_ghost_pad_new_from_template (name, session->recv_rtcp_sink, templ);
1984   gst_pad_set_active (result, TRUE);
1985   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1986
1987   return result;
1988
1989   /* ERRORS */
1990 no_name:
1991   {
1992     g_warning ("gstrtpbin: invalid name given");
1993     return NULL;
1994   }
1995 create_error:
1996   {
1997     /* create_session already warned */
1998     return NULL;
1999   }
2000 existed:
2001   {
2002     g_warning ("gstrtpbin: recv_rtcp pad already requested for session %d",
2003         sessid);
2004     return NULL;
2005   }
2006 pad_failed:
2007   {
2008     g_warning ("gstrtpbin: failed to get session pad");
2009     return NULL;
2010   }
2011 link_failed:
2012   {
2013     g_warning ("gstrtpbin: failed to link pads");
2014     return NULL;
2015   }
2016 }
2017
2018 /* Create a pad for sending RTP for the session in @name. Must be called with
2019  * RTP_BIN_LOCK.
2020  */
2021 static GstPad *
2022 create_send_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
2023 {
2024   GstPad *result, *srcghost;
2025   gchar *gname;
2026   guint sessid;
2027   GstRtpBinSession *session;
2028   GstElementClass *klass;
2029
2030   /* first get the session number */
2031   if (name == NULL || sscanf (name, "send_rtp_sink_%d", &sessid) != 1)
2032     goto no_name;
2033
2034   /* get or create session */
2035   session = find_session_by_id (rtpbin, sessid);
2036   if (!session) {
2037     /* create session now */
2038     session = create_session (rtpbin, sessid);
2039     if (session == NULL)
2040       goto create_error;
2041   }
2042
2043   /* check if pad was requested */
2044   if (session->send_rtp_sink != NULL)
2045     goto existed;
2046
2047   /* get send_rtp pad and store */
2048   session->send_rtp_sink =
2049       gst_element_get_request_pad (session->session, "send_rtp_sink");
2050   if (session->send_rtp_sink == NULL)
2051     goto pad_failed;
2052
2053   result =
2054       gst_ghost_pad_new_from_template (name, session->send_rtp_sink, templ);
2055   gst_pad_set_active (result, TRUE);
2056   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
2057
2058   /* get srcpad */
2059   session->send_rtp_src =
2060       gst_element_get_static_pad (session->session, "send_rtp_src");
2061   if (session->send_rtp_src == NULL)
2062     goto no_srcpad;
2063
2064   /* ghost the new source pad */
2065   klass = GST_ELEMENT_GET_CLASS (rtpbin);
2066   gname = g_strdup_printf ("send_rtp_src_%d", sessid);
2067   templ = gst_element_class_get_pad_template (klass, "send_rtp_src_%d");
2068   srcghost =
2069       gst_ghost_pad_new_from_template (gname, session->send_rtp_src, templ);
2070   gst_pad_set_active (srcghost, TRUE);
2071   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), srcghost);
2072   g_free (gname);
2073
2074   return result;
2075
2076   /* ERRORS */
2077 no_name:
2078   {
2079     g_warning ("gstrtpbin: invalid name given");
2080     return NULL;
2081   }
2082 create_error:
2083   {
2084     /* create_session already warned */
2085     return NULL;
2086   }
2087 existed:
2088   {
2089     g_warning ("gstrtpbin: send_rtp pad already requested for session %d",
2090         sessid);
2091     return NULL;
2092   }
2093 pad_failed:
2094   {
2095     g_warning ("gstrtpbin: failed to get session pad for session %d", sessid);
2096     return NULL;
2097   }
2098 no_srcpad:
2099   {
2100     g_warning ("gstrtpbin: failed to get rtp source pad for session %d",
2101         sessid);
2102     return NULL;
2103   }
2104 }
2105
2106 /* Create a pad for sending RTCP for the session in @name. Must be called with
2107  * RTP_BIN_LOCK.
2108  */
2109 static GstPad *
2110 create_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
2111 {
2112   GstPad *result;
2113   guint sessid;
2114   GstRtpBinSession *session;
2115
2116   /* first get the session number */
2117   if (name == NULL || sscanf (name, "send_rtcp_src_%d", &sessid) != 1)
2118     goto no_name;
2119
2120   /* get or create session */
2121   session = find_session_by_id (rtpbin, sessid);
2122   if (!session)
2123     goto no_session;
2124
2125   /* check if pad was requested */
2126   if (session->send_rtcp_src != NULL)
2127     goto existed;
2128
2129   /* get rtcp_src pad and store */
2130   session->send_rtcp_src =
2131       gst_element_get_request_pad (session->session, "send_rtcp_src");
2132   if (session->send_rtcp_src == NULL)
2133     goto pad_failed;
2134
2135   result =
2136       gst_ghost_pad_new_from_template (name, session->send_rtcp_src, templ);
2137   gst_pad_set_active (result, TRUE);
2138   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
2139
2140   return result;
2141
2142   /* ERRORS */
2143 no_name:
2144   {
2145     g_warning ("gstrtpbin: invalid name given");
2146     return NULL;
2147   }
2148 no_session:
2149   {
2150     g_warning ("gstrtpbin: session with id %d does not exist", sessid);
2151     return NULL;
2152   }
2153 existed:
2154   {
2155     g_warning ("gstrtpbin: send_rtcp_src pad already requested for session %d",
2156         sessid);
2157     return NULL;
2158   }
2159 pad_failed:
2160   {
2161     g_warning ("gstrtpbin: failed to get rtcp pad for session %d", sessid);
2162     return NULL;
2163   }
2164 }
2165
2166 /* If the requested name is NULL we should create a name with
2167  * the session number assuming we want the lowest posible session
2168  * with a free pad like the template */
2169 static gchar *
2170 gst_rtp_bin_get_free_pad_name (GstElement * element, GstPadTemplate * templ)
2171 {
2172   gboolean name_found = FALSE;
2173   gint session = 0;
2174   GstPad *pad = NULL;
2175   GstIterator *pad_it = NULL;
2176   gchar *pad_name = NULL;
2177
2178   GST_DEBUG_OBJECT (element, "find a free pad name for template");
2179   while (!name_found) {
2180     g_free (pad_name);
2181     pad_name = g_strdup_printf (templ->name_template, session++);
2182     pad_it = gst_element_iterate_pads (GST_ELEMENT (element));
2183     name_found = TRUE;
2184     while (gst_iterator_next (pad_it, (gpointer) & pad) == GST_ITERATOR_OK) {
2185       gchar *name;
2186
2187       name = gst_pad_get_name (pad);
2188       if (strcmp (name, pad_name) == 0)
2189         name_found = FALSE;
2190       g_free (name);
2191     }
2192     gst_iterator_free (pad_it);
2193   }
2194
2195   GST_DEBUG_OBJECT (element, "free pad name found: '%s'", pad_name);
2196   return pad_name;
2197 }
2198
2199 /* 
2200  */
2201 static GstPad *
2202 gst_rtp_bin_request_new_pad (GstElement * element,
2203     GstPadTemplate * templ, const gchar * name)
2204 {
2205   GstRtpBin *rtpbin;
2206   GstElementClass *klass;
2207   GstPad *result;
2208   gchar *pad_name = NULL;
2209
2210   g_return_val_if_fail (templ != NULL, NULL);
2211   g_return_val_if_fail (GST_IS_RTP_BIN (element), NULL);
2212
2213   rtpbin = GST_RTP_BIN (element);
2214   klass = GST_ELEMENT_GET_CLASS (element);
2215
2216   GST_RTP_BIN_LOCK (rtpbin);
2217
2218   if (name == NULL) {
2219     /* use a free pad name */
2220     pad_name = gst_rtp_bin_get_free_pad_name (element, templ);
2221   } else {
2222     /* use the provided name */
2223     pad_name = g_strdup (name);
2224   }
2225
2226   GST_DEBUG ("Trying to request a pad with name %s", pad_name);
2227
2228   /* figure out the template */
2229   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink_%d")) {
2230     result = create_recv_rtp (rtpbin, templ, pad_name);
2231   } else if (templ == gst_element_class_get_pad_template (klass,
2232           "recv_rtcp_sink_%d")) {
2233     result = create_recv_rtcp (rtpbin, templ, pad_name);
2234   } else if (templ == gst_element_class_get_pad_template (klass,
2235           "send_rtp_sink_%d")) {
2236     result = create_send_rtp (rtpbin, templ, pad_name);
2237   } else if (templ == gst_element_class_get_pad_template (klass,
2238           "send_rtcp_src_%d")) {
2239     result = create_rtcp (rtpbin, templ, pad_name);
2240   } else
2241     goto wrong_template;
2242
2243   g_free (pad_name);
2244   GST_RTP_BIN_UNLOCK (rtpbin);
2245
2246   return result;
2247
2248   /* ERRORS */
2249 wrong_template:
2250   {
2251     g_free (pad_name);
2252     GST_RTP_BIN_UNLOCK (rtpbin);
2253     g_warning ("gstrtpbin: this is not our template");
2254     return NULL;
2255   }
2256 }
2257
2258 static void
2259 gst_rtp_bin_release_pad (GstElement * element, GstPad * pad)
2260 {
2261 }