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