2 * Copyright (C) <2005,2006> Wim Taymans <wim at fluendo dot com>
3 * <2006> Lutz Mueller <lutz at topfrose dot de>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
21 * Unless otherwise indicated, Source Code is licensed under MIT license.
22 * See further explanation attached in License Statement (distributed in the file
25 * Permission is hereby granted, free of charge, to any person obtaining a copy of
26 * this software and associated documentation files (the "Software"), to deal in
27 * the Software without restriction, including without limitation the rights to
28 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
29 * of the Software, and to permit persons to whom the Software is furnished to do
30 * so, subject to the following conditions:
32 * The above copyright notice and this permission notice shall be included in all
33 * copies or substantial portions of the Software.
35 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 * SECTION:element-rtspsrc
46 * Makes a connection to an RTSP server and read the data.
47 * rtspsrc strictly follows RFC 2326 and therefore does not (yet) support
48 * RealMedia/Quicktime/Microsoft extensions.
50 * RTSP supports transport over TCP or UDP in unicast or multicast mode. By
51 * default rtspsrc will negotiate a connection in the following order:
52 * UDP unicast/UDP multicast/TCP. The order cannot be changed but the allowed
53 * protocols can be controlled with the #GstRTSPSrc:protocols property.
55 * rtspsrc currently understands SDP as the format of the session description.
56 * For each stream listed in the SDP a new rtp_stream%d pad will be created
57 * with caps derived from the SDP media description. This is a caps of mime type
58 * "application/x-rtp" that can be connected to any available RTP depayloader
61 * rtspsrc will internally instantiate an RTP session manager element
62 * that will handle the RTCP messages to and from the server, jitter removal,
63 * packet reordering along with providing a clock for the pipeline.
64 * This feature is implemented using the gstrtpbin element.
66 * rtspsrc acts like a live source and will therefore only generate data in the
70 * <title>Example launch line</title>
72 * gst-launch-1.0 rtspsrc location=rtsp://some.server/url ! fakesink
73 * ]| Establish a connection to an RTSP server and send the raw RTP packets to a
77 * Last reviewed on 2006-08-18 (0.10.5)
86 #endif /* HAVE_UNISTD_H */
92 #include <gst/net/gstnet.h>
93 #include <gst/sdp/gstsdpmessage.h>
94 #include <gst/rtp/gstrtppayloads.h>
96 #include "gst/gst-i18n-plugin.h"
98 #include "gstrtspsrc.h"
100 GST_DEBUG_CATEGORY_STATIC (rtspsrc_debug);
101 #define GST_CAT_DEFAULT (rtspsrc_debug)
103 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream_%u",
106 GST_STATIC_CAPS ("application/x-rtp; application/x-rdt"));
108 /* templates used internally */
109 static GstStaticPadTemplate anysrctemplate =
110 GST_STATIC_PAD_TEMPLATE ("internalsrc_%u",
113 GST_STATIC_CAPS_ANY);
115 static GstStaticPadTemplate anysinktemplate =
116 GST_STATIC_PAD_TEMPLATE ("internalsink_%u",
119 GST_STATIC_CAPS_ANY);
123 SIGNAL_HANDLE_REQUEST,
127 enum _GstRtspSrcRtcpSyncMode
134 enum _GstRtspSrcBufferMode
142 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
144 gst_rtsp_src_buffer_mode_get_type (void)
146 static GType buffer_mode_type = 0;
147 static const GEnumValue buffer_modes[] = {
148 {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
149 {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
150 {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
151 {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
155 if (!buffer_mode_type) {
157 g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
159 return buffer_mode_type;
162 #define DEFAULT_LOCATION NULL
163 #define DEFAULT_PROTOCOLS GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
164 #define DEFAULT_DEBUG FALSE
165 #define DEFAULT_RETRY 20
166 #define DEFAULT_TIMEOUT 5000000
167 #define DEFAULT_UDP_BUFFER_SIZE 0x80000
168 #define DEFAULT_TCP_TIMEOUT 20000000
169 #define DEFAULT_LATENCY_MS 2000
170 #define DEFAULT_DROP_ON_LATENCY FALSE
171 #define DEFAULT_CONNECTION_SPEED 0
172 #define DEFAULT_NAT_METHOD GST_RTSP_NAT_DUMMY
173 #define DEFAULT_DO_RTCP TRUE
174 #define DEFAULT_DO_RTSP_KEEP_ALIVE TRUE
175 #define DEFAULT_PROXY NULL
176 #define DEFAULT_RTP_BLOCKSIZE 0
177 #define DEFAULT_USER_ID NULL
178 #define DEFAULT_USER_PW NULL
179 #define DEFAULT_BUFFER_MODE BUFFER_MODE_AUTO
180 #define DEFAULT_PORT_RANGE NULL
181 #define DEFAULT_SHORT_HEADER FALSE
182 #define DEFAULT_PROBATION 2
183 #define DEFAULT_UDP_RECONNECT TRUE
184 #define DEFAULT_MULTICAST_IFACE NULL
185 #define DEFAULT_NTP_SYNC FALSE
186 #define DEFAULT_USE_PIPELINE_CLOCK FALSE
198 PROP_DROP_ON_LATENCY,
199 PROP_CONNECTION_SPEED,
202 PROP_DO_RTSP_KEEP_ALIVE,
211 PROP_UDP_BUFFER_SIZE,
215 PROP_MULTICAST_IFACE,
217 PROP_USE_PIPELINE_CLOCK,
221 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
223 gst_rtsp_nat_method_get_type (void)
225 static GType rtsp_nat_method_type = 0;
226 static const GEnumValue rtsp_nat_method[] = {
227 {GST_RTSP_NAT_NONE, "None", "none"},
228 {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
232 if (!rtsp_nat_method_type) {
233 rtsp_nat_method_type =
234 g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
236 return rtsp_nat_method_type;
239 static void gst_rtspsrc_finalize (GObject * object);
241 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
242 const GValue * value, GParamSpec * pspec);
243 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
244 GValue * value, GParamSpec * pspec);
246 static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
248 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
249 gpointer iface_data);
251 static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
254 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
255 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
257 static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
259 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
260 GstStateChange transition);
261 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
262 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
264 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
265 GstRTSPMessage * response);
267 static void gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask);
268 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
269 GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
271 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
272 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
274 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
275 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
276 gboolean only_close);
278 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
279 const gchar * uri, GError ** error);
280 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
282 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
283 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
284 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
285 GstRTSPStream * stream, GstEvent * event);
286 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
288 /* commands we send to out loop to notify it of events */
289 #define CMD_OPEN (1 << 0)
290 #define CMD_PLAY (1 << 1)
291 #define CMD_PAUSE (1 << 2)
292 #define CMD_CLOSE (1 << 3)
293 #define CMD_WAIT (1 << 4)
294 #define CMD_RECONNECT (1 << 5)
295 #define CMD_LOOP (1 << 6)
297 /* mask for all commands */
298 #define CMD_ALL ((CMD_LOOP << 1) - 1)
300 #define GST_ELEMENT_PROGRESS(el, type, code, text) \
302 gchar *__txt = _gst_element_error_printf text; \
303 gst_element_post_message (GST_ELEMENT_CAST (el), \
304 gst_message_new_progress (GST_OBJECT_CAST (el), \
305 GST_PROGRESS_TYPE_ ##type, code, __txt)); \
309 static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
311 #define gst_rtspsrc_parent_class parent_class
312 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
313 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
316 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
318 GObjectClass *gobject_class;
319 GstElementClass *gstelement_class;
320 GstBinClass *gstbin_class;
322 gobject_class = (GObjectClass *) klass;
323 gstelement_class = (GstElementClass *) klass;
324 gstbin_class = (GstBinClass *) klass;
326 GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
328 gobject_class->set_property = gst_rtspsrc_set_property;
329 gobject_class->get_property = gst_rtspsrc_get_property;
331 gobject_class->finalize = gst_rtspsrc_finalize;
333 g_object_class_install_property (gobject_class, PROP_LOCATION,
334 g_param_spec_string ("location", "RTSP Location",
335 "Location of the RTSP url to read",
336 DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338 g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
339 g_param_spec_flags ("protocols", "Protocols",
340 "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
341 DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
343 g_object_class_install_property (gobject_class, PROP_DEBUG,
344 g_param_spec_boolean ("debug", "Debug",
345 "Dump request and response messages to stdout",
346 DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348 g_object_class_install_property (gobject_class, PROP_RETRY,
349 g_param_spec_uint ("retry", "Retry",
350 "Max number of retries when allocating RTP ports.",
351 0, G_MAXUINT16, DEFAULT_RETRY,
352 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
354 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
355 g_param_spec_uint64 ("timeout", "Timeout",
356 "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
357 0, G_MAXUINT64, DEFAULT_TIMEOUT,
358 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
360 g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
361 g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
362 "Fail after timeout microseconds on TCP connections (0 = disabled)",
363 0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
364 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
366 g_object_class_install_property (gobject_class, PROP_LATENCY,
367 g_param_spec_uint ("latency", "Buffer latency in ms",
368 "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
369 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
371 g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
372 g_param_spec_boolean ("drop-on-latency",
373 "Drop buffers when maximum latency is reached",
374 "Tells the jitterbuffer to never exceed the given latency in size",
375 DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
377 g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
378 g_param_spec_uint64 ("connection-speed", "Connection Speed",
379 "Network connection speed in kbps (0 = unknown)",
380 0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
381 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
383 g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
384 g_param_spec_enum ("nat-method", "NAT Method",
385 "Method to use for traversing firewalls and NAT",
386 GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
387 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
390 * GstRTSPSrc::do-rtcp
392 * Enable RTCP support. Some old server don't like RTCP and then this property
393 * needs to be set to FALSE.
397 g_object_class_install_property (gobject_class, PROP_DO_RTCP,
398 g_param_spec_boolean ("do-rtcp", "Do RTCP",
399 "Send RTCP packets, disable for old incompatible server.",
400 DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
403 * GstRTSPSrc::do-rtsp-keep-alive
405 * Enable RTSP keep laive support. Some old server don't like RTSP
406 * keep alive and then this property needs to be set to FALSE.
410 g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
411 g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
412 "Send RTSP keep alive packets, disable for old incompatible server.",
413 DEFAULT_DO_RTSP_KEEP_ALIVE,
414 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
419 * Set the proxy parameters. This has to be a string of the format
420 * [http://][user:passwd@]host[:port].
424 g_object_class_install_property (gobject_class, PROP_PROXY,
425 g_param_spec_string ("proxy", "Proxy",
426 "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
427 DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
429 * GstRTSPSrc::proxy-id
431 * Sets the proxy URI user id for authentication. If the URI set via the
432 * "proxy" property contains a user-id already, that will take precedence.
436 g_object_class_install_property (gobject_class, PROP_PROXY_ID,
437 g_param_spec_string ("proxy-id", "proxy-id",
438 "HTTP proxy URI user id for authentication", "",
439 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
441 * GstRTSPSrc::proxy-pw
443 * Sets the proxy URI password for authentication. If the URI set via the
444 * "proxy" property contains a password already, that will take precedence.
448 g_object_class_install_property (gobject_class, PROP_PROXY_PW,
449 g_param_spec_string ("proxy-pw", "proxy-pw",
450 "HTTP proxy URI user password for authentication", "",
451 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
454 * GstRTSPSrc::rtp_blocksize
456 * RTP package size to suggest to server.
460 g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
461 g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
462 "RTP package size to suggest to server (0 = disabled)",
463 0, 65536, DEFAULT_RTP_BLOCKSIZE,
464 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
466 g_object_class_install_property (gobject_class,
468 g_param_spec_string ("user-id", "user-id",
469 "RTSP location URI user id for authentication", DEFAULT_USER_ID,
470 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
471 g_object_class_install_property (gobject_class, PROP_USER_PW,
472 g_param_spec_string ("user-pw", "user-pw",
473 "RTSP location URI user password for authentication", DEFAULT_USER_PW,
474 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
477 * GstRTSPSrc::buffer-mode:
479 * Control the buffering and timestamping mode used by the jitterbuffer.
483 g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
484 g_param_spec_enum ("buffer-mode", "Buffer Mode",
485 "Control the buffering algorithm in use",
486 GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
487 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
490 * GstRTSPSrc::port-range:
492 * Configure the client port numbers that can be used to recieve RTP and
497 g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
498 g_param_spec_string ("port-range", "Port range",
499 "Client port range that can be used to receive RTP and RTCP data, "
500 "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
501 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
504 * GstRTSPSrc::udp-buffer-size:
506 * Size of the kernel UDP receive buffer in bytes.
510 g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
511 g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
512 "Size of the kernel UDP receive buffer in bytes, 0=default",
513 0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
514 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
517 * GstRTSPSrc::short-header:
519 * Only send the basic RTSP headers for broken encoders.
523 g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
524 g_param_spec_boolean ("short-header", "Short Header",
525 "Only send the basic RTSP headers for broken encoders",
526 DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
528 g_object_class_install_property (gobject_class, PROP_PROBATION,
529 g_param_spec_uint ("probation", "Number of probations",
530 "Consecutive packet sequence numbers to accept the source",
531 0, G_MAXUINT, DEFAULT_PROBATION,
532 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
534 g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
535 g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
536 "Reconnect to the server if RTSP connection is closed when doing UDP",
537 DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
539 g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
540 g_param_spec_string ("multicast-iface", "Multicast Interface",
541 "The network interface on which to join the multicast group",
542 DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
544 g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
545 g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
546 "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
547 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
549 g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
550 g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
551 "Use the pipeline running-time to set the NTP time in the RTCP SR messages",
552 DEFAULT_USE_PIPELINE_CLOCK,
553 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
556 * GstRTSPSrc::handle-request:
557 * @rtspsrc: a #GstRTSPSrc
558 * @request: a #GstRTSPMessage
559 * @response: a #GstRTSPMessage
561 * Handle a server request in @request and prepare @response.
563 * This signal is called from the streaming thread, you should therefore not
564 * do any state changes on @rtspsrc because this might deadlock. If you want
565 * to modify the state as a result of this signal, post a
566 * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
571 gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST] =
572 g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
573 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
574 G_TYPE_POINTER, G_TYPE_POINTER);
576 gstelement_class->send_event = gst_rtspsrc_send_event;
577 gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
578 gstelement_class->change_state = gst_rtspsrc_change_state;
580 gst_element_class_add_pad_template (gstelement_class,
581 gst_static_pad_template_get (&rtptemplate));
583 gst_element_class_set_static_metadata (gstelement_class,
584 "RTSP packet receiver", "Source/Network",
585 "Receive data over the network via RTSP (RFC 2326)",
586 "Wim Taymans <wim@fluendo.com>, "
587 "Thijs Vermeir <thijs.vermeir@barco.com>, "
588 "Lutz Mueller <lutz@topfrose.de>");
590 gstbin_class->handle_message = gst_rtspsrc_handle_message;
592 gst_rtsp_ext_list_init ();
597 gst_rtspsrc_init (GstRTSPSrc * src)
599 src->conninfo.location = g_strdup (DEFAULT_LOCATION);
600 src->protocols = DEFAULT_PROTOCOLS;
601 src->debug = DEFAULT_DEBUG;
602 src->retry = DEFAULT_RETRY;
603 src->udp_timeout = DEFAULT_TIMEOUT;
604 gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
605 src->latency = DEFAULT_LATENCY_MS;
606 src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
607 src->connection_speed = DEFAULT_CONNECTION_SPEED;
608 src->nat_method = DEFAULT_NAT_METHOD;
609 src->do_rtcp = DEFAULT_DO_RTCP;
610 src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
611 gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
612 src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
613 src->user_id = g_strdup (DEFAULT_USER_ID);
614 src->user_pw = g_strdup (DEFAULT_USER_PW);
615 src->buffer_mode = DEFAULT_BUFFER_MODE;
616 src->client_port_range.min = 0;
617 src->client_port_range.max = 0;
618 src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
619 src->short_header = DEFAULT_SHORT_HEADER;
620 src->probation = DEFAULT_PROBATION;
621 src->udp_reconnect = DEFAULT_UDP_RECONNECT;
622 src->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
623 src->ntp_sync = DEFAULT_NTP_SYNC;
624 src->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
626 /* get a list of all extensions */
627 src->extensions = gst_rtsp_ext_list_get ();
629 /* connect to send signal */
630 gst_rtsp_ext_list_connect (src->extensions, "send",
631 (GCallback) gst_rtspsrc_send_cb, src);
633 /* protects the streaming thread in interleaved mode or the polling
634 * thread in UDP mode. */
635 g_rec_mutex_init (&src->stream_rec_lock);
637 /* protects our state changes from multiple invocations */
638 g_rec_mutex_init (&src->state_rec_lock);
640 src->state = GST_RTSP_STATE_INVALID;
642 GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
646 gst_rtspsrc_finalize (GObject * object)
650 rtspsrc = GST_RTSPSRC (object);
652 gst_rtsp_ext_list_free (rtspsrc->extensions);
653 g_free (rtspsrc->conninfo.location);
654 gst_rtsp_url_free (rtspsrc->conninfo.url);
655 g_free (rtspsrc->conninfo.url_str);
656 g_free (rtspsrc->user_id);
657 g_free (rtspsrc->user_pw);
658 g_free (rtspsrc->multi_iface);
661 gst_sdp_message_free (rtspsrc->sdp);
664 if (rtspsrc->provided_clock)
665 gst_object_unref (rtspsrc->provided_clock);
668 g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
669 g_rec_mutex_clear (&rtspsrc->state_rec_lock);
671 G_OBJECT_CLASS (parent_class)->finalize (object);
675 gst_rtspsrc_provide_clock (GstElement * element)
677 GstRTSPSrc *src = GST_RTSPSRC (element);
680 if ((clock = src->provided_clock) != NULL)
681 gst_object_ref (clock);
686 /* a proxy string of the format [user:passwd@]host[:port] */
688 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
692 g_free (rtsp->proxy_user);
693 rtsp->proxy_user = NULL;
694 g_free (rtsp->proxy_passwd);
695 rtsp->proxy_passwd = NULL;
696 g_free (rtsp->proxy_host);
697 rtsp->proxy_host = NULL;
698 rtsp->proxy_port = 0;
705 /* we allow http:// in front but ignore it */
706 if (g_str_has_prefix (p, "http://"))
709 at = strchr (p, '@');
711 /* look for user:passwd */
712 col = strchr (proxy, ':');
713 if (col == NULL || col > at)
716 rtsp->proxy_user = g_strndup (p, col - p);
718 rtsp->proxy_passwd = g_strndup (col, at - col);
723 if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
724 rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
725 if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
726 rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
727 if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
728 GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
729 GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
732 col = strchr (p, ':');
735 /* everything before the colon is the hostname */
736 rtsp->proxy_host = g_strndup (p, col - p);
738 rtsp->proxy_port = strtoul (p, (char **) &p, 10);
740 rtsp->proxy_host = g_strdup (p);
741 rtsp->proxy_port = 8080;
747 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
749 rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
750 rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
753 rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
755 rtspsrc->ptcp_timeout = NULL;
759 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
764 rtspsrc = GST_RTSPSRC (object);
768 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
769 g_value_get_string (value), NULL);
772 rtspsrc->protocols = g_value_get_flags (value);
775 rtspsrc->debug = g_value_get_boolean (value);
778 rtspsrc->retry = g_value_get_uint (value);
781 rtspsrc->udp_timeout = g_value_get_uint64 (value);
783 case PROP_TCP_TIMEOUT:
784 gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
787 rtspsrc->latency = g_value_get_uint (value);
789 case PROP_DROP_ON_LATENCY:
790 rtspsrc->drop_on_latency = g_value_get_boolean (value);
792 case PROP_CONNECTION_SPEED:
793 rtspsrc->connection_speed = g_value_get_uint64 (value);
795 case PROP_NAT_METHOD:
796 rtspsrc->nat_method = g_value_get_enum (value);
799 rtspsrc->do_rtcp = g_value_get_boolean (value);
801 case PROP_DO_RTSP_KEEP_ALIVE:
802 rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
805 gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
808 if (rtspsrc->prop_proxy_id)
809 g_free (rtspsrc->prop_proxy_id);
810 rtspsrc->prop_proxy_id = g_value_dup_string (value);
813 if (rtspsrc->prop_proxy_pw)
814 g_free (rtspsrc->prop_proxy_pw);
815 rtspsrc->prop_proxy_pw = g_value_dup_string (value);
817 case PROP_RTP_BLOCKSIZE:
818 rtspsrc->rtp_blocksize = g_value_get_uint (value);
821 if (rtspsrc->user_id)
822 g_free (rtspsrc->user_id);
823 rtspsrc->user_id = g_value_dup_string (value);
826 if (rtspsrc->user_pw)
827 g_free (rtspsrc->user_pw);
828 rtspsrc->user_pw = g_value_dup_string (value);
830 case PROP_BUFFER_MODE:
831 rtspsrc->buffer_mode = g_value_get_enum (value);
833 case PROP_PORT_RANGE:
837 str = g_value_get_string (value);
839 sscanf (str, "%u-%u",
840 &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
842 rtspsrc->client_port_range.min = 0;
843 rtspsrc->client_port_range.max = 0;
847 case PROP_UDP_BUFFER_SIZE:
848 rtspsrc->udp_buffer_size = g_value_get_int (value);
850 case PROP_SHORT_HEADER:
851 rtspsrc->short_header = g_value_get_boolean (value);
854 rtspsrc->probation = g_value_get_uint (value);
856 case PROP_UDP_RECONNECT:
857 rtspsrc->udp_reconnect = g_value_get_boolean (value);
859 case PROP_MULTICAST_IFACE:
860 g_free (rtspsrc->multi_iface);
862 if (g_value_get_string (value) == NULL)
863 rtspsrc->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
865 rtspsrc->multi_iface = g_value_dup_string (value);
868 rtspsrc->ntp_sync = g_value_get_boolean (value);
870 case PROP_USE_PIPELINE_CLOCK:
871 rtspsrc->use_pipeline_clock = g_value_get_boolean (value);
874 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
880 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
885 rtspsrc = GST_RTSPSRC (object);
889 g_value_set_string (value, rtspsrc->conninfo.location);
892 g_value_set_flags (value, rtspsrc->protocols);
895 g_value_set_boolean (value, rtspsrc->debug);
898 g_value_set_uint (value, rtspsrc->retry);
901 g_value_set_uint64 (value, rtspsrc->udp_timeout);
903 case PROP_TCP_TIMEOUT:
907 timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
908 rtspsrc->tcp_timeout.tv_usec;
909 g_value_set_uint64 (value, timeout);
913 g_value_set_uint (value, rtspsrc->latency);
915 case PROP_DROP_ON_LATENCY:
916 g_value_set_boolean (value, rtspsrc->drop_on_latency);
918 case PROP_CONNECTION_SPEED:
919 g_value_set_uint64 (value, rtspsrc->connection_speed);
921 case PROP_NAT_METHOD:
922 g_value_set_enum (value, rtspsrc->nat_method);
925 g_value_set_boolean (value, rtspsrc->do_rtcp);
927 case PROP_DO_RTSP_KEEP_ALIVE:
928 g_value_set_boolean (value, rtspsrc->do_rtsp_keep_alive);
934 if (rtspsrc->proxy_host) {
936 g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
940 g_value_take_string (value, str);
944 g_value_set_string (value, rtspsrc->prop_proxy_id);
947 g_value_set_string (value, rtspsrc->prop_proxy_pw);
949 case PROP_RTP_BLOCKSIZE:
950 g_value_set_uint (value, rtspsrc->rtp_blocksize);
953 g_value_set_string (value, rtspsrc->user_id);
956 g_value_set_string (value, rtspsrc->user_pw);
958 case PROP_BUFFER_MODE:
959 g_value_set_enum (value, rtspsrc->buffer_mode);
961 case PROP_PORT_RANGE:
965 if (rtspsrc->client_port_range.min != 0) {
966 str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
967 rtspsrc->client_port_range.max);
971 g_value_take_string (value, str);
974 case PROP_UDP_BUFFER_SIZE:
975 g_value_set_int (value, rtspsrc->udp_buffer_size);
977 case PROP_SHORT_HEADER:
978 g_value_set_boolean (value, rtspsrc->short_header);
981 g_value_set_uint (value, rtspsrc->probation);
983 case PROP_UDP_RECONNECT:
984 g_value_set_boolean (value, rtspsrc->udp_reconnect);
986 case PROP_MULTICAST_IFACE:
987 g_value_set_string (value, rtspsrc->multi_iface);
990 g_value_set_boolean (value, rtspsrc->ntp_sync);
992 case PROP_USE_PIPELINE_CLOCK:
993 g_value_set_boolean (value, rtspsrc->use_pipeline_clock);
996 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1002 find_stream_by_id (GstRTSPStream * stream, gint * id)
1004 if (stream->id == *id)
1011 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
1013 if (stream->channel[0] == *channel || stream->channel[1] == *channel)
1020 find_stream_by_pt (GstRTSPStream * stream, gint * pt)
1022 if (stream->pt == *pt)
1029 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
1031 GstElement *src = (GstElement *) a;
1033 if (stream->udpsrc[0] == src)
1035 if (stream->udpsrc[1] == src)
1042 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
1044 /* check qualified setup_url */
1045 if (!strcmp (stream->conninfo.location, (gchar *) a))
1047 /* check original control_url */
1048 if (!strcmp (stream->control_url, (gchar *) a))
1051 /* check if qualified setup_url ends with string */
1052 if (g_str_has_suffix (stream->control_url, (gchar *) a))
1058 static GstRTSPStream *
1059 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
1063 /* find and get stream */
1064 if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
1065 return (GstRTSPStream *) lstream->data;
1070 static const GstSDPBandwidth *
1071 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1072 const GstSDPMedia * media, const gchar * type)
1076 /* first look in the media specific section */
1077 len = gst_sdp_media_bandwidths_len (media);
1078 for (i = 0; i < len; i++) {
1079 const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
1081 if (strcmp (bw->bwtype, type) == 0)
1084 /* then look in the message specific section */
1085 len = gst_sdp_message_bandwidths_len (sdp);
1086 for (i = 0; i < len; i++) {
1087 const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
1089 if (strcmp (bw->bwtype, type) == 0)
1096 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1097 const GstSDPMedia * media, GstRTSPStream * stream)
1099 const GstSDPBandwidth *bw;
1101 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
1102 stream->as_bandwidth = bw->bandwidth;
1104 stream->as_bandwidth = -1;
1106 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
1107 stream->rr_bandwidth = bw->bandwidth;
1109 stream->rr_bandwidth = -1;
1111 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
1112 stream->rs_bandwidth = bw->bandwidth;
1114 stream->rs_bandwidth = -1;
1118 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
1119 const GstSDPConnection * conn)
1121 if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
1124 if (conn->addrtype == NULL)
1127 /* check for IPV6 */
1128 if (strcmp (conn->addrtype, "IP4") == 0)
1129 stream->is_ipv6 = FALSE;
1130 else if (strcmp (conn->addrtype, "IP6") == 0)
1131 stream->is_ipv6 = TRUE;
1136 g_free (stream->destination);
1137 stream->destination = g_strdup (conn->address);
1139 /* check for multicast */
1140 stream->is_multicast =
1141 gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
1143 stream->ttl = conn->ttl;
1146 /* Go over the connections for a stream.
1147 * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
1149 * - If we are dealing with a localhost address, we disable multicast
1152 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
1153 const GstSDPMedia * media, GstRTSPStream * stream)
1155 const GstSDPConnection *conn;
1158 /* first look in the media specific section */
1159 len = gst_sdp_media_connections_len (media);
1160 for (i = 0; i < len; i++) {
1161 conn = gst_sdp_media_get_connection (media, i);
1163 gst_rtspsrc_do_stream_connection (src, stream, conn);
1165 /* then look in the message specific section */
1166 if ((conn = gst_sdp_message_get_connection (sdp))) {
1167 gst_rtspsrc_do_stream_connection (src, stream, conn);
1171 static GstRTSPStream *
1172 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
1174 GstRTSPStream *stream;
1175 const gchar *control_url;
1176 const gchar *payload;
1177 const GstSDPMedia *media;
1179 /* get media, should not return NULL */
1180 media = gst_sdp_message_get_media (sdp, idx);
1184 stream = g_new0 (GstRTSPStream, 1);
1185 stream->parent = src;
1186 /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1188 stream->last_ret = GST_FLOW_NOT_LINKED;
1189 stream->added = FALSE;
1190 stream->disabled = FALSE;
1191 stream->id = src->numstreams++;
1192 stream->eos = FALSE;
1193 stream->discont = TRUE;
1194 stream->seqbase = -1;
1195 stream->timebase = -1;
1197 /* collect bandwidth information for this steam. FIXME, configure in the RTP
1198 * session manager to scale RTCP. */
1199 gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1201 /* collect connection info */
1202 gst_rtspsrc_collect_connections (src, sdp, media, stream);
1204 /* we must have a payload. No payload means we cannot create caps */
1205 /* FIXME, handle multiple formats. The problem here is that we just want to
1206 * take the first available format that we can handle but in order to do that
1207 * we need to scan for depayloader plugins. Scanning for payloader plugins is
1208 * also suboptimal because the user maybe just wants to save the raw stream
1209 * and then we don't care. */
1210 if ((payload = gst_sdp_media_get_format (media, 0))) {
1211 stream->pt = atoi (payload);
1213 stream->caps = gst_rtspsrc_media_to_caps (stream->pt, media);
1215 GST_DEBUG ("mapping sdp session level attributes to caps");
1216 gst_rtspsrc_sdp_attributes_to_caps (sdp->attributes, stream->caps);
1217 GST_DEBUG ("mapping sdp media level attributes to caps");
1218 gst_rtspsrc_sdp_attributes_to_caps (media->attributes, stream->caps);
1220 if (stream->pt >= 96) {
1221 /* If we have a dynamic payload type, see if we have a stream with the
1222 * same payload number. If there is one, they are part of the same
1223 * container and we only need to add one pad. */
1224 if (find_stream (src, &stream->pt, (gpointer) find_stream_by_pt)) {
1225 stream->container = TRUE;
1226 GST_DEBUG ("found another stream with pt %d, marking as container",
1231 /* collect port number */
1232 stream->port = gst_sdp_media_get_port (media);
1234 /* get control url to construct the setup url. The setup url is used to
1235 * configure the transport of the stream and is used to identity the stream in
1236 * the RTP-Info header field returned from PLAY. */
1237 control_url = gst_sdp_media_get_attribute_val (media, "control");
1238 if (control_url == NULL)
1239 control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1241 GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1242 GST_DEBUG_OBJECT (src, " pt: %d", stream->pt);
1243 GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1244 GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1245 GST_DEBUG_OBJECT (src, " caps: %" GST_PTR_FORMAT, stream->caps);
1246 GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1248 if (control_url != NULL) {
1249 stream->control_url = g_strdup (control_url);
1250 /* Build a fully qualified url using the content_base if any or by prefixing
1251 * the original request.
1252 * If the control_url starts with a '/' or a non rtsp: protocol we will most
1253 * likely build a URL that the server will fail to understand, this is ok,
1254 * we will fail then. */
1255 if (g_str_has_prefix (control_url, "rtsp://"))
1256 stream->conninfo.location = g_strdup (control_url);
1261 if (g_strcmp0 (control_url, "*") == 0)
1265 base = src->control;
1266 else if (src->content_base)
1267 base = src->content_base;
1268 else if (src->conninfo.url_str)
1269 base = src->conninfo.url_str;
1273 /* check if the base ends or control starts with / */
1274 has_slash = g_str_has_prefix (control_url, "/");
1275 has_slash = has_slash || g_str_has_suffix (base, "/");
1277 /* concatenate the two strings, insert / when not present */
1278 stream->conninfo.location =
1279 g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1282 GST_DEBUG_OBJECT (src, " setup: %s",
1283 GST_STR_NULL (stream->conninfo.location));
1285 /* we keep track of all streams */
1286 src->streams = g_list_append (src->streams, stream);
1294 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1298 GST_DEBUG_OBJECT (src, "free stream %p", stream);
1301 gst_caps_unref (stream->caps);
1303 g_free (stream->destination);
1304 g_free (stream->control_url);
1305 g_free (stream->conninfo.location);
1307 for (i = 0; i < 2; i++) {
1308 if (stream->udpsrc[i]) {
1309 gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1310 gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1311 gst_object_unref (stream->udpsrc[i]);
1312 stream->udpsrc[i] = NULL;
1314 if (stream->channelpad[i]) {
1315 gst_object_unref (stream->channelpad[i]);
1316 stream->channelpad[i] = NULL;
1318 if (stream->udpsink[i]) {
1319 gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1320 gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1321 gst_object_unref (stream->udpsink[i]);
1322 stream->udpsink[i] = NULL;
1325 if (stream->fakesrc) {
1326 gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1327 gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1328 gst_object_unref (stream->fakesrc);
1329 stream->fakesrc = NULL;
1331 if (stream->srcpad) {
1332 gst_pad_set_active (stream->srcpad, FALSE);
1333 if (stream->added) {
1334 gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1335 stream->added = FALSE;
1337 stream->srcpad = NULL;
1339 if (stream->rtcppad) {
1340 gst_object_unref (stream->rtcppad);
1341 stream->rtcppad = NULL;
1343 if (stream->session) {
1344 g_object_unref (stream->session);
1345 stream->session = NULL;
1351 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1355 GST_DEBUG_OBJECT (src, "cleanup");
1357 for (walk = src->streams; walk; walk = g_list_next (walk)) {
1358 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1360 gst_rtspsrc_stream_free (src, stream);
1362 g_list_free (src->streams);
1363 src->streams = NULL;
1365 if (src->manager_sig_id) {
1366 g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1367 src->manager_sig_id = 0;
1369 gst_element_set_state (src->manager, GST_STATE_NULL);
1370 gst_bin_remove (GST_BIN_CAST (src), src->manager);
1371 src->manager = NULL;
1373 src->numstreams = 0;
1375 gst_structure_free (src->props);
1378 g_free (src->content_base);
1379 src->content_base = NULL;
1381 g_free (src->control);
1382 src->control = NULL;
1385 gst_rtsp_range_free (src->range);
1388 /* don't clear the SDP when it was used in the url */
1389 if (src->sdp && !src->from_sdp) {
1390 gst_sdp_message_free (src->sdp);
1393 if (src->start_segment) {
1394 gst_event_unref (src->start_segment);
1395 src->start_segment = NULL;
1397 if (src->provided_clock) {
1398 gst_object_unref (src->provided_clock);
1399 src->provided_clock = NULL;
1403 #define PARSE_INT(p, del, res) \
1406 p = strstr (p, del); \
1416 #define PARSE_STRING(p, del, res) \
1419 p = strstr (p, del); \
1431 #define SKIP_SPACES(p) \
1432 while (*p && g_ascii_isspace (*p)) \
1437 * <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1440 gst_rtspsrc_parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
1441 gint * rate, gchar ** params)
1445 p = (gchar *) rtpmap;
1447 PARSE_INT (p, " ", *payload);
1455 PARSE_STRING (p, "/", *name);
1456 if (*name == NULL) {
1457 GST_DEBUG ("no rate, name %s", p);
1458 /* no rate, assume -1 then, this is not supposed to happen but RealMedia
1459 * streams seem to omit the rate. */
1466 p = strstr (p, "/");
1484 * Mapping SDP attributes to caps
1486 * prepend 'a-' to IANA registered sdp attributes names
1487 * (ie: not prefixed with 'x-') in order to avoid
1488 * collision with gstreamer standard caps properties names
1491 gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
1493 if (attributes->len > 0) {
1497 s = gst_caps_get_structure (caps, 0);
1499 for (i = 0; i < attributes->len; i++) {
1500 GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
1501 gchar *tofree, *key;
1505 /* skip some of the attribute we already handle */
1506 if (!strcmp (key, "fmtp"))
1508 if (!strcmp (key, "rtpmap"))
1510 if (!strcmp (key, "control"))
1512 if (!strcmp (key, "range"))
1515 /* string must be valid UTF8 */
1516 if (!g_utf8_validate (attr->value, -1, NULL))
1519 if (!g_str_has_prefix (key, "x-"))
1520 tofree = key = g_strdup_printf ("a-%s", key);
1524 GST_DEBUG ("adding caps: %s=%s", key, attr->value);
1525 gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
1532 * Mapping of caps to and from SDP fields:
1534 * m=<media> <UDP port> RTP/AVP <payload>
1535 * a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1536 * a=fmtp:<payload> <param>[=<value>];...
1539 gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
1542 const gchar *rtpmap;
1546 gchar *params = NULL;
1552 /* get and parse rtpmap */
1553 if ((rtpmap = gst_sdp_media_get_attribute_val (media, "rtpmap"))) {
1554 ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, ¶ms);
1556 if (payload != pt) {
1557 /* we ignore the rtpmap if the payload type is different. */
1558 g_warning ("rtpmap of wrong payload type, ignoring");
1564 /* if we failed to parse the rtpmap for a dynamic payload type, we have an
1568 /* else we can ignore */
1569 g_warning ("error parsing rtpmap, ignoring");
1572 /* dynamic payloads need rtpmap or we fail */
1576 /* check if we have a rate, if not, we need to look up the rate from the
1577 * default rates based on the payload types. */
1579 const GstRTPPayloadInfo *info;
1581 if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
1582 /* dynamic types, use media and encoding_name */
1583 tmp = g_ascii_strdown (media->media, -1);
1584 info = gst_rtp_payload_info_for_name (tmp, name);
1587 /* static types, use payload type */
1588 info = gst_rtp_payload_info_for_pt (pt);
1592 if ((rate = info->clock_rate) == 0)
1595 /* we fail if we cannot find one */
1600 tmp = g_ascii_strdown (media->media, -1);
1601 caps = gst_caps_new_simple ("application/x-unknown",
1602 "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
1604 s = gst_caps_get_structure (caps, 0);
1606 gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
1608 /* encoding name must be upper case */
1610 tmp = g_ascii_strup (name, -1);
1611 gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
1615 /* params must be lower case */
1616 if (params != NULL) {
1617 tmp = g_ascii_strdown (params, -1);
1618 gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
1622 /* parse optional fmtp: field */
1623 if ((fmtp = gst_sdp_media_get_attribute_val (media, "fmtp"))) {
1629 /* p is now of the format <payload> <param>[=<value>];... */
1630 PARSE_INT (p, " ", payload);
1631 if (payload != -1 && payload == pt) {
1635 /* <param>[=<value>] are separated with ';' */
1636 pairs = g_strsplit (p, ";", 0);
1637 for (i = 0; pairs[i]; i++) {
1639 const gchar *val, *key;
1641 /* the key may not have a '=', the value can have other '='s */
1642 valpos = strstr (pairs[i], "=");
1644 /* we have a '=' and thus a value, remove the '=' with \0 */
1646 /* value is everything between '=' and ';'. We split the pairs at ;
1647 * boundaries so we can take the remainder of the value. Some servers
1648 * put spaces around the value which we strip off here. Alternatively
1649 * we could strip those spaces in the depayloaders should these spaces
1650 * actually carry any meaning in the future. */
1651 val = g_strstrip (valpos + 1);
1653 /* simple <param>;.. is translated into <param>=1;... */
1656 /* strip the key of spaces, convert key to lowercase but not the value. */
1657 key = g_strstrip (pairs[i]);
1658 if (strlen (key) > 1) {
1659 tmp = g_ascii_strdown (key, -1);
1660 gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
1672 g_warning ("rtpmap type not given for dynamic payload %d", pt);
1677 g_warning ("rate unknown for payload type %d", pt);
1683 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
1684 gint * rtpport, gint * rtcpport)
1687 GstStateChangeReturn ret;
1688 GstElement *udpsrc0, *udpsrc1;
1689 gint tmp_rtp, tmp_rtcp;
1693 src = stream->parent;
1699 /* Start at next port */
1700 tmp_rtp = src->next_port_num;
1702 if (stream->is_ipv6)
1703 host = "udp://[::0]";
1705 host = "udp://0.0.0.0";
1707 /* try to allocate 2 UDP ports, the RTP port should be an even
1708 * number and the RTCP port should be the next (uneven) port */
1711 if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
1712 tmp_rtp >= src->client_port_range.max)
1715 udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1716 if (udpsrc0 == NULL)
1717 goto no_udp_protocol;
1718 g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
1720 if (src->udp_buffer_size != 0)
1721 g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
1724 ret = gst_element_set_state (udpsrc0, GST_STATE_PAUSED);
1725 if (ret == GST_STATE_CHANGE_FAILURE) {
1727 GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
1730 if (++count > src->retry)
1733 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1734 gst_element_set_state (udpsrc0, GST_STATE_NULL);
1735 gst_object_unref (udpsrc0);
1738 GST_DEBUG_OBJECT (src, "retry %d", count);
1741 goto no_udp_protocol;
1744 g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
1745 GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
1747 /* check if port is even */
1748 if ((tmp_rtp & 0x01) != 0) {
1749 /* port not even, close and allocate another */
1750 if (++count > src->retry)
1753 GST_DEBUG_OBJECT (src, "RTP port not even");
1755 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1756 gst_element_set_state (udpsrc0, GST_STATE_NULL);
1757 gst_object_unref (udpsrc0);
1760 GST_DEBUG_OBJECT (src, "retry %d", count);
1765 /* allocate port+1 for RTCP now */
1766 udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1767 if (udpsrc1 == NULL)
1768 goto no_udp_rtcp_protocol;
1771 tmp_rtcp = tmp_rtp + 1;
1772 if (src->client_port_range.max > 0 && tmp_rtcp > src->client_port_range.max)
1775 g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
1777 GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
1778 ret = gst_element_set_state (udpsrc1, GST_STATE_PAUSED);
1779 /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
1780 if (ret == GST_STATE_CHANGE_FAILURE) {
1781 GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
1783 if (++count > src->retry)
1786 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1787 gst_element_set_state (udpsrc0, GST_STATE_NULL);
1788 gst_object_unref (udpsrc0);
1791 GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
1792 gst_element_set_state (udpsrc1, GST_STATE_NULL);
1793 gst_object_unref (udpsrc1);
1797 GST_DEBUG_OBJECT (src, "retry %d", count);
1801 /* all fine, do port check */
1802 g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
1803 g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
1805 /* this should not happen... */
1806 if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
1809 /* we keep these elements, we configure all in configure_transport when the
1810 * server told us to really use the UDP ports. */
1811 stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
1812 stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
1813 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
1814 gst_element_set_locked_state (stream->udpsrc[1], TRUE);
1816 /* keep track of next available port number when we have a range
1818 if (src->next_port_num != 0)
1819 src->next_port_num = tmp_rtcp + 1;
1826 GST_DEBUG_OBJECT (src, "could not get UDP source");
1831 GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
1835 no_udp_rtcp_protocol:
1837 GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
1842 GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
1843 tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
1849 gst_element_set_state (udpsrc0, GST_STATE_NULL);
1850 gst_object_unref (udpsrc0);
1853 gst_element_set_state (udpsrc1, GST_STATE_NULL);
1854 gst_object_unref (udpsrc1);
1861 gst_rtspsrc_set_state (GstRTSPSrc * src, GstState state)
1866 gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
1868 for (walk = src->streams; walk; walk = g_list_next (walk)) {
1869 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1872 for (i = 0; i < 2; i++) {
1873 if (stream->udpsrc[i])
1874 gst_element_set_state (stream->udpsrc[i], state);
1880 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
1887 event = gst_event_new_flush_start ();
1888 GST_DEBUG_OBJECT (src, "start flush");
1890 state = GST_STATE_PAUSED;
1892 event = gst_event_new_flush_stop (FALSE);
1893 GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
1896 state = GST_STATE_PLAYING;
1898 state = GST_STATE_PAUSED;
1900 gst_rtspsrc_push_event (src, event);
1901 gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
1902 gst_rtspsrc_set_state (src, state);
1905 static GstRTSPResult
1906 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
1907 GstRTSPMessage * message, GTimeVal * timeout)
1912 ret = gst_rtsp_connection_send (conn, message, timeout);
1914 ret = GST_RTSP_ERROR;
1919 static GstRTSPResult
1920 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
1921 GstRTSPMessage * message, GTimeVal * timeout)
1926 ret = gst_rtsp_connection_receive (conn, message, timeout);
1928 ret = GST_RTSP_ERROR;
1934 gst_rtspsrc_get_position (GstRTSPSrc * src)
1939 query = gst_query_new_position (GST_FORMAT_TIME);
1940 /* should be known somewhere down the stream (e.g. jitterbuffer) */
1941 for (walk = src->streams; walk; walk = g_list_next (walk)) {
1942 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1946 if (stream->srcpad) {
1947 if (gst_pad_query (stream->srcpad, query)) {
1948 gst_query_parse_position (query, &fmt, &pos);
1949 GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
1950 GST_TIME_ARGS (pos));
1951 src->last_pos = pos;
1961 gst_rtspsrc_do_seek (GstRTSPSrc * src, GstSegment * segment)
1963 src->state = GST_RTSP_STATE_SEEKING;
1964 /* PLAY will add the range header now. */
1965 src->need_range = TRUE;
1971 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
1976 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
1978 gboolean flush, skip;
1981 GstSegment seeksegment = { 0, };
1985 GST_DEBUG_OBJECT (src, "doing seek with event");
1987 gst_event_parse_seek (event, &rate, &format, &flags,
1988 &cur_type, &cur, &stop_type, &stop);
1990 /* no negative rates yet */
1994 /* we need TIME format */
1995 if (format != src->segment.format)
1998 GST_DEBUG_OBJECT (src, "doing seek without event");
2000 cur_type = GST_SEEK_TYPE_SET;
2001 stop_type = GST_SEEK_TYPE_SET;
2004 /* get flush flag */
2005 flush = flags & GST_SEEK_FLAG_FLUSH;
2006 skip = flags & GST_SEEK_FLAG_SKIP;
2008 /* now we need to make sure the streaming thread is stopped. We do this by
2009 * either sending a FLUSH_START event downstream which will cause the
2010 * streaming thread to stop with a WRONG_STATE.
2011 * For a non-flushing seek we simply pause the task, which will happen as soon
2012 * as it completes one iteration (and thus might block when the sink is
2013 * blocking in preroll). */
2015 GST_DEBUG_OBJECT (src, "starting flush");
2016 gst_rtspsrc_flush (src, TRUE, FALSE);
2019 gst_task_pause (src->task);
2023 /* we should now be able to grab the streaming thread because we stopped it
2024 * with the above flush/pause code */
2025 GST_RTSP_STREAM_LOCK (src);
2027 GST_DEBUG_OBJECT (src, "stopped streaming");
2029 /* copy segment, we need this because we still need the old
2030 * segment when we close the current segment. */
2031 memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2033 /* configure the seek parameters in the seeksegment. We will then have the
2034 * right values in the segment to perform the seek */
2036 GST_DEBUG_OBJECT (src, "configuring seek");
2037 gst_segment_do_seek (&seeksegment, rate, format, flags,
2038 cur_type, cur, stop_type, stop, &update);
2041 /* figure out the last position we need to play. If it's configured (stop !=
2042 * -1), use that, else we play until the total duration of the file */
2043 if ((stop = seeksegment.stop) == -1)
2044 stop = seeksegment.duration;
2046 playing = (src->state == GST_RTSP_STATE_PLAYING);
2048 /* if we were playing, pause first */
2050 /* obtain current position in case seek fails */
2051 gst_rtspsrc_get_position (src);
2052 gst_rtspsrc_pause (src, FALSE);
2056 gst_rtspsrc_do_seek (src, &seeksegment);
2058 /* and continue playing */
2060 gst_rtspsrc_play (src, &seeksegment, FALSE);
2062 /* prepare for streaming again */
2064 /* if we started flush, we stop now */
2065 GST_DEBUG_OBJECT (src, "stopping flush");
2066 gst_rtspsrc_flush (src, FALSE, playing);
2069 /* now we did the seek and can activate the new segment values */
2070 memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2072 /* if we're doing a segment seek, post a SEGMENT_START message */
2073 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2074 gst_element_post_message (GST_ELEMENT_CAST (src),
2075 gst_message_new_segment_start (GST_OBJECT_CAST (src),
2076 src->segment.format, src->segment.position));
2079 /* now create the newsegment */
2080 GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2081 " to %" G_GINT64_FORMAT, src->segment.position, stop);
2084 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2085 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2086 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2087 stream->discont = TRUE;
2090 GST_RTSP_STREAM_UNLOCK (src);
2097 GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2102 GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2108 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2112 gboolean res = TRUE;
2115 src = GST_RTSPSRC_CAST (parent);
2117 GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2118 GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2120 switch (GST_EVENT_TYPE (event)) {
2121 case GST_EVENT_SEEK:
2122 res = gst_rtspsrc_perform_seek (src, event);
2126 case GST_EVENT_NAVIGATION:
2127 case GST_EVENT_LATENCY:
2135 if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2136 res = gst_pad_send_event (target, event);
2137 gst_object_unref (target);
2139 gst_event_unref (event);
2142 gst_event_unref (event);
2148 /* this is the final event function we receive on the internal source pad when
2149 * we deal with TCP connections */
2151 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2156 GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2158 switch (GST_EVENT_TYPE (event)) {
2159 case GST_EVENT_SEEK:
2161 case GST_EVENT_NAVIGATION:
2162 case GST_EVENT_LATENCY:
2164 gst_event_unref (event);
2171 /* this is the final query function we receive on the internal source pad when
2172 * we deal with TCP connections */
2174 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2178 gboolean res = TRUE;
2180 src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2182 GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2183 GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2185 switch (GST_QUERY_TYPE (query)) {
2186 case GST_QUERY_POSITION:
2191 case GST_QUERY_DURATION:
2195 gst_query_parse_duration (query, &format, NULL);
2198 case GST_FORMAT_TIME:
2199 gst_query_set_duration (query, format, src->segment.duration);
2207 case GST_QUERY_LATENCY:
2209 /* we are live with a min latency of 0 and unlimited max latency, this
2210 * result will be updated by the session manager if there is any. */
2211 gst_query_set_latency (query, TRUE, 0, -1);
2221 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2223 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2227 gboolean res = FALSE;
2229 src = GST_RTSPSRC_CAST (parent);
2231 GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2232 GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2234 switch (GST_QUERY_TYPE (query)) {
2235 case GST_QUERY_DURATION:
2239 gst_query_parse_duration (query, &format, NULL);
2242 case GST_FORMAT_TIME:
2243 gst_query_set_duration (query, format, src->segment.duration);
2251 case GST_QUERY_SEEKING:
2255 gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2256 if (format == GST_FORMAT_TIME) {
2258 src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2260 /* seeking without duration is unlikely */
2261 seekable = seekable && src->seekable && src->segment.duration &&
2262 GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2264 /* FIXME ?? should we have 0 and segment.duration here; see demuxers */
2265 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
2266 src->segment.start, src->segment.stop);
2275 uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2277 gst_query_set_uri (query, uri);
2285 GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2287 /* forward the query to the proxy target pad */
2289 res = gst_pad_query (target, query);
2290 gst_object_unref (target);
2299 /* callback for RTCP messages to be sent to the server when operating in TCP
2301 static GstFlowReturn
2302 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2305 GstRTSPStream *stream;
2306 GstFlowReturn res = GST_FLOW_OK;
2311 GstRTSPMessage message = { 0 };
2312 GstRTSPConnection *conn;
2314 stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2315 src = stream->parent;
2317 gst_buffer_map (buffer, &map, GST_MAP_READ);
2321 gst_rtsp_message_init_data (&message, stream->channel[1]);
2323 /* lend the body data to the message */
2324 gst_rtsp_message_take_body (&message, data, size);
2326 if (stream->conninfo.connection)
2327 conn = stream->conninfo.connection;
2329 conn = src->conninfo.connection;
2331 GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2332 ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2333 GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2335 /* and steal it away again because we will free it when unreffing the
2337 gst_rtsp_message_steal_body (&message, &data, &size);
2338 gst_rtsp_message_unset (&message);
2340 gst_buffer_unmap (buffer, &map);
2341 gst_buffer_unref (buffer);
2346 static GstPadProbeReturn
2347 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2349 GstRTSPSrc *src = user_data;
2351 GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2352 GST_DEBUG_PAD_NAME (pad));
2354 /* activate the streams */
2355 GST_OBJECT_LOCK (src);
2356 if (!src->need_activate)
2359 src->need_activate = FALSE;
2360 GST_OBJECT_UNLOCK (src);
2362 gst_rtspsrc_activate_streams (src);
2364 return GST_PAD_PROBE_OK;
2368 GST_OBJECT_UNLOCK (src);
2369 return GST_PAD_PROBE_OK;
2373 /* this callback is called when the session manager generated a new src pad with
2374 * payloaded RTP packets. We simply ghost the pad here. */
2376 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2379 GstPadTemplate *template;
2382 GstRTSPStream *stream;
2385 GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2387 GST_RTSP_STATE_LOCK (src);
2389 name = gst_object_get_name (GST_OBJECT_CAST (pad));
2390 if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2391 goto unknown_stream;
2393 GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2395 stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2397 goto unknown_stream;
2400 stream->ssrc = ssrc;
2402 /* we'll add it later see below */
2403 stream->added = TRUE;
2405 /* check if we added all streams */
2407 for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
2408 GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
2410 GST_DEBUG_OBJECT (src, "stream %p, container %d, disabled %d, added %d",
2411 ostream, ostream->container, ostream->disabled, ostream->added);
2413 /* a container stream only needs one pad added. Also disabled streams don't
2415 if (!ostream->container && !ostream->disabled && !ostream->added) {
2420 GST_RTSP_STATE_UNLOCK (src);
2422 /* create a new pad we will use to stream to */
2423 template = gst_static_pad_template_get (&rtptemplate);
2424 stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2425 gst_object_unref (template);
2428 gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2429 gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2430 gst_pad_set_active (stream->srcpad, TRUE);
2431 gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2434 GST_DEBUG_OBJECT (src, "We added all streams");
2435 /* when we get here, all stream are added and we can fire the no-more-pads
2437 gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2445 GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2446 GST_RTSP_STATE_UNLOCK (src);
2453 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2455 GstRTSPStream *stream;
2458 GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2460 GST_RTSP_STATE_LOCK (src);
2461 stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2463 goto unknown_stream;
2465 caps = stream->caps;
2467 gst_caps_ref (caps);
2468 GST_RTSP_STATE_UNLOCK (src);
2474 GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2475 GST_RTSP_STATE_UNLOCK (src);
2481 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2483 GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2489 gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
2495 GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2501 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2503 GstRTSPSrc *src = stream->parent;
2506 g_object_get (source, "ssrc", &ssrc, NULL);
2508 GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
2509 ssrc, stream->ssrc, stream->id);
2511 if (ssrc == stream->ssrc)
2512 gst_rtspsrc_do_stream_eos (src, stream);
2516 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2518 GstRTSPSrc *src = stream->parent;
2521 g_object_get (source, "ssrc", &ssrc, NULL);
2523 GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
2524 ssrc, stream->ssrc, stream->id);
2526 if (ssrc == stream->ssrc)
2527 gst_rtspsrc_do_stream_eos (src, stream);
2531 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2533 GstRTSPStream *stream;
2535 GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2537 /* get stream for session */
2538 stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2540 gst_rtspsrc_do_stream_eos (src, stream);
2545 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2547 GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2551 /* try to get and configure a manager */
2553 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
2554 GstRTSPTransport * transport)
2556 const gchar *manager;
2558 GstStateChangeReturn ret;
2560 /* find a manager */
2561 if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
2565 GST_DEBUG_OBJECT (src, "using manager %s", manager);
2567 /* configure the manager */
2568 if (src->manager == NULL) {
2569 GObjectClass *klass;
2571 if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
2573 if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
2577 goto use_no_manager;
2579 if (!(src->manager = gst_element_factory_make (manager, "manager")))
2580 goto manager_failed;
2583 /* we manage this element */
2584 gst_element_set_locked_state (src->manager, TRUE);
2585 gst_bin_add (GST_BIN_CAST (src), src->manager);
2587 ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
2588 if (ret == GST_STATE_CHANGE_FAILURE)
2589 goto start_manager_failure;
2591 g_object_set (src->manager, "latency", src->latency, NULL);
2593 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2595 if (g_object_class_find_property (klass, "ntp-sync")) {
2596 g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
2599 if (g_object_class_find_property (klass, "use-pipeline-clock")) {
2600 g_object_set (src->manager, "use-pipeline-clock",
2601 src->use_pipeline_clock, NULL);
2604 if (g_object_class_find_property (klass, "drop-on-latency")) {
2605 g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
2609 if (g_object_class_find_property (klass, "buffer-mode")) {
2610 if (src->buffer_mode != BUFFER_MODE_AUTO) {
2611 g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2613 gboolean need_slave;
2615 const gchar *encoding;
2617 /* buffer mode pauses are handled by adding offsets to buffer times,
2618 * but some depayloaders may have a hard time syncing output times
2619 * with such input times, e.g. container ones, most notably ASF */
2620 /* TODO alternatives are having an event that indicates these shifts,
2621 * or having rtsp extensions provide suggestion on buffer mode */
2622 need_slave = stream->container;
2623 if (stream->caps && (s = gst_caps_get_structure (stream->caps, 0)) &&
2624 (encoding = gst_structure_get_string (s, "encoding-name")))
2625 need_slave = need_slave || (strcmp (encoding, "X-ASF-PF") == 0);
2626 GST_DEBUG_OBJECT (src, "auto buffering mode, need_slave %d",
2628 /* valid duration implies not likely live pipeline,
2629 * so slaving in jitterbuffer does not make much sense
2630 * (and might mess things up due to bursts) */
2631 if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
2632 src->segment.duration && !need_slave) {
2633 GST_DEBUG_OBJECT (src, "selected buffer");
2634 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER,
2637 GST_DEBUG_OBJECT (src, "selected slave");
2638 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2643 /* connect to signals if we did not already do so */
2644 GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
2646 src->manager_sig_id =
2647 g_signal_connect (src->manager, "pad-added",
2648 (GCallback) new_manager_pad, src);
2649 src->manager_ptmap_id =
2650 g_signal_connect (src->manager, "request-pt-map",
2651 (GCallback) request_pt_map, src);
2653 g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
2657 /* we stream directly to the manager, get some pads. Each RTSP stream goes
2658 * into a separate RTP session. */
2659 name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
2660 stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
2662 name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
2663 stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
2666 /* now configure the bandwidth in the manager */
2667 if (g_signal_lookup ("get-internal-session",
2668 G_OBJECT_TYPE (src->manager)) != 0) {
2669 GObject *rtpsession;
2671 g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
2674 GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
2676 stream->session = rtpsession;
2678 if (stream->as_bandwidth != -1) {
2679 GST_INFO_OBJECT (src, "setting AS: %f",
2680 (gdouble) (stream->as_bandwidth * 1000));
2681 g_object_set (rtpsession, "bandwidth",
2682 (gdouble) (stream->as_bandwidth * 1000), NULL);
2684 if (stream->rr_bandwidth != -1) {
2685 GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
2686 g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
2689 if (stream->rs_bandwidth != -1) {
2690 GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
2691 g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
2695 g_object_set (rtpsession, "probation", src->probation, NULL);
2697 g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
2699 g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
2701 g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
2703 g_signal_connect (rtpsession, "on-ssrc-active",
2704 (GCallback) on_ssrc_active, stream);
2715 GST_DEBUG_OBJECT (src, "cannot get a session manager");
2720 GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
2723 start_manager_failure:
2725 GST_DEBUG_OBJECT (src, "could not start session manager");
2730 /* free the UDP sources allocated when negotiating a transport.
2731 * This function is called when the server negotiated to a transport where the
2732 * UDP sources are not needed anymore, such as TCP or multicast. */
2734 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
2738 for (i = 0; i < 2; i++) {
2739 if (stream->udpsrc[i]) {
2740 GST_DEBUG ("free UDP source %d for stream %p", i, stream);
2741 gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
2742 gst_object_unref (stream->udpsrc[i]);
2743 stream->udpsrc[i] = NULL;
2748 /* for TCP, create pads to send and receive data to and from the manager and to
2749 * intercept various events and queries
2752 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
2753 GstRTSPTransport * transport, GstPad ** outpad)
2756 GstPadTemplate *template;
2757 GstPad *pad0, *pad1;
2759 /* configure for interleaved delivery, nothing needs to be done
2760 * here, the loop function will call the chain functions of the
2761 * session manager. */
2762 stream->channel[0] = transport->interleaved.min;
2763 stream->channel[1] = transport->interleaved.max;
2764 GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
2765 stream->channel[0], stream->channel[1]);
2767 /* we can remove the allocated UDP ports now */
2768 gst_rtspsrc_stream_free_udp (stream);
2770 /* no session manager, send data to srcpad directly */
2771 if (!stream->channelpad[0]) {
2772 GST_DEBUG_OBJECT (src, "no manager, creating pad");
2774 /* create a new pad we will use to stream to */
2775 name = g_strdup_printf ("stream_%u", stream->id);
2776 template = gst_static_pad_template_get (&rtptemplate);
2777 stream->channelpad[0] = gst_pad_new_from_template (template, name);
2778 gst_object_unref (template);
2781 /* set caps and activate */
2782 gst_pad_use_fixed_caps (stream->channelpad[0]);
2783 gst_pad_set_active (stream->channelpad[0], TRUE);
2785 *outpad = gst_object_ref (stream->channelpad[0]);
2787 GST_DEBUG_OBJECT (src, "using manager source pad");
2789 template = gst_static_pad_template_get (&anysrctemplate);
2791 /* allocate pads for sending the channel data into the manager */
2792 pad0 = gst_pad_new_from_template (template, "internalsrc_0");
2793 gst_pad_link (pad0, stream->channelpad[0]);
2794 gst_object_unref (stream->channelpad[0]);
2795 stream->channelpad[0] = pad0;
2796 gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
2797 gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
2798 gst_pad_set_element_private (pad0, src);
2799 gst_pad_set_active (pad0, TRUE);
2801 if (stream->channelpad[1]) {
2802 /* if we have a sinkpad for the other channel, create a pad and link to the
2804 pad1 = gst_pad_new_from_template (template, "internalsrc_1");
2805 gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
2806 gst_pad_link (pad1, stream->channelpad[1]);
2807 gst_object_unref (stream->channelpad[1]);
2808 stream->channelpad[1] = pad1;
2809 gst_pad_set_active (pad1, TRUE);
2811 gst_object_unref (template);
2813 /* setup RTCP transport back to the server if we have to. */
2814 if (src->manager && src->do_rtcp) {
2817 template = gst_static_pad_template_get (&anysinktemplate);
2819 stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
2820 gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
2821 gst_pad_set_element_private (stream->rtcppad, stream);
2822 gst_pad_set_active (stream->rtcppad, TRUE);
2824 /* get session RTCP pad */
2825 name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2826 pad = gst_element_get_request_pad (src->manager, name);
2831 gst_pad_link (pad, stream->rtcppad);
2832 gst_object_unref (pad);
2835 gst_object_unref (template);
2841 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
2842 GstRTSPTransport * transport, const gchar ** destination, gint * min,
2843 gint * max, guint * ttl)
2845 if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
2847 if (!(*destination = transport->destination))
2848 *destination = stream->destination;
2851 /* transport first */
2852 *min = transport->port.min;
2853 *max = transport->port.max;
2854 if (*min == -1 && *max == -1) {
2855 /* then try from SDP */
2856 if (stream->port != 0) {
2857 *min = stream->port;
2858 *max = stream->port + 1;
2864 if (!(*ttl = transport->ttl))
2869 /* first take the source, then the endpoint to figure out where to send
2871 if (!(*destination = transport->source)) {
2872 if (src->conninfo.connection)
2873 *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
2874 else if (stream->conninfo.connection)
2876 gst_rtsp_connection_get_ip (stream->conninfo.connection);
2880 /* for unicast we only expect the ports here */
2881 *min = transport->server_port.min;
2882 *max = transport->server_port.max;
2887 /* For multicast create UDP sources and join the multicast group. */
2889 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
2890 GstRTSPTransport * transport, GstPad ** outpad)
2893 const gchar *destination;
2896 GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
2898 /* we can remove the allocated UDP ports now */
2899 gst_rtspsrc_stream_free_udp (stream);
2901 gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
2904 /* we need a destination now */
2905 if (destination == NULL)
2906 goto no_destination;
2908 /* we really need ports now or we won't be able to receive anything at all */
2909 if (min == -1 && max == -1)
2912 GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
2913 destination, min, max);
2915 /* creating UDP source for RTP */
2917 uri = g_strdup_printf ("udp://%s:%d", destination, min);
2919 gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
2921 if (stream->udpsrc[0] == NULL)
2924 /* take ownership */
2925 gst_object_ref_sink (stream->udpsrc[0]);
2927 if (src->udp_buffer_size != 0)
2928 g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
2929 src->udp_buffer_size, NULL);
2931 if (src->multi_iface != NULL)
2932 g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
2933 src->multi_iface, NULL);
2936 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
2937 gst_element_set_state (stream->udpsrc[0], GST_STATE_PAUSED);
2940 /* creating another UDP source for RTCP */
2944 uri = g_strdup_printf ("udp://%s:%d", destination, max);
2946 gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
2948 if (stream->udpsrc[1] == NULL)
2951 caps = gst_caps_new_empty_simple ("application/x-rtcp");
2952 g_object_set (stream->udpsrc[1], "caps", caps, NULL);
2953 gst_caps_unref (caps);
2955 /* take ownership */
2956 gst_object_ref_sink (stream->udpsrc[1]);
2958 if (src->multi_iface != NULL)
2959 g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
2960 src->multi_iface, NULL);
2962 gst_element_set_state (stream->udpsrc[1], GST_STATE_PAUSED);
2969 GST_DEBUG_OBJECT (src, "no UDP source element found");
2974 GST_DEBUG_OBJECT (src, "no destination found");
2979 GST_DEBUG_OBJECT (src, "no ports found");
2984 /* configure the remainder of the UDP ports */
2986 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
2987 GstRTSPTransport * transport, GstPad ** outpad)
2989 /* we manage the UDP elements now. For unicast, the UDP sources where
2990 * allocated in the stream when we suggested a transport. */
2991 if (stream->udpsrc[0]) {
2992 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
2993 gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
2995 GST_DEBUG_OBJECT (src, "setting up UDP source");
2997 /* configure a timeout on the UDP port. When the timeout message is
2998 * posted, we assume UDP transport is not possible. We reconnect using TCP
3000 g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3001 src->udp_timeout * 1000, NULL);
3003 /* get output pad of the UDP source. */
3004 *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3006 /* save it so we can unblock */
3007 stream->blockedpad = *outpad;
3009 /* configure pad block on the pad. As soon as there is dataflow on the
3010 * UDP source, we know that UDP is not blocked by a firewall and we can
3011 * configure all the streams to let the application autoplug decoders. */
3013 gst_pad_add_probe (stream->blockedpad,
3014 GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked, src, NULL);
3016 if (stream->channelpad[0]) {
3017 GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3018 /* configure for UDP delivery, we need to connect the UDP pads to
3019 * the session plugin. */
3020 gst_pad_link (*outpad, stream->channelpad[0]);
3021 gst_object_unref (*outpad);
3023 /* we connected to pad-added signal to get pads from the manager */
3025 GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3030 if (stream->udpsrc[1]) {
3033 gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3034 gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3036 caps = gst_caps_new_empty_simple ("application/x-rtcp");
3037 g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3038 gst_caps_unref (caps);
3040 if (stream->channelpad[1]) {
3043 GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3045 pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3046 gst_pad_link (pad, stream->channelpad[1]);
3047 gst_object_unref (pad);
3049 /* leave unlinked */
3055 /* configure the UDP sink back to the server for status reports */
3057 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3058 GstRTSPStream * stream, GstRTSPTransport * transport)
3061 gint rtp_port, rtcp_port;
3062 gboolean do_rtp, do_rtcp;
3063 const gchar *destination;
3068 /* get transport info */
3069 gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3070 &rtp_port, &rtcp_port, &ttl);
3072 /* see what we need to do */
3073 do_rtp = (rtp_port != -1);
3074 /* it's possible that the server does not want us to send RTCP in which case
3076 do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3078 /* we need a destination when we have RTP or RTCP ports */
3079 if (destination == NULL && (do_rtp || do_rtcp))
3080 goto no_destination;
3082 /* try to construct the fakesrc to the RTP port of the server to open up any
3085 GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3088 uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3089 stream->udpsink[0] =
3090 gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3092 if (stream->udpsink[0] == NULL)
3093 goto no_sink_element;
3095 /* don't join multicast group, we will have the source socket do that */
3096 /* no sync or async state changes needed */
3097 g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3098 "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3100 g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3102 if (stream->udpsrc[0]) {
3103 /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3104 * so that NAT firewalls will open a hole for us */
3105 g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3106 GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3107 /* configure socket and make sure udpsink does not close it when shutting
3108 * down, it belongs to udpsrc after all. */
3109 g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3110 "close-socket", FALSE, NULL);
3111 g_object_unref (socket);
3114 /* the source for the dummy packets to open up NAT */
3115 stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3116 if (stream->fakesrc == NULL)
3117 goto no_fakesrc_element;
3119 /* random data in 5 buffers, a size of 200 bytes should be fine */
3120 g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3121 "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3123 /* we don't want to consider this a sink */
3124 GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
3126 /* keep everything locked */
3127 gst_element_set_locked_state (stream->udpsink[0], TRUE);
3128 gst_element_set_locked_state (stream->fakesrc, TRUE);
3130 gst_object_ref (stream->udpsink[0]);
3131 gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3132 gst_object_ref (stream->fakesrc);
3133 gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3135 gst_element_link (stream->fakesrc, stream->udpsink[0]);
3138 GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3141 uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3142 stream->udpsink[1] =
3143 gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3145 if (stream->udpsink[1] == NULL)
3146 goto no_sink_element;
3148 /* don't join multicast group, we will have the source socket do that */
3149 /* no sync or async state changes needed */
3150 g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3151 "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3153 g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3155 if (stream->udpsrc[1]) {
3156 /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3157 * because some servers check the port number of where it sends RTCP to identify
3158 * the RTCP packets it receives */
3159 g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3160 GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3161 /* configure socket and make sure udpsink does not close it when shutting
3162 * down, it belongs to udpsrc after all. */
3163 g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3164 "close-socket", FALSE, NULL);
3165 g_object_unref (socket);
3168 /* we don't want to consider this a sink */
3169 GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
3171 /* we keep this playing always */
3172 gst_element_set_locked_state (stream->udpsink[1], TRUE);
3173 gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3175 gst_object_ref (stream->udpsink[1]);
3176 gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3178 stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3180 /* get session RTCP pad */
3181 name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3182 pad = gst_element_get_request_pad (src->manager, name);
3187 gst_pad_link (pad, stream->rtcppad);
3188 gst_object_unref (pad);
3197 GST_DEBUG_OBJECT (src, "no destination address specified");
3202 GST_DEBUG_OBJECT (src, "no UDP sink element found");
3207 GST_DEBUG_OBJECT (src, "no fakesrc element found");
3212 /* sets up all elements needed for streaming over the specified transport.
3213 * Does not yet expose the element pads, this will be done when there is actuall
3214 * dataflow detected, which might never happen when UDP is blocked in a
3215 * firewall, for example.
3218 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3219 GstRTSPTransport * transport)
3222 GstPad *outpad = NULL;
3223 GstPadTemplate *template;
3228 src = stream->parent;
3230 GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3232 s = gst_caps_get_structure (stream->caps, 0);
3234 /* get the proper mime type for this stream now */
3235 if (gst_rtsp_transport_get_mime (transport->trans, &mime) < 0)
3236 goto unknown_transport;
3238 goto unknown_transport;
3240 /* configure the final mime type */
3241 GST_DEBUG_OBJECT (src, "setting mime to %s", mime);
3242 gst_structure_set_name (s, mime);
3244 /* try to get and configure a manager, channelpad[0-1] will be configured with
3245 * the pads for the manager, or NULL when no manager is needed. */
3246 if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3249 switch (transport->lower_transport) {
3250 case GST_RTSP_LOWER_TRANS_TCP:
3251 if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3252 goto transport_failed;
3254 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3255 if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3256 goto transport_failed;
3257 /* fallthrough, the rest is the same for UDP and MCAST */
3258 case GST_RTSP_LOWER_TRANS_UDP:
3259 if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3260 goto transport_failed;
3261 /* configure udpsinks back to the server for RTCP messages and for the
3262 * dummy RTP messages to open NAT. */
3263 if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3264 goto transport_failed;
3267 goto unknown_transport;
3271 GST_DEBUG_OBJECT (src, "creating ghostpad");
3273 gst_pad_use_fixed_caps (outpad);
3275 /* create ghostpad, don't add just yet, this will be done when we activate
3277 name = g_strdup_printf ("stream_%u", stream->id);
3278 template = gst_static_pad_template_get (&rtptemplate);
3279 stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3280 gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3281 gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3282 gst_object_unref (template);
3285 gst_object_unref (outpad);
3287 /* mark pad as ok */
3288 stream->last_ret = GST_FLOW_OK;
3295 GST_DEBUG_OBJECT (src, "failed to configure transport");
3300 GST_DEBUG_OBJECT (src, "unknown transport");
3305 GST_DEBUG_OBJECT (src, "cannot get a session manager");
3310 /* send a couple of dummy random packets on the receiver RTP port to the server,
3311 * this should make a firewall think we initiated the data transfer and
3312 * hopefully allow packets to go from the sender port to our RTP receiver port */
3314 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3318 if (src->nat_method != GST_RTSP_NAT_DUMMY)
3321 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3322 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3324 if (stream->fakesrc && stream->udpsink[0]) {
3325 GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3326 gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3327 gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3328 gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3329 gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3335 /* Adds the source pads of all configured streams to the element.
3336 * This code is performed when we detected dataflow.
3338 * We detect dataflow from either the _loop function or with pad probes on the
3342 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3346 GST_DEBUG_OBJECT (src, "activating streams");
3348 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3349 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3351 if (stream->udpsrc[0]) {
3352 /* remove timeout, we are streaming now and timeouts will be handled by
3353 * the session manager and jitter buffer */
3354 g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3356 if (stream->srcpad) {
3357 GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3358 gst_pad_set_active (stream->srcpad, TRUE);
3360 /* if we don't have a session manager, set the caps now. If we have a
3361 * session, we will get a notification of the pad and the caps. */
3362 if (!src->manager) {
3363 GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3364 gst_pad_set_caps (stream->srcpad, stream->caps);
3367 if (!stream->added) {
3368 GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3369 gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3370 stream->added = TRUE;
3375 /* unblock all pads */
3376 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3377 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3379 if (stream->blockid) {
3380 GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3381 gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3382 stream->blockid = 0;
3390 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3391 gboolean reset_manager)
3394 guint64 start, stop;
3395 gdouble play_speed, play_scale;
3397 GST_DEBUG_OBJECT (src, "configuring stream caps");
3399 start = segment->position;
3400 stop = segment->duration;
3401 play_speed = segment->rate;
3402 play_scale = segment->applied_rate;
3404 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3405 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3408 if ((caps = stream->caps)) {
3409 caps = gst_caps_make_writable (caps);
3411 if (stream->timebase != -1)
3412 gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3413 (guint) stream->timebase, NULL);
3414 if (stream->seqbase != -1)
3415 gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3416 (guint) stream->seqbase, NULL);
3417 gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3419 gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3420 gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3421 gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3423 stream->caps = caps;
3425 GST_DEBUG_OBJECT (src, "stream %p, caps %" GST_PTR_FORMAT, stream, caps);
3427 if (reset_manager && src->manager) {
3428 GST_DEBUG_OBJECT (src, "clear session");
3429 g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3433 static GstFlowReturn
3434 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3439 /* store the value */
3440 stream->last_ret = ret;
3442 /* if it's success we can return the value right away */
3443 if (ret == GST_FLOW_OK)
3446 /* any other error that is not-linked can be returned right
3448 if (ret != GST_FLOW_NOT_LINKED)
3451 /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3452 for (streams = src->streams; streams; streams = g_list_next (streams)) {
3453 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3455 ret = ostream->last_ret;
3456 /* some other return value (must be SUCCESS but we can return
3457 * other values as well) */
3458 if (ret != GST_FLOW_NOT_LINKED)
3461 /* if we get here, all other pads were unlinked and we return
3462 * NOT_LINKED then */
3468 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
3471 gboolean res = TRUE;
3473 /* only streams that have a connection to the outside world */
3474 if (stream->container || stream->disabled)
3477 if (stream->udpsrc[0]) {
3478 gst_event_ref (event);
3479 res = gst_element_send_event (stream->udpsrc[0], event);
3480 } else if (stream->channelpad[0]) {
3481 gst_event_ref (event);
3482 if (GST_PAD_IS_SRC (stream->channelpad[0]))
3483 res = gst_pad_push_event (stream->channelpad[0], event);
3485 res = gst_pad_send_event (stream->channelpad[0], event);
3488 if (stream->udpsrc[1]) {
3489 gst_event_ref (event);
3490 res &= gst_element_send_event (stream->udpsrc[1], event);
3491 } else if (stream->channelpad[1]) {
3492 gst_event_ref (event);
3493 if (GST_PAD_IS_SRC (stream->channelpad[1]))
3494 res &= gst_pad_push_event (stream->channelpad[1], event);
3496 res &= gst_pad_send_event (stream->channelpad[1], event);
3500 gst_event_unref (event);
3506 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
3509 gboolean res = TRUE;
3511 for (streams = src->streams; streams; streams = g_list_next (streams)) {
3512 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3514 gst_event_ref (event);
3515 res &= gst_rtspsrc_stream_push_event (src, ostream, event);
3517 gst_event_unref (event);
3522 static GstRTSPResult
3523 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3528 if (info->connection == NULL) {
3529 if (info->url == NULL) {
3530 GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
3531 if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
3535 /* create connection */
3536 GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
3537 if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
3538 goto could_not_create;
3541 g_free (info->url_str);
3542 info->url_str = gst_rtsp_url_get_request_uri (info->url);
3544 GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
3546 if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
3547 gst_rtsp_connection_set_tunneled (info->connection, TRUE);
3549 if (src->proxy_host) {
3550 GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
3552 gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
3557 if (!info->connected) {
3560 GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
3561 ("Connecting to %s", info->location));
3562 GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
3564 gst_rtsp_connection_connect (info->connection,
3565 src->ptcp_timeout)) < 0)
3566 goto could_not_connect;
3568 info->connected = TRUE;
3575 GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
3580 gchar *str = gst_rtsp_strresult (res);
3581 GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
3587 gchar *str = gst_rtsp_strresult (res);
3588 GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
3594 static GstRTSPResult
3595 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
3598 GST_RTSP_STATE_LOCK (src);
3599 if (info->connected) {
3600 GST_DEBUG_OBJECT (src, "closing connection...");
3601 gst_rtsp_connection_close (info->connection);
3602 info->connected = FALSE;
3604 if (free && info->connection) {
3605 /* free connection */
3606 GST_DEBUG_OBJECT (src, "freeing connection...");
3607 gst_rtsp_connection_free (info->connection);
3608 info->connection = NULL;
3610 GST_RTSP_STATE_UNLOCK (src);
3614 static GstRTSPResult
3615 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3620 GST_DEBUG_OBJECT (src, "reconnecting connection...");
3621 gst_rtsp_conninfo_close (src, info, FALSE);
3622 res = gst_rtsp_conninfo_connect (src, info, async);
3628 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
3632 GST_DEBUG_OBJECT (src, "set flushing %d", flush);
3633 GST_RTSP_STATE_LOCK (src);
3634 if (src->conninfo.connection && src->conninfo.flushing != flush) {
3635 GST_DEBUG_OBJECT (src, "connection flush");
3636 gst_rtsp_connection_flush (src->conninfo.connection, flush);
3637 src->conninfo.flushing = flush;
3639 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3640 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3641 if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
3642 GST_DEBUG_OBJECT (src, "stream %p flush", stream);
3643 gst_rtsp_connection_flush (stream->conninfo.connection, flush);
3644 stream->conninfo.flushing = flush;
3647 GST_RTSP_STATE_UNLOCK (src);
3650 /* FIXME, handle server request, reply with OK, for now */
3651 static GstRTSPResult
3652 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
3653 GstRTSPMessage * request)
3655 GstRTSPMessage response = { 0 };
3658 GST_DEBUG_OBJECT (src, "got server request message");
3661 gst_rtsp_message_dump (request);
3663 res = gst_rtsp_ext_list_receive_request (src->extensions, request);
3665 if (res == GST_RTSP_ENOTIMPL) {
3666 /* default implementation, send OK */
3667 GST_DEBUG_OBJECT (src, "prepare OK reply");
3669 gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
3674 /* let app parse and reply */
3675 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
3676 0, request, response);
3679 gst_rtsp_message_dump (&response);
3681 res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
3685 gst_rtsp_message_unset (&response);
3686 } else if (res == GST_RTSP_EEOF)
3694 gst_rtsp_message_unset (&response);
3699 /* send server keep-alive */
3700 static GstRTSPResult
3701 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
3703 GstRTSPMessage request = { 0 };
3705 GstRTSPMethod method;
3708 if (src->do_rtsp_keep_alive == FALSE) {
3709 GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
3710 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3714 GST_DEBUG_OBJECT (src, "creating server keep-alive");
3716 /* find a method to use for keep-alive */
3717 if (src->methods & GST_RTSP_GET_PARAMETER)
3718 method = GST_RTSP_GET_PARAMETER;
3720 method = GST_RTSP_OPTIONS;
3723 control = src->control;
3725 control = src->conninfo.url_str;
3727 if (control == NULL)
3730 res = gst_rtsp_message_init_request (&request, method, control);
3735 gst_rtsp_message_dump (&request);
3738 gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
3743 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3744 gst_rtsp_message_unset (&request);
3751 GST_WARNING_OBJECT (src, "no control url to send keepalive");
3756 gchar *str = gst_rtsp_strresult (res);
3758 gst_rtsp_message_unset (&request);
3759 GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
3760 ("Could not send keep-alive. (%s)", str));
3766 static GstFlowReturn
3767 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
3769 GstFlowReturn ret = GST_FLOW_OK;
3771 GstRTSPStream *stream;
3772 GstPad *outpad = NULL;
3779 channel = message->type_data.data.channel;
3781 stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
3783 goto unknown_stream;
3785 if (channel == stream->channel[0]) {
3786 outpad = stream->channelpad[0];
3788 } else if (channel == stream->channel[1]) {
3789 outpad = stream->channelpad[1];
3795 /* take a look at the body to figure out what we have */
3796 gst_rtsp_message_get_body (message, &data, &size);
3798 goto invalid_length;
3800 /* channels are not correct on some servers, do extra check */
3801 if (data[1] >= 200 && data[1] <= 204) {
3802 /* hmm RTCP message switch to the RTCP pad of the same stream. */
3803 outpad = stream->channelpad[1];
3807 /* we have no clue what this is, just ignore then. */
3809 goto unknown_stream;
3811 /* take the message body for further processing */
3812 gst_rtsp_message_steal_body (message, &data, &size);
3814 /* strip the trailing \0 */
3817 buf = gst_buffer_new ();
3818 gst_buffer_append_memory (buf,
3819 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
3821 /* don't need message anymore */
3822 gst_rtsp_message_unset (message);
3824 GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
3827 if (src->need_activate) {
3833 /* generate an SHA256 sum of the URI */
3834 cs = g_checksum_new (G_CHECKSUM_SHA256);
3835 uri = src->conninfo.location;
3836 g_checksum_update (cs, (const guchar *) uri, strlen (uri));
3838 g_strdup_printf ("%s/%d", g_checksum_get_string (cs), stream->id);
3839 g_checksum_free (cs);
3840 event = gst_event_new_stream_start (stream_id);
3842 gst_rtspsrc_push_event (src, event);
3844 gst_rtspsrc_activate_streams (src);
3845 src->need_activate = FALSE;
3847 if ((event = src->start_segment) != NULL) {
3848 src->start_segment = NULL;
3849 gst_rtspsrc_push_event (src, event);
3852 if (src->base_time == -1) {
3853 /* Take current running_time. This timestamp will be put on
3854 * the first buffer of each stream because we are a live source and so we
3855 * timestamp with the running_time. When we are dealing with TCP, we also
3856 * only timestamp the first buffer (using the DISCONT flag) because a server
3857 * typically bursts data, for which we don't want to compensate by speeding
3858 * up the media. The other timestamps will be interpollated from this one
3859 * using the RTP timestamps. */
3860 GST_OBJECT_LOCK (src);
3861 if (GST_ELEMENT_CLOCK (src)) {
3863 GstClockTime base_time;
3865 now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
3866 base_time = GST_ELEMENT_CAST (src)->base_time;
3868 src->base_time = now - base_time;
3870 GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
3871 GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
3873 GST_OBJECT_UNLOCK (src);
3876 if (stream->discont && !is_rtcp) {
3877 /* mark first RTP buffer as discont */
3878 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3879 stream->discont = FALSE;
3880 /* first buffer gets the timestamp, other buffers are not timestamped and
3881 * their presentation time will be interpollated from the rtp timestamps. */
3882 GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
3883 GST_TIME_ARGS (src->base_time));
3885 GST_BUFFER_TIMESTAMP (buf) = src->base_time;
3888 /* chain to the peer pad */
3889 if (GST_PAD_IS_SINK (outpad))
3890 ret = gst_pad_chain (outpad, buf);
3892 ret = gst_pad_push (outpad, buf);
3895 /* combine all stream flows for the data transport */
3896 ret = gst_rtspsrc_combine_flows (src, stream, ret);
3903 GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
3904 gst_rtsp_message_unset (message);
3909 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3910 ("Short message received, ignoring."));
3911 gst_rtsp_message_unset (message);
3916 static GstFlowReturn
3917 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
3919 GstRTSPMessage message = { 0 };
3921 GstFlowReturn ret = GST_FLOW_OK;
3922 GTimeVal tv_timeout;
3925 /* get the next timeout interval */
3926 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3928 /* see if the timeout period expired */
3929 if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
3930 GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
3931 /* send keep-alive, only act on interrupt, a warning will be posted for
3933 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3935 /* get new timeout */
3936 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3939 GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
3940 tv_timeout.tv_sec, tv_timeout.tv_usec);
3942 /* protect the connection with the connection lock so that we can see when
3943 * we are finished doing server communication */
3945 gst_rtspsrc_connection_receive (src, src->conninfo.connection,
3946 &message, src->ptcp_timeout);
3950 GST_DEBUG_OBJECT (src, "we received a server message");
3952 case GST_RTSP_EINTR:
3953 /* we got interrupted this means we need to stop */
3955 case GST_RTSP_ETIMEOUT:
3956 /* no reply, send keep alive */
3957 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
3958 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3962 /* go EOS when the server closed the connection */
3968 switch (message.type) {
3969 case GST_RTSP_MESSAGE_REQUEST:
3970 /* server sends us a request message, handle it */
3972 gst_rtspsrc_handle_request (src, src->conninfo.connection,
3974 if (res == GST_RTSP_EEOF)
3977 goto handle_request_failed;
3979 case GST_RTSP_MESSAGE_RESPONSE:
3980 /* we ignore response messages */
3981 GST_DEBUG_OBJECT (src, "ignoring response message");
3983 gst_rtsp_message_dump (&message);
3985 case GST_RTSP_MESSAGE_DATA:
3986 GST_DEBUG_OBJECT (src, "got data message");
3987 ret = gst_rtspsrc_handle_data (src, &message);
3988 if (ret != GST_FLOW_OK)
3989 goto handle_data_failed;
3992 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
3997 g_assert_not_reached ();
4002 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4003 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4004 ("The server closed the connection."));
4005 src->conninfo.connected = FALSE;
4006 gst_rtsp_message_unset (&message);
4007 return GST_FLOW_EOS;
4011 gst_rtsp_message_unset (&message);
4012 GST_DEBUG_OBJECT (src, "got interrupted");
4013 return GST_FLOW_FLUSHING;
4017 gchar *str = gst_rtsp_strresult (res);
4019 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4020 ("Could not receive message. (%s)", str));
4023 gst_rtsp_message_unset (&message);
4024 return GST_FLOW_ERROR;
4026 handle_request_failed:
4028 gchar *str = gst_rtsp_strresult (res);
4030 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4031 ("Could not handle server message. (%s)", str));
4033 gst_rtsp_message_unset (&message);
4034 return GST_FLOW_ERROR;
4038 GST_DEBUG_OBJECT (src, "could no handle data message");
4043 static GstFlowReturn
4044 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4047 GstRTSPMessage message = { 0 };
4051 GTimeVal tv_timeout;
4053 /* get the next timeout interval */
4054 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4056 GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4057 (gint) tv_timeout.tv_sec);
4059 gst_rtsp_message_unset (&message);
4061 /* we should continue reading the TCP socket because the server might
4062 * send us requests. When the session timeout expires, we need to send a
4063 * keep-alive request to keep the session open. */
4064 res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4065 &message, &tv_timeout);
4069 GST_DEBUG_OBJECT (src, "we received a server message");
4071 case GST_RTSP_EINTR:
4072 /* we got interrupted, see what we have to do */
4074 case GST_RTSP_ETIMEOUT:
4075 /* send keep-alive, ignore the result, a warning will be posted. */
4076 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4077 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4081 /* server closed the connection. not very fatal for UDP, reconnect and
4082 * see what happens. */
4083 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4084 ("The server closed the connection."));
4085 if (src->udp_reconnect) {
4087 gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4094 GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4096 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4097 ("Unhandled return value %d.", res));
4101 switch (message.type) {
4102 case GST_RTSP_MESSAGE_REQUEST:
4103 /* server sends us a request message, handle it */
4105 gst_rtspsrc_handle_request (src, src->conninfo.connection,
4107 if (res == GST_RTSP_EEOF)
4110 goto handle_request_failed;
4112 case GST_RTSP_MESSAGE_RESPONSE:
4113 /* we ignore response and data messages */
4114 GST_DEBUG_OBJECT (src, "ignoring response message");
4116 gst_rtsp_message_dump (&message);
4117 if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4118 GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4119 if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4120 GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4121 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4128 case GST_RTSP_MESSAGE_DATA:
4129 /* we ignore response and data messages */
4130 GST_DEBUG_OBJECT (src, "ignoring data message");
4133 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4138 g_assert_not_reached ();
4140 /* we get here when the connection got interrupted */
4143 gst_rtsp_message_unset (&message);
4144 GST_DEBUG_OBJECT (src, "got interrupted");
4145 return GST_FLOW_FLUSHING;
4149 gchar *str = gst_rtsp_strresult (res);
4152 src->conninfo.connected = FALSE;
4153 if (res != GST_RTSP_EINTR) {
4154 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4155 ("Could not connect to server. (%s)", str));
4157 ret = GST_FLOW_ERROR;
4159 ret = GST_FLOW_FLUSHING;
4165 gchar *str = gst_rtsp_strresult (res);
4167 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4168 ("Could not receive message. (%s)", str));
4170 return GST_FLOW_ERROR;
4172 handle_request_failed:
4174 gchar *str = gst_rtsp_strresult (res);
4177 gst_rtsp_message_unset (&message);
4178 if (res != GST_RTSP_EINTR) {
4179 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4180 ("Could not handle server message. (%s)", str));
4182 ret = GST_FLOW_ERROR;
4184 ret = GST_FLOW_FLUSHING;
4190 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4191 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4192 ("The server closed the connection."));
4193 src->conninfo.connected = FALSE;
4194 gst_rtsp_message_unset (&message);
4195 return GST_FLOW_EOS;
4199 static GstRTSPResult
4200 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4202 GstRTSPResult res = GST_RTSP_OK;
4205 GST_DEBUG_OBJECT (src, "doing reconnect");
4207 GST_OBJECT_LOCK (src);
4208 /* only restart when the pads were not yet activated, else we were
4209 * streaming over UDP */
4210 restart = src->need_activate;
4211 GST_OBJECT_UNLOCK (src);
4213 /* no need to restart, we're done */
4217 /* we can try only TCP now */
4218 src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4220 /* close and cleanup our state */
4221 if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4224 /* see if we have TCP left to try. Also don't try TCP when we were configured
4226 if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4229 /* We post a warning message now to inform the user
4230 * that nothing happened. It's most likely a firewall thing. */
4231 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4232 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4233 "firewall is blocking it. Retrying using a TCP connection.",
4234 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4236 /* open new connection using tcp */
4237 if (gst_rtspsrc_open (src, async) < 0)
4240 /* start playback */
4241 if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4250 src->cur_protocols = 0;
4251 /* no transport possible, post an error and stop */
4252 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4253 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4254 "firewall is blocking it. No other protocols to try.",
4255 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4256 return GST_RTSP_ERROR;
4260 GST_DEBUG_OBJECT (src, "open failed");
4265 GST_DEBUG_OBJECT (src, "play failed");
4271 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4275 GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4278 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4281 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4284 GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4292 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4296 GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4299 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4302 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4305 GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4313 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4317 GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4320 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4323 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4326 GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4334 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4338 GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4341 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4344 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4347 GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4355 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4357 if (ret == GST_RTSP_OK)
4358 gst_rtspsrc_loop_complete_cmd (src, cmd);
4359 else if (ret == GST_RTSP_EINTR)
4360 gst_rtspsrc_loop_cancel_cmd (src, cmd);
4362 gst_rtspsrc_loop_error_cmd (src, cmd);
4366 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4370 /* start new request */
4371 gst_rtspsrc_loop_start_cmd (src, cmd);
4373 GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4375 GST_OBJECT_LOCK (src);
4376 old = src->pending_cmd;
4377 if (old == CMD_RECONNECT) {
4378 GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4379 cmd = CMD_RECONNECT;
4381 if (old != CMD_WAIT) {
4382 src->pending_cmd = CMD_WAIT;
4383 GST_OBJECT_UNLOCK (src);
4384 /* cancel previous request */
4385 GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4386 gst_rtspsrc_loop_cancel_cmd (src, old);
4387 GST_OBJECT_LOCK (src);
4389 src->pending_cmd = cmd;
4390 /* interrupt if allowed */
4391 if (src->busy_cmd & mask) {
4392 GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4393 gst_rtspsrc_connection_flush (src, TRUE);
4395 GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4398 gst_task_start (src->task);
4399 GST_OBJECT_UNLOCK (src);
4403 gst_rtspsrc_loop (GstRTSPSrc * src)
4407 if (!src->conninfo.connection || !src->conninfo.connected)
4410 if (src->interleaved)
4411 ret = gst_rtspsrc_loop_interleaved (src);
4413 ret = gst_rtspsrc_loop_udp (src);
4415 if (ret != GST_FLOW_OK)
4423 GST_WARNING_OBJECT (src, "we are not connected");
4424 ret = GST_FLOW_FLUSHING;
4429 const gchar *reason = gst_flow_get_name (ret);
4431 GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4432 src->running = FALSE;
4433 if (ret == GST_FLOW_EOS) {
4434 /* perform EOS logic */
4435 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4436 gst_element_post_message (GST_ELEMENT_CAST (src),
4437 gst_message_new_segment_done (GST_OBJECT_CAST (src),
4438 src->segment.format, src->segment.position));
4439 gst_rtspsrc_push_event (src,
4440 gst_event_new_segment_done (src->segment.format,
4441 src->segment.position));
4443 gst_rtspsrc_push_event (src, gst_event_new_eos ());
4445 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4446 /* for fatal errors we post an error message, post the error before the
4447 * EOS so the app knows about the error first. */
4448 GST_ELEMENT_ERROR (src, STREAM, FAILED,
4449 ("Internal data flow error."),
4450 ("streaming task paused, reason %s (%d)", reason, ret));
4451 gst_rtspsrc_push_event (src, gst_event_new_eos ());
4453 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
4458 #ifndef GST_DISABLE_GST_DEBUG
4459 static const gchar *
4460 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4464 while (method != 0) {
4481 static const gchar *
4482 gst_rtspsrc_skip_lws (const gchar * s)
4484 while (g_ascii_isspace (*s))
4489 static const gchar *
4490 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4492 while (s > start && g_ascii_isspace (*(s - 1)))
4497 static const gchar *
4498 gst_rtspsrc_skip_commas (const gchar * s)
4500 /* The grammar allows for multiple commas */
4501 while (g_ascii_isspace (*s) || *s == ',')
4506 static const gchar *
4507 gst_rtspsrc_skip_item (const gchar * s)
4509 gboolean quoted = FALSE;
4510 const gchar *start = s;
4512 /* A list item ends at the last non-whitespace character
4513 * before a comma which is not inside a quoted-string. Or at
4514 * the end of the string.
4520 if (*s == '\\' && *(s + 1))
4529 return gst_rtspsrc_unskip_lws (s, start);
4533 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4537 src = quoted_string + 1;
4538 dst = quoted_string;
4539 while (*src && *src != '"') {
4540 if (*src == '\\' && *(src + 1))
4547 /* Extract the authentication tokens that the server provided for each method
4548 * into an array of structures and give those to the connection object.
4551 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4552 const gchar * header, gboolean * stale)
4554 GSList *list = NULL, *iter;
4556 gchar *item, *eq, *name_end, *value;
4558 g_return_if_fail (stale != NULL);
4560 gst_rtsp_connection_clear_auth_params (conn);
4563 /* Parse a header whose content is described by RFC2616 as
4564 * "#something", where "something" does not itself contain commas,
4565 * except as part of quoted-strings, into a list of allocated strings.
4567 header = gst_rtspsrc_skip_commas (header);
4569 end = gst_rtspsrc_skip_item (header);
4570 list = g_slist_prepend (list, g_strndup (header, end - header));
4571 header = gst_rtspsrc_skip_commas (end);
4576 list = g_slist_reverse (list);
4577 for (iter = list; iter; iter = iter->next) {
4580 eq = strchr (item, '=');
4582 name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4583 if (name_end == item) {
4584 /* That's no good... */
4591 value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4593 gst_rtsp_decode_quoted_string (value);
4597 if (item && (strcmp (item, "stale") == 0) &&
4598 value && (strcmp (value, "TRUE") == 0))
4600 gst_rtsp_connection_set_auth_param (conn, item, value);
4604 g_slist_free (list);
4607 /* Parse a WWW-Authenticate Response header and determine the
4608 * available authentication methods
4610 * This code should also cope with the fact that each WWW-Authenticate
4611 * header can contain multiple challenge methods + tokens
4613 * At the moment, for Basic auth, we just do a minimal check and don't
4614 * even parse out the realm */
4616 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4617 GstRTSPConnection * conn, gboolean * stale)
4621 g_return_if_fail (hdr != NULL);
4622 g_return_if_fail (methods != NULL);
4623 g_return_if_fail (stale != NULL);
4625 /* Skip whitespace at the start of the string */
4626 for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4628 if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4629 *methods |= GST_RTSP_AUTH_BASIC;
4630 else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4631 *methods |= GST_RTSP_AUTH_DIGEST;
4632 gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4637 * gst_rtspsrc_setup_auth:
4638 * @src: the rtsp source
4640 * Configure a username and password and auth method on the
4641 * connection object based on a response we received from the
4644 * Currently, this requires that a username and password were supplied
4645 * in the uri. In the future, they may be requested on demand by sending
4646 * a message up the bus.
4648 * Returns: TRUE if authentication information could be set up correctly.
4651 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4655 GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4656 GstRTSPAuthMethod method;
4657 GstRTSPResult auth_result;
4659 GstRTSPConnection *conn;
4661 gboolean stale = FALSE;
4663 conn = src->conninfo.connection;
4665 /* Identify the available auth methods and see if any are supported */
4666 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4667 &hdr, 0) == GST_RTSP_OK) {
4668 gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4671 if (avail_methods == GST_RTSP_AUTH_NONE)
4672 goto no_auth_available;
4674 /* For digest auth, if the response indicates that the session
4675 * data are stale, we just update them in the connection object and
4676 * return TRUE to retry the request */
4678 src->tried_url_auth = FALSE;
4680 url = gst_rtsp_connection_get_url (conn);
4682 /* Do we have username and password available? */
4683 if (url != NULL && !src->tried_url_auth && url->user != NULL
4684 && url->passwd != NULL) {
4687 src->tried_url_auth = TRUE;
4688 GST_DEBUG_OBJECT (src,
4689 "Attempting authentication using credentials from the URL");
4691 user = src->user_id;
4692 pass = src->user_pw;
4693 GST_DEBUG_OBJECT (src,
4694 "Attempting authentication using credentials from the properties");
4697 /* FIXME: If the url didn't contain username and password or we tried them
4698 * already, request a username and passwd from the application via some kind
4699 * of credentials request message */
4701 /* If we don't have a username and passwd at this point, bail out. */
4702 if (user == NULL || pass == NULL)
4705 /* Try to configure for each available authentication method, strongest to
4707 for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4708 /* Check if this method is available on the server */
4709 if ((method & avail_methods) == 0)
4712 /* Pass the credentials to the connection to try on the next request */
4713 auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4714 /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4715 * ignore it and end up retrying later */
4716 if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4717 GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4718 gst_rtsp_auth_method_to_string (method));
4723 if (method == GST_RTSP_AUTH_NONE)
4724 goto no_auth_available;
4730 /* Output an error indicating that we couldn't connect because there were
4731 * no supported authentication protocols */
4732 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4733 ("No supported authentication protocol was found"));
4738 /* We don't fire an error message, we just return FALSE and let the
4739 * normal NOT_AUTHORIZED error be propagated */
4744 static GstRTSPResult
4745 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4746 GstRTSPMessage * request, GstRTSPMessage * response,
4747 GstRTSPStatusCode * code)
4750 GstRTSPStatusCode thecode;
4751 gchar *content_base = NULL;
4755 if (!src->short_header)
4756 gst_rtsp_ext_list_before_send (src->extensions, request);
4758 GST_DEBUG_OBJECT (src, "sending message");
4761 gst_rtsp_message_dump (request);
4763 res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4767 gst_rtsp_connection_reset_timeout (conn);
4770 res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4775 gst_rtsp_message_dump (response);
4777 switch (response->type) {
4778 case GST_RTSP_MESSAGE_REQUEST:
4779 res = gst_rtspsrc_handle_request (src, conn, response);
4780 if (res == GST_RTSP_EEOF)
4783 goto handle_request_failed;
4785 case GST_RTSP_MESSAGE_RESPONSE:
4786 /* ok, a response is good */
4787 GST_DEBUG_OBJECT (src, "received response message");
4789 case GST_RTSP_MESSAGE_DATA:
4790 /* get next response */
4791 GST_DEBUG_OBJECT (src, "handle data response message");
4792 gst_rtspsrc_handle_data (src, response);
4795 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4800 thecode = response->type_data.response.code;
4802 GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4804 /* if the caller wanted the result code, we store it. */
4808 /* If the request didn't succeed, bail out before doing any more */
4809 if (thecode != GST_RTSP_STS_OK)
4812 /* store new content base if any */
4813 gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4816 g_free (src->content_base);
4817 src->content_base = g_strdup (content_base);
4819 gst_rtsp_ext_list_after_send (src->extensions, request, response);
4826 gchar *str = gst_rtsp_strresult (res);
4828 if (res != GST_RTSP_EINTR) {
4829 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4830 ("Could not send message. (%s)", str));
4832 GST_WARNING_OBJECT (src, "send interrupted");
4841 GST_WARNING_OBJECT (src, "server closed connection");
4842 if ((try == 0) && !src->interleaved && src->udp_reconnect) {
4844 /* if reconnect succeeds, try again */
4846 gst_rtsp_conninfo_reconnect (src, &src->conninfo,
4850 /* only try once after reconnect, then fallthrough and error out */
4853 gchar *str = gst_rtsp_strresult (res);
4855 if (res != GST_RTSP_EINTR) {
4856 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4857 ("Could not receive message. (%s)", str));
4859 GST_WARNING_OBJECT (src, "receive interrupted");
4867 handle_request_failed:
4869 /* ERROR was posted */
4870 gst_rtsp_message_unset (response);
4875 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4876 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4877 ("The server closed the connection."));
4878 gst_rtsp_message_unset (response);
4885 * @src: the rtsp source
4886 * @conn: the connection to send on
4887 * @request: must point to a valid request
4888 * @response: must point to an empty #GstRTSPMessage
4889 * @code: an optional code result
4891 * send @request and retrieve the response in @response. optionally @code can be
4892 * non-NULL in which case it will contain the status code of the response.
4894 * If This function returns #GST_RTSP_OK, @response will contain a valid response
4895 * message that should be cleaned with gst_rtsp_message_unset() after usage.
4897 * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
4898 * @response message) if the response code was not 200 (OK).
4900 * If the attempt results in an authentication failure, then this will attempt
4901 * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
4904 * Returns: #GST_RTSP_OK if the processing was successful.
4906 static GstRTSPResult
4907 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4908 GstRTSPMessage * request, GstRTSPMessage * response,
4909 GstRTSPStatusCode * code)
4911 GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
4912 GstRTSPResult res = GST_RTSP_ERROR;
4915 GstRTSPMethod method = GST_RTSP_INVALID;
4921 /* make sure we don't loop forever */
4925 /* save method so we can disable it when the server complains */
4926 method = request->type_data.request.method;
4929 gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
4933 case GST_RTSP_STS_UNAUTHORIZED:
4934 if (gst_rtspsrc_setup_auth (src, response)) {
4935 /* Try the request/response again after configuring the auth info
4943 } while (retry == TRUE);
4945 /* If the user requested the code, let them handle errors, otherwise
4946 * post an error below */
4949 else if (int_code != GST_RTSP_STS_OK)
4950 goto error_response;
4957 GST_DEBUG_OBJECT (src, "got error %d", res);
4962 res = GST_RTSP_ERROR;
4964 switch (response->type_data.response.code) {
4965 case GST_RTSP_STS_NOT_FOUND:
4966 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
4967 response->type_data.response.reason));
4969 case GST_RTSP_STS_MOVED_PERMANENTLY:
4970 case GST_RTSP_STS_MOVE_TEMPORARILY:
4972 gchar *new_location;
4973 GstRTSPLowerTrans transports;
4975 GST_DEBUG_OBJECT (src, "got redirection");
4976 /* if we don't have a Location Header, we must error */
4977 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
4978 &new_location, 0) < 0)
4981 /* When we receive a redirect result, we go back to the INIT state after
4982 * parsing the new URI. The caller should do the needed steps to issue
4983 * a new setup when it detects this state change. */
4984 GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
4986 /* save current transports */
4987 if (src->conninfo.url)
4988 transports = src->conninfo.url->transports;
4990 transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
4992 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
4994 /* set old transports */
4995 if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
4996 src->conninfo.url->transports = transports;
4998 src->need_redirect = TRUE;
4999 src->state = GST_RTSP_STATE_INIT;
5003 case GST_RTSP_STS_NOT_ACCEPTABLE:
5004 case GST_RTSP_STS_NOT_IMPLEMENTED:
5005 case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5006 GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5007 gst_rtsp_method_as_text (method));
5008 src->methods &= ~method;
5012 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5013 ("Got error response: %d (%s).", response->type_data.response.code,
5014 response->type_data.response.reason));
5017 /* if we return ERROR we should unset the response ourselves */
5018 if (res == GST_RTSP_ERROR)
5019 gst_rtsp_message_unset (response);
5025 static GstRTSPResult
5026 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5027 GstRTSPMessage * response, GstRTSPSrc * src)
5029 return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5034 /* parse the response and collect all the supported methods. We need this
5035 * information so that we don't try to send an unsupported request to the
5039 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5041 GstRTSPHeaderField field;
5045 /* reset supported methods */
5048 /* Try Allow Header first */
5049 field = GST_RTSP_HDR_ALLOW;
5052 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5053 if (indx == 0 && !respoptions) {
5054 /* if no Allow header was found then try the Public header... */
5055 field = GST_RTSP_HDR_PUBLIC;
5056 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5061 src->methods |= gst_rtsp_options_from_text (respoptions);
5066 if (src->methods == 0) {
5067 /* neither Allow nor Public are required, assume the server supports
5068 * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5070 GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5071 src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5073 /* always assume PLAY, FIXME, extensions should be able to override
5075 src->methods |= GST_RTSP_PLAY;
5076 /* also assume it will support Range */
5077 src->seekable = TRUE;
5079 /* we need describe and setup */
5080 if (!(src->methods & GST_RTSP_DESCRIBE))
5082 if (!(src->methods & GST_RTSP_SETUP))
5090 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5091 ("Server does not support DESCRIBE."));
5096 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5097 ("Server does not support SETUP."));
5102 /* masks to be kept in sync with the hardcoded protocol order of preference
5104 static guint protocol_masks[] = {
5105 GST_RTSP_LOWER_TRANS_UDP,
5106 GST_RTSP_LOWER_TRANS_UDP_MCAST,
5107 GST_RTSP_LOWER_TRANS_TCP,
5111 static GstRTSPResult
5112 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5113 GstRTSPLowerTrans protocols, gchar ** transports)
5117 gboolean add_udp_str;
5122 gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5127 GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5129 /* extension listed transports, use those */
5130 if (*transports != NULL)
5133 /* it's the default */
5134 add_udp_str = FALSE;
5136 /* the default RTSP transports */
5137 result = g_string_new ("");
5138 if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5139 GST_DEBUG_OBJECT (src, "adding UDP unicast");
5141 g_string_append (result, "RTP/AVP");
5143 g_string_append (result, "/UDP");
5144 g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5145 } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5146 GST_DEBUG_OBJECT (src, "adding UDP multicast");
5148 /* we don't have to allocate any UDP ports yet, if the selected transport
5149 * turns out to be multicast we can create them and join the multicast
5150 * group indicated in the transport reply */
5151 if (result->len > 0)
5152 g_string_append (result, ",");
5153 g_string_append (result, "RTP/AVP");
5155 g_string_append (result, "/UDP");
5156 g_string_append (result, ";multicast");
5157 if (src->next_port_num != 0) {
5158 if (src->client_port_range.max > 0 &&
5159 src->next_port_num >= src->client_port_range.max)
5162 g_string_append_printf (result, ";client_port=%d-%d",
5163 src->next_port_num, src->next_port_num + 1);
5165 } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5166 GST_DEBUG_OBJECT (src, "adding TCP");
5168 if (result->len > 0)
5169 g_string_append (result, ",");
5170 g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
5172 *transports = g_string_free (result, FALSE);
5174 GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5181 GST_ERROR ("extension gave error %d", res);
5186 GST_ERROR ("no more ports available");
5187 return GST_RTSP_ERROR;
5191 static GstRTSPResult
5192 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5193 gint orig_rtpport, gint orig_rtcpport)
5196 gint nr_udp, nr_int;
5198 gint rtpport = 0, rtcpport = 0;
5201 src = stream->parent;
5203 /* find number of placeholders first */
5204 if (strstr (*transports, "%%i2"))
5206 else if (strstr (*transports, "%%i1"))
5211 if (strstr (*transports, "%%u2"))
5213 else if (strstr (*transports, "%%u1"))
5218 if (nr_udp == 0 && nr_int == 0)
5222 if (!orig_rtpport || !orig_rtcpport) {
5223 if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5226 rtpport = orig_rtpport;
5227 rtcpport = orig_rtcpport;
5231 str = g_string_new ("");
5233 while ((next = strstr (p, "%%"))) {
5234 g_string_append_len (str, p, next - p);
5235 if (next[2] == 'u') {
5237 g_string_append_printf (str, "%d", rtpport);
5238 else if (next[3] == '2')
5239 g_string_append_printf (str, "%d", rtcpport);
5241 if (next[2] == 'i') {
5243 g_string_append_printf (str, "%d", src->free_channel);
5244 else if (next[3] == '2')
5245 g_string_append_printf (str, "%d", src->free_channel + 1);
5250 /* append final part */
5251 g_string_append (str, p);
5253 g_free (*transports);
5254 *transports = g_string_free (str, FALSE);
5262 GST_ERROR ("failed to allocate udp ports");
5263 return GST_RTSP_ERROR;
5268 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5270 gboolean res = FALSE;
5274 const gchar *enc = NULL;
5276 s = gst_caps_get_structure (stream->caps, 0);
5277 if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5278 res = (strstr (enc, "-REAL") != NULL);
5284 /* Perform the SETUP request for all the streams.
5286 * We ask the server for a specific transport, which initially includes all the
5287 * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5288 * two local UDP ports that we send to the server.
5290 * Once the server replied with a transport, we configure the other streams
5291 * with the same transport.
5293 * This function will also configure the stream for the selected transport,
5294 * which basically means creating the pipeline.
5296 static GstRTSPResult
5297 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5300 GstRTSPResult res = GST_RTSP_ERROR;
5301 GstRTSPMessage request = { 0 };
5302 GstRTSPMessage response = { 0 };
5303 GstRTSPStream *stream = NULL;
5304 GstRTSPLowerTrans protocols;
5305 GstRTSPStatusCode code;
5306 gboolean unsupported_real = FALSE;
5307 gint rtpport, rtcpport;
5311 if (src->conninfo.connection) {
5312 url = gst_rtsp_connection_get_url (src->conninfo.connection);
5313 /* we initially allow all configured lower transports. based on the URL
5314 * transports and the replies from the server we narrow them down. */
5315 protocols = url->transports & src->cur_protocols;
5318 protocols = src->cur_protocols;
5324 /* reset some state */
5325 src->free_channel = 0;
5326 src->interleaved = FALSE;
5327 src->need_activate = FALSE;
5328 /* keep track of next port number, 0 is random */
5329 src->next_port_num = src->client_port_range.min;
5330 rtpport = rtcpport = 0;
5332 if (G_UNLIKELY (src->streams == NULL))
5335 for (walk = src->streams; walk; walk = g_list_next (walk)) {
5336 GstRTSPConnection *conn;
5341 stream = (GstRTSPStream *) walk->data;
5343 /* see if we need to configure this stream */
5344 if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5345 GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5347 stream->disabled = TRUE;
5351 /* merge/overwrite global caps */
5356 s = gst_caps_get_structure (stream->caps, 0);
5358 num = gst_structure_n_fields (src->props);
5359 for (j = 0; j < num; j++) {
5363 name = gst_structure_nth_field_name (src->props, j);
5364 val = gst_structure_get_value (src->props, name);
5365 gst_structure_set_value (s, name, val);
5367 GST_DEBUG_OBJECT (src, "copied %s", name);
5371 /* skip setup if we have no URL for it */
5372 if (stream->conninfo.location == NULL) {
5373 GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5377 if (src->conninfo.connection == NULL) {
5378 if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5379 GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5382 conn = stream->conninfo.connection;
5384 conn = src->conninfo.connection;
5386 GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5387 stream->conninfo.location);
5389 /* if we have a multicast connection, only suggest multicast from now on */
5390 if (stream->is_multicast)
5391 protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5394 /* first selectable protocol */
5395 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5397 if (!protocol_masks[mask])
5401 GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5402 protocol_masks[mask]);
5403 /* create a string with first transport in line */
5405 res = gst_rtspsrc_create_transports_string (src,
5406 protocols & protocol_masks[mask], &transports);
5407 if (res < 0 || transports == NULL)
5408 goto setup_transport_failed;
5410 if (strlen (transports) == 0) {
5411 g_free (transports);
5412 GST_DEBUG_OBJECT (src, "no transports found");
5417 GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5419 /* replace placeholders with real values, this function will optionally
5420 * allocate UDP ports and other info needed to execute the setup request */
5421 res = gst_rtspsrc_prepare_transports (stream, &transports,
5422 retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5424 g_free (transports);
5425 goto setup_transport_failed;
5428 GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5430 /* create SETUP request */
5432 gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5433 stream->conninfo.location);
5435 g_free (transports);
5436 goto create_request_failed;
5439 /* select transport, copy is made when adding to header so we can free it. */
5440 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5441 g_free (transports);
5443 /* if the user wants a non default RTP packet size we add the blocksize
5445 if (src->rtp_blocksize > 0) {
5446 hval = g_strdup_printf ("%d", src->rtp_blocksize);
5447 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5452 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5455 /* handle the code ourselves */
5456 if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5460 case GST_RTSP_STS_OK:
5462 case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5463 gst_rtsp_message_unset (&request);
5464 gst_rtsp_message_unset (&response);
5465 /* cleanup of leftover transport */
5466 gst_rtspsrc_stream_free_udp (stream);
5467 /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5468 * we might be in this case */
5469 if (stream->container && rtpport && rtcpport && !retry) {
5470 GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5475 /* this transport did not go down well, but we may have others to try
5476 * that we did not send yet, try those and only give up then
5477 * but not without checking for lost cause/extension so we can
5478 * post a nicer/more useful error message later */
5479 if (!unsupported_real)
5480 unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5481 /* select next available protocol, give up on this stream if none */
5483 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5485 if (!protocol_masks[mask] || unsupported_real)
5490 /* cleanup of leftover transport and move to the next stream */
5491 gst_rtspsrc_stream_free_udp (stream);
5492 goto response_error;
5495 /* parse response transport */
5497 gchar *resptrans = NULL;
5498 GstRTSPTransport transport = { 0 };
5500 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5503 gst_rtspsrc_stream_free_udp (stream);
5507 /* parse transport, go to next stream on parse error */
5508 if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5509 GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5513 /* update allowed transports for other streams. once the transport of
5514 * one stream has been determined, we make sure that all other streams
5515 * are configured in the same way */
5516 switch (transport.lower_transport) {
5517 case GST_RTSP_LOWER_TRANS_TCP:
5518 GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5519 protocols = GST_RTSP_LOWER_TRANS_TCP;
5520 src->interleaved = TRUE;
5521 /* update free channels */
5523 MAX (transport.interleaved.min, src->free_channel);
5525 MAX (transport.interleaved.max, src->free_channel);
5526 src->free_channel++;
5528 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5529 /* only allow multicast for other streams */
5530 GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5531 protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5532 /* if the server selected our ports, increment our counters so that
5533 * we select a new port later */
5534 if (src->next_port_num == transport.port.min &&
5535 src->next_port_num + 1 == transport.port.max) {
5536 src->next_port_num += 2;
5539 case GST_RTSP_LOWER_TRANS_UDP:
5540 /* only allow unicast for other streams */
5541 GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5542 protocols = GST_RTSP_LOWER_TRANS_UDP;
5545 GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5546 transport.lower_transport);
5550 if (!stream->container || (!src->interleaved && !retry)) {
5551 /* now configure the stream with the selected transport */
5552 if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5553 GST_DEBUG_OBJECT (src,
5554 "could not configure stream %p transport, skipping stream",
5557 } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5558 /* retain the first allocated UDP port pair */
5559 g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5560 g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5563 /* we need to activate at least one streams when we detect activity */
5564 src->need_activate = TRUE;
5566 /* clean up our transport struct */
5567 gst_rtsp_transport_init (&transport);
5568 /* clean up used RTSP messages */
5569 gst_rtsp_message_unset (&request);
5570 gst_rtsp_message_unset (&response);
5574 /* store the transport protocol that was configured */
5575 src->cur_protocols = protocols;
5577 gst_rtsp_ext_list_stream_select (src->extensions, url);
5579 /* if there is nothing to activate, error out */
5580 if (!src->need_activate)
5581 goto nothing_to_activate;
5588 /* no transport possible, post an error and stop */
5589 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5590 ("Could not connect to server, no protocols left"));
5591 return GST_RTSP_ERROR;
5595 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5596 ("SDP contains no streams"));
5597 return GST_RTSP_ERROR;
5599 create_request_failed:
5601 gchar *str = gst_rtsp_strresult (res);
5603 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5604 ("Could not create request. (%s)", str));
5608 setup_transport_failed:
5610 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5611 ("Could not setup transport."));
5612 res = GST_RTSP_ERROR;
5617 const gchar *str = gst_rtsp_status_as_text (code);
5619 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5620 ("Error (%d): %s", code, GST_STR_NULL (str)));
5621 res = GST_RTSP_ERROR;
5626 gchar *str = gst_rtsp_strresult (res);
5628 if (res != GST_RTSP_EINTR) {
5629 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5630 ("Could not send message. (%s)", str));
5632 GST_WARNING_OBJECT (src, "send interrupted");
5639 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5640 ("Server did not select transport."));
5641 res = GST_RTSP_ERROR;
5644 nothing_to_activate:
5646 /* none of the available error codes is really right .. */
5647 if (unsupported_real) {
5648 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5649 (_("No supported stream was found. You might need to install a "
5650 "GStreamer RTSP extension plugin for Real media streams.")),
5653 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5654 (_("No supported stream was found. You might need to allow "
5655 "more transport protocols or may otherwise be missing "
5656 "the right GStreamer RTSP extension plugin.")), (NULL));
5658 return GST_RTSP_ERROR;
5662 gst_rtsp_message_unset (&request);
5663 gst_rtsp_message_unset (&response);
5669 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5670 GstSegment * segment)
5673 GstRTSPTimeRange *therange;
5676 gst_rtsp_range_free (src->range);
5678 if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5679 GST_DEBUG_OBJECT (src, "parsed range %s", range);
5680 src->range = therange;
5682 GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5684 gst_segment_init (segment, GST_FORMAT_TIME);
5688 GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d, max %f ",
5689 therange->min.type, therange->min.seconds, therange->max.type,
5690 therange->max.seconds);
5692 if (therange->min.type == GST_RTSP_TIME_NOW)
5694 else if (therange->min.type == GST_RTSP_TIME_END)
5697 seconds = therange->min.seconds * GST_SECOND;
5699 GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5700 GST_TIME_ARGS (seconds));
5702 /* we need to start playback without clipping from the position reported by
5704 segment->start = seconds;
5705 segment->position = seconds;
5707 if (therange->max.type == GST_RTSP_TIME_NOW)
5709 else if (therange->max.type == GST_RTSP_TIME_END)
5712 seconds = therange->max.seconds * GST_SECOND;
5714 GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5715 GST_TIME_ARGS (seconds));
5717 /* live (WMS) server might send overflowed large max as its idea of infinity,
5718 * compensate to prevent problems later on */
5719 if (seconds != -1 && seconds < 0) {
5721 GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5724 /* live (WMS) might send min == max, which is not worth recording */
5725 if (segment->duration == -1 && seconds == segment->start)
5728 /* don't change duration with unknown value, we might have a valid value
5729 * there that we want to keep. */
5731 segment->duration = seconds;
5736 /* Parse clock profived by the server with following syntax:
5738 * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
5741 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
5743 gboolean res = FALSE;
5745 if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
5746 gchar **fields = NULL, **parts = NULL;
5747 gchar *remote_ip, *str;
5749 GstClockTime base_time;
5752 fields = g_strsplit (gstclock, " ", 0);
5754 /* wrapped clock, not very interesting for now */
5755 if (fields[1] == NULL)
5758 /* remote IP address and port */
5759 if ((str = fields[2]) == NULL)
5762 parts = g_strsplit (str, ":", 0);
5764 if ((remote_ip = parts[0]) == NULL)
5767 if ((str = parts[1]) == NULL)
5775 if ((str = fields[3]) == NULL)
5778 base_time = g_ascii_strtoull (str, NULL, 10);
5781 gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
5784 if (src->provided_clock)
5785 gst_object_unref (src->provided_clock);
5786 src->provided_clock = netclock;
5788 gst_element_post_message (GST_ELEMENT_CAST (src),
5789 gst_message_new_clock_provide (GST_OBJECT_CAST (src),
5790 src->provided_clock, TRUE));
5794 g_strfreev (fields);
5800 /* must be called with the RTSP state lock */
5801 static GstRTSPResult
5802 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5808 /* prepare global stream caps properties */
5810 gst_structure_remove_all_fields (src->props);
5812 src->props = gst_structure_new_empty ("RTSPProperties");
5815 gst_sdp_message_dump (sdp);
5817 gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5819 gst_segment_init (&src->segment, GST_FORMAT_TIME);
5821 /* parse range for duration reporting. */
5826 range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5830 /* keep track of the range and configure it in the segment */
5831 if (gst_rtspsrc_parse_range (src, range, &src->segment))
5835 /* parse clock information. This is GStreamer specific, a server can tell the
5836 * client what clock it is using and wrap that in a network clock. The
5837 * advantage of that is that we can slave to it. */
5839 const gchar *gstclock;
5842 gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
5843 if (gstclock == NULL)
5846 /* parse the clock and expose it in the provide_clock method */
5847 if (gst_rtspsrc_parse_gst_clock (src, gstclock))
5851 /* try to find a global control attribute. Note that a '*' means that we should
5852 * do aggregate control with the current url (so we don't do anything and
5853 * leave the current connection as is) */
5855 const gchar *control;
5858 control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
5859 if (control == NULL)
5862 /* only take fully qualified urls */
5863 if (g_str_has_prefix (control, "rtsp://"))
5867 g_free (src->conninfo.location);
5868 src->conninfo.location = g_strdup (control);
5869 /* make a connection for this, if there was a connection already, nothing
5871 if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
5872 GST_ERROR_OBJECT (src, "could not connect");
5875 /* we need to keep the control url separate from the connection url because
5876 * the rules for constructing the media control url need it */
5877 g_free (src->control);
5878 src->control = g_strdup (control);
5881 /* create streams */
5882 n_streams = gst_sdp_message_medias_len (sdp);
5883 for (i = 0; i < n_streams; i++) {
5884 gst_rtspsrc_create_stream (src, sdp, i);
5887 src->state = GST_RTSP_STATE_INIT;
5890 if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
5893 /* reset our state */
5894 src->need_range = TRUE;
5897 src->state = GST_RTSP_STATE_READY;
5904 GST_ERROR_OBJECT (src, "setup failed");
5905 gst_rtspsrc_cleanup (src);
5910 static GstRTSPResult
5911 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
5915 GstRTSPMessage request = { 0 };
5916 GstRTSPMessage response = { 0 };
5919 gchar *respcont = NULL;
5922 src->need_redirect = FALSE;
5924 /* can't continue without a valid url */
5925 if (G_UNLIKELY (src->conninfo.url == NULL)) {
5926 res = GST_RTSP_EINVAL;
5929 src->tried_url_auth = FALSE;
5931 if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
5932 goto connect_failed;
5934 /* create OPTIONS */
5935 GST_DEBUG_OBJECT (src, "create options...");
5937 gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
5938 src->conninfo.url_str);
5940 goto create_request_failed;
5943 GST_DEBUG_OBJECT (src, "send options...");
5946 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
5949 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5954 if (!gst_rtspsrc_parse_methods (src, &response))
5957 /* create DESCRIBE */
5958 GST_DEBUG_OBJECT (src, "create describe...");
5960 gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
5961 src->conninfo.url_str);
5963 goto create_request_failed;
5965 /* we only accept SDP for now */
5966 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
5970 GST_DEBUG_OBJECT (src, "send describe...");
5973 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
5976 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5980 /* we only perform redirect for the describe, currently */
5981 if (src->need_redirect) {
5982 /* close connection, we don't have to send a TEARDOWN yet, ignore the
5984 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5986 gst_rtsp_message_unset (&request);
5987 gst_rtsp_message_unset (&response);
5993 /* it could be that the DESCRIBE method was not implemented */
5994 if (!src->methods & GST_RTSP_DESCRIBE)
5997 /* check if reply is SDP */
5998 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6000 /* could not be set but since the request returned OK, we assume it
6001 * was SDP, else check it. */
6003 if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6004 goto wrong_content_type;
6007 /* get message body and parse as SDP */
6008 gst_rtsp_message_get_body (&response, &data, &size);
6009 if (data == NULL || size == 0)
6012 GST_DEBUG_OBJECT (src, "parse SDP...");
6013 gst_sdp_message_new (sdp);
6014 gst_sdp_message_parse_buffer (data, size, *sdp);
6016 /* clean up any messages */
6017 gst_rtsp_message_unset (&request);
6018 gst_rtsp_message_unset (&response);
6025 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6026 ("No valid RTSP URL was provided"));
6031 gchar *str = gst_rtsp_strresult (res);
6033 if (res != GST_RTSP_EINTR) {
6034 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6035 ("Failed to connect. (%s)", str));
6037 GST_WARNING_OBJECT (src, "connect interrupted");
6042 create_request_failed:
6044 gchar *str = gst_rtsp_strresult (res);
6046 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6047 ("Could not create request. (%s)", str));
6053 /* Don't post a message - the rtsp_send method will have
6054 * taken care of it because we passed NULL for the response code */
6059 /* error was posted */
6060 res = GST_RTSP_ERROR;
6065 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6066 ("Server does not support SDP, got %s.", respcont));
6067 res = GST_RTSP_ERROR;
6072 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6073 ("Server can not provide an SDP."));
6074 res = GST_RTSP_ERROR;
6079 if (src->conninfo.connection) {
6080 GST_DEBUG_OBJECT (src, "free connection");
6081 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6083 gst_rtsp_message_unset (&request);
6084 gst_rtsp_message_unset (&response);
6089 static GstRTSPResult
6090 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6095 GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6097 if (src->sdp == NULL) {
6098 if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6102 if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6107 gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6114 GST_WARNING_OBJECT (src, "can't get sdp");
6115 src->open_error = TRUE;
6120 GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6121 src->open_error = TRUE;
6126 static GstRTSPResult
6127 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6129 GstRTSPMessage request = { 0 };
6130 GstRTSPMessage response = { 0 };
6131 GstRTSPResult res = GST_RTSP_OK;
6135 GST_DEBUG_OBJECT (src, "TEARDOWN...");
6137 gst_rtspsrc_set_state (src, GST_STATE_READY);
6139 if (src->state < GST_RTSP_STATE_READY) {
6140 GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6147 /* construct a control url */
6149 control = src->control;
6151 control = src->conninfo.url_str;
6153 if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6156 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6157 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6159 GstRTSPConnInfo *info;
6161 /* try aggregate control first but do non-aggregate control otherwise */
6163 setup_url = control;
6164 else if ((setup_url = stream->conninfo.location) == NULL)
6167 if (src->conninfo.connection) {
6168 info = &src->conninfo;
6169 } else if (stream->conninfo.connection) {
6170 info = &stream->conninfo;
6174 if (!info->connected)
6179 gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6181 goto create_request_failed;
6184 GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6187 gst_rtspsrc_send (src, info->connection, &request, &response,
6191 /* FIXME, parse result? */
6192 gst_rtsp_message_unset (&request);
6193 gst_rtsp_message_unset (&response);
6196 /* early exit when we did aggregate control */
6202 /* close connections */
6203 GST_DEBUG_OBJECT (src, "closing connection...");
6204 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6205 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6206 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6207 gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6211 gst_rtspsrc_cleanup (src);
6213 src->state = GST_RTSP_STATE_INVALID;
6216 gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6221 create_request_failed:
6223 gchar *str = gst_rtsp_strresult (res);
6225 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6226 ("Could not create request. (%s)", str));
6232 gchar *str = gst_rtsp_strresult (res);
6234 gst_rtsp_message_unset (&request);
6235 if (res != GST_RTSP_EINTR) {
6236 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6237 ("Could not send message. (%s)", str));
6239 GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
6246 GST_DEBUG_OBJECT (src,
6247 "TEARDOWN and PLAY not supported, can't do TEARDOWN");
6252 /* RTP-Info is of the format:
6254 * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
6256 * rtptime corresponds to the timestamp for the NPT time given in the header
6257 * seqbase corresponds to the next sequence number we received. This number
6258 * indicates the first seqnum after the seek and should be used to discard
6259 * packets that are from before the seek.
6262 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
6267 GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
6269 infos = g_strsplit (rtpinfo, ",", 0);
6270 for (i = 0; infos[i]; i++) {
6272 GstRTSPStream *stream;
6276 GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
6278 /* init values, types of seqbase and timebase are bigger than needed so we
6279 * can store -1 as uninitialized values */
6284 /* parse url, find stream for url.
6285 * parse seq and rtptime. The seq number should be configured in the rtp
6286 * depayloader or session manager to detect gaps. Same for the rtptime, it
6287 * should be used to create an initial time newsegment. */
6288 fields = g_strsplit (infos[i], ";", 0);
6289 for (j = 0; fields[j]; j++) {
6290 GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
6291 /* remove leading whitespace */
6292 fields[j] = g_strchug (fields[j]);
6293 if (g_str_has_prefix (fields[j], "url=")) {
6294 /* get the url and the stream */
6296 find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
6297 } else if (g_str_has_prefix (fields[j], "seq=")) {
6298 seqbase = atoi (fields[j] + 4);
6299 } else if (g_str_has_prefix (fields[j], "rtptime=")) {
6300 timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
6303 g_strfreev (fields);
6304 /* now we need to store the values for the caps of the stream */
6305 if (stream != NULL) {
6306 GST_DEBUG_OBJECT (src,
6307 "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
6308 stream, seqbase, timebase);
6310 /* we have a stream, configure detected params */
6311 stream->seqbase = seqbase;
6312 stream->timebase = timebase;
6321 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
6326 interval = strtoul (rtcp, NULL, 10);
6327 GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
6332 interval *= GST_MSECOND;
6334 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6335 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6337 /* already (optionally) retrieved this when configuring manager */
6338 if (stream->session) {
6339 GObject *rtpsession = stream->session;
6341 GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
6343 g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
6347 /* now it happens that (Xenon) server sending this may also provide bogus
6348 * RTCP SR sync data (i.e. with quite some jitter), so never mind those
6349 * and just use RTP-Info to sync */
6351 GObjectClass *klass;
6353 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6354 if (g_object_class_find_property (klass, "rtcp-sync")) {
6355 GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6356 g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6362 gst_rtspsrc_get_float (const gchar * dstr)
6364 gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6366 /* canonicalise floating point string so we can handle float strings
6367 * in the form "24.930" or "24,930" irrespective of the current locale */
6368 g_strlcpy (s, dstr, sizeof (s));
6369 g_strdelimit (s, ",", '.');
6370 return g_ascii_strtod (s, NULL);
6374 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6376 gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6378 if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6379 g_strlcpy (val_str, "now", sizeof (val_str));
6381 if (segment->position == 0) {
6382 g_strlcpy (val_str, "0", sizeof (val_str));
6384 g_ascii_dtostr (val_str, sizeof (val_str),
6385 ((gdouble) segment->position) / GST_SECOND);
6388 return g_strdup_printf ("npt=%s-", val_str);
6392 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6394 stream->timebase = -1;
6395 stream->seqbase = -1;
6399 stream->caps = gst_caps_make_writable (stream->caps);
6400 s = gst_caps_get_structure (stream->caps, 0);
6401 gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6405 static GstRTSPResult
6406 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6408 GstRTSPResult res = GST_RTSP_OK;
6410 if (src->state < GST_RTSP_STATE_READY) {
6411 res = GST_RTSP_ERROR;
6412 if (src->open_error) {
6413 GST_DEBUG_OBJECT (src, "the stream was in error");
6417 gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6419 if ((res = gst_rtspsrc_open (src, async)) < 0) {
6420 GST_DEBUG_OBJECT (src, "failed to open stream");
6429 static GstRTSPResult
6430 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6432 GstRTSPMessage request = { 0 };
6433 GstRTSPMessage response = { 0 };
6434 GstRTSPResult res = GST_RTSP_OK;
6440 GST_DEBUG_OBJECT (src, "PLAY...");
6442 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6445 if (!(src->methods & GST_RTSP_PLAY))
6448 if (src->state == GST_RTSP_STATE_PLAYING)
6451 if (!src->conninfo.connection || !src->conninfo.connected)
6454 /* send some dummy packets before we activate the receive in the
6456 gst_rtspsrc_send_dummy_packets (src);
6458 gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
6460 /* construct a control url */
6462 control = src->control;
6464 control = src->conninfo.url_str;
6466 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6467 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6469 GstRTSPConnection *conn;
6471 /* try aggregate control first but do non-aggregate control otherwise */
6473 setup_url = control;
6474 else if ((setup_url = stream->conninfo.location) == NULL)
6477 if (src->conninfo.connection) {
6478 conn = src->conninfo.connection;
6479 } else if (stream->conninfo.connection) {
6480 conn = stream->conninfo.connection;
6486 res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6488 goto create_request_failed;
6490 if (src->need_range) {
6491 hval = gen_range_header (src, segment);
6493 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_RANGE, hval);
6496 /* store the newsegment event so it can be sent from the streaming thread. */
6497 if (src->start_segment)
6498 gst_event_unref (src->start_segment);
6499 src->start_segment = gst_event_new_segment (&src->segment);
6502 if (segment->rate != 1.0) {
6503 gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6505 g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6507 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6509 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6513 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6515 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6518 /* seek may have silently failed as it is not supported */
6519 if (!(src->methods & GST_RTSP_PLAY)) {
6520 GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6521 /* obviously it is supported as we made it here */
6522 src->methods |= GST_RTSP_PLAY;
6523 src->seekable = FALSE;
6524 /* but there is nothing to parse in the response,
6525 * so convey we have no idea and not to expect anything particular */
6526 clear_rtp_base (src, stream);
6530 /* need to do for all streams */
6531 for (run = src->streams; run; run = g_list_next (run))
6532 clear_rtp_base (src, (GstRTSPStream *) run->data);
6534 /* NOTE the above also disables npt based eos detection */
6535 /* and below forces position to 0,
6536 * which is visible feedback we lost the plot */
6537 segment->start = segment->position = src->last_pos;
6540 gst_rtsp_message_unset (&request);
6542 /* parse RTP npt field. This is the current position in the stream (Normal
6543 * Play Time) and should be put in the NEWSEGMENT position field. */
6544 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6546 gst_rtspsrc_parse_range (src, hval, segment);
6548 /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6549 segment->rate = 1.0;
6551 /* parse Speed header. This is the intended playback rate of the stream
6552 * and should be put in the NEWSEGMENT rate field. */
6553 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6554 0) == GST_RTSP_OK) {
6555 segment->rate = gst_rtspsrc_get_float (hval);
6556 } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6557 &hval, 0) == GST_RTSP_OK) {
6558 segment->rate = gst_rtspsrc_get_float (hval);
6561 /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6562 * for the RTP packets. If this is not present, we assume all starts from 0...
6563 * This is info for the RTP session manager that we pass to it in caps. */
6565 while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6566 &hval, hval_idx++) == GST_RTSP_OK)
6567 gst_rtspsrc_parse_rtpinfo (src, hval);
6569 /* some servers indicate RTCP parameters in PLAY response,
6570 * rather than properly in SDP */
6571 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6572 &hval, 0) == GST_RTSP_OK)
6573 gst_rtspsrc_handle_rtcp_interval (src, hval);
6575 gst_rtsp_message_unset (&response);
6577 /* early exit when we did aggregate control */
6581 /* configure the caps of the streams after we parsed all headers. Only reset
6582 * the manager object when we set a new Range header (we did a seek) */
6583 gst_rtspsrc_configure_caps (src, segment, src->need_range);
6585 /* set again when needed */
6586 src->need_range = FALSE;
6588 src->running = TRUE;
6589 src->base_time = -1;
6590 src->state = GST_RTSP_STATE_PLAYING;
6593 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6594 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6595 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6596 stream->discont = TRUE;
6601 gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6608 GST_DEBUG_OBJECT (src, "failed to open stream");
6613 GST_DEBUG_OBJECT (src, "PLAY is not supported");
6618 GST_DEBUG_OBJECT (src, "we were already PLAYING");
6621 create_request_failed:
6623 gchar *str = gst_rtsp_strresult (res);
6625 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6626 ("Could not create request. (%s)", str));
6632 gchar *str = gst_rtsp_strresult (res);
6634 gst_rtsp_message_unset (&request);
6635 if (res != GST_RTSP_EINTR) {
6636 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6637 ("Could not send message. (%s)", str));
6639 GST_WARNING_OBJECT (src, "PLAY interrupted");
6646 static GstRTSPResult
6647 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
6649 GstRTSPResult res = GST_RTSP_OK;
6650 GstRTSPMessage request = { 0 };
6651 GstRTSPMessage response = { 0 };
6655 GST_DEBUG_OBJECT (src, "PAUSE...");
6657 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6660 if (!(src->methods & GST_RTSP_PAUSE))
6663 if (src->state == GST_RTSP_STATE_READY)
6666 if (!src->conninfo.connection || !src->conninfo.connected)
6669 /* construct a control url */
6671 control = src->control;
6673 control = src->conninfo.url_str;
6675 /* loop over the streams. We might exit the loop early when we could do an
6676 * aggregate control */
6677 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6678 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6679 GstRTSPConnection *conn;
6682 /* try aggregate control first but do non-aggregate control otherwise */
6684 setup_url = control;
6685 else if ((setup_url = stream->conninfo.location) == NULL)
6688 if (src->conninfo.connection) {
6689 conn = src->conninfo.connection;
6690 } else if (stream->conninfo.connection) {
6691 conn = stream->conninfo.connection;
6697 GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6698 ("Sending PAUSE request"));
6701 gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6703 goto create_request_failed;
6705 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6708 gst_rtsp_message_unset (&request);
6709 gst_rtsp_message_unset (&response);
6711 /* exit early when we did agregate control */
6716 /* change element states now */
6717 gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
6720 src->state = GST_RTSP_STATE_READY;
6724 gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6731 GST_DEBUG_OBJECT (src, "failed to open stream");
6736 GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6741 GST_DEBUG_OBJECT (src, "we were already PAUSED");
6744 create_request_failed:
6746 gchar *str = gst_rtsp_strresult (res);
6748 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6749 ("Could not create request. (%s)", str));
6755 gchar *str = gst_rtsp_strresult (res);
6757 gst_rtsp_message_unset (&request);
6758 if (res != GST_RTSP_EINTR) {
6759 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6760 ("Could not send message. (%s)", str));
6762 GST_WARNING_OBJECT (src, "PAUSE interrupted");
6770 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6772 GstRTSPSrc *rtspsrc;
6774 rtspsrc = GST_RTSPSRC (bin);
6776 switch (GST_MESSAGE_TYPE (message)) {
6777 case GST_MESSAGE_EOS:
6778 gst_message_unref (message);
6780 case GST_MESSAGE_ELEMENT:
6782 const GstStructure *s = gst_message_get_structure (message);
6784 if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6785 gboolean ignore_timeout;
6787 GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6789 GST_OBJECT_LOCK (rtspsrc);
6790 ignore_timeout = rtspsrc->ignore_timeout;
6791 rtspsrc->ignore_timeout = TRUE;
6792 GST_OBJECT_UNLOCK (rtspsrc);
6794 /* we only act on the first udp timeout message, others are irrelevant
6795 * and can be ignored. */
6796 if (!ignore_timeout)
6797 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
6799 gst_message_unref (message);
6802 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6805 case GST_MESSAGE_ERROR:
6808 GstRTSPStream *stream;
6811 udpsrc = GST_MESSAGE_SRC (message);
6813 GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6814 GST_ELEMENT_NAME (udpsrc));
6816 stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6820 /* we ignore the RTCP udpsrc */
6821 if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6824 /* if we get error messages from the udp sources, that's not a problem as
6825 * long as not all of them error out. We also don't really know what the
6826 * problem is, the message does not give enough detail... */
6827 ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6828 GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
6829 if (ret != GST_FLOW_OK)
6833 gst_message_unref (message);
6837 /* fatal but not our message, forward */
6838 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6843 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6849 /* the thread where everything happens */
6851 gst_rtspsrc_thread (GstRTSPSrc * src)
6855 GST_OBJECT_LOCK (src);
6856 cmd = src->pending_cmd;
6857 if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
6859 src->pending_cmd = CMD_LOOP;
6861 src->pending_cmd = CMD_WAIT;
6862 GST_DEBUG_OBJECT (src, "got command %d", cmd);
6864 /* we got the message command, so ensure communication is possible again */
6865 gst_rtspsrc_connection_flush (src, FALSE);
6867 src->busy_cmd = cmd;
6868 GST_OBJECT_UNLOCK (src);
6872 gst_rtspsrc_open (src, TRUE);
6875 gst_rtspsrc_play (src, &src->segment, TRUE);
6878 gst_rtspsrc_pause (src, TRUE);
6881 gst_rtspsrc_close (src, TRUE, FALSE);
6884 gst_rtspsrc_loop (src);
6887 gst_rtspsrc_reconnect (src, FALSE);
6893 GST_OBJECT_LOCK (src);
6894 /* and go back to sleep */
6895 if (src->pending_cmd == CMD_WAIT) {
6897 gst_task_pause (src->task);
6900 src->busy_cmd = CMD_WAIT;
6901 GST_OBJECT_UNLOCK (src);
6905 gst_rtspsrc_start (GstRTSPSrc * src)
6907 GST_DEBUG_OBJECT (src, "starting");
6909 GST_OBJECT_LOCK (src);
6911 src->pending_cmd = CMD_WAIT;
6913 if (src->task == NULL) {
6914 src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
6915 if (src->task == NULL)
6918 gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
6920 GST_OBJECT_UNLOCK (src);
6927 GST_ERROR_OBJECT (src, "failed to create task");
6933 gst_rtspsrc_stop (GstRTSPSrc * src)
6937 GST_DEBUG_OBJECT (src, "stopping");
6939 /* also cancels pending task */
6940 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
6942 GST_OBJECT_LOCK (src);
6943 if ((task = src->task)) {
6945 GST_OBJECT_UNLOCK (src);
6947 gst_task_stop (task);
6949 /* make sure it is not running */
6950 GST_RTSP_STREAM_LOCK (src);
6951 GST_RTSP_STREAM_UNLOCK (src);
6953 /* now wait for the task to finish */
6954 gst_task_join (task);
6956 /* and free the task */
6957 gst_object_unref (GST_OBJECT (task));
6959 GST_OBJECT_LOCK (src);
6961 GST_OBJECT_UNLOCK (src);
6963 /* ensure synchronously all is closed and clean */
6964 gst_rtspsrc_close (src, FALSE, TRUE);
6969 static GstStateChangeReturn
6970 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
6972 GstRTSPSrc *rtspsrc;
6973 GstStateChangeReturn ret;
6975 rtspsrc = GST_RTSPSRC (element);
6977 switch (transition) {
6978 case GST_STATE_CHANGE_NULL_TO_READY:
6979 if (!gst_rtspsrc_start (rtspsrc))
6982 case GST_STATE_CHANGE_READY_TO_PAUSED:
6983 /* init some state */
6984 rtspsrc->cur_protocols = rtspsrc->protocols;
6985 /* first attempt, don't ignore timeouts */
6986 rtspsrc->ignore_timeout = FALSE;
6987 rtspsrc->open_error = FALSE;
6988 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
6990 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6991 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6992 /* unblock the tcp tasks and make the loop waiting */
6993 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP);
6994 /* make sure it is waiting before we send PAUSE or PLAY below */
6995 GST_RTSP_STREAM_LOCK (rtspsrc);
6996 GST_RTSP_STREAM_UNLOCK (rtspsrc);
6998 case GST_STATE_CHANGE_PAUSED_TO_READY:
7004 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7005 if (ret == GST_STATE_CHANGE_FAILURE)
7008 switch (transition) {
7009 case GST_STATE_CHANGE_NULL_TO_READY:
7010 ret = GST_STATE_CHANGE_SUCCESS;
7012 case GST_STATE_CHANGE_READY_TO_PAUSED:
7013 ret = GST_STATE_CHANGE_NO_PREROLL;
7015 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7016 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7017 ret = GST_STATE_CHANGE_SUCCESS;
7019 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7020 /* send pause request and keep the idle task around */
7021 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7022 ret = GST_STATE_CHANGE_NO_PREROLL;
7024 case GST_STATE_CHANGE_PAUSED_TO_READY:
7025 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7026 ret = GST_STATE_CHANGE_SUCCESS;
7028 case GST_STATE_CHANGE_READY_TO_NULL:
7029 gst_rtspsrc_stop (rtspsrc);
7030 ret = GST_STATE_CHANGE_SUCCESS;
7041 GST_DEBUG_OBJECT (rtspsrc, "start failed");
7042 return GST_STATE_CHANGE_FAILURE;
7047 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7050 GstRTSPSrc *rtspsrc;
7052 rtspsrc = GST_RTSPSRC (element);
7054 if (GST_EVENT_IS_DOWNSTREAM (event)) {
7055 res = gst_rtspsrc_push_event (rtspsrc, event);
7057 res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7064 /*** GSTURIHANDLER INTERFACE *************************************************/
7067 gst_rtspsrc_uri_get_type (GType type)
7072 static const gchar *const *
7073 gst_rtspsrc_uri_get_protocols (GType type)
7075 static const gchar *protocols[] =
7076 { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7077 "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7084 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7086 GstRTSPSrc *src = GST_RTSPSRC (handler);
7088 /* FIXME: make thread-safe */
7089 return g_strdup (src->conninfo.location);
7093 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7098 GstRTSPUrl *newurl = NULL;
7099 GstSDPMessage *sdp = NULL;
7101 src = GST_RTSPSRC (handler);
7103 /* same URI, we're fine */
7104 if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7107 if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7108 if ((res = gst_sdp_message_new (&sdp) < 0))
7111 GST_DEBUG_OBJECT (src, "parsing SDP message");
7112 if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7116 GST_DEBUG_OBJECT (src, "parsing URI");
7117 if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7121 /* if worked, free previous and store new url object along with the original
7123 GST_DEBUG_OBJECT (src, "configuring URI");
7124 g_free (src->conninfo.location);
7125 src->conninfo.location = g_strdup (uri);
7126 gst_rtsp_url_free (src->conninfo.url);
7127 src->conninfo.url = newurl;
7128 g_free (src->conninfo.url_str);
7130 src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7132 src->conninfo.url_str = NULL;
7135 gst_sdp_message_free (src->sdp);
7137 src->from_sdp = sdp != NULL;
7139 GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7140 GST_DEBUG_OBJECT (src, "request uri is: %s",
7141 GST_STR_NULL (src->conninfo.url_str));
7148 GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7153 GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7154 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7155 "Could not create SDP");
7160 GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7161 GST_STR_NULL (uri));
7162 gst_sdp_message_free (sdp);
7163 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7169 GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7170 GST_STR_NULL (uri), res);
7171 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7172 "Invalid RTSP URI");
7178 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7180 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7182 iface->get_type = gst_rtspsrc_uri_get_type;
7183 iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7184 iface->get_uri = gst_rtspsrc_uri_get_uri;
7185 iface->set_uri = gst_rtspsrc_uri_set_uri;