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) {
3635 GST_DEBUG_OBJECT (src, "connection flush");
3636 gst_rtsp_connection_flush (src->conninfo.connection, flush);
3638 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3639 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3640 GST_DEBUG_OBJECT (src, "stream %p flush", stream);
3641 if (stream->conninfo.connection)
3642 gst_rtsp_connection_flush (stream->conninfo.connection, flush);
3644 GST_RTSP_STATE_UNLOCK (src);
3647 /* FIXME, handle server request, reply with OK, for now */
3648 static GstRTSPResult
3649 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
3650 GstRTSPMessage * request)
3652 GstRTSPMessage response = { 0 };
3655 GST_DEBUG_OBJECT (src, "got server request message");
3658 gst_rtsp_message_dump (request);
3660 res = gst_rtsp_ext_list_receive_request (src->extensions, request);
3662 if (res == GST_RTSP_ENOTIMPL) {
3663 /* default implementation, send OK */
3664 GST_DEBUG_OBJECT (src, "prepare OK reply");
3666 gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
3671 /* let app parse and reply */
3672 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
3673 0, request, response);
3676 gst_rtsp_message_dump (&response);
3678 res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
3682 gst_rtsp_message_unset (&response);
3683 } else if (res == GST_RTSP_EEOF)
3691 gst_rtsp_message_unset (&response);
3696 /* send server keep-alive */
3697 static GstRTSPResult
3698 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
3700 GstRTSPMessage request = { 0 };
3702 GstRTSPMethod method;
3705 if (src->do_rtsp_keep_alive == FALSE) {
3706 GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
3707 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3711 GST_DEBUG_OBJECT (src, "creating server keep-alive");
3713 /* find a method to use for keep-alive */
3714 if (src->methods & GST_RTSP_GET_PARAMETER)
3715 method = GST_RTSP_GET_PARAMETER;
3717 method = GST_RTSP_OPTIONS;
3720 control = src->control;
3722 control = src->conninfo.url_str;
3724 if (control == NULL)
3727 res = gst_rtsp_message_init_request (&request, method, control);
3732 gst_rtsp_message_dump (&request);
3735 gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
3740 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3741 gst_rtsp_message_unset (&request);
3748 GST_WARNING_OBJECT (src, "no control url to send keepalive");
3753 gchar *str = gst_rtsp_strresult (res);
3755 gst_rtsp_message_unset (&request);
3756 GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
3757 ("Could not send keep-alive. (%s)", str));
3763 static GstFlowReturn
3764 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
3766 GstFlowReturn ret = GST_FLOW_OK;
3768 GstRTSPStream *stream;
3769 GstPad *outpad = NULL;
3776 channel = message->type_data.data.channel;
3778 stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
3780 goto unknown_stream;
3782 if (channel == stream->channel[0]) {
3783 outpad = stream->channelpad[0];
3785 } else if (channel == stream->channel[1]) {
3786 outpad = stream->channelpad[1];
3792 /* take a look at the body to figure out what we have */
3793 gst_rtsp_message_get_body (message, &data, &size);
3795 goto invalid_length;
3797 /* channels are not correct on some servers, do extra check */
3798 if (data[1] >= 200 && data[1] <= 204) {
3799 /* hmm RTCP message switch to the RTCP pad of the same stream. */
3800 outpad = stream->channelpad[1];
3804 /* we have no clue what this is, just ignore then. */
3806 goto unknown_stream;
3808 /* take the message body for further processing */
3809 gst_rtsp_message_steal_body (message, &data, &size);
3811 /* strip the trailing \0 */
3814 buf = gst_buffer_new ();
3815 gst_buffer_append_memory (buf,
3816 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
3818 /* don't need message anymore */
3819 gst_rtsp_message_unset (message);
3821 GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
3824 if (src->need_activate) {
3830 /* generate an SHA256 sum of the URI */
3831 cs = g_checksum_new (G_CHECKSUM_SHA256);
3832 uri = src->conninfo.location;
3833 g_checksum_update (cs, (const guchar *) uri, strlen (uri));
3835 g_strdup_printf ("%s/%d", g_checksum_get_string (cs), stream->id);
3836 g_checksum_free (cs);
3837 event = gst_event_new_stream_start (stream_id);
3839 gst_rtspsrc_push_event (src, event);
3841 gst_rtspsrc_activate_streams (src);
3842 src->need_activate = FALSE;
3844 if ((event = src->start_segment) != NULL) {
3845 src->start_segment = NULL;
3846 gst_rtspsrc_push_event (src, event);
3849 if (src->base_time == -1) {
3850 /* Take current running_time. This timestamp will be put on
3851 * the first buffer of each stream because we are a live source and so we
3852 * timestamp with the running_time. When we are dealing with TCP, we also
3853 * only timestamp the first buffer (using the DISCONT flag) because a server
3854 * typically bursts data, for which we don't want to compensate by speeding
3855 * up the media. The other timestamps will be interpollated from this one
3856 * using the RTP timestamps. */
3857 GST_OBJECT_LOCK (src);
3858 if (GST_ELEMENT_CLOCK (src)) {
3860 GstClockTime base_time;
3862 now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
3863 base_time = GST_ELEMENT_CAST (src)->base_time;
3865 src->base_time = now - base_time;
3867 GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
3868 GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
3870 GST_OBJECT_UNLOCK (src);
3873 if (stream->discont && !is_rtcp) {
3874 /* mark first RTP buffer as discont */
3875 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3876 stream->discont = FALSE;
3877 /* first buffer gets the timestamp, other buffers are not timestamped and
3878 * their presentation time will be interpollated from the rtp timestamps. */
3879 GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
3880 GST_TIME_ARGS (src->base_time));
3882 GST_BUFFER_TIMESTAMP (buf) = src->base_time;
3885 /* chain to the peer pad */
3886 if (GST_PAD_IS_SINK (outpad))
3887 ret = gst_pad_chain (outpad, buf);
3889 ret = gst_pad_push (outpad, buf);
3892 /* combine all stream flows for the data transport */
3893 ret = gst_rtspsrc_combine_flows (src, stream, ret);
3900 GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
3901 gst_rtsp_message_unset (message);
3906 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3907 ("Short message received, ignoring."));
3908 gst_rtsp_message_unset (message);
3913 static GstFlowReturn
3914 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
3916 GstRTSPMessage message = { 0 };
3918 GstFlowReturn ret = GST_FLOW_OK;
3919 GTimeVal tv_timeout;
3922 /* get the next timeout interval */
3923 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3925 /* see if the timeout period expired */
3926 if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
3927 GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
3928 /* send keep-alive, only act on interrupt, a warning will be posted for
3930 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3932 /* get new timeout */
3933 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3936 GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
3937 tv_timeout.tv_sec, tv_timeout.tv_usec);
3939 /* protect the connection with the connection lock so that we can see when
3940 * we are finished doing server communication */
3942 gst_rtspsrc_connection_receive (src, src->conninfo.connection,
3943 &message, src->ptcp_timeout);
3947 GST_DEBUG_OBJECT (src, "we received a server message");
3949 case GST_RTSP_EINTR:
3950 /* we got interrupted this means we need to stop */
3952 case GST_RTSP_ETIMEOUT:
3953 /* no reply, send keep alive */
3954 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
3955 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3959 /* go EOS when the server closed the connection */
3965 switch (message.type) {
3966 case GST_RTSP_MESSAGE_REQUEST:
3967 /* server sends us a request message, handle it */
3969 gst_rtspsrc_handle_request (src, src->conninfo.connection,
3971 if (res == GST_RTSP_EEOF)
3974 goto handle_request_failed;
3976 case GST_RTSP_MESSAGE_RESPONSE:
3977 /* we ignore response messages */
3978 GST_DEBUG_OBJECT (src, "ignoring response message");
3980 gst_rtsp_message_dump (&message);
3982 case GST_RTSP_MESSAGE_DATA:
3983 GST_DEBUG_OBJECT (src, "got data message");
3984 ret = gst_rtspsrc_handle_data (src, &message);
3985 if (ret != GST_FLOW_OK)
3986 goto handle_data_failed;
3989 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
3994 g_assert_not_reached ();
3999 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4000 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4001 ("The server closed the connection."));
4002 src->conninfo.connected = FALSE;
4003 gst_rtsp_message_unset (&message);
4004 return GST_FLOW_EOS;
4008 gst_rtsp_message_unset (&message);
4009 GST_DEBUG_OBJECT (src, "got interrupted: stop connection flush");
4010 gst_rtspsrc_connection_flush (src, FALSE);
4011 return GST_FLOW_FLUSHING;
4015 gchar *str = gst_rtsp_strresult (res);
4017 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4018 ("Could not receive message. (%s)", str));
4021 gst_rtsp_message_unset (&message);
4022 return GST_FLOW_ERROR;
4024 handle_request_failed:
4026 gchar *str = gst_rtsp_strresult (res);
4028 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4029 ("Could not handle server message. (%s)", str));
4031 gst_rtsp_message_unset (&message);
4032 return GST_FLOW_ERROR;
4036 GST_DEBUG_OBJECT (src, "could no handle data message");
4041 static GstFlowReturn
4042 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4045 GstRTSPMessage message = { 0 };
4049 GTimeVal tv_timeout;
4051 /* get the next timeout interval */
4052 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4054 GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4055 (gint) tv_timeout.tv_sec);
4057 gst_rtsp_message_unset (&message);
4059 /* we should continue reading the TCP socket because the server might
4060 * send us requests. When the session timeout expires, we need to send a
4061 * keep-alive request to keep the session open. */
4062 res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4063 &message, &tv_timeout);
4067 GST_DEBUG_OBJECT (src, "we received a server message");
4069 case GST_RTSP_EINTR:
4070 /* we got interrupted, see what we have to do */
4072 case GST_RTSP_ETIMEOUT:
4073 /* send keep-alive, ignore the result, a warning will be posted. */
4074 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4075 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4079 /* server closed the connection. not very fatal for UDP, reconnect and
4080 * see what happens. */
4081 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4082 ("The server closed the connection."));
4083 if (src->udp_reconnect) {
4085 gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4092 GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4094 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4095 ("Unhandled return value %d.", res));
4099 switch (message.type) {
4100 case GST_RTSP_MESSAGE_REQUEST:
4101 /* server sends us a request message, handle it */
4103 gst_rtspsrc_handle_request (src, src->conninfo.connection,
4105 if (res == GST_RTSP_EEOF)
4108 goto handle_request_failed;
4110 case GST_RTSP_MESSAGE_RESPONSE:
4111 /* we ignore response and data messages */
4112 GST_DEBUG_OBJECT (src, "ignoring response message");
4114 gst_rtsp_message_dump (&message);
4115 if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4116 GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4117 if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4118 GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4119 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4126 case GST_RTSP_MESSAGE_DATA:
4127 /* we ignore response and data messages */
4128 GST_DEBUG_OBJECT (src, "ignoring data message");
4131 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4136 g_assert_not_reached ();
4138 /* we get here when the connection got interrupted */
4141 gst_rtsp_message_unset (&message);
4142 GST_DEBUG_OBJECT (src, "got interrupted: stop connection flush");
4143 gst_rtspsrc_connection_flush (src, FALSE);
4144 return GST_FLOW_FLUSHING;
4148 gchar *str = gst_rtsp_strresult (res);
4151 src->conninfo.connected = FALSE;
4152 if (res != GST_RTSP_EINTR) {
4153 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4154 ("Could not connect to server. (%s)", str));
4156 ret = GST_FLOW_ERROR;
4158 ret = GST_FLOW_FLUSHING;
4164 gchar *str = gst_rtsp_strresult (res);
4166 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4167 ("Could not receive message. (%s)", str));
4169 return GST_FLOW_ERROR;
4171 handle_request_failed:
4173 gchar *str = gst_rtsp_strresult (res);
4176 gst_rtsp_message_unset (&message);
4177 if (res != GST_RTSP_EINTR) {
4178 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4179 ("Could not handle server message. (%s)", str));
4181 ret = GST_FLOW_ERROR;
4183 ret = GST_FLOW_FLUSHING;
4189 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4190 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4191 ("The server closed the connection."));
4192 src->conninfo.connected = FALSE;
4193 gst_rtsp_message_unset (&message);
4194 return GST_FLOW_EOS;
4198 static GstRTSPResult
4199 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4201 GstRTSPResult res = GST_RTSP_OK;
4204 GST_DEBUG_OBJECT (src, "doing reconnect");
4206 GST_OBJECT_LOCK (src);
4207 /* only restart when the pads were not yet activated, else we were
4208 * streaming over UDP */
4209 restart = src->need_activate;
4210 GST_OBJECT_UNLOCK (src);
4212 /* no need to restart, we're done */
4216 /* we can try only TCP now */
4217 src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4219 /* close and cleanup our state */
4220 if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4223 /* see if we have TCP left to try. Also don't try TCP when we were configured
4225 if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4228 /* We post a warning message now to inform the user
4229 * that nothing happened. It's most likely a firewall thing. */
4230 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4231 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4232 "firewall is blocking it. Retrying using a TCP connection.",
4233 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4235 /* open new connection using tcp */
4236 if (gst_rtspsrc_open (src, async) < 0)
4239 /* start playback */
4240 if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4249 src->cur_protocols = 0;
4250 /* no transport possible, post an error and stop */
4251 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4252 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4253 "firewall is blocking it. No other protocols to try.",
4254 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4255 return GST_RTSP_ERROR;
4259 GST_DEBUG_OBJECT (src, "open failed");
4264 GST_DEBUG_OBJECT (src, "play failed");
4270 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4274 GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4277 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4280 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4283 GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4291 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4295 GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4298 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4301 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4304 GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4312 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4316 GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4319 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4322 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4325 GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4333 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4337 GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4340 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4343 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4346 GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4354 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4356 if (ret == GST_RTSP_OK)
4357 gst_rtspsrc_loop_complete_cmd (src, cmd);
4358 else if (ret == GST_RTSP_EINTR)
4359 gst_rtspsrc_loop_cancel_cmd (src, cmd);
4361 gst_rtspsrc_loop_error_cmd (src, cmd);
4365 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4369 /* start new request */
4370 gst_rtspsrc_loop_start_cmd (src, cmd);
4372 GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4374 GST_OBJECT_LOCK (src);
4375 old = src->pending_cmd;
4376 if (old == CMD_RECONNECT) {
4377 GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4378 cmd = CMD_RECONNECT;
4380 if (old != CMD_WAIT) {
4381 src->pending_cmd = CMD_WAIT;
4382 GST_OBJECT_UNLOCK (src);
4383 /* cancel previous request */
4384 GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4385 gst_rtspsrc_loop_cancel_cmd (src, old);
4386 GST_OBJECT_LOCK (src);
4388 src->pending_cmd = cmd;
4389 /* interrupt if allowed */
4390 if (src->busy_cmd & mask) {
4391 GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4392 gst_rtspsrc_connection_flush (src, TRUE);
4394 GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4397 gst_task_start (src->task);
4398 GST_OBJECT_UNLOCK (src);
4402 gst_rtspsrc_loop (GstRTSPSrc * src)
4406 if (!src->conninfo.connection || !src->conninfo.connected)
4409 if (src->interleaved)
4410 ret = gst_rtspsrc_loop_interleaved (src);
4412 ret = gst_rtspsrc_loop_udp (src);
4414 if (ret != GST_FLOW_OK)
4422 GST_WARNING_OBJECT (src, "we are not connected");
4423 ret = GST_FLOW_FLUSHING;
4428 const gchar *reason = gst_flow_get_name (ret);
4430 GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4431 src->running = FALSE;
4432 if (ret == GST_FLOW_EOS) {
4433 /* perform EOS logic */
4434 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4435 gst_element_post_message (GST_ELEMENT_CAST (src),
4436 gst_message_new_segment_done (GST_OBJECT_CAST (src),
4437 src->segment.format, src->segment.position));
4438 gst_rtspsrc_push_event (src,
4439 gst_event_new_segment_done (src->segment.format,
4440 src->segment.position));
4442 gst_rtspsrc_push_event (src, gst_event_new_eos ());
4444 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4445 /* for fatal errors we post an error message, post the error before the
4446 * EOS so the app knows about the error first. */
4447 GST_ELEMENT_ERROR (src, STREAM, FAILED,
4448 ("Internal data flow error."),
4449 ("streaming task paused, reason %s (%d)", reason, ret));
4450 gst_rtspsrc_push_event (src, gst_event_new_eos ());
4452 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
4457 #ifndef GST_DISABLE_GST_DEBUG
4458 static const gchar *
4459 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4463 while (method != 0) {
4480 static const gchar *
4481 gst_rtspsrc_skip_lws (const gchar * s)
4483 while (g_ascii_isspace (*s))
4488 static const gchar *
4489 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4491 while (s > start && g_ascii_isspace (*(s - 1)))
4496 static const gchar *
4497 gst_rtspsrc_skip_commas (const gchar * s)
4499 /* The grammar allows for multiple commas */
4500 while (g_ascii_isspace (*s) || *s == ',')
4505 static const gchar *
4506 gst_rtspsrc_skip_item (const gchar * s)
4508 gboolean quoted = FALSE;
4509 const gchar *start = s;
4511 /* A list item ends at the last non-whitespace character
4512 * before a comma which is not inside a quoted-string. Or at
4513 * the end of the string.
4519 if (*s == '\\' && *(s + 1))
4528 return gst_rtspsrc_unskip_lws (s, start);
4532 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4536 src = quoted_string + 1;
4537 dst = quoted_string;
4538 while (*src && *src != '"') {
4539 if (*src == '\\' && *(src + 1))
4546 /* Extract the authentication tokens that the server provided for each method
4547 * into an array of structures and give those to the connection object.
4550 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4551 const gchar * header, gboolean * stale)
4553 GSList *list = NULL, *iter;
4555 gchar *item, *eq, *name_end, *value;
4557 g_return_if_fail (stale != NULL);
4559 gst_rtsp_connection_clear_auth_params (conn);
4562 /* Parse a header whose content is described by RFC2616 as
4563 * "#something", where "something" does not itself contain commas,
4564 * except as part of quoted-strings, into a list of allocated strings.
4566 header = gst_rtspsrc_skip_commas (header);
4568 end = gst_rtspsrc_skip_item (header);
4569 list = g_slist_prepend (list, g_strndup (header, end - header));
4570 header = gst_rtspsrc_skip_commas (end);
4575 list = g_slist_reverse (list);
4576 for (iter = list; iter; iter = iter->next) {
4579 eq = strchr (item, '=');
4581 name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4582 if (name_end == item) {
4583 /* That's no good... */
4590 value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4592 gst_rtsp_decode_quoted_string (value);
4596 if (item && (strcmp (item, "stale") == 0) &&
4597 value && (strcmp (value, "TRUE") == 0))
4599 gst_rtsp_connection_set_auth_param (conn, item, value);
4603 g_slist_free (list);
4606 /* Parse a WWW-Authenticate Response header and determine the
4607 * available authentication methods
4609 * This code should also cope with the fact that each WWW-Authenticate
4610 * header can contain multiple challenge methods + tokens
4612 * At the moment, for Basic auth, we just do a minimal check and don't
4613 * even parse out the realm */
4615 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4616 GstRTSPConnection * conn, gboolean * stale)
4620 g_return_if_fail (hdr != NULL);
4621 g_return_if_fail (methods != NULL);
4622 g_return_if_fail (stale != NULL);
4624 /* Skip whitespace at the start of the string */
4625 for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4627 if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4628 *methods |= GST_RTSP_AUTH_BASIC;
4629 else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4630 *methods |= GST_RTSP_AUTH_DIGEST;
4631 gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4636 * gst_rtspsrc_setup_auth:
4637 * @src: the rtsp source
4639 * Configure a username and password and auth method on the
4640 * connection object based on a response we received from the
4643 * Currently, this requires that a username and password were supplied
4644 * in the uri. In the future, they may be requested on demand by sending
4645 * a message up the bus.
4647 * Returns: TRUE if authentication information could be set up correctly.
4650 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4654 GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4655 GstRTSPAuthMethod method;
4656 GstRTSPResult auth_result;
4658 GstRTSPConnection *conn;
4660 gboolean stale = FALSE;
4662 conn = src->conninfo.connection;
4664 /* Identify the available auth methods and see if any are supported */
4665 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4666 &hdr, 0) == GST_RTSP_OK) {
4667 gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4670 if (avail_methods == GST_RTSP_AUTH_NONE)
4671 goto no_auth_available;
4673 /* For digest auth, if the response indicates that the session
4674 * data are stale, we just update them in the connection object and
4675 * return TRUE to retry the request */
4677 src->tried_url_auth = FALSE;
4679 url = gst_rtsp_connection_get_url (conn);
4681 /* Do we have username and password available? */
4682 if (url != NULL && !src->tried_url_auth && url->user != NULL
4683 && url->passwd != NULL) {
4686 src->tried_url_auth = TRUE;
4687 GST_DEBUG_OBJECT (src,
4688 "Attempting authentication using credentials from the URL");
4690 user = src->user_id;
4691 pass = src->user_pw;
4692 GST_DEBUG_OBJECT (src,
4693 "Attempting authentication using credentials from the properties");
4696 /* FIXME: If the url didn't contain username and password or we tried them
4697 * already, request a username and passwd from the application via some kind
4698 * of credentials request message */
4700 /* If we don't have a username and passwd at this point, bail out. */
4701 if (user == NULL || pass == NULL)
4704 /* Try to configure for each available authentication method, strongest to
4706 for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4707 /* Check if this method is available on the server */
4708 if ((method & avail_methods) == 0)
4711 /* Pass the credentials to the connection to try on the next request */
4712 auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4713 /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4714 * ignore it and end up retrying later */
4715 if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4716 GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4717 gst_rtsp_auth_method_to_string (method));
4722 if (method == GST_RTSP_AUTH_NONE)
4723 goto no_auth_available;
4729 /* Output an error indicating that we couldn't connect because there were
4730 * no supported authentication protocols */
4731 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4732 ("No supported authentication protocol was found"));
4737 /* We don't fire an error message, we just return FALSE and let the
4738 * normal NOT_AUTHORIZED error be propagated */
4743 static GstRTSPResult
4744 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4745 GstRTSPMessage * request, GstRTSPMessage * response,
4746 GstRTSPStatusCode * code)
4749 GstRTSPStatusCode thecode;
4750 gchar *content_base = NULL;
4754 if (!src->short_header)
4755 gst_rtsp_ext_list_before_send (src->extensions, request);
4757 GST_DEBUG_OBJECT (src, "sending message");
4760 gst_rtsp_message_dump (request);
4762 res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4766 gst_rtsp_connection_reset_timeout (conn);
4769 res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4774 gst_rtsp_message_dump (response);
4776 switch (response->type) {
4777 case GST_RTSP_MESSAGE_REQUEST:
4778 res = gst_rtspsrc_handle_request (src, conn, response);
4779 if (res == GST_RTSP_EEOF)
4782 goto handle_request_failed;
4784 case GST_RTSP_MESSAGE_RESPONSE:
4785 /* ok, a response is good */
4786 GST_DEBUG_OBJECT (src, "received response message");
4788 case GST_RTSP_MESSAGE_DATA:
4789 /* get next response */
4790 GST_DEBUG_OBJECT (src, "handle data response message");
4791 gst_rtspsrc_handle_data (src, response);
4794 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4799 thecode = response->type_data.response.code;
4801 GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4803 /* if the caller wanted the result code, we store it. */
4807 /* If the request didn't succeed, bail out before doing any more */
4808 if (thecode != GST_RTSP_STS_OK)
4811 /* store new content base if any */
4812 gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4815 g_free (src->content_base);
4816 src->content_base = g_strdup (content_base);
4818 gst_rtsp_ext_list_after_send (src->extensions, request, response);
4825 gchar *str = gst_rtsp_strresult (res);
4827 if (res != GST_RTSP_EINTR) {
4828 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4829 ("Could not send message. (%s)", str));
4831 GST_WARNING_OBJECT (src, "send interrupted");
4840 GST_WARNING_OBJECT (src, "server closed connection");
4841 if ((try == 0) && !src->interleaved && src->udp_reconnect) {
4843 /* if reconnect succeeds, try again */
4845 gst_rtsp_conninfo_reconnect (src, &src->conninfo,
4849 /* only try once after reconnect, then fallthrough and error out */
4852 gchar *str = gst_rtsp_strresult (res);
4854 if (res != GST_RTSP_EINTR) {
4855 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4856 ("Could not receive message. (%s)", str));
4858 GST_WARNING_OBJECT (src, "receive interrupted");
4866 handle_request_failed:
4868 /* ERROR was posted */
4869 gst_rtsp_message_unset (response);
4874 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4875 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4876 ("The server closed the connection."));
4877 gst_rtsp_message_unset (response);
4884 * @src: the rtsp source
4885 * @conn: the connection to send on
4886 * @request: must point to a valid request
4887 * @response: must point to an empty #GstRTSPMessage
4888 * @code: an optional code result
4890 * send @request and retrieve the response in @response. optionally @code can be
4891 * non-NULL in which case it will contain the status code of the response.
4893 * If This function returns #GST_RTSP_OK, @response will contain a valid response
4894 * message that should be cleaned with gst_rtsp_message_unset() after usage.
4896 * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
4897 * @response message) if the response code was not 200 (OK).
4899 * If the attempt results in an authentication failure, then this will attempt
4900 * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
4903 * Returns: #GST_RTSP_OK if the processing was successful.
4905 static GstRTSPResult
4906 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4907 GstRTSPMessage * request, GstRTSPMessage * response,
4908 GstRTSPStatusCode * code)
4910 GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
4911 GstRTSPResult res = GST_RTSP_ERROR;
4914 GstRTSPMethod method = GST_RTSP_INVALID;
4920 /* make sure we don't loop forever */
4924 /* save method so we can disable it when the server complains */
4925 method = request->type_data.request.method;
4928 gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
4932 case GST_RTSP_STS_UNAUTHORIZED:
4933 if (gst_rtspsrc_setup_auth (src, response)) {
4934 /* Try the request/response again after configuring the auth info
4942 } while (retry == TRUE);
4944 /* If the user requested the code, let them handle errors, otherwise
4945 * post an error below */
4948 else if (int_code != GST_RTSP_STS_OK)
4949 goto error_response;
4956 GST_DEBUG_OBJECT (src, "got error %d", res);
4961 res = GST_RTSP_ERROR;
4963 switch (response->type_data.response.code) {
4964 case GST_RTSP_STS_NOT_FOUND:
4965 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
4966 response->type_data.response.reason));
4968 case GST_RTSP_STS_MOVED_PERMANENTLY:
4969 case GST_RTSP_STS_MOVE_TEMPORARILY:
4971 gchar *new_location;
4972 GstRTSPLowerTrans transports;
4974 GST_DEBUG_OBJECT (src, "got redirection");
4975 /* if we don't have a Location Header, we must error */
4976 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
4977 &new_location, 0) < 0)
4980 /* When we receive a redirect result, we go back to the INIT state after
4981 * parsing the new URI. The caller should do the needed steps to issue
4982 * a new setup when it detects this state change. */
4983 GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
4985 /* save current transports */
4986 if (src->conninfo.url)
4987 transports = src->conninfo.url->transports;
4989 transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
4991 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
4993 /* set old transports */
4994 if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
4995 src->conninfo.url->transports = transports;
4997 src->need_redirect = TRUE;
4998 src->state = GST_RTSP_STATE_INIT;
5002 case GST_RTSP_STS_NOT_ACCEPTABLE:
5003 case GST_RTSP_STS_NOT_IMPLEMENTED:
5004 case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5005 GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5006 gst_rtsp_method_as_text (method));
5007 src->methods &= ~method;
5011 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5012 ("Got error response: %d (%s).", response->type_data.response.code,
5013 response->type_data.response.reason));
5016 /* if we return ERROR we should unset the response ourselves */
5017 if (res == GST_RTSP_ERROR)
5018 gst_rtsp_message_unset (response);
5024 static GstRTSPResult
5025 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5026 GstRTSPMessage * response, GstRTSPSrc * src)
5028 return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5033 /* parse the response and collect all the supported methods. We need this
5034 * information so that we don't try to send an unsupported request to the
5038 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5040 GstRTSPHeaderField field;
5044 /* reset supported methods */
5047 /* Try Allow Header first */
5048 field = GST_RTSP_HDR_ALLOW;
5051 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5052 if (indx == 0 && !respoptions) {
5053 /* if no Allow header was found then try the Public header... */
5054 field = GST_RTSP_HDR_PUBLIC;
5055 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5060 src->methods |= gst_rtsp_options_from_text (respoptions);
5065 if (src->methods == 0) {
5066 /* neither Allow nor Public are required, assume the server supports
5067 * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5069 GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5070 src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5072 /* always assume PLAY, FIXME, extensions should be able to override
5074 src->methods |= GST_RTSP_PLAY;
5075 /* also assume it will support Range */
5076 src->seekable = TRUE;
5078 /* we need describe and setup */
5079 if (!(src->methods & GST_RTSP_DESCRIBE))
5081 if (!(src->methods & GST_RTSP_SETUP))
5089 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5090 ("Server does not support DESCRIBE."));
5095 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5096 ("Server does not support SETUP."));
5101 /* masks to be kept in sync with the hardcoded protocol order of preference
5103 static guint protocol_masks[] = {
5104 GST_RTSP_LOWER_TRANS_UDP,
5105 GST_RTSP_LOWER_TRANS_UDP_MCAST,
5106 GST_RTSP_LOWER_TRANS_TCP,
5110 static GstRTSPResult
5111 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5112 GstRTSPLowerTrans protocols, gchar ** transports)
5116 gboolean add_udp_str;
5121 gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5126 GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5128 /* extension listed transports, use those */
5129 if (*transports != NULL)
5132 /* it's the default */
5133 add_udp_str = FALSE;
5135 /* the default RTSP transports */
5136 result = g_string_new ("");
5137 if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5138 GST_DEBUG_OBJECT (src, "adding UDP unicast");
5140 g_string_append (result, "RTP/AVP");
5142 g_string_append (result, "/UDP");
5143 g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5144 } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5145 GST_DEBUG_OBJECT (src, "adding UDP multicast");
5147 /* we don't have to allocate any UDP ports yet, if the selected transport
5148 * turns out to be multicast we can create them and join the multicast
5149 * group indicated in the transport reply */
5150 if (result->len > 0)
5151 g_string_append (result, ",");
5152 g_string_append (result, "RTP/AVP");
5154 g_string_append (result, "/UDP");
5155 g_string_append (result, ";multicast");
5156 if (src->next_port_num != 0) {
5157 if (src->client_port_range.max > 0 &&
5158 src->next_port_num >= src->client_port_range.max)
5161 g_string_append_printf (result, ";client_port=%d-%d",
5162 src->next_port_num, src->next_port_num + 1);
5164 } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5165 GST_DEBUG_OBJECT (src, "adding TCP");
5167 if (result->len > 0)
5168 g_string_append (result, ",");
5169 g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
5171 *transports = g_string_free (result, FALSE);
5173 GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5180 GST_ERROR ("extension gave error %d", res);
5185 GST_ERROR ("no more ports available");
5186 return GST_RTSP_ERROR;
5190 static GstRTSPResult
5191 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5192 gint orig_rtpport, gint orig_rtcpport)
5195 gint nr_udp, nr_int;
5197 gint rtpport = 0, rtcpport = 0;
5200 src = stream->parent;
5202 /* find number of placeholders first */
5203 if (strstr (*transports, "%%i2"))
5205 else if (strstr (*transports, "%%i1"))
5210 if (strstr (*transports, "%%u2"))
5212 else if (strstr (*transports, "%%u1"))
5217 if (nr_udp == 0 && nr_int == 0)
5221 if (!orig_rtpport || !orig_rtcpport) {
5222 if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5225 rtpport = orig_rtpport;
5226 rtcpport = orig_rtcpport;
5230 str = g_string_new ("");
5232 while ((next = strstr (p, "%%"))) {
5233 g_string_append_len (str, p, next - p);
5234 if (next[2] == 'u') {
5236 g_string_append_printf (str, "%d", rtpport);
5237 else if (next[3] == '2')
5238 g_string_append_printf (str, "%d", rtcpport);
5240 if (next[2] == 'i') {
5242 g_string_append_printf (str, "%d", src->free_channel);
5243 else if (next[3] == '2')
5244 g_string_append_printf (str, "%d", src->free_channel + 1);
5249 /* append final part */
5250 g_string_append (str, p);
5252 g_free (*transports);
5253 *transports = g_string_free (str, FALSE);
5261 GST_ERROR ("failed to allocate udp ports");
5262 return GST_RTSP_ERROR;
5267 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5269 gboolean res = FALSE;
5273 const gchar *enc = NULL;
5275 s = gst_caps_get_structure (stream->caps, 0);
5276 if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5277 res = (strstr (enc, "-REAL") != NULL);
5283 /* Perform the SETUP request for all the streams.
5285 * We ask the server for a specific transport, which initially includes all the
5286 * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5287 * two local UDP ports that we send to the server.
5289 * Once the server replied with a transport, we configure the other streams
5290 * with the same transport.
5292 * This function will also configure the stream for the selected transport,
5293 * which basically means creating the pipeline.
5295 static GstRTSPResult
5296 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5299 GstRTSPResult res = GST_RTSP_ERROR;
5300 GstRTSPMessage request = { 0 };
5301 GstRTSPMessage response = { 0 };
5302 GstRTSPStream *stream = NULL;
5303 GstRTSPLowerTrans protocols;
5304 GstRTSPStatusCode code;
5305 gboolean unsupported_real = FALSE;
5306 gint rtpport, rtcpport;
5310 if (src->conninfo.connection) {
5311 url = gst_rtsp_connection_get_url (src->conninfo.connection);
5312 /* we initially allow all configured lower transports. based on the URL
5313 * transports and the replies from the server we narrow them down. */
5314 protocols = url->transports & src->cur_protocols;
5317 protocols = src->cur_protocols;
5323 /* reset some state */
5324 src->free_channel = 0;
5325 src->interleaved = FALSE;
5326 src->need_activate = FALSE;
5327 /* keep track of next port number, 0 is random */
5328 src->next_port_num = src->client_port_range.min;
5329 rtpport = rtcpport = 0;
5331 if (G_UNLIKELY (src->streams == NULL))
5334 for (walk = src->streams; walk; walk = g_list_next (walk)) {
5335 GstRTSPConnection *conn;
5340 stream = (GstRTSPStream *) walk->data;
5342 /* see if we need to configure this stream */
5343 if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5344 GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5346 stream->disabled = TRUE;
5350 /* merge/overwrite global caps */
5355 s = gst_caps_get_structure (stream->caps, 0);
5357 num = gst_structure_n_fields (src->props);
5358 for (j = 0; j < num; j++) {
5362 name = gst_structure_nth_field_name (src->props, j);
5363 val = gst_structure_get_value (src->props, name);
5364 gst_structure_set_value (s, name, val);
5366 GST_DEBUG_OBJECT (src, "copied %s", name);
5370 /* skip setup if we have no URL for it */
5371 if (stream->conninfo.location == NULL) {
5372 GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5376 if (src->conninfo.connection == NULL) {
5377 if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5378 GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5381 conn = stream->conninfo.connection;
5383 conn = src->conninfo.connection;
5385 GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5386 stream->conninfo.location);
5388 /* if we have a multicast connection, only suggest multicast from now on */
5389 if (stream->is_multicast)
5390 protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5393 /* first selectable protocol */
5394 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5396 if (!protocol_masks[mask])
5400 GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5401 protocol_masks[mask]);
5402 /* create a string with first transport in line */
5404 res = gst_rtspsrc_create_transports_string (src,
5405 protocols & protocol_masks[mask], &transports);
5406 if (res < 0 || transports == NULL)
5407 goto setup_transport_failed;
5409 if (strlen (transports) == 0) {
5410 g_free (transports);
5411 GST_DEBUG_OBJECT (src, "no transports found");
5416 GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5418 /* replace placeholders with real values, this function will optionally
5419 * allocate UDP ports and other info needed to execute the setup request */
5420 res = gst_rtspsrc_prepare_transports (stream, &transports,
5421 retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5423 g_free (transports);
5424 goto setup_transport_failed;
5427 GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5429 /* create SETUP request */
5431 gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5432 stream->conninfo.location);
5434 g_free (transports);
5435 goto create_request_failed;
5438 /* select transport, copy is made when adding to header so we can free it. */
5439 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5440 g_free (transports);
5442 /* if the user wants a non default RTP packet size we add the blocksize
5444 if (src->rtp_blocksize > 0) {
5445 hval = g_strdup_printf ("%d", src->rtp_blocksize);
5446 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5451 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5454 /* handle the code ourselves */
5455 if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5459 case GST_RTSP_STS_OK:
5461 case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5462 gst_rtsp_message_unset (&request);
5463 gst_rtsp_message_unset (&response);
5464 /* cleanup of leftover transport */
5465 gst_rtspsrc_stream_free_udp (stream);
5466 /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5467 * we might be in this case */
5468 if (stream->container && rtpport && rtcpport && !retry) {
5469 GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5474 /* this transport did not go down well, but we may have others to try
5475 * that we did not send yet, try those and only give up then
5476 * but not without checking for lost cause/extension so we can
5477 * post a nicer/more useful error message later */
5478 if (!unsupported_real)
5479 unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5480 /* select next available protocol, give up on this stream if none */
5482 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5484 if (!protocol_masks[mask] || unsupported_real)
5489 /* cleanup of leftover transport and move to the next stream */
5490 gst_rtspsrc_stream_free_udp (stream);
5491 goto response_error;
5494 /* parse response transport */
5496 gchar *resptrans = NULL;
5497 GstRTSPTransport transport = { 0 };
5499 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5502 gst_rtspsrc_stream_free_udp (stream);
5506 /* parse transport, go to next stream on parse error */
5507 if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5508 GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5512 /* update allowed transports for other streams. once the transport of
5513 * one stream has been determined, we make sure that all other streams
5514 * are configured in the same way */
5515 switch (transport.lower_transport) {
5516 case GST_RTSP_LOWER_TRANS_TCP:
5517 GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5518 protocols = GST_RTSP_LOWER_TRANS_TCP;
5519 src->interleaved = TRUE;
5520 /* update free channels */
5522 MAX (transport.interleaved.min, src->free_channel);
5524 MAX (transport.interleaved.max, src->free_channel);
5525 src->free_channel++;
5527 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5528 /* only allow multicast for other streams */
5529 GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5530 protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5531 /* if the server selected our ports, increment our counters so that
5532 * we select a new port later */
5533 if (src->next_port_num == transport.port.min &&
5534 src->next_port_num + 1 == transport.port.max) {
5535 src->next_port_num += 2;
5538 case GST_RTSP_LOWER_TRANS_UDP:
5539 /* only allow unicast for other streams */
5540 GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5541 protocols = GST_RTSP_LOWER_TRANS_UDP;
5544 GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5545 transport.lower_transport);
5549 if (!stream->container || (!src->interleaved && !retry)) {
5550 /* now configure the stream with the selected transport */
5551 if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5552 GST_DEBUG_OBJECT (src,
5553 "could not configure stream %p transport, skipping stream",
5556 } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5557 /* retain the first allocated UDP port pair */
5558 g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5559 g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5562 /* we need to activate at least one streams when we detect activity */
5563 src->need_activate = TRUE;
5565 /* clean up our transport struct */
5566 gst_rtsp_transport_init (&transport);
5567 /* clean up used RTSP messages */
5568 gst_rtsp_message_unset (&request);
5569 gst_rtsp_message_unset (&response);
5573 /* store the transport protocol that was configured */
5574 src->cur_protocols = protocols;
5576 gst_rtsp_ext_list_stream_select (src->extensions, url);
5578 /* if there is nothing to activate, error out */
5579 if (!src->need_activate)
5580 goto nothing_to_activate;
5587 /* no transport possible, post an error and stop */
5588 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5589 ("Could not connect to server, no protocols left"));
5590 return GST_RTSP_ERROR;
5594 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5595 ("SDP contains no streams"));
5596 return GST_RTSP_ERROR;
5598 create_request_failed:
5600 gchar *str = gst_rtsp_strresult (res);
5602 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5603 ("Could not create request. (%s)", str));
5607 setup_transport_failed:
5609 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5610 ("Could not setup transport."));
5611 res = GST_RTSP_ERROR;
5616 const gchar *str = gst_rtsp_status_as_text (code);
5618 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5619 ("Error (%d): %s", code, GST_STR_NULL (str)));
5620 res = GST_RTSP_ERROR;
5625 gchar *str = gst_rtsp_strresult (res);
5627 if (res != GST_RTSP_EINTR) {
5628 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5629 ("Could not send message. (%s)", str));
5631 GST_WARNING_OBJECT (src, "send interrupted");
5638 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5639 ("Server did not select transport."));
5640 res = GST_RTSP_ERROR;
5643 nothing_to_activate:
5645 /* none of the available error codes is really right .. */
5646 if (unsupported_real) {
5647 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5648 (_("No supported stream was found. You might need to install a "
5649 "GStreamer RTSP extension plugin for Real media streams.")),
5652 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5653 (_("No supported stream was found. You might need to allow "
5654 "more transport protocols or may otherwise be missing "
5655 "the right GStreamer RTSP extension plugin.")), (NULL));
5657 return GST_RTSP_ERROR;
5661 gst_rtsp_message_unset (&request);
5662 gst_rtsp_message_unset (&response);
5668 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5669 GstSegment * segment)
5672 GstRTSPTimeRange *therange;
5675 gst_rtsp_range_free (src->range);
5677 if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5678 GST_DEBUG_OBJECT (src, "parsed range %s", range);
5679 src->range = therange;
5681 GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5683 gst_segment_init (segment, GST_FORMAT_TIME);
5687 GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d, max %f ",
5688 therange->min.type, therange->min.seconds, therange->max.type,
5689 therange->max.seconds);
5691 if (therange->min.type == GST_RTSP_TIME_NOW)
5693 else if (therange->min.type == GST_RTSP_TIME_END)
5696 seconds = therange->min.seconds * GST_SECOND;
5698 GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5699 GST_TIME_ARGS (seconds));
5701 /* we need to start playback without clipping from the position reported by
5703 segment->start = seconds;
5704 segment->position = seconds;
5706 if (therange->max.type == GST_RTSP_TIME_NOW)
5708 else if (therange->max.type == GST_RTSP_TIME_END)
5711 seconds = therange->max.seconds * GST_SECOND;
5713 GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5714 GST_TIME_ARGS (seconds));
5716 /* live (WMS) server might send overflowed large max as its idea of infinity,
5717 * compensate to prevent problems later on */
5718 if (seconds != -1 && seconds < 0) {
5720 GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5723 /* live (WMS) might send min == max, which is not worth recording */
5724 if (segment->duration == -1 && seconds == segment->start)
5727 /* don't change duration with unknown value, we might have a valid value
5728 * there that we want to keep. */
5730 segment->duration = seconds;
5735 /* Parse clock profived by the server with following syntax:
5737 * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
5740 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
5742 gboolean res = FALSE;
5744 if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
5745 gchar **fields = NULL, **parts = NULL;
5746 gchar *remote_ip, *str;
5748 GstClockTime base_time;
5751 fields = g_strsplit (gstclock, " ", 0);
5753 /* wrapped clock, not very interesting for now */
5754 if (fields[1] == NULL)
5757 /* remote IP address and port */
5758 if ((str = fields[2]) == NULL)
5761 parts = g_strsplit (str, ":", 0);
5763 if ((remote_ip = parts[0]) == NULL)
5766 if ((str = parts[1]) == NULL)
5774 if ((str = fields[3]) == NULL)
5777 base_time = g_ascii_strtoull (str, NULL, 10);
5780 gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
5783 if (src->provided_clock)
5784 gst_object_unref (src->provided_clock);
5785 src->provided_clock = netclock;
5787 gst_element_post_message (GST_ELEMENT_CAST (src),
5788 gst_message_new_clock_provide (GST_OBJECT_CAST (src),
5789 src->provided_clock, TRUE));
5793 g_strfreev (fields);
5799 /* must be called with the RTSP state lock */
5800 static GstRTSPResult
5801 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5807 /* prepare global stream caps properties */
5809 gst_structure_remove_all_fields (src->props);
5811 src->props = gst_structure_new_empty ("RTSPProperties");
5814 gst_sdp_message_dump (sdp);
5816 gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5818 gst_segment_init (&src->segment, GST_FORMAT_TIME);
5820 /* parse range for duration reporting. */
5825 range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5829 /* keep track of the range and configure it in the segment */
5830 if (gst_rtspsrc_parse_range (src, range, &src->segment))
5834 /* parse clock information. This is GStreamer specific, a server can tell the
5835 * client what clock it is using and wrap that in a network clock. The
5836 * advantage of that is that we can slave to it. */
5838 const gchar *gstclock;
5841 gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
5842 if (gstclock == NULL)
5845 /* parse the clock and expose it in the provide_clock method */
5846 if (gst_rtspsrc_parse_gst_clock (src, gstclock))
5850 /* try to find a global control attribute. Note that a '*' means that we should
5851 * do aggregate control with the current url (so we don't do anything and
5852 * leave the current connection as is) */
5854 const gchar *control;
5857 control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
5858 if (control == NULL)
5861 /* only take fully qualified urls */
5862 if (g_str_has_prefix (control, "rtsp://"))
5866 g_free (src->conninfo.location);
5867 src->conninfo.location = g_strdup (control);
5868 /* make a connection for this, if there was a connection already, nothing
5870 if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
5871 GST_ERROR_OBJECT (src, "could not connect");
5874 /* we need to keep the control url separate from the connection url because
5875 * the rules for constructing the media control url need it */
5876 g_free (src->control);
5877 src->control = g_strdup (control);
5880 /* create streams */
5881 n_streams = gst_sdp_message_medias_len (sdp);
5882 for (i = 0; i < n_streams; i++) {
5883 gst_rtspsrc_create_stream (src, sdp, i);
5886 src->state = GST_RTSP_STATE_INIT;
5889 if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
5892 /* reset our state */
5893 src->need_range = TRUE;
5896 src->state = GST_RTSP_STATE_READY;
5903 GST_ERROR_OBJECT (src, "setup failed");
5904 gst_rtspsrc_cleanup (src);
5909 static GstRTSPResult
5910 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
5914 GstRTSPMessage request = { 0 };
5915 GstRTSPMessage response = { 0 };
5918 gchar *respcont = NULL;
5921 src->need_redirect = FALSE;
5923 /* can't continue without a valid url */
5924 if (G_UNLIKELY (src->conninfo.url == NULL)) {
5925 res = GST_RTSP_EINVAL;
5928 src->tried_url_auth = FALSE;
5930 if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
5931 goto connect_failed;
5933 /* create OPTIONS */
5934 GST_DEBUG_OBJECT (src, "create options...");
5936 gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
5937 src->conninfo.url_str);
5939 goto create_request_failed;
5942 GST_DEBUG_OBJECT (src, "send options...");
5945 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
5948 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5953 if (!gst_rtspsrc_parse_methods (src, &response))
5956 /* create DESCRIBE */
5957 GST_DEBUG_OBJECT (src, "create describe...");
5959 gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
5960 src->conninfo.url_str);
5962 goto create_request_failed;
5964 /* we only accept SDP for now */
5965 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
5969 GST_DEBUG_OBJECT (src, "send describe...");
5972 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
5975 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5979 /* we only perform redirect for the describe, currently */
5980 if (src->need_redirect) {
5981 /* close connection, we don't have to send a TEARDOWN yet, ignore the
5983 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5985 gst_rtsp_message_unset (&request);
5986 gst_rtsp_message_unset (&response);
5992 /* it could be that the DESCRIBE method was not implemented */
5993 if (!src->methods & GST_RTSP_DESCRIBE)
5996 /* check if reply is SDP */
5997 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
5999 /* could not be set but since the request returned OK, we assume it
6000 * was SDP, else check it. */
6002 if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6003 goto wrong_content_type;
6006 /* get message body and parse as SDP */
6007 gst_rtsp_message_get_body (&response, &data, &size);
6008 if (data == NULL || size == 0)
6011 GST_DEBUG_OBJECT (src, "parse SDP...");
6012 gst_sdp_message_new (sdp);
6013 gst_sdp_message_parse_buffer (data, size, *sdp);
6015 /* clean up any messages */
6016 gst_rtsp_message_unset (&request);
6017 gst_rtsp_message_unset (&response);
6024 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6025 ("No valid RTSP URL was provided"));
6030 gchar *str = gst_rtsp_strresult (res);
6032 if (res != GST_RTSP_EINTR) {
6033 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6034 ("Failed to connect. (%s)", str));
6036 GST_WARNING_OBJECT (src, "connect interrupted");
6041 create_request_failed:
6043 gchar *str = gst_rtsp_strresult (res);
6045 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6046 ("Could not create request. (%s)", str));
6052 /* Don't post a message - the rtsp_send method will have
6053 * taken care of it because we passed NULL for the response code */
6058 /* error was posted */
6059 res = GST_RTSP_ERROR;
6064 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6065 ("Server does not support SDP, got %s.", respcont));
6066 res = GST_RTSP_ERROR;
6071 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6072 ("Server can not provide an SDP."));
6073 res = GST_RTSP_ERROR;
6078 if (src->conninfo.connection) {
6079 GST_DEBUG_OBJECT (src, "free connection");
6080 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6082 gst_rtsp_message_unset (&request);
6083 gst_rtsp_message_unset (&response);
6088 static GstRTSPResult
6089 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6094 GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6096 if (src->sdp == NULL) {
6097 if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6101 if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6106 gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6113 GST_WARNING_OBJECT (src, "can't get sdp");
6114 src->open_error = TRUE;
6119 GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6120 src->open_error = TRUE;
6125 static GstRTSPResult
6126 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6128 GstRTSPMessage request = { 0 };
6129 GstRTSPMessage response = { 0 };
6130 GstRTSPResult res = GST_RTSP_OK;
6134 GST_DEBUG_OBJECT (src, "TEARDOWN...");
6136 gst_rtspsrc_set_state (src, GST_STATE_READY);
6138 if (src->state < GST_RTSP_STATE_READY) {
6139 GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6146 /* construct a control url */
6148 control = src->control;
6150 control = src->conninfo.url_str;
6152 if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6155 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6156 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6158 GstRTSPConnInfo *info;
6160 /* try aggregate control first but do non-aggregate control otherwise */
6162 setup_url = control;
6163 else if ((setup_url = stream->conninfo.location) == NULL)
6166 if (src->conninfo.connection) {
6167 info = &src->conninfo;
6168 } else if (stream->conninfo.connection) {
6169 info = &stream->conninfo;
6173 if (!info->connected)
6178 gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6180 goto create_request_failed;
6183 GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6186 gst_rtspsrc_send (src, info->connection, &request, &response,
6190 /* FIXME, parse result? */
6191 gst_rtsp_message_unset (&request);
6192 gst_rtsp_message_unset (&response);
6195 /* early exit when we did aggregate control */
6201 /* close connections */
6202 GST_DEBUG_OBJECT (src, "closing connection...");
6203 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6204 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6205 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6206 gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6210 gst_rtspsrc_cleanup (src);
6212 src->state = GST_RTSP_STATE_INVALID;
6215 gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6220 create_request_failed:
6222 gchar *str = gst_rtsp_strresult (res);
6224 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6225 ("Could not create request. (%s)", str));
6231 gchar *str = gst_rtsp_strresult (res);
6233 gst_rtsp_message_unset (&request);
6234 if (res != GST_RTSP_EINTR) {
6235 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6236 ("Could not send message. (%s)", str));
6238 GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
6245 GST_DEBUG_OBJECT (src,
6246 "TEARDOWN and PLAY not supported, can't do TEARDOWN");
6251 /* RTP-Info is of the format:
6253 * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
6255 * rtptime corresponds to the timestamp for the NPT time given in the header
6256 * seqbase corresponds to the next sequence number we received. This number
6257 * indicates the first seqnum after the seek and should be used to discard
6258 * packets that are from before the seek.
6261 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
6266 GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
6268 infos = g_strsplit (rtpinfo, ",", 0);
6269 for (i = 0; infos[i]; i++) {
6271 GstRTSPStream *stream;
6275 GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
6277 /* init values, types of seqbase and timebase are bigger than needed so we
6278 * can store -1 as uninitialized values */
6283 /* parse url, find stream for url.
6284 * parse seq and rtptime. The seq number should be configured in the rtp
6285 * depayloader or session manager to detect gaps. Same for the rtptime, it
6286 * should be used to create an initial time newsegment. */
6287 fields = g_strsplit (infos[i], ";", 0);
6288 for (j = 0; fields[j]; j++) {
6289 GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
6290 /* remove leading whitespace */
6291 fields[j] = g_strchug (fields[j]);
6292 if (g_str_has_prefix (fields[j], "url=")) {
6293 /* get the url and the stream */
6295 find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
6296 } else if (g_str_has_prefix (fields[j], "seq=")) {
6297 seqbase = atoi (fields[j] + 4);
6298 } else if (g_str_has_prefix (fields[j], "rtptime=")) {
6299 timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
6302 g_strfreev (fields);
6303 /* now we need to store the values for the caps of the stream */
6304 if (stream != NULL) {
6305 GST_DEBUG_OBJECT (src,
6306 "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
6307 stream, seqbase, timebase);
6309 /* we have a stream, configure detected params */
6310 stream->seqbase = seqbase;
6311 stream->timebase = timebase;
6320 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
6325 interval = strtoul (rtcp, NULL, 10);
6326 GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
6331 interval *= GST_MSECOND;
6333 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6334 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6336 /* already (optionally) retrieved this when configuring manager */
6337 if (stream->session) {
6338 GObject *rtpsession = stream->session;
6340 GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
6342 g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
6346 /* now it happens that (Xenon) server sending this may also provide bogus
6347 * RTCP SR sync data (i.e. with quite some jitter), so never mind those
6348 * and just use RTP-Info to sync */
6350 GObjectClass *klass;
6352 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6353 if (g_object_class_find_property (klass, "rtcp-sync")) {
6354 GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6355 g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6361 gst_rtspsrc_get_float (const gchar * dstr)
6363 gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6365 /* canonicalise floating point string so we can handle float strings
6366 * in the form "24.930" or "24,930" irrespective of the current locale */
6367 g_strlcpy (s, dstr, sizeof (s));
6368 g_strdelimit (s, ",", '.');
6369 return g_ascii_strtod (s, NULL);
6373 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6375 gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6377 if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6378 g_strlcpy (val_str, "now", sizeof (val_str));
6380 if (segment->position == 0) {
6381 g_strlcpy (val_str, "0", sizeof (val_str));
6383 g_ascii_dtostr (val_str, sizeof (val_str),
6384 ((gdouble) segment->position) / GST_SECOND);
6387 return g_strdup_printf ("npt=%s-", val_str);
6391 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6393 stream->timebase = -1;
6394 stream->seqbase = -1;
6398 stream->caps = gst_caps_make_writable (stream->caps);
6399 s = gst_caps_get_structure (stream->caps, 0);
6400 gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6404 static GstRTSPResult
6405 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6407 GstRTSPResult res = GST_RTSP_OK;
6409 if (src->state < GST_RTSP_STATE_READY) {
6410 res = GST_RTSP_ERROR;
6411 if (src->open_error) {
6412 GST_DEBUG_OBJECT (src, "the stream was in error");
6416 gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6418 if ((res = gst_rtspsrc_open (src, async)) < 0) {
6419 GST_DEBUG_OBJECT (src, "failed to open stream");
6428 static GstRTSPResult
6429 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6431 GstRTSPMessage request = { 0 };
6432 GstRTSPMessage response = { 0 };
6433 GstRTSPResult res = GST_RTSP_OK;
6439 GST_DEBUG_OBJECT (src, "PLAY...");
6441 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6444 if (!(src->methods & GST_RTSP_PLAY))
6447 if (src->state == GST_RTSP_STATE_PLAYING)
6450 if (!src->conninfo.connection || !src->conninfo.connected)
6453 /* send some dummy packets before we activate the receive in the
6455 gst_rtspsrc_send_dummy_packets (src);
6457 gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
6459 /* construct a control url */
6461 control = src->control;
6463 control = src->conninfo.url_str;
6465 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6466 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6468 GstRTSPConnection *conn;
6470 /* try aggregate control first but do non-aggregate control otherwise */
6472 setup_url = control;
6473 else if ((setup_url = stream->conninfo.location) == NULL)
6476 if (src->conninfo.connection) {
6477 conn = src->conninfo.connection;
6478 } else if (stream->conninfo.connection) {
6479 conn = stream->conninfo.connection;
6485 res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6487 goto create_request_failed;
6489 if (src->need_range) {
6490 hval = gen_range_header (src, segment);
6492 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_RANGE, hval);
6495 /* store the newsegment event so it can be sent from the streaming thread. */
6496 if (src->start_segment)
6497 gst_event_unref (src->start_segment);
6498 src->start_segment = gst_event_new_segment (&src->segment);
6501 if (segment->rate != 1.0) {
6502 gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6504 g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6506 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6508 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6512 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6514 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6517 /* seek may have silently failed as it is not supported */
6518 if (!(src->methods & GST_RTSP_PLAY)) {
6519 GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6520 /* obviously it is supported as we made it here */
6521 src->methods |= GST_RTSP_PLAY;
6522 src->seekable = FALSE;
6523 /* but there is nothing to parse in the response,
6524 * so convey we have no idea and not to expect anything particular */
6525 clear_rtp_base (src, stream);
6529 /* need to do for all streams */
6530 for (run = src->streams; run; run = g_list_next (run))
6531 clear_rtp_base (src, (GstRTSPStream *) run->data);
6533 /* NOTE the above also disables npt based eos detection */
6534 /* and below forces position to 0,
6535 * which is visible feedback we lost the plot */
6536 segment->start = segment->position = src->last_pos;
6539 gst_rtsp_message_unset (&request);
6541 /* parse RTP npt field. This is the current position in the stream (Normal
6542 * Play Time) and should be put in the NEWSEGMENT position field. */
6543 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6545 gst_rtspsrc_parse_range (src, hval, segment);
6547 /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6548 segment->rate = 1.0;
6550 /* parse Speed header. This is the intended playback rate of the stream
6551 * and should be put in the NEWSEGMENT rate field. */
6552 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6553 0) == GST_RTSP_OK) {
6554 segment->rate = gst_rtspsrc_get_float (hval);
6555 } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6556 &hval, 0) == GST_RTSP_OK) {
6557 segment->rate = gst_rtspsrc_get_float (hval);
6560 /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6561 * for the RTP packets. If this is not present, we assume all starts from 0...
6562 * This is info for the RTP session manager that we pass to it in caps. */
6564 while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6565 &hval, hval_idx++) == GST_RTSP_OK)
6566 gst_rtspsrc_parse_rtpinfo (src, hval);
6568 /* some servers indicate RTCP parameters in PLAY response,
6569 * rather than properly in SDP */
6570 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6571 &hval, 0) == GST_RTSP_OK)
6572 gst_rtspsrc_handle_rtcp_interval (src, hval);
6574 gst_rtsp_message_unset (&response);
6576 /* early exit when we did aggregate control */
6580 /* configure the caps of the streams after we parsed all headers. Only reset
6581 * the manager object when we set a new Range header (we did a seek) */
6582 gst_rtspsrc_configure_caps (src, segment, src->need_range);
6584 /* set again when needed */
6585 src->need_range = FALSE;
6587 src->running = TRUE;
6588 src->base_time = -1;
6589 src->state = GST_RTSP_STATE_PLAYING;
6592 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6593 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6594 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6595 stream->discont = TRUE;
6600 gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6607 GST_DEBUG_OBJECT (src, "failed to open stream");
6612 GST_DEBUG_OBJECT (src, "PLAY is not supported");
6617 GST_DEBUG_OBJECT (src, "we were already PLAYING");
6620 create_request_failed:
6622 gchar *str = gst_rtsp_strresult (res);
6624 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6625 ("Could not create request. (%s)", str));
6631 gchar *str = gst_rtsp_strresult (res);
6633 gst_rtsp_message_unset (&request);
6634 if (res != GST_RTSP_EINTR) {
6635 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6636 ("Could not send message. (%s)", str));
6638 GST_WARNING_OBJECT (src, "PLAY interrupted");
6645 static GstRTSPResult
6646 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
6648 GstRTSPResult res = GST_RTSP_OK;
6649 GstRTSPMessage request = { 0 };
6650 GstRTSPMessage response = { 0 };
6654 GST_DEBUG_OBJECT (src, "PAUSE...");
6656 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6659 if (!(src->methods & GST_RTSP_PAUSE))
6662 if (src->state == GST_RTSP_STATE_READY)
6665 if (!src->conninfo.connection || !src->conninfo.connected)
6668 /* construct a control url */
6670 control = src->control;
6672 control = src->conninfo.url_str;
6674 /* loop over the streams. We might exit the loop early when we could do an
6675 * aggregate control */
6676 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6677 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6678 GstRTSPConnection *conn;
6681 /* try aggregate control first but do non-aggregate control otherwise */
6683 setup_url = control;
6684 else if ((setup_url = stream->conninfo.location) == NULL)
6687 if (src->conninfo.connection) {
6688 conn = src->conninfo.connection;
6689 } else if (stream->conninfo.connection) {
6690 conn = stream->conninfo.connection;
6696 GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6697 ("Sending PAUSE request"));
6700 gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6702 goto create_request_failed;
6704 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6707 gst_rtsp_message_unset (&request);
6708 gst_rtsp_message_unset (&response);
6710 /* exit early when we did agregate control */
6715 /* change element states now */
6716 gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
6719 src->state = GST_RTSP_STATE_READY;
6723 gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6730 GST_DEBUG_OBJECT (src, "failed to open stream");
6735 GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6740 GST_DEBUG_OBJECT (src, "we were already PAUSED");
6743 create_request_failed:
6745 gchar *str = gst_rtsp_strresult (res);
6747 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6748 ("Could not create request. (%s)", str));
6754 gchar *str = gst_rtsp_strresult (res);
6756 gst_rtsp_message_unset (&request);
6757 if (res != GST_RTSP_EINTR) {
6758 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6759 ("Could not send message. (%s)", str));
6761 GST_WARNING_OBJECT (src, "PAUSE interrupted");
6769 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6771 GstRTSPSrc *rtspsrc;
6773 rtspsrc = GST_RTSPSRC (bin);
6775 switch (GST_MESSAGE_TYPE (message)) {
6776 case GST_MESSAGE_EOS:
6777 gst_message_unref (message);
6779 case GST_MESSAGE_ELEMENT:
6781 const GstStructure *s = gst_message_get_structure (message);
6783 if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6784 gboolean ignore_timeout;
6786 GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6788 GST_OBJECT_LOCK (rtspsrc);
6789 ignore_timeout = rtspsrc->ignore_timeout;
6790 rtspsrc->ignore_timeout = TRUE;
6791 GST_OBJECT_UNLOCK (rtspsrc);
6793 /* we only act on the first udp timeout message, others are irrelevant
6794 * and can be ignored. */
6795 if (!ignore_timeout)
6796 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
6798 gst_message_unref (message);
6801 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6804 case GST_MESSAGE_ERROR:
6807 GstRTSPStream *stream;
6810 udpsrc = GST_MESSAGE_SRC (message);
6812 GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6813 GST_ELEMENT_NAME (udpsrc));
6815 stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6819 /* we ignore the RTCP udpsrc */
6820 if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6823 /* if we get error messages from the udp sources, that's not a problem as
6824 * long as not all of them error out. We also don't really know what the
6825 * problem is, the message does not give enough detail... */
6826 ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6827 GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
6828 if (ret != GST_FLOW_OK)
6832 gst_message_unref (message);
6836 /* fatal but not our message, forward */
6837 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6842 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6848 /* the thread where everything happens */
6850 gst_rtspsrc_thread (GstRTSPSrc * src)
6854 GST_OBJECT_LOCK (src);
6855 cmd = src->pending_cmd;
6856 if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
6858 src->pending_cmd = CMD_LOOP;
6860 src->pending_cmd = CMD_WAIT;
6861 GST_DEBUG_OBJECT (src, "got command %d", cmd);
6863 /* we got the message command, so ensure communication is possible again */
6864 gst_rtspsrc_connection_flush (src, FALSE);
6866 src->busy_cmd = cmd;
6867 GST_OBJECT_UNLOCK (src);
6871 gst_rtspsrc_open (src, TRUE);
6874 gst_rtspsrc_play (src, &src->segment, TRUE);
6877 gst_rtspsrc_pause (src, TRUE);
6880 gst_rtspsrc_close (src, TRUE, FALSE);
6883 gst_rtspsrc_loop (src);
6886 gst_rtspsrc_reconnect (src, FALSE);
6892 GST_OBJECT_LOCK (src);
6893 /* and go back to sleep */
6894 if (src->pending_cmd == CMD_WAIT) {
6896 gst_task_pause (src->task);
6899 src->busy_cmd = CMD_WAIT;
6900 GST_OBJECT_UNLOCK (src);
6904 gst_rtspsrc_start (GstRTSPSrc * src)
6906 GST_DEBUG_OBJECT (src, "starting");
6908 GST_OBJECT_LOCK (src);
6910 src->pending_cmd = CMD_WAIT;
6912 if (src->task == NULL) {
6913 src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
6914 if (src->task == NULL)
6917 gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
6919 GST_OBJECT_UNLOCK (src);
6926 GST_ERROR_OBJECT (src, "failed to create task");
6932 gst_rtspsrc_stop (GstRTSPSrc * src)
6936 GST_DEBUG_OBJECT (src, "stopping");
6938 /* also cancels pending task */
6939 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
6941 GST_OBJECT_LOCK (src);
6942 if ((task = src->task)) {
6944 GST_OBJECT_UNLOCK (src);
6946 gst_task_stop (task);
6948 /* make sure it is not running */
6949 GST_RTSP_STREAM_LOCK (src);
6950 GST_RTSP_STREAM_UNLOCK (src);
6952 /* now wait for the task to finish */
6953 gst_task_join (task);
6955 /* and free the task */
6956 gst_object_unref (GST_OBJECT (task));
6958 GST_OBJECT_LOCK (src);
6960 GST_OBJECT_UNLOCK (src);
6962 /* ensure synchronously all is closed and clean */
6963 gst_rtspsrc_close (src, FALSE, TRUE);
6968 static GstStateChangeReturn
6969 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
6971 GstRTSPSrc *rtspsrc;
6972 GstStateChangeReturn ret;
6974 rtspsrc = GST_RTSPSRC (element);
6976 switch (transition) {
6977 case GST_STATE_CHANGE_NULL_TO_READY:
6978 if (!gst_rtspsrc_start (rtspsrc))
6981 case GST_STATE_CHANGE_READY_TO_PAUSED:
6982 /* init some state */
6983 rtspsrc->cur_protocols = rtspsrc->protocols;
6984 /* first attempt, don't ignore timeouts */
6985 rtspsrc->ignore_timeout = FALSE;
6986 rtspsrc->open_error = FALSE;
6987 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
6989 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6990 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6991 /* unblock the tcp tasks and make the loop waiting */
6992 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP);
6993 /* make sure it is waiting before we send PAUSE or PLAY below */
6994 GST_RTSP_STREAM_LOCK (rtspsrc);
6995 GST_RTSP_STREAM_UNLOCK (rtspsrc);
6997 case GST_STATE_CHANGE_PAUSED_TO_READY:
7003 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7004 if (ret == GST_STATE_CHANGE_FAILURE)
7007 switch (transition) {
7008 case GST_STATE_CHANGE_NULL_TO_READY:
7009 ret = GST_STATE_CHANGE_SUCCESS;
7011 case GST_STATE_CHANGE_READY_TO_PAUSED:
7012 ret = GST_STATE_CHANGE_NO_PREROLL;
7014 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7015 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7016 ret = GST_STATE_CHANGE_SUCCESS;
7018 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7019 /* send pause request and keep the idle task around */
7020 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7021 ret = GST_STATE_CHANGE_NO_PREROLL;
7023 case GST_STATE_CHANGE_PAUSED_TO_READY:
7024 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7025 ret = GST_STATE_CHANGE_SUCCESS;
7027 case GST_STATE_CHANGE_READY_TO_NULL:
7028 gst_rtspsrc_stop (rtspsrc);
7029 ret = GST_STATE_CHANGE_SUCCESS;
7040 GST_DEBUG_OBJECT (rtspsrc, "start failed");
7041 return GST_STATE_CHANGE_FAILURE;
7046 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7049 GstRTSPSrc *rtspsrc;
7051 rtspsrc = GST_RTSPSRC (element);
7053 if (GST_EVENT_IS_DOWNSTREAM (event)) {
7054 res = gst_rtspsrc_push_event (rtspsrc, event);
7056 res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7063 /*** GSTURIHANDLER INTERFACE *************************************************/
7066 gst_rtspsrc_uri_get_type (GType type)
7071 static const gchar *const *
7072 gst_rtspsrc_uri_get_protocols (GType type)
7074 static const gchar *protocols[] =
7075 { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7076 "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7083 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7085 GstRTSPSrc *src = GST_RTSPSRC (handler);
7087 /* FIXME: make thread-safe */
7088 return g_strdup (src->conninfo.location);
7092 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7097 GstRTSPUrl *newurl = NULL;
7098 GstSDPMessage *sdp = NULL;
7100 src = GST_RTSPSRC (handler);
7102 /* same URI, we're fine */
7103 if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7106 if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7107 if ((res = gst_sdp_message_new (&sdp) < 0))
7110 GST_DEBUG_OBJECT (src, "parsing SDP message");
7111 if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7115 GST_DEBUG_OBJECT (src, "parsing URI");
7116 if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7120 /* if worked, free previous and store new url object along with the original
7122 GST_DEBUG_OBJECT (src, "configuring URI");
7123 g_free (src->conninfo.location);
7124 src->conninfo.location = g_strdup (uri);
7125 gst_rtsp_url_free (src->conninfo.url);
7126 src->conninfo.url = newurl;
7127 g_free (src->conninfo.url_str);
7129 src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7131 src->conninfo.url_str = NULL;
7134 gst_sdp_message_free (src->sdp);
7136 src->from_sdp = sdp != NULL;
7138 GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7139 GST_DEBUG_OBJECT (src, "request uri is: %s",
7140 GST_STR_NULL (src->conninfo.url_str));
7147 GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7152 GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7153 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7154 "Could not create SDP");
7159 GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7160 GST_STR_NULL (uri));
7161 gst_sdp_message_free (sdp);
7162 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7168 GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7169 GST_STR_NULL (uri), res);
7170 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7171 "Invalid RTSP URI");
7177 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7179 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7181 iface->get_type = gst_rtspsrc_uri_get_type;
7182 iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7183 iface->get_uri = gst_rtspsrc_uri_get_uri;
7184 iface->set_uri = gst_rtspsrc_uri_set_uri;