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