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