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