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