gst/rtpmanager/: Updated example pipelines in docs.
[platform/upstream/gstreamer.git] / gst / rtpmanager / gstrtpbin.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim@fluendo.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. The session number must be specified when
60  * requesting the sink pad. 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
144 /* elementfactory information */
145 static const GstElementDetails rtpbin_details = GST_ELEMENT_DETAILS ("RTP Bin",
146     "Filter/Network/RTP",
147     "Implement an RTP bin",
148     "Wim Taymans <wim@fluendo.com>");
149
150 /* sink pads */
151 static GstStaticPadTemplate rtpbin_recv_rtp_sink_template =
152 GST_STATIC_PAD_TEMPLATE ("recv_rtp_sink_%d",
153     GST_PAD_SINK,
154     GST_PAD_REQUEST,
155     GST_STATIC_CAPS ("application/x-rtp")
156     );
157
158 static GstStaticPadTemplate rtpbin_recv_rtcp_sink_template =
159 GST_STATIC_PAD_TEMPLATE ("recv_rtcp_sink_%d",
160     GST_PAD_SINK,
161     GST_PAD_REQUEST,
162     GST_STATIC_CAPS ("application/x-rtcp")
163     );
164
165 static GstStaticPadTemplate rtpbin_send_rtp_sink_template =
166 GST_STATIC_PAD_TEMPLATE ("send_rtp_sink_%d",
167     GST_PAD_SINK,
168     GST_PAD_REQUEST,
169     GST_STATIC_CAPS ("application/x-rtp")
170     );
171
172 /* src pads */
173 static GstStaticPadTemplate rtpbin_recv_rtp_src_template =
174 GST_STATIC_PAD_TEMPLATE ("recv_rtp_src_%d_%d_%d",
175     GST_PAD_SRC,
176     GST_PAD_SOMETIMES,
177     GST_STATIC_CAPS ("application/x-rtp")
178     );
179
180 static GstStaticPadTemplate rtpbin_send_rtcp_src_template =
181 GST_STATIC_PAD_TEMPLATE ("send_rtcp_src_%d",
182     GST_PAD_SRC,
183     GST_PAD_REQUEST,
184     GST_STATIC_CAPS ("application/x-rtcp")
185     );
186
187 static GstStaticPadTemplate rtpbin_send_rtp_src_template =
188 GST_STATIC_PAD_TEMPLATE ("send_rtp_src_%d",
189     GST_PAD_SRC,
190     GST_PAD_SOMETIMES,
191     GST_STATIC_CAPS ("application/x-rtp")
192     );
193
194 /* padtemplate for the internal pad */
195 static GstStaticPadTemplate rtpbin_sync_sink_template =
196 GST_STATIC_PAD_TEMPLATE ("sink_%d",
197     GST_PAD_SINK,
198     GST_PAD_SOMETIMES,
199     GST_STATIC_CAPS ("application/x-rtcp")
200     );
201
202 #define GST_RTP_BIN_GET_PRIVATE(obj)  \
203    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTP_BIN, GstRtpBinPrivate))
204
205 #define GST_RTP_BIN_LOCK(bin)   g_mutex_lock ((bin)->priv->bin_lock)
206 #define GST_RTP_BIN_UNLOCK(bin) g_mutex_unlock ((bin)->priv->bin_lock)
207
208 struct _GstRtpBinPrivate
209 {
210   GMutex *bin_lock;
211 };
212
213 /* signals and args */
214 enum
215 {
216   SIGNAL_REQUEST_PT_MAP,
217   SIGNAL_CLEAR_PT_MAP,
218
219   SIGNAL_ON_NEW_SSRC,
220   SIGNAL_ON_SSRC_COLLISION,
221   SIGNAL_ON_SSRC_VALIDATED,
222   SIGNAL_ON_BYE_SSRC,
223   SIGNAL_ON_BYE_TIMEOUT,
224   SIGNAL_ON_TIMEOUT,
225   LAST_SIGNAL
226 };
227
228 #define DEFAULT_LATENCY_MS      200
229
230 enum
231 {
232   PROP_0,
233   PROP_LATENCY
234 };
235
236 /* helper objects */
237 typedef struct _GstRtpBinSession GstRtpBinSession;
238 typedef struct _GstRtpBinStream GstRtpBinStream;
239 typedef struct _GstRtpBinClient GstRtpBinClient;
240
241 static guint gst_rtp_bin_signals[LAST_SIGNAL] = { 0 };
242
243 static GstCaps *pt_map_requested (GstElement * element, guint pt,
244     GstRtpBinSession * session);
245
246 /* Manages the RTP stream for one SSRC.
247  *
248  * We pipe the stream (comming from the SSRC demuxer) into a jitterbuffer.
249  * If we see an SDES RTCP packet that links multiple SSRCs together based on a
250  * common CNAME, we create a GstRtpBinClient structure to group the SSRCs
251  * together (see below).
252  */
253 struct _GstRtpBinStream
254 {
255   /* the SSRC of this stream */
256   guint32 ssrc;
257
258   /* parent bin */
259   GstRtpBin *bin;
260
261   /* the session this SSRC belongs to */
262   GstRtpBinSession *session;
263
264   /* the jitterbuffer of the SSRC */
265   GstElement *buffer;
266
267   /* the PT demuxer of the SSRC */
268   GstElement *demux;
269   gulong demux_newpad_sig;
270   gulong demux_ptreq_sig;
271
272   /* the internal pad we use to get RTCP sync messages */
273   GstPad *sync_pad;
274   gboolean have_sync;
275   guint64 last_unix;
276   guint64 last_extrtptime;
277
278   /* mapping to local RTP and NTP time */
279   guint64 local_rtp;
280   guint64 local_unix;
281   gint64 unix_delta;
282
283   /* for lip-sync */
284   guint64 clock_base;
285   gint clock_rate;
286   gint64 ts_offset;
287   gint64 prev_ts_offset;
288 };
289
290 #define GST_RTP_SESSION_LOCK(sess)   g_mutex_lock ((sess)->lock)
291 #define GST_RTP_SESSION_UNLOCK(sess) g_mutex_unlock ((sess)->lock)
292
293 /* Manages the receiving end of the packets.
294  *
295  * There is one such structure for each RTP session (audio/video/...).
296  * We get the RTP/RTCP packets and stuff them into the session manager. From
297  * there they are pushed into an SSRC demuxer that splits the stream based on
298  * SSRC. Each of the SSRC streams go into their own jitterbuffer (managed with
299  * the GstRtpBinStream above).
300  */
301 struct _GstRtpBinSession
302 {
303   /* session id */
304   gint id;
305   /* the parent bin */
306   GstRtpBin *bin;
307   /* the session element */
308   GstElement *session;
309   /* the SSRC demuxer */
310   GstElement *demux;
311   gulong demux_newpad_sig;
312
313   GMutex *lock;
314
315   /* list of GstRtpBinStream */
316   GSList *streams;
317
318   /* mapping of payload type to caps */
319   GHashTable *ptmap;
320
321   /* the pads of the session */
322   GstPad *recv_rtp_sink;
323   GstPad *recv_rtp_src;
324   GstPad *recv_rtcp_sink;
325   GstPad *sync_src;
326   GstPad *send_rtp_sink;
327   GstPad *send_rtp_src;
328   GstPad *send_rtcp_src;
329 };
330
331 /* Manages the RTP streams that come from one client and should therefore be
332  * synchronized.
333  */
334 struct _GstRtpBinClient
335 {
336   /* the common CNAME for the streams */
337   gchar *cname;
338   guint cname_len;
339
340   /* the streams */
341   guint nstreams;
342   GSList *streams;
343
344   gint64 min_delta;
345 };
346
347 /* find a session with the given id. Must be called with RTP_BIN_LOCK */
348 static GstRtpBinSession *
349 find_session_by_id (GstRtpBin * rtpbin, gint id)
350 {
351   GSList *walk;
352
353   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
354     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
355
356     if (sess->id == id)
357       return sess;
358   }
359   return NULL;
360 }
361
362 static void
363 on_new_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
364 {
365   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC], 0,
366       sess->id, ssrc);
367 }
368
369 static void
370 on_ssrc_collision (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
371 {
372   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION], 0,
373       sess->id, ssrc);
374 }
375
376 static void
377 on_ssrc_validated (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
378 {
379   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
380       sess->id, ssrc);
381 }
382
383 static void
384 on_bye_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
385 {
386   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC], 0,
387       sess->id, ssrc);
388 }
389
390 static void
391 on_bye_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
392 {
393   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT], 0,
394       sess->id, ssrc);
395 }
396
397 static void
398 on_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
399 {
400   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT], 0,
401       sess->id, ssrc);
402 }
403
404 /* create a session with the given id.  Must be called with RTP_BIN_LOCK */
405 static GstRtpBinSession *
406 create_session (GstRtpBin * rtpbin, gint id)
407 {
408   GstRtpBinSession *sess;
409   GstElement *session, *demux;
410
411   if (!(session = gst_element_factory_make ("gstrtpsession", NULL)))
412     goto no_session;
413
414   if (!(demux = gst_element_factory_make ("gstrtpssrcdemux", NULL)))
415     goto no_demux;
416
417   sess = g_new0 (GstRtpBinSession, 1);
418   sess->lock = g_mutex_new ();
419   sess->id = id;
420   sess->bin = rtpbin;
421   sess->session = session;
422   sess->demux = demux;
423   sess->ptmap = g_hash_table_new (NULL, NULL);
424   rtpbin->sessions = g_slist_prepend (rtpbin->sessions, sess);
425
426   /* provide clock_rate to the session manager when needed */
427   g_signal_connect (session, "request-pt-map",
428       (GCallback) pt_map_requested, sess);
429
430   g_signal_connect (sess->session, "on-new-ssrc",
431       (GCallback) on_new_ssrc, sess);
432   g_signal_connect (sess->session, "on-ssrc-collision",
433       (GCallback) on_ssrc_collision, sess);
434   g_signal_connect (sess->session, "on-ssrc-validated",
435       (GCallback) on_ssrc_validated, sess);
436   g_signal_connect (sess->session, "on-bye-ssrc",
437       (GCallback) on_bye_ssrc, sess);
438   g_signal_connect (sess->session, "on-bye-timeout",
439       (GCallback) on_bye_timeout, sess);
440   g_signal_connect (sess->session, "on-timeout", (GCallback) on_timeout, sess);
441
442   gst_bin_add (GST_BIN_CAST (rtpbin), session);
443   gst_element_set_state (session, GST_STATE_PLAYING);
444   gst_bin_add (GST_BIN_CAST (rtpbin), demux);
445   gst_element_set_state (demux, GST_STATE_PLAYING);
446
447   return sess;
448
449   /* ERRORS */
450 no_session:
451   {
452     g_warning ("gstrtpbin: could not create gstrtpsession element");
453     return NULL;
454   }
455 no_demux:
456   {
457     gst_object_unref (session);
458     g_warning ("gstrtpbin: could not create gstrtpssrcdemux element");
459     return NULL;
460   }
461 }
462
463 #if 0
464 static GstRtpBinStream *
465 find_stream_by_ssrc (GstRtpBinSession * session, guint32 ssrc)
466 {
467   GSList *walk;
468
469   for (walk = session->streams; walk; walk = g_slist_next (walk)) {
470     GstRtpBinStream *stream = (GstRtpBinStream *) walk->data;
471
472     if (stream->ssrc == ssrc)
473       return stream;
474   }
475   return NULL;
476 }
477 #endif
478
479 /* get the payload type caps for the specific payload @pt in @session */
480 static GstCaps *
481 get_pt_map (GstRtpBinSession * session, guint pt)
482 {
483   GstCaps *caps = NULL;
484   GstRtpBin *bin;
485   GValue ret = { 0 };
486   GValue args[3] = { {0}, {0}, {0} };
487
488   GST_DEBUG ("searching pt %d in cache", pt);
489
490   GST_RTP_SESSION_LOCK (session);
491
492   /* first look in the cache */
493   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
494   if (caps)
495     goto done;
496
497   bin = session->bin;
498
499   GST_DEBUG ("emiting signal for pt %d in session %d", pt, session->id);
500
501   /* not in cache, send signal to request caps */
502   g_value_init (&args[0], GST_TYPE_ELEMENT);
503   g_value_set_object (&args[0], bin);
504   g_value_init (&args[1], G_TYPE_UINT);
505   g_value_set_uint (&args[1], session->id);
506   g_value_init (&args[2], G_TYPE_UINT);
507   g_value_set_uint (&args[2], pt);
508
509   g_value_init (&ret, GST_TYPE_CAPS);
510   g_value_set_boxed (&ret, NULL);
511
512   g_signal_emitv (args, gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP], 0, &ret);
513
514   caps = (GstCaps *) g_value_get_boxed (&ret);
515   if (!caps)
516     goto no_caps;
517
518   GST_DEBUG ("caching pt %d as %" GST_PTR_FORMAT, pt, caps);
519
520   /* store in cache */
521   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (pt), caps);
522
523 done:
524   GST_RTP_SESSION_UNLOCK (session);
525
526   return caps;
527
528   /* ERRORS */
529 no_caps:
530   {
531     GST_RTP_SESSION_UNLOCK (session);
532     GST_DEBUG ("no pt map could be obtained");
533     return NULL;
534   }
535 }
536
537 static gboolean
538 return_true (gpointer key, gpointer value, gpointer user_data)
539 {
540   return TRUE;
541 }
542
543 static void
544 gst_rtp_bin_clear_pt_map (GstRtpBin * bin)
545 {
546   GSList *walk;
547
548   GST_RTP_BIN_LOCK (bin);
549   GST_DEBUG_OBJECT (bin, "clearing pt map");
550   for (walk = bin->sessions; walk; walk = g_slist_next (walk)) {
551     GstRtpBinSession *session = (GstRtpBinSession *) walk->data;
552
553     GST_RTP_SESSION_LOCK (session);
554 #if 0
555     /* This requires GLib 2.12 */
556     g_hash_table_remove_all (session->ptmap);
557 #else
558     g_hash_table_foreach_remove (session->ptmap, return_true, NULL);
559 #endif
560     GST_RTP_SESSION_UNLOCK (session);
561   }
562   GST_RTP_BIN_UNLOCK (bin);
563 }
564
565 static GstRtpBinClient *
566 gst_rtp_bin_get_client (GstRtpBin * bin, guint8 len, guint8 * data,
567     gboolean * created)
568 {
569   GstRtpBinClient *result = NULL;
570   GSList *walk;
571
572   for (walk = bin->clients; walk; walk = g_slist_next (walk)) {
573     GstRtpBinClient *client = (GstRtpBinClient *) walk->data;
574
575     if (len != client->cname_len)
576       continue;
577
578     if (!strncmp ((gchar *) data, client->cname, client->cname_len)) {
579       GST_DEBUG_OBJECT (bin, "found existing client %p with CNAME %s", client,
580           client->cname);
581       result = client;
582       break;
583     }
584   }
585
586   /* nothing found, create one */
587   if (result == NULL) {
588     result = g_new0 (GstRtpBinClient, 1);
589     result->cname = g_strndup ((gchar *) data, len);
590     result->cname_len = len;
591     result->min_delta = G_MAXINT64;
592     bin->clients = g_slist_prepend (bin->clients, result);
593     GST_DEBUG_OBJECT (bin, "created new client %p with CNAME %s", result,
594         result->cname);
595   }
596   return result;
597 }
598
599 /* associate a stream to the given CNAME. This will make sure all streams for
600  * that CNAME are synchronized together. */
601 static void
602 gst_rtp_bin_associate (GstRtpBin * bin, GstRtpBinStream * stream, guint8 len,
603     guint8 * data)
604 {
605   GstRtpBinClient *client;
606   gboolean created;
607   GSList *walk;
608
609   /* first find or create the CNAME */
610   client = gst_rtp_bin_get_client (bin, len, data, &created);
611
612   /* find stream in the client */
613   for (walk = client->streams; walk; walk = g_slist_next (walk)) {
614     GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
615
616     if (ostream == stream)
617       break;
618   }
619   /* not found, add it to the list */
620   if (walk == NULL) {
621     GST_DEBUG_OBJECT (bin,
622         "new association of SSRC %08x with client %p with CNAME %s",
623         stream->ssrc, client, client->cname);
624     client->streams = g_slist_prepend (client->streams, stream);
625     client->nstreams++;
626   } else {
627     GST_DEBUG_OBJECT (bin,
628         "found association of SSRC %08x with client %p with CNAME %s",
629         stream->ssrc, client, client->cname);
630   }
631
632   /* we can only continue if we know the local clock-base and clock-rate */
633   if (stream->clock_base == -1)
634     goto no_clock_base;
635   if (stream->clock_rate <= 0)
636     goto no_clock_rate;
637
638   /* map last RTP time to local timeline using our clock-base */
639   stream->local_rtp = stream->last_extrtptime - stream->clock_base;
640
641   GST_DEBUG_OBJECT (bin,
642       "base %" G_GUINT64_FORMAT ", extrtptime %" G_GUINT64_FORMAT
643       ", local RTP %" G_GUINT64_FORMAT ", clock-rate %d", stream->clock_base,
644       stream->last_extrtptime, stream->local_rtp, stream->clock_rate);
645
646   /* calculate local NTP time in gstreamer timestamp */
647   stream->local_unix =
648       gst_util_uint64_scale_int (stream->local_rtp, GST_SECOND,
649       stream->clock_rate);
650   /* calculate delta between server and receiver */
651   stream->unix_delta = stream->last_unix - stream->local_unix;
652
653   GST_DEBUG_OBJECT (bin,
654       "local UNIX %" G_GUINT64_FORMAT ", remote UNIX %" G_GUINT64_FORMAT
655       ", delta %" G_GINT64_FORMAT, stream->local_unix, stream->last_unix,
656       stream->unix_delta);
657
658   /* recalc inter stream playout offset, but only if there are more than one
659    * stream. */
660   if (client->nstreams > 1) {
661     gint64 min;
662
663     /* calculate the min of all deltas */
664     min = G_MAXINT64;
665     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
666       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
667
668       if (ostream->unix_delta < min)
669         min = ostream->unix_delta;
670     }
671
672     GST_DEBUG_OBJECT (bin, "client %p min delta %" G_GINT64_FORMAT, client,
673         min);
674
675     /* calculate offsets for each stream */
676     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
677       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
678
679       ostream->ts_offset = ostream->unix_delta - min;
680
681       /* delta changed, see how much */
682       if (ostream->prev_ts_offset != ostream->ts_offset) {
683         gint64 diff;
684
685         if (ostream->prev_ts_offset > ostream->ts_offset)
686           diff = ostream->prev_ts_offset - ostream->ts_offset;
687         else
688           diff = ostream->ts_offset - ostream->prev_ts_offset;
689
690         /* only change diff when it changed more than 1 millisecond. This
691          * compensates for rounding errors in NTP to RTP timestamp
692          * conversions */
693         if (diff > GST_MSECOND)
694           g_object_set (ostream->buffer, "ts-offset", ostream->ts_offset, NULL);
695
696         ostream->prev_ts_offset = ostream->ts_offset;
697       }
698       GST_DEBUG_OBJECT (bin, "stream SSRC %08x, delta %" G_GINT64_FORMAT,
699           ostream->ssrc, ostream->ts_offset);
700     }
701   }
702   return;
703
704 no_clock_base:
705   {
706     GST_WARNING_OBJECT (bin, "we have no clock-base");
707     return;
708   }
709 no_clock_rate:
710   {
711     GST_WARNING_OBJECT (bin, "we have no clock-rate");
712     return;
713   }
714 }
715
716 #define GST_RTCP_BUFFER_FOR_PACKETS(b,buffer,packet) \
717   for ((b) = gst_rtcp_buffer_get_first_packet ((buffer), (packet)); (b); \
718           (b) = gst_rtcp_packet_move_to_next ((packet)))
719
720 #define GST_RTCP_SDES_FOR_ITEMS(b,packet) \
721   for ((b) = gst_rtcp_packet_sdes_first_item ((packet)); (b); \
722           (b) = gst_rtcp_packet_sdes_next_item ((packet)))
723
724 #define GST_RTCP_SDES_FOR_ENTRIES(b,packet) \
725   for ((b) = gst_rtcp_packet_sdes_first_entry ((packet)); (b); \
726           (b) = gst_rtcp_packet_sdes_next_entry ((packet)))
727
728 static GstFlowReturn
729 gst_rtp_bin_sync_chain (GstPad * pad, GstBuffer * buffer)
730 {
731   GstFlowReturn ret = GST_FLOW_OK;
732   GstRtpBinStream *stream;
733   GstRtpBin *bin;
734   GstRTCPPacket packet;
735   guint32 ssrc;
736   guint64 ntptime;
737   guint32 rtptime;
738   gboolean have_sr, have_sdes;
739   gboolean more;
740
741   stream = gst_pad_get_element_private (pad);
742   bin = stream->bin;
743
744   GST_DEBUG_OBJECT (bin, "received sync packet");
745
746   if (!gst_rtcp_buffer_validate (buffer))
747     goto invalid_rtcp;
748
749   have_sr = FALSE;
750   have_sdes = FALSE;
751   GST_RTCP_BUFFER_FOR_PACKETS (more, buffer, &packet) {
752     /* first packet must be SR or RR or else the validate would have failed */
753     switch (gst_rtcp_packet_get_type (&packet)) {
754       case GST_RTCP_TYPE_SR:
755         /* only parse first. There is only supposed to be one SR in the packet
756          * but we will deal with malformed packets gracefully */
757         if (have_sr)
758           break;
759         /* get NTP and RTP times */
760         gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, &ntptime, &rtptime,
761             NULL, NULL);
762
763         GST_DEBUG_OBJECT (bin, "received sync packet from SSRC %08x", ssrc);
764         /* ignore SR that is not ours */
765         if (ssrc != stream->ssrc)
766           continue;
767
768         have_sr = TRUE;
769
770         /* store values in the stream */
771         stream->have_sync = TRUE;
772         stream->last_unix = gst_rtcp_ntp_to_unix (ntptime);
773         /* use extended timestamp */
774         gst_rtp_buffer_ext_timestamp (&stream->last_extrtptime, rtptime);
775         break;
776       case GST_RTCP_TYPE_SDES:
777       {
778         gboolean more_items, more_entries;
779
780         /* only deal with first SDES, there is only supposed to be one SDES in
781          * the RTCP packet but we deal with bad packets gracefully. Also bail
782          * out if we have not seen an SR item yet. */
783         if (have_sdes || !have_sr)
784           break;
785
786         GST_RTCP_SDES_FOR_ITEMS (more_items, &packet) {
787           /* skip items that are not about the SSRC of the sender */
788           if (gst_rtcp_packet_sdes_get_ssrc (&packet) != ssrc)
789             continue;
790
791           /* find the CNAME entry */
792           GST_RTCP_SDES_FOR_ENTRIES (more_entries, &packet) {
793             GstRTCPSDESType type;
794             guint8 len;
795             guint8 *data;
796
797             gst_rtcp_packet_sdes_get_entry (&packet, &type, &len, &data);
798
799             if (type == GST_RTCP_SDES_CNAME) {
800               stream->clock_base = GST_BUFFER_OFFSET (buffer);
801               /* associate the stream to CNAME */
802               gst_rtp_bin_associate (bin, stream, len, data);
803             }
804           }
805         }
806         have_sdes = TRUE;
807         break;
808       }
809       default:
810         /* we can ignore these packets */
811         break;
812     }
813   }
814
815   gst_buffer_unref (buffer);
816
817   return ret;
818
819   /* ERRORS */
820 invalid_rtcp:
821   {
822     /* this is fatal and should be filtered earlier */
823     GST_ELEMENT_ERROR (bin, STREAM, DECODE, (NULL),
824         ("invalid RTCP packet received"));
825     gst_buffer_unref (buffer);
826     return GST_FLOW_ERROR;
827   }
828 }
829
830 /* create a new stream with @ssrc in @session. Must be called with
831  * RTP_SESSION_LOCK. */
832 static GstRtpBinStream *
833 create_stream (GstRtpBinSession * session, guint32 ssrc)
834 {
835   GstElement *buffer, *demux;
836   GstRtpBinStream *stream;
837   GstPadTemplate *templ;
838   gchar *padname;
839
840   if (!(buffer = gst_element_factory_make ("gstrtpjitterbuffer", NULL)))
841     goto no_jitterbuffer;
842
843   if (!(demux = gst_element_factory_make ("gstrtpptdemux", NULL)))
844     goto no_demux;
845
846   stream = g_new0 (GstRtpBinStream, 1);
847   stream->ssrc = ssrc;
848   stream->bin = session->bin;
849   stream->session = session;
850   stream->buffer = buffer;
851   stream->demux = demux;
852   stream->last_extrtptime = -1;
853   stream->have_sync = FALSE;
854   session->streams = g_slist_prepend (session->streams, stream);
855
856   /* make an internal sinkpad for RTCP sync packets. Take ownership of the
857    * pad. We will link this pad later. */
858   padname = g_strdup_printf ("sync_%d", ssrc);
859   templ = gst_static_pad_template_get (&rtpbin_sync_sink_template);
860   stream->sync_pad = gst_pad_new_from_template (templ, padname);
861   gst_object_unref (templ);
862   gst_object_ref (stream->sync_pad);
863   gst_object_sink (stream->sync_pad);
864   gst_pad_set_element_private (stream->sync_pad, stream);
865   gst_pad_set_chain_function (stream->sync_pad, gst_rtp_bin_sync_chain);
866   gst_pad_set_active (stream->sync_pad, TRUE);
867
868   /* provide clock_rate to the jitterbuffer when needed */
869   g_signal_connect (buffer, "request-pt-map",
870       (GCallback) pt_map_requested, session);
871
872   /* configure latency */
873   g_object_set (buffer, "latency", session->bin->latency, NULL);
874
875   gst_bin_add (GST_BIN_CAST (session->bin), buffer);
876   gst_element_set_state (buffer, GST_STATE_PLAYING);
877   gst_bin_add (GST_BIN_CAST (session->bin), demux);
878   gst_element_set_state (demux, GST_STATE_PLAYING);
879
880   /* link stuff */
881   gst_element_link (buffer, demux);
882
883   return stream;
884
885   /* ERRORS */
886 no_jitterbuffer:
887   {
888     g_warning ("gstrtpbin: could not create gstrtpjitterbuffer element");
889     return NULL;
890   }
891 no_demux:
892   {
893     gst_object_unref (buffer);
894     g_warning ("gstrtpbin: could not create gstrtpptdemux element");
895     return NULL;
896   }
897 }
898
899 /* GObject vmethods */
900 static void gst_rtp_bin_finalize (GObject * object);
901 static void gst_rtp_bin_set_property (GObject * object, guint prop_id,
902     const GValue * value, GParamSpec * pspec);
903 static void gst_rtp_bin_get_property (GObject * object, guint prop_id,
904     GValue * value, GParamSpec * pspec);
905
906 /* GstElement vmethods */
907 static GstClock *gst_rtp_bin_provide_clock (GstElement * element);
908 static GstStateChangeReturn gst_rtp_bin_change_state (GstElement * element,
909     GstStateChange transition);
910 static GstPad *gst_rtp_bin_request_new_pad (GstElement * element,
911     GstPadTemplate * templ, const gchar * name);
912 static void gst_rtp_bin_release_pad (GstElement * element, GstPad * pad);
913 static void gst_rtp_bin_clear_pt_map (GstRtpBin * bin);
914
915 GST_BOILERPLATE (GstRtpBin, gst_rtp_bin, GstBin, GST_TYPE_BIN);
916
917 static void
918 gst_rtp_bin_base_init (gpointer klass)
919 {
920   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
921
922   /* sink pads */
923   gst_element_class_add_pad_template (element_class,
924       gst_static_pad_template_get (&rtpbin_recv_rtp_sink_template));
925   gst_element_class_add_pad_template (element_class,
926       gst_static_pad_template_get (&rtpbin_recv_rtcp_sink_template));
927   gst_element_class_add_pad_template (element_class,
928       gst_static_pad_template_get (&rtpbin_send_rtp_sink_template));
929
930   /* src pads */
931   gst_element_class_add_pad_template (element_class,
932       gst_static_pad_template_get (&rtpbin_recv_rtp_src_template));
933   gst_element_class_add_pad_template (element_class,
934       gst_static_pad_template_get (&rtpbin_send_rtcp_src_template));
935   gst_element_class_add_pad_template (element_class,
936       gst_static_pad_template_get (&rtpbin_send_rtp_src_template));
937
938   gst_element_class_set_details (element_class, &rtpbin_details);
939 }
940
941 static void
942 gst_rtp_bin_class_init (GstRtpBinClass * klass)
943 {
944   GObjectClass *gobject_class;
945   GstElementClass *gstelement_class;
946
947   gobject_class = (GObjectClass *) klass;
948   gstelement_class = (GstElementClass *) klass;
949
950   g_type_class_add_private (klass, sizeof (GstRtpBinPrivate));
951
952   gobject_class->finalize = gst_rtp_bin_finalize;
953   gobject_class->set_property = gst_rtp_bin_set_property;
954   gobject_class->get_property = gst_rtp_bin_get_property;
955
956   g_object_class_install_property (gobject_class, PROP_LATENCY,
957       g_param_spec_uint ("latency", "Buffer latency in ms",
958           "Default amount of ms to buffer in the jitterbuffers", 0,
959           G_MAXUINT, DEFAULT_LATENCY_MS, G_PARAM_READWRITE));
960
961   /**
962    * GstRtpBin::request-pt-map:
963    * @rtpbin: the object which received the signal
964    * @session: the session
965    * @pt: the pt
966    *
967    * Request the payload type as #GstCaps for @pt in @session.
968    */
969   gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP] =
970       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
971       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, request_pt_map),
972       NULL, NULL, gst_rtp_bin_marshal_BOXED__UINT_UINT, GST_TYPE_CAPS, 2,
973       G_TYPE_UINT, G_TYPE_UINT);
974   /**
975    * GstRtpBin::clear-pt-map:
976    * @rtpbin: the object which received the signal
977    *
978    * Clear all previously cached pt-mapping obtained with
979    * GstRtpBin::request-pt-map.
980    */
981   gst_rtp_bin_signals[SIGNAL_CLEAR_PT_MAP] =
982       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
983       G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass, clear_pt_map),
984       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
985
986   /**
987    * GstRtpBin::on-new-ssrc:
988    * @rtpbin: the object which received the signal
989    * @session: the session
990    * @ssrc: the SSRC 
991    *
992    * Notify of a new SSRC that entered @session.
993    */
994   gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC] =
995       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
996       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_new_ssrc),
997       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
998       G_TYPE_UINT, G_TYPE_UINT);
999   /**
1000    * GstRtpBin::on-ssrc_collision:
1001    * @rtpbin: the object which received the signal
1002    * @session: the session
1003    * @ssrc: the SSRC 
1004    *
1005    * Notify when we have an SSRC collision
1006    */
1007   gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION] =
1008       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
1009       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_collision),
1010       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1011       G_TYPE_UINT, G_TYPE_UINT);
1012   /**
1013    * GstRtpBin::on-ssrc_validated:
1014    * @rtpbin: the object which received the signal
1015    * @session: the session
1016    * @ssrc: the SSRC 
1017    *
1018    * Notify of a new SSRC that became validated.
1019    */
1020   gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED] =
1021       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
1022       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_validated),
1023       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1024       G_TYPE_UINT, G_TYPE_UINT);
1025
1026   /**
1027    * GstRtpBin::on-bye-ssrc:
1028    * @rtpbin: the object which received the signal
1029    * @session: the session
1030    * @ssrc: the SSRC 
1031    *
1032    * Notify of an SSRC that became inactive because of a BYE packet.
1033    */
1034   gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC] =
1035       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
1036       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_ssrc),
1037       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1038       G_TYPE_UINT, G_TYPE_UINT);
1039   /**
1040    * GstRtpBin::on-bye-timeout:
1041    * @rtpbin: the object which received the signal
1042    * @session: the session
1043    * @ssrc: the SSRC 
1044    *
1045    * Notify of an SSRC that has timed out because of BYE
1046    */
1047   gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT] =
1048       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
1049       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_timeout),
1050       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1051       G_TYPE_UINT, G_TYPE_UINT);
1052   /**
1053    * GstRtpBin::on-timeout:
1054    * @rtpbin: the object which received the signal
1055    * @session: the session
1056    * @ssrc: the SSRC 
1057    *
1058    * Notify of an SSRC that has timed out
1059    */
1060   gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT] =
1061       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
1062       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_timeout),
1063       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1064       G_TYPE_UINT, G_TYPE_UINT);
1065
1066   gstelement_class->provide_clock =
1067       GST_DEBUG_FUNCPTR (gst_rtp_bin_provide_clock);
1068   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rtp_bin_change_state);
1069   gstelement_class->request_new_pad =
1070       GST_DEBUG_FUNCPTR (gst_rtp_bin_request_new_pad);
1071   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_rtp_bin_release_pad);
1072
1073   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_bin_clear_pt_map);
1074
1075   GST_DEBUG_CATEGORY_INIT (gst_rtp_bin_debug, "rtpbin", 0, "RTP bin");
1076 }
1077
1078 static void
1079 gst_rtp_bin_init (GstRtpBin * rtpbin, GstRtpBinClass * klass)
1080 {
1081   rtpbin->priv = GST_RTP_BIN_GET_PRIVATE (rtpbin);
1082   rtpbin->priv->bin_lock = g_mutex_new ();
1083   rtpbin->provided_clock = gst_system_clock_obtain ();
1084   rtpbin->latency = DEFAULT_LATENCY_MS;
1085 }
1086
1087 static void
1088 gst_rtp_bin_finalize (GObject * object)
1089 {
1090   GstRtpBin *rtpbin;
1091
1092   rtpbin = GST_RTP_BIN (object);
1093
1094   g_mutex_free (rtpbin->priv->bin_lock);
1095
1096   G_OBJECT_CLASS (parent_class)->finalize (object);
1097 }
1098
1099 static void
1100 gst_rtp_bin_set_property (GObject * object, guint prop_id,
1101     const GValue * value, GParamSpec * pspec)
1102 {
1103   GstRtpBin *rtpbin;
1104
1105   rtpbin = GST_RTP_BIN (object);
1106
1107   switch (prop_id) {
1108     case PROP_LATENCY:
1109       rtpbin->latency = g_value_get_uint (value);
1110       break;
1111     default:
1112       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1113       break;
1114   }
1115 }
1116
1117 static void
1118 gst_rtp_bin_get_property (GObject * object, guint prop_id,
1119     GValue * value, GParamSpec * pspec)
1120 {
1121   GstRtpBin *rtpbin;
1122
1123   rtpbin = GST_RTP_BIN (object);
1124
1125   switch (prop_id) {
1126     case PROP_LATENCY:
1127       g_value_set_uint (value, rtpbin->latency);
1128       break;
1129     default:
1130       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1131       break;
1132   }
1133 }
1134
1135 static GstClock *
1136 gst_rtp_bin_provide_clock (GstElement * element)
1137 {
1138   GstRtpBin *rtpbin;
1139
1140   rtpbin = GST_RTP_BIN (element);
1141
1142   return GST_CLOCK_CAST (gst_object_ref (rtpbin->provided_clock));
1143 }
1144
1145 static GstStateChangeReturn
1146 gst_rtp_bin_change_state (GstElement * element, GstStateChange transition)
1147 {
1148   GstStateChangeReturn res;
1149   GstRtpBin *rtpbin;
1150
1151   rtpbin = GST_RTP_BIN (element);
1152
1153   switch (transition) {
1154     case GST_STATE_CHANGE_NULL_TO_READY:
1155       break;
1156     case GST_STATE_CHANGE_READY_TO_PAUSED:
1157       break;
1158     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1159       break;
1160     default:
1161       break;
1162   }
1163
1164   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1165
1166   switch (transition) {
1167     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1168       break;
1169     case GST_STATE_CHANGE_PAUSED_TO_READY:
1170       break;
1171     case GST_STATE_CHANGE_READY_TO_NULL:
1172       break;
1173     default:
1174       break;
1175   }
1176   return res;
1177 }
1178
1179 /* a new pad (SSRC) was created in @session */
1180 static void
1181 new_payload_found (GstElement * element, guint pt, GstPad * pad,
1182     GstRtpBinStream * stream)
1183 {
1184   GstRtpBin *rtpbin;
1185   GstElementClass *klass;
1186   GstPadTemplate *templ;
1187   gchar *padname;
1188   GstPad *gpad;
1189
1190   rtpbin = stream->bin;
1191
1192   GST_DEBUG ("new payload pad %d", pt);
1193
1194   /* ghost the pad to the parent */
1195   klass = GST_ELEMENT_GET_CLASS (rtpbin);
1196   templ = gst_element_class_get_pad_template (klass, "recv_rtp_src_%d_%d_%d");
1197   padname = g_strdup_printf ("recv_rtp_src_%d_%u_%d",
1198       stream->session->id, stream->ssrc, pt);
1199   gpad = gst_ghost_pad_new_from_template (padname, pad, templ);
1200   g_free (padname);
1201
1202   gst_pad_set_active (gpad, TRUE);
1203   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), gpad);
1204 }
1205
1206 static GstCaps *
1207 pt_map_requested (GstElement * element, guint pt, GstRtpBinSession * session)
1208 {
1209   GstRtpBin *rtpbin;
1210   GstCaps *caps;
1211
1212   rtpbin = session->bin;
1213
1214   GST_DEBUG_OBJECT (rtpbin, "payload map requested for pt %d in session %d", pt,
1215       session->id);
1216
1217   caps = get_pt_map (session, pt);
1218   if (!caps)
1219     goto no_caps;
1220
1221   return caps;
1222
1223   /* ERRORS */
1224 no_caps:
1225   {
1226     GST_DEBUG_OBJECT (rtpbin, "could not get caps");
1227     return NULL;
1228   }
1229 }
1230
1231 /* emited when caps changed for the session */
1232 static void
1233 caps_changed (GstPad * pad, GParamSpec * pspec, GstRtpBinSession * session)
1234 {
1235   GstRtpBin *bin;
1236   GstCaps *caps;
1237   gint payload;
1238   const GstStructure *s;
1239
1240   bin = session->bin;
1241
1242   g_object_get (pad, "caps", &caps, NULL);
1243
1244   if (caps == NULL)
1245     return;
1246
1247   GST_DEBUG_OBJECT (bin, "got caps %" GST_PTR_FORMAT, caps);
1248
1249   s = gst_caps_get_structure (caps, 0);
1250
1251   /* get payload, finish when it's not there */
1252   if (!gst_structure_get_int (s, "payload", &payload))
1253     return;
1254
1255   GST_RTP_SESSION_LOCK (session);
1256   GST_DEBUG_OBJECT (bin, "insert caps for payload %d", payload);
1257   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (payload), caps);
1258   GST_RTP_SESSION_UNLOCK (session);
1259 }
1260
1261 /* a new pad (SSRC) was created in @session */
1262 static void
1263 new_ssrc_pad_found (GstElement * element, guint ssrc, GstPad * pad,
1264     GstRtpBinSession * session)
1265 {
1266   GstRtpBinStream *stream;
1267   GstPad *sinkpad, *srcpad;
1268   gchar *padname;
1269   GstCaps *caps;
1270
1271   GST_DEBUG_OBJECT (session->bin, "new SSRC pad %08x", ssrc);
1272
1273   GST_RTP_SESSION_LOCK (session);
1274
1275   /* create new stream */
1276   stream = create_stream (session, ssrc);
1277   if (!stream)
1278     goto no_stream;
1279
1280   /* get the caps of the pad, we need the clock-rate and base_time if any. */
1281   if ((caps = gst_pad_get_caps (pad))) {
1282     const GstStructure *s;
1283     guint val;
1284
1285     GST_DEBUG_OBJECT (session->bin, "pad has caps %" GST_PTR_FORMAT, caps);
1286
1287     s = gst_caps_get_structure (caps, 0);
1288
1289     if (!gst_structure_get_int (s, "clock-rate", &stream->clock_rate))
1290       stream->clock_rate = -1;
1291
1292     if (gst_structure_get_uint (s, "clock-base", &val))
1293       stream->clock_base = val;
1294     else
1295       stream->clock_base = -1;
1296   }
1297
1298   /* get pad and link */
1299   GST_DEBUG_OBJECT (session->bin, "linking jitterbuffer");
1300   sinkpad = gst_element_get_static_pad (stream->buffer, "sink");
1301   gst_pad_link (pad, sinkpad);
1302   gst_object_unref (sinkpad);
1303
1304   /* get the RTCP sync pad */
1305   GST_DEBUG_OBJECT (session->bin, "linking sync pad");
1306   padname = g_strdup_printf ("rtcp_src_%d", ssrc);
1307   srcpad = gst_element_get_pad (element, padname);
1308   g_free (padname);
1309   gst_pad_link (srcpad, stream->sync_pad);
1310   gst_object_unref (srcpad);
1311
1312   /* connect to the new-pad signal of the payload demuxer, this will expose the
1313    * new pad by ghosting it. */
1314   stream->demux_newpad_sig = g_signal_connect (stream->demux,
1315       "new-payload-type", (GCallback) new_payload_found, stream);
1316   /* connect to the request-pt-map signal. This signal will be emited by the
1317    * demuxer so that it can apply a proper caps on the buffers for the
1318    * depayloaders. */
1319   stream->demux_ptreq_sig = g_signal_connect (stream->demux,
1320       "request-pt-map", (GCallback) pt_map_requested, session);
1321
1322   GST_RTP_SESSION_UNLOCK (session);
1323
1324   return;
1325
1326   /* ERRORS */
1327 no_stream:
1328   {
1329     GST_RTP_SESSION_UNLOCK (session);
1330     GST_DEBUG ("could not create stream");
1331     return;
1332   }
1333 }
1334
1335 /* Create a pad for receiving RTP for the session in @name. Must be called with
1336  * RTP_BIN_LOCK.
1337  */
1338 static GstPad *
1339 create_recv_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1340 {
1341   GstPad *result, *sinkdpad;
1342   guint sessid;
1343   GstRtpBinSession *session;
1344   GstPadLinkReturn lres;
1345
1346   /* first get the session number */
1347   if (name == NULL || sscanf (name, "recv_rtp_sink_%d", &sessid) != 1)
1348     goto no_name;
1349
1350   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
1351
1352   /* get or create session */
1353   session = find_session_by_id (rtpbin, sessid);
1354   if (!session) {
1355     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
1356     /* create session now */
1357     session = create_session (rtpbin, sessid);
1358     if (session == NULL)
1359       goto create_error;
1360   }
1361
1362   /* check if pad was requested */
1363   if (session->recv_rtp_sink != NULL)
1364     goto existed;
1365
1366   GST_DEBUG_OBJECT (rtpbin, "getting RTP sink pad");
1367   /* get recv_rtp pad and store */
1368   session->recv_rtp_sink =
1369       gst_element_get_request_pad (session->session, "recv_rtp_sink");
1370   if (session->recv_rtp_sink == NULL)
1371     goto pad_failed;
1372
1373   g_signal_connect (session->recv_rtp_sink, "notify::caps",
1374       (GCallback) caps_changed, session);
1375
1376   GST_DEBUG_OBJECT (rtpbin, "getting RTP src pad");
1377   /* get srcpad, link to SSRCDemux */
1378   session->recv_rtp_src =
1379       gst_element_get_static_pad (session->session, "recv_rtp_src");
1380   if (session->recv_rtp_src == NULL)
1381     goto pad_failed;
1382
1383   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTP sink pad");
1384   sinkdpad = gst_element_get_static_pad (session->demux, "sink");
1385   GST_DEBUG_OBJECT (rtpbin, "linking demuxer RTP sink pad");
1386   lres = gst_pad_link (session->recv_rtp_src, sinkdpad);
1387   gst_object_unref (sinkdpad);
1388   if (lres != GST_PAD_LINK_OK)
1389     goto link_failed;
1390
1391   /* connect to the new-ssrc-pad signal of the SSRC demuxer */
1392   session->demux_newpad_sig = g_signal_connect (session->demux,
1393       "new-ssrc-pad", (GCallback) new_ssrc_pad_found, session);
1394
1395   GST_DEBUG_OBJECT (rtpbin, "ghosting session sink pad");
1396   result =
1397       gst_ghost_pad_new_from_template (name, session->recv_rtp_sink, templ);
1398   gst_pad_set_active (result, TRUE);
1399   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1400
1401   return result;
1402
1403   /* ERRORS */
1404 no_name:
1405   {
1406     g_warning ("gstrtpbin: invalid name given");
1407     return NULL;
1408   }
1409 create_error:
1410   {
1411     /* create_session already warned */
1412     return NULL;
1413   }
1414 existed:
1415   {
1416     g_warning ("gstrtpbin: recv_rtp pad already requested for session %d",
1417         sessid);
1418     return NULL;
1419   }
1420 pad_failed:
1421   {
1422     g_warning ("gstrtpbin: failed to get session pad");
1423     return NULL;
1424   }
1425 link_failed:
1426   {
1427     g_warning ("gstrtpbin: failed to link pads");
1428     return NULL;
1429   }
1430 }
1431
1432 /* Create a pad for receiving RTCP for the session in @name. Must be called with
1433  * RTP_BIN_LOCK.
1434  */
1435 static GstPad *
1436 create_recv_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ,
1437     const gchar * name)
1438 {
1439   GstPad *result;
1440   guint sessid;
1441   GstRtpBinSession *session;
1442   GstPad *sinkdpad;
1443   GstPadLinkReturn lres;
1444
1445   /* first get the session number */
1446   if (name == NULL || sscanf (name, "recv_rtcp_sink_%d", &sessid) != 1)
1447     goto no_name;
1448
1449   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
1450
1451   /* get or create the session */
1452   session = find_session_by_id (rtpbin, sessid);
1453   if (!session) {
1454     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
1455     /* create session now */
1456     session = create_session (rtpbin, sessid);
1457     if (session == NULL)
1458       goto create_error;
1459   }
1460
1461   /* check if pad was requested */
1462   if (session->recv_rtcp_sink != NULL)
1463     goto existed;
1464
1465   /* get recv_rtp pad and store */
1466   GST_DEBUG_OBJECT (rtpbin, "getting RTCP sink pad");
1467   session->recv_rtcp_sink =
1468       gst_element_get_request_pad (session->session, "recv_rtcp_sink");
1469   if (session->recv_rtcp_sink == NULL)
1470     goto pad_failed;
1471
1472   /* get srcpad, link to SSRCDemux */
1473   GST_DEBUG_OBJECT (rtpbin, "getting sync src pad");
1474   session->sync_src = gst_element_get_static_pad (session->session, "sync_src");
1475   if (session->sync_src == NULL)
1476     goto pad_failed;
1477
1478   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTCP sink pad");
1479   sinkdpad = gst_element_get_static_pad (session->demux, "rtcp_sink");
1480   lres = gst_pad_link (session->sync_src, sinkdpad);
1481   gst_object_unref (sinkdpad);
1482   if (lres != GST_PAD_LINK_OK)
1483     goto link_failed;
1484
1485   result =
1486       gst_ghost_pad_new_from_template (name, session->recv_rtcp_sink, templ);
1487   gst_pad_set_active (result, TRUE);
1488   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1489
1490   return result;
1491
1492   /* ERRORS */
1493 no_name:
1494   {
1495     g_warning ("gstrtpbin: invalid name given");
1496     return NULL;
1497   }
1498 create_error:
1499   {
1500     /* create_session already warned */
1501     return NULL;
1502   }
1503 existed:
1504   {
1505     g_warning ("gstrtpbin: recv_rtcp pad already requested for session %d",
1506         sessid);
1507     return NULL;
1508   }
1509 pad_failed:
1510   {
1511     g_warning ("gstrtpbin: failed to get session pad");
1512     return NULL;
1513   }
1514 link_failed:
1515   {
1516     g_warning ("gstrtpbin: failed to link pads");
1517     return NULL;
1518   }
1519 }
1520
1521 /* Create a pad for sending RTP for the session in @name. Must be called with
1522  * RTP_BIN_LOCK.
1523  */
1524 static GstPad *
1525 create_send_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1526 {
1527   GstPad *result, *srcghost;
1528   gchar *gname;
1529   guint sessid;
1530   GstRtpBinSession *session;
1531   GstElementClass *klass;
1532
1533   /* first get the session number */
1534   if (name == NULL || sscanf (name, "send_rtp_sink_%d", &sessid) != 1)
1535     goto no_name;
1536
1537   /* get or create session */
1538   session = find_session_by_id (rtpbin, sessid);
1539   if (!session) {
1540     /* create session now */
1541     session = create_session (rtpbin, sessid);
1542     if (session == NULL)
1543       goto create_error;
1544   }
1545
1546   /* check if pad was requested */
1547   if (session->send_rtp_sink != NULL)
1548     goto existed;
1549
1550   /* get send_rtp pad and store */
1551   session->send_rtp_sink =
1552       gst_element_get_request_pad (session->session, "send_rtp_sink");
1553   if (session->send_rtp_sink == NULL)
1554     goto pad_failed;
1555
1556   g_signal_connect (session->send_rtp_sink, "notify::caps",
1557       (GCallback) caps_changed, session);
1558
1559   result =
1560       gst_ghost_pad_new_from_template (name, session->send_rtp_sink, templ);
1561   gst_pad_set_active (result, TRUE);
1562   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1563
1564   /* get srcpad */
1565   session->send_rtp_src =
1566       gst_element_get_static_pad (session->session, "send_rtp_src");
1567   if (session->send_rtp_src == NULL)
1568     goto no_srcpad;
1569
1570   /* ghost the new source pad */
1571   klass = GST_ELEMENT_GET_CLASS (rtpbin);
1572   gname = g_strdup_printf ("send_rtp_src_%d", sessid);
1573   templ = gst_element_class_get_pad_template (klass, "send_rtp_src_%d");
1574   srcghost =
1575       gst_ghost_pad_new_from_template (gname, session->send_rtp_src, templ);
1576   gst_pad_set_active (srcghost, TRUE);
1577   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), srcghost);
1578   g_free (gname);
1579
1580   return result;
1581
1582   /* ERRORS */
1583 no_name:
1584   {
1585     g_warning ("gstrtpbin: invalid name given");
1586     return NULL;
1587   }
1588 create_error:
1589   {
1590     /* create_session already warned */
1591     return NULL;
1592   }
1593 existed:
1594   {
1595     g_warning ("gstrtpbin: send_rtp pad already requested for session %d",
1596         sessid);
1597     return NULL;
1598   }
1599 pad_failed:
1600   {
1601     g_warning ("gstrtpbin: failed to get session pad for session %d", sessid);
1602     return NULL;
1603   }
1604 no_srcpad:
1605   {
1606     g_warning ("gstrtpbin: failed to get rtp source pad for session %d",
1607         sessid);
1608     return NULL;
1609   }
1610 }
1611
1612 /* Create a pad for sending RTCP for the session in @name. Must be called with
1613  * RTP_BIN_LOCK.
1614  */
1615 static GstPad *
1616 create_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1617 {
1618   GstPad *result;
1619   guint sessid;
1620   GstRtpBinSession *session;
1621
1622   /* first get the session number */
1623   if (name == NULL || sscanf (name, "send_rtcp_src_%d", &sessid) != 1)
1624     goto no_name;
1625
1626   /* get or create session */
1627   session = find_session_by_id (rtpbin, sessid);
1628   if (!session)
1629     goto no_session;
1630
1631   /* check if pad was requested */
1632   if (session->send_rtcp_src != NULL)
1633     goto existed;
1634
1635   /* get rtcp_src pad and store */
1636   session->send_rtcp_src =
1637       gst_element_get_request_pad (session->session, "send_rtcp_src");
1638   if (session->send_rtcp_src == NULL)
1639     goto pad_failed;
1640
1641   result =
1642       gst_ghost_pad_new_from_template (name, session->send_rtcp_src, templ);
1643   gst_pad_set_active (result, TRUE);
1644   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1645
1646   return result;
1647
1648   /* ERRORS */
1649 no_name:
1650   {
1651     g_warning ("gstrtpbin: invalid name given");
1652     return NULL;
1653   }
1654 no_session:
1655   {
1656     g_warning ("gstrtpbin: session with id %d does not exist", sessid);
1657     return NULL;
1658   }
1659 existed:
1660   {
1661     g_warning ("gstrtpbin: send_rtcp_src pad already requested for session %d",
1662         sessid);
1663     return NULL;
1664   }
1665 pad_failed:
1666   {
1667     g_warning ("gstrtpbin: failed to get rtcp pad for session %d", sessid);
1668     return NULL;
1669   }
1670 }
1671
1672 /* 
1673  */
1674 static GstPad *
1675 gst_rtp_bin_request_new_pad (GstElement * element,
1676     GstPadTemplate * templ, const gchar * name)
1677 {
1678   GstRtpBin *rtpbin;
1679   GstElementClass *klass;
1680   GstPad *result;
1681
1682   g_return_val_if_fail (templ != NULL, NULL);
1683   g_return_val_if_fail (GST_IS_RTP_BIN (element), NULL);
1684
1685   rtpbin = GST_RTP_BIN (element);
1686   klass = GST_ELEMENT_GET_CLASS (element);
1687
1688   GST_RTP_BIN_LOCK (rtpbin);
1689
1690   /* figure out the template */
1691   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink_%d")) {
1692     result = create_recv_rtp (rtpbin, templ, name);
1693   } else if (templ == gst_element_class_get_pad_template (klass,
1694           "recv_rtcp_sink_%d")) {
1695     result = create_recv_rtcp (rtpbin, templ, name);
1696   } else if (templ == gst_element_class_get_pad_template (klass,
1697           "send_rtp_sink_%d")) {
1698     result = create_send_rtp (rtpbin, templ, name);
1699   } else if (templ == gst_element_class_get_pad_template (klass,
1700           "send_rtcp_src_%d")) {
1701     result = create_rtcp (rtpbin, templ, name);
1702   } else
1703     goto wrong_template;
1704
1705   GST_RTP_BIN_UNLOCK (rtpbin);
1706
1707   return result;
1708
1709   /* ERRORS */
1710 wrong_template:
1711   {
1712     GST_RTP_BIN_UNLOCK (rtpbin);
1713     g_warning ("gstrtpbin: this is not our template");
1714     return NULL;
1715   }
1716 }
1717
1718 static void
1719 gst_rtp_bin_release_pad (GstElement * element, GstPad * pad)
1720 {
1721 }