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