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
84 #endif /* HAVE_UNISTD_H */
90 #include <gst/net/gstnet.h>
91 #include <gst/sdp/gstsdpmessage.h>
92 #include <gst/sdp/gstmikey.h>
93 #include <gst/rtp/gstrtppayloads.h>
95 #include "gst/gst-i18n-plugin.h"
97 #include "gstrtspsrc.h"
99 GST_DEBUG_CATEGORY_STATIC (rtspsrc_debug);
100 #define GST_CAT_DEFAULT (rtspsrc_debug)
102 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream_%u",
105 GST_STATIC_CAPS ("application/x-rtp; application/x-rdt"));
107 /* templates used internally */
108 static GstStaticPadTemplate anysrctemplate =
109 GST_STATIC_PAD_TEMPLATE ("internalsrc_%u",
112 GST_STATIC_CAPS_ANY);
114 static GstStaticPadTemplate anysinktemplate =
115 GST_STATIC_PAD_TEMPLATE ("internalsink_%u",
118 GST_STATIC_CAPS_ANY);
122 SIGNAL_HANDLE_REQUEST,
124 SIGNAL_SELECT_STREAM,
126 SIGNAL_REQUEST_RTCP_KEY,
130 enum _GstRtspSrcRtcpSyncMode
137 enum _GstRtspSrcBufferMode
146 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
148 gst_rtsp_src_buffer_mode_get_type (void)
150 static GType buffer_mode_type = 0;
151 static const GEnumValue buffer_modes[] = {
152 {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
153 {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
154 {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
155 {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
156 {BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks", "synced"},
160 if (!buffer_mode_type) {
162 g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
164 return buffer_mode_type;
167 #define AES_128_KEY_LEN 16
168 #define AES_256_KEY_LEN 32
170 #define HMAC_32_KEY_LEN 4
171 #define HMAC_80_KEY_LEN 10
173 #define DEFAULT_LOCATION NULL
174 #define DEFAULT_PROTOCOLS GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
175 #define DEFAULT_DEBUG FALSE
176 #define DEFAULT_RETRY 20
177 #define DEFAULT_TIMEOUT 5000000
178 #define DEFAULT_UDP_BUFFER_SIZE 0x80000
179 #define DEFAULT_TCP_TIMEOUT 20000000
180 #define DEFAULT_LATENCY_MS 2000
181 #define DEFAULT_DROP_ON_LATENCY FALSE
182 #define DEFAULT_CONNECTION_SPEED 0
183 #define DEFAULT_NAT_METHOD GST_RTSP_NAT_DUMMY
184 #define DEFAULT_DO_RTCP TRUE
185 #define DEFAULT_DO_RTSP_KEEP_ALIVE TRUE
186 #define DEFAULT_PROXY NULL
187 #define DEFAULT_RTP_BLOCKSIZE 0
188 #define DEFAULT_USER_ID NULL
189 #define DEFAULT_USER_PW NULL
190 #define DEFAULT_BUFFER_MODE BUFFER_MODE_AUTO
191 #define DEFAULT_PORT_RANGE NULL
192 #define DEFAULT_SHORT_HEADER FALSE
193 #define DEFAULT_PROBATION 2
194 #define DEFAULT_UDP_RECONNECT TRUE
195 #define DEFAULT_MULTICAST_IFACE NULL
196 #define DEFAULT_NTP_SYNC FALSE
197 #define DEFAULT_USE_PIPELINE_CLOCK FALSE
198 #define DEFAULT_TLS_VALIDATION_FLAGS G_TLS_CERTIFICATE_VALIDATE_ALL
199 #define DEFAULT_TLS_DATABASE NULL
211 PROP_DROP_ON_LATENCY,
212 PROP_CONNECTION_SPEED,
215 PROP_DO_RTSP_KEEP_ALIVE,
224 PROP_UDP_BUFFER_SIZE,
228 PROP_MULTICAST_IFACE,
230 PROP_USE_PIPELINE_CLOCK,
232 PROP_TLS_VALIDATION_FLAGS,
237 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
239 gst_rtsp_nat_method_get_type (void)
241 static GType rtsp_nat_method_type = 0;
242 static const GEnumValue rtsp_nat_method[] = {
243 {GST_RTSP_NAT_NONE, "None", "none"},
244 {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
248 if (!rtsp_nat_method_type) {
249 rtsp_nat_method_type =
250 g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
252 return rtsp_nat_method_type;
255 static void gst_rtspsrc_finalize (GObject * object);
257 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
258 const GValue * value, GParamSpec * pspec);
259 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
260 GValue * value, GParamSpec * pspec);
262 static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
264 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
265 gpointer iface_data);
267 static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
270 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
271 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
273 static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
275 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
276 GstStateChange transition);
277 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
278 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
280 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
281 GstRTSPMessage * response);
283 static gboolean gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd,
285 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
286 GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
288 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
289 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
291 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
292 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
293 gboolean only_close);
295 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
296 const gchar * uri, GError ** error);
297 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
299 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
300 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
301 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
302 GstRTSPStream * stream, GstEvent * event);
303 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
304 static void gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush);
312 /* commands we send to out loop to notify it of events */
313 #define CMD_OPEN (1 << 0)
314 #define CMD_PLAY (1 << 1)
315 #define CMD_PAUSE (1 << 2)
316 #define CMD_CLOSE (1 << 3)
317 #define CMD_WAIT (1 << 4)
318 #define CMD_RECONNECT (1 << 5)
319 #define CMD_LOOP (1 << 6)
321 /* mask for all commands */
322 #define CMD_ALL ((CMD_LOOP << 1) - 1)
324 #define GST_ELEMENT_PROGRESS(el, type, code, text) \
326 gchar *__txt = _gst_element_error_printf text; \
327 gst_element_post_message (GST_ELEMENT_CAST (el), \
328 gst_message_new_progress (GST_OBJECT_CAST (el), \
329 GST_PROGRESS_TYPE_ ##type, code, __txt)); \
333 static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
335 #define gst_rtspsrc_parent_class parent_class
336 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
337 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
340 default_select_stream (GstRTSPSrc * src, guint id, GstCaps * caps)
342 GST_DEBUG_OBJECT (src, "default handler");
347 select_stream_accum (GSignalInvocationHint * ihint,
348 GValue * return_accu, const GValue * handler_return, gpointer data)
352 myboolean = g_value_get_boolean (handler_return);
353 GST_DEBUG ("accum %d", myboolean);
354 g_value_set_boolean (return_accu, myboolean);
356 /* stop emission if FALSE */
361 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
363 GObjectClass *gobject_class;
364 GstElementClass *gstelement_class;
365 GstBinClass *gstbin_class;
367 gobject_class = (GObjectClass *) klass;
368 gstelement_class = (GstElementClass *) klass;
369 gstbin_class = (GstBinClass *) klass;
371 GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
373 gobject_class->set_property = gst_rtspsrc_set_property;
374 gobject_class->get_property = gst_rtspsrc_get_property;
376 gobject_class->finalize = gst_rtspsrc_finalize;
378 g_object_class_install_property (gobject_class, PROP_LOCATION,
379 g_param_spec_string ("location", "RTSP Location",
380 "Location of the RTSP url to read",
381 DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
383 g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
384 g_param_spec_flags ("protocols", "Protocols",
385 "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
386 DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388 g_object_class_install_property (gobject_class, PROP_DEBUG,
389 g_param_spec_boolean ("debug", "Debug",
390 "Dump request and response messages to stdout",
391 DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
393 g_object_class_install_property (gobject_class, PROP_RETRY,
394 g_param_spec_uint ("retry", "Retry",
395 "Max number of retries when allocating RTP ports.",
396 0, G_MAXUINT16, DEFAULT_RETRY,
397 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
399 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
400 g_param_spec_uint64 ("timeout", "Timeout",
401 "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
402 0, G_MAXUINT64, DEFAULT_TIMEOUT,
403 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
405 g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
406 g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
407 "Fail after timeout microseconds on TCP connections (0 = disabled)",
408 0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
409 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
411 g_object_class_install_property (gobject_class, PROP_LATENCY,
412 g_param_spec_uint ("latency", "Buffer latency in ms",
413 "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
414 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
416 g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
417 g_param_spec_boolean ("drop-on-latency",
418 "Drop buffers when maximum latency is reached",
419 "Tells the jitterbuffer to never exceed the given latency in size",
420 DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
422 g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
423 g_param_spec_uint64 ("connection-speed", "Connection Speed",
424 "Network connection speed in kbps (0 = unknown)",
425 0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
426 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
428 g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
429 g_param_spec_enum ("nat-method", "NAT Method",
430 "Method to use for traversing firewalls and NAT",
431 GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
432 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
435 * GstRTSPSrc:do-rtcp:
437 * Enable RTCP support. Some old server don't like RTCP and then this property
438 * needs to be set to FALSE.
440 g_object_class_install_property (gobject_class, PROP_DO_RTCP,
441 g_param_spec_boolean ("do-rtcp", "Do RTCP",
442 "Send RTCP packets, disable for old incompatible server.",
443 DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446 * GstRTSPSrc:do-rtsp-keep-alive:
448 * Enable RTSP keep alive support. Some old server don't like RTSP
449 * keep alive and then this property needs to be set to FALSE.
451 g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
452 g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
453 "Send RTSP keep alive packets, disable for old incompatible server.",
454 DEFAULT_DO_RTSP_KEEP_ALIVE,
455 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
460 * Set the proxy parameters. This has to be a string of the format
461 * [http://][user:passwd@]host[:port].
463 g_object_class_install_property (gobject_class, PROP_PROXY,
464 g_param_spec_string ("proxy", "Proxy",
465 "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
466 DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
468 * GstRTSPSrc:proxy-id:
470 * Sets the proxy URI user id for authentication. If the URI set via the
471 * "proxy" property contains a user-id already, that will take precedence.
475 g_object_class_install_property (gobject_class, PROP_PROXY_ID,
476 g_param_spec_string ("proxy-id", "proxy-id",
477 "HTTP proxy URI user id for authentication", "",
478 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
480 * GstRTSPSrc:proxy-pw:
482 * Sets the proxy URI password for authentication. If the URI set via the
483 * "proxy" property contains a password already, that will take precedence.
487 g_object_class_install_property (gobject_class, PROP_PROXY_PW,
488 g_param_spec_string ("proxy-pw", "proxy-pw",
489 "HTTP proxy URI user password for authentication", "",
490 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
493 * GstRTSPSrc:rtp-blocksize:
495 * RTP package size to suggest to server.
497 g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
498 g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
499 "RTP package size to suggest to server (0 = disabled)",
500 0, 65536, DEFAULT_RTP_BLOCKSIZE,
501 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
503 g_object_class_install_property (gobject_class,
505 g_param_spec_string ("user-id", "user-id",
506 "RTSP location URI user id for authentication", DEFAULT_USER_ID,
507 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
508 g_object_class_install_property (gobject_class, PROP_USER_PW,
509 g_param_spec_string ("user-pw", "user-pw",
510 "RTSP location URI user password for authentication", DEFAULT_USER_PW,
511 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
514 * GstRTSPSrc:buffer-mode:
516 * Control the buffering and timestamping mode used by the jitterbuffer.
518 g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
519 g_param_spec_enum ("buffer-mode", "Buffer Mode",
520 "Control the buffering algorithm in use",
521 GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
522 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
525 * GstRTSPSrc:port-range:
527 * Configure the client port numbers that can be used to recieve RTP and
530 g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
531 g_param_spec_string ("port-range", "Port range",
532 "Client port range that can be used to receive RTP and RTCP data, "
533 "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
534 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
537 * GstRTSPSrc:udp-buffer-size:
539 * Size of the kernel UDP receive buffer in bytes.
541 g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
542 g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
543 "Size of the kernel UDP receive buffer in bytes, 0=default",
544 0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
545 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
548 * GstRTSPSrc:short-header:
550 * Only send the basic RTSP headers for broken encoders.
552 g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
553 g_param_spec_boolean ("short-header", "Short Header",
554 "Only send the basic RTSP headers for broken encoders",
555 DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
557 g_object_class_install_property (gobject_class, PROP_PROBATION,
558 g_param_spec_uint ("probation", "Number of probations",
559 "Consecutive packet sequence numbers to accept the source",
560 0, G_MAXUINT, DEFAULT_PROBATION,
561 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
563 g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
564 g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
565 "Reconnect to the server if RTSP connection is closed when doing UDP",
566 DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
568 g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
569 g_param_spec_string ("multicast-iface", "Multicast Interface",
570 "The network interface on which to join the multicast group",
571 DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
573 g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
574 g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
575 "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
576 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
578 g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
579 g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
580 "Use the pipeline running-time to set the NTP time in the RTCP SR messages",
581 DEFAULT_USE_PIPELINE_CLOCK,
582 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
584 g_object_class_install_property (gobject_class, PROP_SDES,
585 g_param_spec_boxed ("sdes", "SDES",
586 "The SDES items of this session",
587 GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
590 * GstRTSPSrc::tls-validation-flags:
592 * TLS certificate validation flags used to validate server
597 g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
598 g_param_spec_flags ("tls-validation-flags", "TLS validation flags",
599 "TLS certificate validation flags used to validate the server certificate",
600 G_TYPE_TLS_CERTIFICATE_FLAGS, DEFAULT_TLS_VALIDATION_FLAGS,
601 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
604 * GstRTSPSrc::tls-database:
606 * TLS database with anchor certificate authorities used to validate
607 * the server certificate.
611 g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
612 g_param_spec_object ("tls-database", "TLS database",
613 "TLS database with anchor certificate authorities used to validate the server certificate",
614 G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
617 * GstRTSPSrc::handle-request:
618 * @rtspsrc: a #GstRTSPSrc
619 * @request: a #GstRTSPMessage
620 * @response: a #GstRTSPMessage
622 * Handle a server request in @request and prepare @response.
624 * This signal is called from the streaming thread, you should therefore not
625 * do any state changes on @rtspsrc because this might deadlock. If you want
626 * to modify the state as a result of this signal, post a
627 * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
632 gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST] =
633 g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
634 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
635 G_TYPE_POINTER, G_TYPE_POINTER);
638 * GstRTSPSrc::on-sdp:
639 * @rtspsrc: a #GstRTSPSrc
640 * @sdp: a #GstSDPMessage
642 * Emited when the client has retrieved the SDP and before it configures the
643 * streams in the SDP. @sdp can be inspected and modified.
645 * This signal is called from the streaming thread, you should therefore not
646 * do any state changes on @rtspsrc because this might deadlock. If you want
647 * to modify the state as a result of this signal, post a
648 * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
653 gst_rtspsrc_signals[SIGNAL_ON_SDP] =
654 g_signal_new ("on-sdp", G_TYPE_FROM_CLASS (klass), 0,
655 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
656 GST_TYPE_SDP_MESSAGE | G_SIGNAL_TYPE_STATIC_SCOPE);
659 * GstRTSPSrc::select-stream:
660 * @rtspsrc: a #GstRTSPSrc
661 * @num: the stream number
662 * @caps: the stream caps
664 * Emited before the client decides to configure the stream @num with
667 * Returns: %TRUE when the stream should be selected, %FALSE when the stream
672 gst_rtspsrc_signals[SIGNAL_SELECT_STREAM] =
673 g_signal_new_class_handler ("select-stream", G_TYPE_FROM_CLASS (klass),
674 G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP,
675 (GCallback) default_select_stream, select_stream_accum, NULL,
676 g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_UINT,
679 * GstRTSPSrc::new-manager:
680 * @rtspsrc: a #GstRTSPSrc
681 * @manager: a #GstElement
683 * Emited after a new manager (like rtpbin) was created and the default
684 * properties were configured.
688 gst_rtspsrc_signals[SIGNAL_NEW_MANAGER] =
689 g_signal_new_class_handler ("new-manager", G_TYPE_FROM_CLASS (klass),
690 G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
691 g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
694 * GstRTSPSrc::request-rtcp-key:
695 * @rtspsrc: a #GstRTSPSrc
697 * Signal emited to get the crypto parameters relevant to the RTCP
698 * stream. User should provide the key and the RTCP encryption ciphers
699 * and authentication, and return them wrapped in a GstCaps.
703 gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY] =
704 g_signal_new ("request-rtcp-key", G_TYPE_FROM_CLASS (klass),
705 G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, GST_TYPE_CAPS, 0, G_TYPE_NONE);
707 gstelement_class->send_event = gst_rtspsrc_send_event;
708 gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
709 gstelement_class->change_state = gst_rtspsrc_change_state;
711 gst_element_class_add_pad_template (gstelement_class,
712 gst_static_pad_template_get (&rtptemplate));
714 gst_element_class_set_static_metadata (gstelement_class,
715 "RTSP packet receiver", "Source/Network",
716 "Receive data over the network via RTSP (RFC 2326)",
717 "Wim Taymans <wim@fluendo.com>, "
718 "Thijs Vermeir <thijs.vermeir@barco.com>, "
719 "Lutz Mueller <lutz@topfrose.de>");
721 gstbin_class->handle_message = gst_rtspsrc_handle_message;
723 gst_rtsp_ext_list_init ();
727 gst_rtspsrc_init (GstRTSPSrc * src)
729 src->conninfo.location = g_strdup (DEFAULT_LOCATION);
730 src->protocols = DEFAULT_PROTOCOLS;
731 src->debug = DEFAULT_DEBUG;
732 src->retry = DEFAULT_RETRY;
733 src->udp_timeout = DEFAULT_TIMEOUT;
734 gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
735 src->latency = DEFAULT_LATENCY_MS;
736 src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
737 src->connection_speed = DEFAULT_CONNECTION_SPEED;
738 src->nat_method = DEFAULT_NAT_METHOD;
739 src->do_rtcp = DEFAULT_DO_RTCP;
740 src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
741 gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
742 src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
743 src->user_id = g_strdup (DEFAULT_USER_ID);
744 src->user_pw = g_strdup (DEFAULT_USER_PW);
745 src->buffer_mode = DEFAULT_BUFFER_MODE;
746 src->client_port_range.min = 0;
747 src->client_port_range.max = 0;
748 src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
749 src->short_header = DEFAULT_SHORT_HEADER;
750 src->probation = DEFAULT_PROBATION;
751 src->udp_reconnect = DEFAULT_UDP_RECONNECT;
752 src->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
753 src->ntp_sync = DEFAULT_NTP_SYNC;
754 src->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
756 src->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
757 src->tls_database = DEFAULT_TLS_DATABASE;
759 /* get a list of all extensions */
760 src->extensions = gst_rtsp_ext_list_get ();
762 /* connect to send signal */
763 gst_rtsp_ext_list_connect (src->extensions, "send",
764 (GCallback) gst_rtspsrc_send_cb, src);
766 /* protects the streaming thread in interleaved mode or the polling
767 * thread in UDP mode. */
768 g_rec_mutex_init (&src->stream_rec_lock);
770 /* protects our state changes from multiple invocations */
771 g_rec_mutex_init (&src->state_rec_lock);
773 src->state = GST_RTSP_STATE_INVALID;
775 GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
779 gst_rtspsrc_finalize (GObject * object)
783 rtspsrc = GST_RTSPSRC (object);
785 gst_rtsp_ext_list_free (rtspsrc->extensions);
786 g_free (rtspsrc->conninfo.location);
787 gst_rtsp_url_free (rtspsrc->conninfo.url);
788 g_free (rtspsrc->conninfo.url_str);
789 g_free (rtspsrc->user_id);
790 g_free (rtspsrc->user_pw);
791 g_free (rtspsrc->multi_iface);
794 gst_sdp_message_free (rtspsrc->sdp);
797 if (rtspsrc->provided_clock)
798 gst_object_unref (rtspsrc->provided_clock);
801 gst_structure_free (rtspsrc->sdes);
803 if (rtspsrc->tls_database)
804 g_object_unref (rtspsrc->tls_database);
807 g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
808 g_rec_mutex_clear (&rtspsrc->state_rec_lock);
810 G_OBJECT_CLASS (parent_class)->finalize (object);
814 gst_rtspsrc_provide_clock (GstElement * element)
816 GstRTSPSrc *src = GST_RTSPSRC (element);
819 if ((clock = src->provided_clock) != NULL)
820 gst_object_ref (clock);
825 /* a proxy string of the format [user:passwd@]host[:port] */
827 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
831 g_free (rtsp->proxy_user);
832 rtsp->proxy_user = NULL;
833 g_free (rtsp->proxy_passwd);
834 rtsp->proxy_passwd = NULL;
835 g_free (rtsp->proxy_host);
836 rtsp->proxy_host = NULL;
837 rtsp->proxy_port = 0;
844 /* we allow http:// in front but ignore it */
845 if (g_str_has_prefix (p, "http://"))
848 at = strchr (p, '@');
850 /* look for user:passwd */
851 col = strchr (proxy, ':');
852 if (col == NULL || col > at)
855 rtsp->proxy_user = g_strndup (p, col - p);
857 rtsp->proxy_passwd = g_strndup (col, at - col);
862 if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
863 rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
864 if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
865 rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
866 if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
867 GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
868 GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
871 col = strchr (p, ':');
874 /* everything before the colon is the hostname */
875 rtsp->proxy_host = g_strndup (p, col - p);
877 rtsp->proxy_port = strtoul (p, (char **) &p, 10);
879 rtsp->proxy_host = g_strdup (p);
880 rtsp->proxy_port = 8080;
886 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
888 rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
889 rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
892 rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
894 rtspsrc->ptcp_timeout = NULL;
898 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
903 rtspsrc = GST_RTSPSRC (object);
907 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
908 g_value_get_string (value), NULL);
911 rtspsrc->protocols = g_value_get_flags (value);
914 rtspsrc->debug = g_value_get_boolean (value);
917 rtspsrc->retry = g_value_get_uint (value);
920 rtspsrc->udp_timeout = g_value_get_uint64 (value);
922 case PROP_TCP_TIMEOUT:
923 gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
926 rtspsrc->latency = g_value_get_uint (value);
928 case PROP_DROP_ON_LATENCY:
929 rtspsrc->drop_on_latency = g_value_get_boolean (value);
931 case PROP_CONNECTION_SPEED:
932 rtspsrc->connection_speed = g_value_get_uint64 (value);
934 case PROP_NAT_METHOD:
935 rtspsrc->nat_method = g_value_get_enum (value);
938 rtspsrc->do_rtcp = g_value_get_boolean (value);
940 case PROP_DO_RTSP_KEEP_ALIVE:
941 rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
944 gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
947 if (rtspsrc->prop_proxy_id)
948 g_free (rtspsrc->prop_proxy_id);
949 rtspsrc->prop_proxy_id = g_value_dup_string (value);
952 if (rtspsrc->prop_proxy_pw)
953 g_free (rtspsrc->prop_proxy_pw);
954 rtspsrc->prop_proxy_pw = g_value_dup_string (value);
956 case PROP_RTP_BLOCKSIZE:
957 rtspsrc->rtp_blocksize = g_value_get_uint (value);
960 if (rtspsrc->user_id)
961 g_free (rtspsrc->user_id);
962 rtspsrc->user_id = g_value_dup_string (value);
965 if (rtspsrc->user_pw)
966 g_free (rtspsrc->user_pw);
967 rtspsrc->user_pw = g_value_dup_string (value);
969 case PROP_BUFFER_MODE:
970 rtspsrc->buffer_mode = g_value_get_enum (value);
972 case PROP_PORT_RANGE:
976 str = g_value_get_string (value);
978 sscanf (str, "%u-%u",
979 &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
981 rtspsrc->client_port_range.min = 0;
982 rtspsrc->client_port_range.max = 0;
986 case PROP_UDP_BUFFER_SIZE:
987 rtspsrc->udp_buffer_size = g_value_get_int (value);
989 case PROP_SHORT_HEADER:
990 rtspsrc->short_header = g_value_get_boolean (value);
993 rtspsrc->probation = g_value_get_uint (value);
995 case PROP_UDP_RECONNECT:
996 rtspsrc->udp_reconnect = g_value_get_boolean (value);
998 case PROP_MULTICAST_IFACE:
999 g_free (rtspsrc->multi_iface);
1001 if (g_value_get_string (value) == NULL)
1002 rtspsrc->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
1004 rtspsrc->multi_iface = g_value_dup_string (value);
1007 rtspsrc->ntp_sync = g_value_get_boolean (value);
1009 case PROP_USE_PIPELINE_CLOCK:
1010 rtspsrc->use_pipeline_clock = g_value_get_boolean (value);
1013 rtspsrc->sdes = g_value_dup_boxed (value);
1015 case PROP_TLS_VALIDATION_FLAGS:
1016 rtspsrc->tls_validation_flags = g_value_get_flags (value);
1018 case PROP_TLS_DATABASE:
1019 g_clear_object (&rtspsrc->tls_database);
1020 rtspsrc->tls_database = g_value_dup_object (value);
1023 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1029 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
1032 GstRTSPSrc *rtspsrc;
1034 rtspsrc = GST_RTSPSRC (object);
1038 g_value_set_string (value, rtspsrc->conninfo.location);
1040 case PROP_PROTOCOLS:
1041 g_value_set_flags (value, rtspsrc->protocols);
1044 g_value_set_boolean (value, rtspsrc->debug);
1047 g_value_set_uint (value, rtspsrc->retry);
1050 g_value_set_uint64 (value, rtspsrc->udp_timeout);
1052 case PROP_TCP_TIMEOUT:
1056 timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
1057 rtspsrc->tcp_timeout.tv_usec;
1058 g_value_set_uint64 (value, timeout);
1062 g_value_set_uint (value, rtspsrc->latency);
1064 case PROP_DROP_ON_LATENCY:
1065 g_value_set_boolean (value, rtspsrc->drop_on_latency);
1067 case PROP_CONNECTION_SPEED:
1068 g_value_set_uint64 (value, rtspsrc->connection_speed);
1070 case PROP_NAT_METHOD:
1071 g_value_set_enum (value, rtspsrc->nat_method);
1074 g_value_set_boolean (value, rtspsrc->do_rtcp);
1076 case PROP_DO_RTSP_KEEP_ALIVE:
1077 g_value_set_boolean (value, rtspsrc->do_rtsp_keep_alive);
1083 if (rtspsrc->proxy_host) {
1085 g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
1089 g_value_take_string (value, str);
1093 g_value_set_string (value, rtspsrc->prop_proxy_id);
1096 g_value_set_string (value, rtspsrc->prop_proxy_pw);
1098 case PROP_RTP_BLOCKSIZE:
1099 g_value_set_uint (value, rtspsrc->rtp_blocksize);
1102 g_value_set_string (value, rtspsrc->user_id);
1105 g_value_set_string (value, rtspsrc->user_pw);
1107 case PROP_BUFFER_MODE:
1108 g_value_set_enum (value, rtspsrc->buffer_mode);
1110 case PROP_PORT_RANGE:
1114 if (rtspsrc->client_port_range.min != 0) {
1115 str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
1116 rtspsrc->client_port_range.max);
1120 g_value_take_string (value, str);
1123 case PROP_UDP_BUFFER_SIZE:
1124 g_value_set_int (value, rtspsrc->udp_buffer_size);
1126 case PROP_SHORT_HEADER:
1127 g_value_set_boolean (value, rtspsrc->short_header);
1129 case PROP_PROBATION:
1130 g_value_set_uint (value, rtspsrc->probation);
1132 case PROP_UDP_RECONNECT:
1133 g_value_set_boolean (value, rtspsrc->udp_reconnect);
1135 case PROP_MULTICAST_IFACE:
1136 g_value_set_string (value, rtspsrc->multi_iface);
1139 g_value_set_boolean (value, rtspsrc->ntp_sync);
1141 case PROP_USE_PIPELINE_CLOCK:
1142 g_value_set_boolean (value, rtspsrc->use_pipeline_clock);
1145 g_value_set_boxed (value, rtspsrc->sdes);
1147 case PROP_TLS_VALIDATION_FLAGS:
1148 g_value_set_flags (value, rtspsrc->tls_validation_flags);
1150 case PROP_TLS_DATABASE:
1151 g_value_set_object (value, rtspsrc->tls_database);
1154 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1160 find_stream_by_id (GstRTSPStream * stream, gint * id)
1162 if (stream->id == *id)
1169 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
1171 if (stream->channel[0] == *channel || stream->channel[1] == *channel)
1178 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
1180 GstElement *src = (GstElement *) a;
1182 if (stream->udpsrc[0] == src)
1184 if (stream->udpsrc[1] == src)
1191 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
1193 if (stream->conninfo.location) {
1194 /* check qualified setup_url */
1195 if (!strcmp (stream->conninfo.location, (gchar *) a))
1198 if (stream->control_url) {
1199 /* check original control_url */
1200 if (!strcmp (stream->control_url, (gchar *) a))
1203 /* check if qualified setup_url ends with string */
1204 if (g_str_has_suffix (stream->control_url, (gchar *) a))
1211 static GstRTSPStream *
1212 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
1216 /* find and get stream */
1217 if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
1218 return (GstRTSPStream *) lstream->data;
1223 static const GstSDPBandwidth *
1224 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1225 const GstSDPMedia * media, const gchar * type)
1229 /* first look in the media specific section */
1230 len = gst_sdp_media_bandwidths_len (media);
1231 for (i = 0; i < len; i++) {
1232 const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
1234 if (strcmp (bw->bwtype, type) == 0)
1237 /* then look in the message specific section */
1238 len = gst_sdp_message_bandwidths_len (sdp);
1239 for (i = 0; i < len; i++) {
1240 const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
1242 if (strcmp (bw->bwtype, type) == 0)
1249 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1250 const GstSDPMedia * media, GstRTSPStream * stream)
1252 const GstSDPBandwidth *bw;
1254 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
1255 stream->as_bandwidth = bw->bandwidth;
1257 stream->as_bandwidth = -1;
1259 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
1260 stream->rr_bandwidth = bw->bandwidth;
1262 stream->rr_bandwidth = -1;
1264 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
1265 stream->rs_bandwidth = bw->bandwidth;
1267 stream->rs_bandwidth = -1;
1271 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
1272 const GstSDPConnection * conn)
1274 if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
1277 if (conn->addrtype == NULL)
1280 /* check for IPV6 */
1281 if (strcmp (conn->addrtype, "IP4") == 0)
1282 stream->is_ipv6 = FALSE;
1283 else if (strcmp (conn->addrtype, "IP6") == 0)
1284 stream->is_ipv6 = TRUE;
1289 g_free (stream->destination);
1290 stream->destination = g_strdup (conn->address);
1292 /* check for multicast */
1293 stream->is_multicast =
1294 gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
1296 stream->ttl = conn->ttl;
1299 /* Go over the connections for a stream.
1300 * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
1302 * - If we are dealing with a localhost address, we disable multicast
1305 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
1306 const GstSDPMedia * media, GstRTSPStream * stream)
1308 const GstSDPConnection *conn;
1311 /* first look in the media specific section */
1312 len = gst_sdp_media_connections_len (media);
1313 for (i = 0; i < len; i++) {
1314 conn = gst_sdp_media_get_connection (media, i);
1316 gst_rtspsrc_do_stream_connection (src, stream, conn);
1318 /* then look in the message specific section */
1319 if ((conn = gst_sdp_message_get_connection (sdp))) {
1320 gst_rtspsrc_do_stream_connection (src, stream, conn);
1324 /* m=<media> <UDP port> RTP/AVP <payload>
1327 gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
1328 const GstSDPMedia * media, GstRTSPStream * stream)
1334 proto = gst_sdp_media_get_proto (media);
1338 if (g_str_equal (proto, "RTP/AVP"))
1339 stream->profile = GST_RTSP_PROFILE_AVP;
1340 else if (g_str_equal (proto, "RTP/SAVP"))
1341 stream->profile = GST_RTSP_PROFILE_SAVP;
1342 else if (g_str_equal (proto, "RTP/AVPF"))
1343 stream->profile = GST_RTSP_PROFILE_AVPF;
1344 else if (g_str_equal (proto, "RTP/SAVPF"))
1345 stream->profile = GST_RTSP_PROFILE_SAVPF;
1349 len = gst_sdp_media_formats_len (media);
1350 for (i = 0; i < len; i++) {
1357 pt = atoi (gst_sdp_media_get_format (media, i));
1359 GST_DEBUG_OBJECT (src, " looking at %d pt: %d", i, pt);
1362 caps = gst_rtspsrc_media_to_caps (pt, media);
1364 GST_WARNING_OBJECT (src, " skipping pt %d without caps", pt);
1368 /* do some tweaks */
1369 s = gst_caps_get_structure (caps, 0);
1370 if ((enc = gst_structure_get_string (s, "encoding-name"))) {
1371 stream->is_real = (strstr (enc, "-REAL") != NULL);
1372 if (strcmp (enc, "X-ASF-PF") == 0)
1373 stream->container = TRUE;
1375 GST_DEBUG ("mapping sdp session level attributes to caps");
1376 gst_rtspsrc_sdp_attributes_to_caps (sdp->attributes, caps);
1377 GST_DEBUG ("mapping sdp media level attributes to caps");
1378 gst_rtspsrc_sdp_attributes_to_caps (media->attributes, caps);
1380 /* the first pt will be the default */
1381 if (stream->ptmap->len == 0)
1382 stream->default_pt = pt;
1386 g_array_append_val (stream->ptmap, item);
1392 GST_ERROR_OBJECT (src, "can't find proto in media");
1397 GST_ERROR_OBJECT (src, "unknown proto in media %s", proto);
1402 static const gchar *
1403 get_aggregate_control (GstRTSPSrc * src)
1408 base = src->control;
1409 else if (src->content_base)
1410 base = src->content_base;
1411 else if (src->conninfo.url_str)
1412 base = src->conninfo.url_str;
1420 clear_ptmap_item (PtMapItem * item)
1423 gst_caps_unref (item->caps);
1426 static GstRTSPStream *
1427 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
1429 GstRTSPStream *stream;
1430 const gchar *control_url;
1431 const GstSDPMedia *media;
1433 /* get media, should not return NULL */
1434 media = gst_sdp_message_get_media (sdp, idx);
1438 stream = g_new0 (GstRTSPStream, 1);
1439 stream->parent = src;
1440 /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1442 stream->last_ret = GST_FLOW_NOT_LINKED;
1443 stream->added = FALSE;
1444 stream->setup = FALSE;
1445 stream->skipped = FALSE;
1447 stream->eos = FALSE;
1448 stream->discont = TRUE;
1449 stream->seqbase = -1;
1450 stream->timebase = -1;
1451 stream->send_ssrc = g_random_int ();
1452 stream->profile = GST_RTSP_PROFILE_AVP;
1453 stream->ptmap = g_array_new (FALSE, FALSE, sizeof (PtMapItem));
1454 g_array_set_clear_func (stream->ptmap, (GDestroyNotify) clear_ptmap_item);
1456 /* collect bandwidth information for this steam. FIXME, configure in the RTP
1457 * session manager to scale RTCP. */
1458 gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1460 /* collect connection info */
1461 gst_rtspsrc_collect_connections (src, sdp, media, stream);
1463 /* make the payload type map */
1464 gst_rtspsrc_collect_payloads (src, sdp, media, stream);
1466 /* collect port number */
1467 stream->port = gst_sdp_media_get_port (media);
1469 /* get control url to construct the setup url. The setup url is used to
1470 * configure the transport of the stream and is used to identity the stream in
1471 * the RTP-Info header field returned from PLAY. */
1472 control_url = gst_sdp_media_get_attribute_val (media, "control");
1473 if (control_url == NULL)
1474 control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1476 GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1477 GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1478 GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1479 GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1481 if (control_url != NULL) {
1482 stream->control_url = g_strdup (control_url);
1483 /* Build a fully qualified url using the content_base if any or by prefixing
1484 * the original request.
1485 * If the control_url starts with a '/' or a non rtsp: protocol we will most
1486 * likely build a URL that the server will fail to understand, this is ok,
1487 * we will fail then. */
1488 if (g_str_has_prefix (control_url, "rtsp://"))
1489 stream->conninfo.location = g_strdup (control_url);
1494 if (g_strcmp0 (control_url, "*") == 0)
1497 base = get_aggregate_control (src);
1499 /* check if the base ends or control starts with / */
1500 has_slash = g_str_has_prefix (control_url, "/");
1501 has_slash = has_slash || g_str_has_suffix (base, "/");
1503 /* concatenate the two strings, insert / when not present */
1504 stream->conninfo.location =
1505 g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1508 GST_DEBUG_OBJECT (src, " setup: %s",
1509 GST_STR_NULL (stream->conninfo.location));
1511 /* we keep track of all streams */
1512 src->streams = g_list_append (src->streams, stream);
1520 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1524 GST_DEBUG_OBJECT (src, "free stream %p", stream);
1526 g_array_free (stream->ptmap, TRUE);
1528 g_free (stream->destination);
1529 g_free (stream->control_url);
1530 g_free (stream->conninfo.location);
1532 for (i = 0; i < 2; i++) {
1533 if (stream->udpsrc[i]) {
1534 gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1535 gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1536 gst_object_unref (stream->udpsrc[i]);
1538 if (stream->channelpad[i])
1539 gst_object_unref (stream->channelpad[i]);
1541 if (stream->udpsink[i]) {
1542 gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1543 gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1544 gst_object_unref (stream->udpsink[i]);
1547 if (stream->fakesrc) {
1548 gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1549 gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1550 gst_object_unref (stream->fakesrc);
1552 if (stream->srcpad) {
1553 gst_pad_set_active (stream->srcpad, FALSE);
1555 gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1557 if (stream->srtpenc)
1558 gst_object_unref (stream->srtpenc);
1559 if (stream->srtpdec)
1560 gst_object_unref (stream->srtpdec);
1561 if (stream->srtcpparams)
1562 gst_caps_unref (stream->srtcpparams);
1563 if (stream->rtcppad)
1564 gst_object_unref (stream->rtcppad);
1565 if (stream->session)
1566 g_object_unref (stream->session);
1571 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1575 GST_DEBUG_OBJECT (src, "cleanup");
1577 for (walk = src->streams; walk; walk = g_list_next (walk)) {
1578 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1580 gst_rtspsrc_stream_free (src, stream);
1582 g_list_free (src->streams);
1583 src->streams = NULL;
1585 if (src->manager_sig_id) {
1586 g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1587 src->manager_sig_id = 0;
1589 gst_element_set_state (src->manager, GST_STATE_NULL);
1590 gst_bin_remove (GST_BIN_CAST (src), src->manager);
1591 src->manager = NULL;
1594 gst_structure_free (src->props);
1597 g_free (src->content_base);
1598 src->content_base = NULL;
1600 g_free (src->control);
1601 src->control = NULL;
1604 gst_rtsp_range_free (src->range);
1607 /* don't clear the SDP when it was used in the url */
1608 if (src->sdp && !src->from_sdp) {
1609 gst_sdp_message_free (src->sdp);
1612 if (src->start_segment) {
1613 gst_event_unref (src->start_segment);
1614 src->start_segment = NULL;
1616 if (src->provided_clock) {
1617 gst_object_unref (src->provided_clock);
1618 src->provided_clock = NULL;
1622 #define PARSE_INT(p, del, res) \
1625 p = strstr (p, del); \
1635 #define PARSE_STRING(p, del, res) \
1638 p = strstr (p, del); \
1650 #define SKIP_SPACES(p) \
1651 while (*p && g_ascii_isspace (*p)) \
1656 * <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1659 gst_rtspsrc_parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
1660 gint * rate, gchar ** params)
1664 p = (gchar *) rtpmap;
1666 PARSE_INT (p, " ", *payload);
1674 PARSE_STRING (p, "/", *name);
1675 if (*name == NULL) {
1676 GST_DEBUG ("no rate, name %s", p);
1677 /* no rate, assume -1 then, this is not supposed to happen but RealMedia
1678 * streams seem to omit the rate. */
1685 p = strstr (p, "/");
1703 parse_keymgmt (const gchar * keymgmt, GstCaps * caps)
1705 gboolean res = FALSE;
1709 GstMIKEYMessage *msg;
1710 const GstMIKEYPayload *payload;
1711 const gchar *srtp_cipher;
1712 const gchar *srtp_auth;
1714 p = (gchar *) keymgmt;
1720 PARSE_STRING (p, " ", kmpid);
1721 if (!g_str_equal (kmpid, "mikey"))
1724 data = g_base64_decode (p, &size);
1728 msg = gst_mikey_message_new_from_data (data, size, NULL, NULL);
1732 srtp_cipher = "aes-128-icm";
1733 srtp_auth = "hmac-sha1-80";
1735 /* check the Security policy if any */
1736 if ((payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, 0))) {
1737 GstMIKEYPayloadSP *p = (GstMIKEYPayloadSP *) payload;
1740 if (p->proto != GST_MIKEY_SEC_PROTO_SRTP)
1743 len = gst_mikey_payload_sp_get_n_params (payload);
1744 for (i = 0; i < len; i++) {
1745 const GstMIKEYPayloadSPParam *param =
1746 gst_mikey_payload_sp_get_param (payload, i);
1748 switch (param->type) {
1749 case GST_MIKEY_SP_SRTP_ENC_ALG:
1750 switch (param->val[0]) {
1752 srtp_cipher = "null";
1756 srtp_cipher = "aes-128-icm";
1762 case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
1763 switch (param->val[0]) {
1764 case AES_128_KEY_LEN:
1765 srtp_cipher = "aes-128-icm";
1767 case AES_256_KEY_LEN:
1768 srtp_cipher = "aes-256-icm";
1774 case GST_MIKEY_SP_SRTP_AUTH_ALG:
1775 switch (param->val[0]) {
1781 srtp_auth = "hmac-sha1-80";
1787 case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
1788 switch (param->val[0]) {
1789 case HMAC_32_KEY_LEN:
1790 srtp_auth = "hmac-sha1-32";
1792 case HMAC_80_KEY_LEN:
1793 srtp_auth = "hmac-sha1-80";
1799 case GST_MIKEY_SP_SRTP_SRTP_ENC:
1801 case GST_MIKEY_SP_SRTP_SRTCP_ENC:
1809 if (!(payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_KEMAC, 0)))
1812 GstMIKEYPayloadKEMAC *p = (GstMIKEYPayloadKEMAC *) payload;
1813 const GstMIKEYPayload *sub;
1814 GstMIKEYPayloadKeyData *pkd;
1817 if (p->enc_alg != GST_MIKEY_ENC_NULL || p->mac_alg != GST_MIKEY_MAC_NULL)
1820 if (!(sub = gst_mikey_payload_kemac_get_sub (payload, 0)))
1823 if (sub->type != GST_MIKEY_PT_KEY_DATA)
1826 pkd = (GstMIKEYPayloadKeyData *) sub;
1828 gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1830 gst_caps_set_simple (caps, "srtp-key", GST_TYPE_BUFFER, buf, NULL);
1833 gst_caps_set_simple (caps,
1834 "srtp-cipher", G_TYPE_STRING, srtp_cipher,
1835 "srtp-auth", G_TYPE_STRING, srtp_auth,
1836 "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
1837 "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
1841 gst_mikey_message_free (msg);
1847 * Mapping SDP attributes to caps
1849 * prepend 'a-' to IANA registered sdp attributes names
1850 * (ie: not prefixed with 'x-') in order to avoid
1851 * collision with gstreamer standard caps properties names
1854 gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
1856 if (attributes->len > 0) {
1860 s = gst_caps_get_structure (caps, 0);
1862 for (i = 0; i < attributes->len; i++) {
1863 GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
1864 gchar *tofree, *key;
1868 /* skip some of the attribute we already handle */
1869 if (!strcmp (key, "fmtp"))
1871 if (!strcmp (key, "rtpmap"))
1873 if (!strcmp (key, "control"))
1875 if (!strcmp (key, "range"))
1877 if (g_str_equal (key, "key-mgmt")) {
1878 parse_keymgmt (attr->value, caps);
1882 /* string must be valid UTF8 */
1883 if (!g_utf8_validate (attr->value, -1, NULL))
1886 if (!g_str_has_prefix (key, "x-"))
1887 tofree = key = g_strdup_printf ("a-%s", key);
1891 GST_DEBUG ("adding caps: %s=%s", key, attr->value);
1892 gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
1898 static const gchar *
1899 rtsp_get_attribute_for_pt (const GstSDPMedia * media, const gchar * name,
1908 if ((attr = gst_sdp_media_get_attribute_val_n (media, name, i)) == NULL)
1911 if (sscanf (attr, "%d ", &val) != 1)
1921 * Mapping of caps to and from SDP fields:
1923 * a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1924 * a=fmtp:<payload> <param>[=<value>];...
1927 gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
1930 const gchar *rtpmap;
1934 gchar *params = NULL;
1940 /* get and parse rtpmap */
1941 rtpmap = rtsp_get_attribute_for_pt (media, "rtpmap", pt);
1944 ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, ¶ms);
1946 g_warning ("error parsing rtpmap, ignoring");
1950 /* dynamic payloads need rtpmap or we fail */
1951 if (rtpmap == NULL && pt >= 96)
1954 /* check if we have a rate, if not, we need to look up the rate from the
1955 * default rates based on the payload types. */
1957 const GstRTPPayloadInfo *info;
1959 if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
1960 /* dynamic types, use media and encoding_name */
1961 tmp = g_ascii_strdown (media->media, -1);
1962 info = gst_rtp_payload_info_for_name (tmp, name);
1965 /* static types, use payload type */
1966 info = gst_rtp_payload_info_for_pt (pt);
1970 if ((rate = info->clock_rate) == 0)
1973 /* we fail if we cannot find one */
1978 tmp = g_ascii_strdown (media->media, -1);
1979 caps = gst_caps_new_simple ("application/x-unknown",
1980 "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
1982 s = gst_caps_get_structure (caps, 0);
1984 gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
1986 /* encoding name must be upper case */
1988 tmp = g_ascii_strup (name, -1);
1989 gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
1993 /* params must be lower case */
1994 if (params != NULL) {
1995 tmp = g_ascii_strdown (params, -1);
1996 gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
2000 /* parse optional fmtp: field */
2001 if ((fmtp = rtsp_get_attribute_for_pt (media, "fmtp", pt))) {
2007 /* p is now of the format <payload> <param>[=<value>];... */
2008 PARSE_INT (p, " ", payload);
2009 if (payload != -1 && payload == pt) {
2013 /* <param>[=<value>] are separated with ';' */
2014 pairs = g_strsplit (p, ";", 0);
2015 for (i = 0; pairs[i]; i++) {
2017 const gchar *val, *key;
2019 /* the key may not have a '=', the value can have other '='s */
2020 valpos = strstr (pairs[i], "=");
2022 /* we have a '=' and thus a value, remove the '=' with \0 */
2024 /* value is everything between '=' and ';'. We split the pairs at ;
2025 * boundaries so we can take the remainder of the value. Some servers
2026 * put spaces around the value which we strip off here. Alternatively
2027 * we could strip those spaces in the depayloaders should these spaces
2028 * actually carry any meaning in the future. */
2029 val = g_strstrip (valpos + 1);
2031 /* simple <param>;.. is translated into <param>=1;... */
2034 /* strip the key of spaces, convert key to lowercase but not the value. */
2035 key = g_strstrip (pairs[i]);
2036 if (strlen (key) > 1) {
2037 tmp = g_ascii_strdown (key, -1);
2038 gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
2050 g_warning ("rtpmap type not given for dynamic payload %d", pt);
2055 g_warning ("rate unknown for payload type %d", pt);
2061 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
2062 gint * rtpport, gint * rtcpport)
2065 GstStateChangeReturn ret;
2066 GstElement *udpsrc0, *udpsrc1;
2067 gint tmp_rtp, tmp_rtcp;
2071 src = stream->parent;
2077 /* Start at next port */
2078 tmp_rtp = src->next_port_num;
2080 if (stream->is_ipv6)
2081 host = "udp://[::0]";
2083 host = "udp://0.0.0.0";
2085 /* try to allocate 2 UDP ports, the RTP port should be an even
2086 * number and the RTCP port should be the next (uneven) port */
2089 if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
2090 tmp_rtp >= src->client_port_range.max)
2093 udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2094 if (udpsrc0 == NULL)
2095 goto no_udp_protocol;
2096 g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
2098 if (src->udp_buffer_size != 0)
2099 g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
2102 ret = gst_element_set_state (udpsrc0, GST_STATE_READY);
2103 if (ret == GST_STATE_CHANGE_FAILURE) {
2105 GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
2108 if (++count > src->retry)
2111 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2112 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2113 gst_object_unref (udpsrc0);
2116 GST_DEBUG_OBJECT (src, "retry %d", count);
2119 goto no_udp_protocol;
2122 g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
2123 GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
2125 /* check if port is even */
2126 if ((tmp_rtp & 0x01) != 0) {
2127 /* port not even, close and allocate another */
2128 if (++count > src->retry)
2131 GST_DEBUG_OBJECT (src, "RTP port not even");
2133 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2134 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2135 gst_object_unref (udpsrc0);
2138 GST_DEBUG_OBJECT (src, "retry %d", count);
2143 /* allocate port+1 for RTCP now */
2144 udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2145 if (udpsrc1 == NULL)
2146 goto no_udp_rtcp_protocol;
2149 tmp_rtcp = tmp_rtp + 1;
2150 if (src->client_port_range.max > 0 && tmp_rtcp > src->client_port_range.max)
2153 g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
2155 GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
2156 ret = gst_element_set_state (udpsrc1, GST_STATE_READY);
2157 /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
2158 if (ret == GST_STATE_CHANGE_FAILURE) {
2159 GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
2161 if (++count > src->retry)
2164 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2165 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2166 gst_object_unref (udpsrc0);
2169 GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
2170 gst_element_set_state (udpsrc1, GST_STATE_NULL);
2171 gst_object_unref (udpsrc1);
2175 GST_DEBUG_OBJECT (src, "retry %d", count);
2179 /* all fine, do port check */
2180 g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
2181 g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
2183 /* this should not happen... */
2184 if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
2187 /* we keep these elements, we configure all in configure_transport when the
2188 * server told us to really use the UDP ports. */
2189 stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
2190 stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
2191 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
2192 gst_element_set_locked_state (stream->udpsrc[1], TRUE);
2194 /* keep track of next available port number when we have a range
2196 if (src->next_port_num != 0)
2197 src->next_port_num = tmp_rtcp + 1;
2204 GST_DEBUG_OBJECT (src, "could not get UDP source");
2209 GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
2213 no_udp_rtcp_protocol:
2215 GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
2220 GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
2221 tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
2227 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2228 gst_object_unref (udpsrc0);
2231 gst_element_set_state (udpsrc1, GST_STATE_NULL);
2232 gst_object_unref (udpsrc1);
2239 gst_rtspsrc_set_state (GstRTSPSrc * src, GstState state)
2244 gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
2246 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2247 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2250 for (i = 0; i < 2; i++) {
2251 if (stream->udpsrc[i])
2252 gst_element_set_state (stream->udpsrc[i], state);
2258 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
2265 event = gst_event_new_flush_start ();
2266 GST_DEBUG_OBJECT (src, "start flush");
2268 state = GST_STATE_PAUSED;
2270 event = gst_event_new_flush_stop (FALSE);
2271 GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
2274 state = GST_STATE_PLAYING;
2276 state = GST_STATE_PAUSED;
2278 gst_rtspsrc_push_event (src, event);
2279 gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
2280 gst_rtspsrc_set_state (src, state);
2283 static GstRTSPResult
2284 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
2285 GstRTSPMessage * message, GTimeVal * timeout)
2290 ret = gst_rtsp_connection_send (conn, message, timeout);
2292 ret = GST_RTSP_ERROR;
2297 static GstRTSPResult
2298 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
2299 GstRTSPMessage * message, GTimeVal * timeout)
2304 ret = gst_rtsp_connection_receive (conn, message, timeout);
2306 ret = GST_RTSP_ERROR;
2312 gst_rtspsrc_get_position (GstRTSPSrc * src)
2317 query = gst_query_new_position (GST_FORMAT_TIME);
2318 /* should be known somewhere down the stream (e.g. jitterbuffer) */
2319 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2320 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2324 if (stream->srcpad) {
2325 if (gst_pad_query (stream->srcpad, query)) {
2326 gst_query_parse_position (query, &fmt, &pos);
2327 GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
2328 GST_TIME_ARGS (pos));
2329 src->last_pos = pos;
2339 gst_rtspsrc_do_seek (GstRTSPSrc * src, GstSegment * segment)
2341 src->state = GST_RTSP_STATE_SEEKING;
2342 /* PLAY will add the range header now. */
2343 src->need_range = TRUE;
2349 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
2354 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2356 gboolean flush, skip;
2359 GstSegment seeksegment = { 0, };
2363 GST_DEBUG_OBJECT (src, "doing seek with event");
2365 gst_event_parse_seek (event, &rate, &format, &flags,
2366 &cur_type, &cur, &stop_type, &stop);
2368 /* no negative rates yet */
2372 /* we need TIME format */
2373 if (format != src->segment.format)
2376 GST_DEBUG_OBJECT (src, "doing seek without event");
2378 cur_type = GST_SEEK_TYPE_SET;
2379 stop_type = GST_SEEK_TYPE_SET;
2382 /* get flush flag */
2383 flush = flags & GST_SEEK_FLAG_FLUSH;
2384 skip = flags & GST_SEEK_FLAG_SKIP;
2386 /* now we need to make sure the streaming thread is stopped. We do this by
2387 * either sending a FLUSH_START event downstream which will cause the
2388 * streaming thread to stop with a WRONG_STATE.
2389 * For a non-flushing seek we simply pause the task, which will happen as soon
2390 * as it completes one iteration (and thus might block when the sink is
2391 * blocking in preroll). */
2393 GST_DEBUG_OBJECT (src, "starting flush");
2394 gst_rtspsrc_flush (src, TRUE, FALSE);
2397 gst_task_pause (src->task);
2401 /* we should now be able to grab the streaming thread because we stopped it
2402 * with the above flush/pause code */
2403 GST_RTSP_STREAM_LOCK (src);
2405 GST_DEBUG_OBJECT (src, "stopped streaming");
2407 /* stop flushing the rtsp connection so we can send PAUSE/PLAY below */
2408 gst_rtspsrc_connection_flush (src, FALSE);
2410 /* copy segment, we need this because we still need the old
2411 * segment when we close the current segment. */
2412 memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2414 /* configure the seek parameters in the seeksegment. We will then have the
2415 * right values in the segment to perform the seek */
2417 GST_DEBUG_OBJECT (src, "configuring seek");
2418 gst_segment_do_seek (&seeksegment, rate, format, flags,
2419 cur_type, cur, stop_type, stop, &update);
2422 /* figure out the last position we need to play. If it's configured (stop !=
2423 * -1), use that, else we play until the total duration of the file */
2424 if ((stop = seeksegment.stop) == -1)
2425 stop = seeksegment.duration;
2427 playing = (src->state == GST_RTSP_STATE_PLAYING);
2429 /* if we were playing, pause first */
2431 /* obtain current position in case seek fails */
2432 gst_rtspsrc_get_position (src);
2433 gst_rtspsrc_pause (src, FALSE);
2437 gst_rtspsrc_do_seek (src, &seeksegment);
2439 /* and continue playing */
2441 gst_rtspsrc_play (src, &seeksegment, FALSE);
2443 /* prepare for streaming again */
2445 /* if we started flush, we stop now */
2446 GST_DEBUG_OBJECT (src, "stopping flush");
2447 gst_rtspsrc_flush (src, FALSE, playing);
2450 /* now we did the seek and can activate the new segment values */
2451 memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2453 /* if we're doing a segment seek, post a SEGMENT_START message */
2454 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2455 gst_element_post_message (GST_ELEMENT_CAST (src),
2456 gst_message_new_segment_start (GST_OBJECT_CAST (src),
2457 src->segment.format, src->segment.position));
2460 /* now create the newsegment */
2461 GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2462 " to %" G_GINT64_FORMAT, src->segment.position, stop);
2465 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2466 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2467 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2468 stream->discont = TRUE;
2471 GST_RTSP_STREAM_UNLOCK (src);
2478 GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2483 GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2489 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2493 gboolean res = TRUE;
2496 src = GST_RTSPSRC_CAST (parent);
2498 GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2499 GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2501 switch (GST_EVENT_TYPE (event)) {
2502 case GST_EVENT_SEEK:
2503 res = gst_rtspsrc_perform_seek (src, event);
2507 case GST_EVENT_NAVIGATION:
2508 case GST_EVENT_LATENCY:
2516 if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2517 res = gst_pad_send_event (target, event);
2518 gst_object_unref (target);
2520 gst_event_unref (event);
2523 gst_event_unref (event);
2529 /* this is the final event function we receive on the internal source pad when
2530 * we deal with TCP connections */
2532 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2537 GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2539 switch (GST_EVENT_TYPE (event)) {
2540 case GST_EVENT_SEEK:
2542 case GST_EVENT_NAVIGATION:
2543 case GST_EVENT_LATENCY:
2545 gst_event_unref (event);
2552 /* this is the final query function we receive on the internal source pad when
2553 * we deal with TCP connections */
2555 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2559 gboolean res = TRUE;
2561 src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2563 GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2564 GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2566 switch (GST_QUERY_TYPE (query)) {
2567 case GST_QUERY_POSITION:
2572 case GST_QUERY_DURATION:
2576 gst_query_parse_duration (query, &format, NULL);
2579 case GST_FORMAT_TIME:
2580 gst_query_set_duration (query, format, src->segment.duration);
2588 case GST_QUERY_LATENCY:
2590 /* we are live with a min latency of 0 and unlimited max latency, this
2591 * result will be updated by the session manager if there is any. */
2592 gst_query_set_latency (query, TRUE, 0, -1);
2602 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2604 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2608 gboolean res = FALSE;
2610 src = GST_RTSPSRC_CAST (parent);
2612 GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2613 GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2615 switch (GST_QUERY_TYPE (query)) {
2616 case GST_QUERY_DURATION:
2620 gst_query_parse_duration (query, &format, NULL);
2623 case GST_FORMAT_TIME:
2624 gst_query_set_duration (query, format, src->segment.duration);
2632 case GST_QUERY_SEEKING:
2636 gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2637 if (format == GST_FORMAT_TIME) {
2639 src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2641 /* seeking without duration is unlikely */
2642 seekable = seekable && src->seekable && src->segment.duration &&
2643 GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2645 /* FIXME ?? should we have 0 and segment.duration here; see demuxers */
2646 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
2647 src->segment.start, src->segment.stop);
2656 uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2658 gst_query_set_uri (query, uri);
2666 GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2668 /* forward the query to the proxy target pad */
2670 res = gst_pad_query (target, query);
2671 gst_object_unref (target);
2680 /* callback for RTCP messages to be sent to the server when operating in TCP
2682 static GstFlowReturn
2683 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2686 GstRTSPStream *stream;
2687 GstFlowReturn res = GST_FLOW_OK;
2692 GstRTSPMessage message = { 0 };
2693 GstRTSPConnection *conn;
2695 stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2696 src = stream->parent;
2698 gst_buffer_map (buffer, &map, GST_MAP_READ);
2702 gst_rtsp_message_init_data (&message, stream->channel[1]);
2704 /* lend the body data to the message */
2705 gst_rtsp_message_take_body (&message, data, size);
2707 if (stream->conninfo.connection)
2708 conn = stream->conninfo.connection;
2710 conn = src->conninfo.connection;
2712 GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2713 ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2714 GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2716 /* and steal it away again because we will free it when unreffing the
2718 gst_rtsp_message_steal_body (&message, &data, &size);
2719 gst_rtsp_message_unset (&message);
2721 gst_buffer_unmap (buffer, &map);
2722 gst_buffer_unref (buffer);
2727 static GstPadProbeReturn
2728 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2730 GstRTSPSrc *src = user_data;
2732 GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2733 GST_DEBUG_PAD_NAME (pad));
2735 /* activate the streams */
2736 GST_OBJECT_LOCK (src);
2737 if (!src->need_activate)
2740 src->need_activate = FALSE;
2741 GST_OBJECT_UNLOCK (src);
2743 gst_rtspsrc_activate_streams (src);
2745 return GST_PAD_PROBE_OK;
2749 GST_OBJECT_UNLOCK (src);
2750 return GST_PAD_PROBE_OK;
2755 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
2757 GstPad *gpad = GST_PAD_CAST (user_data);
2759 GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
2760 gst_pad_store_sticky_event (gpad, *event);
2765 /* this callback is called when the session manager generated a new src pad with
2766 * payloaded RTP packets. We simply ghost the pad here. */
2768 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2771 GstPadTemplate *template;
2774 GstRTSPStream *stream;
2777 GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2779 GST_RTSP_STATE_LOCK (src);
2781 name = gst_object_get_name (GST_OBJECT_CAST (pad));
2782 if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2783 goto unknown_stream;
2785 GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2787 stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2789 goto unknown_stream;
2792 stream->ssrc = ssrc;
2794 /* we'll add it later see below */
2795 stream->added = TRUE;
2797 /* check if we added all streams */
2799 for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
2800 GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
2802 GST_DEBUG_OBJECT (src, "stream %p, container %d, added %d, setup %d",
2803 ostream, ostream->container, ostream->added, ostream->setup);
2805 /* if we find a stream for which we did a setup that is not added, we
2806 * need to wait some more */
2807 if (ostream->setup && !ostream->added) {
2812 GST_RTSP_STATE_UNLOCK (src);
2814 /* create a new pad we will use to stream to */
2815 template = gst_static_pad_template_get (&rtptemplate);
2816 stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2817 gst_object_unref (template);
2820 gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2821 gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2822 gst_pad_set_active (stream->srcpad, TRUE);
2823 gst_pad_sticky_events_foreach (pad, copy_sticky_events, stream->srcpad);
2824 gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2827 GST_DEBUG_OBJECT (src, "We added all streams");
2828 /* when we get here, all stream are added and we can fire the no-more-pads
2830 gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2838 GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2839 GST_RTSP_STATE_UNLOCK (src);
2846 stream_get_caps_for_pt (GstRTSPStream * stream, guint pt)
2850 len = stream->ptmap->len;
2851 for (i = 0; i < len; i++) {
2852 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
2860 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2862 GstRTSPStream *stream;
2865 GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2867 GST_RTSP_STATE_LOCK (src);
2868 stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2870 goto unknown_stream;
2872 if ((caps = stream_get_caps_for_pt (stream, pt)))
2873 gst_caps_ref (caps);
2874 GST_RTSP_STATE_UNLOCK (src);
2880 GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2881 GST_RTSP_STATE_UNLOCK (src);
2887 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2889 GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2895 gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
2901 GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2907 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2909 GstRTSPSrc *src = stream->parent;
2912 g_object_get (source, "ssrc", &ssrc, NULL);
2914 GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
2915 ssrc, stream->ssrc, stream->id);
2917 if (ssrc == stream->ssrc)
2918 gst_rtspsrc_do_stream_eos (src, stream);
2922 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2924 GstRTSPSrc *src = stream->parent;
2927 g_object_get (source, "ssrc", &ssrc, NULL);
2929 GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
2930 ssrc, stream->ssrc, stream->id);
2932 if (ssrc == stream->ssrc)
2933 gst_rtspsrc_do_stream_eos (src, stream);
2937 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2939 GstRTSPStream *stream;
2941 GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2943 /* get stream for session */
2944 stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2946 gst_rtspsrc_do_stream_eos (src, stream);
2951 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2953 GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2958 set_manager_buffer_mode (GstRTSPSrc * src)
2960 GObjectClass *klass;
2962 if (src->manager == NULL)
2965 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2967 if (!g_object_class_find_property (klass, "buffer-mode"))
2970 if (src->buffer_mode != BUFFER_MODE_AUTO) {
2971 g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2976 GST_DEBUG_OBJECT (src,
2977 "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
2979 if (src->provided_clock) {
2980 GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
2982 if (clock == src->provided_clock) {
2983 GST_DEBUG_OBJECT (src, "selected synced");
2984 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
2987 gst_object_unref (clock);
2992 /* Otherwise fall-through and use another buffer mode */
2994 gst_object_unref (clock);
2997 GST_DEBUG_OBJECT (src, "auto buffering mode");
2998 if (src->use_buffering) {
2999 GST_DEBUG_OBJECT (src, "selected buffer");
3000 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
3002 GST_DEBUG_OBJECT (src, "selected slave");
3003 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
3008 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
3010 GST_DEBUG ("request key %u", ssrc);
3011 return gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
3015 request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
3017 GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3018 if (stream->id != session)
3021 if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3022 stream->profile != GST_RTSP_PROFILE_SAVPF)
3025 if (stream->srtpdec == NULL) {
3028 name = g_strdup_printf ("srtpdec_%u", session);
3029 stream->srtpdec = gst_element_factory_make ("srtpdec", name);
3032 g_signal_connect (stream->srtpdec, "request-key",
3033 (GCallback) request_key, stream);
3035 return gst_object_ref (stream->srtpdec);
3039 request_rtcp_encoder (GstElement * rtpbin, guint session,
3040 GstRTSPStream * stream)
3045 GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3046 if (stream->id != session)
3049 if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3050 stream->profile != GST_RTSP_PROFILE_SAVPF)
3053 if (stream->srtpenc == NULL) {
3056 name = g_strdup_printf ("srtpenc_%u", session);
3057 stream->srtpenc = gst_element_factory_make ("srtpenc", name);
3060 /* get RTCP crypto parameters from caps */
3061 s = gst_caps_get_structure (stream->srtcpparams, 0);
3065 GType ciphertype, authtype;
3066 GValue rtcp_cipher = G_VALUE_INIT, rtcp_auth = G_VALUE_INIT;
3068 ciphertype = g_type_from_name ("GstSrtpCipherType");
3069 authtype = g_type_from_name ("GstSrtpAuthType");
3070 g_value_init (&rtcp_cipher, ciphertype);
3071 g_value_init (&rtcp_auth, authtype);
3073 str = gst_structure_get_string (s, "srtcp-cipher");
3074 gst_value_deserialize (&rtcp_cipher, str);
3075 str = gst_structure_get_string (s, "srtcp-auth");
3076 gst_value_deserialize (&rtcp_auth, str);
3077 gst_structure_get (s, "srtp-key", GST_TYPE_BUFFER, &buf, NULL);
3079 g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-cipher",
3081 g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-auth",
3083 g_object_set (stream->srtpenc, "key", buf, NULL);
3085 g_value_unset (&rtcp_cipher);
3086 g_value_unset (&rtcp_auth);
3089 name = g_strdup_printf ("rtcp_sink_%d", session);
3090 pad = gst_element_get_request_pad (stream->srtpenc, name);
3092 gst_object_unref (pad);
3094 return gst_object_ref (stream->srtpenc);
3098 /* try to get and configure a manager */
3100 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
3101 GstRTSPTransport * transport)
3103 const gchar *manager;
3105 GstStateChangeReturn ret;
3107 /* find a manager */
3108 if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
3112 GST_DEBUG_OBJECT (src, "using manager %s", manager);
3114 /* configure the manager */
3115 if (src->manager == NULL) {
3116 GObjectClass *klass;
3118 if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
3120 if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
3124 goto use_no_manager;
3126 if (!(src->manager = gst_element_factory_make (manager, "manager")))
3127 goto manager_failed;
3130 /* we manage this element */
3131 gst_element_set_locked_state (src->manager, TRUE);
3132 gst_bin_add (GST_BIN_CAST (src), src->manager);
3134 ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
3135 if (ret == GST_STATE_CHANGE_FAILURE)
3136 goto start_manager_failure;
3138 g_object_set (src->manager, "latency", src->latency, NULL);
3140 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3142 if (g_object_class_find_property (klass, "ntp-sync")) {
3143 g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
3146 if (g_object_class_find_property (klass, "use-pipeline-clock")) {
3147 g_object_set (src->manager, "use-pipeline-clock",
3148 src->use_pipeline_clock, NULL);
3151 if (src->sdes && g_object_class_find_property (klass, "sdes")) {
3152 g_object_set (src->manager, "sdes", src->sdes, NULL);
3155 if (g_object_class_find_property (klass, "drop-on-latency")) {
3156 g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
3160 /* buffer mode pauses are handled by adding offsets to buffer times,
3161 * but some depayloaders may have a hard time syncing output times
3162 * with such input times, e.g. container ones, most notably ASF */
3163 /* TODO alternatives are having an event that indicates these shifts,
3164 * or having rtsp extensions provide suggestion on buffer mode */
3165 /* valid duration implies not likely live pipeline,
3166 * so slaving in jitterbuffer does not make much sense
3167 * (and might mess things up due to bursts) */
3168 if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
3169 src->segment.duration && !stream->container) {
3170 src->use_buffering = TRUE;
3172 src->use_buffering = FALSE;
3175 set_manager_buffer_mode (src);
3177 /* connect to signals */
3178 GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
3180 src->manager_sig_id =
3181 g_signal_connect (src->manager, "pad-added",
3182 (GCallback) new_manager_pad, src);
3183 src->manager_ptmap_id =
3184 g_signal_connect (src->manager, "request-pt-map",
3185 (GCallback) request_pt_map, src);
3187 g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
3190 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
3193 g_signal_connect (src->manager, "request-rtp-decoder",
3194 (GCallback) request_rtp_decoder, stream);
3195 g_signal_connect (src->manager, "request-rtcp-decoder",
3196 (GCallback) request_rtp_decoder, stream);
3197 g_signal_connect (src->manager, "request-rtcp-encoder",
3198 (GCallback) request_rtcp_encoder, stream);
3200 /* we stream directly to the manager, get some pads. Each RTSP stream goes
3201 * into a separate RTP session. */
3202 name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
3203 stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
3205 name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
3206 stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
3209 /* now configure the bandwidth in the manager */
3210 if (g_signal_lookup ("get-internal-session",
3211 G_OBJECT_TYPE (src->manager)) != 0) {
3212 GObject *rtpsession;
3214 g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
3217 GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
3219 stream->session = rtpsession;
3221 if (stream->as_bandwidth != -1) {
3222 GST_INFO_OBJECT (src, "setting AS: %f",
3223 (gdouble) (stream->as_bandwidth * 1000));
3224 g_object_set (rtpsession, "bandwidth",
3225 (gdouble) (stream->as_bandwidth * 1000), NULL);
3227 if (stream->rr_bandwidth != -1) {
3228 GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
3229 g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
3232 if (stream->rs_bandwidth != -1) {
3233 GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
3234 g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
3238 g_object_set (rtpsession, "probation", src->probation, NULL);
3240 g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
3242 g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
3244 g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
3246 g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
3248 g_signal_connect (rtpsession, "on-ssrc-active",
3249 (GCallback) on_ssrc_active, stream);
3260 GST_DEBUG_OBJECT (src, "cannot get a session manager");
3265 GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
3268 start_manager_failure:
3270 GST_DEBUG_OBJECT (src, "could not start session manager");
3275 /* free the UDP sources allocated when negotiating a transport.
3276 * This function is called when the server negotiated to a transport where the
3277 * UDP sources are not needed anymore, such as TCP or multicast. */
3279 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
3283 for (i = 0; i < 2; i++) {
3284 if (stream->udpsrc[i]) {
3285 GST_DEBUG ("free UDP source %d for stream %p", i, stream);
3286 gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
3287 gst_object_unref (stream->udpsrc[i]);
3288 stream->udpsrc[i] = NULL;
3293 /* for TCP, create pads to send and receive data to and from the manager and to
3294 * intercept various events and queries
3297 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
3298 GstRTSPTransport * transport, GstPad ** outpad)
3301 GstPadTemplate *template;
3302 GstPad *pad0, *pad1;
3304 /* configure for interleaved delivery, nothing needs to be done
3305 * here, the loop function will call the chain functions of the
3306 * session manager. */
3307 stream->channel[0] = transport->interleaved.min;
3308 stream->channel[1] = transport->interleaved.max;
3309 GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
3310 stream->channel[0], stream->channel[1]);
3312 /* we can remove the allocated UDP ports now */
3313 gst_rtspsrc_stream_free_udp (stream);
3315 /* no session manager, send data to srcpad directly */
3316 if (!stream->channelpad[0]) {
3317 GST_DEBUG_OBJECT (src, "no manager, creating pad");
3319 /* create a new pad we will use to stream to */
3320 name = g_strdup_printf ("stream_%u", stream->id);
3321 template = gst_static_pad_template_get (&rtptemplate);
3322 stream->channelpad[0] = gst_pad_new_from_template (template, name);
3323 gst_object_unref (template);
3326 /* set caps and activate */
3327 gst_pad_use_fixed_caps (stream->channelpad[0]);
3328 gst_pad_set_active (stream->channelpad[0], TRUE);
3330 *outpad = gst_object_ref (stream->channelpad[0]);
3332 GST_DEBUG_OBJECT (src, "using manager source pad");
3334 template = gst_static_pad_template_get (&anysrctemplate);
3336 /* allocate pads for sending the channel data into the manager */
3337 pad0 = gst_pad_new_from_template (template, "internalsrc_0");
3338 gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
3339 gst_object_unref (stream->channelpad[0]);
3340 stream->channelpad[0] = pad0;
3341 gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
3342 gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
3343 gst_pad_set_element_private (pad0, src);
3344 gst_pad_set_active (pad0, TRUE);
3346 if (stream->channelpad[1]) {
3347 /* if we have a sinkpad for the other channel, create a pad and link to the
3349 pad1 = gst_pad_new_from_template (template, "internalsrc_1");
3350 gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
3351 gst_pad_link_full (pad1, stream->channelpad[1],
3352 GST_PAD_LINK_CHECK_NOTHING);
3353 gst_object_unref (stream->channelpad[1]);
3354 stream->channelpad[1] = pad1;
3355 gst_pad_set_active (pad1, TRUE);
3357 gst_object_unref (template);
3359 /* setup RTCP transport back to the server if we have to. */
3360 if (src->manager && src->do_rtcp) {
3363 template = gst_static_pad_template_get (&anysinktemplate);
3365 stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
3366 gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
3367 gst_pad_set_element_private (stream->rtcppad, stream);
3368 gst_pad_set_active (stream->rtcppad, TRUE);
3370 /* get session RTCP pad */
3371 name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3372 pad = gst_element_get_request_pad (src->manager, name);
3377 gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3378 gst_object_unref (pad);
3381 gst_object_unref (template);
3387 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3388 GstRTSPTransport * transport, const gchar ** destination, gint * min,
3389 gint * max, guint * ttl)
3391 if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3393 if (!(*destination = transport->destination))
3394 *destination = stream->destination;
3397 /* transport first */
3398 *min = transport->port.min;
3399 *max = transport->port.max;
3400 if (*min == -1 && *max == -1) {
3401 /* then try from SDP */
3402 if (stream->port != 0) {
3403 *min = stream->port;
3404 *max = stream->port + 1;
3410 if (!(*ttl = transport->ttl))
3415 /* first take the source, then the endpoint to figure out where to send
3417 if (!(*destination = transport->source)) {
3418 if (src->conninfo.connection)
3419 *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3420 else if (stream->conninfo.connection)
3422 gst_rtsp_connection_get_ip (stream->conninfo.connection);
3426 /* for unicast we only expect the ports here */
3427 *min = transport->server_port.min;
3428 *max = transport->server_port.max;
3433 /* For multicast create UDP sources and join the multicast group. */
3435 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3436 GstRTSPTransport * transport, GstPad ** outpad)
3439 const gchar *destination;
3442 GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3444 /* we can remove the allocated UDP ports now */
3445 gst_rtspsrc_stream_free_udp (stream);
3447 gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3450 /* we need a destination now */
3451 if (destination == NULL)
3452 goto no_destination;
3454 /* we really need ports now or we won't be able to receive anything at all */
3455 if (min == -1 && max == -1)
3458 GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3459 destination, min, max);
3461 /* creating UDP source for RTP */
3463 uri = g_strdup_printf ("udp://%s:%d", destination, min);
3465 gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3467 if (stream->udpsrc[0] == NULL)
3470 /* take ownership */
3471 gst_object_ref_sink (stream->udpsrc[0]);
3473 if (src->udp_buffer_size != 0)
3474 g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3475 src->udp_buffer_size, NULL);
3477 if (src->multi_iface != NULL)
3478 g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3479 src->multi_iface, NULL);
3482 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3483 gst_element_set_state (stream->udpsrc[0], GST_STATE_READY);
3486 /* creating another UDP source for RTCP */
3490 uri = g_strdup_printf ("udp://%s:%d", destination, max);
3492 gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3494 if (stream->udpsrc[1] == NULL)
3497 if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3498 stream->profile == GST_RTSP_PROFILE_SAVPF)
3499 caps = gst_caps_new_empty_simple ("application/x-srtcp");
3501 caps = gst_caps_new_empty_simple ("application/x-rtcp");
3502 g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3503 gst_caps_unref (caps);
3505 /* take ownership */
3506 gst_object_ref_sink (stream->udpsrc[1]);
3508 if (src->multi_iface != NULL)
3509 g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3510 src->multi_iface, NULL);
3512 gst_element_set_state (stream->udpsrc[1], GST_STATE_READY);
3519 GST_DEBUG_OBJECT (src, "no UDP source element found");
3524 GST_DEBUG_OBJECT (src, "no destination found");
3529 GST_DEBUG_OBJECT (src, "no ports found");
3534 /* configure the remainder of the UDP ports */
3536 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3537 GstRTSPTransport * transport, GstPad ** outpad)
3539 /* we manage the UDP elements now. For unicast, the UDP sources where
3540 * allocated in the stream when we suggested a transport. */
3541 if (stream->udpsrc[0]) {
3544 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3545 gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3547 GST_DEBUG_OBJECT (src, "setting up UDP source");
3549 /* configure a timeout on the UDP port. When the timeout message is
3550 * posted, we assume UDP transport is not possible. We reconnect using TCP
3552 g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3553 src->udp_timeout * 1000, NULL);
3555 if ((caps = stream_get_caps_for_pt (stream, stream->default_pt)))
3556 g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3558 /* get output pad of the UDP source. */
3559 *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3561 /* save it so we can unblock */
3562 stream->blockedpad = *outpad;
3564 /* configure pad block on the pad. As soon as there is dataflow on the
3565 * UDP source, we know that UDP is not blocked by a firewall and we can
3566 * configure all the streams to let the application autoplug decoders. */
3568 gst_pad_add_probe (stream->blockedpad,
3569 GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
3570 GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
3572 if (stream->channelpad[0]) {
3573 GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3574 /* configure for UDP delivery, we need to connect the UDP pads to
3575 * the session plugin. */
3576 gst_pad_link_full (*outpad, stream->channelpad[0],
3577 GST_PAD_LINK_CHECK_NOTHING);
3578 gst_object_unref (*outpad);
3580 /* we connected to pad-added signal to get pads from the manager */
3582 GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3587 if (stream->udpsrc[1]) {
3590 gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3591 gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3593 if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3594 stream->profile == GST_RTSP_PROFILE_SAVPF)
3595 caps = gst_caps_new_empty_simple ("application/x-srtcp");
3597 caps = gst_caps_new_empty_simple ("application/x-rtcp");
3598 g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3599 gst_caps_unref (caps);
3601 if (stream->channelpad[1]) {
3604 GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3606 pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3607 gst_pad_link_full (pad, stream->channelpad[1],
3608 GST_PAD_LINK_CHECK_NOTHING);
3609 gst_object_unref (pad);
3611 /* leave unlinked */
3617 /* configure the UDP sink back to the server for status reports */
3619 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3620 GstRTSPStream * stream, GstRTSPTransport * transport)
3623 gint rtp_port, rtcp_port;
3624 gboolean do_rtp, do_rtcp;
3625 const gchar *destination;
3630 /* get transport info */
3631 gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3632 &rtp_port, &rtcp_port, &ttl);
3634 /* see what we need to do */
3635 do_rtp = (rtp_port != -1);
3636 /* it's possible that the server does not want us to send RTCP in which case
3638 do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3640 /* we need a destination when we have RTP or RTCP ports */
3641 if (destination == NULL && (do_rtp || do_rtcp))
3642 goto no_destination;
3644 /* try to construct the fakesrc to the RTP port of the server to open up any
3647 GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3650 uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3651 stream->udpsink[0] =
3652 gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3654 if (stream->udpsink[0] == NULL)
3655 goto no_sink_element;
3657 /* don't join multicast group, we will have the source socket do that */
3658 /* no sync or async state changes needed */
3659 g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3660 "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3662 g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3664 if (stream->udpsrc[0]) {
3665 /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3666 * so that NAT firewalls will open a hole for us */
3667 g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3668 GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3669 /* configure socket and make sure udpsink does not close it when shutting
3670 * down, it belongs to udpsrc after all. */
3671 g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3672 "close-socket", FALSE, NULL);
3673 g_object_unref (socket);
3676 /* the source for the dummy packets to open up NAT */
3677 stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3678 if (stream->fakesrc == NULL)
3679 goto no_fakesrc_element;
3681 /* random data in 5 buffers, a size of 200 bytes should be fine */
3682 g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3683 "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3685 /* we don't want to consider this a sink */
3686 GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
3688 /* keep everything locked */
3689 gst_element_set_locked_state (stream->udpsink[0], TRUE);
3690 gst_element_set_locked_state (stream->fakesrc, TRUE);
3692 gst_object_ref (stream->udpsink[0]);
3693 gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3694 gst_object_ref (stream->fakesrc);
3695 gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3697 gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
3698 "sink", GST_PAD_LINK_CHECK_NOTHING);
3701 GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3704 uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3705 stream->udpsink[1] =
3706 gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3708 if (stream->udpsink[1] == NULL)
3709 goto no_sink_element;
3711 /* don't join multicast group, we will have the source socket do that */
3712 /* no sync or async state changes needed */
3713 g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3714 "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3716 g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3718 if (stream->udpsrc[1]) {
3719 /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3720 * because some servers check the port number of where it sends RTCP to identify
3721 * the RTCP packets it receives */
3722 g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3723 GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3724 /* configure socket and make sure udpsink does not close it when shutting
3725 * down, it belongs to udpsrc after all. */
3726 g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3727 "close-socket", FALSE, NULL);
3728 g_object_unref (socket);
3731 /* we don't want to consider this a sink */
3732 GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
3734 /* we keep this playing always */
3735 gst_element_set_locked_state (stream->udpsink[1], TRUE);
3736 gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3738 gst_object_ref (stream->udpsink[1]);
3739 gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3741 stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3743 /* get session RTCP pad */
3744 name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3745 pad = gst_element_get_request_pad (src->manager, name);
3750 gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3751 gst_object_unref (pad);
3760 GST_DEBUG_OBJECT (src, "no destination address specified");
3765 GST_DEBUG_OBJECT (src, "no UDP sink element found");
3770 GST_DEBUG_OBJECT (src, "no fakesrc element found");
3775 /* sets up all elements needed for streaming over the specified transport.
3776 * Does not yet expose the element pads, this will be done when there is actuall
3777 * dataflow detected, which might never happen when UDP is blocked in a
3778 * firewall, for example.
3781 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3782 GstRTSPTransport * transport)
3785 GstPad *outpad = NULL;
3786 GstPadTemplate *template;
3788 const gchar *media_type;
3791 src = stream->parent;
3793 GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3795 /* get the proper media type for this stream now */
3796 if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
3797 goto unknown_transport;
3799 goto unknown_transport;
3801 /* configure the final media type */
3802 GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
3804 len = stream->ptmap->len;
3805 for (i = 0; i < len; i++) {
3807 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3809 if (item->caps == NULL)
3812 s = gst_caps_get_structure (item->caps, 0);
3813 gst_structure_set_name (s, media_type);
3814 /* set ssrc if known */
3815 if (transport->ssrc)
3816 gst_structure_set (s, "ssrc", G_TYPE_UINT, transport->ssrc, NULL);
3819 /* try to get and configure a manager, channelpad[0-1] will be configured with
3820 * the pads for the manager, or NULL when no manager is needed. */
3821 if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3824 switch (transport->lower_transport) {
3825 case GST_RTSP_LOWER_TRANS_TCP:
3826 if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3827 goto transport_failed;
3829 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3830 if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3831 goto transport_failed;
3832 /* fallthrough, the rest is the same for UDP and MCAST */
3833 case GST_RTSP_LOWER_TRANS_UDP:
3834 if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3835 goto transport_failed;
3836 /* configure udpsinks back to the server for RTCP messages and for the
3837 * dummy RTP messages to open NAT. */
3838 if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3839 goto transport_failed;
3842 goto unknown_transport;
3846 GST_DEBUG_OBJECT (src, "creating ghostpad");
3848 gst_pad_use_fixed_caps (outpad);
3850 /* create ghostpad, don't add just yet, this will be done when we activate
3852 name = g_strdup_printf ("stream_%u", stream->id);
3853 template = gst_static_pad_template_get (&rtptemplate);
3854 stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3855 gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3856 gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3857 gst_object_unref (template);
3860 gst_object_unref (outpad);
3862 /* mark pad as ok */
3863 stream->last_ret = GST_FLOW_OK;
3870 GST_DEBUG_OBJECT (src, "failed to configure transport");
3875 GST_DEBUG_OBJECT (src, "unknown transport");
3880 GST_DEBUG_OBJECT (src, "cannot get a session manager");
3885 /* send a couple of dummy random packets on the receiver RTP port to the server,
3886 * this should make a firewall think we initiated the data transfer and
3887 * hopefully allow packets to go from the sender port to our RTP receiver port */
3889 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3893 if (src->nat_method != GST_RTSP_NAT_DUMMY)
3896 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3897 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3899 if (stream->fakesrc && stream->udpsink[0]) {
3900 GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3901 gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3902 gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3903 gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3904 gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3910 /* Adds the source pads of all configured streams to the element.
3911 * This code is performed when we detected dataflow.
3913 * We detect dataflow from either the _loop function or with pad probes on the
3917 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3921 GST_DEBUG_OBJECT (src, "activating streams");
3923 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3924 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3926 if (stream->udpsrc[0]) {
3927 /* remove timeout, we are streaming now and timeouts will be handled by
3928 * the session manager and jitter buffer */
3929 g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3931 if (stream->srcpad) {
3932 GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3933 gst_pad_set_active (stream->srcpad, TRUE);
3935 /* if we don't have a session manager, set the caps now. If we have a
3936 * session, we will get a notification of the pad and the caps. */
3937 if (!src->manager) {
3940 caps = stream_get_caps_for_pt (stream, stream->default_pt);
3941 GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3942 gst_pad_set_caps (stream->srcpad, caps);
3945 if (!stream->added) {
3946 GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3947 gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3948 stream->added = TRUE;
3953 /* unblock all pads */
3954 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3955 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3957 if (stream->blockid) {
3958 GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3959 gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3960 stream->blockid = 0;
3968 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3969 gboolean reset_manager)
3972 guint64 start, stop;
3973 gdouble play_speed, play_scale;
3975 GST_DEBUG_OBJECT (src, "configuring stream caps");
3977 start = segment->position;
3978 stop = segment->duration;
3979 play_speed = segment->rate;
3980 play_scale = segment->applied_rate;
3982 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3983 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3989 len = stream->ptmap->len;
3990 for (j = 0; j < len; j++) {
3992 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, j);
3994 if (item->caps == NULL)
3997 caps = gst_caps_make_writable (item->caps);
3999 if (stream->timebase != -1)
4000 gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
4001 (guint) stream->timebase, NULL);
4002 if (stream->seqbase != -1)
4003 gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
4004 (guint) stream->seqbase, NULL);
4005 gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
4007 gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
4008 gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
4009 gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
4012 GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
4015 if (item->pt == stream->default_pt && stream->udpsrc[0]) {
4016 g_object_set (stream->udpsrc[0], "caps", caps, NULL);
4020 if (reset_manager && src->manager) {
4021 GST_DEBUG_OBJECT (src, "clear session");
4022 g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
4026 static GstFlowReturn
4027 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
4032 /* store the value */
4033 stream->last_ret = ret;
4035 /* if it's success we can return the value right away */
4036 if (ret == GST_FLOW_OK)
4039 /* any other error that is not-linked can be returned right
4041 if (ret != GST_FLOW_NOT_LINKED)
4044 /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4045 for (streams = src->streams; streams; streams = g_list_next (streams)) {
4046 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4048 ret = ostream->last_ret;
4049 /* some other return value (must be SUCCESS but we can return
4050 * other values as well) */
4051 if (ret != GST_FLOW_NOT_LINKED)
4054 /* if we get here, all other pads were unlinked and we return
4055 * NOT_LINKED then */
4061 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
4064 gboolean res = TRUE;
4066 /* only streams that have a connection to the outside world */
4070 if (stream->udpsrc[0]) {
4071 gst_event_ref (event);
4072 res = gst_element_send_event (stream->udpsrc[0], event);
4073 } else if (stream->channelpad[0]) {
4074 gst_event_ref (event);
4075 if (GST_PAD_IS_SRC (stream->channelpad[0]))
4076 res = gst_pad_push_event (stream->channelpad[0], event);
4078 res = gst_pad_send_event (stream->channelpad[0], event);
4081 if (stream->udpsrc[1]) {
4082 gst_event_ref (event);
4083 res &= gst_element_send_event (stream->udpsrc[1], event);
4084 } else if (stream->channelpad[1]) {
4085 gst_event_ref (event);
4086 if (GST_PAD_IS_SRC (stream->channelpad[1]))
4087 res &= gst_pad_push_event (stream->channelpad[1], event);
4089 res &= gst_pad_send_event (stream->channelpad[1], event);
4093 gst_event_unref (event);
4099 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
4102 gboolean res = TRUE;
4104 for (streams = src->streams; streams; streams = g_list_next (streams)) {
4105 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4107 gst_event_ref (event);
4108 res &= gst_rtspsrc_stream_push_event (src, ostream, event);
4110 gst_event_unref (event);
4115 static GstRTSPResult
4116 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4121 if (info->connection == NULL) {
4122 if (info->url == NULL) {
4123 GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
4124 if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
4128 /* create connection */
4129 GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
4130 if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
4131 goto could_not_create;
4134 g_free (info->url_str);
4135 info->url_str = gst_rtsp_url_get_request_uri (info->url);
4137 GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
4139 if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
4140 if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
4141 src->tls_validation_flags))
4142 GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
4144 if (src->tls_database)
4145 gst_rtsp_connection_set_tls_database (info->connection,
4149 if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
4150 gst_rtsp_connection_set_tunneled (info->connection, TRUE);
4152 if (src->proxy_host) {
4153 GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
4155 gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
4160 if (!info->connected) {
4163 GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
4164 ("Connecting to %s", info->location));
4165 GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
4167 gst_rtsp_connection_connect (info->connection,
4168 src->ptcp_timeout)) < 0)
4169 goto could_not_connect;
4171 info->connected = TRUE;
4178 GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
4183 gchar *str = gst_rtsp_strresult (res);
4184 GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
4190 gchar *str = gst_rtsp_strresult (res);
4191 GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
4197 static GstRTSPResult
4198 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
4201 GST_RTSP_STATE_LOCK (src);
4202 if (info->connected) {
4203 GST_DEBUG_OBJECT (src, "closing connection...");
4204 gst_rtsp_connection_close (info->connection);
4205 info->connected = FALSE;
4207 if (free && info->connection) {
4208 /* free connection */
4209 GST_DEBUG_OBJECT (src, "freeing connection...");
4210 gst_rtsp_connection_free (info->connection);
4211 info->connection = NULL;
4213 GST_RTSP_STATE_UNLOCK (src);
4217 static GstRTSPResult
4218 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4223 GST_DEBUG_OBJECT (src, "reconnecting connection...");
4224 gst_rtsp_conninfo_close (src, info, FALSE);
4225 res = gst_rtsp_conninfo_connect (src, info, async);
4231 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
4235 GST_DEBUG_OBJECT (src, "set flushing %d", flush);
4236 GST_RTSP_STATE_LOCK (src);
4237 if (src->conninfo.connection && src->conninfo.flushing != flush) {
4238 GST_DEBUG_OBJECT (src, "connection flush");
4239 gst_rtsp_connection_flush (src->conninfo.connection, flush);
4240 src->conninfo.flushing = flush;
4242 for (walk = src->streams; walk; walk = g_list_next (walk)) {
4243 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4244 if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
4245 GST_DEBUG_OBJECT (src, "stream %p flush", stream);
4246 gst_rtsp_connection_flush (stream->conninfo.connection, flush);
4247 stream->conninfo.flushing = flush;
4250 GST_RTSP_STATE_UNLOCK (src);
4253 /* FIXME, handle server request, reply with OK, for now */
4254 static GstRTSPResult
4255 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
4256 GstRTSPMessage * request)
4258 GstRTSPMessage response = { 0 };
4261 GST_DEBUG_OBJECT (src, "got server request message");
4264 gst_rtsp_message_dump (request);
4266 res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4268 if (res == GST_RTSP_ENOTIMPL) {
4269 /* default implementation, send OK */
4270 GST_DEBUG_OBJECT (src, "prepare OK reply");
4272 gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4277 /* let app parse and reply */
4278 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4279 0, request, &response);
4282 gst_rtsp_message_dump (&response);
4284 res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
4288 gst_rtsp_message_unset (&response);
4289 } else if (res == GST_RTSP_EEOF)
4297 gst_rtsp_message_unset (&response);
4302 /* send server keep-alive */
4303 static GstRTSPResult
4304 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4306 GstRTSPMessage request = { 0 };
4308 GstRTSPMethod method;
4309 const gchar *control;
4311 if (src->do_rtsp_keep_alive == FALSE) {
4312 GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4313 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4317 GST_DEBUG_OBJECT (src, "creating server keep-alive");
4319 /* find a method to use for keep-alive */
4320 if (src->methods & GST_RTSP_GET_PARAMETER)
4321 method = GST_RTSP_GET_PARAMETER;
4323 method = GST_RTSP_OPTIONS;
4325 control = get_aggregate_control (src);
4326 if (control == NULL)
4329 res = gst_rtsp_message_init_request (&request, method, control);
4334 gst_rtsp_message_dump (&request);
4337 gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
4342 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4343 gst_rtsp_message_unset (&request);
4350 GST_WARNING_OBJECT (src, "no control url to send keepalive");
4355 gchar *str = gst_rtsp_strresult (res);
4357 gst_rtsp_message_unset (&request);
4358 GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4359 ("Could not send keep-alive. (%s)", str));
4365 static GstFlowReturn
4366 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4368 GstFlowReturn ret = GST_FLOW_OK;
4370 GstRTSPStream *stream;
4371 GstPad *outpad = NULL;
4378 channel = message->type_data.data.channel;
4380 stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4382 goto unknown_stream;
4384 if (channel == stream->channel[0]) {
4385 outpad = stream->channelpad[0];
4387 } else if (channel == stream->channel[1]) {
4388 outpad = stream->channelpad[1];
4394 /* take a look at the body to figure out what we have */
4395 gst_rtsp_message_get_body (message, &data, &size);
4397 goto invalid_length;
4399 /* channels are not correct on some servers, do extra check */
4400 if (data[1] >= 200 && data[1] <= 204) {
4401 /* hmm RTCP message switch to the RTCP pad of the same stream. */
4402 outpad = stream->channelpad[1];
4406 /* we have no clue what this is, just ignore then. */
4408 goto unknown_stream;
4410 /* take the message body for further processing */
4411 gst_rtsp_message_steal_body (message, &data, &size);
4413 /* strip the trailing \0 */
4416 buf = gst_buffer_new ();
4417 gst_buffer_append_memory (buf,
4418 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4420 /* don't need message anymore */
4421 gst_rtsp_message_unset (message);
4423 GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4426 if (src->need_activate) {
4432 guint group_id = gst_util_group_id_next ();
4434 /* generate an SHA256 sum of the URI */
4435 cs = g_checksum_new (G_CHECKSUM_SHA256);
4436 uri = src->conninfo.location;
4437 g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4439 for (streams = src->streams; streams; streams = g_list_next (streams)) {
4440 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4443 g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4444 event = gst_event_new_stream_start (stream_id);
4445 gst_event_set_group_id (event, group_id);
4448 gst_rtspsrc_stream_push_event (src, ostream, event);
4450 g_checksum_free (cs);
4452 gst_rtspsrc_activate_streams (src);
4453 src->need_activate = FALSE;
4455 if ((event = src->start_segment) != NULL) {
4456 src->start_segment = NULL;
4457 gst_rtspsrc_push_event (src, event);
4460 if (src->base_time == -1) {
4461 /* Take current running_time. This timestamp will be put on
4462 * the first buffer of each stream because we are a live source and so we
4463 * timestamp with the running_time. When we are dealing with TCP, we also
4464 * only timestamp the first buffer (using the DISCONT flag) because a server
4465 * typically bursts data, for which we don't want to compensate by speeding
4466 * up the media. The other timestamps will be interpollated from this one
4467 * using the RTP timestamps. */
4468 GST_OBJECT_LOCK (src);
4469 if (GST_ELEMENT_CLOCK (src)) {
4471 GstClockTime base_time;
4473 now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4474 base_time = GST_ELEMENT_CAST (src)->base_time;
4476 src->base_time = now - base_time;
4478 GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4479 GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4481 GST_OBJECT_UNLOCK (src);
4484 if (stream->discont && !is_rtcp) {
4485 /* mark first RTP buffer as discont */
4486 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4487 stream->discont = FALSE;
4488 /* first buffer gets the timestamp, other buffers are not timestamped and
4489 * their presentation time will be interpollated from the rtp timestamps. */
4490 GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4491 GST_TIME_ARGS (src->base_time));
4493 GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4496 /* chain to the peer pad */
4497 if (GST_PAD_IS_SINK (outpad))
4498 ret = gst_pad_chain (outpad, buf);
4500 ret = gst_pad_push (outpad, buf);
4503 /* combine all stream flows for the data transport */
4504 ret = gst_rtspsrc_combine_flows (src, stream, ret);
4511 GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4512 gst_rtsp_message_unset (message);
4517 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4518 ("Short message received, ignoring."));
4519 gst_rtsp_message_unset (message);
4524 static GstFlowReturn
4525 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4527 GstRTSPMessage message = { 0 };
4529 GstFlowReturn ret = GST_FLOW_OK;
4530 GTimeVal tv_timeout;
4533 /* get the next timeout interval */
4534 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4536 /* see if the timeout period expired */
4537 if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4538 GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4539 /* send keep-alive, only act on interrupt, a warning will be posted for
4541 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4543 /* get new timeout */
4544 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4547 GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4548 tv_timeout.tv_sec, tv_timeout.tv_usec);
4550 /* protect the connection with the connection lock so that we can see when
4551 * we are finished doing server communication */
4553 gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4554 &message, src->ptcp_timeout);
4558 GST_DEBUG_OBJECT (src, "we received a server message");
4560 case GST_RTSP_EINTR:
4561 /* we got interrupted this means we need to stop */
4563 case GST_RTSP_ETIMEOUT:
4564 /* no reply, send keep alive */
4565 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4566 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4570 /* go EOS when the server closed the connection */
4576 switch (message.type) {
4577 case GST_RTSP_MESSAGE_REQUEST:
4578 /* server sends us a request message, handle it */
4580 gst_rtspsrc_handle_request (src, src->conninfo.connection,
4582 if (res == GST_RTSP_EEOF)
4585 goto handle_request_failed;
4587 case GST_RTSP_MESSAGE_RESPONSE:
4588 /* we ignore response messages */
4589 GST_DEBUG_OBJECT (src, "ignoring response message");
4591 gst_rtsp_message_dump (&message);
4593 case GST_RTSP_MESSAGE_DATA:
4594 GST_DEBUG_OBJECT (src, "got data message");
4595 ret = gst_rtspsrc_handle_data (src, &message);
4596 if (ret != GST_FLOW_OK)
4597 goto handle_data_failed;
4600 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4605 g_assert_not_reached ();
4610 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4611 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4612 ("The server closed the connection."));
4613 src->conninfo.connected = FALSE;
4614 gst_rtsp_message_unset (&message);
4615 return GST_FLOW_EOS;
4619 gst_rtsp_message_unset (&message);
4620 GST_DEBUG_OBJECT (src, "got interrupted");
4621 return GST_FLOW_FLUSHING;
4625 gchar *str = gst_rtsp_strresult (res);
4627 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4628 ("Could not receive message. (%s)", str));
4631 gst_rtsp_message_unset (&message);
4632 return GST_FLOW_ERROR;
4634 handle_request_failed:
4636 gchar *str = gst_rtsp_strresult (res);
4638 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4639 ("Could not handle server message. (%s)", str));
4641 gst_rtsp_message_unset (&message);
4642 return GST_FLOW_ERROR;
4646 GST_DEBUG_OBJECT (src, "could no handle data message");
4651 static GstFlowReturn
4652 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4655 GstRTSPMessage message = { 0 };
4659 GTimeVal tv_timeout;
4661 /* get the next timeout interval */
4662 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4664 GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4665 (gint) tv_timeout.tv_sec);
4667 gst_rtsp_message_unset (&message);
4669 /* we should continue reading the TCP socket because the server might
4670 * send us requests. When the session timeout expires, we need to send a
4671 * keep-alive request to keep the session open. */
4672 res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4673 &message, &tv_timeout);
4677 GST_DEBUG_OBJECT (src, "we received a server message");
4679 case GST_RTSP_EINTR:
4680 /* we got interrupted, see what we have to do */
4682 case GST_RTSP_ETIMEOUT:
4683 /* send keep-alive, ignore the result, a warning will be posted. */
4684 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4685 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4689 /* server closed the connection. not very fatal for UDP, reconnect and
4690 * see what happens. */
4691 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4692 ("The server closed the connection."));
4693 if (src->udp_reconnect) {
4695 gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4702 GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4704 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4705 ("Unhandled return value %d.", res));
4709 switch (message.type) {
4710 case GST_RTSP_MESSAGE_REQUEST:
4711 /* server sends us a request message, handle it */
4713 gst_rtspsrc_handle_request (src, src->conninfo.connection,
4715 if (res == GST_RTSP_EEOF)
4718 goto handle_request_failed;
4720 case GST_RTSP_MESSAGE_RESPONSE:
4721 /* we ignore response and data messages */
4722 GST_DEBUG_OBJECT (src, "ignoring response message");
4724 gst_rtsp_message_dump (&message);
4725 if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4726 GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4727 if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4728 GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4729 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4736 case GST_RTSP_MESSAGE_DATA:
4737 /* we ignore response and data messages */
4738 GST_DEBUG_OBJECT (src, "ignoring data message");
4741 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4746 g_assert_not_reached ();
4748 /* we get here when the connection got interrupted */
4751 gst_rtsp_message_unset (&message);
4752 GST_DEBUG_OBJECT (src, "got interrupted");
4753 return GST_FLOW_FLUSHING;
4757 gchar *str = gst_rtsp_strresult (res);
4760 src->conninfo.connected = FALSE;
4761 if (res != GST_RTSP_EINTR) {
4762 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4763 ("Could not connect to server. (%s)", str));
4765 ret = GST_FLOW_ERROR;
4767 ret = GST_FLOW_FLUSHING;
4773 gchar *str = gst_rtsp_strresult (res);
4775 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4776 ("Could not receive message. (%s)", str));
4778 return GST_FLOW_ERROR;
4780 handle_request_failed:
4782 gchar *str = gst_rtsp_strresult (res);
4785 gst_rtsp_message_unset (&message);
4786 if (res != GST_RTSP_EINTR) {
4787 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4788 ("Could not handle server message. (%s)", str));
4790 ret = GST_FLOW_ERROR;
4792 ret = GST_FLOW_FLUSHING;
4798 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4799 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4800 ("The server closed the connection."));
4801 src->conninfo.connected = FALSE;
4802 gst_rtsp_message_unset (&message);
4803 return GST_FLOW_EOS;
4807 static GstRTSPResult
4808 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4810 GstRTSPResult res = GST_RTSP_OK;
4813 GST_DEBUG_OBJECT (src, "doing reconnect");
4815 GST_OBJECT_LOCK (src);
4816 /* only restart when the pads were not yet activated, else we were
4817 * streaming over UDP */
4818 restart = src->need_activate;
4819 GST_OBJECT_UNLOCK (src);
4821 /* no need to restart, we're done */
4825 /* we can try only TCP now */
4826 src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4828 /* close and cleanup our state */
4829 if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4832 /* see if we have TCP left to try. Also don't try TCP when we were configured
4834 if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4837 /* We post a warning message now to inform the user
4838 * that nothing happened. It's most likely a firewall thing. */
4839 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4840 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4841 "firewall is blocking it. Retrying using a TCP connection.",
4842 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4844 /* open new connection using tcp */
4845 if (gst_rtspsrc_open (src, async) < 0)
4848 /* start playback */
4849 if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4858 src->cur_protocols = 0;
4859 /* no transport possible, post an error and stop */
4860 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4861 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4862 "firewall is blocking it. No other protocols to try.",
4863 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4864 return GST_RTSP_ERROR;
4868 GST_DEBUG_OBJECT (src, "open failed");
4873 GST_DEBUG_OBJECT (src, "play failed");
4879 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4883 GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4886 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4889 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4892 GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4900 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4904 GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4907 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4910 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4913 GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4921 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4925 GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4928 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4931 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4934 GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4942 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4946 GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4949 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4952 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4955 GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4963 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4965 if (ret == GST_RTSP_OK)
4966 gst_rtspsrc_loop_complete_cmd (src, cmd);
4967 else if (ret == GST_RTSP_EINTR)
4968 gst_rtspsrc_loop_cancel_cmd (src, cmd);
4970 gst_rtspsrc_loop_error_cmd (src, cmd);
4974 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4977 gboolean flushed = FALSE;
4979 /* start new request */
4980 gst_rtspsrc_loop_start_cmd (src, cmd);
4982 GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4984 GST_OBJECT_LOCK (src);
4985 old = src->pending_cmd;
4986 if (old == CMD_RECONNECT) {
4987 GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4988 cmd = CMD_RECONNECT;
4990 if (old != CMD_WAIT) {
4991 src->pending_cmd = CMD_WAIT;
4992 GST_OBJECT_UNLOCK (src);
4993 /* cancel previous request */
4994 GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4995 gst_rtspsrc_loop_cancel_cmd (src, old);
4996 GST_OBJECT_LOCK (src);
4998 src->pending_cmd = cmd;
4999 /* interrupt if allowed */
5000 if (src->busy_cmd & mask) {
5001 GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
5002 gst_rtspsrc_connection_flush (src, TRUE);
5005 GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
5008 gst_task_start (src->task);
5009 GST_OBJECT_UNLOCK (src);
5015 gst_rtspsrc_loop (GstRTSPSrc * src)
5019 if (!src->conninfo.connection || !src->conninfo.connected)
5022 if (src->interleaved)
5023 ret = gst_rtspsrc_loop_interleaved (src);
5025 ret = gst_rtspsrc_loop_udp (src);
5027 if (ret != GST_FLOW_OK)
5035 GST_WARNING_OBJECT (src, "we are not connected");
5036 ret = GST_FLOW_FLUSHING;
5041 const gchar *reason = gst_flow_get_name (ret);
5043 GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
5044 src->running = FALSE;
5045 if (ret == GST_FLOW_EOS) {
5046 /* perform EOS logic */
5047 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5048 gst_element_post_message (GST_ELEMENT_CAST (src),
5049 gst_message_new_segment_done (GST_OBJECT_CAST (src),
5050 src->segment.format, src->segment.position));
5051 gst_rtspsrc_push_event (src,
5052 gst_event_new_segment_done (src->segment.format,
5053 src->segment.position));
5055 gst_rtspsrc_push_event (src, gst_event_new_eos ());
5057 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
5058 /* for fatal errors we post an error message, post the error before the
5059 * EOS so the app knows about the error first. */
5060 GST_ELEMENT_ERROR (src, STREAM, FAILED,
5061 ("Internal data flow error."),
5062 ("streaming task paused, reason %s (%d)", reason, ret));
5063 gst_rtspsrc_push_event (src, gst_event_new_eos ());
5065 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
5070 #ifndef GST_DISABLE_GST_DEBUG
5071 static const gchar *
5072 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5076 while (method != 0) {
5093 static const gchar *
5094 gst_rtspsrc_skip_lws (const gchar * s)
5096 while (g_ascii_isspace (*s))
5101 static const gchar *
5102 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
5104 while (s > start && g_ascii_isspace (*(s - 1)))
5109 static const gchar *
5110 gst_rtspsrc_skip_commas (const gchar * s)
5112 /* The grammar allows for multiple commas */
5113 while (g_ascii_isspace (*s) || *s == ',')
5118 static const gchar *
5119 gst_rtspsrc_skip_item (const gchar * s)
5121 gboolean quoted = FALSE;
5122 const gchar *start = s;
5124 /* A list item ends at the last non-whitespace character
5125 * before a comma which is not inside a quoted-string. Or at
5126 * the end of the string.
5132 if (*s == '\\' && *(s + 1))
5141 return gst_rtspsrc_unskip_lws (s, start);
5145 gst_rtsp_decode_quoted_string (gchar * quoted_string)
5149 src = quoted_string + 1;
5150 dst = quoted_string;
5151 while (*src && *src != '"') {
5152 if (*src == '\\' && *(src + 1))
5159 /* Extract the authentication tokens that the server provided for each method
5160 * into an array of structures and give those to the connection object.
5163 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
5164 const gchar * header, gboolean * stale)
5166 GSList *list = NULL, *iter;
5168 gchar *item, *eq, *name_end, *value;
5170 g_return_if_fail (stale != NULL);
5172 gst_rtsp_connection_clear_auth_params (conn);
5175 /* Parse a header whose content is described by RFC2616 as
5176 * "#something", where "something" does not itself contain commas,
5177 * except as part of quoted-strings, into a list of allocated strings.
5179 header = gst_rtspsrc_skip_commas (header);
5181 end = gst_rtspsrc_skip_item (header);
5182 list = g_slist_prepend (list, g_strndup (header, end - header));
5183 header = gst_rtspsrc_skip_commas (end);
5188 list = g_slist_reverse (list);
5189 for (iter = list; iter; iter = iter->next) {
5192 eq = strchr (item, '=');
5194 name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
5195 if (name_end == item) {
5196 /* That's no good... */
5203 value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
5205 gst_rtsp_decode_quoted_string (value);
5209 if (value && strcmp (item, "stale") == 0 && strcmp (value, "TRUE") == 0)
5211 gst_rtsp_connection_set_auth_param (conn, item, value);
5215 g_slist_free (list);
5218 /* Parse a WWW-Authenticate Response header and determine the
5219 * available authentication methods
5221 * This code should also cope with the fact that each WWW-Authenticate
5222 * header can contain multiple challenge methods + tokens
5224 * At the moment, for Basic auth, we just do a minimal check and don't
5225 * even parse out the realm */
5227 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
5228 GstRTSPConnection * conn, gboolean * stale)
5232 g_return_if_fail (hdr != NULL);
5233 g_return_if_fail (methods != NULL);
5234 g_return_if_fail (stale != NULL);
5236 /* Skip whitespace at the start of the string */
5237 for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
5239 if (g_ascii_strncasecmp (start, "basic", 5) == 0)
5240 *methods |= GST_RTSP_AUTH_BASIC;
5241 else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
5242 *methods |= GST_RTSP_AUTH_DIGEST;
5243 gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
5248 * gst_rtspsrc_setup_auth:
5249 * @src: the rtsp source
5251 * Configure a username and password and auth method on the
5252 * connection object based on a response we received from the
5255 * Currently, this requires that a username and password were supplied
5256 * in the uri. In the future, they may be requested on demand by sending
5257 * a message up the bus.
5259 * Returns: TRUE if authentication information could be set up correctly.
5262 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5266 GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5267 GstRTSPAuthMethod method;
5268 GstRTSPResult auth_result;
5270 GstRTSPConnection *conn;
5272 gboolean stale = FALSE;
5274 conn = src->conninfo.connection;
5276 /* Identify the available auth methods and see if any are supported */
5277 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
5278 &hdr, 0) == GST_RTSP_OK) {
5279 gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
5282 if (avail_methods == GST_RTSP_AUTH_NONE)
5283 goto no_auth_available;
5285 /* For digest auth, if the response indicates that the session
5286 * data are stale, we just update them in the connection object and
5287 * return TRUE to retry the request */
5289 src->tried_url_auth = FALSE;
5291 url = gst_rtsp_connection_get_url (conn);
5293 /* Do we have username and password available? */
5294 if (url != NULL && !src->tried_url_auth && url->user != NULL
5295 && url->passwd != NULL) {
5298 src->tried_url_auth = TRUE;
5299 GST_DEBUG_OBJECT (src,
5300 "Attempting authentication using credentials from the URL");
5302 user = src->user_id;
5303 pass = src->user_pw;
5304 GST_DEBUG_OBJECT (src,
5305 "Attempting authentication using credentials from the properties");
5308 /* FIXME: If the url didn't contain username and password or we tried them
5309 * already, request a username and passwd from the application via some kind
5310 * of credentials request message */
5312 /* If we don't have a username and passwd at this point, bail out. */
5313 if (user == NULL || pass == NULL)
5316 /* Try to configure for each available authentication method, strongest to
5318 for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5319 /* Check if this method is available on the server */
5320 if ((method & avail_methods) == 0)
5323 /* Pass the credentials to the connection to try on the next request */
5324 auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5325 /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5326 * ignore it and end up retrying later */
5327 if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5328 GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5329 gst_rtsp_auth_method_to_string (method));
5334 if (method == GST_RTSP_AUTH_NONE)
5335 goto no_auth_available;
5341 /* Output an error indicating that we couldn't connect because there were
5342 * no supported authentication protocols */
5343 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5344 ("No supported authentication protocol was found"));
5349 /* We don't fire an error message, we just return FALSE and let the
5350 * normal NOT_AUTHORIZED error be propagated */
5355 static GstRTSPResult
5356 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5357 GstRTSPMessage * request, GstRTSPMessage * response,
5358 GstRTSPStatusCode * code)
5361 GstRTSPStatusCode thecode;
5362 gchar *content_base = NULL;
5366 if (!src->short_header)
5367 gst_rtsp_ext_list_before_send (src->extensions, request);
5369 GST_DEBUG_OBJECT (src, "sending message");
5372 gst_rtsp_message_dump (request);
5374 res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
5378 gst_rtsp_connection_reset_timeout (conn);
5381 res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
5386 gst_rtsp_message_dump (response);
5388 switch (response->type) {
5389 case GST_RTSP_MESSAGE_REQUEST:
5390 res = gst_rtspsrc_handle_request (src, conn, response);
5391 if (res == GST_RTSP_EEOF)
5394 goto handle_request_failed;
5396 case GST_RTSP_MESSAGE_RESPONSE:
5397 /* ok, a response is good */
5398 GST_DEBUG_OBJECT (src, "received response message");
5400 case GST_RTSP_MESSAGE_DATA:
5401 /* get next response */
5402 GST_DEBUG_OBJECT (src, "handle data response message");
5403 gst_rtspsrc_handle_data (src, response);
5406 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5411 thecode = response->type_data.response.code;
5413 GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5415 /* if the caller wanted the result code, we store it. */
5419 /* If the request didn't succeed, bail out before doing any more */
5420 if (thecode != GST_RTSP_STS_OK)
5423 /* store new content base if any */
5424 gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5427 g_free (src->content_base);
5428 src->content_base = g_strdup (content_base);
5430 gst_rtsp_ext_list_after_send (src->extensions, request, response);
5437 gchar *str = gst_rtsp_strresult (res);
5439 if (res != GST_RTSP_EINTR) {
5440 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5441 ("Could not send message. (%s)", str));
5443 GST_WARNING_OBJECT (src, "send interrupted");
5452 GST_WARNING_OBJECT (src, "server closed connection");
5453 if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5455 /* if reconnect succeeds, try again */
5457 gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5461 /* only try once after reconnect, then fallthrough and error out */
5464 gchar *str = gst_rtsp_strresult (res);
5466 if (res != GST_RTSP_EINTR) {
5467 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5468 ("Could not receive message. (%s)", str));
5470 GST_WARNING_OBJECT (src, "receive interrupted");
5478 handle_request_failed:
5480 /* ERROR was posted */
5481 gst_rtsp_message_unset (response);
5486 GST_DEBUG_OBJECT (src, "we got an eof from the server");
5487 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5488 ("The server closed the connection."));
5489 gst_rtsp_message_unset (response);
5496 * @src: the rtsp source
5497 * @conn: the connection to send on
5498 * @request: must point to a valid request
5499 * @response: must point to an empty #GstRTSPMessage
5500 * @code: an optional code result
5502 * send @request and retrieve the response in @response. optionally @code can be
5503 * non-NULL in which case it will contain the status code of the response.
5505 * If This function returns #GST_RTSP_OK, @response will contain a valid response
5506 * message that should be cleaned with gst_rtsp_message_unset() after usage.
5508 * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5509 * @response message) if the response code was not 200 (OK).
5511 * If the attempt results in an authentication failure, then this will attempt
5512 * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5515 * Returns: #GST_RTSP_OK if the processing was successful.
5517 static GstRTSPResult
5518 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5519 GstRTSPMessage * request, GstRTSPMessage * response,
5520 GstRTSPStatusCode * code)
5522 GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5523 GstRTSPResult res = GST_RTSP_ERROR;
5526 GstRTSPMethod method = GST_RTSP_INVALID;
5532 /* make sure we don't loop forever */
5536 /* save method so we can disable it when the server complains */
5537 method = request->type_data.request.method;
5540 gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5544 case GST_RTSP_STS_UNAUTHORIZED:
5545 if (gst_rtspsrc_setup_auth (src, response)) {
5546 /* Try the request/response again after configuring the auth info
5554 } while (retry == TRUE);
5556 /* If the user requested the code, let them handle errors, otherwise
5557 * post an error below */
5560 else if (int_code != GST_RTSP_STS_OK)
5561 goto error_response;
5568 GST_DEBUG_OBJECT (src, "got error %d", res);
5573 res = GST_RTSP_ERROR;
5575 switch (response->type_data.response.code) {
5576 case GST_RTSP_STS_NOT_FOUND:
5577 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5578 response->type_data.response.reason));
5580 case GST_RTSP_STS_MOVED_PERMANENTLY:
5581 case GST_RTSP_STS_MOVE_TEMPORARILY:
5583 gchar *new_location;
5584 GstRTSPLowerTrans transports;
5586 GST_DEBUG_OBJECT (src, "got redirection");
5587 /* if we don't have a Location Header, we must error */
5588 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5589 &new_location, 0) < 0)
5592 /* When we receive a redirect result, we go back to the INIT state after
5593 * parsing the new URI. The caller should do the needed steps to issue
5594 * a new setup when it detects this state change. */
5595 GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5597 /* save current transports */
5598 if (src->conninfo.url)
5599 transports = src->conninfo.url->transports;
5601 transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5603 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5605 /* set old transports */
5606 if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5607 src->conninfo.url->transports = transports;
5609 src->need_redirect = TRUE;
5610 src->state = GST_RTSP_STATE_INIT;
5614 case GST_RTSP_STS_NOT_ACCEPTABLE:
5615 case GST_RTSP_STS_NOT_IMPLEMENTED:
5616 case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5617 GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5618 gst_rtsp_method_as_text (method));
5619 src->methods &= ~method;
5623 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5624 ("Got error response: %d (%s).", response->type_data.response.code,
5625 response->type_data.response.reason));
5628 /* if we return ERROR we should unset the response ourselves */
5629 if (res == GST_RTSP_ERROR)
5630 gst_rtsp_message_unset (response);
5636 static GstRTSPResult
5637 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5638 GstRTSPMessage * response, GstRTSPSrc * src)
5640 return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5645 /* parse the response and collect all the supported methods. We need this
5646 * information so that we don't try to send an unsupported request to the
5650 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5652 GstRTSPHeaderField field;
5656 /* reset supported methods */
5659 /* Try Allow Header first */
5660 field = GST_RTSP_HDR_ALLOW;
5663 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5664 if (indx == 0 && !respoptions) {
5665 /* if no Allow header was found then try the Public header... */
5666 field = GST_RTSP_HDR_PUBLIC;
5667 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5672 src->methods |= gst_rtsp_options_from_text (respoptions);
5677 if (src->methods == 0) {
5678 /* neither Allow nor Public are required, assume the server supports
5679 * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5681 GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5682 src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5684 /* always assume PLAY, FIXME, extensions should be able to override
5686 src->methods |= GST_RTSP_PLAY;
5687 /* also assume it will support Range */
5688 src->seekable = TRUE;
5690 /* we need describe and setup */
5691 if (!(src->methods & GST_RTSP_DESCRIBE))
5693 if (!(src->methods & GST_RTSP_SETUP))
5701 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5702 ("Server does not support DESCRIBE."));
5707 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5708 ("Server does not support SETUP."));
5713 /* masks to be kept in sync with the hardcoded protocol order of preference
5715 static guint protocol_masks[] = {
5716 GST_RTSP_LOWER_TRANS_UDP,
5717 GST_RTSP_LOWER_TRANS_UDP_MCAST,
5718 GST_RTSP_LOWER_TRANS_TCP,
5722 static GstRTSPResult
5723 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5724 GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
5728 gboolean add_udp_str;
5733 gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5738 GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5740 /* extension listed transports, use those */
5741 if (*transports != NULL)
5744 /* it's the default */
5745 add_udp_str = FALSE;
5747 /* the default RTSP transports */
5748 result = g_string_new ("RTP");
5751 case GST_RTSP_PROFILE_AVP:
5752 g_string_append (result, "/AVP");
5754 case GST_RTSP_PROFILE_SAVP:
5755 g_string_append (result, "/SAVP");
5757 case GST_RTSP_PROFILE_AVPF:
5758 g_string_append (result, "/AVPF");
5760 case GST_RTSP_PROFILE_SAVPF:
5761 g_string_append (result, "/SAVPF");
5767 if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5768 GST_DEBUG_OBJECT (src, "adding UDP unicast");
5770 g_string_append (result, "/UDP");
5771 g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5772 } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5773 GST_DEBUG_OBJECT (src, "adding UDP multicast");
5774 /* we don't have to allocate any UDP ports yet, if the selected transport
5775 * turns out to be multicast we can create them and join the multicast
5776 * group indicated in the transport reply */
5778 g_string_append (result, "/UDP");
5779 g_string_append (result, ";multicast");
5780 if (src->next_port_num != 0) {
5781 if (src->client_port_range.max > 0 &&
5782 src->next_port_num >= src->client_port_range.max)
5785 g_string_append_printf (result, ";client_port=%d-%d",
5786 src->next_port_num, src->next_port_num + 1);
5788 } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5789 GST_DEBUG_OBJECT (src, "adding TCP");
5791 g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
5793 *transports = g_string_free (result, FALSE);
5795 GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5802 GST_ERROR ("extension gave error %d", res);
5807 GST_ERROR ("no more ports available");
5808 return GST_RTSP_ERROR;
5812 static GstRTSPResult
5813 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5814 gint orig_rtpport, gint orig_rtcpport)
5817 gint nr_udp, nr_int;
5819 gint rtpport = 0, rtcpport = 0;
5822 src = stream->parent;
5824 /* find number of placeholders first */
5825 if (strstr (*transports, "%%i2"))
5827 else if (strstr (*transports, "%%i1"))
5832 if (strstr (*transports, "%%u2"))
5834 else if (strstr (*transports, "%%u1"))
5839 if (nr_udp == 0 && nr_int == 0)
5843 if (!orig_rtpport || !orig_rtcpport) {
5844 if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5847 rtpport = orig_rtpport;
5848 rtcpport = orig_rtcpport;
5852 str = g_string_new ("");
5854 while ((next = strstr (p, "%%"))) {
5855 g_string_append_len (str, p, next - p);
5856 if (next[2] == 'u') {
5858 g_string_append_printf (str, "%d", rtpport);
5859 else if (next[3] == '2')
5860 g_string_append_printf (str, "%d", rtcpport);
5862 if (next[2] == 'i') {
5864 g_string_append_printf (str, "%d", src->free_channel);
5865 else if (next[3] == '2')
5866 g_string_append_printf (str, "%d", src->free_channel + 1);
5871 /* append final part */
5872 g_string_append (str, p);
5874 g_free (*transports);
5875 *transports = g_string_free (str, FALSE);
5883 GST_ERROR ("failed to allocate udp ports");
5884 return GST_RTSP_ERROR;
5889 enc_key_length_from_cipher_name (const gchar * cipher)
5891 if (g_strcmp0 (cipher, "aes-128-icm") == 0)
5892 return AES_128_KEY_LEN;
5893 else if (g_strcmp0 (cipher, "aes-256-icm") == 0)
5894 return AES_256_KEY_LEN;
5896 GST_ERROR ("encryption algorithm '%s' not supported", cipher);
5902 auth_key_length_from_auth_name (const gchar * auth)
5904 if (g_strcmp0 (auth, "hmac-sha1-32") == 0)
5905 return HMAC_32_KEY_LEN;
5906 else if (g_strcmp0 (auth, "hmac-sha1-80") == 0)
5907 return HMAC_80_KEY_LEN;
5909 GST_ERROR ("authentication algorithm '%s' not supported", auth);
5915 signal_get_srtcp_params (GstRTSPSrc * src)
5917 GstCaps *caps = NULL;
5919 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0, &caps);
5922 GST_DEBUG_OBJECT (src, "SRTP parameters received");
5928 default_srtcp_params (void)
5936 /* create a random key */
5937 key_data = g_malloc (KEY_SIZE);
5938 for (i = 0; i < KEY_SIZE; i += 4)
5939 GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
5941 buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
5943 caps = gst_caps_new_simple ("application/x-srtp",
5944 "srtp-key", GST_TYPE_BUFFER, buf,
5945 "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
5946 "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
5952 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
5955 gchar *result, *base64;
5958 GstMIKEYMessage *msg;
5959 GstMIKEYPayload *payload, *pkd;
5965 const gchar *srtcpcipher, *srtcpauth;
5967 stream->srtcpparams = signal_get_srtcp_params (src);
5968 if (stream->srtcpparams == NULL)
5969 stream->srtcpparams = default_srtcp_params ();
5971 s = gst_caps_get_structure (stream->srtcpparams, 0);
5973 srtcpcipher = gst_structure_get_string (s, "srtcp-cipher");
5974 srtcpauth = gst_structure_get_string (s, "srtcp-auth");
5975 val = gst_structure_get_value (s, "srtp-key");
5977 if (srtcpcipher == NULL || srtcpauth == NULL || val == NULL) {
5978 GST_ERROR_OBJECT (src, "could not find the right SRTP parameters in caps");
5982 srtpkey = gst_value_get_buffer (val);
5984 msg = gst_mikey_message_new ();
5985 /* unencrypted MIKEY message, we send this over TLS so this is allowed */
5986 gst_mikey_message_set_info (msg, GST_MIKEY_VERSION, GST_MIKEY_TYPE_PSK_INIT,
5987 FALSE, GST_MIKEY_PRF_MIKEY_1, g_random_int (), GST_MIKEY_MAP_TYPE_SRTP);
5988 /* add policy '0' for our SSRC */
5989 gst_mikey_message_add_cs_srtp (msg, 0, stream->send_ssrc, 0);
5990 /* timestamp is now */
5991 gst_mikey_message_add_t_now_ntp_utc (msg);
5992 /* add some random data */
5993 gst_mikey_message_add_rand_len (msg, 16);
5995 /* the policy '0' is SRTP */
5996 payload = gst_mikey_payload_new (GST_MIKEY_PT_SP);
5997 gst_mikey_payload_sp_set (payload, 0, GST_MIKEY_SEC_PROTO_SRTP);
5999 /* only AES-CM is supported */
6001 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_ALG, 1, &byte);
6002 /* encryption key length */
6003 byte = enc_key_length_from_cipher_name (srtcpcipher);
6004 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_KEY_LEN, 1,
6006 /* only HMAC-SHA1 */
6007 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_ALG, 1,
6009 /* authentication key length */
6010 byte = auth_key_length_from_auth_name (srtcpauth);
6011 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_KEY_LEN, 1,
6013 /* we enable encryption on RTP and RTCP */
6014 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_ENC, 1,
6016 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTCP_ENC, 1,
6018 /* we enable authentication on RTP and RTCP */
6019 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_AUTH, 1,
6021 gst_mikey_message_add_payload (msg, payload);
6023 /* make unencrypted KEMAC */
6024 payload = gst_mikey_payload_new (GST_MIKEY_PT_KEMAC);
6025 gst_mikey_payload_kemac_set (payload, GST_MIKEY_ENC_NULL, GST_MIKEY_MAC_NULL);
6026 /* add the key in KEMAC */
6027 pkd = gst_mikey_payload_new (GST_MIKEY_PT_KEY_DATA);
6028 gst_buffer_map (srtpkey, &info, GST_MAP_READ);
6029 gst_mikey_payload_key_data_set_key (pkd, GST_MIKEY_KD_TEK, info.size,
6031 gst_buffer_unmap (srtpkey, &info);
6032 gst_mikey_payload_kemac_add_sub (payload, pkd);
6033 gst_mikey_message_add_payload (msg, payload);
6035 /* now serialize this to bytes */
6036 bytes = gst_mikey_message_to_bytes (msg, NULL, NULL);
6037 gst_mikey_message_free (msg);
6038 /* and make it into base64 */
6039 data = g_bytes_get_data (bytes, &size);
6040 base64 = g_base64_encode (data, size);
6041 g_bytes_unref (bytes);
6043 result = g_strdup_printf ("prot=mikey;uri=\"%s\";data=\"%s\"",
6044 stream->conninfo.location, base64);
6051 /* Perform the SETUP request for all the streams.
6053 * We ask the server for a specific transport, which initially includes all the
6054 * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6055 * two local UDP ports that we send to the server.
6057 * Once the server replied with a transport, we configure the other streams
6058 * with the same transport.
6060 * This function will also configure the stream for the selected transport,
6061 * which basically means creating the pipeline.
6063 static GstRTSPResult
6064 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
6067 GstRTSPResult res = GST_RTSP_ERROR;
6068 GstRTSPMessage request = { 0 };
6069 GstRTSPMessage response = { 0 };
6070 GstRTSPStream *stream = NULL;
6071 GstRTSPLowerTrans protocols;
6072 GstRTSPStatusCode code;
6073 gboolean unsupported_real = FALSE;
6074 gint rtpport, rtcpport;
6078 if (src->conninfo.connection) {
6079 url = gst_rtsp_connection_get_url (src->conninfo.connection);
6080 /* we initially allow all configured lower transports. based on the URL
6081 * transports and the replies from the server we narrow them down. */
6082 protocols = url->transports & src->cur_protocols;
6085 protocols = src->cur_protocols;
6091 /* reset some state */
6092 src->free_channel = 0;
6093 src->interleaved = FALSE;
6094 src->need_activate = FALSE;
6095 /* keep track of next port number, 0 is random */
6096 src->next_port_num = src->client_port_range.min;
6097 rtpport = rtcpport = 0;
6099 if (G_UNLIKELY (src->streams == NULL))
6102 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6103 GstRTSPConnection *conn;
6110 stream = (GstRTSPStream *) walk->data;
6112 caps = stream_get_caps_for_pt (stream, stream->default_pt);
6114 GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
6118 if (stream->skipped) {
6119 GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6123 /* see if we need to configure this stream */
6124 if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6125 GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6130 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6131 stream->id, caps, &selected);
6133 GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6137 /* merge/overwrite global caps */
6142 s = gst_caps_get_structure (caps, 0);
6144 num = gst_structure_n_fields (src->props);
6145 for (j = 0; j < num; j++) {
6149 name = gst_structure_nth_field_name (src->props, j);
6150 val = gst_structure_get_value (src->props, name);
6151 gst_structure_set_value (s, name, val);
6153 GST_DEBUG_OBJECT (src, "copied %s", name);
6157 /* skip setup if we have no URL for it */
6158 if (stream->conninfo.location == NULL) {
6159 GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6163 if (src->conninfo.connection == NULL) {
6164 if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6165 GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6168 conn = stream->conninfo.connection;
6170 conn = src->conninfo.connection;
6172 GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6173 stream->conninfo.location);
6175 /* if we have a multicast connection, only suggest multicast from now on */
6176 if (stream->is_multicast)
6177 protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6180 /* first selectable protocol */
6181 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6183 if (!protocol_masks[mask])
6187 GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6188 protocol_masks[mask]);
6189 /* create a string with first transport in line */
6191 res = gst_rtspsrc_create_transports_string (src,
6192 protocols & protocol_masks[mask], stream->profile, &transports);
6193 if (res < 0 || transports == NULL)
6194 goto setup_transport_failed;
6196 if (strlen (transports) == 0) {
6197 g_free (transports);
6198 GST_DEBUG_OBJECT (src, "no transports found");
6203 GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6205 /* replace placeholders with real values, this function will optionally
6206 * allocate UDP ports and other info needed to execute the setup request */
6207 res = gst_rtspsrc_prepare_transports (stream, &transports,
6208 retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6210 g_free (transports);
6211 goto setup_transport_failed;
6214 GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6216 /* create SETUP request */
6218 gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
6219 stream->conninfo.location);
6221 g_free (transports);
6222 goto create_request_failed;
6225 /* select transport */
6226 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6229 if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6230 stream->profile == GST_RTSP_PROFILE_SAVPF) {
6231 hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6232 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6235 /* if the user wants a non default RTP packet size we add the blocksize
6237 if (src->rtp_blocksize > 0) {
6238 hval = g_strdup_printf ("%d", src->rtp_blocksize);
6239 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6243 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6246 /* handle the code ourselves */
6247 if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
6251 case GST_RTSP_STS_OK:
6253 case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6254 gst_rtsp_message_unset (&request);
6255 gst_rtsp_message_unset (&response);
6256 /* cleanup of leftover transport */
6257 gst_rtspsrc_stream_free_udp (stream);
6258 /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6259 * we might be in this case */
6260 if (stream->container && rtpport && rtcpport && !retry) {
6261 GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6266 /* this transport did not go down well, but we may have others to try
6267 * that we did not send yet, try those and only give up then
6268 * but not without checking for lost cause/extension so we can
6269 * post a nicer/more useful error message later */
6270 if (!unsupported_real)
6271 unsupported_real = stream->is_real;
6272 /* select next available protocol, give up on this stream if none */
6274 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6276 if (!protocol_masks[mask] || unsupported_real)
6281 /* cleanup of leftover transport and move to the next stream */
6282 gst_rtspsrc_stream_free_udp (stream);
6283 goto response_error;
6286 /* parse response transport */
6288 gchar *resptrans = NULL;
6289 GstRTSPTransport transport = { 0 };
6291 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
6294 gst_rtspsrc_stream_free_udp (stream);
6298 /* parse transport, go to next stream on parse error */
6299 if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6300 GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6304 /* update allowed transports for other streams. once the transport of
6305 * one stream has been determined, we make sure that all other streams
6306 * are configured in the same way */
6307 switch (transport.lower_transport) {
6308 case GST_RTSP_LOWER_TRANS_TCP:
6309 GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6310 protocols = GST_RTSP_LOWER_TRANS_TCP;
6311 src->interleaved = TRUE;
6312 /* update free channels */
6314 MAX (transport.interleaved.min, src->free_channel);
6316 MAX (transport.interleaved.max, src->free_channel);
6317 src->free_channel++;
6319 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6320 /* only allow multicast for other streams */
6321 GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6322 protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6323 /* if the server selected our ports, increment our counters so that
6324 * we select a new port later */
6325 if (src->next_port_num == transport.port.min &&
6326 src->next_port_num + 1 == transport.port.max) {
6327 src->next_port_num += 2;
6330 case GST_RTSP_LOWER_TRANS_UDP:
6331 /* only allow unicast for other streams */
6332 GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6333 protocols = GST_RTSP_LOWER_TRANS_UDP;
6336 GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6337 transport.lower_transport);
6341 if (!stream->container || (!src->interleaved && !retry)) {
6342 /* now configure the stream with the selected transport */
6343 if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6344 GST_DEBUG_OBJECT (src,
6345 "could not configure stream %p transport, skipping stream",
6348 } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
6349 /* retain the first allocated UDP port pair */
6350 g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
6351 g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
6354 /* we need to activate at least one streams when we detect activity */
6355 src->need_activate = TRUE;
6357 /* stream is setup now */
6358 stream->setup = TRUE;
6363 GstRTSPStream *sskip;
6365 skip = g_list_next (skip);
6369 sskip = (GstRTSPStream *) skip->data;
6371 /* skip all streams with the same control url */
6372 if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6373 GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6374 sskip, sskip->conninfo.location);
6375 sskip->skipped = TRUE;
6380 /* clean up our transport struct */
6381 gst_rtsp_transport_init (&transport);
6382 /* clean up used RTSP messages */
6383 gst_rtsp_message_unset (&request);
6384 gst_rtsp_message_unset (&response);
6388 /* store the transport protocol that was configured */
6389 src->cur_protocols = protocols;
6391 gst_rtsp_ext_list_stream_select (src->extensions, url);
6393 /* if there is nothing to activate, error out */
6394 if (!src->need_activate)
6395 goto nothing_to_activate;
6402 /* no transport possible, post an error and stop */
6403 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6404 ("Could not connect to server, no protocols left"));
6405 return GST_RTSP_ERROR;
6409 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6410 ("SDP contains no streams"));
6411 return GST_RTSP_ERROR;
6413 create_request_failed:
6415 gchar *str = gst_rtsp_strresult (res);
6417 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6418 ("Could not create request. (%s)", str));
6422 setup_transport_failed:
6424 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6425 ("Could not setup transport."));
6426 res = GST_RTSP_ERROR;
6431 const gchar *str = gst_rtsp_status_as_text (code);
6433 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6434 ("Error (%d): %s", code, GST_STR_NULL (str)));
6435 res = GST_RTSP_ERROR;
6440 gchar *str = gst_rtsp_strresult (res);
6442 if (res != GST_RTSP_EINTR) {
6443 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6444 ("Could not send message. (%s)", str));
6446 GST_WARNING_OBJECT (src, "send interrupted");
6453 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6454 ("Server did not select transport."));
6455 res = GST_RTSP_ERROR;
6458 nothing_to_activate:
6460 /* none of the available error codes is really right .. */
6461 if (unsupported_real) {
6462 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6463 (_("No supported stream was found. You might need to install a "
6464 "GStreamer RTSP extension plugin for Real media streams.")),
6467 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6468 (_("No supported stream was found. You might need to allow "
6469 "more transport protocols or may otherwise be missing "
6470 "the right GStreamer RTSP extension plugin.")), (NULL));
6472 return GST_RTSP_ERROR;
6476 gst_rtsp_message_unset (&request);
6477 gst_rtsp_message_unset (&response);
6483 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6484 GstSegment * segment)
6487 GstRTSPTimeRange *therange;
6490 gst_rtsp_range_free (src->range);
6492 if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6493 GST_DEBUG_OBJECT (src, "parsed range %s", range);
6494 src->range = therange;
6496 GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6498 gst_segment_init (segment, GST_FORMAT_TIME);
6502 GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d, max %f ",
6503 therange->min.type, therange->min.seconds, therange->max.type,
6504 therange->max.seconds);
6506 if (therange->min.type == GST_RTSP_TIME_NOW)
6508 else if (therange->min.type == GST_RTSP_TIME_END)
6511 seconds = therange->min.seconds * GST_SECOND;
6513 GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6514 GST_TIME_ARGS (seconds));
6516 /* we need to start playback without clipping from the position reported by
6518 segment->start = seconds;
6519 segment->position = seconds;
6521 if (therange->max.type == GST_RTSP_TIME_NOW)
6523 else if (therange->max.type == GST_RTSP_TIME_END)
6526 seconds = therange->max.seconds * GST_SECOND;
6528 GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6529 GST_TIME_ARGS (seconds));
6531 /* live (WMS) server might send overflowed large max as its idea of infinity,
6532 * compensate to prevent problems later on */
6533 if (seconds != -1 && seconds < 0) {
6535 GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6538 /* live (WMS) might send min == max, which is not worth recording */
6539 if (segment->duration == -1 && seconds == segment->start)
6542 /* don't change duration with unknown value, we might have a valid value
6543 * there that we want to keep. */
6545 segment->duration = seconds;
6550 /* Parse clock profived by the server with following syntax:
6552 * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6555 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6557 gboolean res = FALSE;
6559 if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6560 gchar **fields = NULL, **parts = NULL;
6561 gchar *remote_ip, *str;
6563 GstClockTime base_time;
6566 fields = g_strsplit (gstclock, " ", 0);
6568 /* wrapped clock, not very interesting for now */
6569 if (fields[1] == NULL)
6572 /* remote IP address and port */
6573 if ((str = fields[2]) == NULL)
6576 parts = g_strsplit (str, ":", 0);
6578 if ((remote_ip = parts[0]) == NULL)
6581 if ((str = parts[1]) == NULL)
6589 if ((str = fields[3]) == NULL)
6592 base_time = g_ascii_strtoull (str, NULL, 10);
6595 gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
6598 if (src->provided_clock)
6599 gst_object_unref (src->provided_clock);
6600 src->provided_clock = netclock;
6602 gst_element_post_message (GST_ELEMENT_CAST (src),
6603 gst_message_new_clock_provide (GST_OBJECT_CAST (src),
6604 src->provided_clock, TRUE));
6608 g_strfreev (fields);
6614 /* must be called with the RTSP state lock */
6615 static GstRTSPResult
6616 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
6622 /* prepare global stream caps properties */
6624 gst_structure_remove_all_fields (src->props);
6626 src->props = gst_structure_new_empty ("RTSPProperties");
6629 gst_sdp_message_dump (sdp);
6631 gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
6633 /* let the app inspect and change the SDP */
6634 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
6636 gst_segment_init (&src->segment, GST_FORMAT_TIME);
6638 /* parse range for duration reporting. */
6643 range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
6647 /* keep track of the range and configure it in the segment */
6648 if (gst_rtspsrc_parse_range (src, range, &src->segment))
6652 /* parse clock information. This is GStreamer specific, a server can tell the
6653 * client what clock it is using and wrap that in a network clock. The
6654 * advantage of that is that we can slave to it. */
6656 const gchar *gstclock;
6659 gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6660 if (gstclock == NULL)
6663 /* parse the clock and expose it in the provide_clock method */
6664 if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6668 /* try to find a global control attribute. Note that a '*' means that we should
6669 * do aggregate control with the current url (so we don't do anything and
6670 * leave the current connection as is) */
6672 const gchar *control;
6675 control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6676 if (control == NULL)
6679 /* only take fully qualified urls */
6680 if (g_str_has_prefix (control, "rtsp://"))
6684 g_free (src->conninfo.location);
6685 src->conninfo.location = g_strdup (control);
6686 /* make a connection for this, if there was a connection already, nothing
6688 if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6689 GST_ERROR_OBJECT (src, "could not connect");
6692 /* we need to keep the control url separate from the connection url because
6693 * the rules for constructing the media control url need it */
6694 g_free (src->control);
6695 src->control = g_strdup (control);
6698 /* create streams */
6699 n_streams = gst_sdp_message_medias_len (sdp);
6700 for (i = 0; i < n_streams; i++) {
6701 gst_rtspsrc_create_stream (src, sdp, i);
6704 src->state = GST_RTSP_STATE_INIT;
6707 if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
6710 /* reset our state */
6711 src->need_range = TRUE;
6714 src->state = GST_RTSP_STATE_READY;
6721 GST_ERROR_OBJECT (src, "setup failed");
6722 gst_rtspsrc_cleanup (src);
6727 static GstRTSPResult
6728 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6732 GstRTSPMessage request = { 0 };
6733 GstRTSPMessage response = { 0 };
6736 gchar *respcont = NULL;
6739 src->need_redirect = FALSE;
6741 /* can't continue without a valid url */
6742 if (G_UNLIKELY (src->conninfo.url == NULL)) {
6743 res = GST_RTSP_EINVAL;
6746 src->tried_url_auth = FALSE;
6748 if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
6749 goto connect_failed;
6751 /* create OPTIONS */
6752 GST_DEBUG_OBJECT (src, "create options...");
6754 gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
6755 src->conninfo.url_str);
6757 goto create_request_failed;
6760 GST_DEBUG_OBJECT (src, "send options...");
6763 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
6766 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6771 if (!gst_rtspsrc_parse_methods (src, &response))
6774 /* create DESCRIBE */
6775 GST_DEBUG_OBJECT (src, "create describe...");
6777 gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
6778 src->conninfo.url_str);
6780 goto create_request_failed;
6782 /* we only accept SDP for now */
6783 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
6787 GST_DEBUG_OBJECT (src, "send describe...");
6790 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
6793 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6797 /* we only perform redirect for the describe, currently */
6798 if (src->need_redirect) {
6799 /* close connection, we don't have to send a TEARDOWN yet, ignore the
6801 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6803 gst_rtsp_message_unset (&request);
6804 gst_rtsp_message_unset (&response);
6810 /* it could be that the DESCRIBE method was not implemented */
6811 if (!src->methods & GST_RTSP_DESCRIBE)
6814 /* check if reply is SDP */
6815 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6817 /* could not be set but since the request returned OK, we assume it
6818 * was SDP, else check it. */
6820 if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6821 goto wrong_content_type;
6824 /* get message body and parse as SDP */
6825 gst_rtsp_message_get_body (&response, &data, &size);
6826 if (data == NULL || size == 0)
6829 GST_DEBUG_OBJECT (src, "parse SDP...");
6830 gst_sdp_message_new (sdp);
6831 gst_sdp_message_parse_buffer (data, size, *sdp);
6833 /* clean up any messages */
6834 gst_rtsp_message_unset (&request);
6835 gst_rtsp_message_unset (&response);
6842 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6843 ("No valid RTSP URL was provided"));
6848 gchar *str = gst_rtsp_strresult (res);
6850 if (res != GST_RTSP_EINTR) {
6851 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6852 ("Failed to connect. (%s)", str));
6854 GST_WARNING_OBJECT (src, "connect interrupted");
6859 create_request_failed:
6861 gchar *str = gst_rtsp_strresult (res);
6863 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6864 ("Could not create request. (%s)", str));
6870 /* Don't post a message - the rtsp_send method will have
6871 * taken care of it because we passed NULL for the response code */
6876 /* error was posted */
6877 res = GST_RTSP_ERROR;
6882 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6883 ("Server does not support SDP, got %s.", respcont));
6884 res = GST_RTSP_ERROR;
6889 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6890 ("Server can not provide an SDP."));
6891 res = GST_RTSP_ERROR;
6896 if (src->conninfo.connection) {
6897 GST_DEBUG_OBJECT (src, "free connection");
6898 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6900 gst_rtsp_message_unset (&request);
6901 gst_rtsp_message_unset (&response);
6906 static GstRTSPResult
6907 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6912 GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6914 if (src->sdp == NULL) {
6915 if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6919 if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6924 gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6931 GST_WARNING_OBJECT (src, "can't get sdp");
6932 src->open_error = TRUE;
6937 GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6938 src->open_error = TRUE;
6943 static GstRTSPResult
6944 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6946 GstRTSPMessage request = { 0 };
6947 GstRTSPMessage response = { 0 };
6948 GstRTSPResult res = GST_RTSP_OK;
6950 const gchar *control;
6952 GST_DEBUG_OBJECT (src, "TEARDOWN...");
6954 gst_rtspsrc_set_state (src, GST_STATE_READY);
6956 if (src->state < GST_RTSP_STATE_READY) {
6957 GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6964 /* construct a control url */
6965 control = get_aggregate_control (src);
6967 if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6970 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6971 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6972 const gchar *setup_url;
6973 GstRTSPConnInfo *info;
6975 /* try aggregate control first but do non-aggregate control otherwise */
6977 setup_url = control;
6978 else if ((setup_url = stream->conninfo.location) == NULL)
6981 if (src->conninfo.connection) {
6982 info = &src->conninfo;
6983 } else if (stream->conninfo.connection) {
6984 info = &stream->conninfo;
6988 if (!info->connected)
6993 gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6995 goto create_request_failed;
6998 GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
7001 gst_rtspsrc_send (src, info->connection, &request, &response,
7005 /* FIXME, parse result? */
7006 gst_rtsp_message_unset (&request);
7007 gst_rtsp_message_unset (&response);
7010 /* early exit when we did aggregate control */
7016 /* close connections */
7017 GST_DEBUG_OBJECT (src, "closing connection...");
7018 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7019 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7020 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7021 gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
7025 gst_rtspsrc_cleanup (src);
7027 src->state = GST_RTSP_STATE_INVALID;
7030 gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
7035 create_request_failed:
7037 gchar *str = gst_rtsp_strresult (res);
7039 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7040 ("Could not create request. (%s)", str));
7046 gchar *str = gst_rtsp_strresult (res);
7048 gst_rtsp_message_unset (&request);
7049 if (res != GST_RTSP_EINTR) {
7050 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7051 ("Could not send message. (%s)", str));
7053 GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7060 GST_DEBUG_OBJECT (src,
7061 "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7066 /* RTP-Info is of the format:
7068 * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7070 * rtptime corresponds to the timestamp for the NPT time given in the header
7071 * seqbase corresponds to the next sequence number we received. This number
7072 * indicates the first seqnum after the seek and should be used to discard
7073 * packets that are from before the seek.
7076 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7081 GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7083 infos = g_strsplit (rtpinfo, ",", 0);
7084 for (i = 0; infos[i]; i++) {
7086 GstRTSPStream *stream;
7090 GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7092 /* init values, types of seqbase and timebase are bigger than needed so we
7093 * can store -1 as uninitialized values */
7098 /* parse url, find stream for url.
7099 * parse seq and rtptime. The seq number should be configured in the rtp
7100 * depayloader or session manager to detect gaps. Same for the rtptime, it
7101 * should be used to create an initial time newsegment. */
7102 fields = g_strsplit (infos[i], ";", 0);
7103 for (j = 0; fields[j]; j++) {
7104 GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7105 /* remove leading whitespace */
7106 fields[j] = g_strchug (fields[j]);
7107 if (g_str_has_prefix (fields[j], "url=")) {
7108 /* get the url and the stream */
7110 find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7111 } else if (g_str_has_prefix (fields[j], "seq=")) {
7112 seqbase = atoi (fields[j] + 4);
7113 } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7114 timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7117 g_strfreev (fields);
7118 /* now we need to store the values for the caps of the stream */
7119 if (stream != NULL) {
7120 GST_DEBUG_OBJECT (src,
7121 "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7122 stream, seqbase, timebase);
7124 /* we have a stream, configure detected params */
7125 stream->seqbase = seqbase;
7126 stream->timebase = timebase;
7135 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7140 interval = strtoul (rtcp, NULL, 10);
7141 GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7146 interval *= GST_MSECOND;
7148 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7149 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7151 /* already (optionally) retrieved this when configuring manager */
7152 if (stream->session) {
7153 GObject *rtpsession = stream->session;
7155 GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7157 g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7161 /* now it happens that (Xenon) server sending this may also provide bogus
7162 * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7163 * and just use RTP-Info to sync */
7165 GObjectClass *klass;
7167 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7168 if (g_object_class_find_property (klass, "rtcp-sync")) {
7169 GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7170 g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7176 gst_rtspsrc_get_float (const gchar * dstr)
7178 gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7180 /* canonicalise floating point string so we can handle float strings
7181 * in the form "24.930" or "24,930" irrespective of the current locale */
7182 g_strlcpy (s, dstr, sizeof (s));
7183 g_strdelimit (s, ",", '.');
7184 return g_ascii_strtod (s, NULL);
7188 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7190 gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7192 if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7193 g_strlcpy (val_str, "now", sizeof (val_str));
7195 if (segment->position == 0) {
7196 g_strlcpy (val_str, "0", sizeof (val_str));
7198 g_ascii_dtostr (val_str, sizeof (val_str),
7199 ((gdouble) segment->position) / GST_SECOND);
7202 return g_strdup_printf ("npt=%s-", val_str);
7206 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7210 stream->timebase = -1;
7211 stream->seqbase = -1;
7213 len = stream->ptmap->len;
7214 for (i = 0; i < len; i++) {
7215 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7218 if (item->caps == NULL)
7221 item->caps = gst_caps_make_writable (item->caps);
7222 s = gst_caps_get_structure (item->caps, 0);
7223 gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7227 static GstRTSPResult
7228 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7230 GstRTSPResult res = GST_RTSP_OK;
7232 if (src->state < GST_RTSP_STATE_READY) {
7233 res = GST_RTSP_ERROR;
7234 if (src->open_error) {
7235 GST_DEBUG_OBJECT (src, "the stream was in error");
7239 gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7241 if ((res = gst_rtspsrc_open (src, async)) < 0) {
7242 GST_DEBUG_OBJECT (src, "failed to open stream");
7251 static GstRTSPResult
7252 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
7254 GstRTSPMessage request = { 0 };
7255 GstRTSPMessage response = { 0 };
7256 GstRTSPResult res = GST_RTSP_OK;
7260 const gchar *control;
7262 GST_DEBUG_OBJECT (src, "PLAY...");
7264 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7267 if (!(src->methods & GST_RTSP_PLAY))
7270 if (src->state == GST_RTSP_STATE_PLAYING)
7273 if (!src->conninfo.connection || !src->conninfo.connected)
7276 /* send some dummy packets before we activate the receive in the
7278 gst_rtspsrc_send_dummy_packets (src);
7280 /* require new SR packets */
7282 g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7284 gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7286 /* construct a control url */
7287 control = get_aggregate_control (src);
7289 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7290 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7291 const gchar *setup_url;
7292 GstRTSPConnection *conn;
7294 /* try aggregate control first but do non-aggregate control otherwise */
7296 setup_url = control;
7297 else if ((setup_url = stream->conninfo.location) == NULL)
7300 if (src->conninfo.connection) {
7301 conn = src->conninfo.connection;
7302 } else if (stream->conninfo.connection) {
7303 conn = stream->conninfo.connection;
7309 res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
7311 goto create_request_failed;
7313 if (src->need_range) {
7314 hval = gen_range_header (src, segment);
7316 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7318 /* store the newsegment event so it can be sent from the streaming thread. */
7319 if (src->start_segment)
7320 gst_event_unref (src->start_segment);
7321 src->start_segment = gst_event_new_segment (&src->segment);
7324 if (segment->rate != 1.0) {
7325 gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7327 g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7329 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7331 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7335 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7337 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7340 /* seek may have silently failed as it is not supported */
7341 if (!(src->methods & GST_RTSP_PLAY)) {
7342 GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7343 /* obviously it is supported as we made it here */
7344 src->methods |= GST_RTSP_PLAY;
7345 src->seekable = FALSE;
7346 /* but there is nothing to parse in the response,
7347 * so convey we have no idea and not to expect anything particular */
7348 clear_rtp_base (src, stream);
7352 /* need to do for all streams */
7353 for (run = src->streams; run; run = g_list_next (run))
7354 clear_rtp_base (src, (GstRTSPStream *) run->data);
7356 /* NOTE the above also disables npt based eos detection */
7357 /* and below forces position to 0,
7358 * which is visible feedback we lost the plot */
7359 segment->start = segment->position = src->last_pos;
7362 gst_rtsp_message_unset (&request);
7364 /* parse RTP npt field. This is the current position in the stream (Normal
7365 * Play Time) and should be put in the NEWSEGMENT position field. */
7366 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7368 gst_rtspsrc_parse_range (src, hval, segment);
7370 /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7371 segment->rate = 1.0;
7373 /* parse Speed header. This is the intended playback rate of the stream
7374 * and should be put in the NEWSEGMENT rate field. */
7375 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7376 0) == GST_RTSP_OK) {
7377 segment->rate = gst_rtspsrc_get_float (hval);
7378 } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7379 &hval, 0) == GST_RTSP_OK) {
7380 segment->rate = gst_rtspsrc_get_float (hval);
7383 /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7384 * for the RTP packets. If this is not present, we assume all starts from 0...
7385 * This is info for the RTP session manager that we pass to it in caps. */
7387 while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7388 &hval, hval_idx++) == GST_RTSP_OK)
7389 gst_rtspsrc_parse_rtpinfo (src, hval);
7391 /* some servers indicate RTCP parameters in PLAY response,
7392 * rather than properly in SDP */
7393 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7394 &hval, 0) == GST_RTSP_OK)
7395 gst_rtspsrc_handle_rtcp_interval (src, hval);
7397 gst_rtsp_message_unset (&response);
7399 /* early exit when we did aggregate control */
7403 /* configure the caps of the streams after we parsed all headers. Only reset
7404 * the manager object when we set a new Range header (we did a seek) */
7405 gst_rtspsrc_configure_caps (src, segment, src->need_range);
7407 /* set again when needed */
7408 src->need_range = FALSE;
7410 src->running = TRUE;
7411 src->base_time = -1;
7412 src->state = GST_RTSP_STATE_PLAYING;
7415 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7416 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7417 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7418 stream->discont = TRUE;
7423 gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7430 GST_DEBUG_OBJECT (src, "failed to open stream");
7435 GST_DEBUG_OBJECT (src, "PLAY is not supported");
7440 GST_DEBUG_OBJECT (src, "we were already PLAYING");
7443 create_request_failed:
7445 gchar *str = gst_rtsp_strresult (res);
7447 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7448 ("Could not create request. (%s)", str));
7454 gchar *str = gst_rtsp_strresult (res);
7456 gst_rtsp_message_unset (&request);
7457 if (res != GST_RTSP_EINTR) {
7458 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7459 ("Could not send message. (%s)", str));
7461 GST_WARNING_OBJECT (src, "PLAY interrupted");
7468 static GstRTSPResult
7469 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7471 GstRTSPResult res = GST_RTSP_OK;
7472 GstRTSPMessage request = { 0 };
7473 GstRTSPMessage response = { 0 };
7475 const gchar *control;
7477 GST_DEBUG_OBJECT (src, "PAUSE...");
7479 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7482 if (!(src->methods & GST_RTSP_PAUSE))
7485 if (src->state == GST_RTSP_STATE_READY)
7488 if (!src->conninfo.connection || !src->conninfo.connected)
7491 /* construct a control url */
7492 control = get_aggregate_control (src);
7494 /* loop over the streams. We might exit the loop early when we could do an
7495 * aggregate control */
7496 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7497 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7498 GstRTSPConnection *conn;
7499 const gchar *setup_url;
7501 /* try aggregate control first but do non-aggregate control otherwise */
7503 setup_url = control;
7504 else if ((setup_url = stream->conninfo.location) == NULL)
7507 if (src->conninfo.connection) {
7508 conn = src->conninfo.connection;
7509 } else if (stream->conninfo.connection) {
7510 conn = stream->conninfo.connection;
7516 GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7517 ("Sending PAUSE request"));
7520 gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
7522 goto create_request_failed;
7524 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7527 gst_rtsp_message_unset (&request);
7528 gst_rtsp_message_unset (&response);
7530 /* exit early when we did agregate control */
7535 /* change element states now */
7536 gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7539 src->state = GST_RTSP_STATE_READY;
7543 gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7550 GST_DEBUG_OBJECT (src, "failed to open stream");
7555 GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7560 GST_DEBUG_OBJECT (src, "we were already PAUSED");
7563 create_request_failed:
7565 gchar *str = gst_rtsp_strresult (res);
7567 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7568 ("Could not create request. (%s)", str));
7574 gchar *str = gst_rtsp_strresult (res);
7576 gst_rtsp_message_unset (&request);
7577 if (res != GST_RTSP_EINTR) {
7578 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7579 ("Could not send message. (%s)", str));
7581 GST_WARNING_OBJECT (src, "PAUSE interrupted");
7589 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
7591 GstRTSPSrc *rtspsrc;
7593 rtspsrc = GST_RTSPSRC (bin);
7595 switch (GST_MESSAGE_TYPE (message)) {
7596 case GST_MESSAGE_EOS:
7597 gst_message_unref (message);
7599 case GST_MESSAGE_ELEMENT:
7601 const GstStructure *s = gst_message_get_structure (message);
7603 if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
7604 gboolean ignore_timeout;
7606 GST_DEBUG_OBJECT (bin, "timeout on UDP port");
7608 GST_OBJECT_LOCK (rtspsrc);
7609 ignore_timeout = rtspsrc->ignore_timeout;
7610 rtspsrc->ignore_timeout = TRUE;
7611 GST_OBJECT_UNLOCK (rtspsrc);
7613 /* we only act on the first udp timeout message, others are irrelevant
7614 * and can be ignored. */
7615 if (!ignore_timeout)
7616 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
7618 gst_message_unref (message);
7621 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7624 case GST_MESSAGE_ERROR:
7627 GstRTSPStream *stream;
7630 udpsrc = GST_MESSAGE_SRC (message);
7632 GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
7633 GST_ELEMENT_NAME (udpsrc));
7635 stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
7639 /* we ignore the RTCP udpsrc */
7640 if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
7643 /* if we get error messages from the udp sources, that's not a problem as
7644 * long as not all of them error out. We also don't really know what the
7645 * problem is, the message does not give enough detail... */
7646 ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
7647 GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7648 if (ret != GST_FLOW_OK)
7652 gst_message_unref (message);
7656 /* fatal but not our message, forward */
7657 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7662 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7668 /* the thread where everything happens */
7670 gst_rtspsrc_thread (GstRTSPSrc * src)
7674 GST_OBJECT_LOCK (src);
7675 cmd = src->pending_cmd;
7676 if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7677 || cmd == CMD_LOOP || cmd == CMD_OPEN)
7678 src->pending_cmd = CMD_LOOP;
7680 src->pending_cmd = CMD_WAIT;
7681 GST_DEBUG_OBJECT (src, "got command %d", cmd);
7683 /* we got the message command, so ensure communication is possible again */
7684 gst_rtspsrc_connection_flush (src, FALSE);
7686 src->busy_cmd = cmd;
7687 GST_OBJECT_UNLOCK (src);
7691 gst_rtspsrc_open (src, TRUE);
7694 gst_rtspsrc_play (src, &src->segment, TRUE);
7697 gst_rtspsrc_pause (src, TRUE);
7700 gst_rtspsrc_close (src, TRUE, FALSE);
7703 gst_rtspsrc_loop (src);
7706 gst_rtspsrc_reconnect (src, FALSE);
7712 GST_OBJECT_LOCK (src);
7713 /* and go back to sleep */
7714 if (src->pending_cmd == CMD_WAIT) {
7716 gst_task_pause (src->task);
7719 src->busy_cmd = CMD_WAIT;
7720 GST_OBJECT_UNLOCK (src);
7724 gst_rtspsrc_start (GstRTSPSrc * src)
7726 GST_DEBUG_OBJECT (src, "starting");
7728 GST_OBJECT_LOCK (src);
7730 src->pending_cmd = CMD_WAIT;
7732 if (src->task == NULL) {
7733 src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
7734 if (src->task == NULL)
7737 gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
7739 GST_OBJECT_UNLOCK (src);
7746 GST_OBJECT_UNLOCK (src);
7747 GST_ERROR_OBJECT (src, "failed to create task");
7753 gst_rtspsrc_stop (GstRTSPSrc * src)
7757 GST_DEBUG_OBJECT (src, "stopping");
7759 /* also cancels pending task */
7760 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
7762 GST_OBJECT_LOCK (src);
7763 if ((task = src->task)) {
7765 GST_OBJECT_UNLOCK (src);
7767 gst_task_stop (task);
7769 /* make sure it is not running */
7770 GST_RTSP_STREAM_LOCK (src);
7771 GST_RTSP_STREAM_UNLOCK (src);
7773 /* now wait for the task to finish */
7774 gst_task_join (task);
7776 /* and free the task */
7777 gst_object_unref (GST_OBJECT (task));
7779 GST_OBJECT_LOCK (src);
7781 GST_OBJECT_UNLOCK (src);
7783 /* ensure synchronously all is closed and clean */
7784 gst_rtspsrc_close (src, FALSE, TRUE);
7789 static GstStateChangeReturn
7790 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
7792 GstRTSPSrc *rtspsrc;
7793 GstStateChangeReturn ret;
7795 rtspsrc = GST_RTSPSRC (element);
7797 switch (transition) {
7798 case GST_STATE_CHANGE_NULL_TO_READY:
7799 if (!gst_rtspsrc_start (rtspsrc))
7802 case GST_STATE_CHANGE_READY_TO_PAUSED:
7803 /* init some state */
7804 rtspsrc->cur_protocols = rtspsrc->protocols;
7805 /* first attempt, don't ignore timeouts */
7806 rtspsrc->ignore_timeout = FALSE;
7807 rtspsrc->open_error = FALSE;
7808 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
7810 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7811 set_manager_buffer_mode (rtspsrc);
7813 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7814 /* unblock the tcp tasks and make the loop waiting */
7815 if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
7816 /* make sure it is waiting before we send PAUSE or PLAY below */
7817 GST_RTSP_STREAM_LOCK (rtspsrc);
7818 GST_RTSP_STREAM_UNLOCK (rtspsrc);
7821 case GST_STATE_CHANGE_PAUSED_TO_READY:
7827 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7828 if (ret == GST_STATE_CHANGE_FAILURE)
7831 switch (transition) {
7832 case GST_STATE_CHANGE_NULL_TO_READY:
7833 ret = GST_STATE_CHANGE_SUCCESS;
7835 case GST_STATE_CHANGE_READY_TO_PAUSED:
7836 ret = GST_STATE_CHANGE_NO_PREROLL;
7838 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7839 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7840 ret = GST_STATE_CHANGE_SUCCESS;
7842 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7843 /* send pause request and keep the idle task around */
7844 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7845 ret = GST_STATE_CHANGE_NO_PREROLL;
7847 case GST_STATE_CHANGE_PAUSED_TO_READY:
7848 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7849 ret = GST_STATE_CHANGE_SUCCESS;
7851 case GST_STATE_CHANGE_READY_TO_NULL:
7852 gst_rtspsrc_stop (rtspsrc);
7853 ret = GST_STATE_CHANGE_SUCCESS;
7864 GST_DEBUG_OBJECT (rtspsrc, "start failed");
7865 return GST_STATE_CHANGE_FAILURE;
7870 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7873 GstRTSPSrc *rtspsrc;
7875 rtspsrc = GST_RTSPSRC (element);
7877 if (GST_EVENT_IS_DOWNSTREAM (event)) {
7878 res = gst_rtspsrc_push_event (rtspsrc, event);
7880 res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7887 /*** GSTURIHANDLER INTERFACE *************************************************/
7890 gst_rtspsrc_uri_get_type (GType type)
7895 static const gchar *const *
7896 gst_rtspsrc_uri_get_protocols (GType type)
7898 static const gchar *protocols[] =
7899 { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7900 "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7907 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7909 GstRTSPSrc *src = GST_RTSPSRC (handler);
7911 /* FIXME: make thread-safe */
7912 return g_strdup (src->conninfo.location);
7916 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7921 GstRTSPUrl *newurl = NULL;
7922 GstSDPMessage *sdp = NULL;
7924 src = GST_RTSPSRC (handler);
7926 /* same URI, we're fine */
7927 if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7930 if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7931 if ((res = gst_sdp_message_new (&sdp) < 0))
7934 GST_DEBUG_OBJECT (src, "parsing SDP message");
7935 if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7939 GST_DEBUG_OBJECT (src, "parsing URI");
7940 if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7944 /* if worked, free previous and store new url object along with the original
7946 GST_DEBUG_OBJECT (src, "configuring URI");
7947 g_free (src->conninfo.location);
7948 src->conninfo.location = g_strdup (uri);
7949 gst_rtsp_url_free (src->conninfo.url);
7950 src->conninfo.url = newurl;
7951 g_free (src->conninfo.url_str);
7953 src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7955 src->conninfo.url_str = NULL;
7958 gst_sdp_message_free (src->sdp);
7960 src->from_sdp = sdp != NULL;
7962 GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7963 GST_DEBUG_OBJECT (src, "request uri is: %s",
7964 GST_STR_NULL (src->conninfo.url_str));
7971 GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7976 GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7977 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7978 "Could not create SDP");
7983 GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7984 GST_STR_NULL (uri));
7985 gst_sdp_message_free (sdp);
7986 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7992 GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7993 GST_STR_NULL (uri), res);
7994 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7995 "Invalid RTSP URI");
8001 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
8003 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
8005 iface->get_type = gst_rtspsrc_uri_get_type;
8006 iface->get_protocols = gst_rtspsrc_uri_get_protocols;
8007 iface->get_uri = gst_rtspsrc_uri_get_uri;
8008 iface->set_uri = gst_rtspsrc_uri_set_uri;