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