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