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