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