Merge branch 'master' into 0.11
[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  * @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  * #GstRtpPtDemux element. The #GstRtpPtDemux 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  * Access to the internal statistics of gstrtpbin is provided with the
62  * get-internal-session property. This action signal gives access to the
63  * RTPSession object which further provides action signals to retrieve the
64  * internal source and other sources.
65  *
66  * <refsect2>
67  * <title>Example pipelines</title>
68  * |[
69  * gst-launch udpsrc port=5000 caps="application/x-rtp, ..." ! .recv_rtp_sink_0 \
70  *     gstrtpbin ! rtptheoradepay ! theoradec ! xvimagesink
71  * ]| Receive RTP data from port 5000 and send to the session 0 in gstrtpbin.
72  * |[
73  * gst-launch gstrtpbin name=rtpbin \
74  *         v4l2src ! ffmpegcolorspace ! ffenc_h263 ! rtph263ppay ! rtpbin.send_rtp_sink_0 \
75  *                   rtpbin.send_rtp_src_0 ! udpsink port=5000                            \
76  *                   rtpbin.send_rtcp_src_0 ! udpsink port=5001 sync=false async=false    \
77  *                   udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0                           \
78  *         audiotestsrc ! amrnbenc ! rtpamrpay ! rtpbin.send_rtp_sink_1                   \
79  *                   rtpbin.send_rtp_src_1 ! udpsink port=5002                            \
80  *                   rtpbin.send_rtcp_src_1 ! udpsink port=5003 sync=false async=false    \
81  *                   udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1
82  * ]| Encode and payload H263 video captured from a v4l2src. Encode and payload AMR
83  * audio generated from audiotestsrc. The video is sent to session 0 in rtpbin
84  * and the audio is sent to session 1. Video packets are sent on UDP port 5000
85  * and audio packets on port 5002. The video RTCP packets for session 0 are sent
86  * on port 5001 and the audio RTCP packets for session 0 are sent on port 5003.
87  * RTCP packets for session 0 are received on port 5005 and RTCP for session 1
88  * is received on port 5007. Since RTCP packets from the sender should be sent
89  * as soon as possible and do not participate in preroll, sync=false and
90  * async=false is configured on udpsink
91  * |[
92  * gst-launch -v gstrtpbin name=rtpbin                                          \
93  *     udpsrc caps="application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)H263-1998" \
94  *             port=5000 ! rtpbin.recv_rtp_sink_0                                \
95  *         rtpbin. ! rtph263pdepay ! ffdec_h263 ! xvimagesink                    \
96  *      udpsrc port=5001 ! rtpbin.recv_rtcp_sink_0                               \
97  *      rtpbin.send_rtcp_src_0 ! udpsink port=5005 sync=false async=false        \
98  *     udpsrc caps="application/x-rtp,media=(string)audio,clock-rate=(int)8000,encoding-name=(string)AMR,encoding-params=(string)1,octet-align=(string)1" \
99  *             port=5002 ! rtpbin.recv_rtp_sink_1                                \
100  *         rtpbin. ! rtpamrdepay ! amrnbdec ! alsasink                           \
101  *      udpsrc port=5003 ! rtpbin.recv_rtcp_sink_1                               \
102  *      rtpbin.send_rtcp_src_1 ! udpsink port=5007 sync=false async=false
103  * ]| Receive H263 on port 5000, send it through rtpbin in session 0, depayload,
104  * decode and display the video.
105  * Receive AMR on port 5002, send it through rtpbin in session 1, depayload,
106  * decode and play the audio.
107  * Receive server RTCP packets for session 0 on port 5001 and RTCP packets for
108  * session 1 on port 5003. These packets will be used for session management and
109  * synchronisation.
110  * Send RTCP reports for session 0 on port 5005 and RTCP reports for session 1
111  * on port 5007.
112  * </refsect2>
113  *
114  * Last reviewed on 2007-08-30 (0.10.6)
115  */
116
117 #ifdef HAVE_CONFIG_H
118 #include "config.h"
119 #endif
120 #include <stdio.h>
121 #include <string.h>
122
123 #include <gst/rtp/gstrtpbuffer.h>
124 #include <gst/rtp/gstrtcpbuffer.h>
125
126 #include "gstrtpbin-marshal.h"
127 #include "gstrtpbin.h"
128 #include "rtpsession.h"
129 #include "gstrtpsession.h"
130 #include "gstrtpjitterbuffer.h"
131
132 GST_DEBUG_CATEGORY_STATIC (gst_rtp_bin_debug);
133 #define GST_CAT_DEFAULT gst_rtp_bin_debug
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   /* if we are shutting down or not */
213   gint shutdown;
214
215   gboolean autoremove;
216
217   /* UNIX (ntp) time of last SR sync used */
218   guint64 last_unix;
219 };
220
221 /* signals and args */
222 enum
223 {
224   SIGNAL_REQUEST_PT_MAP,
225   SIGNAL_PAYLOAD_TYPE_CHANGE,
226   SIGNAL_CLEAR_PT_MAP,
227   SIGNAL_RESET_SYNC,
228   SIGNAL_GET_INTERNAL_SESSION,
229
230   SIGNAL_ON_NEW_SSRC,
231   SIGNAL_ON_SSRC_COLLISION,
232   SIGNAL_ON_SSRC_VALIDATED,
233   SIGNAL_ON_SSRC_ACTIVE,
234   SIGNAL_ON_SSRC_SDES,
235   SIGNAL_ON_BYE_SSRC,
236   SIGNAL_ON_BYE_TIMEOUT,
237   SIGNAL_ON_TIMEOUT,
238   SIGNAL_ON_SENDER_TIMEOUT,
239   SIGNAL_ON_NPT_STOP,
240   LAST_SIGNAL
241 };
242
243 #define DEFAULT_LATENCY_MS           200
244 #define DEFAULT_SDES                 NULL
245 #define DEFAULT_DO_LOST              FALSE
246 #define DEFAULT_IGNORE_PT            FALSE
247 #define DEFAULT_NTP_SYNC             FALSE
248 #define DEFAULT_AUTOREMOVE           FALSE
249 #define DEFAULT_BUFFER_MODE          RTP_JITTER_BUFFER_MODE_SLAVE
250 #define DEFAULT_USE_PIPELINE_CLOCK   FALSE
251 #define DEFAULT_RTCP_SYNC            GST_RTP_BIN_RTCP_SYNC_ALWAYS
252 #define DEFAULT_RTCP_SYNC_INTERVAL   0
253
254 enum
255 {
256   PROP_0,
257   PROP_LATENCY,
258   PROP_SDES,
259   PROP_DO_LOST,
260   PROP_IGNORE_PT,
261   PROP_NTP_SYNC,
262   PROP_RTCP_SYNC,
263   PROP_RTCP_SYNC_INTERVAL,
264   PROP_AUTOREMOVE,
265   PROP_BUFFER_MODE,
266   PROP_USE_PIPELINE_CLOCK,
267   PROP_LAST
268 };
269
270 enum
271 {
272   GST_RTP_BIN_RTCP_SYNC_ALWAYS,
273   GST_RTP_BIN_RTCP_SYNC_INITIAL,
274   GST_RTP_BIN_RTCP_SYNC_RTP
275 };
276
277 #define GST_RTP_BIN_RTCP_SYNC_TYPE (gst_rtp_bin_rtcp_sync_get_type())
278 static GType
279 gst_rtp_bin_rtcp_sync_get_type (void)
280 {
281   static GType rtcp_sync_type = 0;
282   static const GEnumValue rtcp_sync_types[] = {
283     {GST_RTP_BIN_RTCP_SYNC_ALWAYS, "always", "always"},
284     {GST_RTP_BIN_RTCP_SYNC_INITIAL, "initial", "initial"},
285     {GST_RTP_BIN_RTCP_SYNC_RTP, "rtp-info", "rtp-info"},
286     {0, NULL, NULL},
287   };
288
289   if (!rtcp_sync_type) {
290     rtcp_sync_type = g_enum_register_static ("GstRTCPSync", rtcp_sync_types);
291   }
292   return rtcp_sync_type;
293 }
294
295 /* helper objects */
296 typedef struct _GstRtpBinSession GstRtpBinSession;
297 typedef struct _GstRtpBinStream GstRtpBinStream;
298 typedef struct _GstRtpBinClient GstRtpBinClient;
299
300 static guint gst_rtp_bin_signals[LAST_SIGNAL] = { 0 };
301
302 static GstCaps *pt_map_requested (GstElement * element, guint pt,
303     GstRtpBinSession * session);
304 static void payload_type_change (GstElement * element, guint pt,
305     GstRtpBinSession * session);
306 static void free_client (GstRtpBinClient * client, GstRtpBin * bin);
307 static void free_stream (GstRtpBinStream * stream);
308
309 /* Manages the RTP stream for one SSRC.
310  *
311  * We pipe the stream (comming from the SSRC demuxer) into a jitterbuffer.
312  * If we see an SDES RTCP packet that links multiple SSRCs together based on a
313  * common CNAME, we create a GstRtpBinClient structure to group the SSRCs
314  * together (see below).
315  */
316 struct _GstRtpBinStream
317 {
318   /* the SSRC of this stream */
319   guint32 ssrc;
320
321   /* parent bin */
322   GstRtpBin *bin;
323
324   /* the session this SSRC belongs to */
325   GstRtpBinSession *session;
326
327   /* the jitterbuffer of the SSRC */
328   GstElement *buffer;
329   gulong buffer_handlesync_sig;
330   gulong buffer_ptreq_sig;
331   gulong buffer_ntpstop_sig;
332   gint percent;
333
334   /* the PT demuxer of the SSRC */
335   GstElement *demux;
336   gulong demux_newpad_sig;
337   gulong demux_padremoved_sig;
338   gulong demux_ptreq_sig;
339   gulong demux_ptchange_sig;
340
341   /* if we have calculated a valid rt_delta for this stream */
342   gboolean have_sync;
343   /* mapping to local RTP and NTP time */
344   gint64 rt_delta;
345   gint64 rtp_delta;
346   /* base rtptime in gst time */
347   gint64 clock_base;
348 };
349
350 #define GST_RTP_SESSION_LOCK(sess)   g_mutex_lock ((sess)->lock)
351 #define GST_RTP_SESSION_UNLOCK(sess) g_mutex_unlock ((sess)->lock)
352
353 /* Manages the receiving end of the packets.
354  *
355  * There is one such structure for each RTP session (audio/video/...).
356  * We get the RTP/RTCP packets and stuff them into the session manager. From
357  * there they are pushed into an SSRC demuxer that splits the stream based on
358  * SSRC. Each of the SSRC streams go into their own jitterbuffer (managed with
359  * the GstRtpBinStream above).
360  */
361 struct _GstRtpBinSession
362 {
363   /* session id */
364   gint id;
365   /* the parent bin */
366   GstRtpBin *bin;
367   /* the session element */
368   GstElement *session;
369   /* the SSRC demuxer */
370   GstElement *demux;
371   gulong demux_newpad_sig;
372   gulong demux_padremoved_sig;
373
374   GMutex *lock;
375
376   /* list of GstRtpBinStream */
377   GSList *streams;
378
379   /* mapping of payload type to caps */
380   GHashTable *ptmap;
381
382   /* the pads of the session */
383   GstPad *recv_rtp_sink;
384   GstPad *recv_rtp_sink_ghost;
385   GstPad *recv_rtp_src;
386   GstPad *recv_rtcp_sink;
387   GstPad *recv_rtcp_sink_ghost;
388   GstPad *sync_src;
389   GstPad *send_rtp_sink;
390   GstPad *send_rtp_sink_ghost;
391   GstPad *send_rtp_src;
392   GstPad *send_rtp_src_ghost;
393   GstPad *send_rtcp_src;
394   GstPad *send_rtcp_src_ghost;
395 };
396
397 /* Manages the RTP streams that come from one client and should therefore be
398  * synchronized.
399  */
400 struct _GstRtpBinClient
401 {
402   /* the common CNAME for the streams */
403   gchar *cname;
404   guint cname_len;
405
406   /* the streams */
407   guint nstreams;
408   GSList *streams;
409 };
410
411 /* find a session with the given id. Must be called with RTP_BIN_LOCK */
412 static GstRtpBinSession *
413 find_session_by_id (GstRtpBin * rtpbin, gint id)
414 {
415   GSList *walk;
416
417   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
418     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
419
420     if (sess->id == id)
421       return sess;
422   }
423   return NULL;
424 }
425
426 /* find a session with the given request pad. Must be called with RTP_BIN_LOCK */
427 static GstRtpBinSession *
428 find_session_by_pad (GstRtpBin * rtpbin, GstPad * pad)
429 {
430   GSList *walk;
431
432   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
433     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
434
435     if ((sess->recv_rtp_sink_ghost == pad) ||
436         (sess->recv_rtcp_sink_ghost == pad) ||
437         (sess->send_rtp_sink_ghost == pad)
438         || (sess->send_rtcp_src_ghost == pad))
439       return sess;
440   }
441   return NULL;
442 }
443
444 static void
445 on_new_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
446 {
447   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC], 0,
448       sess->id, ssrc);
449 }
450
451 static void
452 on_ssrc_collision (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
453 {
454   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION], 0,
455       sess->id, ssrc);
456 }
457
458 static void
459 on_ssrc_validated (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
460 {
461   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
462       sess->id, ssrc);
463 }
464
465 static void
466 on_ssrc_active (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
467 {
468   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_ACTIVE], 0,
469       sess->id, ssrc);
470 }
471
472 static void
473 on_ssrc_sdes (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
474 {
475   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_SDES], 0,
476       sess->id, ssrc);
477 }
478
479 static void
480 on_bye_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
481 {
482   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC], 0,
483       sess->id, ssrc);
484 }
485
486 static void
487 on_bye_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
488 {
489   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT], 0,
490       sess->id, ssrc);
491
492   if (sess->bin->priv->autoremove)
493     g_signal_emit_by_name (sess->demux, "clear-ssrc", ssrc, NULL);
494 }
495
496 static void
497 on_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
498 {
499   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT], 0,
500       sess->id, ssrc);
501
502   if (sess->bin->priv->autoremove)
503     g_signal_emit_by_name (sess->demux, "clear-ssrc", ssrc, NULL);
504 }
505
506 static void
507 on_sender_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
508 {
509   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SENDER_TIMEOUT], 0,
510       sess->id, ssrc);
511 }
512
513 static void
514 on_npt_stop (GstElement * jbuf, GstRtpBinStream * stream)
515 {
516   g_signal_emit (stream->bin, gst_rtp_bin_signals[SIGNAL_ON_NPT_STOP], 0,
517       stream->session->id, stream->ssrc);
518 }
519
520 /* must be called with the SESSION lock */
521 static GstRtpBinStream *
522 find_stream_by_ssrc (GstRtpBinSession * session, guint32 ssrc)
523 {
524   GSList *walk;
525
526   for (walk = session->streams; walk; walk = g_slist_next (walk)) {
527     GstRtpBinStream *stream = (GstRtpBinStream *) walk->data;
528
529     if (stream->ssrc == ssrc)
530       return stream;
531   }
532   return NULL;
533 }
534
535 static void
536 ssrc_demux_pad_removed (GstElement * element, guint ssrc, GstPad * pad,
537     GstRtpBinSession * session)
538 {
539   GstRtpBinStream *stream = NULL;
540
541   GST_RTP_SESSION_LOCK (session);
542   if ((stream = find_stream_by_ssrc (session, ssrc)))
543     session->streams = g_slist_remove (session->streams, stream);
544   GST_RTP_SESSION_UNLOCK (session);
545
546   if (stream)
547     free_stream (stream);
548 }
549
550 /* create a session with the given id.  Must be called with RTP_BIN_LOCK */
551 static GstRtpBinSession *
552 create_session (GstRtpBin * rtpbin, gint id)
553 {
554   GstRtpBinSession *sess;
555   GstElement *session, *demux;
556   GstState target;
557
558   if (!(session = gst_element_factory_make ("gstrtpsession", NULL)))
559     goto no_session;
560
561   if (!(demux = gst_element_factory_make ("gstrtpssrcdemux", NULL)))
562     goto no_demux;
563
564   sess = g_new0 (GstRtpBinSession, 1);
565   sess->lock = g_mutex_new ();
566   sess->id = id;
567   sess->bin = rtpbin;
568   sess->session = session;
569   sess->demux = demux;
570   sess->ptmap = g_hash_table_new_full (NULL, NULL, NULL,
571       (GDestroyNotify) gst_caps_unref);
572   rtpbin->sessions = g_slist_prepend (rtpbin->sessions, sess);
573
574   /* configure SDES items */
575   GST_OBJECT_LOCK (rtpbin);
576   g_object_set (session, "sdes", rtpbin->sdes, "use-pipeline-clock",
577       rtpbin->use_pipeline_clock, NULL);
578   GST_OBJECT_UNLOCK (rtpbin);
579
580   /* provide clock_rate to the session manager when needed */
581   g_signal_connect (session, "request-pt-map",
582       (GCallback) pt_map_requested, sess);
583
584   g_signal_connect (sess->session, "on-new-ssrc",
585       (GCallback) on_new_ssrc, sess);
586   g_signal_connect (sess->session, "on-ssrc-collision",
587       (GCallback) on_ssrc_collision, sess);
588   g_signal_connect (sess->session, "on-ssrc-validated",
589       (GCallback) on_ssrc_validated, sess);
590   g_signal_connect (sess->session, "on-ssrc-active",
591       (GCallback) on_ssrc_active, sess);
592   g_signal_connect (sess->session, "on-ssrc-sdes",
593       (GCallback) on_ssrc_sdes, sess);
594   g_signal_connect (sess->session, "on-bye-ssrc",
595       (GCallback) on_bye_ssrc, sess);
596   g_signal_connect (sess->session, "on-bye-timeout",
597       (GCallback) on_bye_timeout, sess);
598   g_signal_connect (sess->session, "on-timeout", (GCallback) on_timeout, sess);
599   g_signal_connect (sess->session, "on-sender-timeout",
600       (GCallback) on_sender_timeout, sess);
601
602   gst_bin_add (GST_BIN_CAST (rtpbin), session);
603   gst_bin_add (GST_BIN_CAST (rtpbin), demux);
604
605   GST_OBJECT_LOCK (rtpbin);
606   target = GST_STATE_TARGET (rtpbin);
607   GST_OBJECT_UNLOCK (rtpbin);
608
609   /* change state only to what's needed */
610   gst_element_set_state (demux, target);
611   gst_element_set_state (session, target);
612
613   return sess;
614
615   /* ERRORS */
616 no_session:
617   {
618     g_warning ("gstrtpbin: could not create gstrtpsession element");
619     return NULL;
620   }
621 no_demux:
622   {
623     gst_object_unref (session);
624     g_warning ("gstrtpbin: could not create gstrtpssrcdemux element");
625     return NULL;
626   }
627 }
628
629 static void
630 free_session (GstRtpBinSession * sess, GstRtpBin * bin)
631 {
632   GSList *client_walk;
633
634   GST_DEBUG_OBJECT (bin, "freeing session %p", sess);
635
636   gst_element_set_locked_state (sess->demux, TRUE);
637   gst_element_set_locked_state (sess->session, TRUE);
638
639   gst_element_set_state (sess->demux, GST_STATE_NULL);
640   gst_element_set_state (sess->session, GST_STATE_NULL);
641
642   if (sess->recv_rtp_sink != NULL) {
643     gst_element_release_request_pad (sess->session, sess->recv_rtp_sink);
644     gst_object_unref (sess->recv_rtp_sink);
645   }
646   if (sess->recv_rtp_src != NULL)
647     gst_object_unref (sess->recv_rtp_src);
648   if (sess->recv_rtcp_sink != NULL) {
649     gst_element_release_request_pad (sess->session, sess->recv_rtcp_sink);
650     gst_object_unref (sess->recv_rtcp_sink);
651   }
652   if (sess->sync_src != NULL)
653     gst_object_unref (sess->sync_src);
654   if (sess->send_rtp_sink != NULL) {
655     gst_element_release_request_pad (sess->session, sess->send_rtp_sink);
656     gst_object_unref (sess->send_rtp_sink);
657   }
658   if (sess->send_rtp_src != NULL)
659     gst_object_unref (sess->send_rtp_src);
660   if (sess->send_rtcp_src != NULL) {
661     gst_element_release_request_pad (sess->session, sess->send_rtcp_src);
662     gst_object_unref (sess->send_rtcp_src);
663   }
664
665   gst_bin_remove (GST_BIN_CAST (bin), sess->session);
666   gst_bin_remove (GST_BIN_CAST (bin), sess->demux);
667
668   /* remove any references in bin->clients to the streams in sess->streams */
669   client_walk = bin->clients;
670   while (client_walk) {
671     GSList *client_node = client_walk;
672     GstRtpBinClient *client = (GstRtpBinClient *) client_node->data;
673     GSList *stream_walk = client->streams;
674
675     while (stream_walk) {
676       GSList *stream_node = stream_walk;
677       GstRtpBinStream *stream = (GstRtpBinStream *) stream_node->data;
678       GSList *inner_walk;
679
680       stream_walk = g_slist_next (stream_walk);
681
682       for (inner_walk = sess->streams; inner_walk;
683           inner_walk = g_slist_next (inner_walk)) {
684         if ((GstRtpBinStream *) inner_walk->data == stream) {
685           client->streams = g_slist_delete_link (client->streams, stream_node);
686           --client->nstreams;
687           break;
688         }
689       }
690     }
691     client_walk = g_slist_next (client_walk);
692
693     g_assert ((client->streams && client->nstreams > 0) || (!client->streams
694             && client->streams == 0));
695     if (client->nstreams == 0) {
696       free_client (client, bin);
697       bin->clients = g_slist_delete_link (bin->clients, client_node);
698     }
699   }
700
701   g_slist_foreach (sess->streams, (GFunc) free_stream, NULL);
702   g_slist_free (sess->streams);
703
704   g_mutex_free (sess->lock);
705   g_hash_table_destroy (sess->ptmap);
706
707   g_free (sess);
708 }
709
710 /* get the payload type caps for the specific payload @pt in @session */
711 static GstCaps *
712 get_pt_map (GstRtpBinSession * session, guint pt)
713 {
714   GstCaps *caps = NULL;
715   GstRtpBin *bin;
716   GValue ret = { 0 };
717   GValue args[3] = { {0}, {0}, {0} };
718
719   GST_DEBUG ("searching pt %d in cache", pt);
720
721   GST_RTP_SESSION_LOCK (session);
722
723   /* first look in the cache */
724   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
725   if (caps) {
726     gst_caps_ref (caps);
727     goto done;
728   }
729
730   bin = session->bin;
731
732   GST_DEBUG ("emiting signal for pt %d in session %d", pt, session->id);
733
734   /* not in cache, send signal to request caps */
735   g_value_init (&args[0], GST_TYPE_ELEMENT);
736   g_value_set_object (&args[0], bin);
737   g_value_init (&args[1], G_TYPE_UINT);
738   g_value_set_uint (&args[1], session->id);
739   g_value_init (&args[2], G_TYPE_UINT);
740   g_value_set_uint (&args[2], pt);
741
742   g_value_init (&ret, GST_TYPE_CAPS);
743   g_value_set_boxed (&ret, NULL);
744
745   GST_RTP_SESSION_UNLOCK (session);
746
747   g_signal_emitv (args, gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP], 0, &ret);
748
749   GST_RTP_SESSION_LOCK (session);
750
751   g_value_unset (&args[0]);
752   g_value_unset (&args[1]);
753   g_value_unset (&args[2]);
754
755   /* look in the cache again because we let the lock go */
756   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
757   if (caps) {
758     gst_caps_ref (caps);
759     g_value_unset (&ret);
760     goto done;
761   }
762
763   caps = (GstCaps *) g_value_dup_boxed (&ret);
764   g_value_unset (&ret);
765   if (!caps)
766     goto no_caps;
767
768   GST_DEBUG ("caching pt %d as %" GST_PTR_FORMAT, pt, caps);
769
770   /* store in cache, take additional ref */
771   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (pt),
772       gst_caps_ref (caps));
773
774 done:
775   GST_RTP_SESSION_UNLOCK (session);
776
777   return caps;
778
779   /* ERRORS */
780 no_caps:
781   {
782     GST_RTP_SESSION_UNLOCK (session);
783     GST_DEBUG ("no pt map could be obtained");
784     return NULL;
785   }
786 }
787
788 static gboolean
789 return_true (gpointer key, gpointer value, gpointer user_data)
790 {
791   return TRUE;
792 }
793
794 static void
795 gst_rtp_bin_reset_sync (GstRtpBin * rtpbin)
796 {
797   GSList *clients, *streams;
798
799   GST_DEBUG_OBJECT (rtpbin, "Reset sync on all clients");
800
801   GST_RTP_BIN_LOCK (rtpbin);
802   for (clients = rtpbin->clients; clients; clients = g_slist_next (clients)) {
803     GstRtpBinClient *client = (GstRtpBinClient *) clients->data;
804
805     /* reset sync on all streams for this client */
806     for (streams = client->streams; streams; streams = g_slist_next (streams)) {
807       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
808
809       /* make use require a new SR packet for this stream before we attempt new
810        * lip-sync */
811       stream->have_sync = FALSE;
812       stream->rt_delta = 0;
813       stream->rtp_delta = 0;
814       stream->clock_base = -100 * GST_SECOND;
815     }
816   }
817   GST_RTP_BIN_UNLOCK (rtpbin);
818 }
819
820 static void
821 gst_rtp_bin_clear_pt_map (GstRtpBin * bin)
822 {
823   GSList *sessions, *streams;
824
825   GST_RTP_BIN_LOCK (bin);
826   GST_DEBUG_OBJECT (bin, "clearing pt map");
827   for (sessions = bin->sessions; sessions; sessions = g_slist_next (sessions)) {
828     GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
829
830     GST_DEBUG_OBJECT (bin, "clearing session %p", session);
831     g_signal_emit_by_name (session->session, "clear-pt-map", NULL);
832
833     GST_RTP_SESSION_LOCK (session);
834     g_hash_table_foreach_remove (session->ptmap, return_true, NULL);
835
836     for (streams = session->streams; streams; streams = g_slist_next (streams)) {
837       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
838
839       GST_DEBUG_OBJECT (bin, "clearing stream %p", stream);
840       g_signal_emit_by_name (stream->buffer, "clear-pt-map", NULL);
841       if (stream->demux)
842         g_signal_emit_by_name (stream->demux, "clear-pt-map", NULL);
843     }
844     GST_RTP_SESSION_UNLOCK (session);
845   }
846   GST_RTP_BIN_UNLOCK (bin);
847
848   /* reset sync too */
849   gst_rtp_bin_reset_sync (bin);
850 }
851
852 static RTPSession *
853 gst_rtp_bin_get_internal_session (GstRtpBin * bin, guint session_id)
854 {
855   RTPSession *internal_session = NULL;
856   GstRtpBinSession *session;
857
858   GST_RTP_BIN_LOCK (bin);
859   GST_DEBUG_OBJECT (bin, "retrieving internal RTPSession object, index: %d",
860       session_id);
861   session = find_session_by_id (bin, (gint) session_id);
862   if (session) {
863     g_object_get (session->session, "internal-session", &internal_session,
864         NULL);
865   }
866   GST_RTP_BIN_UNLOCK (bin);
867
868   return internal_session;
869 }
870
871 static void
872 gst_rtp_bin_propagate_property_to_jitterbuffer (GstRtpBin * bin,
873     const gchar * name, const GValue * value)
874 {
875   GSList *sessions, *streams;
876
877   GST_RTP_BIN_LOCK (bin);
878   for (sessions = bin->sessions; sessions; sessions = g_slist_next (sessions)) {
879     GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
880
881     GST_RTP_SESSION_LOCK (session);
882     for (streams = session->streams; streams; streams = g_slist_next (streams)) {
883       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
884
885       g_object_set_property (G_OBJECT (stream->buffer), name, value);
886     }
887     GST_RTP_SESSION_UNLOCK (session);
888   }
889   GST_RTP_BIN_UNLOCK (bin);
890 }
891
892 /* get a client with the given SDES name. Must be called with RTP_BIN_LOCK */
893 static GstRtpBinClient *
894 get_client (GstRtpBin * bin, guint8 len, guint8 * data, gboolean * created)
895 {
896   GstRtpBinClient *result = NULL;
897   GSList *walk;
898
899   for (walk = bin->clients; walk; walk = g_slist_next (walk)) {
900     GstRtpBinClient *client = (GstRtpBinClient *) walk->data;
901
902     if (len != client->cname_len)
903       continue;
904
905     if (!strncmp ((gchar *) data, client->cname, client->cname_len)) {
906       GST_DEBUG_OBJECT (bin, "found existing client %p with CNAME %s", client,
907           client->cname);
908       result = client;
909       break;
910     }
911   }
912
913   /* nothing found, create one */
914   if (result == NULL) {
915     result = g_new0 (GstRtpBinClient, 1);
916     result->cname = g_strndup ((gchar *) data, len);
917     result->cname_len = len;
918     bin->clients = g_slist_prepend (bin->clients, result);
919     GST_DEBUG_OBJECT (bin, "created new client %p with CNAME %s", result,
920         result->cname);
921   }
922   return result;
923 }
924
925 static void
926 free_client (GstRtpBinClient * client, GstRtpBin * bin)
927 {
928   GST_DEBUG_OBJECT (bin, "freeing client %p", client);
929   g_slist_free (client->streams);
930   g_free (client->cname);
931   g_free (client);
932 }
933
934 static void
935 get_current_times (GstRtpBin * bin, GstClockTime * running_time,
936     guint64 * ntpnstime)
937 {
938   guint64 ntpns;
939   GstClock *clock;
940   GstClockTime base_time, rt, clock_time;
941
942   GST_OBJECT_LOCK (bin);
943   if ((clock = GST_ELEMENT_CLOCK (bin))) {
944     base_time = GST_ELEMENT_CAST (bin)->base_time;
945     gst_object_ref (clock);
946     GST_OBJECT_UNLOCK (bin);
947
948     clock_time = gst_clock_get_time (clock);
949
950     if (bin->use_pipeline_clock) {
951       ntpns = clock_time;
952     } else {
953       GTimeVal current;
954
955       /* get current NTP time */
956       g_get_current_time (&current);
957       ntpns = GST_TIMEVAL_TO_TIME (current);
958     }
959
960     /* add constant to convert from 1970 based time to 1900 based time */
961     ntpns += (2208988800LL * GST_SECOND);
962
963     /* get current clock time and convert to running time */
964     rt = clock_time - base_time;
965
966     gst_object_unref (clock);
967   } else {
968     GST_OBJECT_UNLOCK (bin);
969     rt = -1;
970     ntpns = -1;
971   }
972   if (running_time)
973     *running_time = rt;
974   if (ntpnstime)
975     *ntpnstime = ntpns;
976 }
977
978 static void
979 stream_set_ts_offset (GstRtpBin * bin, GstRtpBinStream * stream,
980     gint64 ts_offset)
981 {
982   gint64 prev_ts_offset;
983
984   g_object_get (stream->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     diff = prev_ts_offset - ts_offset;
991
992     GST_DEBUG_OBJECT (bin,
993         "ts-offset %" G_GINT64_FORMAT ", prev %" G_GINT64_FORMAT
994         ", diff: %" G_GINT64_FORMAT, ts_offset, prev_ts_offset, diff);
995
996     /* only change diff when it changed more than 4 milliseconds. This
997      * compensates for rounding errors in NTP to RTP timestamp
998      * conversions */
999     if (ABS (diff) > 4 * GST_MSECOND) {
1000       if (ABS (diff) < (3 * GST_SECOND)) {
1001         g_object_set (stream->buffer, "ts-offset", ts_offset, NULL);
1002       } else {
1003         GST_WARNING_OBJECT (bin, "offset unusually large, ignoring");
1004       }
1005     } else {
1006       GST_DEBUG_OBJECT (bin, "offset too small, ignoring");
1007     }
1008   }
1009   GST_DEBUG_OBJECT (bin, "stream SSRC %08x, delta %" G_GINT64_FORMAT,
1010       stream->ssrc, ts_offset);
1011 }
1012
1013 /* associate a stream to the given CNAME. This will make sure all streams for
1014  * that CNAME are synchronized together.
1015  * Must be called with GST_RTP_BIN_LOCK */
1016 static void
1017 gst_rtp_bin_associate (GstRtpBin * bin, GstRtpBinStream * stream, guint8 len,
1018     guint8 * data, guint64 ntptime, guint64 last_extrtptime,
1019     guint64 base_rtptime, guint64 base_time, guint clock_rate,
1020     gint64 rtp_clock_base)
1021 {
1022   GstRtpBinClient *client;
1023   gboolean created;
1024   GSList *walk;
1025   guint64 local_rt;
1026   guint64 local_rtp;
1027   GstClockTime running_time;
1028   guint64 ntpnstime;
1029   gint64 ntpdiff, rtdiff;
1030   guint64 last_unix;
1031
1032   /* first find or create the CNAME */
1033   client = get_client (bin, len, data, &created);
1034
1035   /* find stream in the client */
1036   for (walk = client->streams; walk; walk = g_slist_next (walk)) {
1037     GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
1038
1039     if (ostream == stream)
1040       break;
1041   }
1042   /* not found, add it to the list */
1043   if (walk == NULL) {
1044     GST_DEBUG_OBJECT (bin,
1045         "new association of SSRC %08x with client %p with CNAME %s",
1046         stream->ssrc, client, client->cname);
1047     client->streams = g_slist_prepend (client->streams, stream);
1048     client->nstreams++;
1049   } else {
1050     GST_DEBUG_OBJECT (bin,
1051         "found association of SSRC %08x with client %p with CNAME %s",
1052         stream->ssrc, client, client->cname);
1053   }
1054
1055   if (!GST_CLOCK_TIME_IS_VALID (last_extrtptime)) {
1056     GST_DEBUG_OBJECT (bin, "invalidated sync data");
1057     if (bin->rtcp_sync == GST_RTP_BIN_RTCP_SYNC_RTP) {
1058       /* we don't need that data, so carry on,
1059        * but make some values look saner */
1060       last_extrtptime = base_rtptime;
1061     } else {
1062       /* nothing we can do with this data in this case */
1063       GST_DEBUG_OBJECT (bin, "bailing out");
1064       return;
1065     }
1066   }
1067
1068   /* Take the extended rtptime we found in the SR packet and map it to the
1069    * local rtptime. The local rtp time is used to construct timestamps on the
1070    * buffers so we will calculate what running_time corresponds to the RTP
1071    * timestamp in the SR packet. */
1072   local_rtp = last_extrtptime - base_rtptime;
1073
1074   GST_DEBUG_OBJECT (bin,
1075       "base %" G_GUINT64_FORMAT ", extrtptime %" G_GUINT64_FORMAT
1076       ", local RTP %" G_GUINT64_FORMAT ", clock-rate %d, "
1077       "clock-base %" G_GINT64_FORMAT, base_rtptime,
1078       last_extrtptime, local_rtp, clock_rate, rtp_clock_base);
1079
1080   /* calculate local RTP time in gstreamer timestamp, we essentially perform the
1081    * same conversion that a jitterbuffer would use to convert an rtp timestamp
1082    * into a corresponding gstreamer timestamp. Note that the base_time also
1083    * contains the drift between sender and receiver. */
1084   local_rt = gst_util_uint64_scale_int (local_rtp, GST_SECOND, clock_rate);
1085   local_rt += base_time;
1086
1087   /* convert ntptime to unix time since 1900 */
1088   last_unix = gst_util_uint64_scale (ntptime, GST_SECOND,
1089       (G_GINT64_CONSTANT (1) << 32));
1090
1091   stream->have_sync = TRUE;
1092
1093   GST_DEBUG_OBJECT (bin,
1094       "local UNIX %" G_GUINT64_FORMAT ", remote UNIX %" G_GUINT64_FORMAT,
1095       local_rt, last_unix);
1096
1097   /* recalc inter stream playout offset, but only if there is more than one
1098    * stream or we're doing NTP sync. */
1099   if (bin->ntp_sync) {
1100     /* For NTP sync we need to first get a snapshot of running_time and NTP
1101      * time. We know at what running_time we play a certain RTP time, we also
1102      * calculated when we would play the RTP time in the SR packet. Now we need
1103      * to know how the running_time and the NTP time relate to eachother. */
1104     get_current_times (bin, &running_time, &ntpnstime);
1105
1106     /* see how far away the NTP time is. This is the difference between the
1107      * current NTP time and the NTP time in the last SR packet. */
1108     ntpdiff = ntpnstime - last_unix;
1109     /* see how far away the running_time is. This is the difference between the
1110      * current running_time and the running_time of the RTP timestamp in the
1111      * last SR packet. */
1112     rtdiff = running_time - local_rt;
1113
1114     GST_DEBUG_OBJECT (bin,
1115         "NTP time %" G_GUINT64_FORMAT ", last unix %" G_GUINT64_FORMAT,
1116         ntpnstime, last_unix);
1117     GST_DEBUG_OBJECT (bin,
1118         "NTP diff %" G_GINT64_FORMAT ", RT diff %" G_GINT64_FORMAT, ntpdiff,
1119         rtdiff);
1120
1121     /* combine to get the final diff to apply to the running_time */
1122     stream->rt_delta = rtdiff - ntpdiff;
1123
1124     stream_set_ts_offset (bin, stream, stream->rt_delta);
1125   } else {
1126     gint64 min, rtp_min, clock_base = stream->clock_base;
1127     gboolean all_sync, use_rtp;
1128     gboolean rtcp_sync = g_atomic_int_get (&bin->rtcp_sync);
1129
1130     /* calculate delta between server and receiver. last_unix is created by
1131      * converting the ntptime in the last SR packet to a gstreamer timestamp. This
1132      * delta expresses the difference to our timeline and the server timeline. The
1133      * difference in itself doesn't mean much but we can combine the delta of
1134      * multiple streams to create a stream specific offset. */
1135     stream->rt_delta = last_unix - local_rt;
1136
1137     /* calculate the min of all deltas, ignoring streams that did not yet have a
1138      * valid rt_delta because we did not yet receive an SR packet for those
1139      * streams.
1140      * We calculate the mininum because we would like to only apply positive
1141      * offsets to streams, delaying their playback instead of trying to speed up
1142      * other streams (which might be imposible when we have to create negative
1143      * latencies).
1144      * The stream that has the smallest diff is selected as the reference stream,
1145      * all other streams will have a positive offset to this difference. */
1146
1147     /* some alternative setting allow ignoring RTCP as much as possible,
1148      * for servers generating bogus ntp timeline */
1149     min = rtp_min = G_MAXINT64;
1150     use_rtp = FALSE;
1151     if (rtcp_sync == GST_RTP_BIN_RTCP_SYNC_RTP) {
1152       guint64 ext_base;
1153
1154       use_rtp = TRUE;
1155       /* signed version for convienience */
1156       clock_base = base_rtptime;
1157       /* deal with possible wrap-around */
1158       ext_base = base_rtptime;
1159       rtp_clock_base = gst_rtp_buffer_ext_timestamp (&ext_base, rtp_clock_base);
1160       /* sanity check; base rtp and provided clock_base should be close */
1161       if (rtp_clock_base >= clock_base) {
1162         if (rtp_clock_base - clock_base < 10 * clock_rate) {
1163           rtp_clock_base = base_time +
1164               gst_util_uint64_scale_int (rtp_clock_base - clock_base,
1165               GST_SECOND, clock_rate);
1166         } else {
1167           use_rtp = FALSE;
1168         }
1169       } else {
1170         if (clock_base - rtp_clock_base < 10 * clock_rate) {
1171           rtp_clock_base = base_time -
1172               gst_util_uint64_scale_int (clock_base - rtp_clock_base,
1173               GST_SECOND, clock_rate);
1174         } else {
1175           use_rtp = FALSE;
1176         }
1177       }
1178       /* warn and bail for clarity out if no sane values */
1179       if (!use_rtp) {
1180         GST_WARNING_OBJECT (bin, "unable to sync to provided rtptime");
1181         return;
1182       }
1183       /* store to track changes */
1184       clock_base = rtp_clock_base;
1185       /* generate a fake as before,
1186        * now equating rtptime obtained from RTP-Info,
1187        * where the large time represent the otherwise irrelevant npt/ntp time */
1188       stream->rtp_delta = (GST_SECOND << 28) - rtp_clock_base;
1189     }
1190
1191     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
1192       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
1193
1194       if (!ostream->have_sync) {
1195         all_sync = FALSE;
1196         continue;
1197       }
1198
1199       /* change in current stream's base from previously init'ed value
1200        * leads to reset of all stream's base */
1201       if (stream != ostream && stream->clock_base >= 0 &&
1202           (stream->clock_base != clock_base)) {
1203         GST_DEBUG_OBJECT (bin, "reset upon clock base change");
1204         ostream->clock_base = -100 * GST_SECOND;
1205         ostream->rtp_delta = 0;
1206       }
1207
1208       if (ostream->rt_delta < min)
1209         min = ostream->rt_delta;
1210       if (ostream->rtp_delta < rtp_min)
1211         rtp_min = ostream->rtp_delta;
1212     }
1213
1214     /* arrange to re-sync for each stream upon significant change,
1215      * e.g. post-seek */
1216     all_sync = (stream->clock_base == clock_base);
1217     stream->clock_base = clock_base;
1218
1219     /* may need init performed above later on, but nothing more to do now */
1220     if (client->nstreams <= 1)
1221       return;
1222
1223     GST_DEBUG_OBJECT (bin, "client %p min delta %" G_GINT64_FORMAT
1224         " all sync %d", client, min, all_sync);
1225     GST_DEBUG_OBJECT (bin, "rtcp sync mode %d, use_rtp %d", rtcp_sync, use_rtp);
1226
1227     switch (rtcp_sync) {
1228       case GST_RTP_BIN_RTCP_SYNC_RTP:
1229         if (!use_rtp)
1230           break;
1231         GST_DEBUG_OBJECT (bin, "using rtp generated reports; "
1232             "client %p min rtp delta %" G_GINT64_FORMAT, client, rtp_min);
1233         /* fall-through */
1234       case GST_RTP_BIN_RTCP_SYNC_INITIAL:
1235         /* if all have been synced already, do not bother further */
1236         if (all_sync) {
1237           GST_DEBUG_OBJECT (bin, "all streams already synced; done");
1238           return;
1239         }
1240         break;
1241       default:
1242         break;
1243     }
1244
1245     /* bail out if we adjusted recently enough */
1246     if (all_sync && (last_unix - bin->priv->last_unix) <
1247         bin->rtcp_sync_interval * GST_MSECOND) {
1248       GST_DEBUG_OBJECT (bin, "discarding RTCP sender packet for sync; "
1249           "previous sender info too recent "
1250           "(previous UNIX %" G_GUINT64_FORMAT ")", bin->priv->last_unix);
1251       return;
1252     }
1253     bin->priv->last_unix = last_unix;
1254
1255     /* calculate offsets for each stream */
1256     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
1257       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
1258       gint64 ts_offset;
1259
1260       /* ignore streams for which we didn't receive an SR packet yet, we
1261        * can't synchronize them yet. We can however sync other streams just
1262        * fine. */
1263       if (!ostream->have_sync)
1264         continue;
1265
1266       /* calculate offset to our reference stream, this should always give a
1267        * positive number. */
1268       if (use_rtp)
1269         ts_offset = ostream->rtp_delta - rtp_min;
1270       else
1271         ts_offset = ostream->rt_delta - min;
1272
1273       stream_set_ts_offset (bin, ostream, ts_offset);
1274     }
1275   }
1276   return;
1277 }
1278
1279 #define GST_RTCP_BUFFER_FOR_PACKETS(b,buffer,packet) \
1280   for ((b) = gst_rtcp_buffer_get_first_packet ((buffer), (packet)); (b); \
1281           (b) = gst_rtcp_packet_move_to_next ((packet)))
1282
1283 #define GST_RTCP_SDES_FOR_ITEMS(b,packet) \
1284   for ((b) = gst_rtcp_packet_sdes_first_item ((packet)); (b); \
1285           (b) = gst_rtcp_packet_sdes_next_item ((packet)))
1286
1287 #define GST_RTCP_SDES_FOR_ENTRIES(b,packet) \
1288   for ((b) = gst_rtcp_packet_sdes_first_entry ((packet)); (b); \
1289           (b) = gst_rtcp_packet_sdes_next_entry ((packet)))
1290
1291 static void
1292 gst_rtp_bin_handle_sync (GstElement * jitterbuffer, GstStructure * s,
1293     GstRtpBinStream * stream)
1294 {
1295   GstRtpBin *bin;
1296   GstRTCPPacket packet;
1297   guint32 ssrc;
1298   guint64 ntptime;
1299   gboolean have_sr, have_sdes;
1300   gboolean more;
1301   guint64 base_rtptime;
1302   guint64 base_time;
1303   guint clock_rate;
1304   guint64 clock_base;
1305   guint64 extrtptime;
1306   GstBuffer *buffer;
1307   GstRTCPBuffer rtcp = { NULL };
1308
1309   bin = stream->bin;
1310
1311   GST_DEBUG_OBJECT (bin, "sync handler called");
1312
1313   /* get the last relation between the rtp timestamps and the gstreamer
1314    * timestamps. We get this info directly from the jitterbuffer which
1315    * constructs gstreamer timestamps from rtp timestamps and so it know exactly
1316    * what the current situation is. */
1317   base_rtptime =
1318       g_value_get_uint64 (gst_structure_get_value (s, "base-rtptime"));
1319   base_time = g_value_get_uint64 (gst_structure_get_value (s, "base-time"));
1320   clock_rate = g_value_get_uint (gst_structure_get_value (s, "clock-rate"));
1321   clock_base = g_value_get_uint64 (gst_structure_get_value (s, "clock-base"));
1322   extrtptime =
1323       g_value_get_uint64 (gst_structure_get_value (s, "sr-ext-rtptime"));
1324   buffer = gst_value_get_buffer (gst_structure_get_value (s, "sr-buffer"));
1325
1326   have_sr = FALSE;
1327   have_sdes = FALSE;
1328
1329   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
1330
1331   GST_RTCP_BUFFER_FOR_PACKETS (more, &rtcp, &packet) {
1332     /* first packet must be SR or RR or else the validate would have failed */
1333     switch (gst_rtcp_packet_get_type (&packet)) {
1334       case GST_RTCP_TYPE_SR:
1335         /* only parse first. There is only supposed to be one SR in the packet
1336          * but we will deal with malformed packets gracefully */
1337         if (have_sr)
1338           break;
1339         /* get NTP and RTP times */
1340         gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, &ntptime, NULL,
1341             NULL, NULL);
1342
1343         GST_DEBUG_OBJECT (bin, "received sync packet from SSRC %08x", ssrc);
1344         /* ignore SR that is not ours */
1345         if (ssrc != stream->ssrc)
1346           continue;
1347
1348         have_sr = TRUE;
1349         break;
1350       case GST_RTCP_TYPE_SDES:
1351       {
1352         gboolean more_items, more_entries;
1353
1354         /* only deal with first SDES, there is only supposed to be one SDES in
1355          * the RTCP packet but we deal with bad packets gracefully. Also bail
1356          * out if we have not seen an SR item yet. */
1357         if (have_sdes || !have_sr)
1358           break;
1359
1360         GST_RTCP_SDES_FOR_ITEMS (more_items, &packet) {
1361           /* skip items that are not about the SSRC of the sender */
1362           if (gst_rtcp_packet_sdes_get_ssrc (&packet) != ssrc)
1363             continue;
1364
1365           /* find the CNAME entry */
1366           GST_RTCP_SDES_FOR_ENTRIES (more_entries, &packet) {
1367             GstRTCPSDESType type;
1368             guint8 len;
1369             guint8 *data;
1370
1371             gst_rtcp_packet_sdes_get_entry (&packet, &type, &len, &data);
1372
1373             if (type == GST_RTCP_SDES_CNAME) {
1374               GST_RTP_BIN_LOCK (bin);
1375               /* associate the stream to CNAME */
1376               gst_rtp_bin_associate (bin, stream, len, data,
1377                   ntptime, extrtptime, base_rtptime, base_time, clock_rate,
1378                   clock_base);
1379               GST_RTP_BIN_UNLOCK (bin);
1380             }
1381           }
1382         }
1383         have_sdes = TRUE;
1384         break;
1385       }
1386       default:
1387         /* we can ignore these packets */
1388         break;
1389     }
1390   }
1391   gst_rtcp_buffer_unmap (&rtcp);
1392 }
1393
1394 /* create a new stream with @ssrc in @session. Must be called with
1395  * RTP_SESSION_LOCK. */
1396 static GstRtpBinStream *
1397 create_stream (GstRtpBinSession * session, guint32 ssrc)
1398 {
1399   GstElement *buffer, *demux = NULL;
1400   GstRtpBinStream *stream;
1401   GstRtpBin *rtpbin;
1402   GstState target;
1403
1404   rtpbin = session->bin;
1405
1406   if (!(buffer = gst_element_factory_make ("gstrtpjitterbuffer", NULL)))
1407     goto no_jitterbuffer;
1408
1409   if (!rtpbin->ignore_pt)
1410     if (!(demux = gst_element_factory_make ("gstrtpptdemux", NULL)))
1411       goto no_demux;
1412
1413
1414   stream = g_new0 (GstRtpBinStream, 1);
1415   stream->ssrc = ssrc;
1416   stream->bin = rtpbin;
1417   stream->session = session;
1418   stream->buffer = buffer;
1419   stream->demux = demux;
1420
1421   stream->have_sync = FALSE;
1422   stream->rt_delta = 0;
1423   stream->rtp_delta = 0;
1424   stream->percent = 100;
1425   stream->clock_base = -100 * GST_SECOND;
1426   session->streams = g_slist_prepend (session->streams, stream);
1427
1428   /* provide clock_rate to the jitterbuffer when needed */
1429   stream->buffer_ptreq_sig = g_signal_connect (buffer, "request-pt-map",
1430       (GCallback) pt_map_requested, session);
1431   stream->buffer_ntpstop_sig = g_signal_connect (buffer, "on-npt-stop",
1432       (GCallback) on_npt_stop, stream);
1433
1434   g_object_set_data (G_OBJECT (buffer), "GstRTPBin.session", session);
1435   g_object_set_data (G_OBJECT (buffer), "GstRTPBin.stream", stream);
1436
1437   /* configure latency and packet lost */
1438   g_object_set (buffer, "latency", rtpbin->latency_ms, NULL);
1439   g_object_set (buffer, "do-lost", rtpbin->do_lost, NULL);
1440   g_object_set (buffer, "mode", rtpbin->buffer_mode, NULL);
1441
1442   if (!rtpbin->ignore_pt)
1443     gst_bin_add (GST_BIN_CAST (rtpbin), demux);
1444   gst_bin_add (GST_BIN_CAST (rtpbin), buffer);
1445
1446   /* link stuff */
1447   if (demux)
1448     gst_element_link (buffer, demux);
1449
1450   if (rtpbin->buffering) {
1451     guint64 last_out;
1452
1453     GST_INFO_OBJECT (rtpbin,
1454         "bin is buffering, set jitterbuffer as not active");
1455     g_signal_emit_by_name (buffer, "set-active", FALSE, (gint64) 0, &last_out);
1456   }
1457
1458
1459   GST_OBJECT_LOCK (rtpbin);
1460   target = GST_STATE_TARGET (rtpbin);
1461   GST_OBJECT_UNLOCK (rtpbin);
1462
1463   /* from sink to source */
1464   if (demux)
1465     gst_element_set_state (demux, target);
1466
1467   gst_element_set_state (buffer, target);
1468
1469   return stream;
1470
1471   /* ERRORS */
1472 no_jitterbuffer:
1473   {
1474     g_warning ("gstrtpbin: could not create gstrtpjitterbuffer element");
1475     return NULL;
1476   }
1477 no_demux:
1478   {
1479     gst_object_unref (buffer);
1480     g_warning ("gstrtpbin: could not create gstrtpptdemux element");
1481     return NULL;
1482   }
1483 }
1484
1485 static void
1486 free_stream (GstRtpBinStream * stream)
1487 {
1488   GstRtpBinSession *session;
1489
1490   session = stream->session;
1491
1492   if (stream->demux) {
1493     g_signal_handler_disconnect (stream->demux, stream->demux_newpad_sig);
1494     g_signal_handler_disconnect (stream->demux, stream->demux_ptreq_sig);
1495     g_signal_handler_disconnect (stream->demux, stream->demux_ptchange_sig);
1496   }
1497   g_signal_handler_disconnect (stream->buffer, stream->buffer_handlesync_sig);
1498   g_signal_handler_disconnect (stream->buffer, stream->buffer_ptreq_sig);
1499   g_signal_handler_disconnect (stream->buffer, stream->buffer_ntpstop_sig);
1500
1501   if (stream->demux)
1502     gst_element_set_locked_state (stream->demux, TRUE);
1503   gst_element_set_locked_state (stream->buffer, TRUE);
1504
1505   if (stream->demux)
1506     gst_element_set_state (stream->demux, GST_STATE_NULL);
1507   gst_element_set_state (stream->buffer, GST_STATE_NULL);
1508
1509   /* now remove this signal, we need this while going to NULL because it to
1510    * do some cleanups */
1511   if (stream->demux)
1512     g_signal_handler_disconnect (stream->demux, stream->demux_padremoved_sig);
1513
1514   gst_bin_remove (GST_BIN_CAST (session->bin), stream->buffer);
1515   if (stream->demux)
1516     gst_bin_remove (GST_BIN_CAST (session->bin), stream->demux);
1517
1518   g_free (stream);
1519 }
1520
1521 /* GObject vmethods */
1522 static void gst_rtp_bin_dispose (GObject * object);
1523 static void gst_rtp_bin_finalize (GObject * object);
1524 static void gst_rtp_bin_set_property (GObject * object, guint prop_id,
1525     const GValue * value, GParamSpec * pspec);
1526 static void gst_rtp_bin_get_property (GObject * object, guint prop_id,
1527     GValue * value, GParamSpec * pspec);
1528
1529 /* GstElement vmethods */
1530 static GstStateChangeReturn gst_rtp_bin_change_state (GstElement * element,
1531     GstStateChange transition);
1532 static GstPad *gst_rtp_bin_request_new_pad (GstElement * element,
1533     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
1534 static void gst_rtp_bin_release_pad (GstElement * element, GstPad * pad);
1535 static void gst_rtp_bin_handle_message (GstBin * bin, GstMessage * message);
1536
1537 #define gst_rtp_bin_parent_class parent_class
1538 G_DEFINE_TYPE (GstRtpBin, gst_rtp_bin, GST_TYPE_BIN);
1539
1540 static void
1541 gst_rtp_bin_class_init (GstRtpBinClass * klass)
1542 {
1543   GObjectClass *gobject_class;
1544   GstElementClass *gstelement_class;
1545   GstBinClass *gstbin_class;
1546
1547   gobject_class = (GObjectClass *) klass;
1548   gstelement_class = (GstElementClass *) klass;
1549   gstbin_class = (GstBinClass *) klass;
1550
1551   g_type_class_add_private (klass, sizeof (GstRtpBinPrivate));
1552
1553   gobject_class->dispose = gst_rtp_bin_dispose;
1554   gobject_class->finalize = gst_rtp_bin_finalize;
1555   gobject_class->set_property = gst_rtp_bin_set_property;
1556   gobject_class->get_property = gst_rtp_bin_get_property;
1557
1558   g_object_class_install_property (gobject_class, PROP_LATENCY,
1559       g_param_spec_uint ("latency", "Buffer latency in ms",
1560           "Default amount of ms to buffer in the jitterbuffers", 0,
1561           G_MAXUINT, DEFAULT_LATENCY_MS,
1562           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1563
1564   /**
1565    * GstRtpBin::request-pt-map:
1566    * @rtpbin: the object which received the signal
1567    * @session: the session
1568    * @pt: the pt
1569    *
1570    * Request the payload type as #GstCaps for @pt in @session.
1571    */
1572   gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP] =
1573       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
1574       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, request_pt_map),
1575       NULL, NULL, gst_rtp_bin_marshal_BOXED__UINT_UINT, GST_TYPE_CAPS, 2,
1576       G_TYPE_UINT, G_TYPE_UINT);
1577
1578     /**
1579    * GstRtpBin::payload-type-change:
1580    * @rtpbin: the object which received the signal
1581    * @session: the session
1582    * @pt: the pt
1583    *
1584    * Signal that the current payload type changed to @pt in @session.
1585    *
1586    * Since: 0.10.17
1587    */
1588   gst_rtp_bin_signals[SIGNAL_PAYLOAD_TYPE_CHANGE] =
1589       g_signal_new ("payload-type-change", G_TYPE_FROM_CLASS (klass),
1590       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, payload_type_change),
1591       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1592       G_TYPE_UINT, G_TYPE_UINT);
1593
1594   /**
1595    * GstRtpBin::clear-pt-map:
1596    * @rtpbin: the object which received the signal
1597    *
1598    * Clear all previously cached pt-mapping obtained with
1599    * #GstRtpBin::request-pt-map.
1600    */
1601   gst_rtp_bin_signals[SIGNAL_CLEAR_PT_MAP] =
1602       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
1603       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
1604           clear_pt_map), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
1605       0, G_TYPE_NONE);
1606
1607   /**
1608    * GstRtpBin::reset-sync:
1609    * @rtpbin: the object which received the signal
1610    *
1611    * Reset all currently configured lip-sync parameters and require new SR
1612    * packets for all streams before lip-sync is attempted again.
1613    */
1614   gst_rtp_bin_signals[SIGNAL_RESET_SYNC] =
1615       g_signal_new ("reset-sync", G_TYPE_FROM_CLASS (klass),
1616       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
1617           reset_sync), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
1618       0, G_TYPE_NONE);
1619
1620   /**
1621    * GstRtpBin::get-internal-session:
1622    * @rtpbin: the object which received the signal
1623    * @id: the session id
1624    *
1625    * Request the internal RTPSession object as #GObject in session @id.
1626    */
1627   gst_rtp_bin_signals[SIGNAL_GET_INTERNAL_SESSION] =
1628       g_signal_new ("get-internal-session", G_TYPE_FROM_CLASS (klass),
1629       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
1630           get_internal_session), NULL, NULL, gst_rtp_bin_marshal_OBJECT__UINT,
1631       RTP_TYPE_SESSION, 1, G_TYPE_UINT);
1632
1633   /**
1634    * GstRtpBin::on-new-ssrc:
1635    * @rtpbin: the object which received the signal
1636    * @session: the session
1637    * @ssrc: the SSRC
1638    *
1639    * Notify of a new SSRC that entered @session.
1640    */
1641   gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC] =
1642       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
1643       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_new_ssrc),
1644       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1645       G_TYPE_UINT, G_TYPE_UINT);
1646   /**
1647    * GstRtpBin::on-ssrc-collision:
1648    * @rtpbin: the object which received the signal
1649    * @session: the session
1650    * @ssrc: the SSRC
1651    *
1652    * Notify when we have an SSRC collision
1653    */
1654   gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION] =
1655       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
1656       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_collision),
1657       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1658       G_TYPE_UINT, G_TYPE_UINT);
1659   /**
1660    * GstRtpBin::on-ssrc-validated:
1661    * @rtpbin: the object which received the signal
1662    * @session: the session
1663    * @ssrc: the SSRC
1664    *
1665    * Notify of a new SSRC that became validated.
1666    */
1667   gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED] =
1668       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
1669       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_validated),
1670       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1671       G_TYPE_UINT, G_TYPE_UINT);
1672   /**
1673    * GstRtpBin::on-ssrc-active:
1674    * @rtpbin: the object which received the signal
1675    * @session: the session
1676    * @ssrc: the SSRC
1677    *
1678    * Notify of a SSRC that is active, i.e., sending RTCP.
1679    */
1680   gst_rtp_bin_signals[SIGNAL_ON_SSRC_ACTIVE] =
1681       g_signal_new ("on-ssrc-active", G_TYPE_FROM_CLASS (klass),
1682       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_active),
1683       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1684       G_TYPE_UINT, G_TYPE_UINT);
1685   /**
1686    * GstRtpBin::on-ssrc-sdes:
1687    * @rtpbin: the object which received the signal
1688    * @session: the session
1689    * @ssrc: the SSRC
1690    *
1691    * Notify of a SSRC that is active, i.e., sending RTCP.
1692    */
1693   gst_rtp_bin_signals[SIGNAL_ON_SSRC_SDES] =
1694       g_signal_new ("on-ssrc-sdes", G_TYPE_FROM_CLASS (klass),
1695       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_sdes),
1696       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1697       G_TYPE_UINT, G_TYPE_UINT);
1698
1699   /**
1700    * GstRtpBin::on-bye-ssrc:
1701    * @rtpbin: the object which received the signal
1702    * @session: the session
1703    * @ssrc: the SSRC
1704    *
1705    * Notify of an SSRC that became inactive because of a BYE packet.
1706    */
1707   gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC] =
1708       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
1709       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_ssrc),
1710       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1711       G_TYPE_UINT, G_TYPE_UINT);
1712   /**
1713    * GstRtpBin::on-bye-timeout:
1714    * @rtpbin: the object which received the signal
1715    * @session: the session
1716    * @ssrc: the SSRC
1717    *
1718    * Notify of an SSRC that has timed out because of BYE
1719    */
1720   gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT] =
1721       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
1722       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_timeout),
1723       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1724       G_TYPE_UINT, G_TYPE_UINT);
1725   /**
1726    * GstRtpBin::on-timeout:
1727    * @rtpbin: the object which received the signal
1728    * @session: the session
1729    * @ssrc: the SSRC
1730    *
1731    * Notify of an SSRC that has timed out
1732    */
1733   gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT] =
1734       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
1735       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_timeout),
1736       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1737       G_TYPE_UINT, G_TYPE_UINT);
1738   /**
1739    * GstRtpBin::on-sender-timeout:
1740    * @rtpbin: the object which received the signal
1741    * @session: the session
1742    * @ssrc: the SSRC
1743    *
1744    * Notify of a sender SSRC that has timed out and became a receiver
1745    */
1746   gst_rtp_bin_signals[SIGNAL_ON_SENDER_TIMEOUT] =
1747       g_signal_new ("on-sender-timeout", G_TYPE_FROM_CLASS (klass),
1748       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_sender_timeout),
1749       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1750       G_TYPE_UINT, G_TYPE_UINT);
1751
1752   /**
1753    * GstRtpBin::on-npt-stop:
1754    * @rtpbin: the object which received the signal
1755    * @session: the session
1756    * @ssrc: the SSRC
1757    *
1758    * Notify that SSRC sender has sent data up to the configured NPT stop time.
1759    */
1760   gst_rtp_bin_signals[SIGNAL_ON_NPT_STOP] =
1761       g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
1762       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_npt_stop),
1763       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1764       G_TYPE_UINT, G_TYPE_UINT);
1765
1766   g_object_class_install_property (gobject_class, PROP_SDES,
1767       g_param_spec_boxed ("sdes", "SDES",
1768           "The SDES items of this session",
1769           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1770
1771   g_object_class_install_property (gobject_class, PROP_DO_LOST,
1772       g_param_spec_boolean ("do-lost", "Do Lost",
1773           "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
1774           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1775
1776   g_object_class_install_property (gobject_class, PROP_AUTOREMOVE,
1777       g_param_spec_boolean ("autoremove", "Auto Remove",
1778           "Automatically remove timed out sources", DEFAULT_AUTOREMOVE,
1779           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1780
1781   g_object_class_install_property (gobject_class, PROP_IGNORE_PT,
1782       g_param_spec_boolean ("ignore-pt", "Ignore PT",
1783           "Do not demultiplex based on PT values", DEFAULT_IGNORE_PT,
1784           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1785
1786   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
1787       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
1788           "Use the pipeline clock to set the NTP time in the RTCP SR messages",
1789           DEFAULT_USE_PIPELINE_CLOCK,
1790           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1791   /**
1792    * GstRtpBin::buffer-mode:
1793    *
1794    * Control the buffering and timestamping mode used by the jitterbuffer.
1795    *
1796    * Since: 0.10.17
1797    */
1798   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
1799       g_param_spec_enum ("buffer-mode", "Buffer Mode",
1800           "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
1801           DEFAULT_BUFFER_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1802   /**
1803    * GstRtpBin::ntp-sync:
1804    *
1805    * Synchronize received streams to the NTP clock. When the NTP clock is shared
1806    * between the receivers and the senders (such as when using ntpd) this option
1807    * can be used to synchronize receivers on multiple machines.
1808    *
1809    * Since: 0.10.21
1810    */
1811   g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
1812       g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
1813           "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
1814           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1815
1816   /**
1817    * GstRtpBin::rtcp-sync:
1818    *
1819    * If not synchronizing (directly) to the NTP clock, determines how to sync
1820    * the various streams.
1821    *
1822    * Since: 0.10.31
1823    */
1824   g_object_class_install_property (gobject_class, PROP_RTCP_SYNC,
1825       g_param_spec_enum ("rtcp-sync", "RTCP Sync",
1826           "Use of RTCP SR in synchronization", GST_RTP_BIN_RTCP_SYNC_TYPE,
1827           DEFAULT_RTCP_SYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1828
1829   /**
1830    * GstRtpBin::rtcp-sync-interval:
1831    *
1832    * Determines how often to sync streams using RTCP data.
1833    *
1834    * Since: 0.10.31
1835    */
1836   g_object_class_install_property (gobject_class, PROP_RTCP_SYNC_INTERVAL,
1837       g_param_spec_uint ("rtcp-sync-interval", "RTCP Sync Interval",
1838           "RTCP SR interval synchronization (ms) (0 = always)",
1839           0, G_MAXUINT, DEFAULT_RTCP_SYNC_INTERVAL,
1840           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1841
1842   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rtp_bin_change_state);
1843   gstelement_class->request_new_pad =
1844       GST_DEBUG_FUNCPTR (gst_rtp_bin_request_new_pad);
1845   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_rtp_bin_release_pad);
1846
1847   /* sink pads */
1848   gst_element_class_add_pad_template (gstelement_class,
1849       gst_static_pad_template_get (&rtpbin_recv_rtp_sink_template));
1850   gst_element_class_add_pad_template (gstelement_class,
1851       gst_static_pad_template_get (&rtpbin_recv_rtcp_sink_template));
1852   gst_element_class_add_pad_template (gstelement_class,
1853       gst_static_pad_template_get (&rtpbin_send_rtp_sink_template));
1854
1855   /* src pads */
1856   gst_element_class_add_pad_template (gstelement_class,
1857       gst_static_pad_template_get (&rtpbin_recv_rtp_src_template));
1858   gst_element_class_add_pad_template (gstelement_class,
1859       gst_static_pad_template_get (&rtpbin_send_rtcp_src_template));
1860   gst_element_class_add_pad_template (gstelement_class,
1861       gst_static_pad_template_get (&rtpbin_send_rtp_src_template));
1862
1863   gst_element_class_set_details_simple (gstelement_class, "RTP Bin",
1864       "Filter/Network/RTP",
1865       "Real-Time Transport Protocol bin",
1866       "Wim Taymans <wim.taymans@gmail.com>");
1867
1868   gstbin_class->handle_message = GST_DEBUG_FUNCPTR (gst_rtp_bin_handle_message);
1869
1870   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_bin_clear_pt_map);
1871   klass->reset_sync = GST_DEBUG_FUNCPTR (gst_rtp_bin_reset_sync);
1872   klass->get_internal_session =
1873       GST_DEBUG_FUNCPTR (gst_rtp_bin_get_internal_session);
1874
1875   GST_DEBUG_CATEGORY_INIT (gst_rtp_bin_debug, "rtpbin", 0, "RTP bin");
1876 }
1877
1878 static void
1879 gst_rtp_bin_init (GstRtpBin * rtpbin)
1880 {
1881   gchar *str;
1882
1883   rtpbin->priv = GST_RTP_BIN_GET_PRIVATE (rtpbin);
1884   rtpbin->priv->bin_lock = g_mutex_new ();
1885   rtpbin->priv->dyn_lock = g_mutex_new ();
1886
1887   rtpbin->latency_ms = DEFAULT_LATENCY_MS;
1888   rtpbin->latency_ns = DEFAULT_LATENCY_MS * GST_MSECOND;
1889   rtpbin->do_lost = DEFAULT_DO_LOST;
1890   rtpbin->ignore_pt = DEFAULT_IGNORE_PT;
1891   rtpbin->ntp_sync = DEFAULT_NTP_SYNC;
1892   rtpbin->rtcp_sync = DEFAULT_RTCP_SYNC;
1893   rtpbin->rtcp_sync_interval = DEFAULT_RTCP_SYNC_INTERVAL;
1894   rtpbin->priv->autoremove = DEFAULT_AUTOREMOVE;
1895   rtpbin->buffer_mode = DEFAULT_BUFFER_MODE;
1896   rtpbin->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
1897
1898   /* some default SDES entries */
1899   str = g_strdup_printf ("%s@%s", g_get_user_name (), g_get_host_name ());
1900   rtpbin->sdes = gst_structure_new ("application/x-rtp-source-sdes",
1901       "cname", G_TYPE_STRING, str,
1902       "name", G_TYPE_STRING, g_get_real_name (),
1903       "tool", G_TYPE_STRING, "GStreamer", NULL);
1904   g_free (str);
1905 }
1906
1907 static void
1908 gst_rtp_bin_dispose (GObject * object)
1909 {
1910   GstRtpBin *rtpbin;
1911
1912   rtpbin = GST_RTP_BIN (object);
1913
1914   GST_DEBUG_OBJECT (object, "freeing sessions");
1915   g_slist_foreach (rtpbin->sessions, (GFunc) free_session, rtpbin);
1916   g_slist_free (rtpbin->sessions);
1917   rtpbin->sessions = NULL;
1918   GST_DEBUG_OBJECT (object, "freeing clients");
1919   g_slist_foreach (rtpbin->clients, (GFunc) free_client, rtpbin);
1920   g_slist_free (rtpbin->clients);
1921   rtpbin->clients = NULL;
1922
1923   G_OBJECT_CLASS (parent_class)->dispose (object);
1924 }
1925
1926 static void
1927 gst_rtp_bin_finalize (GObject * object)
1928 {
1929   GstRtpBin *rtpbin;
1930
1931   rtpbin = GST_RTP_BIN (object);
1932
1933   if (rtpbin->sdes)
1934     gst_structure_free (rtpbin->sdes);
1935
1936   g_mutex_free (rtpbin->priv->bin_lock);
1937   g_mutex_free (rtpbin->priv->dyn_lock);
1938
1939   G_OBJECT_CLASS (parent_class)->finalize (object);
1940 }
1941
1942
1943 static void
1944 gst_rtp_bin_set_sdes_struct (GstRtpBin * bin, const GstStructure * sdes)
1945 {
1946   GSList *item;
1947
1948   if (sdes == NULL)
1949     return;
1950
1951   GST_RTP_BIN_LOCK (bin);
1952
1953   GST_OBJECT_LOCK (bin);
1954   if (bin->sdes)
1955     gst_structure_free (bin->sdes);
1956   bin->sdes = gst_structure_copy (sdes);
1957   GST_OBJECT_UNLOCK (bin);
1958
1959   /* store in all sessions */
1960   for (item = bin->sessions; item; item = g_slist_next (item)) {
1961     GstRtpBinSession *session = item->data;
1962     g_object_set (session->session, "sdes", sdes, NULL);
1963   }
1964
1965   GST_RTP_BIN_UNLOCK (bin);
1966 }
1967
1968 static GstStructure *
1969 gst_rtp_bin_get_sdes_struct (GstRtpBin * bin)
1970 {
1971   GstStructure *result;
1972
1973   GST_OBJECT_LOCK (bin);
1974   result = gst_structure_copy (bin->sdes);
1975   GST_OBJECT_UNLOCK (bin);
1976
1977   return result;
1978 }
1979
1980 static void
1981 gst_rtp_bin_set_property (GObject * object, guint prop_id,
1982     const GValue * value, GParamSpec * pspec)
1983 {
1984   GstRtpBin *rtpbin;
1985
1986   rtpbin = GST_RTP_BIN (object);
1987
1988   switch (prop_id) {
1989     case PROP_LATENCY:
1990       GST_RTP_BIN_LOCK (rtpbin);
1991       rtpbin->latency_ms = g_value_get_uint (value);
1992       rtpbin->latency_ns = rtpbin->latency_ms * GST_MSECOND;
1993       GST_RTP_BIN_UNLOCK (rtpbin);
1994       /* propagate the property down to the jitterbuffer */
1995       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin, "latency", value);
1996       break;
1997     case PROP_SDES:
1998       gst_rtp_bin_set_sdes_struct (rtpbin, g_value_get_boxed (value));
1999       break;
2000     case PROP_DO_LOST:
2001       GST_RTP_BIN_LOCK (rtpbin);
2002       rtpbin->do_lost = g_value_get_boolean (value);
2003       GST_RTP_BIN_UNLOCK (rtpbin);
2004       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin, "do-lost", value);
2005       break;
2006     case PROP_NTP_SYNC:
2007       rtpbin->ntp_sync = g_value_get_boolean (value);
2008       break;
2009     case PROP_RTCP_SYNC:
2010       g_atomic_int_set (&rtpbin->rtcp_sync, g_value_get_enum (value));
2011       break;
2012     case PROP_RTCP_SYNC_INTERVAL:
2013       rtpbin->rtcp_sync_interval = g_value_get_uint (value);
2014       break;
2015     case PROP_IGNORE_PT:
2016       rtpbin->ignore_pt = g_value_get_boolean (value);
2017       break;
2018     case PROP_AUTOREMOVE:
2019       rtpbin->priv->autoremove = g_value_get_boolean (value);
2020       break;
2021     case PROP_USE_PIPELINE_CLOCK:
2022     {
2023       GSList *sessions;
2024       GST_RTP_BIN_LOCK (rtpbin);
2025       rtpbin->use_pipeline_clock = g_value_get_boolean (value);
2026       for (sessions = rtpbin->sessions; sessions;
2027           sessions = g_slist_next (sessions)) {
2028         GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
2029
2030         g_object_set (G_OBJECT (session->session),
2031             "use-pipeline-clock", rtpbin->use_pipeline_clock, NULL);
2032       }
2033       GST_RTP_BIN_UNLOCK (rtpbin);
2034     }
2035       break;
2036     case PROP_BUFFER_MODE:
2037       GST_RTP_BIN_LOCK (rtpbin);
2038       rtpbin->buffer_mode = g_value_get_enum (value);
2039       GST_RTP_BIN_UNLOCK (rtpbin);
2040       /* propagate the property down to the jitterbuffer */
2041       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin, "mode", value);
2042       break;
2043     default:
2044       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2045       break;
2046   }
2047 }
2048
2049 static void
2050 gst_rtp_bin_get_property (GObject * object, guint prop_id,
2051     GValue * value, GParamSpec * pspec)
2052 {
2053   GstRtpBin *rtpbin;
2054
2055   rtpbin = GST_RTP_BIN (object);
2056
2057   switch (prop_id) {
2058     case PROP_LATENCY:
2059       GST_RTP_BIN_LOCK (rtpbin);
2060       g_value_set_uint (value, rtpbin->latency_ms);
2061       GST_RTP_BIN_UNLOCK (rtpbin);
2062       break;
2063     case PROP_SDES:
2064       g_value_take_boxed (value, gst_rtp_bin_get_sdes_struct (rtpbin));
2065       break;
2066     case PROP_DO_LOST:
2067       GST_RTP_BIN_LOCK (rtpbin);
2068       g_value_set_boolean (value, rtpbin->do_lost);
2069       GST_RTP_BIN_UNLOCK (rtpbin);
2070       break;
2071     case PROP_IGNORE_PT:
2072       g_value_set_boolean (value, rtpbin->ignore_pt);
2073       break;
2074     case PROP_NTP_SYNC:
2075       g_value_set_boolean (value, rtpbin->ntp_sync);
2076       break;
2077     case PROP_RTCP_SYNC:
2078       g_value_set_enum (value, g_atomic_int_get (&rtpbin->rtcp_sync));
2079       break;
2080     case PROP_RTCP_SYNC_INTERVAL:
2081       g_value_set_uint (value, rtpbin->rtcp_sync_interval);
2082       break;
2083     case PROP_AUTOREMOVE:
2084       g_value_set_boolean (value, rtpbin->priv->autoremove);
2085       break;
2086     case PROP_BUFFER_MODE:
2087       g_value_set_enum (value, rtpbin->buffer_mode);
2088       break;
2089     case PROP_USE_PIPELINE_CLOCK:
2090       g_value_set_boolean (value, rtpbin->use_pipeline_clock);
2091       break;
2092     default:
2093       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2094       break;
2095   }
2096 }
2097
2098 static void
2099 gst_rtp_bin_handle_message (GstBin * bin, GstMessage * message)
2100 {
2101   GstRtpBin *rtpbin;
2102
2103   rtpbin = GST_RTP_BIN (bin);
2104
2105   switch (GST_MESSAGE_TYPE (message)) {
2106     case GST_MESSAGE_ELEMENT:
2107     {
2108       const GstStructure *s = gst_message_get_structure (message);
2109
2110       /* we change the structure name and add the session ID to it */
2111       if (gst_structure_has_name (s, "application/x-rtp-source-sdes")) {
2112         GstRtpBinSession *sess;
2113
2114         /* find the session we set it as object data */
2115         sess = g_object_get_data (G_OBJECT (GST_MESSAGE_SRC (message)),
2116             "GstRTPBin.session");
2117
2118         if (G_LIKELY (sess)) {
2119           message = gst_message_make_writable (message);
2120           s = gst_message_get_structure (message);
2121           gst_structure_set ((GstStructure *) s, "session", G_TYPE_UINT,
2122               sess->id, NULL);
2123         }
2124       }
2125       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
2126       break;
2127     }
2128     case GST_MESSAGE_BUFFERING:
2129     {
2130       gint percent;
2131       gint min_percent = 100;
2132       GSList *sessions, *streams;
2133       GstRtpBinStream *stream;
2134       gboolean change = FALSE, active = FALSE;
2135       GstClockTime min_out_time;
2136       GstBufferingMode mode;
2137       gint avg_in, avg_out;
2138       gint64 buffering_left;
2139
2140       gst_message_parse_buffering (message, &percent);
2141       gst_message_parse_buffering_stats (message, &mode, &avg_in, &avg_out,
2142           &buffering_left);
2143
2144       stream =
2145           g_object_get_data (G_OBJECT (GST_MESSAGE_SRC (message)),
2146           "GstRTPBin.stream");
2147
2148       GST_DEBUG_OBJECT (bin, "got percent %d from stream %p", percent, stream);
2149
2150       /* get the stream */
2151       if (G_LIKELY (stream)) {
2152         GST_RTP_BIN_LOCK (rtpbin);
2153         /* fill in the percent */
2154         stream->percent = percent;
2155
2156         /* calculate the min value for all streams */
2157         for (sessions = rtpbin->sessions; sessions;
2158             sessions = g_slist_next (sessions)) {
2159           GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
2160
2161           GST_RTP_SESSION_LOCK (session);
2162           if (session->streams) {
2163             for (streams = session->streams; streams;
2164                 streams = g_slist_next (streams)) {
2165               GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
2166
2167               GST_DEBUG_OBJECT (bin, "stream %p percent %d", stream,
2168                   stream->percent);
2169
2170               /* find min percent */
2171               if (min_percent > stream->percent)
2172                 min_percent = stream->percent;
2173             }
2174           } else {
2175             GST_INFO_OBJECT (bin,
2176                 "session has no streams, setting min_percent to 0");
2177             min_percent = 0;
2178           }
2179           GST_RTP_SESSION_UNLOCK (session);
2180         }
2181         GST_DEBUG_OBJECT (bin, "min percent %d", min_percent);
2182
2183         if (rtpbin->buffering) {
2184           if (min_percent == 100) {
2185             rtpbin->buffering = FALSE;
2186             active = TRUE;
2187             change = TRUE;
2188           }
2189         } else {
2190           if (min_percent < 100) {
2191             /* pause the streams */
2192             rtpbin->buffering = TRUE;
2193             active = FALSE;
2194             change = TRUE;
2195           }
2196         }
2197         GST_RTP_BIN_UNLOCK (rtpbin);
2198
2199         gst_message_unref (message);
2200
2201         /* make a new buffering message with the min value */
2202         message =
2203             gst_message_new_buffering (GST_OBJECT_CAST (bin), min_percent);
2204         gst_message_set_buffering_stats (message, mode, avg_in, avg_out,
2205             buffering_left);
2206
2207         if (G_UNLIKELY (change)) {
2208           GstClock *clock;
2209           guint64 running_time = 0;
2210           guint64 offset = 0;
2211
2212           /* figure out the running time when we have a clock */
2213           if (G_LIKELY ((clock =
2214                       gst_element_get_clock (GST_ELEMENT_CAST (bin))))) {
2215             guint64 now, base_time;
2216
2217             now = gst_clock_get_time (clock);
2218             base_time = gst_element_get_base_time (GST_ELEMENT_CAST (bin));
2219             running_time = now - base_time;
2220             gst_object_unref (clock);
2221           }
2222           GST_DEBUG_OBJECT (bin,
2223               "running time now %" GST_TIME_FORMAT,
2224               GST_TIME_ARGS (running_time));
2225
2226           GST_RTP_BIN_LOCK (rtpbin);
2227
2228           /* when we reactivate, calculate the offsets so that all streams have
2229            * an output time that is at least as big as the running_time */
2230           offset = 0;
2231           if (active) {
2232             if (running_time > rtpbin->buffer_start) {
2233               offset = running_time - rtpbin->buffer_start;
2234               if (offset >= rtpbin->latency_ns)
2235                 offset -= rtpbin->latency_ns;
2236               else
2237                 offset = 0;
2238             }
2239           }
2240
2241           /* pause all streams */
2242           min_out_time = -1;
2243           for (sessions = rtpbin->sessions; sessions;
2244               sessions = g_slist_next (sessions)) {
2245             GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
2246
2247             GST_RTP_SESSION_LOCK (session);
2248             for (streams = session->streams; streams;
2249                 streams = g_slist_next (streams)) {
2250               GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
2251               GstElement *element = stream->buffer;
2252               guint64 last_out;
2253
2254               g_signal_emit_by_name (element, "set-active", active, offset,
2255                   &last_out);
2256
2257               if (!active) {
2258                 g_object_get (element, "percent", &stream->percent, NULL);
2259
2260                 if (last_out == -1)
2261                   last_out = 0;
2262                 if (min_out_time == -1 || last_out < min_out_time)
2263                   min_out_time = last_out;
2264               }
2265
2266               GST_DEBUG_OBJECT (bin,
2267                   "setting %p to %d, offset %" GST_TIME_FORMAT ", last %"
2268                   GST_TIME_FORMAT ", percent %d", element, active,
2269                   GST_TIME_ARGS (offset), GST_TIME_ARGS (last_out),
2270                   stream->percent);
2271             }
2272             GST_RTP_SESSION_UNLOCK (session);
2273           }
2274           GST_DEBUG_OBJECT (bin,
2275               "min out time %" GST_TIME_FORMAT, GST_TIME_ARGS (min_out_time));
2276
2277           /* the buffer_start is the min out time of all paused jitterbuffers */
2278           if (!active)
2279             rtpbin->buffer_start = min_out_time;
2280
2281           GST_RTP_BIN_UNLOCK (rtpbin);
2282         }
2283       }
2284       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
2285       break;
2286     }
2287     default:
2288     {
2289       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
2290       break;
2291     }
2292   }
2293 }
2294
2295 static GstStateChangeReturn
2296 gst_rtp_bin_change_state (GstElement * element, GstStateChange transition)
2297 {
2298   GstStateChangeReturn res;
2299   GstRtpBin *rtpbin;
2300   GstRtpBinPrivate *priv;
2301
2302   rtpbin = GST_RTP_BIN (element);
2303   priv = rtpbin->priv;
2304
2305   switch (transition) {
2306     case GST_STATE_CHANGE_NULL_TO_READY:
2307       break;
2308     case GST_STATE_CHANGE_READY_TO_PAUSED:
2309       priv->last_unix = 0;
2310       GST_LOG_OBJECT (rtpbin, "clearing shutdown flag");
2311       g_atomic_int_set (&priv->shutdown, 0);
2312       break;
2313     case GST_STATE_CHANGE_PAUSED_TO_READY:
2314       GST_LOG_OBJECT (rtpbin, "setting shutdown flag");
2315       g_atomic_int_set (&priv->shutdown, 1);
2316       /* wait for all callbacks to end by taking the lock. No new callbacks will
2317        * be able to happen as we set the shutdown flag. */
2318       GST_RTP_BIN_DYN_LOCK (rtpbin);
2319       GST_LOG_OBJECT (rtpbin, "dynamic lock taken, we can continue shutdown");
2320       GST_RTP_BIN_DYN_UNLOCK (rtpbin);
2321       break;
2322     default:
2323       break;
2324   }
2325
2326   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2327
2328   switch (transition) {
2329     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2330       break;
2331     case GST_STATE_CHANGE_PAUSED_TO_READY:
2332       break;
2333     case GST_STATE_CHANGE_READY_TO_NULL:
2334       break;
2335     default:
2336       break;
2337   }
2338   return res;
2339 }
2340
2341 /* a new pad (SSRC) was created in @session. This signal is emited from the
2342  * payload demuxer. */
2343 static void
2344 new_payload_found (GstElement * element, guint pt, GstPad * pad,
2345     GstRtpBinStream * stream)
2346 {
2347   GstRtpBin *rtpbin;
2348   GstElementClass *klass;
2349   GstPadTemplate *templ;
2350   gchar *padname;
2351   GstPad *gpad;
2352
2353   rtpbin = stream->bin;
2354
2355   GST_DEBUG ("new payload pad %d", pt);
2356
2357   GST_RTP_BIN_SHUTDOWN_LOCK (rtpbin, shutdown);
2358
2359   /* ghost the pad to the parent */
2360   klass = GST_ELEMENT_GET_CLASS (rtpbin);
2361   templ = gst_element_class_get_pad_template (klass, "recv_rtp_src_%d_%d_%d");
2362   padname = g_strdup_printf ("recv_rtp_src_%d_%u_%d",
2363       stream->session->id, stream->ssrc, pt);
2364   gpad = gst_ghost_pad_new_from_template (padname, pad, templ);
2365   g_free (padname);
2366   g_object_set_data (G_OBJECT (pad), "GstRTPBin.ghostpad", gpad);
2367
2368   gst_pad_set_active (gpad, TRUE);
2369   GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
2370
2371   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), gpad);
2372
2373   return;
2374
2375 shutdown:
2376   {
2377     GST_DEBUG ("ignoring, we are shutting down");
2378     return;
2379   }
2380 }
2381
2382 static void
2383 payload_pad_removed (GstElement * element, GstPad * pad,
2384     GstRtpBinStream * stream)
2385 {
2386   GstRtpBin *rtpbin;
2387   GstPad *gpad;
2388
2389   rtpbin = stream->bin;
2390
2391   GST_DEBUG ("payload pad removed");
2392
2393   GST_RTP_BIN_DYN_LOCK (rtpbin);
2394   if ((gpad = g_object_get_data (G_OBJECT (pad), "GstRTPBin.ghostpad"))) {
2395     g_object_set_data (G_OBJECT (pad), "GstRTPBin.ghostpad", NULL);
2396
2397     gst_pad_set_active (gpad, FALSE);
2398     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin), gpad);
2399   }
2400   GST_RTP_BIN_DYN_UNLOCK (rtpbin);
2401 }
2402
2403 static GstCaps *
2404 pt_map_requested (GstElement * element, guint pt, GstRtpBinSession * session)
2405 {
2406   GstRtpBin *rtpbin;
2407   GstCaps *caps;
2408
2409   rtpbin = session->bin;
2410
2411   GST_DEBUG_OBJECT (rtpbin, "payload map requested for pt %d in session %d", pt,
2412       session->id);
2413
2414   caps = get_pt_map (session, pt);
2415   if (!caps)
2416     goto no_caps;
2417
2418   return caps;
2419
2420   /* ERRORS */
2421 no_caps:
2422   {
2423     GST_DEBUG_OBJECT (rtpbin, "could not get caps");
2424     return NULL;
2425   }
2426 }
2427
2428 static void
2429 payload_type_change (GstElement * element, guint pt, GstRtpBinSession * session)
2430 {
2431   GST_DEBUG_OBJECT (session->bin,
2432       "emiting signal for pt type changed to %d in session %d", pt,
2433       session->id);
2434
2435   g_signal_emit (session->bin, gst_rtp_bin_signals[SIGNAL_PAYLOAD_TYPE_CHANGE],
2436       0, session->id, pt);
2437 }
2438
2439 /* emited when caps changed for the session */
2440 static void
2441 caps_changed (GstPad * pad, GParamSpec * pspec, GstRtpBinSession * session)
2442 {
2443   GstRtpBin *bin;
2444   GstCaps *caps;
2445   gint payload;
2446   const GstStructure *s;
2447
2448   bin = session->bin;
2449
2450   g_object_get (pad, "caps", &caps, NULL);
2451
2452   if (caps == NULL)
2453     return;
2454
2455   GST_DEBUG_OBJECT (bin, "got caps %" GST_PTR_FORMAT, caps);
2456
2457   s = gst_caps_get_structure (caps, 0);
2458
2459   /* get payload, finish when it's not there */
2460   if (!gst_structure_get_int (s, "payload", &payload))
2461     return;
2462
2463   GST_RTP_SESSION_LOCK (session);
2464   GST_DEBUG_OBJECT (bin, "insert caps for payload %d", payload);
2465   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (payload), caps);
2466   GST_RTP_SESSION_UNLOCK (session);
2467 }
2468
2469 /* a new pad (SSRC) was created in @session */
2470 static void
2471 new_ssrc_pad_found (GstElement * element, guint ssrc, GstPad * pad,
2472     GstRtpBinSession * session)
2473 {
2474   GstRtpBin *rtpbin;
2475   GstRtpBinStream *stream;
2476   GstPad *sinkpad, *srcpad;
2477   gchar *padname;
2478
2479   rtpbin = session->bin;
2480
2481   GST_DEBUG_OBJECT (rtpbin, "new SSRC pad %08x, %s:%s", ssrc,
2482       GST_DEBUG_PAD_NAME (pad));
2483
2484   GST_RTP_BIN_SHUTDOWN_LOCK (rtpbin, shutdown);
2485
2486   GST_RTP_SESSION_LOCK (session);
2487
2488   /* create new stream */
2489   stream = create_stream (session, ssrc);
2490   if (!stream)
2491     goto no_stream;
2492
2493   /* get pad and link */
2494   GST_DEBUG_OBJECT (rtpbin, "linking jitterbuffer RTP");
2495   padname = g_strdup_printf ("src_%d", ssrc);
2496   srcpad = gst_element_get_static_pad (element, padname);
2497   g_free (padname);
2498   sinkpad = gst_element_get_static_pad (stream->buffer, "sink");
2499   gst_pad_link (srcpad, sinkpad);
2500   gst_object_unref (sinkpad);
2501   gst_object_unref (srcpad);
2502
2503   GST_DEBUG_OBJECT (rtpbin, "linking jitterbuffer RTCP");
2504   padname = g_strdup_printf ("rtcp_src_%d", ssrc);
2505   srcpad = gst_element_get_static_pad (element, padname);
2506   g_free (padname);
2507   sinkpad = gst_element_get_request_pad (stream->buffer, "sink_rtcp");
2508   gst_pad_link (srcpad, sinkpad);
2509   gst_object_unref (sinkpad);
2510   gst_object_unref (srcpad);
2511
2512   /* connect to the RTCP sync signal from the jitterbuffer */
2513   GST_DEBUG_OBJECT (rtpbin, "connecting sync signal");
2514   stream->buffer_handlesync_sig = g_signal_connect (stream->buffer,
2515       "handle-sync", (GCallback) gst_rtp_bin_handle_sync, stream);
2516
2517   if (stream->demux) {
2518     /* connect to the new-pad signal of the payload demuxer, this will expose the
2519      * new pad by ghosting it. */
2520     stream->demux_newpad_sig = g_signal_connect (stream->demux,
2521         "new-payload-type", (GCallback) new_payload_found, stream);
2522     stream->demux_padremoved_sig = g_signal_connect (stream->demux,
2523         "pad-removed", (GCallback) payload_pad_removed, stream);
2524
2525     /* connect to the request-pt-map signal. This signal will be emited by the
2526      * demuxer so that it can apply a proper caps on the buffers for the
2527      * depayloaders. */
2528     stream->demux_ptreq_sig = g_signal_connect (stream->demux,
2529         "request-pt-map", (GCallback) pt_map_requested, session);
2530     /* connect to the  signal so it can be forwarded. */
2531     stream->demux_ptchange_sig = g_signal_connect (stream->demux,
2532         "payload-type-change", (GCallback) payload_type_change, session);
2533   } else {
2534     /* add gstrtpjitterbuffer src pad to pads */
2535     GstElementClass *klass;
2536     GstPadTemplate *templ;
2537     gchar *padname;
2538     GstPad *gpad, *pad;
2539
2540     pad = gst_element_get_static_pad (stream->buffer, "src");
2541
2542     /* ghost the pad to the parent */
2543     klass = GST_ELEMENT_GET_CLASS (rtpbin);
2544     templ = gst_element_class_get_pad_template (klass, "recv_rtp_src_%d_%d_%d");
2545     padname = g_strdup_printf ("recv_rtp_src_%d_%u_%d",
2546         stream->session->id, stream->ssrc, 255);
2547     gpad = gst_ghost_pad_new_from_template (padname, pad, templ);
2548     g_free (padname);
2549
2550     gst_pad_set_active (gpad, TRUE);
2551     gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), gpad);
2552
2553     gst_object_unref (pad);
2554   }
2555
2556   GST_RTP_SESSION_UNLOCK (session);
2557   GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
2558
2559   return;
2560
2561   /* ERRORS */
2562 shutdown:
2563   {
2564     GST_DEBUG_OBJECT (rtpbin, "we are shutting down");
2565     return;
2566   }
2567 no_stream:
2568   {
2569     GST_RTP_SESSION_UNLOCK (session);
2570     GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
2571     GST_DEBUG_OBJECT (rtpbin, "could not create stream");
2572     return;
2573   }
2574 }
2575
2576 /* Create a pad for receiving RTP for the session in @name. Must be called with
2577  * RTP_BIN_LOCK.
2578  */
2579 static GstPad *
2580 create_recv_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
2581 {
2582   GstPad *sinkdpad;
2583   guint sessid;
2584   GstRtpBinSession *session;
2585   GstPadLinkReturn lres;
2586
2587   /* first get the session number */
2588   if (name == NULL || sscanf (name, "recv_rtp_sink_%d", &sessid) != 1)
2589     goto no_name;
2590
2591   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
2592
2593   /* get or create session */
2594   session = find_session_by_id (rtpbin, sessid);
2595   if (!session) {
2596     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
2597     /* create session now */
2598     session = create_session (rtpbin, sessid);
2599     if (session == NULL)
2600       goto create_error;
2601   }
2602
2603   /* check if pad was requested */
2604   if (session->recv_rtp_sink_ghost != NULL)
2605     return session->recv_rtp_sink_ghost;
2606
2607   GST_DEBUG_OBJECT (rtpbin, "getting RTP sink pad");
2608   /* get recv_rtp pad and store */
2609   session->recv_rtp_sink =
2610       gst_element_get_request_pad (session->session, "recv_rtp_sink");
2611   if (session->recv_rtp_sink == NULL)
2612     goto pad_failed;
2613
2614   g_signal_connect (session->recv_rtp_sink, "notify::caps",
2615       (GCallback) caps_changed, session);
2616
2617   GST_DEBUG_OBJECT (rtpbin, "getting RTP src pad");
2618   /* get srcpad, link to SSRCDemux */
2619   session->recv_rtp_src =
2620       gst_element_get_static_pad (session->session, "recv_rtp_src");
2621   if (session->recv_rtp_src == NULL)
2622     goto pad_failed;
2623
2624   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTP sink pad");
2625   sinkdpad = gst_element_get_static_pad (session->demux, "sink");
2626   GST_DEBUG_OBJECT (rtpbin, "linking demuxer RTP sink pad");
2627   lres = gst_pad_link (session->recv_rtp_src, sinkdpad);
2628   gst_object_unref (sinkdpad);
2629   if (lres != GST_PAD_LINK_OK)
2630     goto link_failed;
2631
2632   /* connect to the new-ssrc-pad signal of the SSRC demuxer */
2633   session->demux_newpad_sig = g_signal_connect (session->demux,
2634       "new-ssrc-pad", (GCallback) new_ssrc_pad_found, session);
2635   session->demux_padremoved_sig = g_signal_connect (session->demux,
2636       "removed-ssrc-pad", (GCallback) ssrc_demux_pad_removed, session);
2637
2638   GST_DEBUG_OBJECT (rtpbin, "ghosting session sink pad");
2639   session->recv_rtp_sink_ghost =
2640       gst_ghost_pad_new_from_template (name, session->recv_rtp_sink, templ);
2641   gst_pad_set_active (session->recv_rtp_sink_ghost, TRUE);
2642   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->recv_rtp_sink_ghost);
2643
2644   return session->recv_rtp_sink_ghost;
2645
2646   /* ERRORS */
2647 no_name:
2648   {
2649     g_warning ("gstrtpbin: invalid name given");
2650     return NULL;
2651   }
2652 create_error:
2653   {
2654     /* create_session already warned */
2655     return NULL;
2656   }
2657 pad_failed:
2658   {
2659     g_warning ("gstrtpbin: failed to get session pad");
2660     return NULL;
2661   }
2662 link_failed:
2663   {
2664     g_warning ("gstrtpbin: failed to link pads");
2665     return NULL;
2666   }
2667 }
2668
2669 static void
2670 remove_recv_rtp (GstRtpBin * rtpbin, GstRtpBinSession * session)
2671 {
2672   if (session->demux_newpad_sig) {
2673     g_signal_handler_disconnect (session->demux, session->demux_newpad_sig);
2674     session->demux_newpad_sig = 0;
2675   }
2676   if (session->demux_padremoved_sig) {
2677     g_signal_handler_disconnect (session->demux, session->demux_padremoved_sig);
2678     session->demux_padremoved_sig = 0;
2679   }
2680   if (session->recv_rtp_src) {
2681     gst_object_unref (session->recv_rtp_src);
2682     session->recv_rtp_src = NULL;
2683   }
2684   if (session->recv_rtp_sink) {
2685     gst_element_release_request_pad (session->session, session->recv_rtp_sink);
2686     gst_object_unref (session->recv_rtp_sink);
2687     session->recv_rtp_sink = NULL;
2688   }
2689   if (session->recv_rtp_sink_ghost) {
2690     gst_pad_set_active (session->recv_rtp_sink_ghost, FALSE);
2691     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
2692         session->recv_rtp_sink_ghost);
2693     session->recv_rtp_sink_ghost = NULL;
2694   }
2695 }
2696
2697 /* Create a pad for receiving RTCP for the session in @name. Must be called with
2698  * RTP_BIN_LOCK.
2699  */
2700 static GstPad *
2701 create_recv_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ,
2702     const gchar * name)
2703 {
2704   guint sessid;
2705   GstRtpBinSession *session;
2706   GstPad *sinkdpad;
2707   GstPadLinkReturn lres;
2708
2709   /* first get the session number */
2710   if (name == NULL || sscanf (name, "recv_rtcp_sink_%d", &sessid) != 1)
2711     goto no_name;
2712
2713   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
2714
2715   /* get or create the session */
2716   session = find_session_by_id (rtpbin, sessid);
2717   if (!session) {
2718     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
2719     /* create session now */
2720     session = create_session (rtpbin, sessid);
2721     if (session == NULL)
2722       goto create_error;
2723   }
2724
2725   /* check if pad was requested */
2726   if (session->recv_rtcp_sink_ghost != NULL)
2727     return session->recv_rtcp_sink_ghost;
2728
2729   /* get recv_rtp pad and store */
2730   GST_DEBUG_OBJECT (rtpbin, "getting RTCP sink pad");
2731   session->recv_rtcp_sink =
2732       gst_element_get_request_pad (session->session, "recv_rtcp_sink");
2733   if (session->recv_rtcp_sink == NULL)
2734     goto pad_failed;
2735
2736   /* get srcpad, link to SSRCDemux */
2737   GST_DEBUG_OBJECT (rtpbin, "getting sync src pad");
2738   session->sync_src = gst_element_get_static_pad (session->session, "sync_src");
2739   if (session->sync_src == NULL)
2740     goto pad_failed;
2741
2742   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTCP sink pad");
2743   sinkdpad = gst_element_get_static_pad (session->demux, "rtcp_sink");
2744   lres = gst_pad_link (session->sync_src, sinkdpad);
2745   gst_object_unref (sinkdpad);
2746   if (lres != GST_PAD_LINK_OK)
2747     goto link_failed;
2748
2749   session->recv_rtcp_sink_ghost =
2750       gst_ghost_pad_new_from_template (name, session->recv_rtcp_sink, templ);
2751   gst_pad_set_active (session->recv_rtcp_sink_ghost, TRUE);
2752   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin),
2753       session->recv_rtcp_sink_ghost);
2754
2755   return session->recv_rtcp_sink_ghost;
2756
2757   /* ERRORS */
2758 no_name:
2759   {
2760     g_warning ("gstrtpbin: invalid name given");
2761     return NULL;
2762   }
2763 create_error:
2764   {
2765     /* create_session already warned */
2766     return NULL;
2767   }
2768 pad_failed:
2769   {
2770     g_warning ("gstrtpbin: failed to get session pad");
2771     return NULL;
2772   }
2773 link_failed:
2774   {
2775     g_warning ("gstrtpbin: failed to link pads");
2776     return NULL;
2777   }
2778 }
2779
2780 static void
2781 remove_recv_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session)
2782 {
2783   if (session->recv_rtcp_sink_ghost) {
2784     gst_pad_set_active (session->recv_rtcp_sink_ghost, FALSE);
2785     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
2786         session->recv_rtcp_sink_ghost);
2787     session->recv_rtcp_sink_ghost = NULL;
2788   }
2789   if (session->sync_src) {
2790     /* releasing the request pad should also unref the sync pad */
2791     gst_object_unref (session->sync_src);
2792     session->sync_src = NULL;
2793   }
2794   if (session->recv_rtcp_sink) {
2795     gst_element_release_request_pad (session->session, session->recv_rtcp_sink);
2796     gst_object_unref (session->recv_rtcp_sink);
2797     session->recv_rtcp_sink = NULL;
2798   }
2799 }
2800
2801 /* Create a pad for sending RTP for the session in @name. Must be called with
2802  * RTP_BIN_LOCK.
2803  */
2804 static GstPad *
2805 create_send_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
2806 {
2807   gchar *gname;
2808   guint sessid;
2809   GstRtpBinSession *session;
2810   GstElementClass *klass;
2811
2812   /* first get the session number */
2813   if (name == NULL || sscanf (name, "send_rtp_sink_%d", &sessid) != 1)
2814     goto no_name;
2815
2816   /* get or create session */
2817   session = find_session_by_id (rtpbin, sessid);
2818   if (!session) {
2819     /* create session now */
2820     session = create_session (rtpbin, sessid);
2821     if (session == NULL)
2822       goto create_error;
2823   }
2824
2825   /* check if pad was requested */
2826   if (session->send_rtp_sink_ghost != NULL)
2827     return session->send_rtp_sink_ghost;
2828
2829   /* get send_rtp pad and store */
2830   session->send_rtp_sink =
2831       gst_element_get_request_pad (session->session, "send_rtp_sink");
2832   if (session->send_rtp_sink == NULL)
2833     goto pad_failed;
2834
2835   session->send_rtp_sink_ghost =
2836       gst_ghost_pad_new_from_template (name, session->send_rtp_sink, templ);
2837   gst_pad_set_active (session->send_rtp_sink_ghost, TRUE);
2838   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->send_rtp_sink_ghost);
2839
2840   /* get srcpad */
2841   session->send_rtp_src =
2842       gst_element_get_static_pad (session->session, "send_rtp_src");
2843   if (session->send_rtp_src == NULL)
2844     goto no_srcpad;
2845
2846   /* ghost the new source pad */
2847   klass = GST_ELEMENT_GET_CLASS (rtpbin);
2848   gname = g_strdup_printf ("send_rtp_src_%d", sessid);
2849   templ = gst_element_class_get_pad_template (klass, "send_rtp_src_%d");
2850   session->send_rtp_src_ghost =
2851       gst_ghost_pad_new_from_template (gname, session->send_rtp_src, templ);
2852   gst_pad_set_active (session->send_rtp_src_ghost, TRUE);
2853   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->send_rtp_src_ghost);
2854   g_free (gname);
2855
2856   return session->send_rtp_sink_ghost;
2857
2858   /* ERRORS */
2859 no_name:
2860   {
2861     g_warning ("gstrtpbin: invalid name given");
2862     return NULL;
2863   }
2864 create_error:
2865   {
2866     /* create_session already warned */
2867     return NULL;
2868   }
2869 pad_failed:
2870   {
2871     g_warning ("gstrtpbin: failed to get session pad for session %d", sessid);
2872     return NULL;
2873   }
2874 no_srcpad:
2875   {
2876     g_warning ("gstrtpbin: failed to get rtp source pad for session %d",
2877         sessid);
2878     return NULL;
2879   }
2880 }
2881
2882 static void
2883 remove_send_rtp (GstRtpBin * rtpbin, GstRtpBinSession * session)
2884 {
2885   if (session->send_rtp_src_ghost) {
2886     gst_pad_set_active (session->send_rtp_src_ghost, FALSE);
2887     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
2888         session->send_rtp_src_ghost);
2889     session->send_rtp_src_ghost = NULL;
2890   }
2891   if (session->send_rtp_src) {
2892     gst_object_unref (session->send_rtp_src);
2893     session->send_rtp_src = NULL;
2894   }
2895   if (session->send_rtp_sink) {
2896     gst_element_release_request_pad (GST_ELEMENT_CAST (session->session),
2897         session->send_rtp_sink);
2898     gst_object_unref (session->send_rtp_sink);
2899     session->send_rtp_sink = NULL;
2900   }
2901   if (session->send_rtp_sink_ghost) {
2902     gst_pad_set_active (session->send_rtp_sink_ghost, FALSE);
2903     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
2904         session->send_rtp_sink_ghost);
2905     session->send_rtp_sink_ghost = NULL;
2906   }
2907 }
2908
2909 /* Create a pad for sending RTCP for the session in @name. Must be called with
2910  * RTP_BIN_LOCK.
2911  */
2912 static GstPad *
2913 create_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
2914 {
2915   guint sessid;
2916   GstRtpBinSession *session;
2917
2918   /* first get the session number */
2919   if (name == NULL || sscanf (name, "send_rtcp_src_%d", &sessid) != 1)
2920     goto no_name;
2921
2922   /* get or create session */
2923   session = find_session_by_id (rtpbin, sessid);
2924   if (!session)
2925     goto no_session;
2926
2927   /* check if pad was requested */
2928   if (session->send_rtcp_src_ghost != NULL)
2929     return session->send_rtcp_src_ghost;
2930
2931   /* get rtcp_src pad and store */
2932   session->send_rtcp_src =
2933       gst_element_get_request_pad (session->session, "send_rtcp_src");
2934   if (session->send_rtcp_src == NULL)
2935     goto pad_failed;
2936
2937   session->send_rtcp_src_ghost =
2938       gst_ghost_pad_new_from_template (name, session->send_rtcp_src, templ);
2939   gst_pad_set_active (session->send_rtcp_src_ghost, TRUE);
2940   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->send_rtcp_src_ghost);
2941
2942   return session->send_rtcp_src_ghost;
2943
2944   /* ERRORS */
2945 no_name:
2946   {
2947     g_warning ("gstrtpbin: invalid name given");
2948     return NULL;
2949   }
2950 no_session:
2951   {
2952     g_warning ("gstrtpbin: session with id %d does not exist", sessid);
2953     return NULL;
2954   }
2955 pad_failed:
2956   {
2957     g_warning ("gstrtpbin: failed to get rtcp pad for session %d", sessid);
2958     return NULL;
2959   }
2960 }
2961
2962 static void
2963 remove_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session)
2964 {
2965   if (session->send_rtcp_src_ghost) {
2966     gst_pad_set_active (session->send_rtcp_src_ghost, FALSE);
2967     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
2968         session->send_rtcp_src_ghost);
2969     session->send_rtcp_src_ghost = NULL;
2970   }
2971   if (session->send_rtcp_src) {
2972     gst_element_release_request_pad (session->session, session->send_rtcp_src);
2973     gst_object_unref (session->send_rtcp_src);
2974     session->send_rtcp_src = NULL;
2975   }
2976 }
2977
2978 /* If the requested name is NULL we should create a name with
2979  * the session number assuming we want the lowest posible session
2980  * with a free pad like the template */
2981 static gchar *
2982 gst_rtp_bin_get_free_pad_name (GstElement * element, GstPadTemplate * templ)
2983 {
2984   gboolean name_found = FALSE;
2985   gint session = 0;
2986   GstIterator *pad_it = NULL;
2987   gchar *pad_name = NULL;
2988   GValue data = { 0, };
2989
2990   GST_DEBUG_OBJECT (element, "find a free pad name for template");
2991   while (!name_found) {
2992     gboolean done = FALSE;
2993
2994     g_free (pad_name);
2995     pad_name = g_strdup_printf (templ->name_template, session++);
2996     pad_it = gst_element_iterate_pads (GST_ELEMENT (element));
2997     name_found = TRUE;
2998     while (!done) {
2999       switch (gst_iterator_next (pad_it, &data)) {
3000         case GST_ITERATOR_OK:
3001         {
3002           GstPad *pad;
3003           gchar *name;
3004
3005           pad = g_value_get_object (&data);
3006           name = gst_pad_get_name (pad);
3007
3008           if (strcmp (name, pad_name) == 0) {
3009             done = TRUE;
3010             name_found = FALSE;
3011           }
3012           g_free (name);
3013           g_value_reset (&data);
3014           break;
3015         }
3016         case GST_ITERATOR_ERROR:
3017         case GST_ITERATOR_RESYNC:
3018           /* restart iteration */
3019           done = TRUE;
3020           name_found = FALSE;
3021           session = 0;
3022           break;
3023         case GST_ITERATOR_DONE:
3024           done = TRUE;
3025           break;
3026       }
3027     }
3028     g_value_unset (&data);
3029     gst_iterator_free (pad_it);
3030   }
3031
3032   GST_DEBUG_OBJECT (element, "free pad name found: '%s'", pad_name);
3033   return pad_name;
3034 }
3035
3036 /*
3037  */
3038 static GstPad *
3039 gst_rtp_bin_request_new_pad (GstElement * element,
3040     GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
3041 {
3042   GstRtpBin *rtpbin;
3043   GstElementClass *klass;
3044   GstPad *result;
3045
3046   gchar *pad_name = NULL;
3047
3048   g_return_val_if_fail (templ != NULL, NULL);
3049   g_return_val_if_fail (GST_IS_RTP_BIN (element), NULL);
3050
3051   rtpbin = GST_RTP_BIN (element);
3052   klass = GST_ELEMENT_GET_CLASS (element);
3053
3054   GST_RTP_BIN_LOCK (rtpbin);
3055
3056   if (name == NULL) {
3057     /* use a free pad name */
3058     pad_name = gst_rtp_bin_get_free_pad_name (element, templ);
3059   } else {
3060     /* use the provided name */
3061     pad_name = g_strdup (name);
3062   }
3063
3064   GST_DEBUG_OBJECT (rtpbin, "Trying to request a pad with name %s", pad_name);
3065
3066   /* figure out the template */
3067   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink_%d")) {
3068     result = create_recv_rtp (rtpbin, templ, pad_name);
3069   } else if (templ == gst_element_class_get_pad_template (klass,
3070           "recv_rtcp_sink_%d")) {
3071     result = create_recv_rtcp (rtpbin, templ, pad_name);
3072   } else if (templ == gst_element_class_get_pad_template (klass,
3073           "send_rtp_sink_%d")) {
3074     result = create_send_rtp (rtpbin, templ, pad_name);
3075   } else if (templ == gst_element_class_get_pad_template (klass,
3076           "send_rtcp_src_%d")) {
3077     result = create_rtcp (rtpbin, templ, pad_name);
3078   } else
3079     goto wrong_template;
3080
3081   g_free (pad_name);
3082   GST_RTP_BIN_UNLOCK (rtpbin);
3083
3084   return result;
3085
3086   /* ERRORS */
3087 wrong_template:
3088   {
3089     g_free (pad_name);
3090     GST_RTP_BIN_UNLOCK (rtpbin);
3091     g_warning ("gstrtpbin: this is not our template");
3092     return NULL;
3093   }
3094 }
3095
3096 static void
3097 gst_rtp_bin_release_pad (GstElement * element, GstPad * pad)
3098 {
3099   GstRtpBinSession *session;
3100   GstRtpBin *rtpbin;
3101
3102   g_return_if_fail (GST_IS_GHOST_PAD (pad));
3103   g_return_if_fail (GST_IS_RTP_BIN (element));
3104
3105   rtpbin = GST_RTP_BIN (element);
3106
3107   GST_RTP_BIN_LOCK (rtpbin);
3108   GST_DEBUG_OBJECT (rtpbin, "Trying to release pad %s:%s",
3109       GST_DEBUG_PAD_NAME (pad));
3110
3111   if (!(session = find_session_by_pad (rtpbin, pad)))
3112     goto unknown_pad;
3113
3114   if (session->recv_rtp_sink_ghost == pad) {
3115     remove_recv_rtp (rtpbin, session);
3116   } else if (session->recv_rtcp_sink_ghost == pad) {
3117     remove_recv_rtcp (rtpbin, session);
3118   } else if (session->send_rtp_sink_ghost == pad) {
3119     remove_send_rtp (rtpbin, session);
3120   } else if (session->send_rtcp_src_ghost == pad) {
3121     remove_rtcp (rtpbin, session);
3122   }
3123
3124   /* no more request pads, free the complete session */
3125   if (session->recv_rtp_sink_ghost == NULL
3126       && session->recv_rtcp_sink_ghost == NULL
3127       && session->send_rtp_sink_ghost == NULL
3128       && session->send_rtcp_src_ghost == NULL) {
3129     GST_DEBUG_OBJECT (rtpbin, "no more pads for session %p", session);
3130     rtpbin->sessions = g_slist_remove (rtpbin->sessions, session);
3131     free_session (session, rtpbin);
3132   }
3133   GST_RTP_BIN_UNLOCK (rtpbin);
3134
3135   return;
3136
3137   /* ERROR */
3138 unknown_pad:
3139   {
3140     GST_RTP_BIN_UNLOCK (rtpbin);
3141     g_warning ("gstrtpbin: %s:%s is not one of our request pads",
3142         GST_DEBUG_PAD_NAME (pad));
3143     return;
3144   }
3145 }