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