ad8272c0a006300d3538869eb0063f492379ed3b
[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., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 /**
21  * SECTION:element-rtpbin
22  * @see_also: rtpjitterbuffer, rtpsession, rtpptdemux, rtpssrcdemux
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  * rtpbin 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 rtpbin 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  * #GstRtpBin also has signals (#GstRtpBin::request-rtp-encoder,
67  * #GstRtpBin::request-rtp-decoder, #GstRtpBin::request-rtcp-encoder and
68  * #GstRtpBin::request-rtp-decoder) to dynamically request for RTP and RTCP encoders
69  * and decoders in order to support SRTP. The encoders must provide the pads
70  * rtp_sink_\%u and rtp_src_\%u for RTP and rtcp_sink_\%u and rtcp_src_\%u for
71  * RTCP. The session number will be used in the pad name. The decoders must provide
72  * rtp_sink and rtp_src for RTP and rtcp_sink and rtcp_src for RTCP. The decoders will
73  * be placed before the #GstRtpSession element, thus they must support SSRC demuxing
74  * internally.
75  *
76  * #GstRtpBin has signals (#GstRtpBin::request-aux-sender and
77  * #GstRtpBin::request-aux-receiver to dynamically request an element that can be
78  * used to create or merge additional RTP streams. AUX elements are needed to
79  * implement FEC or retransmission (such as RFC 4588). An AUX sender must have one
80  * sink_\%u pad that matches the sessionid in the signal and it should have 1 or
81  * more src_\%u pads. For each src_%\u pad, a session will be made (if needed)
82  * and the pad will be linked to the session send_rtp_sink pad. Each session will
83  * then expose its source pad as send_rtp_src_\%u on #GstRtpBin.
84  * An AUX receiver has 1 src_\%u pad that much match the sessionid in the signal
85  * and 1 or more sink_\%u pads. A session will be made for each sink_\%u pad
86  * when the corresponding recv_rtp_sink_\%u pad is requested on #GstRtpBin.
87  *
88  * <refsect2>
89  * <title>Example pipelines</title>
90  * |[
91  * gst-launch-1.0 udpsrc port=5000 caps="application/x-rtp, ..." ! .recv_rtp_sink_0 \
92  *     rtpbin ! rtptheoradepay ! theoradec ! xvimagesink
93  * ]| Receive RTP data from port 5000 and send to the session 0 in rtpbin.
94  * |[
95  * gst-launch-1.0 rtpbin name=rtpbin \
96  *         v4l2src ! videoconvert ! ffenc_h263 ! rtph263ppay ! rtpbin.send_rtp_sink_0 \
97  *                   rtpbin.send_rtp_src_0 ! udpsink port=5000                            \
98  *                   rtpbin.send_rtcp_src_0 ! udpsink port=5001 sync=false async=false    \
99  *                   udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0                           \
100  *         audiotestsrc ! amrnbenc ! rtpamrpay ! rtpbin.send_rtp_sink_1                   \
101  *                   rtpbin.send_rtp_src_1 ! udpsink port=5002                            \
102  *                   rtpbin.send_rtcp_src_1 ! udpsink port=5003 sync=false async=false    \
103  *                   udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1
104  * ]| Encode and payload H263 video captured from a v4l2src. Encode and payload AMR
105  * audio generated from audiotestsrc. The video is sent to session 0 in rtpbin
106  * and the audio is sent to session 1. Video packets are sent on UDP port 5000
107  * and audio packets on port 5002. The video RTCP packets for session 0 are sent
108  * on port 5001 and the audio RTCP packets for session 0 are sent on port 5003.
109  * RTCP packets for session 0 are received on port 5005 and RTCP for session 1
110  * is received on port 5007. Since RTCP packets from the sender should be sent
111  * as soon as possible and do not participate in preroll, sync=false and
112  * async=false is configured on udpsink
113  * |[
114  * gst-launch-1.0 -v rtpbin name=rtpbin                                          \
115  *     udpsrc caps="application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)H263-1998" \
116  *             port=5000 ! rtpbin.recv_rtp_sink_0                                \
117  *         rtpbin. ! rtph263pdepay ! ffdec_h263 ! xvimagesink                    \
118  *      udpsrc port=5001 ! rtpbin.recv_rtcp_sink_0                               \
119  *      rtpbin.send_rtcp_src_0 ! udpsink port=5005 sync=false async=false        \
120  *     udpsrc caps="application/x-rtp,media=(string)audio,clock-rate=(int)8000,encoding-name=(string)AMR,encoding-params=(string)1,octet-align=(string)1" \
121  *             port=5002 ! rtpbin.recv_rtp_sink_1                                \
122  *         rtpbin. ! rtpamrdepay ! amrnbdec ! alsasink                           \
123  *      udpsrc port=5003 ! rtpbin.recv_rtcp_sink_1                               \
124  *      rtpbin.send_rtcp_src_1 ! udpsink port=5007 sync=false async=false
125  * ]| Receive H263 on port 5000, send it through rtpbin in session 0, depayload,
126  * decode and display the video.
127  * Receive AMR on port 5002, send it through rtpbin in session 1, depayload,
128  * decode and play the audio.
129  * Receive server RTCP packets for session 0 on port 5001 and RTCP packets for
130  * session 1 on port 5003. These packets will be used for session management and
131  * synchronisation.
132  * Send RTCP reports for session 0 on port 5005 and RTCP reports for session 1
133  * on port 5007.
134  * </refsect2>
135  */
136
137 #ifdef HAVE_CONFIG_H
138 #include "config.h"
139 #endif
140 #include <stdio.h>
141 #include <string.h>
142
143 #include <gst/rtp/gstrtpbuffer.h>
144 #include <gst/rtp/gstrtcpbuffer.h>
145
146 #include "gstrtpbin.h"
147 #include "rtpsession.h"
148 #include "gstrtpsession.h"
149 #include "gstrtpjitterbuffer.h"
150
151 #include <gst/glib-compat-private.h>
152
153 GST_DEBUG_CATEGORY_STATIC (gst_rtp_bin_debug);
154 #define GST_CAT_DEFAULT gst_rtp_bin_debug
155
156 /* sink pads */
157 static GstStaticPadTemplate rtpbin_recv_rtp_sink_template =
158     GST_STATIC_PAD_TEMPLATE ("recv_rtp_sink_%u",
159     GST_PAD_SINK,
160     GST_PAD_REQUEST,
161     GST_STATIC_CAPS ("application/x-rtp;application/x-srtp")
162     );
163
164 static GstStaticPadTemplate rtpbin_recv_rtcp_sink_template =
165     GST_STATIC_PAD_TEMPLATE ("recv_rtcp_sink_%u",
166     GST_PAD_SINK,
167     GST_PAD_REQUEST,
168     GST_STATIC_CAPS ("application/x-rtcp;application/x-srtcp")
169     );
170
171 static GstStaticPadTemplate rtpbin_send_rtp_sink_template =
172 GST_STATIC_PAD_TEMPLATE ("send_rtp_sink_%u",
173     GST_PAD_SINK,
174     GST_PAD_REQUEST,
175     GST_STATIC_CAPS ("application/x-rtp")
176     );
177
178 /* src pads */
179 static GstStaticPadTemplate rtpbin_recv_rtp_src_template =
180 GST_STATIC_PAD_TEMPLATE ("recv_rtp_src_%u_%u_%u",
181     GST_PAD_SRC,
182     GST_PAD_SOMETIMES,
183     GST_STATIC_CAPS ("application/x-rtp")
184     );
185
186 static GstStaticPadTemplate rtpbin_send_rtcp_src_template =
187     GST_STATIC_PAD_TEMPLATE ("send_rtcp_src_%u",
188     GST_PAD_SRC,
189     GST_PAD_REQUEST,
190     GST_STATIC_CAPS ("application/x-rtcp;application/x-srtcp")
191     );
192
193 static GstStaticPadTemplate rtpbin_send_rtp_src_template =
194     GST_STATIC_PAD_TEMPLATE ("send_rtp_src_%u",
195     GST_PAD_SRC,
196     GST_PAD_SOMETIMES,
197     GST_STATIC_CAPS ("application/x-rtp;application/x-srtp")
198     );
199
200 #define GST_RTP_BIN_LOCK(bin)   g_mutex_lock (&(bin)->priv->bin_lock)
201 #define GST_RTP_BIN_UNLOCK(bin) g_mutex_unlock (&(bin)->priv->bin_lock)
202
203 /* lock to protect dynamic callbacks, like pad-added and new ssrc. */
204 #define GST_RTP_BIN_DYN_LOCK(bin)    g_mutex_lock (&(bin)->priv->dyn_lock)
205 #define GST_RTP_BIN_DYN_UNLOCK(bin)  g_mutex_unlock (&(bin)->priv->dyn_lock)
206
207 /* lock for shutdown */
208 #define GST_RTP_BIN_SHUTDOWN_LOCK(bin,label)     \
209 G_STMT_START {                                   \
210   if (g_atomic_int_get (&bin->priv->shutdown))   \
211     goto label;                                  \
212   GST_RTP_BIN_DYN_LOCK (bin);                    \
213   if (g_atomic_int_get (&bin->priv->shutdown)) { \
214     GST_RTP_BIN_DYN_UNLOCK (bin);                \
215     goto label;                                  \
216   }                                              \
217 } G_STMT_END
218
219 /* unlock for shutdown */
220 #define GST_RTP_BIN_SHUTDOWN_UNLOCK(bin)         \
221   GST_RTP_BIN_DYN_UNLOCK (bin);                  \
222
223 /* Minimum time offset to apply. This compensates for rounding errors in NTP to
224  * RTP timestamp conversions */
225 #define MIN_TS_OFFSET (4 * GST_MSECOND)
226
227 struct _GstRtpBinPrivate
228 {
229   GMutex bin_lock;
230
231   /* lock protecting dynamic adding/removing */
232   GMutex dyn_lock;
233
234   /* if we are shutting down or not */
235   gint shutdown;
236
237   gboolean autoremove;
238
239   /* NTP time in ns of last SR sync used */
240   guint64 last_ntpnstime;
241
242   /* list of extra elements */
243   GList *elements;
244 };
245
246 /* signals and args */
247 enum
248 {
249   SIGNAL_REQUEST_PT_MAP,
250   SIGNAL_PAYLOAD_TYPE_CHANGE,
251   SIGNAL_CLEAR_PT_MAP,
252   SIGNAL_RESET_SYNC,
253   SIGNAL_GET_SESSION,
254   SIGNAL_GET_INTERNAL_SESSION,
255   SIGNAL_GET_STORAGE,
256   SIGNAL_GET_INTERNAL_STORAGE,
257
258   SIGNAL_ON_NEW_SSRC,
259   SIGNAL_ON_SSRC_COLLISION,
260   SIGNAL_ON_SSRC_VALIDATED,
261   SIGNAL_ON_SSRC_ACTIVE,
262   SIGNAL_ON_SSRC_SDES,
263   SIGNAL_ON_BYE_SSRC,
264   SIGNAL_ON_BYE_TIMEOUT,
265   SIGNAL_ON_TIMEOUT,
266   SIGNAL_ON_SENDER_TIMEOUT,
267   SIGNAL_ON_NPT_STOP,
268
269   SIGNAL_REQUEST_RTP_ENCODER,
270   SIGNAL_REQUEST_RTP_DECODER,
271   SIGNAL_REQUEST_RTCP_ENCODER,
272   SIGNAL_REQUEST_RTCP_DECODER,
273
274   SIGNAL_REQUEST_FEC_DECODER,
275   SIGNAL_REQUEST_FEC_ENCODER,
276
277   SIGNAL_NEW_JITTERBUFFER,
278   SIGNAL_NEW_STORAGE,
279
280   SIGNAL_REQUEST_AUX_SENDER,
281   SIGNAL_REQUEST_AUX_RECEIVER,
282
283   SIGNAL_ON_NEW_SENDER_SSRC,
284   SIGNAL_ON_SENDER_SSRC_ACTIVE,
285
286   SIGNAL_ON_BUNDLED_SSRC,
287
288   LAST_SIGNAL
289 };
290
291 #define DEFAULT_LATENCY_MS           200
292 #define DEFAULT_DROP_ON_LATENCY      FALSE
293 #define DEFAULT_SDES                 NULL
294 #define DEFAULT_DO_LOST              FALSE
295 #define DEFAULT_IGNORE_PT            FALSE
296 #define DEFAULT_NTP_SYNC             FALSE
297 #define DEFAULT_AUTOREMOVE           FALSE
298 #define DEFAULT_BUFFER_MODE          RTP_JITTER_BUFFER_MODE_SLAVE
299 #define DEFAULT_USE_PIPELINE_CLOCK   FALSE
300 #define DEFAULT_RTCP_SYNC            GST_RTP_BIN_RTCP_SYNC_ALWAYS
301 #define DEFAULT_RTCP_SYNC_INTERVAL   0
302 #define DEFAULT_DO_SYNC_EVENT        FALSE
303 #define DEFAULT_DO_RETRANSMISSION    FALSE
304 #define DEFAULT_RTP_PROFILE          GST_RTP_PROFILE_AVP
305 #define DEFAULT_NTP_TIME_SOURCE      GST_RTP_NTP_TIME_SOURCE_NTP
306 #define DEFAULT_RTCP_SYNC_SEND_TIME  TRUE
307 #define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
308 #define DEFAULT_MAX_DROPOUT_TIME     60000
309 #define DEFAULT_MAX_MISORDER_TIME    2000
310 #define DEFAULT_RFC7273_SYNC         FALSE
311 #define DEFAULT_MAX_STREAMS          G_MAXUINT
312 #define DEFAULT_MAX_TS_OFFSET_ADJUSTMENT G_GUINT64_CONSTANT(0)
313 #define DEFAULT_MAX_TS_OFFSET        G_GINT64_CONSTANT(3000000000)
314
315 enum
316 {
317   PROP_0,
318   PROP_LATENCY,
319   PROP_DROP_ON_LATENCY,
320   PROP_SDES,
321   PROP_DO_LOST,
322   PROP_IGNORE_PT,
323   PROP_NTP_SYNC,
324   PROP_RTCP_SYNC,
325   PROP_RTCP_SYNC_INTERVAL,
326   PROP_AUTOREMOVE,
327   PROP_BUFFER_MODE,
328   PROP_USE_PIPELINE_CLOCK,
329   PROP_DO_SYNC_EVENT,
330   PROP_DO_RETRANSMISSION,
331   PROP_RTP_PROFILE,
332   PROP_NTP_TIME_SOURCE,
333   PROP_RTCP_SYNC_SEND_TIME,
334   PROP_MAX_RTCP_RTP_TIME_DIFF,
335   PROP_MAX_DROPOUT_TIME,
336   PROP_MAX_MISORDER_TIME,
337   PROP_RFC7273_SYNC,
338   PROP_MAX_STREAMS,
339   PROP_MAX_TS_OFFSET_ADJUSTMENT,
340   PROP_MAX_TS_OFFSET,
341 };
342
343 #define GST_RTP_BIN_RTCP_SYNC_TYPE (gst_rtp_bin_rtcp_sync_get_type())
344 static GType
345 gst_rtp_bin_rtcp_sync_get_type (void)
346 {
347   static GType rtcp_sync_type = 0;
348   static const GEnumValue rtcp_sync_types[] = {
349     {GST_RTP_BIN_RTCP_SYNC_ALWAYS, "always", "always"},
350     {GST_RTP_BIN_RTCP_SYNC_INITIAL, "initial", "initial"},
351     {GST_RTP_BIN_RTCP_SYNC_RTP, "rtp-info", "rtp-info"},
352     {0, NULL, NULL},
353   };
354
355   if (!rtcp_sync_type) {
356     rtcp_sync_type = g_enum_register_static ("GstRTCPSync", rtcp_sync_types);
357   }
358   return rtcp_sync_type;
359 }
360
361 /* helper objects */
362 typedef struct _GstRtpBinSession GstRtpBinSession;
363 typedef struct _GstRtpBinStream GstRtpBinStream;
364 typedef struct _GstRtpBinClient GstRtpBinClient;
365
366 static guint gst_rtp_bin_signals[LAST_SIGNAL] = { 0 };
367
368 static GstCaps *pt_map_requested (GstElement * element, guint pt,
369     GstRtpBinSession * session);
370 static void payload_type_change (GstElement * element, guint pt,
371     GstRtpBinSession * session);
372 static void remove_recv_rtp (GstRtpBin * rtpbin, GstRtpBinSession * session);
373 static void remove_recv_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session);
374 static void remove_send_rtp (GstRtpBin * rtpbin, GstRtpBinSession * session);
375 static void remove_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session);
376 static void free_client (GstRtpBinClient * client, GstRtpBin * bin);
377 static void free_stream (GstRtpBinStream * stream, GstRtpBin * bin);
378 static GstRtpBinSession *create_session (GstRtpBin * rtpbin, gint id);
379 static GstPad *complete_session_sink (GstRtpBin * rtpbin,
380     GstRtpBinSession * session);
381 static void
382 complete_session_receiver (GstRtpBin * rtpbin, GstRtpBinSession * session,
383     guint sessid);
384 static GstPad *complete_session_rtcp (GstRtpBin * rtpbin,
385     GstRtpBinSession * session, guint sessid);
386
387 /* Manages the RTP stream for one SSRC.
388  *
389  * We pipe the stream (comming from the SSRC demuxer) into a jitterbuffer.
390  * If we see an SDES RTCP packet that links multiple SSRCs together based on a
391  * common CNAME, we create a GstRtpBinClient structure to group the SSRCs
392  * together (see below).
393  */
394 struct _GstRtpBinStream
395 {
396   /* the SSRC of this stream */
397   guint32 ssrc;
398
399   /* parent bin */
400   GstRtpBin *bin;
401
402   /* the session this SSRC belongs to */
403   GstRtpBinSession *session;
404
405   /* the jitterbuffer of the SSRC */
406   GstElement *buffer;
407   gulong buffer_handlesync_sig;
408   gulong buffer_ptreq_sig;
409   gulong buffer_ntpstop_sig;
410   gint percent;
411
412   /* the PT demuxer of the SSRC */
413   GstElement *demux;
414   gulong demux_newpad_sig;
415   gulong demux_padremoved_sig;
416   gulong demux_ptreq_sig;
417   gulong demux_ptchange_sig;
418
419   /* if we have calculated a valid rt_delta for this stream */
420   gboolean have_sync;
421   /* mapping to local RTP and NTP time */
422   gint64 rt_delta;
423   gint64 rtp_delta;
424   /* base rtptime in gst time */
425   gint64 clock_base;
426 };
427
428 #define GST_RTP_SESSION_LOCK(sess)   g_mutex_lock (&(sess)->lock)
429 #define GST_RTP_SESSION_UNLOCK(sess) g_mutex_unlock (&(sess)->lock)
430
431 /* Manages the receiving end of the packets.
432  *
433  * There is one such structure for each RTP session (audio/video/...).
434  * We get the RTP/RTCP packets and stuff them into the session manager. From
435  * there they are pushed into an SSRC demuxer that splits the stream based on
436  * SSRC. Each of the SSRC streams go into their own jitterbuffer (managed with
437  * the GstRtpBinStream above).
438  *
439  * Before the SSRC demuxer, a storage element may be inserted for the purpose
440  * of Forward Error Correction.
441  */
442 struct _GstRtpBinSession
443 {
444   /* session id */
445   gint id;
446   /* the parent bin */
447   GstRtpBin *bin;
448   /* the session element */
449   GstElement *session;
450   /* the SSRC demuxer */
451   GstElement *demux;
452   gulong demux_newpad_sig;
453   gulong demux_padremoved_sig;
454
455   /* Fec support */
456   GstElement *storage;
457
458   GMutex lock;
459
460   /* list of GstRtpBinStream */
461   GSList *streams;
462
463   /* list of elements */
464   GSList *elements;
465
466   /* mapping of payload type to caps */
467   GHashTable *ptmap;
468
469   /* the pads of the session */
470   GstPad *recv_rtp_sink;
471   GstPad *recv_rtp_sink_ghost;
472   GstPad *recv_rtp_src;
473   GstPad *recv_rtcp_sink;
474   GstPad *recv_rtcp_sink_ghost;
475   GstPad *sync_src;
476   GstPad *send_rtp_sink;
477   GstPad *send_rtp_sink_ghost;
478   GstPad *send_rtp_src_ghost;
479   GstPad *send_rtcp_src;
480   GstPad *send_rtcp_src_ghost;
481 };
482
483 /* Manages the RTP streams that come from one client and should therefore be
484  * synchronized.
485  */
486 struct _GstRtpBinClient
487 {
488   /* the common CNAME for the streams */
489   gchar *cname;
490   guint cname_len;
491
492   /* the streams */
493   guint nstreams;
494   GSList *streams;
495 };
496
497 /* find a session with the given id. Must be called with RTP_BIN_LOCK */
498 static GstRtpBinSession *
499 find_session_by_id (GstRtpBin * rtpbin, gint id)
500 {
501   GSList *walk;
502
503   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
504     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
505
506     if (sess->id == id)
507       return sess;
508   }
509   return NULL;
510 }
511
512 /* find a session with the given request pad. Must be called with RTP_BIN_LOCK */
513 static GstRtpBinSession *
514 find_session_by_pad (GstRtpBin * rtpbin, GstPad * pad)
515 {
516   GSList *walk;
517
518   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
519     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
520
521     if ((sess->recv_rtp_sink_ghost == pad) ||
522         (sess->recv_rtcp_sink_ghost == pad) ||
523         (sess->send_rtp_sink_ghost == pad)
524         || (sess->send_rtcp_src_ghost == pad))
525       return sess;
526   }
527   return NULL;
528 }
529
530 static void
531 on_new_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
532 {
533   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC], 0,
534       sess->id, ssrc);
535 }
536
537 static void
538 on_ssrc_collision (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
539 {
540   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION], 0,
541       sess->id, ssrc);
542 }
543
544 static void
545 on_ssrc_validated (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
546 {
547   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
548       sess->id, ssrc);
549 }
550
551 static void
552 on_ssrc_active (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
553 {
554   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_ACTIVE], 0,
555       sess->id, ssrc);
556 }
557
558 static void
559 on_ssrc_sdes (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
560 {
561   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_SDES], 0,
562       sess->id, ssrc);
563 }
564
565 static void
566 on_bye_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
567 {
568   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC], 0,
569       sess->id, ssrc);
570 }
571
572 static void
573 on_bye_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
574 {
575   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT], 0,
576       sess->id, ssrc);
577
578   if (sess->bin->priv->autoremove)
579     g_signal_emit_by_name (sess->demux, "clear-ssrc", ssrc, NULL);
580 }
581
582 static void
583 on_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
584 {
585   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT], 0,
586       sess->id, ssrc);
587
588   if (sess->bin->priv->autoremove)
589     g_signal_emit_by_name (sess->demux, "clear-ssrc", ssrc, NULL);
590 }
591
592 static void
593 on_sender_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
594 {
595   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SENDER_TIMEOUT], 0,
596       sess->id, ssrc);
597 }
598
599 static void
600 on_npt_stop (GstElement * jbuf, GstRtpBinStream * stream)
601 {
602   g_signal_emit (stream->bin, gst_rtp_bin_signals[SIGNAL_ON_NPT_STOP], 0,
603       stream->session->id, stream->ssrc);
604 }
605
606 static void
607 on_new_sender_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
608 {
609   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_NEW_SENDER_SSRC], 0,
610       sess->id, ssrc);
611 }
612
613 static void
614 on_sender_ssrc_active (GstElement * session, guint32 ssrc,
615     GstRtpBinSession * sess)
616 {
617   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SENDER_SSRC_ACTIVE],
618       0, sess->id, ssrc);
619 }
620
621 /* must be called with the SESSION lock */
622 static GstRtpBinStream *
623 find_stream_by_ssrc (GstRtpBinSession * session, guint32 ssrc)
624 {
625   GSList *walk;
626
627   for (walk = session->streams; walk; walk = g_slist_next (walk)) {
628     GstRtpBinStream *stream = (GstRtpBinStream *) walk->data;
629
630     if (stream->ssrc == ssrc)
631       return stream;
632   }
633   return NULL;
634 }
635
636 static void
637 ssrc_demux_pad_removed (GstElement * element, guint ssrc, GstPad * pad,
638     GstRtpBinSession * session)
639 {
640   GstRtpBinStream *stream = NULL;
641   GstRtpBin *rtpbin;
642
643   rtpbin = session->bin;
644
645   GST_RTP_BIN_LOCK (rtpbin);
646
647   GST_RTP_SESSION_LOCK (session);
648   if ((stream = find_stream_by_ssrc (session, ssrc)))
649     session->streams = g_slist_remove (session->streams, stream);
650   GST_RTP_SESSION_UNLOCK (session);
651
652   if (stream)
653     free_stream (stream, rtpbin);
654
655   GST_RTP_BIN_UNLOCK (rtpbin);
656 }
657
658 /* create a session with the given id.  Must be called with RTP_BIN_LOCK */
659 static GstRtpBinSession *
660 create_session (GstRtpBin * rtpbin, gint id)
661 {
662   GstRtpBinSession *sess;
663   GstElement *session, *demux;
664   GstElement *storage = NULL;
665   GstState target;
666
667   if (!(session = gst_element_factory_make ("rtpsession", NULL)))
668     goto no_session;
669
670   if (!(demux = gst_element_factory_make ("rtpssrcdemux", NULL)))
671     goto no_demux;
672
673   if (!(storage = gst_element_factory_make ("rtpstorage", NULL)))
674     goto no_storage;
675
676   /* need to sink the storage or otherwise signal handlers from bindings will
677    * take ownership of it and we don't own it anymore */
678   gst_object_ref_sink (storage);
679   g_signal_emit (rtpbin, gst_rtp_bin_signals[SIGNAL_NEW_STORAGE], 0, storage,
680       id);
681
682   sess = g_new0 (GstRtpBinSession, 1);
683   g_mutex_init (&sess->lock);
684   sess->id = id;
685   sess->bin = rtpbin;
686   sess->session = session;
687   sess->demux = demux;
688   sess->storage = storage;
689
690   sess->ptmap = g_hash_table_new_full (NULL, NULL, NULL,
691       (GDestroyNotify) gst_caps_unref);
692   rtpbin->sessions = g_slist_prepend (rtpbin->sessions, sess);
693
694   /* configure SDES items */
695   GST_OBJECT_LOCK (rtpbin);
696   g_object_set (session, "sdes", rtpbin->sdes, "rtp-profile",
697       rtpbin->rtp_profile, "rtcp-sync-send-time", rtpbin->rtcp_sync_send_time,
698       NULL);
699   if (rtpbin->use_pipeline_clock)
700     g_object_set (session, "use-pipeline-clock", rtpbin->use_pipeline_clock,
701         NULL);
702   else
703     g_object_set (session, "ntp-time-source", rtpbin->ntp_time_source, NULL);
704
705   g_object_set (session, "max-dropout-time", rtpbin->max_dropout_time,
706       "max-misorder-time", rtpbin->max_misorder_time, NULL);
707   GST_OBJECT_UNLOCK (rtpbin);
708
709   /* provide clock_rate to the session manager when needed */
710   g_signal_connect (session, "request-pt-map",
711       (GCallback) pt_map_requested, sess);
712
713   g_signal_connect (sess->session, "on-new-ssrc",
714       (GCallback) on_new_ssrc, sess);
715   g_signal_connect (sess->session, "on-ssrc-collision",
716       (GCallback) on_ssrc_collision, sess);
717   g_signal_connect (sess->session, "on-ssrc-validated",
718       (GCallback) on_ssrc_validated, sess);
719   g_signal_connect (sess->session, "on-ssrc-active",
720       (GCallback) on_ssrc_active, sess);
721   g_signal_connect (sess->session, "on-ssrc-sdes",
722       (GCallback) on_ssrc_sdes, sess);
723   g_signal_connect (sess->session, "on-bye-ssrc",
724       (GCallback) on_bye_ssrc, sess);
725   g_signal_connect (sess->session, "on-bye-timeout",
726       (GCallback) on_bye_timeout, sess);
727   g_signal_connect (sess->session, "on-timeout", (GCallback) on_timeout, sess);
728   g_signal_connect (sess->session, "on-sender-timeout",
729       (GCallback) on_sender_timeout, sess);
730   g_signal_connect (sess->session, "on-new-sender-ssrc",
731       (GCallback) on_new_sender_ssrc, sess);
732   g_signal_connect (sess->session, "on-sender-ssrc-active",
733       (GCallback) on_sender_ssrc_active, sess);
734
735   gst_bin_add (GST_BIN_CAST (rtpbin), session);
736   gst_bin_add (GST_BIN_CAST (rtpbin), demux);
737   gst_bin_add (GST_BIN_CAST (rtpbin), storage);
738
739   /* unref the storage again, the bin has a reference now and
740    * we don't need it anymore */
741   gst_object_unref (storage);
742
743   GST_OBJECT_LOCK (rtpbin);
744   target = GST_STATE_TARGET (rtpbin);
745   GST_OBJECT_UNLOCK (rtpbin);
746
747   /* change state only to what's needed */
748   gst_element_set_state (demux, target);
749   gst_element_set_state (session, target);
750   gst_element_set_state (storage, target);
751
752   return sess;
753
754   /* ERRORS */
755 no_session:
756   {
757     g_warning ("rtpbin: could not create rtpsession element");
758     return NULL;
759   }
760 no_demux:
761   {
762     gst_object_unref (session);
763     g_warning ("rtpbin: could not create rtpssrcdemux element");
764     return NULL;
765   }
766 no_storage:
767   {
768     gst_object_unref (session);
769     gst_object_unref (demux);
770     g_warning ("rtpbin: could not create rtpstorage element");
771     return NULL;
772   }
773 }
774
775 static gboolean
776 bin_manage_element (GstRtpBin * bin, GstElement * element)
777 {
778   GstRtpBinPrivate *priv = bin->priv;
779
780   if (g_list_find (priv->elements, element)) {
781     GST_DEBUG_OBJECT (bin, "requested element %p already in bin", element);
782   } else {
783     GST_DEBUG_OBJECT (bin, "adding requested element %p", element);
784
785     if (g_object_is_floating (element))
786       element = gst_object_ref_sink (element);
787
788     if (!gst_bin_add (GST_BIN_CAST (bin), element))
789       goto add_failed;
790     if (!gst_element_sync_state_with_parent (element))
791       GST_WARNING_OBJECT (bin, "unable to sync element state with rtpbin");
792   }
793   /* we add the element multiple times, each we need an equal number of
794    * removes to really remove the element from the bin */
795   priv->elements = g_list_prepend (priv->elements, element);
796
797   return TRUE;
798
799   /* ERRORS */
800 add_failed:
801   {
802     GST_WARNING_OBJECT (bin, "unable to add element");
803     gst_object_unref (element);
804     return FALSE;
805   }
806 }
807
808 static void
809 remove_bin_element (GstElement * element, GstRtpBin * bin)
810 {
811   GstRtpBinPrivate *priv = bin->priv;
812   GList *find;
813
814   find = g_list_find (priv->elements, element);
815   if (find) {
816     priv->elements = g_list_delete_link (priv->elements, find);
817
818     if (!g_list_find (priv->elements, element)) {
819       gst_element_set_locked_state (element, TRUE);
820       gst_bin_remove (GST_BIN_CAST (bin), element);
821       gst_element_set_state (element, GST_STATE_NULL);
822     }
823
824     gst_object_unref (element);
825   }
826 }
827
828 /* called with RTP_BIN_LOCK */
829 static void
830 free_session (GstRtpBinSession * sess, GstRtpBin * bin)
831 {
832   GST_DEBUG_OBJECT (bin, "freeing session %p", sess);
833
834   gst_element_set_locked_state (sess->demux, TRUE);
835   gst_element_set_locked_state (sess->session, TRUE);
836
837   gst_element_set_state (sess->demux, GST_STATE_NULL);
838   gst_element_set_state (sess->session, GST_STATE_NULL);
839
840   remove_recv_rtp (bin, sess);
841   remove_recv_rtcp (bin, sess);
842   remove_send_rtp (bin, sess);
843   remove_rtcp (bin, sess);
844
845   gst_bin_remove (GST_BIN_CAST (bin), sess->session);
846   gst_bin_remove (GST_BIN_CAST (bin), sess->demux);
847
848   g_slist_foreach (sess->elements, (GFunc) remove_bin_element, bin);
849   g_slist_free (sess->elements);
850
851   g_slist_foreach (sess->streams, (GFunc) free_stream, bin);
852   g_slist_free (sess->streams);
853
854   g_mutex_clear (&sess->lock);
855   g_hash_table_destroy (sess->ptmap);
856
857   g_free (sess);
858 }
859
860 /* get the payload type caps for the specific payload @pt in @session */
861 static GstCaps *
862 get_pt_map (GstRtpBinSession * session, guint pt)
863 {
864   GstCaps *caps = NULL;
865   GstRtpBin *bin;
866   GValue ret = { 0 };
867   GValue args[3] = { {0}, {0}, {0} };
868
869   GST_DEBUG ("searching pt %u in cache", pt);
870
871   GST_RTP_SESSION_LOCK (session);
872
873   /* first look in the cache */
874   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
875   if (caps) {
876     gst_caps_ref (caps);
877     goto done;
878   }
879
880   bin = session->bin;
881
882   GST_DEBUG ("emiting signal for pt %u in session %u", pt, session->id);
883
884   /* not in cache, send signal to request caps */
885   g_value_init (&args[0], GST_TYPE_ELEMENT);
886   g_value_set_object (&args[0], bin);
887   g_value_init (&args[1], G_TYPE_UINT);
888   g_value_set_uint (&args[1], session->id);
889   g_value_init (&args[2], G_TYPE_UINT);
890   g_value_set_uint (&args[2], pt);
891
892   g_value_init (&ret, GST_TYPE_CAPS);
893   g_value_set_boxed (&ret, NULL);
894
895   GST_RTP_SESSION_UNLOCK (session);
896
897   g_signal_emitv (args, gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP], 0, &ret);
898
899   GST_RTP_SESSION_LOCK (session);
900
901   g_value_unset (&args[0]);
902   g_value_unset (&args[1]);
903   g_value_unset (&args[2]);
904
905   /* look in the cache again because we let the lock go */
906   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
907   if (caps) {
908     gst_caps_ref (caps);
909     g_value_unset (&ret);
910     goto done;
911   }
912
913   caps = (GstCaps *) g_value_dup_boxed (&ret);
914   g_value_unset (&ret);
915   if (!caps)
916     goto no_caps;
917
918   GST_DEBUG ("caching pt %u as %" GST_PTR_FORMAT, pt, caps);
919
920   /* store in cache, take additional ref */
921   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (pt),
922       gst_caps_ref (caps));
923
924 done:
925   GST_RTP_SESSION_UNLOCK (session);
926
927   return caps;
928
929   /* ERRORS */
930 no_caps:
931   {
932     GST_RTP_SESSION_UNLOCK (session);
933     GST_DEBUG ("no pt map could be obtained");
934     return NULL;
935   }
936 }
937
938 static gboolean
939 return_true (gpointer key, gpointer value, gpointer user_data)
940 {
941   return TRUE;
942 }
943
944 static void
945 gst_rtp_bin_reset_sync (GstRtpBin * rtpbin)
946 {
947   GSList *clients, *streams;
948
949   GST_DEBUG_OBJECT (rtpbin, "Reset sync on all clients");
950
951   GST_RTP_BIN_LOCK (rtpbin);
952   for (clients = rtpbin->clients; clients; clients = g_slist_next (clients)) {
953     GstRtpBinClient *client = (GstRtpBinClient *) clients->data;
954
955     /* reset sync on all streams for this client */
956     for (streams = client->streams; streams; streams = g_slist_next (streams)) {
957       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
958
959       /* make use require a new SR packet for this stream before we attempt new
960        * lip-sync */
961       stream->have_sync = FALSE;
962       stream->rt_delta = 0;
963       stream->rtp_delta = 0;
964       stream->clock_base = -100 * GST_SECOND;
965     }
966   }
967   GST_RTP_BIN_UNLOCK (rtpbin);
968 }
969
970 static void
971 gst_rtp_bin_clear_pt_map (GstRtpBin * bin)
972 {
973   GSList *sessions, *streams;
974
975   GST_RTP_BIN_LOCK (bin);
976   GST_DEBUG_OBJECT (bin, "clearing pt map");
977   for (sessions = bin->sessions; sessions; sessions = g_slist_next (sessions)) {
978     GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
979
980     GST_DEBUG_OBJECT (bin, "clearing session %p", session);
981     g_signal_emit_by_name (session->session, "clear-pt-map", NULL);
982
983     GST_RTP_SESSION_LOCK (session);
984     g_hash_table_foreach_remove (session->ptmap, return_true, NULL);
985
986     for (streams = session->streams; streams; streams = g_slist_next (streams)) {
987       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
988
989       GST_DEBUG_OBJECT (bin, "clearing stream %p", stream);
990       g_signal_emit_by_name (stream->buffer, "clear-pt-map", NULL);
991       if (stream->demux)
992         g_signal_emit_by_name (stream->demux, "clear-pt-map", NULL);
993     }
994     GST_RTP_SESSION_UNLOCK (session);
995   }
996   GST_RTP_BIN_UNLOCK (bin);
997
998   /* reset sync too */
999   gst_rtp_bin_reset_sync (bin);
1000 }
1001
1002 static GstElement *
1003 gst_rtp_bin_get_session (GstRtpBin * bin, guint session_id)
1004 {
1005   GstRtpBinSession *session;
1006   GstElement *ret = NULL;
1007
1008   GST_RTP_BIN_LOCK (bin);
1009   GST_DEBUG_OBJECT (bin, "retrieving GstRtpSession, index: %u", session_id);
1010   session = find_session_by_id (bin, (gint) session_id);
1011   if (session) {
1012     ret = gst_object_ref (session->session);
1013   }
1014   GST_RTP_BIN_UNLOCK (bin);
1015
1016   return ret;
1017 }
1018
1019 static RTPSession *
1020 gst_rtp_bin_get_internal_session (GstRtpBin * bin, guint session_id)
1021 {
1022   RTPSession *internal_session = NULL;
1023   GstRtpBinSession *session;
1024
1025   GST_RTP_BIN_LOCK (bin);
1026   GST_DEBUG_OBJECT (bin, "retrieving internal RTPSession object, index: %u",
1027       session_id);
1028   session = find_session_by_id (bin, (gint) session_id);
1029   if (session) {
1030     g_object_get (session->session, "internal-session", &internal_session,
1031         NULL);
1032   }
1033   GST_RTP_BIN_UNLOCK (bin);
1034
1035   return internal_session;
1036 }
1037
1038 static GstElement *
1039 gst_rtp_bin_get_storage (GstRtpBin * bin, guint session_id)
1040 {
1041   GstRtpBinSession *session;
1042   GstElement *res = NULL;
1043
1044   GST_RTP_BIN_LOCK (bin);
1045   GST_DEBUG_OBJECT (bin, "retrieving internal storage object, index: %u",
1046       session_id);
1047   session = find_session_by_id (bin, (gint) session_id);
1048   if (session && session->storage) {
1049     res = gst_object_ref (session->storage);
1050   }
1051   GST_RTP_BIN_UNLOCK (bin);
1052
1053   return res;
1054 }
1055
1056 static GObject *
1057 gst_rtp_bin_get_internal_storage (GstRtpBin * bin, guint session_id)
1058 {
1059   GObject *internal_storage = NULL;
1060   GstRtpBinSession *session;
1061
1062   GST_RTP_BIN_LOCK (bin);
1063   GST_DEBUG_OBJECT (bin, "retrieving internal storage object, index: %u",
1064       session_id);
1065   session = find_session_by_id (bin, (gint) session_id);
1066   if (session && session->storage) {
1067     g_object_get (session->storage, "internal-storage", &internal_storage,
1068         NULL);
1069   }
1070   GST_RTP_BIN_UNLOCK (bin);
1071
1072   return internal_storage;
1073 }
1074
1075 static GstElement *
1076 gst_rtp_bin_request_encoder (GstRtpBin * bin, guint session_id)
1077 {
1078   GST_DEBUG_OBJECT (bin, "return NULL encoder");
1079   return NULL;
1080 }
1081
1082 static GstElement *
1083 gst_rtp_bin_request_decoder (GstRtpBin * bin, guint session_id)
1084 {
1085   GST_DEBUG_OBJECT (bin, "return NULL decoder");
1086   return NULL;
1087 }
1088
1089 static void
1090 gst_rtp_bin_propagate_property_to_jitterbuffer (GstRtpBin * bin,
1091     const gchar * name, const GValue * value)
1092 {
1093   GSList *sessions, *streams;
1094
1095   GST_RTP_BIN_LOCK (bin);
1096   for (sessions = bin->sessions; sessions; sessions = g_slist_next (sessions)) {
1097     GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
1098
1099     GST_RTP_SESSION_LOCK (session);
1100     for (streams = session->streams; streams; streams = g_slist_next (streams)) {
1101       GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
1102
1103       g_object_set_property (G_OBJECT (stream->buffer), name, value);
1104     }
1105     GST_RTP_SESSION_UNLOCK (session);
1106   }
1107   GST_RTP_BIN_UNLOCK (bin);
1108 }
1109
1110 static void
1111 gst_rtp_bin_propagate_property_to_session (GstRtpBin * bin,
1112     const gchar * name, const GValue * value)
1113 {
1114   GSList *sessions;
1115
1116   GST_RTP_BIN_LOCK (bin);
1117   for (sessions = bin->sessions; sessions; sessions = g_slist_next (sessions)) {
1118     GstRtpBinSession *sess = (GstRtpBinSession *) sessions->data;
1119
1120     g_object_set_property (G_OBJECT (sess->session), name, value);
1121   }
1122   GST_RTP_BIN_UNLOCK (bin);
1123 }
1124
1125 /* get a client with the given SDES name. Must be called with RTP_BIN_LOCK */
1126 static GstRtpBinClient *
1127 get_client (GstRtpBin * bin, guint8 len, guint8 * data, gboolean * created)
1128 {
1129   GstRtpBinClient *result = NULL;
1130   GSList *walk;
1131
1132   for (walk = bin->clients; walk; walk = g_slist_next (walk)) {
1133     GstRtpBinClient *client = (GstRtpBinClient *) walk->data;
1134
1135     if (len != client->cname_len)
1136       continue;
1137
1138     if (!strncmp ((gchar *) data, client->cname, client->cname_len)) {
1139       GST_DEBUG_OBJECT (bin, "found existing client %p with CNAME %s", client,
1140           client->cname);
1141       result = client;
1142       break;
1143     }
1144   }
1145
1146   /* nothing found, create one */
1147   if (result == NULL) {
1148     result = g_new0 (GstRtpBinClient, 1);
1149     result->cname = g_strndup ((gchar *) data, len);
1150     result->cname_len = len;
1151     bin->clients = g_slist_prepend (bin->clients, result);
1152     GST_DEBUG_OBJECT (bin, "created new client %p with CNAME %s", result,
1153         result->cname);
1154   }
1155   return result;
1156 }
1157
1158 static void
1159 free_client (GstRtpBinClient * client, GstRtpBin * bin)
1160 {
1161   GST_DEBUG_OBJECT (bin, "freeing client %p", client);
1162   g_slist_free (client->streams);
1163   g_free (client->cname);
1164   g_free (client);
1165 }
1166
1167 static void
1168 get_current_times (GstRtpBin * bin, GstClockTime * running_time,
1169     guint64 * ntpnstime)
1170 {
1171   guint64 ntpns = -1;
1172   GstClock *clock;
1173   GstClockTime base_time, rt, clock_time;
1174
1175   GST_OBJECT_LOCK (bin);
1176   if ((clock = GST_ELEMENT_CLOCK (bin))) {
1177     base_time = GST_ELEMENT_CAST (bin)->base_time;
1178     gst_object_ref (clock);
1179     GST_OBJECT_UNLOCK (bin);
1180
1181     /* get current clock time and convert to running time */
1182     clock_time = gst_clock_get_time (clock);
1183     rt = clock_time - base_time;
1184
1185     if (bin->use_pipeline_clock) {
1186       ntpns = rt;
1187       /* add constant to convert from 1970 based time to 1900 based time */
1188       ntpns += (2208988800LL * GST_SECOND);
1189     } else {
1190       switch (bin->ntp_time_source) {
1191         case GST_RTP_NTP_TIME_SOURCE_NTP:
1192         case GST_RTP_NTP_TIME_SOURCE_UNIX:{
1193           GTimeVal current;
1194
1195           /* get current NTP time */
1196           g_get_current_time (&current);
1197           ntpns = GST_TIMEVAL_TO_TIME (current);
1198
1199           /* add constant to convert from 1970 based time to 1900 based time */
1200           if (bin->ntp_time_source == GST_RTP_NTP_TIME_SOURCE_NTP)
1201             ntpns += (2208988800LL * GST_SECOND);
1202           break;
1203         }
1204         case GST_RTP_NTP_TIME_SOURCE_RUNNING_TIME:
1205           ntpns = rt;
1206           break;
1207         case GST_RTP_NTP_TIME_SOURCE_CLOCK_TIME:
1208           ntpns = clock_time;
1209           break;
1210         default:
1211           ntpns = -1;           /* Fix uninited compiler warning */
1212           g_assert_not_reached ();
1213           break;
1214       }
1215     }
1216
1217     gst_object_unref (clock);
1218   } else {
1219     GST_OBJECT_UNLOCK (bin);
1220     rt = -1;
1221     ntpns = -1;
1222   }
1223   if (running_time)
1224     *running_time = rt;
1225   if (ntpnstime)
1226     *ntpnstime = ntpns;
1227 }
1228
1229 static void
1230 stream_set_ts_offset (GstRtpBin * bin, GstRtpBinStream * stream,
1231     gint64 ts_offset, gint64 max_ts_offset, gint64 min_ts_offset,
1232     gboolean allow_positive_ts_offset)
1233 {
1234   gint64 prev_ts_offset;
1235
1236   g_object_get (stream->buffer, "ts-offset", &prev_ts_offset, NULL);
1237
1238   /* delta changed, see how much */
1239   if (prev_ts_offset != ts_offset) {
1240     gint64 diff;
1241
1242     diff = prev_ts_offset - ts_offset;
1243
1244     GST_DEBUG_OBJECT (bin,
1245         "ts-offset %" G_GINT64_FORMAT ", prev %" G_GINT64_FORMAT
1246         ", diff: %" G_GINT64_FORMAT, ts_offset, prev_ts_offset, diff);
1247
1248     /* ignore minor offsets */
1249     if (ABS (diff) < min_ts_offset) {
1250       GST_DEBUG_OBJECT (bin, "offset too small, ignoring");
1251       return;
1252     }
1253
1254     /* sanity check offset */
1255     if (max_ts_offset > 0) {
1256       if (ts_offset > 0 && !allow_positive_ts_offset) {
1257         GST_DEBUG_OBJECT (bin,
1258             "offset is positive (clocks are out of sync), ignoring");
1259         return;
1260       }
1261       if (ABS (ts_offset) > max_ts_offset) {
1262         GST_DEBUG_OBJECT (bin, "offset too large, ignoring");
1263         return;
1264       }
1265     }
1266
1267     g_object_set (stream->buffer, "ts-offset", ts_offset, NULL);
1268   }
1269   GST_DEBUG_OBJECT (bin, "stream SSRC %08x, delta %" G_GINT64_FORMAT,
1270       stream->ssrc, ts_offset);
1271 }
1272
1273 static void
1274 gst_rtp_bin_send_sync_event (GstRtpBinStream * stream)
1275 {
1276   if (stream->bin->send_sync_event) {
1277     GstEvent *event;
1278     GstPad *srcpad;
1279
1280     GST_DEBUG_OBJECT (stream->bin,
1281         "sending GstRTCPSRReceived event downstream");
1282
1283     event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
1284         gst_structure_new_empty ("GstRTCPSRReceived"));
1285
1286     srcpad = gst_element_get_static_pad (stream->buffer, "src");
1287     gst_pad_push_event (srcpad, event);
1288     gst_object_unref (srcpad);
1289   }
1290 }
1291
1292 /* associate a stream to the given CNAME. This will make sure all streams for
1293  * that CNAME are synchronized together.
1294  * Must be called with GST_RTP_BIN_LOCK */
1295 static void
1296 gst_rtp_bin_associate (GstRtpBin * bin, GstRtpBinStream * stream, guint8 len,
1297     guint8 * data, guint64 ntptime, guint64 last_extrtptime,
1298     guint64 base_rtptime, guint64 base_time, guint clock_rate,
1299     gint64 rtp_clock_base)
1300 {
1301   GstRtpBinClient *client;
1302   gboolean created;
1303   GSList *walk;
1304   GstClockTime running_time, running_time_rtp;
1305   guint64 ntpnstime;
1306
1307   /* first find or create the CNAME */
1308   client = get_client (bin, len, data, &created);
1309
1310   /* find stream in the client */
1311   for (walk = client->streams; walk; walk = g_slist_next (walk)) {
1312     GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
1313
1314     if (ostream == stream)
1315       break;
1316   }
1317   /* not found, add it to the list */
1318   if (walk == NULL) {
1319     GST_DEBUG_OBJECT (bin,
1320         "new association of SSRC %08x with client %p with CNAME %s",
1321         stream->ssrc, client, client->cname);
1322     client->streams = g_slist_prepend (client->streams, stream);
1323     client->nstreams++;
1324   } else {
1325     GST_DEBUG_OBJECT (bin,
1326         "found association of SSRC %08x with client %p with CNAME %s",
1327         stream->ssrc, client, client->cname);
1328   }
1329
1330   if (!GST_CLOCK_TIME_IS_VALID (last_extrtptime)) {
1331     GST_DEBUG_OBJECT (bin, "invalidated sync data");
1332     if (bin->rtcp_sync == GST_RTP_BIN_RTCP_SYNC_RTP) {
1333       /* we don't need that data, so carry on,
1334        * but make some values look saner */
1335       last_extrtptime = base_rtptime;
1336     } else {
1337       /* nothing we can do with this data in this case */
1338       GST_DEBUG_OBJECT (bin, "bailing out");
1339       return;
1340     }
1341   }
1342
1343   /* Take the extended rtptime we found in the SR packet and map it to the
1344    * local rtptime. The local rtp time is used to construct timestamps on the
1345    * buffers so we will calculate what running_time corresponds to the RTP
1346    * timestamp in the SR packet. */
1347   running_time_rtp = last_extrtptime - base_rtptime;
1348
1349   GST_DEBUG_OBJECT (bin,
1350       "base %" G_GUINT64_FORMAT ", extrtptime %" G_GUINT64_FORMAT
1351       ", local RTP %" G_GUINT64_FORMAT ", clock-rate %d, "
1352       "clock-base %" G_GINT64_FORMAT, base_rtptime,
1353       last_extrtptime, running_time_rtp, clock_rate, rtp_clock_base);
1354
1355   /* calculate local RTP time in gstreamer timestamp, we essentially perform the
1356    * same conversion that a jitterbuffer would use to convert an rtp timestamp
1357    * into a corresponding gstreamer timestamp. Note that the base_time also
1358    * contains the drift between sender and receiver. */
1359   running_time =
1360       gst_util_uint64_scale_int (running_time_rtp, GST_SECOND, clock_rate);
1361   running_time += base_time;
1362
1363   /* convert ntptime to nanoseconds */
1364   ntpnstime = gst_util_uint64_scale (ntptime, GST_SECOND,
1365       (G_GINT64_CONSTANT (1) << 32));
1366
1367   stream->have_sync = TRUE;
1368
1369   GST_DEBUG_OBJECT (bin,
1370       "SR RTP running time %" G_GUINT64_FORMAT ", SR NTP %" G_GUINT64_FORMAT,
1371       running_time, ntpnstime);
1372
1373   /* recalc inter stream playout offset, but only if there is more than one
1374    * stream or we're doing NTP sync. */
1375   if (bin->ntp_sync) {
1376     gint64 ntpdiff, rtdiff;
1377     guint64 local_ntpnstime;
1378     GstClockTime local_running_time;
1379
1380     /* For NTP sync we need to first get a snapshot of running_time and NTP
1381      * time. We know at what running_time we play a certain RTP time, we also
1382      * calculated when we would play the RTP time in the SR packet. Now we need
1383      * to know how the running_time and the NTP time relate to eachother. */
1384     get_current_times (bin, &local_running_time, &local_ntpnstime);
1385
1386     /* see how far away the NTP time is. This is the difference between the
1387      * current NTP time and the NTP time in the last SR packet. */
1388     ntpdiff = local_ntpnstime - ntpnstime;
1389     /* see how far away the running_time is. This is the difference between the
1390      * current running_time and the running_time of the RTP timestamp in the
1391      * last SR packet. */
1392     rtdiff = local_running_time - running_time;
1393
1394     GST_DEBUG_OBJECT (bin,
1395         "local NTP time %" G_GUINT64_FORMAT ", SR NTP time %" G_GUINT64_FORMAT,
1396         local_ntpnstime, ntpnstime);
1397     GST_DEBUG_OBJECT (bin,
1398         "local running time %" G_GUINT64_FORMAT ", SR RTP running time %"
1399         G_GUINT64_FORMAT, local_running_time, running_time);
1400     GST_DEBUG_OBJECT (bin,
1401         "NTP diff %" G_GINT64_FORMAT ", RT diff %" G_GINT64_FORMAT, ntpdiff,
1402         rtdiff);
1403
1404     /* combine to get the final diff to apply to the running_time */
1405     stream->rt_delta = rtdiff - ntpdiff;
1406
1407     stream_set_ts_offset (bin, stream, stream->rt_delta, bin->max_ts_offset,
1408         0, FALSE);
1409   } else {
1410     gint64 min, rtp_min, clock_base = stream->clock_base;
1411     gboolean all_sync, use_rtp;
1412     gboolean rtcp_sync = g_atomic_int_get (&bin->rtcp_sync);
1413
1414     /* calculate delta between server and receiver. ntpnstime is created by
1415      * converting the ntptime in the last SR packet to a gstreamer timestamp. This
1416      * delta expresses the difference to our timeline and the server timeline. The
1417      * difference in itself doesn't mean much but we can combine the delta of
1418      * multiple streams to create a stream specific offset. */
1419     stream->rt_delta = ntpnstime - running_time;
1420
1421     /* calculate the min of all deltas, ignoring streams that did not yet have a
1422      * valid rt_delta because we did not yet receive an SR packet for those
1423      * streams.
1424      * We calculate the mininum because we would like to only apply positive
1425      * offsets to streams, delaying their playback instead of trying to speed up
1426      * other streams (which might be imposible when we have to create negative
1427      * latencies).
1428      * The stream that has the smallest diff is selected as the reference stream,
1429      * all other streams will have a positive offset to this difference. */
1430
1431     /* some alternative setting allow ignoring RTCP as much as possible,
1432      * for servers generating bogus ntp timeline */
1433     min = rtp_min = G_MAXINT64;
1434     use_rtp = FALSE;
1435     if (rtcp_sync == GST_RTP_BIN_RTCP_SYNC_RTP) {
1436       guint64 ext_base;
1437
1438       use_rtp = TRUE;
1439       /* signed version for convienience */
1440       clock_base = base_rtptime;
1441       /* deal with possible wrap-around */
1442       ext_base = base_rtptime;
1443       rtp_clock_base = gst_rtp_buffer_ext_timestamp (&ext_base, rtp_clock_base);
1444       /* sanity check; base rtp and provided clock_base should be close */
1445       if (rtp_clock_base >= clock_base) {
1446         if (rtp_clock_base - clock_base < 10 * clock_rate) {
1447           rtp_clock_base = base_time +
1448               gst_util_uint64_scale_int (rtp_clock_base - clock_base,
1449               GST_SECOND, clock_rate);
1450         } else {
1451           use_rtp = FALSE;
1452         }
1453       } else {
1454         if (clock_base - rtp_clock_base < 10 * clock_rate) {
1455           rtp_clock_base = base_time -
1456               gst_util_uint64_scale_int (clock_base - rtp_clock_base,
1457               GST_SECOND, clock_rate);
1458         } else {
1459           use_rtp = FALSE;
1460         }
1461       }
1462       /* warn and bail for clarity out if no sane values */
1463       if (!use_rtp) {
1464         GST_WARNING_OBJECT (bin, "unable to sync to provided rtptime");
1465         return;
1466       }
1467       /* store to track changes */
1468       clock_base = rtp_clock_base;
1469       /* generate a fake as before,
1470        * now equating rtptime obtained from RTP-Info,
1471        * where the large time represent the otherwise irrelevant npt/ntp time */
1472       stream->rtp_delta = (GST_SECOND << 28) - rtp_clock_base;
1473     } else {
1474       clock_base = rtp_clock_base;
1475     }
1476
1477     all_sync = TRUE;
1478     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
1479       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
1480
1481       if (!ostream->have_sync) {
1482         all_sync = FALSE;
1483         continue;
1484       }
1485
1486       /* change in current stream's base from previously init'ed value
1487        * leads to reset of all stream's base */
1488       if (stream != ostream && stream->clock_base >= 0 &&
1489           (stream->clock_base != clock_base)) {
1490         GST_DEBUG_OBJECT (bin, "reset upon clock base change");
1491         ostream->clock_base = -100 * GST_SECOND;
1492         ostream->rtp_delta = 0;
1493       }
1494
1495       if (ostream->rt_delta < min)
1496         min = ostream->rt_delta;
1497       if (ostream->rtp_delta < rtp_min)
1498         rtp_min = ostream->rtp_delta;
1499     }
1500
1501     /* arrange to re-sync for each stream upon significant change,
1502      * e.g. post-seek */
1503     all_sync = all_sync && (stream->clock_base == clock_base);
1504     stream->clock_base = clock_base;
1505
1506     /* may need init performed above later on, but nothing more to do now */
1507     if (client->nstreams <= 1)
1508       return;
1509
1510     GST_DEBUG_OBJECT (bin, "client %p min delta %" G_GINT64_FORMAT
1511         " all sync %d", client, min, all_sync);
1512     GST_DEBUG_OBJECT (bin, "rtcp sync mode %d, use_rtp %d", rtcp_sync, use_rtp);
1513
1514     switch (rtcp_sync) {
1515       case GST_RTP_BIN_RTCP_SYNC_RTP:
1516         if (!use_rtp)
1517           break;
1518         GST_DEBUG_OBJECT (bin, "using rtp generated reports; "
1519             "client %p min rtp delta %" G_GINT64_FORMAT, client, rtp_min);
1520         /* fall-through */
1521       case GST_RTP_BIN_RTCP_SYNC_INITIAL:
1522         /* if all have been synced already, do not bother further */
1523         if (all_sync) {
1524           GST_DEBUG_OBJECT (bin, "all streams already synced; done");
1525           return;
1526         }
1527         break;
1528       default:
1529         break;
1530     }
1531
1532     /* bail out if we adjusted recently enough */
1533     if (all_sync && (ntpnstime - bin->priv->last_ntpnstime) <
1534         bin->rtcp_sync_interval * GST_MSECOND) {
1535       GST_DEBUG_OBJECT (bin, "discarding RTCP sender packet for sync; "
1536           "previous sender info too recent "
1537           "(previous NTP %" G_GUINT64_FORMAT ")", bin->priv->last_ntpnstime);
1538       return;
1539     }
1540     bin->priv->last_ntpnstime = ntpnstime;
1541
1542     /* calculate offsets for each stream */
1543     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
1544       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
1545       gint64 ts_offset;
1546
1547       /* ignore streams for which we didn't receive an SR packet yet, we
1548        * can't synchronize them yet. We can however sync other streams just
1549        * fine. */
1550       if (!ostream->have_sync)
1551         continue;
1552
1553       /* calculate offset to our reference stream, this should always give a
1554        * positive number. */
1555       if (use_rtp)
1556         ts_offset = ostream->rtp_delta - rtp_min;
1557       else
1558         ts_offset = ostream->rt_delta - min;
1559
1560       stream_set_ts_offset (bin, ostream, ts_offset, bin->max_ts_offset,
1561           MIN_TS_OFFSET, TRUE);
1562     }
1563   }
1564   gst_rtp_bin_send_sync_event (stream);
1565
1566   return;
1567 }
1568
1569 #define GST_RTCP_BUFFER_FOR_PACKETS(b,buffer,packet) \
1570   for ((b) = gst_rtcp_buffer_get_first_packet ((buffer), (packet)); (b); \
1571           (b) = gst_rtcp_packet_move_to_next ((packet)))
1572
1573 #define GST_RTCP_SDES_FOR_ITEMS(b,packet) \
1574   for ((b) = gst_rtcp_packet_sdes_first_item ((packet)); (b); \
1575           (b) = gst_rtcp_packet_sdes_next_item ((packet)))
1576
1577 #define GST_RTCP_SDES_FOR_ENTRIES(b,packet) \
1578   for ((b) = gst_rtcp_packet_sdes_first_entry ((packet)); (b); \
1579           (b) = gst_rtcp_packet_sdes_next_entry ((packet)))
1580
1581 static void
1582 gst_rtp_bin_handle_sync (GstElement * jitterbuffer, GstStructure * s,
1583     GstRtpBinStream * stream)
1584 {
1585   GstRtpBin *bin;
1586   GstRTCPPacket packet;
1587   guint32 ssrc;
1588   guint64 ntptime;
1589   gboolean have_sr, have_sdes;
1590   gboolean more;
1591   guint64 base_rtptime;
1592   guint64 base_time;
1593   guint clock_rate;
1594   guint64 clock_base;
1595   guint64 extrtptime;
1596   GstBuffer *buffer;
1597   GstRTCPBuffer rtcp = { NULL, };
1598
1599   bin = stream->bin;
1600
1601   GST_DEBUG_OBJECT (bin, "sync handler called");
1602
1603   /* get the last relation between the rtp timestamps and the gstreamer
1604    * timestamps. We get this info directly from the jitterbuffer which
1605    * constructs gstreamer timestamps from rtp timestamps and so it know exactly
1606    * what the current situation is. */
1607   base_rtptime =
1608       g_value_get_uint64 (gst_structure_get_value (s, "base-rtptime"));
1609   base_time = g_value_get_uint64 (gst_structure_get_value (s, "base-time"));
1610   clock_rate = g_value_get_uint (gst_structure_get_value (s, "clock-rate"));
1611   clock_base = g_value_get_uint64 (gst_structure_get_value (s, "clock-base"));
1612   extrtptime =
1613       g_value_get_uint64 (gst_structure_get_value (s, "sr-ext-rtptime"));
1614   buffer = gst_value_get_buffer (gst_structure_get_value (s, "sr-buffer"));
1615
1616   have_sr = FALSE;
1617   have_sdes = FALSE;
1618
1619   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
1620
1621   GST_RTCP_BUFFER_FOR_PACKETS (more, &rtcp, &packet) {
1622     /* first packet must be SR or RR or else the validate would have failed */
1623     switch (gst_rtcp_packet_get_type (&packet)) {
1624       case GST_RTCP_TYPE_SR:
1625         /* only parse first. There is only supposed to be one SR in the packet
1626          * but we will deal with malformed packets gracefully */
1627         if (have_sr)
1628           break;
1629         /* get NTP and RTP times */
1630         gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, &ntptime, NULL,
1631             NULL, NULL);
1632
1633         GST_DEBUG_OBJECT (bin, "received sync packet from SSRC %08x", ssrc);
1634         /* ignore SR that is not ours */
1635         if (ssrc != stream->ssrc)
1636           continue;
1637
1638         have_sr = TRUE;
1639         break;
1640       case GST_RTCP_TYPE_SDES:
1641       {
1642         gboolean more_items, more_entries;
1643
1644         /* only deal with first SDES, there is only supposed to be one SDES in
1645          * the RTCP packet but we deal with bad packets gracefully. Also bail
1646          * out if we have not seen an SR item yet. */
1647         if (have_sdes || !have_sr)
1648           break;
1649
1650         GST_RTCP_SDES_FOR_ITEMS (more_items, &packet) {
1651           /* skip items that are not about the SSRC of the sender */
1652           if (gst_rtcp_packet_sdes_get_ssrc (&packet) != ssrc)
1653             continue;
1654
1655           /* find the CNAME entry */
1656           GST_RTCP_SDES_FOR_ENTRIES (more_entries, &packet) {
1657             GstRTCPSDESType type;
1658             guint8 len;
1659             guint8 *data;
1660
1661             gst_rtcp_packet_sdes_get_entry (&packet, &type, &len, &data);
1662
1663             if (type == GST_RTCP_SDES_CNAME) {
1664               GST_RTP_BIN_LOCK (bin);
1665               /* associate the stream to CNAME */
1666               gst_rtp_bin_associate (bin, stream, len, data,
1667                   ntptime, extrtptime, base_rtptime, base_time, clock_rate,
1668                   clock_base);
1669               GST_RTP_BIN_UNLOCK (bin);
1670             }
1671           }
1672         }
1673         have_sdes = TRUE;
1674         break;
1675       }
1676       default:
1677         /* we can ignore these packets */
1678         break;
1679     }
1680   }
1681   gst_rtcp_buffer_unmap (&rtcp);
1682 }
1683
1684 /* create a new stream with @ssrc in @session. Must be called with
1685  * RTP_SESSION_LOCK. */
1686 static GstRtpBinStream *
1687 create_stream (GstRtpBinSession * session, guint32 ssrc)
1688 {
1689   GstElement *buffer, *demux = NULL;
1690   GstRtpBinStream *stream;
1691   GstRtpBin *rtpbin;
1692   GstState target;
1693
1694   rtpbin = session->bin;
1695
1696   if (g_slist_length (session->streams) >= rtpbin->max_streams)
1697     goto max_streams;
1698
1699   if (!(buffer = gst_element_factory_make ("rtpjitterbuffer", NULL)))
1700     goto no_jitterbuffer;
1701
1702   if (!rtpbin->ignore_pt) {
1703     if (!(demux = gst_element_factory_make ("rtpptdemux", NULL)))
1704       goto no_demux;
1705   }
1706
1707   stream = g_new0 (GstRtpBinStream, 1);
1708   stream->ssrc = ssrc;
1709   stream->bin = rtpbin;
1710   stream->session = session;
1711   stream->buffer = buffer;
1712   stream->demux = demux;
1713
1714   stream->have_sync = FALSE;
1715   stream->rt_delta = 0;
1716   stream->rtp_delta = 0;
1717   stream->percent = 100;
1718   stream->clock_base = -100 * GST_SECOND;
1719   session->streams = g_slist_prepend (session->streams, stream);
1720
1721   /* provide clock_rate to the jitterbuffer when needed */
1722   stream->buffer_ptreq_sig = g_signal_connect (buffer, "request-pt-map",
1723       (GCallback) pt_map_requested, session);
1724   stream->buffer_ntpstop_sig = g_signal_connect (buffer, "on-npt-stop",
1725       (GCallback) on_npt_stop, stream);
1726
1727   g_object_set_data (G_OBJECT (buffer), "GstRTPBin.session", session);
1728   g_object_set_data (G_OBJECT (buffer), "GstRTPBin.stream", stream);
1729
1730   /* configure latency and packet lost */
1731   g_object_set (buffer, "latency", rtpbin->latency_ms, NULL);
1732   g_object_set (buffer, "drop-on-latency", rtpbin->drop_on_latency, NULL);
1733   g_object_set (buffer, "do-lost", rtpbin->do_lost, NULL);
1734   g_object_set (buffer, "mode", rtpbin->buffer_mode, NULL);
1735   g_object_set (buffer, "do-retransmission", rtpbin->do_retransmission, NULL);
1736   g_object_set (buffer, "max-rtcp-rtp-time-diff",
1737       rtpbin->max_rtcp_rtp_time_diff, NULL);
1738   g_object_set (buffer, "max-dropout-time", rtpbin->max_dropout_time,
1739       "max-misorder-time", rtpbin->max_misorder_time, NULL);
1740   g_object_set (buffer, "rfc7273-sync", rtpbin->rfc7273_sync, NULL);
1741   g_object_set (buffer, "max-ts-offset-adjustment",
1742       rtpbin->max_ts_offset_adjustment, NULL);
1743
1744   /* need to sink the jitterbufer or otherwise signal handlers from bindings will
1745    * take ownership of it and we don't own it anymore */
1746   gst_object_ref_sink (buffer);
1747   g_signal_emit (rtpbin, gst_rtp_bin_signals[SIGNAL_NEW_JITTERBUFFER], 0,
1748       buffer, session->id, ssrc);
1749
1750   if (!rtpbin->ignore_pt)
1751     gst_bin_add (GST_BIN_CAST (rtpbin), demux);
1752   gst_bin_add (GST_BIN_CAST (rtpbin), buffer);
1753
1754   /* unref the jitterbuffer again, the bin has a reference now and
1755    * we don't need it anymore */
1756   gst_object_unref (buffer);
1757
1758   /* link stuff */
1759   if (demux)
1760     gst_element_link_pads_full (buffer, "src", demux, "sink",
1761         GST_PAD_LINK_CHECK_NOTHING);
1762
1763   if (rtpbin->buffering) {
1764     guint64 last_out;
1765
1766     GST_INFO_OBJECT (rtpbin,
1767         "bin is buffering, set jitterbuffer as not active");
1768     g_signal_emit_by_name (buffer, "set-active", FALSE, (gint64) 0, &last_out);
1769   }
1770
1771
1772   GST_OBJECT_LOCK (rtpbin);
1773   target = GST_STATE_TARGET (rtpbin);
1774   GST_OBJECT_UNLOCK (rtpbin);
1775
1776   /* from sink to source */
1777   if (demux)
1778     gst_element_set_state (demux, target);
1779
1780   gst_element_set_state (buffer, target);
1781
1782   return stream;
1783
1784   /* ERRORS */
1785 max_streams:
1786   {
1787     GST_WARNING_OBJECT (rtpbin, "stream exeeds maximum (%d)",
1788         rtpbin->max_streams);
1789     return NULL;
1790   }
1791 no_jitterbuffer:
1792   {
1793     g_warning ("rtpbin: could not create rtpjitterbuffer element");
1794     return NULL;
1795   }
1796 no_demux:
1797   {
1798     gst_object_unref (buffer);
1799     g_warning ("rtpbin: could not create rtpptdemux element");
1800     return NULL;
1801   }
1802 }
1803
1804 /* called with RTP_BIN_LOCK */
1805 static void
1806 free_stream (GstRtpBinStream * stream, GstRtpBin * bin)
1807 {
1808   GSList *clients, *next_client;
1809
1810   GST_DEBUG_OBJECT (bin, "freeing stream %p", stream);
1811
1812   if (stream->demux) {
1813     g_signal_handler_disconnect (stream->demux, stream->demux_newpad_sig);
1814     g_signal_handler_disconnect (stream->demux, stream->demux_ptreq_sig);
1815     g_signal_handler_disconnect (stream->demux, stream->demux_ptchange_sig);
1816   }
1817   g_signal_handler_disconnect (stream->buffer, stream->buffer_handlesync_sig);
1818   g_signal_handler_disconnect (stream->buffer, stream->buffer_ptreq_sig);
1819   g_signal_handler_disconnect (stream->buffer, stream->buffer_ntpstop_sig);
1820
1821   if (stream->demux)
1822     gst_element_set_locked_state (stream->demux, TRUE);
1823   gst_element_set_locked_state (stream->buffer, TRUE);
1824
1825   if (stream->demux)
1826     gst_element_set_state (stream->demux, GST_STATE_NULL);
1827   gst_element_set_state (stream->buffer, GST_STATE_NULL);
1828
1829   /* now remove this signal, we need this while going to NULL because it to
1830    * do some cleanups */
1831   if (stream->demux)
1832     g_signal_handler_disconnect (stream->demux, stream->demux_padremoved_sig);
1833
1834   gst_bin_remove (GST_BIN_CAST (bin), stream->buffer);
1835   if (stream->demux)
1836     gst_bin_remove (GST_BIN_CAST (bin), stream->demux);
1837
1838   for (clients = bin->clients; clients; clients = next_client) {
1839     GstRtpBinClient *client = (GstRtpBinClient *) clients->data;
1840     GSList *streams, *next_stream;
1841
1842     next_client = g_slist_next (clients);
1843
1844     for (streams = client->streams; streams; streams = next_stream) {
1845       GstRtpBinStream *ostream = (GstRtpBinStream *) streams->data;
1846
1847       next_stream = g_slist_next (streams);
1848
1849       if (ostream == stream) {
1850         client->streams = g_slist_delete_link (client->streams, streams);
1851         /* If this was the last stream belonging to this client,
1852          * clean up the client. */
1853         if (--client->nstreams == 0) {
1854           bin->clients = g_slist_delete_link (bin->clients, clients);
1855           free_client (client, bin);
1856           break;
1857         }
1858       }
1859     }
1860   }
1861   g_free (stream);
1862 }
1863
1864 /* GObject vmethods */
1865 static void gst_rtp_bin_dispose (GObject * object);
1866 static void gst_rtp_bin_finalize (GObject * object);
1867 static void gst_rtp_bin_set_property (GObject * object, guint prop_id,
1868     const GValue * value, GParamSpec * pspec);
1869 static void gst_rtp_bin_get_property (GObject * object, guint prop_id,
1870     GValue * value, GParamSpec * pspec);
1871
1872 /* GstElement vmethods */
1873 static GstStateChangeReturn gst_rtp_bin_change_state (GstElement * element,
1874     GstStateChange transition);
1875 static GstPad *gst_rtp_bin_request_new_pad (GstElement * element,
1876     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
1877 static void gst_rtp_bin_release_pad (GstElement * element, GstPad * pad);
1878 static void gst_rtp_bin_handle_message (GstBin * bin, GstMessage * message);
1879
1880 #define gst_rtp_bin_parent_class parent_class
1881 G_DEFINE_TYPE_WITH_PRIVATE (GstRtpBin, gst_rtp_bin, GST_TYPE_BIN);
1882
1883 static gboolean
1884 _gst_element_accumulator (GSignalInvocationHint * ihint,
1885     GValue * return_accu, const GValue * handler_return, gpointer dummy)
1886 {
1887   GstElement *element;
1888
1889   element = g_value_get_object (handler_return);
1890   GST_DEBUG ("got element %" GST_PTR_FORMAT, element);
1891
1892   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
1893     g_value_set_object (return_accu, element);
1894
1895   /* stop emission if we have an element */
1896   return (element == NULL);
1897 }
1898
1899 static gboolean
1900 _gst_caps_accumulator (GSignalInvocationHint * ihint,
1901     GValue * return_accu, const GValue * handler_return, gpointer dummy)
1902 {
1903   GstCaps *caps;
1904
1905   caps = g_value_get_boxed (handler_return);
1906   GST_DEBUG ("got caps %" GST_PTR_FORMAT, caps);
1907
1908   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
1909     g_value_set_boxed (return_accu, caps);
1910
1911   /* stop emission if we have a caps */
1912   return (caps == NULL);
1913 }
1914
1915 static void
1916 gst_rtp_bin_class_init (GstRtpBinClass * klass)
1917 {
1918   GObjectClass *gobject_class;
1919   GstElementClass *gstelement_class;
1920   GstBinClass *gstbin_class;
1921
1922   gobject_class = (GObjectClass *) klass;
1923   gstelement_class = (GstElementClass *) klass;
1924   gstbin_class = (GstBinClass *) klass;
1925
1926   gobject_class->dispose = gst_rtp_bin_dispose;
1927   gobject_class->finalize = gst_rtp_bin_finalize;
1928   gobject_class->set_property = gst_rtp_bin_set_property;
1929   gobject_class->get_property = gst_rtp_bin_get_property;
1930
1931   g_object_class_install_property (gobject_class, PROP_LATENCY,
1932       g_param_spec_uint ("latency", "Buffer latency in ms",
1933           "Default amount of ms to buffer in the jitterbuffers", 0,
1934           G_MAXUINT, DEFAULT_LATENCY_MS,
1935           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1936
1937   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
1938       g_param_spec_boolean ("drop-on-latency",
1939           "Drop buffers when maximum latency is reached",
1940           "Tells the jitterbuffer to never exceed the given latency in size",
1941           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1942
1943   /**
1944    * GstRtpBin::request-pt-map:
1945    * @rtpbin: the object which received the signal
1946    * @session: the session
1947    * @pt: the pt
1948    *
1949    * Request the payload type as #GstCaps for @pt in @session.
1950    */
1951   gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP] =
1952       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
1953       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, request_pt_map),
1954       _gst_caps_accumulator, NULL, g_cclosure_marshal_generic, GST_TYPE_CAPS,
1955       2, G_TYPE_UINT, G_TYPE_UINT);
1956
1957     /**
1958    * GstRtpBin::payload-type-change:
1959    * @rtpbin: the object which received the signal
1960    * @session: the session
1961    * @pt: the pt
1962    *
1963    * Signal that the current payload type changed to @pt in @session.
1964    */
1965   gst_rtp_bin_signals[SIGNAL_PAYLOAD_TYPE_CHANGE] =
1966       g_signal_new ("payload-type-change", G_TYPE_FROM_CLASS (klass),
1967       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, payload_type_change),
1968       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
1969       G_TYPE_UINT);
1970
1971   /**
1972    * GstRtpBin::clear-pt-map:
1973    * @rtpbin: the object which received the signal
1974    *
1975    * Clear all previously cached pt-mapping obtained with
1976    * #GstRtpBin::request-pt-map.
1977    */
1978   gst_rtp_bin_signals[SIGNAL_CLEAR_PT_MAP] =
1979       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
1980       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
1981           clear_pt_map), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
1982       0, G_TYPE_NONE);
1983
1984   /**
1985    * GstRtpBin::reset-sync:
1986    * @rtpbin: the object which received the signal
1987    *
1988    * Reset all currently configured lip-sync parameters and require new SR
1989    * packets for all streams before lip-sync is attempted again.
1990    */
1991   gst_rtp_bin_signals[SIGNAL_RESET_SYNC] =
1992       g_signal_new ("reset-sync", G_TYPE_FROM_CLASS (klass),
1993       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
1994           reset_sync), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
1995       0, G_TYPE_NONE);
1996
1997   /**
1998    * GstRtpBin::get-session:
1999    * @rtpbin: the object which received the signal
2000    * @id: the session id
2001    *
2002    * Request the related GstRtpSession as #GstElement related with session @id.
2003    *
2004    * Since: 1.8
2005    */
2006   gst_rtp_bin_signals[SIGNAL_GET_SESSION] =
2007       g_signal_new ("get-session", G_TYPE_FROM_CLASS (klass),
2008       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
2009           get_session), NULL, NULL, g_cclosure_marshal_generic,
2010       GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2011
2012   /**
2013    * GstRtpBin::get-internal-session:
2014    * @rtpbin: the object which received the signal
2015    * @id: the session id
2016    *
2017    * Request the internal RTPSession object as #GObject in session @id.
2018    */
2019   gst_rtp_bin_signals[SIGNAL_GET_INTERNAL_SESSION] =
2020       g_signal_new ("get-internal-session", G_TYPE_FROM_CLASS (klass),
2021       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
2022           get_internal_session), NULL, NULL, g_cclosure_marshal_generic,
2023       RTP_TYPE_SESSION, 1, G_TYPE_UINT);
2024
2025   /**
2026    * GstRtpBin::get-internal-storage:
2027    * @rtpbin: the object which received the signal
2028    * @id: the session id
2029    *
2030    * Request the internal RTPStorage object as #GObject in session @id.
2031    *
2032    * Since: 1.14
2033    */
2034   gst_rtp_bin_signals[SIGNAL_GET_INTERNAL_STORAGE] =
2035       g_signal_new ("get-internal-storage", G_TYPE_FROM_CLASS (klass),
2036       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
2037           get_internal_storage), NULL, NULL, g_cclosure_marshal_generic,
2038       G_TYPE_OBJECT, 1, G_TYPE_UINT);
2039
2040   /**
2041    * GstRtpBin::get-storage:
2042    * @rtpbin: the object which received the signal
2043    * @id: the session id
2044    *
2045    * Request the RTPStorage element as #GObject in session @id.
2046    *
2047    * Since: 1.16
2048    */
2049   gst_rtp_bin_signals[SIGNAL_GET_STORAGE] =
2050       g_signal_new ("get-storage", G_TYPE_FROM_CLASS (klass),
2051       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass,
2052           get_storage), NULL, NULL, g_cclosure_marshal_generic,
2053       GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2054
2055   /**
2056    * GstRtpBin::on-new-ssrc:
2057    * @rtpbin: the object which received the signal
2058    * @session: the session
2059    * @ssrc: the SSRC
2060    *
2061    * Notify of a new SSRC that entered @session.
2062    */
2063   gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC] =
2064       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
2065       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_new_ssrc),
2066       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2067       G_TYPE_UINT);
2068   /**
2069    * GstRtpBin::on-ssrc-collision:
2070    * @rtpbin: the object which received the signal
2071    * @session: the session
2072    * @ssrc: the SSRC
2073    *
2074    * Notify when we have an SSRC collision
2075    */
2076   gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION] =
2077       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
2078       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_collision),
2079       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2080       G_TYPE_UINT);
2081   /**
2082    * GstRtpBin::on-ssrc-validated:
2083    * @rtpbin: the object which received the signal
2084    * @session: the session
2085    * @ssrc: the SSRC
2086    *
2087    * Notify of a new SSRC that became validated.
2088    */
2089   gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED] =
2090       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
2091       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_validated),
2092       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2093       G_TYPE_UINT);
2094   /**
2095    * GstRtpBin::on-ssrc-active:
2096    * @rtpbin: the object which received the signal
2097    * @session: the session
2098    * @ssrc: the SSRC
2099    *
2100    * Notify of a SSRC that is active, i.e., sending RTCP.
2101    */
2102   gst_rtp_bin_signals[SIGNAL_ON_SSRC_ACTIVE] =
2103       g_signal_new ("on-ssrc-active", G_TYPE_FROM_CLASS (klass),
2104       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_active),
2105       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2106       G_TYPE_UINT);
2107   /**
2108    * GstRtpBin::on-ssrc-sdes:
2109    * @rtpbin: the object which received the signal
2110    * @session: the session
2111    * @ssrc: the SSRC
2112    *
2113    * Notify of a SSRC that is active, i.e., sending RTCP.
2114    */
2115   gst_rtp_bin_signals[SIGNAL_ON_SSRC_SDES] =
2116       g_signal_new ("on-ssrc-sdes", G_TYPE_FROM_CLASS (klass),
2117       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_sdes),
2118       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2119       G_TYPE_UINT);
2120
2121   /**
2122    * GstRtpBin::on-bye-ssrc:
2123    * @rtpbin: the object which received the signal
2124    * @session: the session
2125    * @ssrc: the SSRC
2126    *
2127    * Notify of an SSRC that became inactive because of a BYE packet.
2128    */
2129   gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC] =
2130       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
2131       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_ssrc),
2132       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2133       G_TYPE_UINT);
2134   /**
2135    * GstRtpBin::on-bye-timeout:
2136    * @rtpbin: the object which received the signal
2137    * @session: the session
2138    * @ssrc: the SSRC
2139    *
2140    * Notify of an SSRC that has timed out because of BYE
2141    */
2142   gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT] =
2143       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
2144       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_timeout),
2145       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2146       G_TYPE_UINT);
2147   /**
2148    * GstRtpBin::on-timeout:
2149    * @rtpbin: the object which received the signal
2150    * @session: the session
2151    * @ssrc: the SSRC
2152    *
2153    * Notify of an SSRC that has timed out
2154    */
2155   gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT] =
2156       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
2157       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_timeout),
2158       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2159       G_TYPE_UINT);
2160   /**
2161    * GstRtpBin::on-sender-timeout:
2162    * @rtpbin: the object which received the signal
2163    * @session: the session
2164    * @ssrc: the SSRC
2165    *
2166    * Notify of a sender SSRC that has timed out and became a receiver
2167    */
2168   gst_rtp_bin_signals[SIGNAL_ON_SENDER_TIMEOUT] =
2169       g_signal_new ("on-sender-timeout", G_TYPE_FROM_CLASS (klass),
2170       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_sender_timeout),
2171       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2172       G_TYPE_UINT);
2173
2174   /**
2175    * GstRtpBin::on-npt-stop:
2176    * @rtpbin: the object which received the signal
2177    * @session: the session
2178    * @ssrc: the SSRC
2179    *
2180    * Notify that SSRC sender has sent data up to the configured NPT stop time.
2181    */
2182   gst_rtp_bin_signals[SIGNAL_ON_NPT_STOP] =
2183       g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
2184       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_npt_stop),
2185       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2186       G_TYPE_UINT);
2187
2188   /**
2189    * GstRtpBin::request-rtp-encoder:
2190    * @rtpbin: the object which received the signal
2191    * @session: the session
2192    *
2193    * Request an RTP encoder element for the given @session. The encoder
2194    * element will be added to the bin if not previously added.
2195    *
2196    * If no handler is connected, no encoder will be used.
2197    *
2198    * Since: 1.4
2199    */
2200   gst_rtp_bin_signals[SIGNAL_REQUEST_RTP_ENCODER] =
2201       g_signal_new ("request-rtp-encoder", G_TYPE_FROM_CLASS (klass),
2202       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2203           request_rtp_encoder), _gst_element_accumulator, NULL,
2204       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2205
2206   /**
2207    * GstRtpBin::request-rtp-decoder:
2208    * @rtpbin: the object which received the signal
2209    * @session: the session
2210    *
2211    * Request an RTP decoder element for the given @session. The decoder
2212    * element will be added to the bin if not previously added.
2213    *
2214    * If no handler is connected, no encoder will be used.
2215    *
2216    * Since: 1.4
2217    */
2218   gst_rtp_bin_signals[SIGNAL_REQUEST_RTP_DECODER] =
2219       g_signal_new ("request-rtp-decoder", G_TYPE_FROM_CLASS (klass),
2220       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2221           request_rtp_decoder), _gst_element_accumulator, NULL,
2222       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2223
2224   /**
2225    * GstRtpBin::request-rtcp-encoder:
2226    * @rtpbin: the object which received the signal
2227    * @session: the session
2228    *
2229    * Request an RTCP encoder element for the given @session. The encoder
2230    * element will be added to the bin if not previously added.
2231    *
2232    * If no handler is connected, no encoder will be used.
2233    *
2234    * Since: 1.4
2235    */
2236   gst_rtp_bin_signals[SIGNAL_REQUEST_RTCP_ENCODER] =
2237       g_signal_new ("request-rtcp-encoder", G_TYPE_FROM_CLASS (klass),
2238       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2239           request_rtcp_encoder), _gst_element_accumulator, NULL,
2240       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2241
2242   /**
2243    * GstRtpBin::request-rtcp-decoder:
2244    * @rtpbin: the object which received the signal
2245    * @session: the session
2246    *
2247    * Request an RTCP decoder element for the given @session. The decoder
2248    * element will be added to the bin if not previously added.
2249    *
2250    * If no handler is connected, no encoder will be used.
2251    *
2252    * Since: 1.4
2253    */
2254   gst_rtp_bin_signals[SIGNAL_REQUEST_RTCP_DECODER] =
2255       g_signal_new ("request-rtcp-decoder", G_TYPE_FROM_CLASS (klass),
2256       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2257           request_rtcp_decoder), _gst_element_accumulator, NULL,
2258       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2259
2260   /**
2261    * GstRtpBin::new-jitterbuffer:
2262    * @rtpbin: the object which received the signal
2263    * @jitterbuffer: the new jitterbuffer
2264    * @session: the session
2265    * @ssrc: the SSRC
2266    *
2267    * Notify that a new @jitterbuffer was created for @session and @ssrc.
2268    * This signal can, for example, be used to configure @jitterbuffer.
2269    *
2270    * Since: 1.4
2271    */
2272   gst_rtp_bin_signals[SIGNAL_NEW_JITTERBUFFER] =
2273       g_signal_new ("new-jitterbuffer", G_TYPE_FROM_CLASS (klass),
2274       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2275           new_jitterbuffer), NULL, NULL, g_cclosure_marshal_generic,
2276       G_TYPE_NONE, 3, GST_TYPE_ELEMENT, G_TYPE_UINT, G_TYPE_UINT);
2277
2278   /**
2279    * GstRtpBin::new-storage:
2280    * @rtpbin: the object which received the signal
2281    * @storage: the new storage
2282    * @session: the session
2283    *
2284    * Notify that a new @storage was created for @session.
2285    * This signal can, for example, be used to configure @storage.
2286    *
2287    * Since: 1.14
2288    */
2289   gst_rtp_bin_signals[SIGNAL_NEW_STORAGE] =
2290       g_signal_new ("new-storage", G_TYPE_FROM_CLASS (klass),
2291       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2292           new_storage), NULL, NULL, g_cclosure_marshal_generic,
2293       G_TYPE_NONE, 2, GST_TYPE_ELEMENT, G_TYPE_UINT);
2294
2295   /**
2296    * GstRtpBin::request-aux-sender:
2297    * @rtpbin: the object which received the signal
2298    * @session: the session
2299    *
2300    * Request an AUX sender element for the given @session. The AUX
2301    * element will be added to the bin.
2302    *
2303    * If no handler is connected, no AUX element will be used.
2304    *
2305    * Since: 1.4
2306    */
2307   gst_rtp_bin_signals[SIGNAL_REQUEST_AUX_SENDER] =
2308       g_signal_new ("request-aux-sender", G_TYPE_FROM_CLASS (klass),
2309       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2310           request_aux_sender), _gst_element_accumulator, NULL,
2311       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2312
2313   /**
2314    * GstRtpBin::request-aux-receiver:
2315    * @rtpbin: the object which received the signal
2316    * @session: the session
2317    *
2318    * Request an AUX receiver element for the given @session. The AUX
2319    * element will be added to the bin.
2320    *
2321    * If no handler is connected, no AUX element will be used.
2322    *
2323    * Since: 1.4
2324    */
2325   gst_rtp_bin_signals[SIGNAL_REQUEST_AUX_RECEIVER] =
2326       g_signal_new ("request-aux-receiver", G_TYPE_FROM_CLASS (klass),
2327       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2328           request_aux_receiver), _gst_element_accumulator, NULL,
2329       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2330
2331   /**
2332    * GstRtpBin::request-fec-decoder:
2333    * @rtpbin: the object which received the signal
2334    * @session: the session index
2335    *
2336    * Request a FEC decoder element for the given @session. The element
2337    * will be added to the bin after the pt demuxer.
2338    *
2339    * If no handler is connected, no FEC decoder will be used.
2340    *
2341    * Since: 1.14
2342    */
2343   gst_rtp_bin_signals[SIGNAL_REQUEST_FEC_DECODER] =
2344       g_signal_new ("request-fec-decoder", G_TYPE_FROM_CLASS (klass),
2345       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2346           request_fec_decoder), _gst_element_accumulator, NULL,
2347       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2348
2349   /**
2350    * GstRtpBin::request-fec-encoder:
2351    * @rtpbin: the object which received the signal
2352    * @session: the session index
2353    *
2354    * Request a FEC encoder element for the given @session. The element
2355    * will be added to the bin after the RTPSession.
2356    *
2357    * If no handler is connected, no FEC encoder will be used.
2358    *
2359    * Since: 1.14
2360    */
2361   gst_rtp_bin_signals[SIGNAL_REQUEST_FEC_ENCODER] =
2362       g_signal_new ("request-fec-encoder", G_TYPE_FROM_CLASS (klass),
2363       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2364           request_fec_encoder), _gst_element_accumulator, NULL,
2365       g_cclosure_marshal_generic, GST_TYPE_ELEMENT, 1, G_TYPE_UINT);
2366
2367   /**
2368    * GstRtpBin::on-new-sender-ssrc:
2369    * @rtpbin: the object which received the signal
2370    * @session: the session
2371    * @ssrc: the sender SSRC
2372    *
2373    * Notify of a new sender SSRC that entered @session.
2374    *
2375    * Since: 1.8
2376    */
2377   gst_rtp_bin_signals[SIGNAL_ON_NEW_SENDER_SSRC] =
2378       g_signal_new ("on-new-sender-ssrc", G_TYPE_FROM_CLASS (klass),
2379       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_new_sender_ssrc),
2380       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_UINT,
2381       G_TYPE_UINT);
2382   /**
2383    * GstRtpBin::on-sender-ssrc-active:
2384    * @rtpbin: the object which received the signal
2385    * @session: the session
2386    * @ssrc: the sender SSRC
2387    *
2388    * Notify of a sender SSRC that is active, i.e., sending RTCP.
2389    *
2390    * Since: 1.8
2391    */
2392   gst_rtp_bin_signals[SIGNAL_ON_SENDER_SSRC_ACTIVE] =
2393       g_signal_new ("on-sender-ssrc-active", G_TYPE_FROM_CLASS (klass),
2394       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass,
2395           on_sender_ssrc_active), NULL, NULL, g_cclosure_marshal_generic,
2396       G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
2397
2398   g_object_class_install_property (gobject_class, PROP_SDES,
2399       g_param_spec_boxed ("sdes", "SDES",
2400           "The SDES items of this session",
2401           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2402
2403   g_object_class_install_property (gobject_class, PROP_DO_LOST,
2404       g_param_spec_boolean ("do-lost", "Do Lost",
2405           "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
2406           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2407
2408   g_object_class_install_property (gobject_class, PROP_AUTOREMOVE,
2409       g_param_spec_boolean ("autoremove", "Auto Remove",
2410           "Automatically remove timed out sources", DEFAULT_AUTOREMOVE,
2411           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2412
2413   g_object_class_install_property (gobject_class, PROP_IGNORE_PT,
2414       g_param_spec_boolean ("ignore-pt", "Ignore PT",
2415           "Do not demultiplex based on PT values", DEFAULT_IGNORE_PT,
2416           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2417
2418   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
2419       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
2420           "Use the pipeline running-time to set the NTP time in the RTCP SR messages "
2421           "(DEPRECATED: Use ntp-time-source property)",
2422           DEFAULT_USE_PIPELINE_CLOCK,
2423           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED));
2424   /**
2425    * GstRtpBin:buffer-mode:
2426    *
2427    * Control the buffering and timestamping mode used by the jitterbuffer.
2428    */
2429   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
2430       g_param_spec_enum ("buffer-mode", "Buffer Mode",
2431           "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
2432           DEFAULT_BUFFER_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2433   /**
2434    * GstRtpBin:ntp-sync:
2435    *
2436    * Set the NTP time from the sender reports as the running-time on the
2437    * buffers. When both the sender and receiver have sychronized
2438    * running-time, i.e. when the clock and base-time is shared
2439    * between the receivers and the and the senders, this option can be
2440    * used to synchronize receivers on multiple machines.
2441    */
2442   g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
2443       g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
2444           "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
2445           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2446
2447   /**
2448    * GstRtpBin:rtcp-sync:
2449    *
2450    * If not synchronizing (directly) to the NTP clock, determines how to sync
2451    * the various streams.
2452    */
2453   g_object_class_install_property (gobject_class, PROP_RTCP_SYNC,
2454       g_param_spec_enum ("rtcp-sync", "RTCP Sync",
2455           "Use of RTCP SR in synchronization", GST_RTP_BIN_RTCP_SYNC_TYPE,
2456           DEFAULT_RTCP_SYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2457
2458   /**
2459    * GstRtpBin:rtcp-sync-interval:
2460    *
2461    * Determines how often to sync streams using RTCP data.
2462    */
2463   g_object_class_install_property (gobject_class, PROP_RTCP_SYNC_INTERVAL,
2464       g_param_spec_uint ("rtcp-sync-interval", "RTCP Sync Interval",
2465           "RTCP SR interval synchronization (ms) (0 = always)",
2466           0, G_MAXUINT, DEFAULT_RTCP_SYNC_INTERVAL,
2467           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2468
2469   g_object_class_install_property (gobject_class, PROP_DO_SYNC_EVENT,
2470       g_param_spec_boolean ("do-sync-event", "Do Sync Event",
2471           "Send event downstream when a stream is synchronized to the sender",
2472           DEFAULT_DO_SYNC_EVENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2473
2474   /**
2475    * GstRtpBin:do-retransmission:
2476    *
2477    * Enables RTP retransmission on all streams. To control retransmission on
2478    * a per-SSRC basis, connect to the #GstRtpBin::new-jitterbuffer signal and
2479    * set the #GstRtpJitterBuffer::do-retransmission property on the
2480    * #GstRtpJitterBuffer object instead.
2481    */
2482   g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
2483       g_param_spec_boolean ("do-retransmission", "Do retransmission",
2484           "Enable retransmission on all streams",
2485           DEFAULT_DO_RETRANSMISSION,
2486           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2487
2488   /**
2489    * GstRtpBin:rtp-profile:
2490    *
2491    * Sets the default RTP profile of newly created RTP sessions. The
2492    * profile can be changed afterwards on a per-session basis.
2493    */
2494   g_object_class_install_property (gobject_class, PROP_RTP_PROFILE,
2495       g_param_spec_enum ("rtp-profile", "RTP Profile",
2496           "Default RTP profile of newly created sessions",
2497           GST_TYPE_RTP_PROFILE, DEFAULT_RTP_PROFILE,
2498           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2499
2500   g_object_class_install_property (gobject_class, PROP_NTP_TIME_SOURCE,
2501       g_param_spec_enum ("ntp-time-source", "NTP Time Source",
2502           "NTP time source for RTCP packets",
2503           gst_rtp_ntp_time_source_get_type (), DEFAULT_NTP_TIME_SOURCE,
2504           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2505
2506   g_object_class_install_property (gobject_class, PROP_RTCP_SYNC_SEND_TIME,
2507       g_param_spec_boolean ("rtcp-sync-send-time", "RTCP Sync Send Time",
2508           "Use send time or capture time for RTCP sync "
2509           "(TRUE = send time, FALSE = capture time)",
2510           DEFAULT_RTCP_SYNC_SEND_TIME,
2511           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2512
2513   g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
2514       g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
2515           "Maximum amount of time in ms that the RTP time in RTCP SRs "
2516           "is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
2517           DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
2518           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2519
2520   g_object_class_install_property (gobject_class, PROP_MAX_DROPOUT_TIME,
2521       g_param_spec_uint ("max-dropout-time", "Max dropout time",
2522           "The maximum time (milliseconds) of missing packets tolerated.",
2523           0, G_MAXUINT, DEFAULT_MAX_DROPOUT_TIME,
2524           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2525
2526   g_object_class_install_property (gobject_class, PROP_MAX_MISORDER_TIME,
2527       g_param_spec_uint ("max-misorder-time", "Max misorder time",
2528           "The maximum time (milliseconds) of misordered packets tolerated.",
2529           0, G_MAXUINT, DEFAULT_MAX_MISORDER_TIME,
2530           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2531
2532   g_object_class_install_property (gobject_class, PROP_RFC7273_SYNC,
2533       g_param_spec_boolean ("rfc7273-sync", "Sync on RFC7273 clock",
2534           "Synchronize received streams to the RFC7273 clock "
2535           "(requires clock and offset to be provided)", DEFAULT_RFC7273_SYNC,
2536           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2537
2538   g_object_class_install_property (gobject_class, PROP_MAX_STREAMS,
2539       g_param_spec_uint ("max-streams", "Max Streams",
2540           "The maximum number of streams to create for one session",
2541           0, G_MAXUINT, DEFAULT_MAX_STREAMS,
2542           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2543
2544   /**
2545    * GstRtpBin:max-ts-offset-adjustment:
2546    *
2547    * Syncing time stamps to NTP time adds a time offset. This parameter
2548    * specifies the maximum number of nanoseconds per frame that this time offset
2549    * may be adjusted with. This is used to avoid sudden large changes to time
2550    * stamps.
2551    *
2552    * Since: 1.14
2553    */
2554   g_object_class_install_property (gobject_class, PROP_MAX_TS_OFFSET_ADJUSTMENT,
2555       g_param_spec_uint64 ("max-ts-offset-adjustment",
2556           "Max Timestamp Offset Adjustment",
2557           "The maximum number of nanoseconds per frame that time stamp offsets "
2558           "may be adjusted (0 = no limit).", 0, G_MAXUINT64,
2559           DEFAULT_MAX_TS_OFFSET_ADJUSTMENT, G_PARAM_READWRITE |
2560           G_PARAM_STATIC_STRINGS));
2561
2562   /**
2563    * GstRtpBin:max-ts-offset:
2564    *
2565    * Used to set an upper limit of how large a time offset may be. This
2566    * is used to protect against unrealistic values as a result of either
2567    * client,server or clock issues.
2568    *
2569    * Since: 1.14
2570    */
2571   g_object_class_install_property (gobject_class, PROP_MAX_TS_OFFSET,
2572       g_param_spec_int64 ("max-ts-offset", "Max TS Offset",
2573           "The maximum absolute value of the time offset in (nanoseconds). "
2574           "Note, if the ntp-sync parameter is set the default value is "
2575           "changed to 0 (no limit)", 0, G_MAXINT64, DEFAULT_MAX_TS_OFFSET,
2576           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
2577
2578   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rtp_bin_change_state);
2579   gstelement_class->request_new_pad =
2580       GST_DEBUG_FUNCPTR (gst_rtp_bin_request_new_pad);
2581   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_rtp_bin_release_pad);
2582
2583   /* sink pads */
2584   gst_element_class_add_static_pad_template (gstelement_class,
2585       &rtpbin_recv_rtp_sink_template);
2586   gst_element_class_add_static_pad_template (gstelement_class,
2587       &rtpbin_recv_rtcp_sink_template);
2588   gst_element_class_add_static_pad_template (gstelement_class,
2589       &rtpbin_send_rtp_sink_template);
2590
2591   /* src pads */
2592   gst_element_class_add_static_pad_template (gstelement_class,
2593       &rtpbin_recv_rtp_src_template);
2594   gst_element_class_add_static_pad_template (gstelement_class,
2595       &rtpbin_send_rtcp_src_template);
2596   gst_element_class_add_static_pad_template (gstelement_class,
2597       &rtpbin_send_rtp_src_template);
2598
2599   gst_element_class_set_static_metadata (gstelement_class, "RTP Bin",
2600       "Filter/Network/RTP",
2601       "Real-Time Transport Protocol bin",
2602       "Wim Taymans <wim.taymans@gmail.com>");
2603
2604   gstbin_class->handle_message = GST_DEBUG_FUNCPTR (gst_rtp_bin_handle_message);
2605
2606   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_bin_clear_pt_map);
2607   klass->reset_sync = GST_DEBUG_FUNCPTR (gst_rtp_bin_reset_sync);
2608   klass->get_session = GST_DEBUG_FUNCPTR (gst_rtp_bin_get_session);
2609   klass->get_internal_session =
2610       GST_DEBUG_FUNCPTR (gst_rtp_bin_get_internal_session);
2611   klass->get_storage = GST_DEBUG_FUNCPTR (gst_rtp_bin_get_storage);
2612   klass->get_internal_storage =
2613       GST_DEBUG_FUNCPTR (gst_rtp_bin_get_internal_storage);
2614   klass->request_rtp_encoder = GST_DEBUG_FUNCPTR (gst_rtp_bin_request_encoder);
2615   klass->request_rtp_decoder = GST_DEBUG_FUNCPTR (gst_rtp_bin_request_decoder);
2616   klass->request_rtcp_encoder = GST_DEBUG_FUNCPTR (gst_rtp_bin_request_encoder);
2617   klass->request_rtcp_decoder = GST_DEBUG_FUNCPTR (gst_rtp_bin_request_decoder);
2618
2619   GST_DEBUG_CATEGORY_INIT (gst_rtp_bin_debug, "rtpbin", 0, "RTP bin");
2620 }
2621
2622 static void
2623 gst_rtp_bin_init (GstRtpBin * rtpbin)
2624 {
2625   gchar *cname;
2626
2627   rtpbin->priv = gst_rtp_bin_get_instance_private (rtpbin);
2628   g_mutex_init (&rtpbin->priv->bin_lock);
2629   g_mutex_init (&rtpbin->priv->dyn_lock);
2630
2631   rtpbin->latency_ms = DEFAULT_LATENCY_MS;
2632   rtpbin->latency_ns = DEFAULT_LATENCY_MS * GST_MSECOND;
2633   rtpbin->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
2634   rtpbin->do_lost = DEFAULT_DO_LOST;
2635   rtpbin->ignore_pt = DEFAULT_IGNORE_PT;
2636   rtpbin->ntp_sync = DEFAULT_NTP_SYNC;
2637   rtpbin->rtcp_sync = DEFAULT_RTCP_SYNC;
2638   rtpbin->rtcp_sync_interval = DEFAULT_RTCP_SYNC_INTERVAL;
2639   rtpbin->priv->autoremove = DEFAULT_AUTOREMOVE;
2640   rtpbin->buffer_mode = DEFAULT_BUFFER_MODE;
2641   rtpbin->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
2642   rtpbin->send_sync_event = DEFAULT_DO_SYNC_EVENT;
2643   rtpbin->do_retransmission = DEFAULT_DO_RETRANSMISSION;
2644   rtpbin->rtp_profile = DEFAULT_RTP_PROFILE;
2645   rtpbin->ntp_time_source = DEFAULT_NTP_TIME_SOURCE;
2646   rtpbin->rtcp_sync_send_time = DEFAULT_RTCP_SYNC_SEND_TIME;
2647   rtpbin->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
2648   rtpbin->max_dropout_time = DEFAULT_MAX_DROPOUT_TIME;
2649   rtpbin->max_misorder_time = DEFAULT_MAX_MISORDER_TIME;
2650   rtpbin->rfc7273_sync = DEFAULT_RFC7273_SYNC;
2651   rtpbin->max_streams = DEFAULT_MAX_STREAMS;
2652   rtpbin->max_ts_offset_adjustment = DEFAULT_MAX_TS_OFFSET_ADJUSTMENT;
2653   rtpbin->max_ts_offset = DEFAULT_MAX_TS_OFFSET;
2654   rtpbin->max_ts_offset_is_set = FALSE;
2655
2656   /* some default SDES entries */
2657   cname = g_strdup_printf ("user%u@host-%x", g_random_int (), g_random_int ());
2658   rtpbin->sdes = gst_structure_new ("application/x-rtp-source-sdes",
2659       "cname", G_TYPE_STRING, cname, "tool", G_TYPE_STRING, "GStreamer", NULL);
2660   g_free (cname);
2661 }
2662
2663 static void
2664 gst_rtp_bin_dispose (GObject * object)
2665 {
2666   GstRtpBin *rtpbin;
2667
2668   rtpbin = GST_RTP_BIN (object);
2669
2670   GST_RTP_BIN_LOCK (rtpbin);
2671   GST_DEBUG_OBJECT (object, "freeing sessions");
2672   g_slist_foreach (rtpbin->sessions, (GFunc) free_session, rtpbin);
2673   g_slist_free (rtpbin->sessions);
2674   rtpbin->sessions = NULL;
2675   GST_RTP_BIN_UNLOCK (rtpbin);
2676
2677   G_OBJECT_CLASS (parent_class)->dispose (object);
2678 }
2679
2680 static void
2681 gst_rtp_bin_finalize (GObject * object)
2682 {
2683   GstRtpBin *rtpbin;
2684
2685   rtpbin = GST_RTP_BIN (object);
2686
2687   if (rtpbin->sdes)
2688     gst_structure_free (rtpbin->sdes);
2689
2690   g_mutex_clear (&rtpbin->priv->bin_lock);
2691   g_mutex_clear (&rtpbin->priv->dyn_lock);
2692
2693   G_OBJECT_CLASS (parent_class)->finalize (object);
2694 }
2695
2696
2697 static void
2698 gst_rtp_bin_set_sdes_struct (GstRtpBin * bin, const GstStructure * sdes)
2699 {
2700   GSList *item;
2701
2702   if (sdes == NULL)
2703     return;
2704
2705   GST_RTP_BIN_LOCK (bin);
2706
2707   GST_OBJECT_LOCK (bin);
2708   if (bin->sdes)
2709     gst_structure_free (bin->sdes);
2710   bin->sdes = gst_structure_copy (sdes);
2711   GST_OBJECT_UNLOCK (bin);
2712
2713   /* store in all sessions */
2714   for (item = bin->sessions; item; item = g_slist_next (item)) {
2715     GstRtpBinSession *session = item->data;
2716     g_object_set (session->session, "sdes", sdes, NULL);
2717   }
2718
2719   GST_RTP_BIN_UNLOCK (bin);
2720 }
2721
2722 static GstStructure *
2723 gst_rtp_bin_get_sdes_struct (GstRtpBin * bin)
2724 {
2725   GstStructure *result;
2726
2727   GST_OBJECT_LOCK (bin);
2728   result = gst_structure_copy (bin->sdes);
2729   GST_OBJECT_UNLOCK (bin);
2730
2731   return result;
2732 }
2733
2734 static void
2735 gst_rtp_bin_set_property (GObject * object, guint prop_id,
2736     const GValue * value, GParamSpec * pspec)
2737 {
2738   GstRtpBin *rtpbin;
2739
2740   rtpbin = GST_RTP_BIN (object);
2741
2742   switch (prop_id) {
2743     case PROP_LATENCY:
2744       GST_RTP_BIN_LOCK (rtpbin);
2745       rtpbin->latency_ms = g_value_get_uint (value);
2746       rtpbin->latency_ns = rtpbin->latency_ms * GST_MSECOND;
2747       GST_RTP_BIN_UNLOCK (rtpbin);
2748       /* propagate the property down to the jitterbuffer */
2749       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin, "latency", value);
2750       break;
2751     case PROP_DROP_ON_LATENCY:
2752       GST_RTP_BIN_LOCK (rtpbin);
2753       rtpbin->drop_on_latency = g_value_get_boolean (value);
2754       GST_RTP_BIN_UNLOCK (rtpbin);
2755       /* propagate the property down to the jitterbuffer */
2756       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2757           "drop-on-latency", value);
2758       break;
2759     case PROP_SDES:
2760       gst_rtp_bin_set_sdes_struct (rtpbin, g_value_get_boxed (value));
2761       break;
2762     case PROP_DO_LOST:
2763       GST_RTP_BIN_LOCK (rtpbin);
2764       rtpbin->do_lost = g_value_get_boolean (value);
2765       GST_RTP_BIN_UNLOCK (rtpbin);
2766       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin, "do-lost", value);
2767       break;
2768     case PROP_NTP_SYNC:
2769       rtpbin->ntp_sync = g_value_get_boolean (value);
2770       /* The default value of max_ts_offset depends on ntp_sync. If user
2771        * hasn't set it then change default value */
2772       if (!rtpbin->max_ts_offset_is_set) {
2773         if (rtpbin->ntp_sync) {
2774           rtpbin->max_ts_offset = 0;
2775         } else {
2776           rtpbin->max_ts_offset = DEFAULT_MAX_TS_OFFSET;
2777         }
2778       }
2779       break;
2780     case PROP_RTCP_SYNC:
2781       g_atomic_int_set (&rtpbin->rtcp_sync, g_value_get_enum (value));
2782       break;
2783     case PROP_RTCP_SYNC_INTERVAL:
2784       rtpbin->rtcp_sync_interval = g_value_get_uint (value);
2785       break;
2786     case PROP_IGNORE_PT:
2787       rtpbin->ignore_pt = g_value_get_boolean (value);
2788       break;
2789     case PROP_AUTOREMOVE:
2790       rtpbin->priv->autoremove = g_value_get_boolean (value);
2791       break;
2792     case PROP_USE_PIPELINE_CLOCK:
2793     {
2794       GSList *sessions;
2795       GST_RTP_BIN_LOCK (rtpbin);
2796       rtpbin->use_pipeline_clock = g_value_get_boolean (value);
2797       for (sessions = rtpbin->sessions; sessions;
2798           sessions = g_slist_next (sessions)) {
2799         GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
2800
2801         g_object_set (G_OBJECT (session->session),
2802             "use-pipeline-clock", rtpbin->use_pipeline_clock, NULL);
2803       }
2804       GST_RTP_BIN_UNLOCK (rtpbin);
2805     }
2806       break;
2807     case PROP_DO_SYNC_EVENT:
2808       rtpbin->send_sync_event = g_value_get_boolean (value);
2809       break;
2810     case PROP_BUFFER_MODE:
2811       GST_RTP_BIN_LOCK (rtpbin);
2812       rtpbin->buffer_mode = g_value_get_enum (value);
2813       GST_RTP_BIN_UNLOCK (rtpbin);
2814       /* propagate the property down to the jitterbuffer */
2815       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin, "mode", value);
2816       break;
2817     case PROP_DO_RETRANSMISSION:
2818       GST_RTP_BIN_LOCK (rtpbin);
2819       rtpbin->do_retransmission = g_value_get_boolean (value);
2820       GST_RTP_BIN_UNLOCK (rtpbin);
2821       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2822           "do-retransmission", value);
2823       break;
2824     case PROP_RTP_PROFILE:
2825       rtpbin->rtp_profile = g_value_get_enum (value);
2826       break;
2827     case PROP_NTP_TIME_SOURCE:{
2828       GSList *sessions;
2829       GST_RTP_BIN_LOCK (rtpbin);
2830       rtpbin->ntp_time_source = g_value_get_enum (value);
2831       for (sessions = rtpbin->sessions; sessions;
2832           sessions = g_slist_next (sessions)) {
2833         GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
2834
2835         g_object_set (G_OBJECT (session->session),
2836             "ntp-time-source", rtpbin->ntp_time_source, NULL);
2837       }
2838       GST_RTP_BIN_UNLOCK (rtpbin);
2839       break;
2840     }
2841     case PROP_RTCP_SYNC_SEND_TIME:{
2842       GSList *sessions;
2843       GST_RTP_BIN_LOCK (rtpbin);
2844       rtpbin->rtcp_sync_send_time = g_value_get_boolean (value);
2845       for (sessions = rtpbin->sessions; sessions;
2846           sessions = g_slist_next (sessions)) {
2847         GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
2848
2849         g_object_set (G_OBJECT (session->session),
2850             "rtcp-sync-send-time", rtpbin->rtcp_sync_send_time, NULL);
2851       }
2852       GST_RTP_BIN_UNLOCK (rtpbin);
2853       break;
2854     }
2855     case PROP_MAX_RTCP_RTP_TIME_DIFF:
2856       GST_RTP_BIN_LOCK (rtpbin);
2857       rtpbin->max_rtcp_rtp_time_diff = g_value_get_int (value);
2858       GST_RTP_BIN_UNLOCK (rtpbin);
2859       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2860           "max-rtcp-rtp-time-diff", value);
2861       break;
2862     case PROP_MAX_DROPOUT_TIME:
2863       GST_RTP_BIN_LOCK (rtpbin);
2864       rtpbin->max_dropout_time = g_value_get_uint (value);
2865       GST_RTP_BIN_UNLOCK (rtpbin);
2866       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2867           "max-dropout-time", value);
2868       gst_rtp_bin_propagate_property_to_session (rtpbin, "max-dropout-time",
2869           value);
2870       break;
2871     case PROP_MAX_MISORDER_TIME:
2872       GST_RTP_BIN_LOCK (rtpbin);
2873       rtpbin->max_misorder_time = g_value_get_uint (value);
2874       GST_RTP_BIN_UNLOCK (rtpbin);
2875       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2876           "max-misorder-time", value);
2877       gst_rtp_bin_propagate_property_to_session (rtpbin, "max-misorder-time",
2878           value);
2879       break;
2880     case PROP_RFC7273_SYNC:
2881       rtpbin->rfc7273_sync = g_value_get_boolean (value);
2882       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2883           "rfc7273-sync", value);
2884       break;
2885     case PROP_MAX_STREAMS:
2886       rtpbin->max_streams = g_value_get_uint (value);
2887       break;
2888     case PROP_MAX_TS_OFFSET_ADJUSTMENT:
2889       rtpbin->max_ts_offset_adjustment = g_value_get_uint64 (value);
2890       gst_rtp_bin_propagate_property_to_jitterbuffer (rtpbin,
2891           "max-ts-offset-adjustment", value);
2892       break;
2893     case PROP_MAX_TS_OFFSET:
2894       rtpbin->max_ts_offset = g_value_get_int64 (value);
2895       rtpbin->max_ts_offset_is_set = TRUE;
2896       break;
2897     default:
2898       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2899       break;
2900   }
2901 }
2902
2903 static void
2904 gst_rtp_bin_get_property (GObject * object, guint prop_id,
2905     GValue * value, GParamSpec * pspec)
2906 {
2907   GstRtpBin *rtpbin;
2908
2909   rtpbin = GST_RTP_BIN (object);
2910
2911   switch (prop_id) {
2912     case PROP_LATENCY:
2913       GST_RTP_BIN_LOCK (rtpbin);
2914       g_value_set_uint (value, rtpbin->latency_ms);
2915       GST_RTP_BIN_UNLOCK (rtpbin);
2916       break;
2917     case PROP_DROP_ON_LATENCY:
2918       GST_RTP_BIN_LOCK (rtpbin);
2919       g_value_set_boolean (value, rtpbin->drop_on_latency);
2920       GST_RTP_BIN_UNLOCK (rtpbin);
2921       break;
2922     case PROP_SDES:
2923       g_value_take_boxed (value, gst_rtp_bin_get_sdes_struct (rtpbin));
2924       break;
2925     case PROP_DO_LOST:
2926       GST_RTP_BIN_LOCK (rtpbin);
2927       g_value_set_boolean (value, rtpbin->do_lost);
2928       GST_RTP_BIN_UNLOCK (rtpbin);
2929       break;
2930     case PROP_IGNORE_PT:
2931       g_value_set_boolean (value, rtpbin->ignore_pt);
2932       break;
2933     case PROP_NTP_SYNC:
2934       g_value_set_boolean (value, rtpbin->ntp_sync);
2935       break;
2936     case PROP_RTCP_SYNC:
2937       g_value_set_enum (value, g_atomic_int_get (&rtpbin->rtcp_sync));
2938       break;
2939     case PROP_RTCP_SYNC_INTERVAL:
2940       g_value_set_uint (value, rtpbin->rtcp_sync_interval);
2941       break;
2942     case PROP_AUTOREMOVE:
2943       g_value_set_boolean (value, rtpbin->priv->autoremove);
2944       break;
2945     case PROP_BUFFER_MODE:
2946       g_value_set_enum (value, rtpbin->buffer_mode);
2947       break;
2948     case PROP_USE_PIPELINE_CLOCK:
2949       g_value_set_boolean (value, rtpbin->use_pipeline_clock);
2950       break;
2951     case PROP_DO_SYNC_EVENT:
2952       g_value_set_boolean (value, rtpbin->send_sync_event);
2953       break;
2954     case PROP_DO_RETRANSMISSION:
2955       GST_RTP_BIN_LOCK (rtpbin);
2956       g_value_set_boolean (value, rtpbin->do_retransmission);
2957       GST_RTP_BIN_UNLOCK (rtpbin);
2958       break;
2959     case PROP_RTP_PROFILE:
2960       g_value_set_enum (value, rtpbin->rtp_profile);
2961       break;
2962     case PROP_NTP_TIME_SOURCE:
2963       g_value_set_enum (value, rtpbin->ntp_time_source);
2964       break;
2965     case PROP_RTCP_SYNC_SEND_TIME:
2966       g_value_set_boolean (value, rtpbin->rtcp_sync_send_time);
2967       break;
2968     case PROP_MAX_RTCP_RTP_TIME_DIFF:
2969       GST_RTP_BIN_LOCK (rtpbin);
2970       g_value_set_int (value, rtpbin->max_rtcp_rtp_time_diff);
2971       GST_RTP_BIN_UNLOCK (rtpbin);
2972       break;
2973     case PROP_MAX_DROPOUT_TIME:
2974       g_value_set_uint (value, rtpbin->max_dropout_time);
2975       break;
2976     case PROP_MAX_MISORDER_TIME:
2977       g_value_set_uint (value, rtpbin->max_misorder_time);
2978       break;
2979     case PROP_RFC7273_SYNC:
2980       g_value_set_boolean (value, rtpbin->rfc7273_sync);
2981       break;
2982     case PROP_MAX_STREAMS:
2983       g_value_set_uint (value, rtpbin->max_streams);
2984       break;
2985     case PROP_MAX_TS_OFFSET_ADJUSTMENT:
2986       g_value_set_uint64 (value, rtpbin->max_ts_offset_adjustment);
2987       break;
2988     case PROP_MAX_TS_OFFSET:
2989       g_value_set_int64 (value, rtpbin->max_ts_offset);
2990       break;
2991     default:
2992       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2993       break;
2994   }
2995 }
2996
2997 static void
2998 gst_rtp_bin_handle_message (GstBin * bin, GstMessage * message)
2999 {
3000   GstRtpBin *rtpbin;
3001
3002   rtpbin = GST_RTP_BIN (bin);
3003
3004   switch (GST_MESSAGE_TYPE (message)) {
3005     case GST_MESSAGE_ELEMENT:
3006     {
3007       const GstStructure *s = gst_message_get_structure (message);
3008
3009       /* we change the structure name and add the session ID to it */
3010       if (gst_structure_has_name (s, "application/x-rtp-source-sdes")) {
3011         GstRtpBinSession *sess;
3012
3013         /* find the session we set it as object data */
3014         sess = g_object_get_data (G_OBJECT (GST_MESSAGE_SRC (message)),
3015             "GstRTPBin.session");
3016
3017         if (G_LIKELY (sess)) {
3018           message = gst_message_make_writable (message);
3019           s = gst_message_get_structure (message);
3020           gst_structure_set ((GstStructure *) s, "session", G_TYPE_UINT,
3021               sess->id, NULL);
3022         }
3023       }
3024       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
3025       break;
3026     }
3027     case GST_MESSAGE_BUFFERING:
3028     {
3029       gint percent;
3030       gint min_percent = 100;
3031       GSList *sessions, *streams;
3032       GstRtpBinStream *stream;
3033       gboolean change = FALSE, active = FALSE;
3034       GstClockTime min_out_time;
3035       GstBufferingMode mode;
3036       gint avg_in, avg_out;
3037       gint64 buffering_left;
3038
3039       gst_message_parse_buffering (message, &percent);
3040       gst_message_parse_buffering_stats (message, &mode, &avg_in, &avg_out,
3041           &buffering_left);
3042
3043       stream =
3044           g_object_get_data (G_OBJECT (GST_MESSAGE_SRC (message)),
3045           "GstRTPBin.stream");
3046
3047       GST_DEBUG_OBJECT (bin, "got percent %d from stream %p", percent, stream);
3048
3049       /* get the stream */
3050       if (G_LIKELY (stream)) {
3051         GST_RTP_BIN_LOCK (rtpbin);
3052         /* fill in the percent */
3053         stream->percent = percent;
3054
3055         /* calculate the min value for all streams */
3056         for (sessions = rtpbin->sessions; sessions;
3057             sessions = g_slist_next (sessions)) {
3058           GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
3059
3060           GST_RTP_SESSION_LOCK (session);
3061           if (session->streams) {
3062             for (streams = session->streams; streams;
3063                 streams = g_slist_next (streams)) {
3064               GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
3065
3066               GST_DEBUG_OBJECT (bin, "stream %p percent %d", stream,
3067                   stream->percent);
3068
3069               /* find min percent */
3070               if (min_percent > stream->percent)
3071                 min_percent = stream->percent;
3072             }
3073           } else {
3074             GST_INFO_OBJECT (bin,
3075                 "session has no streams, setting min_percent to 0");
3076             min_percent = 0;
3077           }
3078           GST_RTP_SESSION_UNLOCK (session);
3079         }
3080         GST_DEBUG_OBJECT (bin, "min percent %d", min_percent);
3081
3082         if (rtpbin->buffering) {
3083           if (min_percent == 100) {
3084             rtpbin->buffering = FALSE;
3085             active = TRUE;
3086             change = TRUE;
3087           }
3088         } else {
3089           if (min_percent < 100) {
3090             /* pause the streams */
3091             rtpbin->buffering = TRUE;
3092             active = FALSE;
3093             change = TRUE;
3094           }
3095         }
3096         GST_RTP_BIN_UNLOCK (rtpbin);
3097
3098         gst_message_unref (message);
3099
3100         /* make a new buffering message with the min value */
3101         message =
3102             gst_message_new_buffering (GST_OBJECT_CAST (bin), min_percent);
3103         gst_message_set_buffering_stats (message, mode, avg_in, avg_out,
3104             buffering_left);
3105
3106         if (G_UNLIKELY (change)) {
3107           GstClock *clock;
3108           guint64 running_time = 0;
3109           guint64 offset = 0;
3110
3111           /* figure out the running time when we have a clock */
3112           if (G_LIKELY ((clock =
3113                       gst_element_get_clock (GST_ELEMENT_CAST (bin))))) {
3114             guint64 now, base_time;
3115
3116             now = gst_clock_get_time (clock);
3117             base_time = gst_element_get_base_time (GST_ELEMENT_CAST (bin));
3118             running_time = now - base_time;
3119             gst_object_unref (clock);
3120           }
3121           GST_DEBUG_OBJECT (bin,
3122               "running time now %" GST_TIME_FORMAT,
3123               GST_TIME_ARGS (running_time));
3124
3125           GST_RTP_BIN_LOCK (rtpbin);
3126
3127           /* when we reactivate, calculate the offsets so that all streams have
3128            * an output time that is at least as big as the running_time */
3129           offset = 0;
3130           if (active) {
3131             if (running_time > rtpbin->buffer_start) {
3132               offset = running_time - rtpbin->buffer_start;
3133               if (offset >= rtpbin->latency_ns)
3134                 offset -= rtpbin->latency_ns;
3135               else
3136                 offset = 0;
3137             }
3138           }
3139
3140           /* pause all streams */
3141           min_out_time = -1;
3142           for (sessions = rtpbin->sessions; sessions;
3143               sessions = g_slist_next (sessions)) {
3144             GstRtpBinSession *session = (GstRtpBinSession *) sessions->data;
3145
3146             GST_RTP_SESSION_LOCK (session);
3147             for (streams = session->streams; streams;
3148                 streams = g_slist_next (streams)) {
3149               GstRtpBinStream *stream = (GstRtpBinStream *) streams->data;
3150               GstElement *element = stream->buffer;
3151               guint64 last_out;
3152
3153               g_signal_emit_by_name (element, "set-active", active, offset,
3154                   &last_out);
3155
3156               if (!active) {
3157                 g_object_get (element, "percent", &stream->percent, NULL);
3158
3159                 if (last_out == -1)
3160                   last_out = 0;
3161                 if (min_out_time == -1 || last_out < min_out_time)
3162                   min_out_time = last_out;
3163               }
3164
3165               GST_DEBUG_OBJECT (bin,
3166                   "setting %p to %d, offset %" GST_TIME_FORMAT ", last %"
3167                   GST_TIME_FORMAT ", percent %d", element, active,
3168                   GST_TIME_ARGS (offset), GST_TIME_ARGS (last_out),
3169                   stream->percent);
3170             }
3171             GST_RTP_SESSION_UNLOCK (session);
3172           }
3173           GST_DEBUG_OBJECT (bin,
3174               "min out time %" GST_TIME_FORMAT, GST_TIME_ARGS (min_out_time));
3175
3176           /* the buffer_start is the min out time of all paused jitterbuffers */
3177           if (!active)
3178             rtpbin->buffer_start = min_out_time;
3179
3180           GST_RTP_BIN_UNLOCK (rtpbin);
3181         }
3182       }
3183       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
3184       break;
3185     }
3186     default:
3187     {
3188       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
3189       break;
3190     }
3191   }
3192 }
3193
3194 static GstStateChangeReturn
3195 gst_rtp_bin_change_state (GstElement * element, GstStateChange transition)
3196 {
3197   GstStateChangeReturn res;
3198   GstRtpBin *rtpbin;
3199   GstRtpBinPrivate *priv;
3200
3201   rtpbin = GST_RTP_BIN (element);
3202   priv = rtpbin->priv;
3203
3204   switch (transition) {
3205     case GST_STATE_CHANGE_NULL_TO_READY:
3206       break;
3207     case GST_STATE_CHANGE_READY_TO_PAUSED:
3208       priv->last_ntpnstime = 0;
3209       GST_LOG_OBJECT (rtpbin, "clearing shutdown flag");
3210       g_atomic_int_set (&priv->shutdown, 0);
3211       break;
3212     case GST_STATE_CHANGE_PAUSED_TO_READY:
3213       GST_LOG_OBJECT (rtpbin, "setting shutdown flag");
3214       g_atomic_int_set (&priv->shutdown, 1);
3215       /* wait for all callbacks to end by taking the lock. No new callbacks will
3216        * be able to happen as we set the shutdown flag. */
3217       GST_RTP_BIN_DYN_LOCK (rtpbin);
3218       GST_LOG_OBJECT (rtpbin, "dynamic lock taken, we can continue shutdown");
3219       GST_RTP_BIN_DYN_UNLOCK (rtpbin);
3220       break;
3221     default:
3222       break;
3223   }
3224
3225   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3226
3227   switch (transition) {
3228     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3229       break;
3230     case GST_STATE_CHANGE_PAUSED_TO_READY:
3231       break;
3232     case GST_STATE_CHANGE_READY_TO_NULL:
3233       break;
3234     default:
3235       break;
3236   }
3237   return res;
3238 }
3239
3240 static GstElement *
3241 session_request_element (GstRtpBinSession * session, guint signal)
3242 {
3243   GstElement *element = NULL;
3244   GstRtpBin *bin = session->bin;
3245
3246   g_signal_emit (bin, gst_rtp_bin_signals[signal], 0, session->id, &element);
3247
3248   if (element) {
3249     if (!bin_manage_element (bin, element))
3250       goto manage_failed;
3251     session->elements = g_slist_prepend (session->elements, element);
3252   }
3253   return element;
3254
3255   /* ERRORS */
3256 manage_failed:
3257   {
3258     GST_WARNING_OBJECT (bin, "unable to manage element");
3259     gst_object_unref (element);
3260     return NULL;
3261   }
3262 }
3263
3264 static gboolean
3265 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
3266 {
3267   GstPad *gpad = GST_PAD_CAST (user_data);
3268
3269   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
3270   gst_pad_store_sticky_event (gpad, *event);
3271
3272   return TRUE;
3273 }
3274
3275 static void
3276 expose_recv_src_pad (GstRtpBin * rtpbin, GstPad * pad, GstRtpBinStream * stream,
3277     guint8 pt)
3278 {
3279   GstElementClass *klass;
3280   GstPadTemplate *templ;
3281   gchar *padname;
3282   GstPad *gpad;
3283
3284   gst_object_ref (pad);
3285
3286   if (stream->session->storage) {
3287     GstElement *fec_decoder =
3288         session_request_element (stream->session, SIGNAL_REQUEST_FEC_DECODER);
3289
3290     if (fec_decoder) {
3291       GstPad *sinkpad, *srcpad;
3292       GstPadLinkReturn ret;
3293
3294       sinkpad = gst_element_get_static_pad (fec_decoder, "sink");
3295
3296       if (!sinkpad)
3297         goto fec_decoder_sink_failed;
3298
3299       ret = gst_pad_link (pad, sinkpad);
3300       gst_object_unref (sinkpad);
3301
3302       if (ret != GST_PAD_LINK_OK)
3303         goto fec_decoder_link_failed;
3304
3305       srcpad = gst_element_get_static_pad (fec_decoder, "src");
3306
3307       if (!srcpad)
3308         goto fec_decoder_src_failed;
3309
3310       gst_pad_sticky_events_foreach (pad, copy_sticky_events, srcpad);
3311       gst_object_unref (pad);
3312       pad = srcpad;
3313     }
3314   }
3315
3316   GST_RTP_BIN_SHUTDOWN_LOCK (rtpbin, shutdown);
3317
3318   /* ghost the pad to the parent */
3319   klass = GST_ELEMENT_GET_CLASS (rtpbin);
3320   templ = gst_element_class_get_pad_template (klass, "recv_rtp_src_%u_%u_%u");
3321   padname = g_strdup_printf ("recv_rtp_src_%u_%u_%u",
3322       stream->session->id, stream->ssrc, pt);
3323   gpad = gst_ghost_pad_new_from_template (padname, pad, templ);
3324   g_free (padname);
3325   g_object_set_data (G_OBJECT (pad), "GstRTPBin.ghostpad", gpad);
3326
3327   gst_pad_set_active (gpad, TRUE);
3328   GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
3329
3330   gst_pad_sticky_events_foreach (pad, copy_sticky_events, gpad);
3331   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), gpad);
3332
3333 done:
3334   gst_object_unref (pad);
3335
3336   return;
3337
3338 shutdown:
3339   {
3340     GST_DEBUG ("ignoring, we are shutting down");
3341     goto done;
3342   }
3343 fec_decoder_sink_failed:
3344   {
3345     g_warning ("rtpbin: failed to get fec encoder sink pad for session %u",
3346         stream->session->id);
3347     goto done;
3348   }
3349 fec_decoder_src_failed:
3350   {
3351     g_warning ("rtpbin: failed to get fec encoder src pad for session %u",
3352         stream->session->id);
3353     goto done;
3354   }
3355 fec_decoder_link_failed:
3356   {
3357     g_warning ("rtpbin: failed to link fec decoder for session %u",
3358         stream->session->id);
3359     goto done;
3360   }
3361 }
3362
3363 /* a new pad (SSRC) was created in @session. This signal is emited from the
3364  * payload demuxer. */
3365 static void
3366 new_payload_found (GstElement * element, guint pt, GstPad * pad,
3367     GstRtpBinStream * stream)
3368 {
3369   GstRtpBin *rtpbin;
3370
3371   rtpbin = stream->bin;
3372
3373   GST_DEBUG_OBJECT (rtpbin, "new payload pad %u", pt);
3374
3375   expose_recv_src_pad (rtpbin, pad, stream, pt);
3376 }
3377
3378 static void
3379 payload_pad_removed (GstElement * element, GstPad * pad,
3380     GstRtpBinStream * stream)
3381 {
3382   GstRtpBin *rtpbin;
3383   GstPad *gpad;
3384
3385   rtpbin = stream->bin;
3386
3387   GST_DEBUG ("payload pad removed");
3388
3389   GST_RTP_BIN_DYN_LOCK (rtpbin);
3390   if ((gpad = g_object_get_data (G_OBJECT (pad), "GstRTPBin.ghostpad"))) {
3391     g_object_set_data (G_OBJECT (pad), "GstRTPBin.ghostpad", NULL);
3392
3393     gst_pad_set_active (gpad, FALSE);
3394     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin), gpad);
3395   }
3396   GST_RTP_BIN_DYN_UNLOCK (rtpbin);
3397 }
3398
3399 static GstCaps *
3400 pt_map_requested (GstElement * element, guint pt, GstRtpBinSession * session)
3401 {
3402   GstRtpBin *rtpbin;
3403   GstCaps *caps;
3404
3405   rtpbin = session->bin;
3406
3407   GST_DEBUG_OBJECT (rtpbin, "payload map requested for pt %u in session %u", pt,
3408       session->id);
3409
3410   caps = get_pt_map (session, pt);
3411   if (!caps)
3412     goto no_caps;
3413
3414   return caps;
3415
3416   /* ERRORS */
3417 no_caps:
3418   {
3419     GST_DEBUG_OBJECT (rtpbin, "could not get caps");
3420     return NULL;
3421   }
3422 }
3423
3424 static GstCaps *
3425 ptdemux_pt_map_requested (GstElement * element, guint pt,
3426     GstRtpBinSession * session)
3427 {
3428   GstCaps *ret = pt_map_requested (element, pt, session);
3429
3430   if (ret && gst_caps_get_size (ret) == 1) {
3431     const GstStructure *s = gst_caps_get_structure (ret, 0);
3432     gboolean is_fec;
3433
3434     if (gst_structure_get_boolean (s, "is-fec", &is_fec) && is_fec) {
3435       GValue v = G_VALUE_INIT;
3436       GValue v2 = G_VALUE_INIT;
3437
3438       GST_INFO_OBJECT (session->bin, "Will ignore FEC pt %u in session %u", pt,
3439           session->id);
3440       g_value_init (&v, GST_TYPE_ARRAY);
3441       g_value_init (&v2, G_TYPE_INT);
3442       g_object_get_property (G_OBJECT (element), "ignored-payload-types", &v);
3443       g_value_set_int (&v2, pt);
3444       gst_value_array_append_value (&v, &v2);
3445       g_value_unset (&v2);
3446       g_object_set_property (G_OBJECT (element), "ignored-payload-types", &v);
3447       g_value_unset (&v);
3448     }
3449   }
3450
3451   return ret;
3452 }
3453
3454 static void
3455 payload_type_change (GstElement * element, guint pt, GstRtpBinSession * session)
3456 {
3457   GST_DEBUG_OBJECT (session->bin,
3458       "emiting signal for pt type changed to %u in session %u", pt,
3459       session->id);
3460
3461   g_signal_emit (session->bin, gst_rtp_bin_signals[SIGNAL_PAYLOAD_TYPE_CHANGE],
3462       0, session->id, pt);
3463 }
3464
3465 /* emitted when caps changed for the session */
3466 static void
3467 caps_changed (GstPad * pad, GParamSpec * pspec, GstRtpBinSession * session)
3468 {
3469   GstRtpBin *bin;
3470   GstCaps *caps;
3471   gint payload;
3472   const GstStructure *s;
3473
3474   bin = session->bin;
3475
3476   g_object_get (pad, "caps", &caps, NULL);
3477
3478   if (caps == NULL)
3479     return;
3480
3481   GST_DEBUG_OBJECT (bin, "got caps %" GST_PTR_FORMAT, caps);
3482
3483   s = gst_caps_get_structure (caps, 0);
3484
3485   /* get payload, finish when it's not there */
3486   if (!gst_structure_get_int (s, "payload", &payload)) {
3487     gst_caps_unref (caps);
3488     return;
3489   }
3490
3491   GST_RTP_SESSION_LOCK (session);
3492   GST_DEBUG_OBJECT (bin, "insert caps for payload %d", payload);
3493   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (payload), caps);
3494   GST_RTP_SESSION_UNLOCK (session);
3495 }
3496
3497 /* a new pad (SSRC) was created in @session */
3498 static void
3499 new_ssrc_pad_found (GstElement * element, guint ssrc, GstPad * pad,
3500     GstRtpBinSession * session)
3501 {
3502   GstRtpBin *rtpbin;
3503   GstRtpBinStream *stream;
3504   GstPad *sinkpad, *srcpad;
3505   gchar *padname;
3506
3507   rtpbin = session->bin;
3508
3509   GST_DEBUG_OBJECT (rtpbin, "new SSRC pad %08x, %s:%s", ssrc,
3510       GST_DEBUG_PAD_NAME (pad));
3511
3512   GST_RTP_BIN_SHUTDOWN_LOCK (rtpbin, shutdown);
3513
3514   GST_RTP_SESSION_LOCK (session);
3515
3516   /* create new stream */
3517   stream = create_stream (session, ssrc);
3518   if (!stream)
3519     goto no_stream;
3520
3521   /* get pad and link */
3522   GST_DEBUG_OBJECT (rtpbin, "linking jitterbuffer RTP");
3523   padname = g_strdup_printf ("src_%u", ssrc);
3524   srcpad = gst_element_get_static_pad (element, padname);
3525   g_free (padname);
3526   sinkpad = gst_element_get_static_pad (stream->buffer, "sink");
3527   gst_pad_link_full (srcpad, sinkpad, GST_PAD_LINK_CHECK_NOTHING);
3528   gst_object_unref (sinkpad);
3529   gst_object_unref (srcpad);
3530
3531   GST_DEBUG_OBJECT (rtpbin, "linking jitterbuffer RTCP");
3532   padname = g_strdup_printf ("rtcp_src_%u", ssrc);
3533   srcpad = gst_element_get_static_pad (element, padname);
3534   g_free (padname);
3535   sinkpad = gst_element_get_request_pad (stream->buffer, "sink_rtcp");
3536   gst_pad_link_full (srcpad, sinkpad, GST_PAD_LINK_CHECK_NOTHING);
3537   gst_object_unref (sinkpad);
3538   gst_object_unref (srcpad);
3539
3540   /* connect to the RTCP sync signal from the jitterbuffer */
3541   GST_DEBUG_OBJECT (rtpbin, "connecting sync signal");
3542   stream->buffer_handlesync_sig = g_signal_connect (stream->buffer,
3543       "handle-sync", (GCallback) gst_rtp_bin_handle_sync, stream);
3544
3545   if (stream->demux) {
3546     /* connect to the new-pad signal of the payload demuxer, this will expose the
3547      * new pad by ghosting it. */
3548     stream->demux_newpad_sig = g_signal_connect (stream->demux,
3549         "new-payload-type", (GCallback) new_payload_found, stream);
3550     stream->demux_padremoved_sig = g_signal_connect (stream->demux,
3551         "pad-removed", (GCallback) payload_pad_removed, stream);
3552
3553     /* connect to the request-pt-map signal. This signal will be emitted by the
3554      * demuxer so that it can apply a proper caps on the buffers for the
3555      * depayloaders. */
3556     stream->demux_ptreq_sig = g_signal_connect (stream->demux,
3557         "request-pt-map", (GCallback) ptdemux_pt_map_requested, session);
3558     /* connect to the  signal so it can be forwarded. */
3559     stream->demux_ptchange_sig = g_signal_connect (stream->demux,
3560         "payload-type-change", (GCallback) payload_type_change, session);
3561
3562     GST_RTP_SESSION_UNLOCK (session);
3563     GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
3564   } else {
3565     /* add rtpjitterbuffer src pad to pads */
3566     GstPad *pad;
3567
3568     pad = gst_element_get_static_pad (stream->buffer, "src");
3569
3570     GST_RTP_SESSION_UNLOCK (session);
3571     GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
3572
3573     expose_recv_src_pad (rtpbin, pad, stream, 255);
3574
3575     gst_object_unref (pad);
3576   }
3577
3578   return;
3579
3580   /* ERRORS */
3581 shutdown:
3582   {
3583     GST_DEBUG_OBJECT (rtpbin, "we are shutting down");
3584     return;
3585   }
3586 no_stream:
3587   {
3588     GST_RTP_SESSION_UNLOCK (session);
3589     GST_RTP_BIN_SHUTDOWN_UNLOCK (rtpbin);
3590     GST_DEBUG_OBJECT (rtpbin, "could not create stream");
3591     return;
3592   }
3593 }
3594
3595 static GstPad *
3596 complete_session_sink (GstRtpBin * rtpbin, GstRtpBinSession * session)
3597 {
3598   guint sessid = session->id;
3599   GstPad *recv_rtp_sink;
3600   GstElement *decoder;
3601
3602   g_assert (!session->recv_rtp_sink);
3603
3604   /* get recv_rtp pad and store */
3605   session->recv_rtp_sink =
3606       gst_element_get_request_pad (session->session, "recv_rtp_sink");
3607   if (session->recv_rtp_sink == NULL)
3608     goto pad_failed;
3609
3610   g_signal_connect (session->recv_rtp_sink, "notify::caps",
3611       (GCallback) caps_changed, session);
3612
3613   GST_DEBUG_OBJECT (rtpbin, "requesting RTP decoder");
3614   decoder = session_request_element (session, SIGNAL_REQUEST_RTP_DECODER);
3615   if (decoder) {
3616     GstPad *decsrc, *decsink;
3617     GstPadLinkReturn ret;
3618
3619     GST_DEBUG_OBJECT (rtpbin, "linking RTP decoder");
3620     decsink = gst_element_get_static_pad (decoder, "rtp_sink");
3621     if (decsink == NULL)
3622       goto dec_sink_failed;
3623
3624     recv_rtp_sink = decsink;
3625
3626     decsrc = gst_element_get_static_pad (decoder, "rtp_src");
3627     if (decsrc == NULL)
3628       goto dec_src_failed;
3629
3630     ret = gst_pad_link (decsrc, session->recv_rtp_sink);
3631
3632     gst_object_unref (decsrc);
3633
3634     if (ret != GST_PAD_LINK_OK)
3635       goto dec_link_failed;
3636
3637   } else {
3638     GST_DEBUG_OBJECT (rtpbin, "no RTP decoder given");
3639     recv_rtp_sink = gst_object_ref (session->recv_rtp_sink);
3640   }
3641
3642   return recv_rtp_sink;
3643
3644   /* ERRORS */
3645 pad_failed:
3646   {
3647     g_warning ("rtpbin: failed to get session recv_rtp_sink pad");
3648     return NULL;
3649   }
3650 dec_sink_failed:
3651   {
3652     g_warning ("rtpbin: failed to get decoder sink pad for session %u", sessid);
3653     return NULL;
3654   }
3655 dec_src_failed:
3656   {
3657     g_warning ("rtpbin: failed to get decoder src pad for session %u", sessid);
3658     gst_object_unref (recv_rtp_sink);
3659     return NULL;
3660   }
3661 dec_link_failed:
3662   {
3663     g_warning ("rtpbin: failed to link rtp decoder for session %u", sessid);
3664     gst_object_unref (recv_rtp_sink);
3665     return NULL;
3666   }
3667 }
3668
3669 static void
3670 complete_session_receiver (GstRtpBin * rtpbin, GstRtpBinSession * session,
3671     guint sessid)
3672 {
3673   GstElement *aux;
3674   GstPad *recv_rtp_src;
3675
3676   g_assert (!session->recv_rtp_src);
3677
3678   session->recv_rtp_src =
3679       gst_element_get_static_pad (session->session, "recv_rtp_src");
3680   if (session->recv_rtp_src == NULL)
3681     goto pad_failed;
3682
3683   /* find out if we need AUX elements */
3684   aux = session_request_element (session, SIGNAL_REQUEST_AUX_RECEIVER);
3685   if (aux) {
3686     gchar *pname;
3687     GstPad *auxsink;
3688     GstPadLinkReturn ret;
3689
3690     GST_DEBUG_OBJECT (rtpbin, "linking AUX receiver");
3691
3692     pname = g_strdup_printf ("sink_%u", sessid);
3693     auxsink = gst_element_get_static_pad (aux, pname);
3694     g_free (pname);
3695     if (auxsink == NULL)
3696       goto aux_sink_failed;
3697
3698     ret = gst_pad_link (session->recv_rtp_src, auxsink);
3699     gst_object_unref (auxsink);
3700     if (ret != GST_PAD_LINK_OK)
3701       goto aux_link_failed;
3702
3703     /* this can be NULL when this AUX element is not to be linked any further */
3704     pname = g_strdup_printf ("src_%u", sessid);
3705     recv_rtp_src = gst_element_get_static_pad (aux, pname);
3706     g_free (pname);
3707   } else {
3708     recv_rtp_src = gst_object_ref (session->recv_rtp_src);
3709   }
3710
3711   /* Add a storage element if needed */
3712   if (recv_rtp_src && session->storage) {
3713     GstPadLinkReturn ret;
3714     GstPad *sinkpad = gst_element_get_static_pad (session->storage, "sink");
3715
3716     ret = gst_pad_link (recv_rtp_src, sinkpad);
3717
3718     gst_object_unref (sinkpad);
3719     gst_object_unref (recv_rtp_src);
3720
3721     if (ret != GST_PAD_LINK_OK)
3722       goto storage_link_failed;
3723
3724     recv_rtp_src = gst_element_get_static_pad (session->storage, "src");
3725   }
3726
3727   if (recv_rtp_src) {
3728     GstPad *sinkdpad;
3729
3730     GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTP sink pad");
3731     sinkdpad = gst_element_get_static_pad (session->demux, "sink");
3732     GST_DEBUG_OBJECT (rtpbin, "linking demuxer RTP sink pad");
3733     gst_pad_link_full (recv_rtp_src, sinkdpad, GST_PAD_LINK_CHECK_NOTHING);
3734     gst_object_unref (sinkdpad);
3735     gst_object_unref (recv_rtp_src);
3736
3737     /* connect to the new-ssrc-pad signal of the SSRC demuxer */
3738     session->demux_newpad_sig = g_signal_connect (session->demux,
3739         "new-ssrc-pad", (GCallback) new_ssrc_pad_found, session);
3740     session->demux_padremoved_sig = g_signal_connect (session->demux,
3741         "removed-ssrc-pad", (GCallback) ssrc_demux_pad_removed, session);
3742   }
3743
3744   return;
3745
3746 pad_failed:
3747   {
3748     g_warning ("rtpbin: failed to get session recv_rtp_src pad");
3749     return;
3750   }
3751 aux_sink_failed:
3752   {
3753     g_warning ("rtpbin: failed to get AUX sink pad for session %u", sessid);
3754     return;
3755   }
3756 aux_link_failed:
3757   {
3758     g_warning ("rtpbin: failed to link AUX pad to session %u", sessid);
3759     return;
3760   }
3761 storage_link_failed:
3762   {
3763     g_warning ("rtpbin: failed to link storage");
3764     return;
3765   }
3766 }
3767
3768 /* Create a pad for receiving RTP for the session in @name. Must be called with
3769  * RTP_BIN_LOCK.
3770  */
3771 static GstPad *
3772 create_recv_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
3773 {
3774   guint sessid;
3775   GstRtpBinSession *session;
3776   GstPad *recv_rtp_sink;
3777
3778   /* first get the session number */
3779   if (name == NULL || sscanf (name, "recv_rtp_sink_%u", &sessid) != 1)
3780     goto no_name;
3781
3782   GST_DEBUG_OBJECT (rtpbin, "finding session %u", sessid);
3783
3784   /* get or create session */
3785   session = find_session_by_id (rtpbin, sessid);
3786   if (!session) {
3787     GST_DEBUG_OBJECT (rtpbin, "creating session %u", sessid);
3788     /* create session now */
3789     session = create_session (rtpbin, sessid);
3790     if (session == NULL)
3791       goto create_error;
3792   }
3793
3794   /* check if pad was requested */
3795   if (session->recv_rtp_sink_ghost != NULL)
3796     return session->recv_rtp_sink_ghost;
3797
3798   /* setup the session sink pad */
3799   recv_rtp_sink = complete_session_sink (rtpbin, session);
3800   if (!recv_rtp_sink)
3801     goto session_sink_failed;
3802
3803   GST_DEBUG_OBJECT (rtpbin, "ghosting session sink pad");
3804   session->recv_rtp_sink_ghost =
3805       gst_ghost_pad_new_from_template (name, recv_rtp_sink, templ);
3806   gst_object_unref (recv_rtp_sink);
3807   gst_pad_set_active (session->recv_rtp_sink_ghost, TRUE);
3808   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->recv_rtp_sink_ghost);
3809
3810   complete_session_receiver (rtpbin, session, sessid);
3811
3812   return session->recv_rtp_sink_ghost;
3813
3814   /* ERRORS */
3815 no_name:
3816   {
3817     g_warning ("rtpbin: invalid name given");
3818     return NULL;
3819   }
3820 create_error:
3821   {
3822     /* create_session already warned */
3823     return NULL;
3824   }
3825 session_sink_failed:
3826   {
3827     /* warning already done */
3828     return NULL;
3829   }
3830 }
3831
3832 static void
3833 remove_recv_rtp (GstRtpBin * rtpbin, GstRtpBinSession * session)
3834 {
3835   if (session->demux_newpad_sig) {
3836     g_signal_handler_disconnect (session->demux, session->demux_newpad_sig);
3837     session->demux_newpad_sig = 0;
3838   }
3839   if (session->demux_padremoved_sig) {
3840     g_signal_handler_disconnect (session->demux, session->demux_padremoved_sig);
3841     session->demux_padremoved_sig = 0;
3842   }
3843   if (session->recv_rtp_src) {
3844     gst_object_unref (session->recv_rtp_src);
3845     session->recv_rtp_src = NULL;
3846   }
3847   if (session->recv_rtp_sink) {
3848     gst_element_release_request_pad (session->session, session->recv_rtp_sink);
3849     gst_object_unref (session->recv_rtp_sink);
3850     session->recv_rtp_sink = NULL;
3851   }
3852   if (session->recv_rtp_sink_ghost) {
3853     gst_pad_set_active (session->recv_rtp_sink_ghost, FALSE);
3854     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
3855         session->recv_rtp_sink_ghost);
3856     session->recv_rtp_sink_ghost = NULL;
3857   }
3858 }
3859
3860 static GstPad *
3861 complete_session_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session,
3862     guint sessid)
3863 {
3864   GstElement *decoder;
3865   GstPad *sinkdpad;
3866   GstPad *decsink = NULL;
3867
3868   /* get recv_rtp pad and store */
3869   GST_DEBUG_OBJECT (rtpbin, "getting RTCP sink pad");
3870   session->recv_rtcp_sink =
3871       gst_element_get_request_pad (session->session, "recv_rtcp_sink");
3872   if (session->recv_rtcp_sink == NULL)
3873     goto pad_failed;
3874
3875   GST_DEBUG_OBJECT (rtpbin, "getting RTCP decoder");
3876   decoder = session_request_element (session, SIGNAL_REQUEST_RTCP_DECODER);
3877   if (decoder) {
3878     GstPad *decsrc;
3879     GstPadLinkReturn ret;
3880
3881     GST_DEBUG_OBJECT (rtpbin, "linking RTCP decoder");
3882     decsink = gst_element_get_static_pad (decoder, "rtcp_sink");
3883     decsrc = gst_element_get_static_pad (decoder, "rtcp_src");
3884
3885     if (decsink == NULL)
3886       goto dec_sink_failed;
3887
3888     if (decsrc == NULL)
3889       goto dec_src_failed;
3890
3891     ret = gst_pad_link (decsrc, session->recv_rtcp_sink);
3892
3893     gst_object_unref (decsrc);
3894
3895     if (ret != GST_PAD_LINK_OK)
3896       goto dec_link_failed;
3897   } else {
3898     GST_DEBUG_OBJECT (rtpbin, "no RTCP decoder given");
3899     decsink = gst_object_ref (session->recv_rtcp_sink);
3900   }
3901
3902   /* get srcpad, link to SSRCDemux */
3903   GST_DEBUG_OBJECT (rtpbin, "getting sync src pad");
3904   session->sync_src = gst_element_get_static_pad (session->session, "sync_src");
3905   if (session->sync_src == NULL)
3906     goto src_pad_failed;
3907
3908   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTCP sink pad");
3909   sinkdpad = gst_element_get_static_pad (session->demux, "rtcp_sink");
3910   gst_pad_link_full (session->sync_src, sinkdpad, GST_PAD_LINK_CHECK_NOTHING);
3911   gst_object_unref (sinkdpad);
3912
3913   return decsink;
3914
3915 pad_failed:
3916   {
3917     g_warning ("rtpbin: failed to get session rtcp_sink pad");
3918     return NULL;
3919   }
3920 dec_sink_failed:
3921   {
3922     g_warning ("rtpbin: failed to get decoder sink pad for session %u", sessid);
3923     return NULL;
3924   }
3925 dec_src_failed:
3926   {
3927     g_warning ("rtpbin: failed to get decoder src pad for session %u", sessid);
3928     goto cleanup;
3929   }
3930 dec_link_failed:
3931   {
3932     g_warning ("rtpbin: failed to link rtcp decoder for session %u", sessid);
3933     goto cleanup;
3934   }
3935 src_pad_failed:
3936   {
3937     g_warning ("rtpbin: failed to get session sync_src pad");
3938   }
3939
3940 cleanup:
3941   gst_object_unref (decsink);
3942   return NULL;
3943 }
3944
3945 /* Create a pad for receiving RTCP for the session in @name. Must be called with
3946  * RTP_BIN_LOCK.
3947  */
3948 static GstPad *
3949 create_recv_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ,
3950     const gchar * name)
3951 {
3952   guint sessid;
3953   GstRtpBinSession *session;
3954   GstPad *decsink = NULL;
3955
3956   /* first get the session number */
3957   if (name == NULL || sscanf (name, "recv_rtcp_sink_%u", &sessid) != 1)
3958     goto no_name;
3959
3960   GST_DEBUG_OBJECT (rtpbin, "finding session %u", sessid);
3961
3962   /* get or create the session */
3963   session = find_session_by_id (rtpbin, sessid);
3964   if (!session) {
3965     GST_DEBUG_OBJECT (rtpbin, "creating session %u", sessid);
3966     /* create session now */
3967     session = create_session (rtpbin, sessid);
3968     if (session == NULL)
3969       goto create_error;
3970   }
3971
3972   /* check if pad was requested */
3973   if (session->recv_rtcp_sink_ghost != NULL)
3974     return session->recv_rtcp_sink_ghost;
3975
3976   decsink = complete_session_rtcp (rtpbin, session, sessid);
3977   if (!decsink)
3978     goto create_error;
3979
3980   session->recv_rtcp_sink_ghost =
3981       gst_ghost_pad_new_from_template (name, decsink, templ);
3982   gst_object_unref (decsink);
3983   gst_pad_set_active (session->recv_rtcp_sink_ghost, TRUE);
3984   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin),
3985       session->recv_rtcp_sink_ghost);
3986
3987   return session->recv_rtcp_sink_ghost;
3988
3989   /* ERRORS */
3990 no_name:
3991   {
3992     g_warning ("rtpbin: invalid name given");
3993     return NULL;
3994   }
3995 create_error:
3996   {
3997     /* create_session already warned */
3998     return NULL;
3999   }
4000 }
4001
4002 static void
4003 remove_recv_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session)
4004 {
4005   if (session->recv_rtcp_sink_ghost) {
4006     gst_pad_set_active (session->recv_rtcp_sink_ghost, FALSE);
4007     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
4008         session->recv_rtcp_sink_ghost);
4009     session->recv_rtcp_sink_ghost = NULL;
4010   }
4011   if (session->sync_src) {
4012     /* releasing the request pad should also unref the sync pad */
4013     gst_object_unref (session->sync_src);
4014     session->sync_src = NULL;
4015   }
4016   if (session->recv_rtcp_sink) {
4017     gst_element_release_request_pad (session->session, session->recv_rtcp_sink);
4018     gst_object_unref (session->recv_rtcp_sink);
4019     session->recv_rtcp_sink = NULL;
4020   }
4021 }
4022
4023 static gboolean
4024 complete_session_src (GstRtpBin * rtpbin, GstRtpBinSession * session)
4025 {
4026   gchar *gname;
4027   guint sessid = session->id;
4028   GstPad *send_rtp_src;
4029   GstElement *encoder;
4030   GstElementClass *klass;
4031   GstPadTemplate *templ;
4032   gboolean ret = FALSE;
4033
4034   /* get srcpad */
4035   send_rtp_src = gst_element_get_static_pad (session->session, "send_rtp_src");
4036
4037   if (send_rtp_src == NULL)
4038     goto no_srcpad;
4039
4040   GST_DEBUG_OBJECT (rtpbin, "getting RTP encoder");
4041   encoder = session_request_element (session, SIGNAL_REQUEST_RTP_ENCODER);
4042   if (encoder) {
4043     gchar *ename;
4044     GstPad *encsrc, *encsink;
4045     GstPadLinkReturn ret;
4046
4047     GST_DEBUG_OBJECT (rtpbin, "linking RTP encoder");
4048     ename = g_strdup_printf ("rtp_src_%u", sessid);
4049     encsrc = gst_element_get_static_pad (encoder, ename);
4050     g_free (ename);
4051
4052     if (encsrc == NULL)
4053       goto enc_src_failed;
4054
4055     ename = g_strdup_printf ("rtp_sink_%u", sessid);
4056     encsink = gst_element_get_static_pad (encoder, ename);
4057     g_free (ename);
4058     if (encsink == NULL)
4059       goto enc_sink_failed;
4060
4061     ret = gst_pad_link (send_rtp_src, encsink);
4062     gst_object_unref (encsink);
4063     gst_object_unref (send_rtp_src);
4064
4065     send_rtp_src = encsrc;
4066
4067     if (ret != GST_PAD_LINK_OK)
4068       goto enc_link_failed;
4069   } else {
4070     GST_DEBUG_OBJECT (rtpbin, "no RTP encoder given");
4071   }
4072
4073   /* ghost the new source pad */
4074   klass = GST_ELEMENT_GET_CLASS (rtpbin);
4075   gname = g_strdup_printf ("send_rtp_src_%u", sessid);
4076   templ = gst_element_class_get_pad_template (klass, "send_rtp_src_%u");
4077   session->send_rtp_src_ghost =
4078       gst_ghost_pad_new_from_template (gname, send_rtp_src, templ);
4079   gst_pad_set_active (session->send_rtp_src_ghost, TRUE);
4080   gst_pad_sticky_events_foreach (send_rtp_src, copy_sticky_events,
4081       session->send_rtp_src_ghost);
4082   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->send_rtp_src_ghost);
4083   g_free (gname);
4084
4085   ret = TRUE;
4086
4087 done:
4088   if (send_rtp_src)
4089     gst_object_unref (send_rtp_src);
4090
4091   return ret;
4092
4093   /* ERRORS */
4094 no_srcpad:
4095   {
4096     g_warning ("rtpbin: failed to get rtp source pad for session %u", sessid);
4097     goto done;
4098   }
4099 enc_src_failed:
4100   {
4101     g_warning ("rtpbin: failed to get %" GST_PTR_FORMAT
4102         " src pad for session %u", encoder, sessid);
4103     goto done;
4104   }
4105 enc_sink_failed:
4106   {
4107     g_warning ("rtpbin: failed to get %" GST_PTR_FORMAT
4108         " sink pad for session %u", encoder, sessid);
4109     goto done;
4110   }
4111 enc_link_failed:
4112   {
4113     g_warning ("rtpbin: failed to link %" GST_PTR_FORMAT " for session %u",
4114         encoder, sessid);
4115     goto done;
4116   }
4117 }
4118
4119 static gboolean
4120 setup_aux_sender_fold (const GValue * item, GValue * result, gpointer user_data)
4121 {
4122   GstPad *pad;
4123   gchar *name;
4124   guint sessid;
4125   GstRtpBinSession *session = user_data, *newsess;
4126   GstRtpBin *rtpbin = session->bin;
4127   GstPadLinkReturn ret;
4128
4129   pad = g_value_get_object (item);
4130   name = gst_pad_get_name (pad);
4131
4132   if (name == NULL || sscanf (name, "src_%u", &sessid) != 1)
4133     goto no_name;
4134
4135   g_free (name);
4136
4137   newsess = find_session_by_id (rtpbin, sessid);
4138   if (newsess == NULL) {
4139     /* create new session */
4140     newsess = create_session (rtpbin, sessid);
4141     if (newsess == NULL)
4142       goto create_error;
4143   } else if (newsess->send_rtp_sink != NULL)
4144     goto existing_session;
4145
4146   /* get send_rtp pad and store */
4147   newsess->send_rtp_sink =
4148       gst_element_get_request_pad (newsess->session, "send_rtp_sink");
4149   if (newsess->send_rtp_sink == NULL)
4150     goto pad_failed;
4151
4152   ret = gst_pad_link (pad, newsess->send_rtp_sink);
4153   if (ret != GST_PAD_LINK_OK)
4154     goto aux_link_failed;
4155
4156   if (!complete_session_src (rtpbin, newsess))
4157     goto session_src_failed;
4158
4159   return TRUE;
4160
4161   /* ERRORS */
4162 no_name:
4163   {
4164     GST_WARNING ("ignoring invalid pad name %s", GST_STR_NULL (name));
4165     g_free (name);
4166     return TRUE;
4167   }
4168 create_error:
4169   {
4170     /* create_session already warned */
4171     return FALSE;
4172   }
4173 existing_session:
4174   {
4175     GST_DEBUG_OBJECT (rtpbin,
4176         "skipping src_%i setup, since it is already configured.", sessid);
4177     return TRUE;
4178   }
4179 pad_failed:
4180   {
4181     g_warning ("rtpbin: failed to get session pad for session %u", sessid);
4182     return FALSE;
4183   }
4184 aux_link_failed:
4185   {
4186     g_warning ("rtpbin: failed to link AUX for session %u", sessid);
4187     return FALSE;
4188   }
4189 session_src_failed:
4190   {
4191     g_warning ("rtpbin: failed to complete AUX for session %u", sessid);
4192     return FALSE;
4193   }
4194 }
4195
4196 static gboolean
4197 setup_aux_sender (GstRtpBin * rtpbin, GstRtpBinSession * session,
4198     GstElement * aux)
4199 {
4200   GstIterator *it;
4201   GValue result = { 0, };
4202   GstIteratorResult res;
4203
4204   it = gst_element_iterate_src_pads (aux);
4205   res = gst_iterator_fold (it, setup_aux_sender_fold, &result, session);
4206   gst_iterator_free (it);
4207
4208   return res == GST_ITERATOR_DONE;
4209 }
4210
4211 /* Create a pad for sending RTP for the session in @name. Must be called with
4212  * RTP_BIN_LOCK.
4213  */
4214 static GstPad *
4215 create_send_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
4216 {
4217   gchar *pname;
4218   guint sessid;
4219   GstPad *send_rtp_sink;
4220   GstElement *aux;
4221   GstElement *encoder;
4222   GstElement *prev = NULL;
4223   GstRtpBinSession *session;
4224
4225   /* first get the session number */
4226   if (name == NULL || sscanf (name, "send_rtp_sink_%u", &sessid) != 1)
4227     goto no_name;
4228
4229   /* get or create session */
4230   session = find_session_by_id (rtpbin, sessid);
4231   if (!session) {
4232     /* create session now */
4233     session = create_session (rtpbin, sessid);
4234     if (session == NULL)
4235       goto create_error;
4236   }
4237
4238   /* check if pad was requested */
4239   if (session->send_rtp_sink_ghost != NULL)
4240     return session->send_rtp_sink_ghost;
4241
4242   /* check if we are already using this session as a sender */
4243   if (session->send_rtp_sink != NULL)
4244     goto existing_session;
4245
4246   encoder = session_request_element (session, SIGNAL_REQUEST_FEC_ENCODER);
4247
4248   if (encoder) {
4249     GST_DEBUG_OBJECT (rtpbin, "Linking FEC encoder");
4250
4251     send_rtp_sink = gst_element_get_static_pad (encoder, "sink");
4252
4253     if (!send_rtp_sink)
4254       goto enc_sink_failed;
4255
4256     prev = encoder;
4257   }
4258
4259   GST_DEBUG_OBJECT (rtpbin, "getting RTP AUX sender");
4260   aux = session_request_element (session, SIGNAL_REQUEST_AUX_SENDER);
4261   if (aux) {
4262     GstPad *sinkpad;
4263     GST_DEBUG_OBJECT (rtpbin, "linking AUX sender");
4264     if (!setup_aux_sender (rtpbin, session, aux))
4265       goto aux_session_failed;
4266
4267     pname = g_strdup_printf ("sink_%u", sessid);
4268     sinkpad = gst_element_get_static_pad (aux, pname);
4269     g_free (pname);
4270
4271     if (sinkpad == NULL)
4272       goto aux_sink_failed;
4273
4274     if (!prev) {
4275       send_rtp_sink = sinkpad;
4276     } else {
4277       GstPad *srcpad = gst_element_get_static_pad (prev, "src");
4278       GstPadLinkReturn ret;
4279
4280       ret = gst_pad_link (srcpad, sinkpad);
4281       gst_object_unref (srcpad);
4282       if (ret != GST_PAD_LINK_OK) {
4283         goto aux_link_failed;
4284       }
4285     }
4286     prev = aux;
4287   } else {
4288     /* get send_rtp pad and store */
4289     session->send_rtp_sink =
4290         gst_element_get_request_pad (session->session, "send_rtp_sink");
4291     if (session->send_rtp_sink == NULL)
4292       goto pad_failed;
4293
4294     if (!complete_session_src (rtpbin, session))
4295       goto session_src_failed;
4296
4297     if (!prev) {
4298       send_rtp_sink = gst_object_ref (session->send_rtp_sink);
4299     } else {
4300       GstPad *srcpad = gst_element_get_static_pad (prev, "src");
4301       GstPadLinkReturn ret;
4302
4303       ret = gst_pad_link (srcpad, session->send_rtp_sink);
4304       gst_object_unref (srcpad);
4305       if (ret != GST_PAD_LINK_OK)
4306         goto session_link_failed;
4307     }
4308   }
4309
4310   session->send_rtp_sink_ghost =
4311       gst_ghost_pad_new_from_template (name, send_rtp_sink, templ);
4312   gst_object_unref (send_rtp_sink);
4313   gst_pad_set_active (session->send_rtp_sink_ghost, TRUE);
4314   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->send_rtp_sink_ghost);
4315
4316   return session->send_rtp_sink_ghost;
4317
4318   /* ERRORS */
4319 no_name:
4320   {
4321     g_warning ("rtpbin: invalid name given");
4322     return NULL;
4323   }
4324 create_error:
4325   {
4326     /* create_session already warned */
4327     return NULL;
4328   }
4329 existing_session:
4330   {
4331     g_warning ("rtpbin: session %u is already in use", sessid);
4332     return NULL;
4333   }
4334 aux_session_failed:
4335   {
4336     g_warning ("rtpbin: failed to get AUX sink pad for session %u", sessid);
4337     return NULL;
4338   }
4339 aux_sink_failed:
4340   {
4341     g_warning ("rtpbin: failed to get AUX sink pad for session %u", sessid);
4342     return NULL;
4343   }
4344 aux_link_failed:
4345   {
4346     g_warning ("rtpbin: failed to link %" GST_PTR_FORMAT " for session %u",
4347         aux, sessid);
4348     return NULL;
4349   }
4350 pad_failed:
4351   {
4352     g_warning ("rtpbin: failed to get session pad for session %u", sessid);
4353     return NULL;
4354   }
4355 session_src_failed:
4356   {
4357     g_warning ("rtpbin: failed to setup source pads for session %u", sessid);
4358     return NULL;
4359   }
4360 session_link_failed:
4361   {
4362     g_warning ("rtpbin: failed to link %" GST_PTR_FORMAT " for session %u",
4363         session, sessid);
4364     return NULL;
4365   }
4366 enc_sink_failed:
4367   {
4368     g_warning ("rtpbin: failed to get %" GST_PTR_FORMAT
4369         " sink pad for session %u", encoder, sessid);
4370     return NULL;
4371   }
4372 }
4373
4374 static void
4375 remove_send_rtp (GstRtpBin * rtpbin, GstRtpBinSession * session)
4376 {
4377   if (session->send_rtp_src_ghost) {
4378     gst_pad_set_active (session->send_rtp_src_ghost, FALSE);
4379     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
4380         session->send_rtp_src_ghost);
4381     session->send_rtp_src_ghost = NULL;
4382   }
4383   if (session->send_rtp_sink) {
4384     gst_element_release_request_pad (GST_ELEMENT_CAST (session->session),
4385         session->send_rtp_sink);
4386     gst_object_unref (session->send_rtp_sink);
4387     session->send_rtp_sink = NULL;
4388   }
4389   if (session->send_rtp_sink_ghost) {
4390     gst_pad_set_active (session->send_rtp_sink_ghost, FALSE);
4391     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
4392         session->send_rtp_sink_ghost);
4393     session->send_rtp_sink_ghost = NULL;
4394   }
4395 }
4396
4397 /* Create a pad for sending RTCP for the session in @name. Must be called with
4398  * RTP_BIN_LOCK.
4399  */
4400 static GstPad *
4401 create_send_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ,
4402     const gchar * name)
4403 {
4404   guint sessid;
4405   GstPad *encsrc;
4406   GstElement *encoder;
4407   GstRtpBinSession *session;
4408
4409   /* first get the session number */
4410   if (name == NULL || sscanf (name, "send_rtcp_src_%u", &sessid) != 1)
4411     goto no_name;
4412
4413   /* get or create session */
4414   session = find_session_by_id (rtpbin, sessid);
4415   if (!session) {
4416     GST_DEBUG_OBJECT (rtpbin, "creating session %u", sessid);
4417     /* create session now */
4418     session = create_session (rtpbin, sessid);
4419     if (session == NULL)
4420       goto create_error;
4421   }
4422
4423   /* check if pad was requested */
4424   if (session->send_rtcp_src_ghost != NULL)
4425     return session->send_rtcp_src_ghost;
4426
4427   /* get rtcp_src pad and store */
4428   session->send_rtcp_src =
4429       gst_element_get_request_pad (session->session, "send_rtcp_src");
4430   if (session->send_rtcp_src == NULL)
4431     goto pad_failed;
4432
4433   GST_DEBUG_OBJECT (rtpbin, "getting RTCP encoder");
4434   encoder = session_request_element (session, SIGNAL_REQUEST_RTCP_ENCODER);
4435   if (encoder) {
4436     gchar *ename;
4437     GstPad *encsink;
4438     GstPadLinkReturn ret;
4439
4440     GST_DEBUG_OBJECT (rtpbin, "linking RTCP encoder");
4441
4442     ename = g_strdup_printf ("rtcp_src_%u", sessid);
4443     encsrc = gst_element_get_static_pad (encoder, ename);
4444     g_free (ename);
4445     if (encsrc == NULL)
4446       goto enc_src_failed;
4447
4448     ename = g_strdup_printf ("rtcp_sink_%u", sessid);
4449     encsink = gst_element_get_static_pad (encoder, ename);
4450     g_free (ename);
4451     if (encsink == NULL)
4452       goto enc_sink_failed;
4453
4454     ret = gst_pad_link (session->send_rtcp_src, encsink);
4455     gst_object_unref (encsink);
4456
4457     if (ret != GST_PAD_LINK_OK)
4458       goto enc_link_failed;
4459   } else {
4460     GST_DEBUG_OBJECT (rtpbin, "no RTCP encoder given");
4461     encsrc = gst_object_ref (session->send_rtcp_src);
4462   }
4463
4464   session->send_rtcp_src_ghost =
4465       gst_ghost_pad_new_from_template (name, encsrc, templ);
4466   gst_object_unref (encsrc);
4467   gst_pad_set_active (session->send_rtcp_src_ghost, TRUE);
4468   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), session->send_rtcp_src_ghost);
4469
4470   return session->send_rtcp_src_ghost;
4471
4472   /* ERRORS */
4473 no_name:
4474   {
4475     g_warning ("rtpbin: invalid name given");
4476     return NULL;
4477   }
4478 create_error:
4479   {
4480     /* create_session already warned */
4481     return NULL;
4482   }
4483 pad_failed:
4484   {
4485     g_warning ("rtpbin: failed to get rtcp pad for session %u", sessid);
4486     return NULL;
4487   }
4488 enc_src_failed:
4489   {
4490     g_warning ("rtpbin: failed to get encoder src pad for session %u", sessid);
4491     return NULL;
4492   }
4493 enc_sink_failed:
4494   {
4495     g_warning ("rtpbin: failed to get encoder sink pad for session %u", sessid);
4496     gst_object_unref (encsrc);
4497     return NULL;
4498   }
4499 enc_link_failed:
4500   {
4501     g_warning ("rtpbin: failed to link rtcp encoder for session %u", sessid);
4502     gst_object_unref (encsrc);
4503     return NULL;
4504   }
4505 }
4506
4507 static void
4508 remove_rtcp (GstRtpBin * rtpbin, GstRtpBinSession * session)
4509 {
4510   if (session->send_rtcp_src_ghost) {
4511     gst_pad_set_active (session->send_rtcp_src_ghost, FALSE);
4512     gst_element_remove_pad (GST_ELEMENT_CAST (rtpbin),
4513         session->send_rtcp_src_ghost);
4514     session->send_rtcp_src_ghost = NULL;
4515   }
4516   if (session->send_rtcp_src) {
4517     gst_element_release_request_pad (session->session, session->send_rtcp_src);
4518     gst_object_unref (session->send_rtcp_src);
4519     session->send_rtcp_src = NULL;
4520   }
4521 }
4522
4523 /* If the requested name is NULL we should create a name with
4524  * the session number assuming we want the lowest posible session
4525  * with a free pad like the template */
4526 static gchar *
4527 gst_rtp_bin_get_free_pad_name (GstElement * element, GstPadTemplate * templ)
4528 {
4529   gboolean name_found = FALSE;
4530   gint session = 0;
4531   GstIterator *pad_it = NULL;
4532   gchar *pad_name = NULL;
4533   GValue data = { 0, };
4534
4535   GST_DEBUG_OBJECT (element, "find a free pad name for template");
4536   while (!name_found) {
4537     gboolean done = FALSE;
4538
4539     g_free (pad_name);
4540     pad_name = g_strdup_printf (templ->name_template, session++);
4541     pad_it = gst_element_iterate_pads (GST_ELEMENT (element));
4542     name_found = TRUE;
4543     while (!done) {
4544       switch (gst_iterator_next (pad_it, &data)) {
4545         case GST_ITERATOR_OK:
4546         {
4547           GstPad *pad;
4548           gchar *name;
4549
4550           pad = g_value_get_object (&data);
4551           name = gst_pad_get_name (pad);
4552
4553           if (strcmp (name, pad_name) == 0) {
4554             done = TRUE;
4555             name_found = FALSE;
4556           }
4557           g_free (name);
4558           g_value_reset (&data);
4559           break;
4560         }
4561         case GST_ITERATOR_ERROR:
4562         case GST_ITERATOR_RESYNC:
4563           /* restart iteration */
4564           done = TRUE;
4565           name_found = FALSE;
4566           session = 0;
4567           break;
4568         case GST_ITERATOR_DONE:
4569           done = TRUE;
4570           break;
4571       }
4572     }
4573     g_value_unset (&data);
4574     gst_iterator_free (pad_it);
4575   }
4576
4577   GST_DEBUG_OBJECT (element, "free pad name found: '%s'", pad_name);
4578   return pad_name;
4579 }
4580
4581 /*
4582  */
4583 static GstPad *
4584 gst_rtp_bin_request_new_pad (GstElement * element,
4585     GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
4586 {
4587   GstRtpBin *rtpbin;
4588   GstElementClass *klass;
4589   GstPad *result;
4590
4591   gchar *pad_name = NULL;
4592
4593   g_return_val_if_fail (templ != NULL, NULL);
4594   g_return_val_if_fail (GST_IS_RTP_BIN (element), NULL);
4595
4596   rtpbin = GST_RTP_BIN (element);
4597   klass = GST_ELEMENT_GET_CLASS (element);
4598
4599   GST_RTP_BIN_LOCK (rtpbin);
4600
4601   if (name == NULL) {
4602     /* use a free pad name */
4603     pad_name = gst_rtp_bin_get_free_pad_name (element, templ);
4604   } else {
4605     /* use the provided name */
4606     pad_name = g_strdup (name);
4607   }
4608
4609   GST_DEBUG_OBJECT (rtpbin, "Trying to request a pad with name %s", pad_name);
4610
4611   /* figure out the template */
4612   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink_%u")) {
4613     result = create_recv_rtp (rtpbin, templ, pad_name);
4614   } else if (templ == gst_element_class_get_pad_template (klass,
4615           "recv_rtcp_sink_%u")) {
4616     result = create_recv_rtcp (rtpbin, templ, pad_name);
4617   } else if (templ == gst_element_class_get_pad_template (klass,
4618           "send_rtp_sink_%u")) {
4619     result = create_send_rtp (rtpbin, templ, pad_name);
4620   } else if (templ == gst_element_class_get_pad_template (klass,
4621           "send_rtcp_src_%u")) {
4622     result = create_send_rtcp (rtpbin, templ, pad_name);
4623   } else
4624     goto wrong_template;
4625
4626   g_free (pad_name);
4627   GST_RTP_BIN_UNLOCK (rtpbin);
4628
4629   return result;
4630
4631   /* ERRORS */
4632 wrong_template:
4633   {
4634     g_free (pad_name);
4635     GST_RTP_BIN_UNLOCK (rtpbin);
4636     g_warning ("rtpbin: this is not our template");
4637     return NULL;
4638   }
4639 }
4640
4641 static void
4642 gst_rtp_bin_release_pad (GstElement * element, GstPad * pad)
4643 {
4644   GstRtpBinSession *session;
4645   GstRtpBin *rtpbin;
4646
4647   g_return_if_fail (GST_IS_GHOST_PAD (pad));
4648   g_return_if_fail (GST_IS_RTP_BIN (element));
4649
4650   rtpbin = GST_RTP_BIN (element);
4651
4652   GST_RTP_BIN_LOCK (rtpbin);
4653   GST_DEBUG_OBJECT (rtpbin, "Trying to release pad %s:%s",
4654       GST_DEBUG_PAD_NAME (pad));
4655
4656   if (!(session = find_session_by_pad (rtpbin, pad)))
4657     goto unknown_pad;
4658
4659   if (session->recv_rtp_sink_ghost == pad) {
4660     remove_recv_rtp (rtpbin, session);
4661   } else if (session->recv_rtcp_sink_ghost == pad) {
4662     remove_recv_rtcp (rtpbin, session);
4663   } else if (session->send_rtp_sink_ghost == pad) {
4664     remove_send_rtp (rtpbin, session);
4665   } else if (session->send_rtcp_src_ghost == pad) {
4666     remove_rtcp (rtpbin, session);
4667   }
4668
4669   /* no more request pads, free the complete session */
4670   if (session->recv_rtp_sink_ghost == NULL
4671       && session->recv_rtcp_sink_ghost == NULL
4672       && session->send_rtp_sink_ghost == NULL
4673       && session->send_rtcp_src_ghost == NULL) {
4674     GST_DEBUG_OBJECT (rtpbin, "no more pads for session %p", session);
4675     rtpbin->sessions = g_slist_remove (rtpbin->sessions, session);
4676     free_session (session, rtpbin);
4677   }
4678   GST_RTP_BIN_UNLOCK (rtpbin);
4679
4680   return;
4681
4682   /* ERROR */
4683 unknown_pad:
4684   {
4685     GST_RTP_BIN_UNLOCK (rtpbin);
4686     g_warning ("rtpbin: %s:%s is not one of our request pads",
4687         GST_DEBUG_PAD_NAME (pad));
4688     return;
4689   }
4690 }