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