gst/rtpmanager/gstrtpbin.c: Use lock to protect variable.
[platform/upstream/gstreamer.git] / gst / rtpmanager / gstrtpbin.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim@fluendo.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  * @short_description: handle media from one RTP bin
23  * @see_also: gstrtpjitterbuffer, gstrtpsession, gstrtpptdemux, gstrtpssrcdemux
24  *
25  * <refsect2>
26  * <para>
27  * RTP bin combines the functions of gstrtpsession, gstrtpssrcdemux, gstrtpjitterbuffer
28  * and gstrtpptdemux in one element. It allows for multiple RTP sessions that will
29  * be synchronized together using RTCP SR packets.
30  * </para>
31  * <para>
32  * gstrtpbin is configured with a number of request pads that define the
33  * functionality that is activated, similar to the gstrtpsession element.
34  * </para>
35  * <para>
36  * To use gstrtpbin as an RTP receiver, request a recv_rtp_sink_%%d pad. The session
37  * number must be specified in the pad name. 
38  * Data received on the recv_rtp_sink_%%d pad will be processed in the gstrtpsession
39  * manager and after being validated forwarded on gstrtpssrcdemuxer element. Each
40  * RTP stream is demuxed based on the SSRC and send to a gstrtpjitterbuffer. After
41  * the packets are released from the jitterbuffer, they will be forwarded to a
42  * gstrtpptdemuxer element. The gstrtpptdemuxer element will demux the packets based
43  * on the payload type and will create a unique pad recv_rtp_src_%%d_%%d_%%d on
44  * gstrtpbin with the session number, SSRC and payload type respectively as the pad
45  * name.
46  * </para>
47  * <para>
48  * To also use gstrtpbin as an RTCP receiver, request a recv_rtcp_sink_%%d pad. The
49  * session number must be specified in the pad name.
50  * </para>
51  * <para>
52  * If you want the session manager to generate and send RTCP packets, request
53  * the send_rtcp_src_%%d pad with the session number in the pad name. Packet pushed
54  * on this pad contain SR/RR RTCP reports that should be sent to all participants
55  * in the session.
56  * </para>
57  * <para>
58  * To use gstrtpbin as a sender, request a send_rtp_sink_%%d pad, which will
59  * automatically create a send_rtp_src_%%d pad. The session number must be specified when
60  * requesting the sink pad. The session manager will modify the
61  * SSRC in the RTP packets to its own SSRC and wil forward the packets on the
62  * send_rtp_src_%%d pad after updating its internal state.
63  * </para>
64  * <para>
65  * The session manager needs the clock-rate of the payload types it is handling
66  * and will signal the GstRtpSession::request-pt-map signal when it needs such a
67  * mapping. One can clear the cached values with the GstRtpSession::clear-pt-map
68  * signal.
69  * </para>
70  * <title>Example pipelines</title>
71  * <para>
72  * <programlisting>
73  * gst-launch udpsrc port=5000 caps="application/x-rtp, ..." ! .recv_rtp_sink_0 \
74  *     gstrtpbin ! rtptheoradepay ! theoradec ! xvimagesink
75  * </programlisting>
76  * Receive RTP data from port 5000 and send to the session 0 in gstrtpbin.
77  * </para>
78  * <para>
79  * <programlisting>
80  * gst-launch gstrtpbin name=rtpbin \
81  *         v4l2src ! ffmpegcolorspace ! ffenc_h263 ! rtph263ppay ! rtpbin.send_rtp_sink_0 \
82  *                   rtpbin.send_rtp_src_0 ! udpsink port=5000                            \
83  *                   rtpbin.send_rtcp_src_0 ! udpsink port=5001 sync=false async=false    \
84  *                   udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0                           \
85  *         audiotestsrc ! amrnbenc ! rtpamrpay ! rtpbin.send_rtp_sink_1                   \
86  *                   rtpbin.send_rtp_src_1 ! udpsink port=5002                            \
87  *                   rtpbin.send_rtcp_src_1 ! udpsink port=5003 sync=false async=false    \
88  *                   udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1
89  * </programlisting>
90  * Encode and payload H263 video captured from a v4l2src. Encode and payload AMR
91  * audio generated from audiotestsrc. The video is sent to session 0 in rtpbin
92  * and the audio is sent to session 1. Video packets are sent on UDP port 5000
93  * and audio packets on port 5002. The video RTCP packets for session 0 are sent
94  * on port 5001 and the audio RTCP packets for session 0 are sent on port 5003.
95  * RTCP packets for session 0 are received on port 5005 and RTCP for session 1
96  * is received on port 5007. Since RTCP packets from the sender should be sent
97  * as soon as possible and do not participate in preroll, sync=false and 
98  * async=false is configured on udpsink
99  * </para>
100  * <para>
101  * <programlisting>
102  *  gst-launch -v gstrtpbin name=rtpbin                                          \
103  *     udpsrc caps="application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)H263-1998" \
104  *             port=5000 ! rtpbin.recv_rtp_sink_0                                \
105  *         rtpbin. ! rtph263pdepay ! ffdec_h263 ! xvimagesink                    \
106  *      udpsrc port=5001 ! rtpbin.recv_rtcp_sink_0                               \
107  *      rtpbin.send_rtcp_src_0 ! udpsink port=5005 sync=false async=false        \
108  *     udpsrc caps="application/x-rtp,media=(string)audio,clock-rate=(int)8000,encoding-name=(string)AMR,encoding-params=(string)1,octet-align=(string)1" \
109  *             port=5002 ! rtpbin.recv_rtp_sink_1                                \
110  *         rtpbin. ! rtpamrdepay ! amrnbdec ! alsasink                           \
111  *      udpsrc port=5003 ! rtpbin.recv_rtcp_sink_1                               \
112  *      rtpbin.send_rtcp_src_1 ! udpsink port=5007 sync=false async=false
113  * </programlisting>
114  * Receive H263 on port 5000, send it through rtpbin in session 0, depayload,
115  * decode and display the video.
116  * Receive AMR on port 5002, send it through rtpbin in session 1, depayload,
117  * decode and play the audio.
118  * Receive server RTCP packets for session 0 on port 5001 and RTCP packets for
119  * session 1 on port 5003. These packets will be used for session management and
120  * synchronisation.
121  * Send RTCP reports for session 0 on port 5005 and RTCP reports for session 1
122  * on port 5007.
123  * </para>
124  * </refsect2>
125  *
126  * Last reviewed on 2007-08-30 (0.10.6)
127  */
128
129 #ifdef HAVE_CONFIG_H
130 #include "config.h"
131 #endif
132 #include <string.h>
133
134 #include <gst/rtp/gstrtpbuffer.h>
135 #include <gst/rtp/gstrtcpbuffer.h>
136
137 #include "gstrtpbin-marshal.h"
138 #include "gstrtpbin.h"
139
140 GST_DEBUG_CATEGORY_STATIC (gst_rtp_bin_debug);
141 #define GST_CAT_DEFAULT gst_rtp_bin_debug
142
143
144 /* elementfactory information */
145 static const GstElementDetails rtpbin_details = GST_ELEMENT_DETAILS ("RTP Bin",
146     "Filter/Network/RTP",
147     "Implement an RTP bin",
148     "Wim Taymans <wim@fluendo.com>");
149
150 /* sink pads */
151 static GstStaticPadTemplate rtpbin_recv_rtp_sink_template =
152 GST_STATIC_PAD_TEMPLATE ("recv_rtp_sink_%d",
153     GST_PAD_SINK,
154     GST_PAD_REQUEST,
155     GST_STATIC_CAPS ("application/x-rtp")
156     );
157
158 static GstStaticPadTemplate rtpbin_recv_rtcp_sink_template =
159 GST_STATIC_PAD_TEMPLATE ("recv_rtcp_sink_%d",
160     GST_PAD_SINK,
161     GST_PAD_REQUEST,
162     GST_STATIC_CAPS ("application/x-rtcp")
163     );
164
165 static GstStaticPadTemplate rtpbin_send_rtp_sink_template =
166 GST_STATIC_PAD_TEMPLATE ("send_rtp_sink_%d",
167     GST_PAD_SINK,
168     GST_PAD_REQUEST,
169     GST_STATIC_CAPS ("application/x-rtp")
170     );
171
172 /* src pads */
173 static GstStaticPadTemplate rtpbin_recv_rtp_src_template =
174 GST_STATIC_PAD_TEMPLATE ("recv_rtp_src_%d_%d_%d",
175     GST_PAD_SRC,
176     GST_PAD_SOMETIMES,
177     GST_STATIC_CAPS ("application/x-rtp")
178     );
179
180 static GstStaticPadTemplate rtpbin_send_rtcp_src_template =
181 GST_STATIC_PAD_TEMPLATE ("send_rtcp_src_%d",
182     GST_PAD_SRC,
183     GST_PAD_REQUEST,
184     GST_STATIC_CAPS ("application/x-rtcp")
185     );
186
187 static GstStaticPadTemplate rtpbin_send_rtp_src_template =
188 GST_STATIC_PAD_TEMPLATE ("send_rtp_src_%d",
189     GST_PAD_SRC,
190     GST_PAD_SOMETIMES,
191     GST_STATIC_CAPS ("application/x-rtp")
192     );
193
194 /* padtemplate for the internal pad */
195 static GstStaticPadTemplate rtpbin_sync_sink_template =
196 GST_STATIC_PAD_TEMPLATE ("sink_%d",
197     GST_PAD_SINK,
198     GST_PAD_SOMETIMES,
199     GST_STATIC_CAPS ("application/x-rtcp")
200     );
201
202 #define GST_RTP_BIN_GET_PRIVATE(obj)  \
203    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTP_BIN, GstRtpBinPrivate))
204
205 #define GST_RTP_BIN_LOCK(bin)   g_mutex_lock ((bin)->priv->bin_lock)
206 #define GST_RTP_BIN_UNLOCK(bin) g_mutex_unlock ((bin)->priv->bin_lock)
207
208 struct _GstRtpBinPrivate
209 {
210   GMutex *bin_lock;
211
212   GstClockTime ntp_ns_base;
213 };
214
215 /* signals and args */
216 enum
217 {
218   SIGNAL_REQUEST_PT_MAP,
219   SIGNAL_CLEAR_PT_MAP,
220
221   SIGNAL_ON_NEW_SSRC,
222   SIGNAL_ON_SSRC_COLLISION,
223   SIGNAL_ON_SSRC_VALIDATED,
224   SIGNAL_ON_BYE_SSRC,
225   SIGNAL_ON_BYE_TIMEOUT,
226   SIGNAL_ON_TIMEOUT,
227   LAST_SIGNAL
228 };
229
230 #define DEFAULT_LATENCY_MS      200
231
232 enum
233 {
234   PROP_0,
235   PROP_LATENCY
236 };
237
238 /* helper objects */
239 typedef struct _GstRtpBinSession GstRtpBinSession;
240 typedef struct _GstRtpBinStream GstRtpBinStream;
241 typedef struct _GstRtpBinClient GstRtpBinClient;
242
243 static guint gst_rtp_bin_signals[LAST_SIGNAL] = { 0 };
244
245 static GstCaps *pt_map_requested (GstElement * element, guint pt,
246     GstRtpBinSession * session);
247
248 static void free_stream (GstRtpBinStream * stream);
249
250 /* Manages the RTP stream for one SSRC.
251  *
252  * We pipe the stream (comming from the SSRC demuxer) into a jitterbuffer.
253  * If we see an SDES RTCP packet that links multiple SSRCs together based on a
254  * common CNAME, we create a GstRtpBinClient structure to group the SSRCs
255  * together (see below).
256  */
257 struct _GstRtpBinStream
258 {
259   /* the SSRC of this stream */
260   guint32 ssrc;
261
262   /* parent bin */
263   GstRtpBin *bin;
264
265   /* the session this SSRC belongs to */
266   GstRtpBinSession *session;
267
268   /* the jitterbuffer of the SSRC */
269   GstElement *buffer;
270
271   /* the PT demuxer of the SSRC */
272   GstElement *demux;
273   gulong demux_newpad_sig;
274   gulong demux_ptreq_sig;
275
276   /* the internal pad we use to get RTCP sync messages */
277   GstPad *sync_pad;
278   gboolean have_sync;
279   guint64 last_unix;
280   guint64 last_extrtptime;
281
282   /* mapping to local RTP and NTP time */
283   guint64 local_rtp;
284   guint64 local_unix;
285   gint64 unix_delta;
286
287   /* for lip-sync */
288   guint64 clock_base;
289   gint clock_rate;
290   gint64 ts_offset;
291   gint64 prev_ts_offset;
292 };
293
294 #define GST_RTP_SESSION_LOCK(sess)   g_mutex_lock ((sess)->lock)
295 #define GST_RTP_SESSION_UNLOCK(sess) g_mutex_unlock ((sess)->lock)
296
297 /* Manages the receiving end of the packets.
298  *
299  * There is one such structure for each RTP session (audio/video/...).
300  * We get the RTP/RTCP packets and stuff them into the session manager. From
301  * there they are pushed into an SSRC demuxer that splits the stream based on
302  * SSRC. Each of the SSRC streams go into their own jitterbuffer (managed with
303  * the GstRtpBinStream above).
304  */
305 struct _GstRtpBinSession
306 {
307   /* session id */
308   gint id;
309   /* the parent bin */
310   GstRtpBin *bin;
311   /* the session element */
312   GstElement *session;
313   /* the SSRC demuxer */
314   GstElement *demux;
315   gulong demux_newpad_sig;
316
317   GMutex *lock;
318
319   /* list of GstRtpBinStream */
320   GSList *streams;
321
322   /* mapping of payload type to caps */
323   GHashTable *ptmap;
324
325   /* the pads of the session */
326   GstPad *recv_rtp_sink;
327   GstPad *recv_rtp_src;
328   GstPad *recv_rtcp_sink;
329   GstPad *sync_src;
330   GstPad *send_rtp_sink;
331   GstPad *send_rtp_src;
332   GstPad *send_rtcp_src;
333 };
334
335 /* Manages the RTP streams that come from one client and should therefore be
336  * synchronized.
337  */
338 struct _GstRtpBinClient
339 {
340   /* the common CNAME for the streams */
341   gchar *cname;
342   guint cname_len;
343
344   /* the streams */
345   guint nstreams;
346   GSList *streams;
347
348   gint64 min_delta;
349 };
350
351 /* find a session with the given id. Must be called with RTP_BIN_LOCK */
352 static GstRtpBinSession *
353 find_session_by_id (GstRtpBin * rtpbin, gint id)
354 {
355   GSList *walk;
356
357   for (walk = rtpbin->sessions; walk; walk = g_slist_next (walk)) {
358     GstRtpBinSession *sess = (GstRtpBinSession *) walk->data;
359
360     if (sess->id == id)
361       return sess;
362   }
363   return NULL;
364 }
365
366 static void
367 on_new_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
368 {
369   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC], 0,
370       sess->id, ssrc);
371 }
372
373 static void
374 on_ssrc_collision (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
375 {
376   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION], 0,
377       sess->id, ssrc);
378 }
379
380 static void
381 on_ssrc_validated (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
382 {
383   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
384       sess->id, ssrc);
385 }
386
387 static void
388 on_bye_ssrc (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
389 {
390   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC], 0,
391       sess->id, ssrc);
392 }
393
394 static void
395 on_bye_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
396 {
397   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT], 0,
398       sess->id, ssrc);
399 }
400
401 static void
402 on_timeout (GstElement * session, guint32 ssrc, GstRtpBinSession * sess)
403 {
404   g_signal_emit (sess->bin, gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT], 0,
405       sess->id, ssrc);
406 }
407
408 /* create a session with the given id.  Must be called with RTP_BIN_LOCK */
409 static GstRtpBinSession *
410 create_session (GstRtpBin * rtpbin, gint id)
411 {
412   GstRtpBinSession *sess;
413   GstElement *session, *demux;
414
415   if (!(session = gst_element_factory_make ("gstrtpsession", NULL)))
416     goto no_session;
417
418   if (!(demux = gst_element_factory_make ("gstrtpssrcdemux", NULL)))
419     goto no_demux;
420
421   sess = g_new0 (GstRtpBinSession, 1);
422   sess->lock = g_mutex_new ();
423   sess->id = id;
424   sess->bin = rtpbin;
425   sess->session = session;
426   sess->demux = demux;
427   sess->ptmap = g_hash_table_new (NULL, NULL);
428   rtpbin->sessions = g_slist_prepend (rtpbin->sessions, sess);
429
430   /* set NTP base or new session */
431   g_object_set (session, "ntp-ns-base", rtpbin->priv->ntp_ns_base, NULL);
432
433   /* provide clock_rate to the session manager when needed */
434   g_signal_connect (session, "request-pt-map",
435       (GCallback) pt_map_requested, sess);
436
437   g_signal_connect (sess->session, "on-new-ssrc",
438       (GCallback) on_new_ssrc, sess);
439   g_signal_connect (sess->session, "on-ssrc-collision",
440       (GCallback) on_ssrc_collision, sess);
441   g_signal_connect (sess->session, "on-ssrc-validated",
442       (GCallback) on_ssrc_validated, sess);
443   g_signal_connect (sess->session, "on-bye-ssrc",
444       (GCallback) on_bye_ssrc, sess);
445   g_signal_connect (sess->session, "on-bye-timeout",
446       (GCallback) on_bye_timeout, sess);
447   g_signal_connect (sess->session, "on-timeout", (GCallback) on_timeout, sess);
448
449   gst_bin_add (GST_BIN_CAST (rtpbin), session);
450   gst_element_set_state (session, GST_STATE_PLAYING);
451   gst_bin_add (GST_BIN_CAST (rtpbin), demux);
452   gst_element_set_state (demux, GST_STATE_PLAYING);
453
454   return sess;
455
456   /* ERRORS */
457 no_session:
458   {
459     g_warning ("gstrtpbin: could not create gstrtpsession element");
460     return NULL;
461   }
462 no_demux:
463   {
464     gst_object_unref (session);
465     g_warning ("gstrtpbin: could not create gstrtpssrcdemux element");
466     return NULL;
467   }
468 }
469
470 static void
471 free_session (GstRtpBinSession * sess)
472 {
473   GstRtpBin *bin;
474
475   bin = sess->bin;
476
477   gst_element_set_state (sess->session, GST_STATE_NULL);
478   gst_element_set_state (sess->demux, GST_STATE_NULL);
479
480   gst_bin_remove (GST_BIN_CAST (bin), sess->session);
481   gst_bin_remove (GST_BIN_CAST (bin), sess->demux);
482
483   g_slist_foreach (sess->streams, (GFunc) free_stream, NULL);
484   g_slist_free (sess->streams);
485
486   g_mutex_free (sess->lock);
487   g_hash_table_destroy (sess->ptmap);
488
489   bin->sessions = g_slist_remove (bin->sessions, sess);
490
491   g_free (sess);
492 }
493
494 #if 0
495 static GstRtpBinStream *
496 find_stream_by_ssrc (GstRtpBinSession * session, guint32 ssrc)
497 {
498   GSList *walk;
499
500   for (walk = session->streams; walk; walk = g_slist_next (walk)) {
501     GstRtpBinStream *stream = (GstRtpBinStream *) walk->data;
502
503     if (stream->ssrc == ssrc)
504       return stream;
505   }
506   return NULL;
507 }
508 #endif
509
510 /* get the payload type caps for the specific payload @pt in @session */
511 static GstCaps *
512 get_pt_map (GstRtpBinSession * session, guint pt)
513 {
514   GstCaps *caps = NULL;
515   GstRtpBin *bin;
516   GValue ret = { 0 };
517   GValue args[3] = { {0}, {0}, {0} };
518
519   GST_DEBUG ("searching pt %d in cache", pt);
520
521   GST_RTP_SESSION_LOCK (session);
522
523   /* first look in the cache */
524   caps = g_hash_table_lookup (session->ptmap, GINT_TO_POINTER (pt));
525   if (caps)
526     goto done;
527
528   bin = session->bin;
529
530   GST_DEBUG ("emiting signal for pt %d in session %d", pt, session->id);
531
532   /* not in cache, send signal to request caps */
533   g_value_init (&args[0], GST_TYPE_ELEMENT);
534   g_value_set_object (&args[0], bin);
535   g_value_init (&args[1], G_TYPE_UINT);
536   g_value_set_uint (&args[1], session->id);
537   g_value_init (&args[2], G_TYPE_UINT);
538   g_value_set_uint (&args[2], pt);
539
540   g_value_init (&ret, GST_TYPE_CAPS);
541   g_value_set_boxed (&ret, NULL);
542
543   g_signal_emitv (args, gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP], 0, &ret);
544
545   caps = (GstCaps *) g_value_get_boxed (&ret);
546   if (!caps)
547     goto no_caps;
548
549   GST_DEBUG ("caching pt %d as %" GST_PTR_FORMAT, pt, caps);
550
551   /* store in cache */
552   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (pt), caps);
553
554 done:
555   GST_RTP_SESSION_UNLOCK (session);
556
557   return caps;
558
559   /* ERRORS */
560 no_caps:
561   {
562     GST_RTP_SESSION_UNLOCK (session);
563     GST_DEBUG ("no pt map could be obtained");
564     return NULL;
565   }
566 }
567
568 static gboolean
569 return_true (gpointer key, gpointer value, gpointer user_data)
570 {
571   return TRUE;
572 }
573
574 static void
575 gst_rtp_bin_clear_pt_map (GstRtpBin * bin)
576 {
577   GSList *walk;
578
579   GST_RTP_BIN_LOCK (bin);
580   GST_DEBUG_OBJECT (bin, "clearing pt map");
581   for (walk = bin->sessions; walk; walk = g_slist_next (walk)) {
582     GstRtpBinSession *session = (GstRtpBinSession *) walk->data;
583
584     GST_RTP_SESSION_LOCK (session);
585 #if 0
586     /* This requires GLib 2.12 */
587     g_hash_table_remove_all (session->ptmap);
588 #else
589     g_hash_table_foreach_remove (session->ptmap, return_true, NULL);
590 #endif
591     GST_RTP_SESSION_UNLOCK (session);
592   }
593   GST_RTP_BIN_UNLOCK (bin);
594 }
595
596 static GstRtpBinClient *
597 get_client (GstRtpBin * bin, guint8 len, guint8 * data, gboolean * created)
598 {
599   GstRtpBinClient *result = NULL;
600   GSList *walk;
601
602   for (walk = bin->clients; walk; walk = g_slist_next (walk)) {
603     GstRtpBinClient *client = (GstRtpBinClient *) walk->data;
604
605     if (len != client->cname_len)
606       continue;
607
608     if (!strncmp ((gchar *) data, client->cname, client->cname_len)) {
609       GST_DEBUG_OBJECT (bin, "found existing client %p with CNAME %s", client,
610           client->cname);
611       result = client;
612       break;
613     }
614   }
615
616   /* nothing found, create one */
617   if (result == NULL) {
618     result = g_new0 (GstRtpBinClient, 1);
619     result->cname = g_strndup ((gchar *) data, len);
620     result->cname_len = len;
621     result->min_delta = G_MAXINT64;
622     bin->clients = g_slist_prepend (bin->clients, result);
623     GST_DEBUG_OBJECT (bin, "created new client %p with CNAME %s", result,
624         result->cname);
625   }
626   return result;
627 }
628
629 static void
630 free_client (GstRtpBinClient * client, GstRtpBin * bin)
631 {
632   bin->clients = g_slist_remove (bin->clients, client);
633   g_free (client->cname);
634   g_free (client);
635 }
636
637 /* associate a stream to the given CNAME. This will make sure all streams for
638  * that CNAME are synchronized together. */
639 static void
640 gst_rtp_bin_associate (GstRtpBin * bin, GstRtpBinStream * stream, guint8 len,
641     guint8 * data)
642 {
643   GstRtpBinClient *client;
644   gboolean created;
645   GSList *walk;
646
647   /* first find or create the CNAME */
648   client = get_client (bin, len, data, &created);
649
650   /* find stream in the client */
651   for (walk = client->streams; walk; walk = g_slist_next (walk)) {
652     GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
653
654     if (ostream == stream)
655       break;
656   }
657   /* not found, add it to the list */
658   if (walk == NULL) {
659     GST_DEBUG_OBJECT (bin,
660         "new association of SSRC %08x with client %p with CNAME %s",
661         stream->ssrc, client, client->cname);
662     client->streams = g_slist_prepend (client->streams, stream);
663     client->nstreams++;
664   } else {
665     GST_DEBUG_OBJECT (bin,
666         "found association of SSRC %08x with client %p with CNAME %s",
667         stream->ssrc, client, client->cname);
668   }
669
670   /* we can only continue if we know the local clock-base and clock-rate */
671   if (stream->clock_base == -1)
672     goto no_clock_base;
673   if (stream->clock_rate <= 0)
674     goto no_clock_rate;
675
676   /* map last RTP time to local timeline using our clock-base */
677   stream->local_rtp = stream->last_extrtptime - stream->clock_base;
678
679   GST_DEBUG_OBJECT (bin,
680       "base %" G_GUINT64_FORMAT ", extrtptime %" G_GUINT64_FORMAT
681       ", local RTP %" G_GUINT64_FORMAT ", clock-rate %d", stream->clock_base,
682       stream->last_extrtptime, stream->local_rtp, stream->clock_rate);
683
684   /* calculate local NTP time in gstreamer timestamp */
685   stream->local_unix =
686       gst_util_uint64_scale_int (stream->local_rtp, GST_SECOND,
687       stream->clock_rate);
688   /* calculate delta between server and receiver */
689   stream->unix_delta = stream->last_unix - stream->local_unix;
690
691   GST_DEBUG_OBJECT (bin,
692       "local UNIX %" G_GUINT64_FORMAT ", remote UNIX %" G_GUINT64_FORMAT
693       ", delta %" G_GINT64_FORMAT, stream->local_unix, stream->last_unix,
694       stream->unix_delta);
695
696   /* recalc inter stream playout offset, but only if there are more than one
697    * stream. */
698   if (client->nstreams > 1) {
699     gint64 min;
700
701     /* calculate the min of all deltas */
702     min = G_MAXINT64;
703     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
704       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
705
706       if (ostream->unix_delta < min)
707         min = ostream->unix_delta;
708     }
709
710     GST_DEBUG_OBJECT (bin, "client %p min delta %" G_GINT64_FORMAT, client,
711         min);
712
713     /* calculate offsets for each stream */
714     for (walk = client->streams; walk; walk = g_slist_next (walk)) {
715       GstRtpBinStream *ostream = (GstRtpBinStream *) walk->data;
716
717       ostream->ts_offset = ostream->unix_delta - min;
718
719       /* delta changed, see how much */
720       if (ostream->prev_ts_offset != ostream->ts_offset) {
721         gint64 diff;
722
723         if (ostream->prev_ts_offset > ostream->ts_offset)
724           diff = ostream->prev_ts_offset - ostream->ts_offset;
725         else
726           diff = ostream->ts_offset - ostream->prev_ts_offset;
727
728         /* only change diff when it changed more than 1 millisecond. This
729          * compensates for rounding errors in NTP to RTP timestamp
730          * conversions */
731         if (diff > GST_MSECOND)
732           g_object_set (ostream->buffer, "ts-offset", ostream->ts_offset, NULL);
733
734         ostream->prev_ts_offset = ostream->ts_offset;
735       }
736       GST_DEBUG_OBJECT (bin, "stream SSRC %08x, delta %" G_GINT64_FORMAT,
737           ostream->ssrc, ostream->ts_offset);
738     }
739   }
740   return;
741
742 no_clock_base:
743   {
744     GST_WARNING_OBJECT (bin, "we have no clock-base");
745     return;
746   }
747 no_clock_rate:
748   {
749     GST_WARNING_OBJECT (bin, "we have no clock-rate");
750     return;
751   }
752 }
753
754 #define GST_RTCP_BUFFER_FOR_PACKETS(b,buffer,packet) \
755   for ((b) = gst_rtcp_buffer_get_first_packet ((buffer), (packet)); (b); \
756           (b) = gst_rtcp_packet_move_to_next ((packet)))
757
758 #define GST_RTCP_SDES_FOR_ITEMS(b,packet) \
759   for ((b) = gst_rtcp_packet_sdes_first_item ((packet)); (b); \
760           (b) = gst_rtcp_packet_sdes_next_item ((packet)))
761
762 #define GST_RTCP_SDES_FOR_ENTRIES(b,packet) \
763   for ((b) = gst_rtcp_packet_sdes_first_entry ((packet)); (b); \
764           (b) = gst_rtcp_packet_sdes_next_entry ((packet)))
765
766 static GstFlowReturn
767 gst_rtp_bin_sync_chain (GstPad * pad, GstBuffer * buffer)
768 {
769   GstFlowReturn ret = GST_FLOW_OK;
770   GstRtpBinStream *stream;
771   GstRtpBin *bin;
772   GstRTCPPacket packet;
773   guint32 ssrc;
774   guint64 ntptime;
775   guint32 rtptime;
776   gboolean have_sr, have_sdes;
777   gboolean more;
778
779   stream = gst_pad_get_element_private (pad);
780   bin = stream->bin;
781
782   GST_DEBUG_OBJECT (bin, "received sync packet");
783
784   if (!gst_rtcp_buffer_validate (buffer))
785     goto invalid_rtcp;
786
787   have_sr = FALSE;
788   have_sdes = FALSE;
789   GST_RTCP_BUFFER_FOR_PACKETS (more, buffer, &packet) {
790     /* first packet must be SR or RR or else the validate would have failed */
791     switch (gst_rtcp_packet_get_type (&packet)) {
792       case GST_RTCP_TYPE_SR:
793         /* only parse first. There is only supposed to be one SR in the packet
794          * but we will deal with malformed packets gracefully */
795         if (have_sr)
796           break;
797         /* get NTP and RTP times */
798         gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, &ntptime, &rtptime,
799             NULL, NULL);
800
801         GST_DEBUG_OBJECT (bin, "received sync packet from SSRC %08x", ssrc);
802         /* ignore SR that is not ours */
803         if (ssrc != stream->ssrc)
804           continue;
805
806         have_sr = TRUE;
807
808         /* store values in the stream */
809         stream->have_sync = TRUE;
810         stream->last_unix = gst_rtcp_ntp_to_unix (ntptime);
811         /* use extended timestamp */
812         gst_rtp_buffer_ext_timestamp (&stream->last_extrtptime, rtptime);
813         break;
814       case GST_RTCP_TYPE_SDES:
815       {
816         gboolean more_items, more_entries;
817
818         /* only deal with first SDES, there is only supposed to be one SDES in
819          * the RTCP packet but we deal with bad packets gracefully. Also bail
820          * out if we have not seen an SR item yet. */
821         if (have_sdes || !have_sr)
822           break;
823
824         GST_RTCP_SDES_FOR_ITEMS (more_items, &packet) {
825           /* skip items that are not about the SSRC of the sender */
826           if (gst_rtcp_packet_sdes_get_ssrc (&packet) != ssrc)
827             continue;
828
829           /* find the CNAME entry */
830           GST_RTCP_SDES_FOR_ENTRIES (more_entries, &packet) {
831             GstRTCPSDESType type;
832             guint8 len;
833             guint8 *data;
834
835             gst_rtcp_packet_sdes_get_entry (&packet, &type, &len, &data);
836
837             if (type == GST_RTCP_SDES_CNAME) {
838               stream->clock_base = GST_BUFFER_OFFSET (buffer);
839               /* associate the stream to CNAME */
840               gst_rtp_bin_associate (bin, stream, len, data);
841             }
842           }
843         }
844         have_sdes = TRUE;
845         break;
846       }
847       default:
848         /* we can ignore these packets */
849         break;
850     }
851   }
852
853   gst_buffer_unref (buffer);
854
855   return ret;
856
857   /* ERRORS */
858 invalid_rtcp:
859   {
860     /* this is fatal and should be filtered earlier */
861     GST_ELEMENT_ERROR (bin, STREAM, DECODE, (NULL),
862         ("invalid RTCP packet received"));
863     gst_buffer_unref (buffer);
864     return GST_FLOW_ERROR;
865   }
866 }
867
868 /* create a new stream with @ssrc in @session. Must be called with
869  * RTP_SESSION_LOCK. */
870 static GstRtpBinStream *
871 create_stream (GstRtpBinSession * session, guint32 ssrc)
872 {
873   GstElement *buffer, *demux;
874   GstRtpBinStream *stream;
875   GstPadTemplate *templ;
876   gchar *padname;
877
878   if (!(buffer = gst_element_factory_make ("gstrtpjitterbuffer", NULL)))
879     goto no_jitterbuffer;
880
881   if (!(demux = gst_element_factory_make ("gstrtpptdemux", NULL)))
882     goto no_demux;
883
884   stream = g_new0 (GstRtpBinStream, 1);
885   stream->ssrc = ssrc;
886   stream->bin = session->bin;
887   stream->session = session;
888   stream->buffer = buffer;
889   stream->demux = demux;
890   stream->last_extrtptime = -1;
891   stream->have_sync = FALSE;
892   session->streams = g_slist_prepend (session->streams, stream);
893
894   /* make an internal sinkpad for RTCP sync packets. Take ownership of the
895    * pad. We will link this pad later. */
896   padname = g_strdup_printf ("sync_%d", ssrc);
897   templ = gst_static_pad_template_get (&rtpbin_sync_sink_template);
898   stream->sync_pad = gst_pad_new_from_template (templ, padname);
899   gst_object_unref (templ);
900   gst_object_ref (stream->sync_pad);
901   gst_object_sink (stream->sync_pad);
902   gst_pad_set_element_private (stream->sync_pad, stream);
903   gst_pad_set_chain_function (stream->sync_pad, gst_rtp_bin_sync_chain);
904   gst_pad_set_active (stream->sync_pad, TRUE);
905
906   /* provide clock_rate to the jitterbuffer when needed */
907   g_signal_connect (buffer, "request-pt-map",
908       (GCallback) pt_map_requested, session);
909
910   /* configure latency */
911   g_object_set (buffer, "latency", session->bin->latency, NULL);
912
913   gst_bin_add (GST_BIN_CAST (session->bin), buffer);
914   gst_element_set_state (buffer, GST_STATE_PLAYING);
915   gst_bin_add (GST_BIN_CAST (session->bin), demux);
916   gst_element_set_state (demux, GST_STATE_PLAYING);
917
918   /* link stuff */
919   gst_element_link (buffer, demux);
920
921   return stream;
922
923   /* ERRORS */
924 no_jitterbuffer:
925   {
926     g_warning ("gstrtpbin: could not create gstrtpjitterbuffer element");
927     return NULL;
928   }
929 no_demux:
930   {
931     gst_object_unref (buffer);
932     g_warning ("gstrtpbin: could not create gstrtpptdemux element");
933     return NULL;
934   }
935 }
936
937 static void
938 free_stream (GstRtpBinStream * stream)
939 {
940   GstRtpBinSession *session;
941
942   session = stream->session;
943
944   gst_element_set_state (stream->buffer, GST_STATE_NULL);
945   gst_element_set_state (stream->demux, GST_STATE_NULL);
946
947   gst_bin_remove (GST_BIN_CAST (session->bin), stream->buffer);
948   gst_bin_remove (GST_BIN_CAST (session->bin), stream->demux);
949
950   gst_object_unref (stream->sync_pad);
951
952   session->streams = g_slist_remove (session->streams, stream);
953
954   g_free (stream);
955 }
956
957 /* GObject vmethods */
958 static void gst_rtp_bin_dispose (GObject * object);
959 static void gst_rtp_bin_finalize (GObject * object);
960 static void gst_rtp_bin_set_property (GObject * object, guint prop_id,
961     const GValue * value, GParamSpec * pspec);
962 static void gst_rtp_bin_get_property (GObject * object, guint prop_id,
963     GValue * value, GParamSpec * pspec);
964
965 /* GstElement vmethods */
966 static GstClock *gst_rtp_bin_provide_clock (GstElement * element);
967 static GstStateChangeReturn gst_rtp_bin_change_state (GstElement * element,
968     GstStateChange transition);
969 static GstPad *gst_rtp_bin_request_new_pad (GstElement * element,
970     GstPadTemplate * templ, const gchar * name);
971 static void gst_rtp_bin_release_pad (GstElement * element, GstPad * pad);
972 static void gst_rtp_bin_clear_pt_map (GstRtpBin * bin);
973
974 GST_BOILERPLATE (GstRtpBin, gst_rtp_bin, GstBin, GST_TYPE_BIN);
975
976 static void
977 gst_rtp_bin_base_init (gpointer klass)
978 {
979   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
980
981   /* sink pads */
982   gst_element_class_add_pad_template (element_class,
983       gst_static_pad_template_get (&rtpbin_recv_rtp_sink_template));
984   gst_element_class_add_pad_template (element_class,
985       gst_static_pad_template_get (&rtpbin_recv_rtcp_sink_template));
986   gst_element_class_add_pad_template (element_class,
987       gst_static_pad_template_get (&rtpbin_send_rtp_sink_template));
988
989   /* src pads */
990   gst_element_class_add_pad_template (element_class,
991       gst_static_pad_template_get (&rtpbin_recv_rtp_src_template));
992   gst_element_class_add_pad_template (element_class,
993       gst_static_pad_template_get (&rtpbin_send_rtcp_src_template));
994   gst_element_class_add_pad_template (element_class,
995       gst_static_pad_template_get (&rtpbin_send_rtp_src_template));
996
997   gst_element_class_set_details (element_class, &rtpbin_details);
998 }
999
1000 static void
1001 gst_rtp_bin_class_init (GstRtpBinClass * klass)
1002 {
1003   GObjectClass *gobject_class;
1004   GstElementClass *gstelement_class;
1005
1006   gobject_class = (GObjectClass *) klass;
1007   gstelement_class = (GstElementClass *) klass;
1008
1009   g_type_class_add_private (klass, sizeof (GstRtpBinPrivate));
1010
1011   gobject_class->dispose = gst_rtp_bin_dispose;
1012   gobject_class->finalize = gst_rtp_bin_finalize;
1013   gobject_class->set_property = gst_rtp_bin_set_property;
1014   gobject_class->get_property = gst_rtp_bin_get_property;
1015
1016   g_object_class_install_property (gobject_class, PROP_LATENCY,
1017       g_param_spec_uint ("latency", "Buffer latency in ms",
1018           "Default amount of ms to buffer in the jitterbuffers", 0,
1019           G_MAXUINT, DEFAULT_LATENCY_MS, G_PARAM_READWRITE));
1020
1021   /**
1022    * GstRtpBin::request-pt-map:
1023    * @rtpbin: the object which received the signal
1024    * @session: the session
1025    * @pt: the pt
1026    *
1027    * Request the payload type as #GstCaps for @pt in @session.
1028    */
1029   gst_rtp_bin_signals[SIGNAL_REQUEST_PT_MAP] =
1030       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
1031       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, request_pt_map),
1032       NULL, NULL, gst_rtp_bin_marshal_BOXED__UINT_UINT, GST_TYPE_CAPS, 2,
1033       G_TYPE_UINT, G_TYPE_UINT);
1034   /**
1035    * GstRtpBin::clear-pt-map:
1036    * @rtpbin: the object which received the signal
1037    *
1038    * Clear all previously cached pt-mapping obtained with
1039    * GstRtpBin::request-pt-map.
1040    */
1041   gst_rtp_bin_signals[SIGNAL_CLEAR_PT_MAP] =
1042       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
1043       G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstRtpBinClass, clear_pt_map),
1044       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
1045
1046   /**
1047    * GstRtpBin::on-new-ssrc:
1048    * @rtpbin: the object which received the signal
1049    * @session: the session
1050    * @ssrc: the SSRC 
1051    *
1052    * Notify of a new SSRC that entered @session.
1053    */
1054   gst_rtp_bin_signals[SIGNAL_ON_NEW_SSRC] =
1055       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
1056       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_new_ssrc),
1057       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1058       G_TYPE_UINT, G_TYPE_UINT);
1059   /**
1060    * GstRtpBin::on-ssrc_collision:
1061    * @rtpbin: the object which received the signal
1062    * @session: the session
1063    * @ssrc: the SSRC 
1064    *
1065    * Notify when we have an SSRC collision
1066    */
1067   gst_rtp_bin_signals[SIGNAL_ON_SSRC_COLLISION] =
1068       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
1069       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_collision),
1070       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1071       G_TYPE_UINT, G_TYPE_UINT);
1072   /**
1073    * GstRtpBin::on-ssrc_validated:
1074    * @rtpbin: the object which received the signal
1075    * @session: the session
1076    * @ssrc: the SSRC 
1077    *
1078    * Notify of a new SSRC that became validated.
1079    */
1080   gst_rtp_bin_signals[SIGNAL_ON_SSRC_VALIDATED] =
1081       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
1082       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_ssrc_validated),
1083       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1084       G_TYPE_UINT, G_TYPE_UINT);
1085
1086   /**
1087    * GstRtpBin::on-bye-ssrc:
1088    * @rtpbin: the object which received the signal
1089    * @session: the session
1090    * @ssrc: the SSRC 
1091    *
1092    * Notify of an SSRC that became inactive because of a BYE packet.
1093    */
1094   gst_rtp_bin_signals[SIGNAL_ON_BYE_SSRC] =
1095       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
1096       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_ssrc),
1097       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1098       G_TYPE_UINT, G_TYPE_UINT);
1099   /**
1100    * GstRtpBin::on-bye-timeout:
1101    * @rtpbin: the object which received the signal
1102    * @session: the session
1103    * @ssrc: the SSRC 
1104    *
1105    * Notify of an SSRC that has timed out because of BYE
1106    */
1107   gst_rtp_bin_signals[SIGNAL_ON_BYE_TIMEOUT] =
1108       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
1109       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_bye_timeout),
1110       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1111       G_TYPE_UINT, G_TYPE_UINT);
1112   /**
1113    * GstRtpBin::on-timeout:
1114    * @rtpbin: the object which received the signal
1115    * @session: the session
1116    * @ssrc: the SSRC 
1117    *
1118    * Notify of an SSRC that has timed out
1119    */
1120   gst_rtp_bin_signals[SIGNAL_ON_TIMEOUT] =
1121       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
1122       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpBinClass, on_timeout),
1123       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT, G_TYPE_NONE, 2,
1124       G_TYPE_UINT, G_TYPE_UINT);
1125
1126   gstelement_class->provide_clock =
1127       GST_DEBUG_FUNCPTR (gst_rtp_bin_provide_clock);
1128   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rtp_bin_change_state);
1129   gstelement_class->request_new_pad =
1130       GST_DEBUG_FUNCPTR (gst_rtp_bin_request_new_pad);
1131   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_rtp_bin_release_pad);
1132
1133   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_bin_clear_pt_map);
1134
1135   GST_DEBUG_CATEGORY_INIT (gst_rtp_bin_debug, "rtpbin", 0, "RTP bin");
1136 }
1137
1138 static void
1139 gst_rtp_bin_init (GstRtpBin * rtpbin, GstRtpBinClass * klass)
1140 {
1141   rtpbin->priv = GST_RTP_BIN_GET_PRIVATE (rtpbin);
1142   rtpbin->priv->bin_lock = g_mutex_new ();
1143   rtpbin->provided_clock = gst_system_clock_obtain ();
1144   rtpbin->latency = DEFAULT_LATENCY_MS;
1145 }
1146
1147 static void
1148 gst_rtp_bin_dispose (GObject * object)
1149 {
1150   GstRtpBin *rtpbin;
1151
1152   rtpbin = GST_RTP_BIN (object);
1153
1154   g_slist_foreach (rtpbin->sessions, (GFunc) free_session, NULL);
1155   g_slist_foreach (rtpbin->clients, (GFunc) free_client, NULL);
1156   g_slist_free (rtpbin->sessions);
1157   rtpbin->sessions = NULL;
1158
1159   G_OBJECT_CLASS (parent_class)->dispose (object);
1160 }
1161
1162 static void
1163 gst_rtp_bin_finalize (GObject * object)
1164 {
1165   GstRtpBin *rtpbin;
1166
1167   rtpbin = GST_RTP_BIN (object);
1168
1169   g_mutex_free (rtpbin->priv->bin_lock);
1170   gst_object_unref (rtpbin->provided_clock);
1171   g_slist_free (rtpbin->sessions);
1172
1173   G_OBJECT_CLASS (parent_class)->finalize (object);
1174 }
1175
1176 static void
1177 gst_rtp_bin_set_property (GObject * object, guint prop_id,
1178     const GValue * value, GParamSpec * pspec)
1179 {
1180   GstRtpBin *rtpbin;
1181
1182   rtpbin = GST_RTP_BIN (object);
1183
1184   switch (prop_id) {
1185     case PROP_LATENCY:
1186       GST_RTP_BIN_LOCK (rtpbin);
1187       rtpbin->latency = g_value_get_uint (value);
1188       GST_RTP_BIN_UNLOCK (rtpbin);
1189       break;
1190     default:
1191       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1192       break;
1193   }
1194 }
1195
1196 static void
1197 gst_rtp_bin_get_property (GObject * object, guint prop_id,
1198     GValue * value, GParamSpec * pspec)
1199 {
1200   GstRtpBin *rtpbin;
1201
1202   rtpbin = GST_RTP_BIN (object);
1203
1204   switch (prop_id) {
1205     case PROP_LATENCY:
1206       GST_RTP_BIN_LOCK (rtpbin);
1207       g_value_set_uint (value, rtpbin->latency);
1208       GST_RTP_BIN_UNLOCK (rtpbin);
1209       break;
1210     default:
1211       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1212       break;
1213   }
1214 }
1215
1216 static GstClock *
1217 gst_rtp_bin_provide_clock (GstElement * element)
1218 {
1219   GstRtpBin *rtpbin;
1220
1221   rtpbin = GST_RTP_BIN (element);
1222
1223   return GST_CLOCK_CAST (gst_object_ref (rtpbin->provided_clock));
1224 }
1225
1226 static void
1227 calc_ntp_ns_base (GstRtpBin * bin)
1228 {
1229   GstClockTime now;
1230   GTimeVal current;
1231   GSList *walk;
1232
1233   /* get the current time and convert it to NTP time in nanoseconds */
1234   g_get_current_time (&current);
1235   now = GST_TIMEVAL_TO_TIME (current);
1236   now += (2208988800LL * GST_SECOND);
1237
1238   GST_RTP_BIN_LOCK (bin);
1239   bin->priv->ntp_ns_base = now;
1240   for (walk = bin->sessions; walk; walk = g_slist_next (walk)) {
1241     GstRtpBinSession *session = (GstRtpBinSession *) walk->data;
1242
1243     g_object_set (session->session, "ntp-ns-base", now, NULL);
1244   }
1245   GST_RTP_BIN_UNLOCK (bin);
1246
1247   return;
1248 }
1249
1250 static GstStateChangeReturn
1251 gst_rtp_bin_change_state (GstElement * element, GstStateChange transition)
1252 {
1253   GstStateChangeReturn res;
1254   GstRtpBin *rtpbin;
1255
1256   rtpbin = GST_RTP_BIN (element);
1257
1258   switch (transition) {
1259     case GST_STATE_CHANGE_NULL_TO_READY:
1260       break;
1261     case GST_STATE_CHANGE_READY_TO_PAUSED:
1262       break;
1263     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1264       calc_ntp_ns_base (rtpbin);
1265       break;
1266     default:
1267       break;
1268   }
1269
1270   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1271
1272   switch (transition) {
1273     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1274       break;
1275     case GST_STATE_CHANGE_PAUSED_TO_READY:
1276       break;
1277     case GST_STATE_CHANGE_READY_TO_NULL:
1278       break;
1279     default:
1280       break;
1281   }
1282   return res;
1283 }
1284
1285 /* a new pad (SSRC) was created in @session */
1286 static void
1287 new_payload_found (GstElement * element, guint pt, GstPad * pad,
1288     GstRtpBinStream * stream)
1289 {
1290   GstRtpBin *rtpbin;
1291   GstElementClass *klass;
1292   GstPadTemplate *templ;
1293   gchar *padname;
1294   GstPad *gpad;
1295
1296   rtpbin = stream->bin;
1297
1298   GST_DEBUG ("new payload pad %d", pt);
1299
1300   /* ghost the pad to the parent */
1301   klass = GST_ELEMENT_GET_CLASS (rtpbin);
1302   templ = gst_element_class_get_pad_template (klass, "recv_rtp_src_%d_%d_%d");
1303   padname = g_strdup_printf ("recv_rtp_src_%d_%u_%d",
1304       stream->session->id, stream->ssrc, pt);
1305   gpad = gst_ghost_pad_new_from_template (padname, pad, templ);
1306   g_free (padname);
1307
1308   gst_pad_set_caps (gpad, GST_PAD_CAPS (pad));
1309   gst_pad_set_active (gpad, TRUE);
1310   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), gpad);
1311 }
1312
1313 static GstCaps *
1314 pt_map_requested (GstElement * element, guint pt, GstRtpBinSession * session)
1315 {
1316   GstRtpBin *rtpbin;
1317   GstCaps *caps;
1318
1319   rtpbin = session->bin;
1320
1321   GST_DEBUG_OBJECT (rtpbin, "payload map requested for pt %d in session %d", pt,
1322       session->id);
1323
1324   caps = get_pt_map (session, pt);
1325   if (!caps)
1326     goto no_caps;
1327
1328   return caps;
1329
1330   /* ERRORS */
1331 no_caps:
1332   {
1333     GST_DEBUG_OBJECT (rtpbin, "could not get caps");
1334     return NULL;
1335   }
1336 }
1337
1338 /* emited when caps changed for the session */
1339 static void
1340 caps_changed (GstPad * pad, GParamSpec * pspec, GstRtpBinSession * session)
1341 {
1342   GstRtpBin *bin;
1343   GstCaps *caps;
1344   gint payload;
1345   const GstStructure *s;
1346
1347   bin = session->bin;
1348
1349   g_object_get (pad, "caps", &caps, NULL);
1350
1351   if (caps == NULL)
1352     return;
1353
1354   GST_DEBUG_OBJECT (bin, "got caps %" GST_PTR_FORMAT, caps);
1355
1356   s = gst_caps_get_structure (caps, 0);
1357
1358   /* get payload, finish when it's not there */
1359   if (!gst_structure_get_int (s, "payload", &payload))
1360     return;
1361
1362   GST_RTP_SESSION_LOCK (session);
1363   GST_DEBUG_OBJECT (bin, "insert caps for payload %d", payload);
1364   g_hash_table_insert (session->ptmap, GINT_TO_POINTER (payload), caps);
1365   GST_RTP_SESSION_UNLOCK (session);
1366 }
1367
1368 /* a new pad (SSRC) was created in @session */
1369 static void
1370 new_ssrc_pad_found (GstElement * element, guint ssrc, GstPad * pad,
1371     GstRtpBinSession * session)
1372 {
1373   GstRtpBinStream *stream;
1374   GstPad *sinkpad, *srcpad;
1375   gchar *padname;
1376   GstCaps *caps;
1377
1378   GST_DEBUG_OBJECT (session->bin, "new SSRC pad %08x", ssrc);
1379
1380   GST_RTP_SESSION_LOCK (session);
1381
1382   /* create new stream */
1383   stream = create_stream (session, ssrc);
1384   if (!stream)
1385     goto no_stream;
1386
1387   /* get the caps of the pad, we need the clock-rate and base_time if any. */
1388   if ((caps = gst_pad_get_caps (pad))) {
1389     const GstStructure *s;
1390     guint val;
1391
1392     GST_DEBUG_OBJECT (session->bin, "pad has caps %" GST_PTR_FORMAT, caps);
1393
1394     s = gst_caps_get_structure (caps, 0);
1395
1396     if (!gst_structure_get_int (s, "clock-rate", &stream->clock_rate))
1397       stream->clock_rate = -1;
1398
1399     if (gst_structure_get_uint (s, "clock-base", &val))
1400       stream->clock_base = val;
1401     else
1402       stream->clock_base = -1;
1403   }
1404
1405   /* get pad and link */
1406   GST_DEBUG_OBJECT (session->bin, "linking jitterbuffer");
1407   sinkpad = gst_element_get_static_pad (stream->buffer, "sink");
1408   gst_pad_link (pad, sinkpad);
1409   gst_object_unref (sinkpad);
1410
1411   /* get the RTCP sync pad */
1412   GST_DEBUG_OBJECT (session->bin, "linking sync pad");
1413   padname = g_strdup_printf ("rtcp_src_%d", ssrc);
1414   srcpad = gst_element_get_pad (element, padname);
1415   g_free (padname);
1416   gst_pad_link (srcpad, stream->sync_pad);
1417   gst_object_unref (srcpad);
1418
1419   /* connect to the new-pad signal of the payload demuxer, this will expose the
1420    * new pad by ghosting it. */
1421   stream->demux_newpad_sig = g_signal_connect (stream->demux,
1422       "new-payload-type", (GCallback) new_payload_found, stream);
1423   /* connect to the request-pt-map signal. This signal will be emited by the
1424    * demuxer so that it can apply a proper caps on the buffers for the
1425    * depayloaders. */
1426   stream->demux_ptreq_sig = g_signal_connect (stream->demux,
1427       "request-pt-map", (GCallback) pt_map_requested, session);
1428
1429   GST_RTP_SESSION_UNLOCK (session);
1430
1431   return;
1432
1433   /* ERRORS */
1434 no_stream:
1435   {
1436     GST_RTP_SESSION_UNLOCK (session);
1437     GST_DEBUG ("could not create stream");
1438     return;
1439   }
1440 }
1441
1442 /* Create a pad for receiving RTP for the session in @name. Must be called with
1443  * RTP_BIN_LOCK.
1444  */
1445 static GstPad *
1446 create_recv_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1447 {
1448   GstPad *result, *sinkdpad;
1449   guint sessid;
1450   GstRtpBinSession *session;
1451   GstPadLinkReturn lres;
1452
1453   /* first get the session number */
1454   if (name == NULL || sscanf (name, "recv_rtp_sink_%d", &sessid) != 1)
1455     goto no_name;
1456
1457   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
1458
1459   /* get or create session */
1460   session = find_session_by_id (rtpbin, sessid);
1461   if (!session) {
1462     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
1463     /* create session now */
1464     session = create_session (rtpbin, sessid);
1465     if (session == NULL)
1466       goto create_error;
1467   }
1468
1469   /* check if pad was requested */
1470   if (session->recv_rtp_sink != NULL)
1471     goto existed;
1472
1473   GST_DEBUG_OBJECT (rtpbin, "getting RTP sink pad");
1474   /* get recv_rtp pad and store */
1475   session->recv_rtp_sink =
1476       gst_element_get_request_pad (session->session, "recv_rtp_sink");
1477   if (session->recv_rtp_sink == NULL)
1478     goto pad_failed;
1479
1480   g_signal_connect (session->recv_rtp_sink, "notify::caps",
1481       (GCallback) caps_changed, session);
1482
1483   GST_DEBUG_OBJECT (rtpbin, "getting RTP src pad");
1484   /* get srcpad, link to SSRCDemux */
1485   session->recv_rtp_src =
1486       gst_element_get_static_pad (session->session, "recv_rtp_src");
1487   if (session->recv_rtp_src == NULL)
1488     goto pad_failed;
1489
1490   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTP sink pad");
1491   sinkdpad = gst_element_get_static_pad (session->demux, "sink");
1492   GST_DEBUG_OBJECT (rtpbin, "linking demuxer RTP sink pad");
1493   lres = gst_pad_link (session->recv_rtp_src, sinkdpad);
1494   gst_object_unref (sinkdpad);
1495   if (lres != GST_PAD_LINK_OK)
1496     goto link_failed;
1497
1498   /* connect to the new-ssrc-pad signal of the SSRC demuxer */
1499   session->demux_newpad_sig = g_signal_connect (session->demux,
1500       "new-ssrc-pad", (GCallback) new_ssrc_pad_found, session);
1501
1502   GST_DEBUG_OBJECT (rtpbin, "ghosting session sink pad");
1503   result =
1504       gst_ghost_pad_new_from_template (name, session->recv_rtp_sink, templ);
1505   gst_pad_set_active (result, TRUE);
1506   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1507
1508   return result;
1509
1510   /* ERRORS */
1511 no_name:
1512   {
1513     g_warning ("gstrtpbin: invalid name given");
1514     return NULL;
1515   }
1516 create_error:
1517   {
1518     /* create_session already warned */
1519     return NULL;
1520   }
1521 existed:
1522   {
1523     g_warning ("gstrtpbin: recv_rtp pad already requested for session %d",
1524         sessid);
1525     return NULL;
1526   }
1527 pad_failed:
1528   {
1529     g_warning ("gstrtpbin: failed to get session pad");
1530     return NULL;
1531   }
1532 link_failed:
1533   {
1534     g_warning ("gstrtpbin: failed to link pads");
1535     return NULL;
1536   }
1537 }
1538
1539 /* Create a pad for receiving RTCP for the session in @name. Must be called with
1540  * RTP_BIN_LOCK.
1541  */
1542 static GstPad *
1543 create_recv_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ,
1544     const gchar * name)
1545 {
1546   GstPad *result;
1547   guint sessid;
1548   GstRtpBinSession *session;
1549   GstPad *sinkdpad;
1550   GstPadLinkReturn lres;
1551
1552   /* first get the session number */
1553   if (name == NULL || sscanf (name, "recv_rtcp_sink_%d", &sessid) != 1)
1554     goto no_name;
1555
1556   GST_DEBUG_OBJECT (rtpbin, "finding session %d", sessid);
1557
1558   /* get or create the session */
1559   session = find_session_by_id (rtpbin, sessid);
1560   if (!session) {
1561     GST_DEBUG_OBJECT (rtpbin, "creating session %d", sessid);
1562     /* create session now */
1563     session = create_session (rtpbin, sessid);
1564     if (session == NULL)
1565       goto create_error;
1566   }
1567
1568   /* check if pad was requested */
1569   if (session->recv_rtcp_sink != NULL)
1570     goto existed;
1571
1572   /* get recv_rtp pad and store */
1573   GST_DEBUG_OBJECT (rtpbin, "getting RTCP sink pad");
1574   session->recv_rtcp_sink =
1575       gst_element_get_request_pad (session->session, "recv_rtcp_sink");
1576   if (session->recv_rtcp_sink == NULL)
1577     goto pad_failed;
1578
1579   /* get srcpad, link to SSRCDemux */
1580   GST_DEBUG_OBJECT (rtpbin, "getting sync src pad");
1581   session->sync_src = gst_element_get_static_pad (session->session, "sync_src");
1582   if (session->sync_src == NULL)
1583     goto pad_failed;
1584
1585   GST_DEBUG_OBJECT (rtpbin, "getting demuxer RTCP sink pad");
1586   sinkdpad = gst_element_get_static_pad (session->demux, "rtcp_sink");
1587   lres = gst_pad_link (session->sync_src, sinkdpad);
1588   gst_object_unref (sinkdpad);
1589   if (lres != GST_PAD_LINK_OK)
1590     goto link_failed;
1591
1592   result =
1593       gst_ghost_pad_new_from_template (name, session->recv_rtcp_sink, templ);
1594   gst_pad_set_active (result, TRUE);
1595   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1596
1597   return result;
1598
1599   /* ERRORS */
1600 no_name:
1601   {
1602     g_warning ("gstrtpbin: invalid name given");
1603     return NULL;
1604   }
1605 create_error:
1606   {
1607     /* create_session already warned */
1608     return NULL;
1609   }
1610 existed:
1611   {
1612     g_warning ("gstrtpbin: recv_rtcp pad already requested for session %d",
1613         sessid);
1614     return NULL;
1615   }
1616 pad_failed:
1617   {
1618     g_warning ("gstrtpbin: failed to get session pad");
1619     return NULL;
1620   }
1621 link_failed:
1622   {
1623     g_warning ("gstrtpbin: failed to link pads");
1624     return NULL;
1625   }
1626 }
1627
1628 /* Create a pad for sending RTP for the session in @name. Must be called with
1629  * RTP_BIN_LOCK.
1630  */
1631 static GstPad *
1632 create_send_rtp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1633 {
1634   GstPad *result, *srcghost;
1635   gchar *gname;
1636   guint sessid;
1637   GstRtpBinSession *session;
1638   GstElementClass *klass;
1639
1640   /* first get the session number */
1641   if (name == NULL || sscanf (name, "send_rtp_sink_%d", &sessid) != 1)
1642     goto no_name;
1643
1644   /* get or create session */
1645   session = find_session_by_id (rtpbin, sessid);
1646   if (!session) {
1647     /* create session now */
1648     session = create_session (rtpbin, sessid);
1649     if (session == NULL)
1650       goto create_error;
1651   }
1652
1653   /* check if pad was requested */
1654   if (session->send_rtp_sink != NULL)
1655     goto existed;
1656
1657   /* get send_rtp pad and store */
1658   session->send_rtp_sink =
1659       gst_element_get_request_pad (session->session, "send_rtp_sink");
1660   if (session->send_rtp_sink == NULL)
1661     goto pad_failed;
1662
1663   result =
1664       gst_ghost_pad_new_from_template (name, session->send_rtp_sink, templ);
1665   gst_pad_set_active (result, TRUE);
1666   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1667
1668   /* get srcpad */
1669   session->send_rtp_src =
1670       gst_element_get_static_pad (session->session, "send_rtp_src");
1671   if (session->send_rtp_src == NULL)
1672     goto no_srcpad;
1673
1674   /* ghost the new source pad */
1675   klass = GST_ELEMENT_GET_CLASS (rtpbin);
1676   gname = g_strdup_printf ("send_rtp_src_%d", sessid);
1677   templ = gst_element_class_get_pad_template (klass, "send_rtp_src_%d");
1678   srcghost =
1679       gst_ghost_pad_new_from_template (gname, session->send_rtp_src, templ);
1680   gst_pad_set_active (srcghost, TRUE);
1681   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), srcghost);
1682   g_free (gname);
1683
1684   return result;
1685
1686   /* ERRORS */
1687 no_name:
1688   {
1689     g_warning ("gstrtpbin: invalid name given");
1690     return NULL;
1691   }
1692 create_error:
1693   {
1694     /* create_session already warned */
1695     return NULL;
1696   }
1697 existed:
1698   {
1699     g_warning ("gstrtpbin: send_rtp pad already requested for session %d",
1700         sessid);
1701     return NULL;
1702   }
1703 pad_failed:
1704   {
1705     g_warning ("gstrtpbin: failed to get session pad for session %d", sessid);
1706     return NULL;
1707   }
1708 no_srcpad:
1709   {
1710     g_warning ("gstrtpbin: failed to get rtp source pad for session %d",
1711         sessid);
1712     return NULL;
1713   }
1714 }
1715
1716 /* Create a pad for sending RTCP for the session in @name. Must be called with
1717  * RTP_BIN_LOCK.
1718  */
1719 static GstPad *
1720 create_rtcp (GstRtpBin * rtpbin, GstPadTemplate * templ, const gchar * name)
1721 {
1722   GstPad *result;
1723   guint sessid;
1724   GstRtpBinSession *session;
1725
1726   /* first get the session number */
1727   if (name == NULL || sscanf (name, "send_rtcp_src_%d", &sessid) != 1)
1728     goto no_name;
1729
1730   /* get or create session */
1731   session = find_session_by_id (rtpbin, sessid);
1732   if (!session)
1733     goto no_session;
1734
1735   /* check if pad was requested */
1736   if (session->send_rtcp_src != NULL)
1737     goto existed;
1738
1739   /* get rtcp_src pad and store */
1740   session->send_rtcp_src =
1741       gst_element_get_request_pad (session->session, "send_rtcp_src");
1742   if (session->send_rtcp_src == NULL)
1743     goto pad_failed;
1744
1745   result =
1746       gst_ghost_pad_new_from_template (name, session->send_rtcp_src, templ);
1747   gst_pad_set_active (result, TRUE);
1748   gst_element_add_pad (GST_ELEMENT_CAST (rtpbin), result);
1749
1750   return result;
1751
1752   /* ERRORS */
1753 no_name:
1754   {
1755     g_warning ("gstrtpbin: invalid name given");
1756     return NULL;
1757   }
1758 no_session:
1759   {
1760     g_warning ("gstrtpbin: session with id %d does not exist", sessid);
1761     return NULL;
1762   }
1763 existed:
1764   {
1765     g_warning ("gstrtpbin: send_rtcp_src pad already requested for session %d",
1766         sessid);
1767     return NULL;
1768   }
1769 pad_failed:
1770   {
1771     g_warning ("gstrtpbin: failed to get rtcp pad for session %d", sessid);
1772     return NULL;
1773   }
1774 }
1775
1776 /* 
1777  */
1778 static GstPad *
1779 gst_rtp_bin_request_new_pad (GstElement * element,
1780     GstPadTemplate * templ, const gchar * name)
1781 {
1782   GstRtpBin *rtpbin;
1783   GstElementClass *klass;
1784   GstPad *result;
1785
1786   g_return_val_if_fail (templ != NULL, NULL);
1787   g_return_val_if_fail (GST_IS_RTP_BIN (element), NULL);
1788
1789   rtpbin = GST_RTP_BIN (element);
1790   klass = GST_ELEMENT_GET_CLASS (element);
1791
1792   GST_RTP_BIN_LOCK (rtpbin);
1793
1794   /* figure out the template */
1795   if (templ == gst_element_class_get_pad_template (klass, "recv_rtp_sink_%d")) {
1796     result = create_recv_rtp (rtpbin, templ, name);
1797   } else if (templ == gst_element_class_get_pad_template (klass,
1798           "recv_rtcp_sink_%d")) {
1799     result = create_recv_rtcp (rtpbin, templ, name);
1800   } else if (templ == gst_element_class_get_pad_template (klass,
1801           "send_rtp_sink_%d")) {
1802     result = create_send_rtp (rtpbin, templ, name);
1803   } else if (templ == gst_element_class_get_pad_template (klass,
1804           "send_rtcp_src_%d")) {
1805     result = create_rtcp (rtpbin, templ, name);
1806   } else
1807     goto wrong_template;
1808
1809   GST_RTP_BIN_UNLOCK (rtpbin);
1810
1811   return result;
1812
1813   /* ERRORS */
1814 wrong_template:
1815   {
1816     GST_RTP_BIN_UNLOCK (rtpbin);
1817     g_warning ("gstrtpbin: this is not our template");
1818     return NULL;
1819   }
1820 }
1821
1822 static void
1823 gst_rtp_bin_release_pad (GstElement * element, GstPad * pad)
1824 {
1825 }