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