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,
129 enum _GstRtspSrcRtcpSyncMode
136 enum _GstRtspSrcBufferMode
145 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
147 gst_rtsp_src_buffer_mode_get_type (void)
149 static GType buffer_mode_type = 0;
150 static const GEnumValue buffer_modes[] = {
151 {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
152 {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
153 {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
154 {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
155 {BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks", "synced"},
159 if (!buffer_mode_type) {
161 g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
163 return buffer_mode_type;
166 #define DEFAULT_LOCATION NULL
167 #define DEFAULT_PROTOCOLS GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
168 #define DEFAULT_DEBUG FALSE
169 #define DEFAULT_RETRY 20
170 #define DEFAULT_TIMEOUT 5000000
171 #define DEFAULT_UDP_BUFFER_SIZE 0x80000
172 #define DEFAULT_TCP_TIMEOUT 20000000
173 #define DEFAULT_LATENCY_MS 2000
174 #define DEFAULT_DROP_ON_LATENCY FALSE
175 #define DEFAULT_CONNECTION_SPEED 0
176 #define DEFAULT_NAT_METHOD GST_RTSP_NAT_DUMMY
177 #define DEFAULT_DO_RTCP TRUE
178 #define DEFAULT_DO_RTSP_KEEP_ALIVE TRUE
179 #define DEFAULT_PROXY NULL
180 #define DEFAULT_RTP_BLOCKSIZE 0
181 #define DEFAULT_USER_ID NULL
182 #define DEFAULT_USER_PW NULL
183 #define DEFAULT_BUFFER_MODE BUFFER_MODE_AUTO
184 #define DEFAULT_PORT_RANGE NULL
185 #define DEFAULT_SHORT_HEADER FALSE
186 #define DEFAULT_PROBATION 2
187 #define DEFAULT_UDP_RECONNECT TRUE
188 #define DEFAULT_MULTICAST_IFACE NULL
189 #define DEFAULT_NTP_SYNC FALSE
190 #define DEFAULT_USE_PIPELINE_CLOCK FALSE
191 #define DEFAULT_TLS_VALIDATION_FLAGS G_TLS_CERTIFICATE_VALIDATE_ALL
192 #define DEFAULT_TLS_DATABASE NULL
204 PROP_DROP_ON_LATENCY,
205 PROP_CONNECTION_SPEED,
208 PROP_DO_RTSP_KEEP_ALIVE,
217 PROP_UDP_BUFFER_SIZE,
221 PROP_MULTICAST_IFACE,
223 PROP_USE_PIPELINE_CLOCK,
225 PROP_TLS_VALIDATION_FLAGS,
230 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
232 gst_rtsp_nat_method_get_type (void)
234 static GType rtsp_nat_method_type = 0;
235 static const GEnumValue rtsp_nat_method[] = {
236 {GST_RTSP_NAT_NONE, "None", "none"},
237 {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
241 if (!rtsp_nat_method_type) {
242 rtsp_nat_method_type =
243 g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
245 return rtsp_nat_method_type;
248 static void gst_rtspsrc_finalize (GObject * object);
250 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
251 const GValue * value, GParamSpec * pspec);
252 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
253 GValue * value, GParamSpec * pspec);
255 static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
257 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
258 gpointer iface_data);
260 static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
263 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
264 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
266 static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
268 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
269 GstStateChange transition);
270 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
271 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
273 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
274 GstRTSPMessage * response);
276 static gboolean gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd,
278 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
279 GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
281 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
282 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
284 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
285 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
286 gboolean only_close);
288 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
289 const gchar * uri, GError ** error);
290 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
292 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
293 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
294 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
295 GstRTSPStream * stream, GstEvent * event);
296 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
297 static void gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush);
305 /* commands we send to out loop to notify it of events */
306 #define CMD_OPEN (1 << 0)
307 #define CMD_PLAY (1 << 1)
308 #define CMD_PAUSE (1 << 2)
309 #define CMD_CLOSE (1 << 3)
310 #define CMD_WAIT (1 << 4)
311 #define CMD_RECONNECT (1 << 5)
312 #define CMD_LOOP (1 << 6)
314 /* mask for all commands */
315 #define CMD_ALL ((CMD_LOOP << 1) - 1)
317 #define GST_ELEMENT_PROGRESS(el, type, code, text) \
319 gchar *__txt = _gst_element_error_printf text; \
320 gst_element_post_message (GST_ELEMENT_CAST (el), \
321 gst_message_new_progress (GST_OBJECT_CAST (el), \
322 GST_PROGRESS_TYPE_ ##type, code, __txt)); \
326 static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
328 #define gst_rtspsrc_parent_class parent_class
329 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
330 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
333 default_select_stream (GstRTSPSrc * src, guint id, GstCaps * caps)
335 GST_DEBUG_OBJECT (src, "default handler");
340 select_stream_accum (GSignalInvocationHint * ihint,
341 GValue * return_accu, const GValue * handler_return, gpointer data)
345 myboolean = g_value_get_boolean (handler_return);
346 GST_DEBUG ("accum %d", myboolean);
347 g_value_set_boolean (return_accu, myboolean);
349 /* stop emission if FALSE */
354 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
356 GObjectClass *gobject_class;
357 GstElementClass *gstelement_class;
358 GstBinClass *gstbin_class;
360 gobject_class = (GObjectClass *) klass;
361 gstelement_class = (GstElementClass *) klass;
362 gstbin_class = (GstBinClass *) klass;
364 GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
366 gobject_class->set_property = gst_rtspsrc_set_property;
367 gobject_class->get_property = gst_rtspsrc_get_property;
369 gobject_class->finalize = gst_rtspsrc_finalize;
371 g_object_class_install_property (gobject_class, PROP_LOCATION,
372 g_param_spec_string ("location", "RTSP Location",
373 "Location of the RTSP url to read",
374 DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
376 g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
377 g_param_spec_flags ("protocols", "Protocols",
378 "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
379 DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
381 g_object_class_install_property (gobject_class, PROP_DEBUG,
382 g_param_spec_boolean ("debug", "Debug",
383 "Dump request and response messages to stdout",
384 DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
386 g_object_class_install_property (gobject_class, PROP_RETRY,
387 g_param_spec_uint ("retry", "Retry",
388 "Max number of retries when allocating RTP ports.",
389 0, G_MAXUINT16, DEFAULT_RETRY,
390 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
393 g_param_spec_uint64 ("timeout", "Timeout",
394 "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
395 0, G_MAXUINT64, DEFAULT_TIMEOUT,
396 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
398 g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
399 g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
400 "Fail after timeout microseconds on TCP connections (0 = disabled)",
401 0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
402 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
404 g_object_class_install_property (gobject_class, PROP_LATENCY,
405 g_param_spec_uint ("latency", "Buffer latency in ms",
406 "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
407 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
409 g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
410 g_param_spec_boolean ("drop-on-latency",
411 "Drop buffers when maximum latency is reached",
412 "Tells the jitterbuffer to never exceed the given latency in size",
413 DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
415 g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
416 g_param_spec_uint64 ("connection-speed", "Connection Speed",
417 "Network connection speed in kbps (0 = unknown)",
418 0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
419 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
421 g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
422 g_param_spec_enum ("nat-method", "NAT Method",
423 "Method to use for traversing firewalls and NAT",
424 GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
425 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
428 * GstRTSPSrc:do-rtcp:
430 * Enable RTCP support. Some old server don't like RTCP and then this property
431 * needs to be set to FALSE.
433 g_object_class_install_property (gobject_class, PROP_DO_RTCP,
434 g_param_spec_boolean ("do-rtcp", "Do RTCP",
435 "Send RTCP packets, disable for old incompatible server.",
436 DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
439 * GstRTSPSrc:do-rtsp-keep-alive:
441 * Enable RTSP keep alive support. Some old server don't like RTSP
442 * keep alive and then this property needs to be set to FALSE.
444 g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
445 g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
446 "Send RTSP keep alive packets, disable for old incompatible server.",
447 DEFAULT_DO_RTSP_KEEP_ALIVE,
448 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
453 * Set the proxy parameters. This has to be a string of the format
454 * [http://][user:passwd@]host[:port].
456 g_object_class_install_property (gobject_class, PROP_PROXY,
457 g_param_spec_string ("proxy", "Proxy",
458 "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
459 DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
461 * GstRTSPSrc:proxy-id:
463 * Sets the proxy URI user id for authentication. If the URI set via the
464 * "proxy" property contains a user-id already, that will take precedence.
468 g_object_class_install_property (gobject_class, PROP_PROXY_ID,
469 g_param_spec_string ("proxy-id", "proxy-id",
470 "HTTP proxy URI user id for authentication", "",
471 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
473 * GstRTSPSrc:proxy-pw:
475 * Sets the proxy URI password for authentication. If the URI set via the
476 * "proxy" property contains a password already, that will take precedence.
480 g_object_class_install_property (gobject_class, PROP_PROXY_PW,
481 g_param_spec_string ("proxy-pw", "proxy-pw",
482 "HTTP proxy URI user password for authentication", "",
483 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
486 * GstRTSPSrc:rtp-blocksize:
488 * RTP package size to suggest to server.
490 g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
491 g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
492 "RTP package size to suggest to server (0 = disabled)",
493 0, 65536, DEFAULT_RTP_BLOCKSIZE,
494 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
496 g_object_class_install_property (gobject_class,
498 g_param_spec_string ("user-id", "user-id",
499 "RTSP location URI user id for authentication", DEFAULT_USER_ID,
500 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
501 g_object_class_install_property (gobject_class, PROP_USER_PW,
502 g_param_spec_string ("user-pw", "user-pw",
503 "RTSP location URI user password for authentication", DEFAULT_USER_PW,
504 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
507 * GstRTSPSrc:buffer-mode:
509 * Control the buffering and timestamping mode used by the jitterbuffer.
511 g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
512 g_param_spec_enum ("buffer-mode", "Buffer Mode",
513 "Control the buffering algorithm in use",
514 GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
515 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
518 * GstRTSPSrc:port-range:
520 * Configure the client port numbers that can be used to recieve RTP and
523 g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
524 g_param_spec_string ("port-range", "Port range",
525 "Client port range that can be used to receive RTP and RTCP data, "
526 "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
527 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
530 * GstRTSPSrc:udp-buffer-size:
532 * Size of the kernel UDP receive buffer in bytes.
534 g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
535 g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
536 "Size of the kernel UDP receive buffer in bytes, 0=default",
537 0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
538 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
541 * GstRTSPSrc:short-header:
543 * Only send the basic RTSP headers for broken encoders.
545 g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
546 g_param_spec_boolean ("short-header", "Short Header",
547 "Only send the basic RTSP headers for broken encoders",
548 DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
550 g_object_class_install_property (gobject_class, PROP_PROBATION,
551 g_param_spec_uint ("probation", "Number of probations",
552 "Consecutive packet sequence numbers to accept the source",
553 0, G_MAXUINT, DEFAULT_PROBATION,
554 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
556 g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
557 g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
558 "Reconnect to the server if RTSP connection is closed when doing UDP",
559 DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
561 g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
562 g_param_spec_string ("multicast-iface", "Multicast Interface",
563 "The network interface on which to join the multicast group",
564 DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
566 g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
567 g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
568 "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
569 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
571 g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
572 g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
573 "Use the pipeline running-time to set the NTP time in the RTCP SR messages",
574 DEFAULT_USE_PIPELINE_CLOCK,
575 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
577 g_object_class_install_property (gobject_class, PROP_SDES,
578 g_param_spec_boxed ("sdes", "SDES",
579 "The SDES items of this session",
580 GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
583 * GstRTSPSrc::tls-validation-flags:
585 * TLS certificate validation flags used to validate server
590 g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
591 g_param_spec_flags ("tls-validation-flags", "TLS validation flags",
592 "TLS certificate validation flags used to validate the server certificate",
593 G_TYPE_TLS_CERTIFICATE_FLAGS, DEFAULT_TLS_VALIDATION_FLAGS,
594 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
597 * GstRTSPSrc::tls-database:
599 * TLS database with anchor certificate authorities used to validate
600 * the server certificate.
604 g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
605 g_param_spec_object ("tls-database", "TLS database",
606 "TLS database with anchor certificate authorities used to validate the server certificate",
607 G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
610 * GstRTSPSrc::handle-request:
611 * @rtspsrc: a #GstRTSPSrc
612 * @request: a #GstRTSPMessage
613 * @response: a #GstRTSPMessage
615 * Handle a server request in @request and prepare @response.
617 * This signal is called from the streaming thread, you should therefore not
618 * do any state changes on @rtspsrc because this might deadlock. If you want
619 * to modify the state as a result of this signal, post a
620 * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
625 gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST] =
626 g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
627 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
628 G_TYPE_POINTER, G_TYPE_POINTER);
631 * GstRTSPSrc::on-sdp:
632 * @rtspsrc: a #GstRTSPSrc
633 * @sdp: a #GstSDPMessage
635 * Emited when the client has retrieved the SDP and before it configures the
636 * streams in the SDP. @sdp can be inspected and modified.
638 * This signal is called from the streaming thread, you should therefore not
639 * do any state changes on @rtspsrc because this might deadlock. If you want
640 * to modify the state as a result of this signal, post a
641 * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
646 gst_rtspsrc_signals[SIGNAL_ON_SDP] =
647 g_signal_new ("on-sdp", G_TYPE_FROM_CLASS (klass), 0,
648 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
649 GST_TYPE_SDP_MESSAGE | G_SIGNAL_TYPE_STATIC_SCOPE);
652 * GstRTSPSrc::select-stream:
653 * @rtspsrc: a #GstRTSPSrc
654 * @num: the stream number
655 * @caps: the stream caps
657 * Emited before the client decides to configure the stream @num with
660 * Returns: %TRUE when the stream should be selected, %FALSE when the stream
665 gst_rtspsrc_signals[SIGNAL_SELECT_STREAM] =
666 g_signal_new_class_handler ("select-stream", G_TYPE_FROM_CLASS (klass),
667 G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP,
668 (GCallback) default_select_stream, select_stream_accum, NULL,
669 g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_UINT,
672 * GstRTSPSrc::new-manager:
673 * @rtspsrc: a #GstRTSPSrc
674 * @manager: a #GstElement
676 * Emited after a new manager (like rtpbin) was created and the default
677 * properties were configured.
681 gst_rtspsrc_signals[SIGNAL_NEW_MANAGER] =
682 g_signal_new_class_handler ("new-manager", G_TYPE_FROM_CLASS (klass),
683 G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
684 g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
686 gstelement_class->send_event = gst_rtspsrc_send_event;
687 gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
688 gstelement_class->change_state = gst_rtspsrc_change_state;
690 gst_element_class_add_pad_template (gstelement_class,
691 gst_static_pad_template_get (&rtptemplate));
693 gst_element_class_set_static_metadata (gstelement_class,
694 "RTSP packet receiver", "Source/Network",
695 "Receive data over the network via RTSP (RFC 2326)",
696 "Wim Taymans <wim@fluendo.com>, "
697 "Thijs Vermeir <thijs.vermeir@barco.com>, "
698 "Lutz Mueller <lutz@topfrose.de>");
700 gstbin_class->handle_message = gst_rtspsrc_handle_message;
702 gst_rtsp_ext_list_init ();
706 gst_rtspsrc_init (GstRTSPSrc * src)
708 src->conninfo.location = g_strdup (DEFAULT_LOCATION);
709 src->protocols = DEFAULT_PROTOCOLS;
710 src->debug = DEFAULT_DEBUG;
711 src->retry = DEFAULT_RETRY;
712 src->udp_timeout = DEFAULT_TIMEOUT;
713 gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
714 src->latency = DEFAULT_LATENCY_MS;
715 src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
716 src->connection_speed = DEFAULT_CONNECTION_SPEED;
717 src->nat_method = DEFAULT_NAT_METHOD;
718 src->do_rtcp = DEFAULT_DO_RTCP;
719 src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
720 gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
721 src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
722 src->user_id = g_strdup (DEFAULT_USER_ID);
723 src->user_pw = g_strdup (DEFAULT_USER_PW);
724 src->buffer_mode = DEFAULT_BUFFER_MODE;
725 src->client_port_range.min = 0;
726 src->client_port_range.max = 0;
727 src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
728 src->short_header = DEFAULT_SHORT_HEADER;
729 src->probation = DEFAULT_PROBATION;
730 src->udp_reconnect = DEFAULT_UDP_RECONNECT;
731 src->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
732 src->ntp_sync = DEFAULT_NTP_SYNC;
733 src->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
735 src->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
736 src->tls_database = DEFAULT_TLS_DATABASE;
738 /* get a list of all extensions */
739 src->extensions = gst_rtsp_ext_list_get ();
741 /* connect to send signal */
742 gst_rtsp_ext_list_connect (src->extensions, "send",
743 (GCallback) gst_rtspsrc_send_cb, src);
745 /* protects the streaming thread in interleaved mode or the polling
746 * thread in UDP mode. */
747 g_rec_mutex_init (&src->stream_rec_lock);
749 /* protects our state changes from multiple invocations */
750 g_rec_mutex_init (&src->state_rec_lock);
752 src->state = GST_RTSP_STATE_INVALID;
754 GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
758 gst_rtspsrc_finalize (GObject * object)
762 rtspsrc = GST_RTSPSRC (object);
764 gst_rtsp_ext_list_free (rtspsrc->extensions);
765 g_free (rtspsrc->conninfo.location);
766 gst_rtsp_url_free (rtspsrc->conninfo.url);
767 g_free (rtspsrc->conninfo.url_str);
768 g_free (rtspsrc->user_id);
769 g_free (rtspsrc->user_pw);
770 g_free (rtspsrc->multi_iface);
773 gst_sdp_message_free (rtspsrc->sdp);
776 if (rtspsrc->provided_clock)
777 gst_object_unref (rtspsrc->provided_clock);
780 gst_structure_free (rtspsrc->sdes);
782 if (rtspsrc->tls_database)
783 g_object_unref (rtspsrc->tls_database);
786 g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
787 g_rec_mutex_clear (&rtspsrc->state_rec_lock);
789 G_OBJECT_CLASS (parent_class)->finalize (object);
793 gst_rtspsrc_provide_clock (GstElement * element)
795 GstRTSPSrc *src = GST_RTSPSRC (element);
798 if ((clock = src->provided_clock) != NULL)
799 gst_object_ref (clock);
804 /* a proxy string of the format [user:passwd@]host[:port] */
806 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
810 g_free (rtsp->proxy_user);
811 rtsp->proxy_user = NULL;
812 g_free (rtsp->proxy_passwd);
813 rtsp->proxy_passwd = NULL;
814 g_free (rtsp->proxy_host);
815 rtsp->proxy_host = NULL;
816 rtsp->proxy_port = 0;
823 /* we allow http:// in front but ignore it */
824 if (g_str_has_prefix (p, "http://"))
827 at = strchr (p, '@');
829 /* look for user:passwd */
830 col = strchr (proxy, ':');
831 if (col == NULL || col > at)
834 rtsp->proxy_user = g_strndup (p, col - p);
836 rtsp->proxy_passwd = g_strndup (col, at - col);
841 if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
842 rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
843 if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
844 rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
845 if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
846 GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
847 GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
850 col = strchr (p, ':');
853 /* everything before the colon is the hostname */
854 rtsp->proxy_host = g_strndup (p, col - p);
856 rtsp->proxy_port = strtoul (p, (char **) &p, 10);
858 rtsp->proxy_host = g_strdup (p);
859 rtsp->proxy_port = 8080;
865 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
867 rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
868 rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
871 rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
873 rtspsrc->ptcp_timeout = NULL;
877 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
882 rtspsrc = GST_RTSPSRC (object);
886 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
887 g_value_get_string (value), NULL);
890 rtspsrc->protocols = g_value_get_flags (value);
893 rtspsrc->debug = g_value_get_boolean (value);
896 rtspsrc->retry = g_value_get_uint (value);
899 rtspsrc->udp_timeout = g_value_get_uint64 (value);
901 case PROP_TCP_TIMEOUT:
902 gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
905 rtspsrc->latency = g_value_get_uint (value);
907 case PROP_DROP_ON_LATENCY:
908 rtspsrc->drop_on_latency = g_value_get_boolean (value);
910 case PROP_CONNECTION_SPEED:
911 rtspsrc->connection_speed = g_value_get_uint64 (value);
913 case PROP_NAT_METHOD:
914 rtspsrc->nat_method = g_value_get_enum (value);
917 rtspsrc->do_rtcp = g_value_get_boolean (value);
919 case PROP_DO_RTSP_KEEP_ALIVE:
920 rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
923 gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
926 if (rtspsrc->prop_proxy_id)
927 g_free (rtspsrc->prop_proxy_id);
928 rtspsrc->prop_proxy_id = g_value_dup_string (value);
931 if (rtspsrc->prop_proxy_pw)
932 g_free (rtspsrc->prop_proxy_pw);
933 rtspsrc->prop_proxy_pw = g_value_dup_string (value);
935 case PROP_RTP_BLOCKSIZE:
936 rtspsrc->rtp_blocksize = g_value_get_uint (value);
939 if (rtspsrc->user_id)
940 g_free (rtspsrc->user_id);
941 rtspsrc->user_id = g_value_dup_string (value);
944 if (rtspsrc->user_pw)
945 g_free (rtspsrc->user_pw);
946 rtspsrc->user_pw = g_value_dup_string (value);
948 case PROP_BUFFER_MODE:
949 rtspsrc->buffer_mode = g_value_get_enum (value);
951 case PROP_PORT_RANGE:
955 str = g_value_get_string (value);
957 sscanf (str, "%u-%u",
958 &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
960 rtspsrc->client_port_range.min = 0;
961 rtspsrc->client_port_range.max = 0;
965 case PROP_UDP_BUFFER_SIZE:
966 rtspsrc->udp_buffer_size = g_value_get_int (value);
968 case PROP_SHORT_HEADER:
969 rtspsrc->short_header = g_value_get_boolean (value);
972 rtspsrc->probation = g_value_get_uint (value);
974 case PROP_UDP_RECONNECT:
975 rtspsrc->udp_reconnect = g_value_get_boolean (value);
977 case PROP_MULTICAST_IFACE:
978 g_free (rtspsrc->multi_iface);
980 if (g_value_get_string (value) == NULL)
981 rtspsrc->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
983 rtspsrc->multi_iface = g_value_dup_string (value);
986 rtspsrc->ntp_sync = g_value_get_boolean (value);
988 case PROP_USE_PIPELINE_CLOCK:
989 rtspsrc->use_pipeline_clock = g_value_get_boolean (value);
992 rtspsrc->sdes = g_value_dup_boxed (value);
994 case PROP_TLS_VALIDATION_FLAGS:
995 rtspsrc->tls_validation_flags = g_value_get_flags (value);
997 case PROP_TLS_DATABASE:
998 g_clear_object (&rtspsrc->tls_database);
999 rtspsrc->tls_database = g_value_dup_object (value);
1002 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1008 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
1011 GstRTSPSrc *rtspsrc;
1013 rtspsrc = GST_RTSPSRC (object);
1017 g_value_set_string (value, rtspsrc->conninfo.location);
1019 case PROP_PROTOCOLS:
1020 g_value_set_flags (value, rtspsrc->protocols);
1023 g_value_set_boolean (value, rtspsrc->debug);
1026 g_value_set_uint (value, rtspsrc->retry);
1029 g_value_set_uint64 (value, rtspsrc->udp_timeout);
1031 case PROP_TCP_TIMEOUT:
1035 timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
1036 rtspsrc->tcp_timeout.tv_usec;
1037 g_value_set_uint64 (value, timeout);
1041 g_value_set_uint (value, rtspsrc->latency);
1043 case PROP_DROP_ON_LATENCY:
1044 g_value_set_boolean (value, rtspsrc->drop_on_latency);
1046 case PROP_CONNECTION_SPEED:
1047 g_value_set_uint64 (value, rtspsrc->connection_speed);
1049 case PROP_NAT_METHOD:
1050 g_value_set_enum (value, rtspsrc->nat_method);
1053 g_value_set_boolean (value, rtspsrc->do_rtcp);
1055 case PROP_DO_RTSP_KEEP_ALIVE:
1056 g_value_set_boolean (value, rtspsrc->do_rtsp_keep_alive);
1062 if (rtspsrc->proxy_host) {
1064 g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
1068 g_value_take_string (value, str);
1072 g_value_set_string (value, rtspsrc->prop_proxy_id);
1075 g_value_set_string (value, rtspsrc->prop_proxy_pw);
1077 case PROP_RTP_BLOCKSIZE:
1078 g_value_set_uint (value, rtspsrc->rtp_blocksize);
1081 g_value_set_string (value, rtspsrc->user_id);
1084 g_value_set_string (value, rtspsrc->user_pw);
1086 case PROP_BUFFER_MODE:
1087 g_value_set_enum (value, rtspsrc->buffer_mode);
1089 case PROP_PORT_RANGE:
1093 if (rtspsrc->client_port_range.min != 0) {
1094 str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
1095 rtspsrc->client_port_range.max);
1099 g_value_take_string (value, str);
1102 case PROP_UDP_BUFFER_SIZE:
1103 g_value_set_int (value, rtspsrc->udp_buffer_size);
1105 case PROP_SHORT_HEADER:
1106 g_value_set_boolean (value, rtspsrc->short_header);
1108 case PROP_PROBATION:
1109 g_value_set_uint (value, rtspsrc->probation);
1111 case PROP_UDP_RECONNECT:
1112 g_value_set_boolean (value, rtspsrc->udp_reconnect);
1114 case PROP_MULTICAST_IFACE:
1115 g_value_set_string (value, rtspsrc->multi_iface);
1118 g_value_set_boolean (value, rtspsrc->ntp_sync);
1120 case PROP_USE_PIPELINE_CLOCK:
1121 g_value_set_boolean (value, rtspsrc->use_pipeline_clock);
1124 g_value_set_boxed (value, rtspsrc->sdes);
1126 case PROP_TLS_VALIDATION_FLAGS:
1127 g_value_set_flags (value, rtspsrc->tls_validation_flags);
1129 case PROP_TLS_DATABASE:
1130 g_value_set_object (value, rtspsrc->tls_database);
1133 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1139 find_stream_by_id (GstRTSPStream * stream, gint * id)
1141 if (stream->id == *id)
1148 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
1150 if (stream->channel[0] == *channel || stream->channel[1] == *channel)
1157 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
1159 GstElement *src = (GstElement *) a;
1161 if (stream->udpsrc[0] == src)
1163 if (stream->udpsrc[1] == src)
1170 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
1172 if (stream->conninfo.location) {
1173 /* check qualified setup_url */
1174 if (!strcmp (stream->conninfo.location, (gchar *) a))
1177 if (stream->control_url) {
1178 /* check original control_url */
1179 if (!strcmp (stream->control_url, (gchar *) a))
1182 /* check if qualified setup_url ends with string */
1183 if (g_str_has_suffix (stream->control_url, (gchar *) a))
1190 static GstRTSPStream *
1191 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
1195 /* find and get stream */
1196 if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
1197 return (GstRTSPStream *) lstream->data;
1202 static const GstSDPBandwidth *
1203 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1204 const GstSDPMedia * media, const gchar * type)
1208 /* first look in the media specific section */
1209 len = gst_sdp_media_bandwidths_len (media);
1210 for (i = 0; i < len; i++) {
1211 const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
1213 if (strcmp (bw->bwtype, type) == 0)
1216 /* then look in the message specific section */
1217 len = gst_sdp_message_bandwidths_len (sdp);
1218 for (i = 0; i < len; i++) {
1219 const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
1221 if (strcmp (bw->bwtype, type) == 0)
1228 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1229 const GstSDPMedia * media, GstRTSPStream * stream)
1231 const GstSDPBandwidth *bw;
1233 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
1234 stream->as_bandwidth = bw->bandwidth;
1236 stream->as_bandwidth = -1;
1238 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
1239 stream->rr_bandwidth = bw->bandwidth;
1241 stream->rr_bandwidth = -1;
1243 if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
1244 stream->rs_bandwidth = bw->bandwidth;
1246 stream->rs_bandwidth = -1;
1250 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
1251 const GstSDPConnection * conn)
1253 if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
1256 if (conn->addrtype == NULL)
1259 /* check for IPV6 */
1260 if (strcmp (conn->addrtype, "IP4") == 0)
1261 stream->is_ipv6 = FALSE;
1262 else if (strcmp (conn->addrtype, "IP6") == 0)
1263 stream->is_ipv6 = TRUE;
1268 g_free (stream->destination);
1269 stream->destination = g_strdup (conn->address);
1271 /* check for multicast */
1272 stream->is_multicast =
1273 gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
1275 stream->ttl = conn->ttl;
1278 /* Go over the connections for a stream.
1279 * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
1281 * - If we are dealing with a localhost address, we disable multicast
1284 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
1285 const GstSDPMedia * media, GstRTSPStream * stream)
1287 const GstSDPConnection *conn;
1290 /* first look in the media specific section */
1291 len = gst_sdp_media_connections_len (media);
1292 for (i = 0; i < len; i++) {
1293 conn = gst_sdp_media_get_connection (media, i);
1295 gst_rtspsrc_do_stream_connection (src, stream, conn);
1297 /* then look in the message specific section */
1298 if ((conn = gst_sdp_message_get_connection (sdp))) {
1299 gst_rtspsrc_do_stream_connection (src, stream, conn);
1303 /* m=<media> <UDP port> RTP/AVP <payload>
1306 gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
1307 const GstSDPMedia * media, GstRTSPStream * stream)
1313 proto = gst_sdp_media_get_proto (media);
1317 if (g_str_equal (proto, "RTP/AVP"))
1318 stream->profile = GST_RTSP_PROFILE_AVP;
1319 else if (g_str_equal (proto, "RTP/SAVP"))
1320 stream->profile = GST_RTSP_PROFILE_SAVP;
1321 else if (g_str_equal (proto, "RTP/AVPF"))
1322 stream->profile = GST_RTSP_PROFILE_AVPF;
1323 else if (g_str_equal (proto, "RTP/SAVPF"))
1324 stream->profile = GST_RTSP_PROFILE_SAVPF;
1328 len = gst_sdp_media_formats_len (media);
1329 for (i = 0; i < len; i++) {
1336 pt = atoi (gst_sdp_media_get_format (media, i));
1338 GST_DEBUG_OBJECT (src, " looking at %d pt: %d", i, pt);
1341 caps = gst_rtspsrc_media_to_caps (pt, media);
1343 GST_WARNING_OBJECT (src, " skipping pt %d without caps", pt);
1347 /* do some tweaks */
1348 s = gst_caps_get_structure (caps, 0);
1349 if ((enc = gst_structure_get_string (s, "encoding-name"))) {
1350 stream->is_real = (strstr (enc, "-REAL") != NULL);
1351 if (strcmp (enc, "X-ASF-PF") == 0)
1352 stream->container = TRUE;
1354 GST_DEBUG ("mapping sdp session level attributes to caps");
1355 gst_rtspsrc_sdp_attributes_to_caps (sdp->attributes, caps);
1356 GST_DEBUG ("mapping sdp media level attributes to caps");
1357 gst_rtspsrc_sdp_attributes_to_caps (media->attributes, caps);
1359 /* the first pt will be the default */
1360 if (stream->ptmap->len == 0)
1361 stream->default_pt = pt;
1365 g_array_append_val (stream->ptmap, item);
1371 GST_ERROR_OBJECT (src, "can't find proto in media");
1376 GST_ERROR_OBJECT (src, "unknown proto in media %s", proto);
1381 static const gchar *
1382 get_aggregate_control (GstRTSPSrc * src)
1387 base = src->control;
1388 else if (src->content_base)
1389 base = src->content_base;
1390 else if (src->conninfo.url_str)
1391 base = src->conninfo.url_str;
1399 clear_ptmap_item (PtMapItem * item)
1402 gst_caps_unref (item->caps);
1405 static GstRTSPStream *
1406 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
1408 GstRTSPStream *stream;
1409 const gchar *control_url;
1410 const GstSDPMedia *media;
1412 /* get media, should not return NULL */
1413 media = gst_sdp_message_get_media (sdp, idx);
1417 stream = g_new0 (GstRTSPStream, 1);
1418 stream->parent = src;
1419 /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1421 stream->last_ret = GST_FLOW_NOT_LINKED;
1422 stream->added = FALSE;
1423 stream->setup = FALSE;
1424 stream->skipped = FALSE;
1426 stream->eos = FALSE;
1427 stream->discont = TRUE;
1428 stream->seqbase = -1;
1429 stream->timebase = -1;
1430 stream->profile = GST_RTSP_PROFILE_AVP;
1431 stream->ptmap = g_array_new (FALSE, FALSE, sizeof (PtMapItem));
1432 g_array_set_clear_func (stream->ptmap, (GDestroyNotify) clear_ptmap_item);
1434 /* collect bandwidth information for this steam. FIXME, configure in the RTP
1435 * session manager to scale RTCP. */
1436 gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1438 /* collect connection info */
1439 gst_rtspsrc_collect_connections (src, sdp, media, stream);
1441 /* make the payload type map */
1442 gst_rtspsrc_collect_payloads (src, sdp, media, stream);
1444 /* collect port number */
1445 stream->port = gst_sdp_media_get_port (media);
1447 /* get control url to construct the setup url. The setup url is used to
1448 * configure the transport of the stream and is used to identity the stream in
1449 * the RTP-Info header field returned from PLAY. */
1450 control_url = gst_sdp_media_get_attribute_val (media, "control");
1451 if (control_url == NULL)
1452 control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1454 GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1455 GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1456 GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1457 GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1459 if (control_url != NULL) {
1460 stream->control_url = g_strdup (control_url);
1461 /* Build a fully qualified url using the content_base if any or by prefixing
1462 * the original request.
1463 * If the control_url starts with a '/' or a non rtsp: protocol we will most
1464 * likely build a URL that the server will fail to understand, this is ok,
1465 * we will fail then. */
1466 if (g_str_has_prefix (control_url, "rtsp://"))
1467 stream->conninfo.location = g_strdup (control_url);
1472 if (g_strcmp0 (control_url, "*") == 0)
1475 base = get_aggregate_control (src);
1477 /* check if the base ends or control starts with / */
1478 has_slash = g_str_has_prefix (control_url, "/");
1479 has_slash = has_slash || g_str_has_suffix (base, "/");
1481 /* concatenate the two strings, insert / when not present */
1482 stream->conninfo.location =
1483 g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1486 GST_DEBUG_OBJECT (src, " setup: %s",
1487 GST_STR_NULL (stream->conninfo.location));
1489 /* we keep track of all streams */
1490 src->streams = g_list_append (src->streams, stream);
1498 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1502 GST_DEBUG_OBJECT (src, "free stream %p", stream);
1504 g_array_free (stream->ptmap, TRUE);
1506 g_free (stream->destination);
1507 g_free (stream->control_url);
1508 g_free (stream->conninfo.location);
1510 for (i = 0; i < 2; i++) {
1511 if (stream->udpsrc[i]) {
1512 gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1513 gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1514 gst_object_unref (stream->udpsrc[i]);
1516 if (stream->channelpad[i])
1517 gst_object_unref (stream->channelpad[i]);
1519 if (stream->udpsink[i]) {
1520 gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1521 gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1522 gst_object_unref (stream->udpsink[i]);
1525 if (stream->fakesrc) {
1526 gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1527 gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1528 gst_object_unref (stream->fakesrc);
1530 if (stream->srcpad) {
1531 gst_pad_set_active (stream->srcpad, FALSE);
1533 gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1535 if (stream->srtpenc)
1536 gst_object_unref (stream->srtpenc);
1537 if (stream->srtpdec)
1538 gst_object_unref (stream->srtpdec);
1540 gst_buffer_unref (stream->key);
1541 if (stream->rtcppad)
1542 gst_object_unref (stream->rtcppad);
1543 if (stream->session)
1544 g_object_unref (stream->session);
1549 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1553 GST_DEBUG_OBJECT (src, "cleanup");
1555 for (walk = src->streams; walk; walk = g_list_next (walk)) {
1556 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1558 gst_rtspsrc_stream_free (src, stream);
1560 g_list_free (src->streams);
1561 src->streams = NULL;
1563 if (src->manager_sig_id) {
1564 g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1565 src->manager_sig_id = 0;
1567 gst_element_set_state (src->manager, GST_STATE_NULL);
1568 gst_bin_remove (GST_BIN_CAST (src), src->manager);
1569 src->manager = NULL;
1572 gst_structure_free (src->props);
1575 g_free (src->content_base);
1576 src->content_base = NULL;
1578 g_free (src->control);
1579 src->control = NULL;
1582 gst_rtsp_range_free (src->range);
1585 /* don't clear the SDP when it was used in the url */
1586 if (src->sdp && !src->from_sdp) {
1587 gst_sdp_message_free (src->sdp);
1590 if (src->start_segment) {
1591 gst_event_unref (src->start_segment);
1592 src->start_segment = NULL;
1594 if (src->provided_clock) {
1595 gst_object_unref (src->provided_clock);
1596 src->provided_clock = NULL;
1600 #define PARSE_INT(p, del, res) \
1603 p = strstr (p, del); \
1613 #define PARSE_STRING(p, del, res) \
1616 p = strstr (p, del); \
1628 #define SKIP_SPACES(p) \
1629 while (*p && g_ascii_isspace (*p)) \
1634 * <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1637 gst_rtspsrc_parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
1638 gint * rate, gchar ** params)
1642 p = (gchar *) rtpmap;
1644 PARSE_INT (p, " ", *payload);
1652 PARSE_STRING (p, "/", *name);
1653 if (*name == NULL) {
1654 GST_DEBUG ("no rate, name %s", p);
1655 /* no rate, assume -1 then, this is not supposed to happen but RealMedia
1656 * streams seem to omit the rate. */
1663 p = strstr (p, "/");
1681 parse_keymgmt (const gchar * keymgmt, GstCaps * caps)
1683 gboolean res = FALSE;
1687 GstMIKEYMessage *msg;
1688 const GstMIKEYPayload *payload;
1689 const gchar *srtp_cipher;
1690 const gchar *srtp_auth;
1692 p = (gchar *) keymgmt;
1698 PARSE_STRING (p, " ", kmpid);
1699 if (!g_str_equal (kmpid, "mikey"))
1702 data = g_base64_decode (p, &size);
1706 msg = gst_mikey_message_new_from_data (data, size, NULL, NULL);
1710 srtp_cipher = "aes-128-icm";
1711 srtp_auth = "hmac-sha1-80";
1713 /* check the Security policy if any */
1714 if ((payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, 0))) {
1715 GstMIKEYPayloadSP *p = (GstMIKEYPayloadSP *) payload;
1718 if (p->proto != GST_MIKEY_SEC_PROTO_SRTP)
1721 len = gst_mikey_payload_sp_get_n_params (payload);
1722 for (i = 0; i < len; i++) {
1723 const GstMIKEYPayloadSPParam *param =
1724 gst_mikey_payload_sp_get_param (payload, i);
1726 switch (param->type) {
1727 case GST_MIKEY_SP_SRTP_ENC_ALG:
1728 switch (param->val[0]) {
1730 srtp_cipher = "null";
1734 srtp_cipher = "aes-128-icm";
1740 case GST_MIKEY_SP_SRTP_AUTH_ALG:
1741 switch (param->val[0]) {
1747 srtp_auth = "hmac-sha1-80";
1753 case GST_MIKEY_SP_SRTP_SRTP_ENC:
1755 case GST_MIKEY_SP_SRTP_SRTCP_ENC:
1763 if (!(payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_KEMAC, 0)))
1766 GstMIKEYPayloadKEMAC *p = (GstMIKEYPayloadKEMAC *) payload;
1767 const GstMIKEYPayload *sub;
1768 GstMIKEYPayloadKeyData *pkd;
1771 if (p->enc_alg != GST_MIKEY_ENC_NULL || p->mac_alg != GST_MIKEY_MAC_NULL)
1774 if (!(sub = gst_mikey_payload_kemac_get_sub (payload, 0)))
1777 if (sub->type != GST_MIKEY_PT_KEY_DATA)
1780 pkd = (GstMIKEYPayloadKeyData *) sub;
1782 gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1784 gst_caps_set_simple (caps, "srtp-key", GST_TYPE_BUFFER, buf, NULL);
1787 gst_caps_set_simple (caps,
1788 "srtp-cipher", G_TYPE_STRING, srtp_cipher,
1789 "srtp-auth", G_TYPE_STRING, srtp_auth,
1790 "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
1791 "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
1795 gst_mikey_message_free (msg);
1801 * Mapping SDP attributes to caps
1803 * prepend 'a-' to IANA registered sdp attributes names
1804 * (ie: not prefixed with 'x-') in order to avoid
1805 * collision with gstreamer standard caps properties names
1808 gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
1810 if (attributes->len > 0) {
1814 s = gst_caps_get_structure (caps, 0);
1816 for (i = 0; i < attributes->len; i++) {
1817 GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
1818 gchar *tofree, *key;
1822 /* skip some of the attribute we already handle */
1823 if (!strcmp (key, "fmtp"))
1825 if (!strcmp (key, "rtpmap"))
1827 if (!strcmp (key, "control"))
1829 if (!strcmp (key, "range"))
1831 if (g_str_equal (key, "key-mgmt")) {
1832 parse_keymgmt (attr->value, caps);
1836 /* string must be valid UTF8 */
1837 if (!g_utf8_validate (attr->value, -1, NULL))
1840 if (!g_str_has_prefix (key, "x-"))
1841 tofree = key = g_strdup_printf ("a-%s", key);
1845 GST_DEBUG ("adding caps: %s=%s", key, attr->value);
1846 gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
1852 static const gchar *
1853 rtsp_get_attribute_for_pt (const GstSDPMedia * media, const gchar * name,
1862 if ((attr = gst_sdp_media_get_attribute_val_n (media, name, i)) == NULL)
1865 if (sscanf (attr, "%d ", &val) != 1)
1875 * Mapping of caps to and from SDP fields:
1877 * a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1878 * a=fmtp:<payload> <param>[=<value>];...
1881 gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
1884 const gchar *rtpmap;
1888 gchar *params = NULL;
1894 /* get and parse rtpmap */
1895 rtpmap = rtsp_get_attribute_for_pt (media, "rtpmap", pt);
1898 ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, ¶ms);
1900 g_warning ("error parsing rtpmap, ignoring");
1904 /* dynamic payloads need rtpmap or we fail */
1905 if (rtpmap == NULL && pt >= 96)
1908 /* check if we have a rate, if not, we need to look up the rate from the
1909 * default rates based on the payload types. */
1911 const GstRTPPayloadInfo *info;
1913 if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
1914 /* dynamic types, use media and encoding_name */
1915 tmp = g_ascii_strdown (media->media, -1);
1916 info = gst_rtp_payload_info_for_name (tmp, name);
1919 /* static types, use payload type */
1920 info = gst_rtp_payload_info_for_pt (pt);
1924 if ((rate = info->clock_rate) == 0)
1927 /* we fail if we cannot find one */
1932 tmp = g_ascii_strdown (media->media, -1);
1933 caps = gst_caps_new_simple ("application/x-unknown",
1934 "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
1936 s = gst_caps_get_structure (caps, 0);
1938 gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
1940 /* encoding name must be upper case */
1942 tmp = g_ascii_strup (name, -1);
1943 gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
1947 /* params must be lower case */
1948 if (params != NULL) {
1949 tmp = g_ascii_strdown (params, -1);
1950 gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
1954 /* parse optional fmtp: field */
1955 if ((fmtp = rtsp_get_attribute_for_pt (media, "fmtp", pt))) {
1961 /* p is now of the format <payload> <param>[=<value>];... */
1962 PARSE_INT (p, " ", payload);
1963 if (payload != -1 && payload == pt) {
1967 /* <param>[=<value>] are separated with ';' */
1968 pairs = g_strsplit (p, ";", 0);
1969 for (i = 0; pairs[i]; i++) {
1971 const gchar *val, *key;
1973 /* the key may not have a '=', the value can have other '='s */
1974 valpos = strstr (pairs[i], "=");
1976 /* we have a '=' and thus a value, remove the '=' with \0 */
1978 /* value is everything between '=' and ';'. We split the pairs at ;
1979 * boundaries so we can take the remainder of the value. Some servers
1980 * put spaces around the value which we strip off here. Alternatively
1981 * we could strip those spaces in the depayloaders should these spaces
1982 * actually carry any meaning in the future. */
1983 val = g_strstrip (valpos + 1);
1985 /* simple <param>;.. is translated into <param>=1;... */
1988 /* strip the key of spaces, convert key to lowercase but not the value. */
1989 key = g_strstrip (pairs[i]);
1990 if (strlen (key) > 1) {
1991 tmp = g_ascii_strdown (key, -1);
1992 gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
2004 g_warning ("rtpmap type not given for dynamic payload %d", pt);
2009 g_warning ("rate unknown for payload type %d", pt);
2015 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
2016 gint * rtpport, gint * rtcpport)
2019 GstStateChangeReturn ret;
2020 GstElement *udpsrc0, *udpsrc1;
2021 gint tmp_rtp, tmp_rtcp;
2025 src = stream->parent;
2031 /* Start at next port */
2032 tmp_rtp = src->next_port_num;
2034 if (stream->is_ipv6)
2035 host = "udp://[::0]";
2037 host = "udp://0.0.0.0";
2039 /* try to allocate 2 UDP ports, the RTP port should be an even
2040 * number and the RTCP port should be the next (uneven) port */
2043 if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
2044 tmp_rtp >= src->client_port_range.max)
2047 udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2048 if (udpsrc0 == NULL)
2049 goto no_udp_protocol;
2050 g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
2052 if (src->udp_buffer_size != 0)
2053 g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
2056 ret = gst_element_set_state (udpsrc0, GST_STATE_READY);
2057 if (ret == GST_STATE_CHANGE_FAILURE) {
2059 GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
2062 if (++count > src->retry)
2065 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2066 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2067 gst_object_unref (udpsrc0);
2070 GST_DEBUG_OBJECT (src, "retry %d", count);
2073 goto no_udp_protocol;
2076 g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
2077 GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
2079 /* check if port is even */
2080 if ((tmp_rtp & 0x01) != 0) {
2081 /* port not even, close and allocate another */
2082 if (++count > src->retry)
2085 GST_DEBUG_OBJECT (src, "RTP port not even");
2087 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2088 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2089 gst_object_unref (udpsrc0);
2092 GST_DEBUG_OBJECT (src, "retry %d", count);
2097 /* allocate port+1 for RTCP now */
2098 udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2099 if (udpsrc1 == NULL)
2100 goto no_udp_rtcp_protocol;
2103 tmp_rtcp = tmp_rtp + 1;
2104 if (src->client_port_range.max > 0 && tmp_rtcp > src->client_port_range.max)
2107 g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
2109 GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
2110 ret = gst_element_set_state (udpsrc1, GST_STATE_READY);
2111 /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
2112 if (ret == GST_STATE_CHANGE_FAILURE) {
2113 GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
2115 if (++count > src->retry)
2118 GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2119 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2120 gst_object_unref (udpsrc0);
2123 GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
2124 gst_element_set_state (udpsrc1, GST_STATE_NULL);
2125 gst_object_unref (udpsrc1);
2129 GST_DEBUG_OBJECT (src, "retry %d", count);
2133 /* all fine, do port check */
2134 g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
2135 g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
2137 /* this should not happen... */
2138 if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
2141 /* we keep these elements, we configure all in configure_transport when the
2142 * server told us to really use the UDP ports. */
2143 stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
2144 stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
2145 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
2146 gst_element_set_locked_state (stream->udpsrc[1], TRUE);
2148 /* keep track of next available port number when we have a range
2150 if (src->next_port_num != 0)
2151 src->next_port_num = tmp_rtcp + 1;
2158 GST_DEBUG_OBJECT (src, "could not get UDP source");
2163 GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
2167 no_udp_rtcp_protocol:
2169 GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
2174 GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
2175 tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
2181 gst_element_set_state (udpsrc0, GST_STATE_NULL);
2182 gst_object_unref (udpsrc0);
2185 gst_element_set_state (udpsrc1, GST_STATE_NULL);
2186 gst_object_unref (udpsrc1);
2193 gst_rtspsrc_set_state (GstRTSPSrc * src, GstState state)
2198 gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
2200 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2201 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2204 for (i = 0; i < 2; i++) {
2205 if (stream->udpsrc[i])
2206 gst_element_set_state (stream->udpsrc[i], state);
2212 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
2219 event = gst_event_new_flush_start ();
2220 GST_DEBUG_OBJECT (src, "start flush");
2222 state = GST_STATE_PAUSED;
2224 event = gst_event_new_flush_stop (FALSE);
2225 GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
2228 state = GST_STATE_PLAYING;
2230 state = GST_STATE_PAUSED;
2232 gst_rtspsrc_push_event (src, event);
2233 gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
2234 gst_rtspsrc_set_state (src, state);
2237 static GstRTSPResult
2238 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
2239 GstRTSPMessage * message, GTimeVal * timeout)
2244 ret = gst_rtsp_connection_send (conn, message, timeout);
2246 ret = GST_RTSP_ERROR;
2251 static GstRTSPResult
2252 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
2253 GstRTSPMessage * message, GTimeVal * timeout)
2258 ret = gst_rtsp_connection_receive (conn, message, timeout);
2260 ret = GST_RTSP_ERROR;
2266 gst_rtspsrc_get_position (GstRTSPSrc * src)
2271 query = gst_query_new_position (GST_FORMAT_TIME);
2272 /* should be known somewhere down the stream (e.g. jitterbuffer) */
2273 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2274 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2278 if (stream->srcpad) {
2279 if (gst_pad_query (stream->srcpad, query)) {
2280 gst_query_parse_position (query, &fmt, &pos);
2281 GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
2282 GST_TIME_ARGS (pos));
2283 src->last_pos = pos;
2293 gst_rtspsrc_do_seek (GstRTSPSrc * src, GstSegment * segment)
2295 src->state = GST_RTSP_STATE_SEEKING;
2296 /* PLAY will add the range header now. */
2297 src->need_range = TRUE;
2303 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
2308 GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2310 gboolean flush, skip;
2313 GstSegment seeksegment = { 0, };
2317 GST_DEBUG_OBJECT (src, "doing seek with event");
2319 gst_event_parse_seek (event, &rate, &format, &flags,
2320 &cur_type, &cur, &stop_type, &stop);
2322 /* no negative rates yet */
2326 /* we need TIME format */
2327 if (format != src->segment.format)
2330 GST_DEBUG_OBJECT (src, "doing seek without event");
2332 cur_type = GST_SEEK_TYPE_SET;
2333 stop_type = GST_SEEK_TYPE_SET;
2336 /* get flush flag */
2337 flush = flags & GST_SEEK_FLAG_FLUSH;
2338 skip = flags & GST_SEEK_FLAG_SKIP;
2340 /* now we need to make sure the streaming thread is stopped. We do this by
2341 * either sending a FLUSH_START event downstream which will cause the
2342 * streaming thread to stop with a WRONG_STATE.
2343 * For a non-flushing seek we simply pause the task, which will happen as soon
2344 * as it completes one iteration (and thus might block when the sink is
2345 * blocking in preroll). */
2347 GST_DEBUG_OBJECT (src, "starting flush");
2348 gst_rtspsrc_flush (src, TRUE, FALSE);
2351 gst_task_pause (src->task);
2355 /* we should now be able to grab the streaming thread because we stopped it
2356 * with the above flush/pause code */
2357 GST_RTSP_STREAM_LOCK (src);
2359 GST_DEBUG_OBJECT (src, "stopped streaming");
2361 /* stop flushing the rtsp connection so we can send PAUSE/PLAY below */
2362 gst_rtspsrc_connection_flush (src, FALSE);
2364 /* copy segment, we need this because we still need the old
2365 * segment when we close the current segment. */
2366 memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2368 /* configure the seek parameters in the seeksegment. We will then have the
2369 * right values in the segment to perform the seek */
2371 GST_DEBUG_OBJECT (src, "configuring seek");
2372 gst_segment_do_seek (&seeksegment, rate, format, flags,
2373 cur_type, cur, stop_type, stop, &update);
2376 /* figure out the last position we need to play. If it's configured (stop !=
2377 * -1), use that, else we play until the total duration of the file */
2378 if ((stop = seeksegment.stop) == -1)
2379 stop = seeksegment.duration;
2381 playing = (src->state == GST_RTSP_STATE_PLAYING);
2383 /* if we were playing, pause first */
2385 /* obtain current position in case seek fails */
2386 gst_rtspsrc_get_position (src);
2387 gst_rtspsrc_pause (src, FALSE);
2391 gst_rtspsrc_do_seek (src, &seeksegment);
2393 /* and continue playing */
2395 gst_rtspsrc_play (src, &seeksegment, FALSE);
2397 /* prepare for streaming again */
2399 /* if we started flush, we stop now */
2400 GST_DEBUG_OBJECT (src, "stopping flush");
2401 gst_rtspsrc_flush (src, FALSE, playing);
2404 /* now we did the seek and can activate the new segment values */
2405 memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2407 /* if we're doing a segment seek, post a SEGMENT_START message */
2408 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2409 gst_element_post_message (GST_ELEMENT_CAST (src),
2410 gst_message_new_segment_start (GST_OBJECT_CAST (src),
2411 src->segment.format, src->segment.position));
2414 /* now create the newsegment */
2415 GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2416 " to %" G_GINT64_FORMAT, src->segment.position, stop);
2419 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2420 for (walk = src->streams; walk; walk = g_list_next (walk)) {
2421 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2422 stream->discont = TRUE;
2425 GST_RTSP_STREAM_UNLOCK (src);
2432 GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2437 GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2443 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2447 gboolean res = TRUE;
2450 src = GST_RTSPSRC_CAST (parent);
2452 GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2453 GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2455 switch (GST_EVENT_TYPE (event)) {
2456 case GST_EVENT_SEEK:
2457 res = gst_rtspsrc_perform_seek (src, event);
2461 case GST_EVENT_NAVIGATION:
2462 case GST_EVENT_LATENCY:
2470 if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2471 res = gst_pad_send_event (target, event);
2472 gst_object_unref (target);
2474 gst_event_unref (event);
2477 gst_event_unref (event);
2483 /* this is the final event function we receive on the internal source pad when
2484 * we deal with TCP connections */
2486 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2491 GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2493 switch (GST_EVENT_TYPE (event)) {
2494 case GST_EVENT_SEEK:
2496 case GST_EVENT_NAVIGATION:
2497 case GST_EVENT_LATENCY:
2499 gst_event_unref (event);
2506 /* this is the final query function we receive on the internal source pad when
2507 * we deal with TCP connections */
2509 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2513 gboolean res = TRUE;
2515 src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2517 GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2518 GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2520 switch (GST_QUERY_TYPE (query)) {
2521 case GST_QUERY_POSITION:
2526 case GST_QUERY_DURATION:
2530 gst_query_parse_duration (query, &format, NULL);
2533 case GST_FORMAT_TIME:
2534 gst_query_set_duration (query, format, src->segment.duration);
2542 case GST_QUERY_LATENCY:
2544 /* we are live with a min latency of 0 and unlimited max latency, this
2545 * result will be updated by the session manager if there is any. */
2546 gst_query_set_latency (query, TRUE, 0, -1);
2556 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2558 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2562 gboolean res = FALSE;
2564 src = GST_RTSPSRC_CAST (parent);
2566 GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2567 GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2569 switch (GST_QUERY_TYPE (query)) {
2570 case GST_QUERY_DURATION:
2574 gst_query_parse_duration (query, &format, NULL);
2577 case GST_FORMAT_TIME:
2578 gst_query_set_duration (query, format, src->segment.duration);
2586 case GST_QUERY_SEEKING:
2590 gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2591 if (format == GST_FORMAT_TIME) {
2593 src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2595 /* seeking without duration is unlikely */
2596 seekable = seekable && src->seekable && src->segment.duration &&
2597 GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2599 /* FIXME ?? should we have 0 and segment.duration here; see demuxers */
2600 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
2601 src->segment.start, src->segment.stop);
2610 uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2612 gst_query_set_uri (query, uri);
2620 GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2622 /* forward the query to the proxy target pad */
2624 res = gst_pad_query (target, query);
2625 gst_object_unref (target);
2634 /* callback for RTCP messages to be sent to the server when operating in TCP
2636 static GstFlowReturn
2637 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2640 GstRTSPStream *stream;
2641 GstFlowReturn res = GST_FLOW_OK;
2646 GstRTSPMessage message = { 0 };
2647 GstRTSPConnection *conn;
2649 stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2650 src = stream->parent;
2652 gst_buffer_map (buffer, &map, GST_MAP_READ);
2656 gst_rtsp_message_init_data (&message, stream->channel[1]);
2658 /* lend the body data to the message */
2659 gst_rtsp_message_take_body (&message, data, size);
2661 if (stream->conninfo.connection)
2662 conn = stream->conninfo.connection;
2664 conn = src->conninfo.connection;
2666 GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2667 ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2668 GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2670 /* and steal it away again because we will free it when unreffing the
2672 gst_rtsp_message_steal_body (&message, &data, &size);
2673 gst_rtsp_message_unset (&message);
2675 gst_buffer_unmap (buffer, &map);
2676 gst_buffer_unref (buffer);
2681 static GstPadProbeReturn
2682 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2684 GstRTSPSrc *src = user_data;
2686 GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2687 GST_DEBUG_PAD_NAME (pad));
2689 /* activate the streams */
2690 GST_OBJECT_LOCK (src);
2691 if (!src->need_activate)
2694 src->need_activate = FALSE;
2695 GST_OBJECT_UNLOCK (src);
2697 gst_rtspsrc_activate_streams (src);
2699 return GST_PAD_PROBE_OK;
2703 GST_OBJECT_UNLOCK (src);
2704 return GST_PAD_PROBE_OK;
2709 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
2711 GstPad *gpad = GST_PAD_CAST (user_data);
2713 GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
2714 gst_pad_store_sticky_event (gpad, *event);
2719 /* this callback is called when the session manager generated a new src pad with
2720 * payloaded RTP packets. We simply ghost the pad here. */
2722 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2725 GstPadTemplate *template;
2728 GstRTSPStream *stream;
2731 GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2733 GST_RTSP_STATE_LOCK (src);
2735 name = gst_object_get_name (GST_OBJECT_CAST (pad));
2736 if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2737 goto unknown_stream;
2739 GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2741 stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2743 goto unknown_stream;
2746 stream->ssrc = ssrc;
2748 /* we'll add it later see below */
2749 stream->added = TRUE;
2751 /* check if we added all streams */
2753 for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
2754 GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
2756 GST_DEBUG_OBJECT (src, "stream %p, container %d, added %d, setup %d",
2757 ostream, ostream->container, ostream->added, ostream->setup);
2759 /* if we find a stream for which we did a setup that is not added, we
2760 * need to wait some more */
2761 if (ostream->setup && !ostream->added) {
2766 GST_RTSP_STATE_UNLOCK (src);
2768 /* create a new pad we will use to stream to */
2769 template = gst_static_pad_template_get (&rtptemplate);
2770 stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2771 gst_object_unref (template);
2774 gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2775 gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2776 gst_pad_set_active (stream->srcpad, TRUE);
2777 gst_pad_sticky_events_foreach (pad, copy_sticky_events, stream->srcpad);
2778 gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2781 GST_DEBUG_OBJECT (src, "We added all streams");
2782 /* when we get here, all stream are added and we can fire the no-more-pads
2784 gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2792 GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2793 GST_RTSP_STATE_UNLOCK (src);
2800 stream_get_caps_for_pt (GstRTSPStream * stream, guint pt)
2804 len = stream->ptmap->len;
2805 for (i = 0; i < len; i++) {
2806 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
2814 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2816 GstRTSPStream *stream;
2819 GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2821 GST_RTSP_STATE_LOCK (src);
2822 stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2824 goto unknown_stream;
2826 if ((caps = stream_get_caps_for_pt (stream, pt)))
2827 gst_caps_ref (caps);
2828 GST_RTSP_STATE_UNLOCK (src);
2834 GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2835 GST_RTSP_STATE_UNLOCK (src);
2841 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2843 GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2849 gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
2855 GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2861 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2863 GstRTSPSrc *src = stream->parent;
2866 g_object_get (source, "ssrc", &ssrc, NULL);
2868 GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
2869 ssrc, stream->ssrc, stream->id);
2871 if (ssrc == stream->ssrc)
2872 gst_rtspsrc_do_stream_eos (src, stream);
2876 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2878 GstRTSPSrc *src = stream->parent;
2881 g_object_get (source, "ssrc", &ssrc, NULL);
2883 GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
2884 ssrc, stream->ssrc, stream->id);
2886 if (ssrc == stream->ssrc)
2887 gst_rtspsrc_do_stream_eos (src, stream);
2891 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2893 GstRTSPStream *stream;
2895 GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2897 /* get stream for session */
2898 stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2900 gst_rtspsrc_do_stream_eos (src, stream);
2905 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2907 GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2912 set_manager_buffer_mode (GstRTSPSrc * src)
2914 GObjectClass *klass;
2916 if (src->manager == NULL)
2919 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2921 if (!g_object_class_find_property (klass, "buffer-mode"))
2924 if (src->buffer_mode != BUFFER_MODE_AUTO) {
2925 g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2930 GST_DEBUG_OBJECT (src,
2931 "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
2933 if (src->provided_clock) {
2934 GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
2936 if (clock == src->provided_clock) {
2937 GST_DEBUG_OBJECT (src, "selected synced");
2938 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
2941 gst_object_unref (clock);
2946 /* Otherwise fall-through and use another buffer mode */
2948 gst_object_unref (clock);
2951 GST_DEBUG_OBJECT (src, "auto buffering mode");
2952 if (src->use_buffering) {
2953 GST_DEBUG_OBJECT (src, "selected buffer");
2954 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
2956 GST_DEBUG_OBJECT (src, "selected slave");
2957 g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2962 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
2964 GST_DEBUG ("request key %u", ssrc);
2965 return gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
2969 request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
2971 GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
2972 if (stream->id != session)
2975 if (stream->profile != GST_RTSP_PROFILE_SAVP &&
2976 stream->profile != GST_RTSP_PROFILE_SAVPF)
2979 if (stream->srtpdec == NULL) {
2982 name = g_strdup_printf ("srtpdec_%u", session);
2983 stream->srtpdec = gst_element_factory_make ("srtpdec", name);
2986 g_signal_connect (stream->srtpdec, "request-key",
2987 (GCallback) request_key, stream);
2989 return gst_object_ref (stream->srtpdec);
2993 request_rtcp_encoder (GstElement * rtpbin, guint session,
2994 GstRTSPStream * stream)
2999 GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3000 if (stream->id != session)
3003 if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3004 stream->profile != GST_RTSP_PROFILE_SAVPF)
3007 if (stream->srtpenc == NULL) {
3008 name = g_strdup_printf ("srtpenc_%u", session);
3009 stream->srtpenc = gst_element_factory_make ("srtpenc", name);
3012 /* key has been made before */
3013 g_object_set (stream->srtpenc, "key", stream->key, NULL);
3015 name = g_strdup_printf ("rtcp_sink_%d", session);
3016 pad = gst_element_get_request_pad (stream->srtpenc, name);
3018 gst_object_unref (pad);
3020 return gst_object_ref (stream->srtpenc);
3024 /* try to get and configure a manager */
3026 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
3027 GstRTSPTransport * transport)
3029 const gchar *manager;
3031 GstStateChangeReturn ret;
3033 /* find a manager */
3034 if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
3038 GST_DEBUG_OBJECT (src, "using manager %s", manager);
3040 /* configure the manager */
3041 if (src->manager == NULL) {
3042 GObjectClass *klass;
3044 if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
3046 if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
3050 goto use_no_manager;
3052 if (!(src->manager = gst_element_factory_make (manager, "manager")))
3053 goto manager_failed;
3056 /* we manage this element */
3057 gst_element_set_locked_state (src->manager, TRUE);
3058 gst_bin_add (GST_BIN_CAST (src), src->manager);
3060 ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
3061 if (ret == GST_STATE_CHANGE_FAILURE)
3062 goto start_manager_failure;
3064 g_object_set (src->manager, "latency", src->latency, NULL);
3066 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3068 if (g_object_class_find_property (klass, "ntp-sync")) {
3069 g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
3072 if (g_object_class_find_property (klass, "use-pipeline-clock")) {
3073 g_object_set (src->manager, "use-pipeline-clock",
3074 src->use_pipeline_clock, NULL);
3077 if (src->sdes && g_object_class_find_property (klass, "sdes")) {
3078 g_object_set (src->manager, "sdes", src->sdes, NULL);
3081 if (g_object_class_find_property (klass, "drop-on-latency")) {
3082 g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
3086 /* buffer mode pauses are handled by adding offsets to buffer times,
3087 * but some depayloaders may have a hard time syncing output times
3088 * with such input times, e.g. container ones, most notably ASF */
3089 /* TODO alternatives are having an event that indicates these shifts,
3090 * or having rtsp extensions provide suggestion on buffer mode */
3091 /* valid duration implies not likely live pipeline,
3092 * so slaving in jitterbuffer does not make much sense
3093 * (and might mess things up due to bursts) */
3094 if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
3095 src->segment.duration && !stream->container) {
3096 src->use_buffering = TRUE;
3098 src->use_buffering = FALSE;
3101 set_manager_buffer_mode (src);
3103 /* connect to signals */
3104 GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
3106 src->manager_sig_id =
3107 g_signal_connect (src->manager, "pad-added",
3108 (GCallback) new_manager_pad, src);
3109 src->manager_ptmap_id =
3110 g_signal_connect (src->manager, "request-pt-map",
3111 (GCallback) request_pt_map, src);
3113 g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
3116 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
3119 g_signal_connect (src->manager, "request-rtp-decoder",
3120 (GCallback) request_rtp_decoder, stream);
3121 g_signal_connect (src->manager, "request-rtcp-decoder",
3122 (GCallback) request_rtp_decoder, stream);
3123 g_signal_connect (src->manager, "request-rtcp-encoder",
3124 (GCallback) request_rtcp_encoder, stream);
3126 /* we stream directly to the manager, get some pads. Each RTSP stream goes
3127 * into a separate RTP session. */
3128 name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
3129 stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
3131 name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
3132 stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
3135 /* now configure the bandwidth in the manager */
3136 if (g_signal_lookup ("get-internal-session",
3137 G_OBJECT_TYPE (src->manager)) != 0) {
3138 GObject *rtpsession;
3140 g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
3143 GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
3145 stream->session = rtpsession;
3147 if (stream->as_bandwidth != -1) {
3148 GST_INFO_OBJECT (src, "setting AS: %f",
3149 (gdouble) (stream->as_bandwidth * 1000));
3150 g_object_set (rtpsession, "bandwidth",
3151 (gdouble) (stream->as_bandwidth * 1000), NULL);
3153 if (stream->rr_bandwidth != -1) {
3154 GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
3155 g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
3158 if (stream->rs_bandwidth != -1) {
3159 GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
3160 g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
3164 g_object_set (rtpsession, "probation", src->probation, NULL);
3166 g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
3168 g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
3170 g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
3172 g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
3174 g_signal_connect (rtpsession, "on-ssrc-active",
3175 (GCallback) on_ssrc_active, stream);
3186 GST_DEBUG_OBJECT (src, "cannot get a session manager");
3191 GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
3194 start_manager_failure:
3196 GST_DEBUG_OBJECT (src, "could not start session manager");
3201 /* free the UDP sources allocated when negotiating a transport.
3202 * This function is called when the server negotiated to a transport where the
3203 * UDP sources are not needed anymore, such as TCP or multicast. */
3205 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
3209 for (i = 0; i < 2; i++) {
3210 if (stream->udpsrc[i]) {
3211 GST_DEBUG ("free UDP source %d for stream %p", i, stream);
3212 gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
3213 gst_object_unref (stream->udpsrc[i]);
3214 stream->udpsrc[i] = NULL;
3219 /* for TCP, create pads to send and receive data to and from the manager and to
3220 * intercept various events and queries
3223 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
3224 GstRTSPTransport * transport, GstPad ** outpad)
3227 GstPadTemplate *template;
3228 GstPad *pad0, *pad1;
3230 /* configure for interleaved delivery, nothing needs to be done
3231 * here, the loop function will call the chain functions of the
3232 * session manager. */
3233 stream->channel[0] = transport->interleaved.min;
3234 stream->channel[1] = transport->interleaved.max;
3235 GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
3236 stream->channel[0], stream->channel[1]);
3238 /* we can remove the allocated UDP ports now */
3239 gst_rtspsrc_stream_free_udp (stream);
3241 /* no session manager, send data to srcpad directly */
3242 if (!stream->channelpad[0]) {
3243 GST_DEBUG_OBJECT (src, "no manager, creating pad");
3245 /* create a new pad we will use to stream to */
3246 name = g_strdup_printf ("stream_%u", stream->id);
3247 template = gst_static_pad_template_get (&rtptemplate);
3248 stream->channelpad[0] = gst_pad_new_from_template (template, name);
3249 gst_object_unref (template);
3252 /* set caps and activate */
3253 gst_pad_use_fixed_caps (stream->channelpad[0]);
3254 gst_pad_set_active (stream->channelpad[0], TRUE);
3256 *outpad = gst_object_ref (stream->channelpad[0]);
3258 GST_DEBUG_OBJECT (src, "using manager source pad");
3260 template = gst_static_pad_template_get (&anysrctemplate);
3262 /* allocate pads for sending the channel data into the manager */
3263 pad0 = gst_pad_new_from_template (template, "internalsrc_0");
3264 gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
3265 gst_object_unref (stream->channelpad[0]);
3266 stream->channelpad[0] = pad0;
3267 gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
3268 gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
3269 gst_pad_set_element_private (pad0, src);
3270 gst_pad_set_active (pad0, TRUE);
3272 if (stream->channelpad[1]) {
3273 /* if we have a sinkpad for the other channel, create a pad and link to the
3275 pad1 = gst_pad_new_from_template (template, "internalsrc_1");
3276 gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
3277 gst_pad_link_full (pad1, stream->channelpad[1],
3278 GST_PAD_LINK_CHECK_NOTHING);
3279 gst_object_unref (stream->channelpad[1]);
3280 stream->channelpad[1] = pad1;
3281 gst_pad_set_active (pad1, TRUE);
3283 gst_object_unref (template);
3285 /* setup RTCP transport back to the server if we have to. */
3286 if (src->manager && src->do_rtcp) {
3289 template = gst_static_pad_template_get (&anysinktemplate);
3291 stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
3292 gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
3293 gst_pad_set_element_private (stream->rtcppad, stream);
3294 gst_pad_set_active (stream->rtcppad, TRUE);
3296 /* get session RTCP pad */
3297 name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3298 pad = gst_element_get_request_pad (src->manager, name);
3303 gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3304 gst_object_unref (pad);
3307 gst_object_unref (template);
3313 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3314 GstRTSPTransport * transport, const gchar ** destination, gint * min,
3315 gint * max, guint * ttl)
3317 if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3319 if (!(*destination = transport->destination))
3320 *destination = stream->destination;
3323 /* transport first */
3324 *min = transport->port.min;
3325 *max = transport->port.max;
3326 if (*min == -1 && *max == -1) {
3327 /* then try from SDP */
3328 if (stream->port != 0) {
3329 *min = stream->port;
3330 *max = stream->port + 1;
3336 if (!(*ttl = transport->ttl))
3341 /* first take the source, then the endpoint to figure out where to send
3343 if (!(*destination = transport->source)) {
3344 if (src->conninfo.connection)
3345 *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3346 else if (stream->conninfo.connection)
3348 gst_rtsp_connection_get_ip (stream->conninfo.connection);
3352 /* for unicast we only expect the ports here */
3353 *min = transport->server_port.min;
3354 *max = transport->server_port.max;
3359 /* For multicast create UDP sources and join the multicast group. */
3361 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3362 GstRTSPTransport * transport, GstPad ** outpad)
3365 const gchar *destination;
3368 GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3370 /* we can remove the allocated UDP ports now */
3371 gst_rtspsrc_stream_free_udp (stream);
3373 gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3376 /* we need a destination now */
3377 if (destination == NULL)
3378 goto no_destination;
3380 /* we really need ports now or we won't be able to receive anything at all */
3381 if (min == -1 && max == -1)
3384 GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3385 destination, min, max);
3387 /* creating UDP source for RTP */
3389 uri = g_strdup_printf ("udp://%s:%d", destination, min);
3391 gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3393 if (stream->udpsrc[0] == NULL)
3396 /* take ownership */
3397 gst_object_ref_sink (stream->udpsrc[0]);
3399 if (src->udp_buffer_size != 0)
3400 g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3401 src->udp_buffer_size, NULL);
3403 if (src->multi_iface != NULL)
3404 g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3405 src->multi_iface, NULL);
3408 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3409 gst_element_set_state (stream->udpsrc[0], GST_STATE_READY);
3412 /* creating another UDP source for RTCP */
3416 uri = g_strdup_printf ("udp://%s:%d", destination, max);
3418 gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3420 if (stream->udpsrc[1] == NULL)
3423 if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3424 stream->profile == GST_RTSP_PROFILE_SAVPF)
3425 caps = gst_caps_new_empty_simple ("application/x-srtcp");
3427 caps = gst_caps_new_empty_simple ("application/x-rtcp");
3428 g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3429 gst_caps_unref (caps);
3431 /* take ownership */
3432 gst_object_ref_sink (stream->udpsrc[1]);
3434 if (src->multi_iface != NULL)
3435 g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3436 src->multi_iface, NULL);
3438 gst_element_set_state (stream->udpsrc[1], GST_STATE_READY);
3445 GST_DEBUG_OBJECT (src, "no UDP source element found");
3450 GST_DEBUG_OBJECT (src, "no destination found");
3455 GST_DEBUG_OBJECT (src, "no ports found");
3460 /* configure the remainder of the UDP ports */
3462 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3463 GstRTSPTransport * transport, GstPad ** outpad)
3465 /* we manage the UDP elements now. For unicast, the UDP sources where
3466 * allocated in the stream when we suggested a transport. */
3467 if (stream->udpsrc[0]) {
3470 gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3471 gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3473 GST_DEBUG_OBJECT (src, "setting up UDP source");
3475 /* configure a timeout on the UDP port. When the timeout message is
3476 * posted, we assume UDP transport is not possible. We reconnect using TCP
3478 g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3479 src->udp_timeout * 1000, NULL);
3481 if ((caps = stream_get_caps_for_pt (stream, stream->default_pt)))
3482 g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3484 /* get output pad of the UDP source. */
3485 *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3487 /* save it so we can unblock */
3488 stream->blockedpad = *outpad;
3490 /* configure pad block on the pad. As soon as there is dataflow on the
3491 * UDP source, we know that UDP is not blocked by a firewall and we can
3492 * configure all the streams to let the application autoplug decoders. */
3494 gst_pad_add_probe (stream->blockedpad,
3495 GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
3496 GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
3498 if (stream->channelpad[0]) {
3499 GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3500 /* configure for UDP delivery, we need to connect the UDP pads to
3501 * the session plugin. */
3502 gst_pad_link_full (*outpad, stream->channelpad[0],
3503 GST_PAD_LINK_CHECK_NOTHING);
3504 gst_object_unref (*outpad);
3506 /* we connected to pad-added signal to get pads from the manager */
3508 GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3513 if (stream->udpsrc[1]) {
3516 gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3517 gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3519 if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3520 stream->profile == GST_RTSP_PROFILE_SAVPF)
3521 caps = gst_caps_new_empty_simple ("application/x-srtcp");
3523 caps = gst_caps_new_empty_simple ("application/x-rtcp");
3524 g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3525 gst_caps_unref (caps);
3527 if (stream->channelpad[1]) {
3530 GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3532 pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3533 gst_pad_link_full (pad, stream->channelpad[1],
3534 GST_PAD_LINK_CHECK_NOTHING);
3535 gst_object_unref (pad);
3537 /* leave unlinked */
3543 /* configure the UDP sink back to the server for status reports */
3545 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3546 GstRTSPStream * stream, GstRTSPTransport * transport)
3549 gint rtp_port, rtcp_port;
3550 gboolean do_rtp, do_rtcp;
3551 const gchar *destination;
3556 /* get transport info */
3557 gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3558 &rtp_port, &rtcp_port, &ttl);
3560 /* see what we need to do */
3561 do_rtp = (rtp_port != -1);
3562 /* it's possible that the server does not want us to send RTCP in which case
3564 do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3566 /* we need a destination when we have RTP or RTCP ports */
3567 if (destination == NULL && (do_rtp || do_rtcp))
3568 goto no_destination;
3570 /* try to construct the fakesrc to the RTP port of the server to open up any
3573 GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3576 uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3577 stream->udpsink[0] =
3578 gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3580 if (stream->udpsink[0] == NULL)
3581 goto no_sink_element;
3583 /* don't join multicast group, we will have the source socket do that */
3584 /* no sync or async state changes needed */
3585 g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3586 "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3588 g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3590 if (stream->udpsrc[0]) {
3591 /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3592 * so that NAT firewalls will open a hole for us */
3593 g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3594 GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3595 /* configure socket and make sure udpsink does not close it when shutting
3596 * down, it belongs to udpsrc after all. */
3597 g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3598 "close-socket", FALSE, NULL);
3599 g_object_unref (socket);
3602 /* the source for the dummy packets to open up NAT */
3603 stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3604 if (stream->fakesrc == NULL)
3605 goto no_fakesrc_element;
3607 /* random data in 5 buffers, a size of 200 bytes should be fine */
3608 g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3609 "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3611 /* we don't want to consider this a sink */
3612 GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
3614 /* keep everything locked */
3615 gst_element_set_locked_state (stream->udpsink[0], TRUE);
3616 gst_element_set_locked_state (stream->fakesrc, TRUE);
3618 gst_object_ref (stream->udpsink[0]);
3619 gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3620 gst_object_ref (stream->fakesrc);
3621 gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3623 gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
3624 "sink", GST_PAD_LINK_CHECK_NOTHING);
3627 GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3630 uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3631 stream->udpsink[1] =
3632 gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3634 if (stream->udpsink[1] == NULL)
3635 goto no_sink_element;
3637 /* don't join multicast group, we will have the source socket do that */
3638 /* no sync or async state changes needed */
3639 g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3640 "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3642 g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3644 if (stream->udpsrc[1]) {
3645 /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3646 * because some servers check the port number of where it sends RTCP to identify
3647 * the RTCP packets it receives */
3648 g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3649 GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3650 /* configure socket and make sure udpsink does not close it when shutting
3651 * down, it belongs to udpsrc after all. */
3652 g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3653 "close-socket", FALSE, NULL);
3654 g_object_unref (socket);
3657 /* we don't want to consider this a sink */
3658 GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
3660 /* we keep this playing always */
3661 gst_element_set_locked_state (stream->udpsink[1], TRUE);
3662 gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3664 gst_object_ref (stream->udpsink[1]);
3665 gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3667 stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3669 /* get session RTCP pad */
3670 name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3671 pad = gst_element_get_request_pad (src->manager, name);
3676 gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3677 gst_object_unref (pad);
3686 GST_DEBUG_OBJECT (src, "no destination address specified");
3691 GST_DEBUG_OBJECT (src, "no UDP sink element found");
3696 GST_DEBUG_OBJECT (src, "no fakesrc element found");
3701 /* sets up all elements needed for streaming over the specified transport.
3702 * Does not yet expose the element pads, this will be done when there is actuall
3703 * dataflow detected, which might never happen when UDP is blocked in a
3704 * firewall, for example.
3707 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3708 GstRTSPTransport * transport)
3711 GstPad *outpad = NULL;
3712 GstPadTemplate *template;
3714 const gchar *media_type;
3717 src = stream->parent;
3719 GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3721 /* get the proper media type for this stream now */
3722 if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
3723 goto unknown_transport;
3725 goto unknown_transport;
3727 /* configure the final media type */
3728 GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
3730 len = stream->ptmap->len;
3731 for (i = 0; i < len; i++) {
3733 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3735 if (item->caps == NULL)
3738 s = gst_caps_get_structure (item->caps, 0);
3739 gst_structure_set_name (s, media_type);
3740 /* set ssrc if known */
3741 if (transport->ssrc)
3742 gst_structure_set (s, "ssrc", G_TYPE_UINT, transport->ssrc, NULL);
3745 /* try to get and configure a manager, channelpad[0-1] will be configured with
3746 * the pads for the manager, or NULL when no manager is needed. */
3747 if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3750 switch (transport->lower_transport) {
3751 case GST_RTSP_LOWER_TRANS_TCP:
3752 if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3753 goto transport_failed;
3755 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3756 if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3757 goto transport_failed;
3758 /* fallthrough, the rest is the same for UDP and MCAST */
3759 case GST_RTSP_LOWER_TRANS_UDP:
3760 if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3761 goto transport_failed;
3762 /* configure udpsinks back to the server for RTCP messages and for the
3763 * dummy RTP messages to open NAT. */
3764 if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3765 goto transport_failed;
3768 goto unknown_transport;
3772 GST_DEBUG_OBJECT (src, "creating ghostpad");
3774 gst_pad_use_fixed_caps (outpad);
3776 /* create ghostpad, don't add just yet, this will be done when we activate
3778 name = g_strdup_printf ("stream_%u", stream->id);
3779 template = gst_static_pad_template_get (&rtptemplate);
3780 stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3781 gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3782 gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3783 gst_object_unref (template);
3786 gst_object_unref (outpad);
3788 /* mark pad as ok */
3789 stream->last_ret = GST_FLOW_OK;
3796 GST_DEBUG_OBJECT (src, "failed to configure transport");
3801 GST_DEBUG_OBJECT (src, "unknown transport");
3806 GST_DEBUG_OBJECT (src, "cannot get a session manager");
3811 /* send a couple of dummy random packets on the receiver RTP port to the server,
3812 * this should make a firewall think we initiated the data transfer and
3813 * hopefully allow packets to go from the sender port to our RTP receiver port */
3815 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3819 if (src->nat_method != GST_RTSP_NAT_DUMMY)
3822 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3823 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3825 if (stream->fakesrc && stream->udpsink[0]) {
3826 GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3827 gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3828 gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3829 gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3830 gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3836 /* Adds the source pads of all configured streams to the element.
3837 * This code is performed when we detected dataflow.
3839 * We detect dataflow from either the _loop function or with pad probes on the
3843 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3847 GST_DEBUG_OBJECT (src, "activating streams");
3849 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3850 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3852 if (stream->udpsrc[0]) {
3853 /* remove timeout, we are streaming now and timeouts will be handled by
3854 * the session manager and jitter buffer */
3855 g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3857 if (stream->srcpad) {
3858 GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3859 gst_pad_set_active (stream->srcpad, TRUE);
3861 /* if we don't have a session manager, set the caps now. If we have a
3862 * session, we will get a notification of the pad and the caps. */
3863 if (!src->manager) {
3866 caps = stream_get_caps_for_pt (stream, stream->default_pt);
3867 GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3868 gst_pad_set_caps (stream->srcpad, caps);
3871 if (!stream->added) {
3872 GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3873 gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3874 stream->added = TRUE;
3879 /* unblock all pads */
3880 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3881 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3883 if (stream->blockid) {
3884 GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3885 gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3886 stream->blockid = 0;
3894 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3895 gboolean reset_manager)
3898 guint64 start, stop;
3899 gdouble play_speed, play_scale;
3901 GST_DEBUG_OBJECT (src, "configuring stream caps");
3903 start = segment->position;
3904 stop = segment->duration;
3905 play_speed = segment->rate;
3906 play_scale = segment->applied_rate;
3908 for (walk = src->streams; walk; walk = g_list_next (walk)) {
3909 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3915 len = stream->ptmap->len;
3916 for (j = 0; j < len; j++) {
3918 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, j);
3920 if (item->caps == NULL)
3923 caps = gst_caps_make_writable (item->caps);
3925 if (stream->timebase != -1)
3926 gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3927 (guint) stream->timebase, NULL);
3928 if (stream->seqbase != -1)
3929 gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3930 (guint) stream->seqbase, NULL);
3931 gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3933 gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3934 gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3935 gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3938 GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
3941 if (item->pt == stream->default_pt && stream->udpsrc[0]) {
3942 g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3946 if (reset_manager && src->manager) {
3947 GST_DEBUG_OBJECT (src, "clear session");
3948 g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3952 static GstFlowReturn
3953 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3958 /* store the value */
3959 stream->last_ret = ret;
3961 /* if it's success we can return the value right away */
3962 if (ret == GST_FLOW_OK)
3965 /* any other error that is not-linked can be returned right
3967 if (ret != GST_FLOW_NOT_LINKED)
3970 /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3971 for (streams = src->streams; streams; streams = g_list_next (streams)) {
3972 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3974 ret = ostream->last_ret;
3975 /* some other return value (must be SUCCESS but we can return
3976 * other values as well) */
3977 if (ret != GST_FLOW_NOT_LINKED)
3980 /* if we get here, all other pads were unlinked and we return
3981 * NOT_LINKED then */
3987 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
3990 gboolean res = TRUE;
3992 /* only streams that have a connection to the outside world */
3996 if (stream->udpsrc[0]) {
3997 gst_event_ref (event);
3998 res = gst_element_send_event (stream->udpsrc[0], event);
3999 } else if (stream->channelpad[0]) {
4000 gst_event_ref (event);
4001 if (GST_PAD_IS_SRC (stream->channelpad[0]))
4002 res = gst_pad_push_event (stream->channelpad[0], event);
4004 res = gst_pad_send_event (stream->channelpad[0], event);
4007 if (stream->udpsrc[1]) {
4008 gst_event_ref (event);
4009 res &= gst_element_send_event (stream->udpsrc[1], event);
4010 } else if (stream->channelpad[1]) {
4011 gst_event_ref (event);
4012 if (GST_PAD_IS_SRC (stream->channelpad[1]))
4013 res &= gst_pad_push_event (stream->channelpad[1], event);
4015 res &= gst_pad_send_event (stream->channelpad[1], event);
4019 gst_event_unref (event);
4025 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
4028 gboolean res = TRUE;
4030 for (streams = src->streams; streams; streams = g_list_next (streams)) {
4031 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4033 gst_event_ref (event);
4034 res &= gst_rtspsrc_stream_push_event (src, ostream, event);
4036 gst_event_unref (event);
4041 static GstRTSPResult
4042 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4047 if (info->connection == NULL) {
4048 if (info->url == NULL) {
4049 GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
4050 if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
4054 /* create connection */
4055 GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
4056 if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
4057 goto could_not_create;
4060 g_free (info->url_str);
4061 info->url_str = gst_rtsp_url_get_request_uri (info->url);
4063 GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
4065 if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
4066 if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
4067 src->tls_validation_flags))
4068 GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
4070 if (src->tls_database)
4071 gst_rtsp_connection_set_tls_database (info->connection,
4075 if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
4076 gst_rtsp_connection_set_tunneled (info->connection, TRUE);
4078 if (src->proxy_host) {
4079 GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
4081 gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
4086 if (!info->connected) {
4089 GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
4090 ("Connecting to %s", info->location));
4091 GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
4093 gst_rtsp_connection_connect (info->connection,
4094 src->ptcp_timeout)) < 0)
4095 goto could_not_connect;
4097 info->connected = TRUE;
4104 GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
4109 gchar *str = gst_rtsp_strresult (res);
4110 GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
4116 gchar *str = gst_rtsp_strresult (res);
4117 GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
4123 static GstRTSPResult
4124 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
4127 GST_RTSP_STATE_LOCK (src);
4128 if (info->connected) {
4129 GST_DEBUG_OBJECT (src, "closing connection...");
4130 gst_rtsp_connection_close (info->connection);
4131 info->connected = FALSE;
4133 if (free && info->connection) {
4134 /* free connection */
4135 GST_DEBUG_OBJECT (src, "freeing connection...");
4136 gst_rtsp_connection_free (info->connection);
4137 info->connection = NULL;
4139 GST_RTSP_STATE_UNLOCK (src);
4143 static GstRTSPResult
4144 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4149 GST_DEBUG_OBJECT (src, "reconnecting connection...");
4150 gst_rtsp_conninfo_close (src, info, FALSE);
4151 res = gst_rtsp_conninfo_connect (src, info, async);
4157 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
4161 GST_DEBUG_OBJECT (src, "set flushing %d", flush);
4162 GST_RTSP_STATE_LOCK (src);
4163 if (src->conninfo.connection && src->conninfo.flushing != flush) {
4164 GST_DEBUG_OBJECT (src, "connection flush");
4165 gst_rtsp_connection_flush (src->conninfo.connection, flush);
4166 src->conninfo.flushing = flush;
4168 for (walk = src->streams; walk; walk = g_list_next (walk)) {
4169 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4170 if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
4171 GST_DEBUG_OBJECT (src, "stream %p flush", stream);
4172 gst_rtsp_connection_flush (stream->conninfo.connection, flush);
4173 stream->conninfo.flushing = flush;
4176 GST_RTSP_STATE_UNLOCK (src);
4179 /* FIXME, handle server request, reply with OK, for now */
4180 static GstRTSPResult
4181 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
4182 GstRTSPMessage * request)
4184 GstRTSPMessage response = { 0 };
4187 GST_DEBUG_OBJECT (src, "got server request message");
4190 gst_rtsp_message_dump (request);
4192 res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4194 if (res == GST_RTSP_ENOTIMPL) {
4195 /* default implementation, send OK */
4196 GST_DEBUG_OBJECT (src, "prepare OK reply");
4198 gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4203 /* let app parse and reply */
4204 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4205 0, request, &response);
4208 gst_rtsp_message_dump (&response);
4210 res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
4214 gst_rtsp_message_unset (&response);
4215 } else if (res == GST_RTSP_EEOF)
4223 gst_rtsp_message_unset (&response);
4228 /* send server keep-alive */
4229 static GstRTSPResult
4230 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4232 GstRTSPMessage request = { 0 };
4234 GstRTSPMethod method;
4235 const gchar *control;
4237 if (src->do_rtsp_keep_alive == FALSE) {
4238 GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4239 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4243 GST_DEBUG_OBJECT (src, "creating server keep-alive");
4245 /* find a method to use for keep-alive */
4246 if (src->methods & GST_RTSP_GET_PARAMETER)
4247 method = GST_RTSP_GET_PARAMETER;
4249 method = GST_RTSP_OPTIONS;
4251 control = get_aggregate_control (src);
4252 if (control == NULL)
4255 res = gst_rtsp_message_init_request (&request, method, control);
4260 gst_rtsp_message_dump (&request);
4263 gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
4268 gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4269 gst_rtsp_message_unset (&request);
4276 GST_WARNING_OBJECT (src, "no control url to send keepalive");
4281 gchar *str = gst_rtsp_strresult (res);
4283 gst_rtsp_message_unset (&request);
4284 GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4285 ("Could not send keep-alive. (%s)", str));
4291 static GstFlowReturn
4292 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4294 GstFlowReturn ret = GST_FLOW_OK;
4296 GstRTSPStream *stream;
4297 GstPad *outpad = NULL;
4304 channel = message->type_data.data.channel;
4306 stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4308 goto unknown_stream;
4310 if (channel == stream->channel[0]) {
4311 outpad = stream->channelpad[0];
4313 } else if (channel == stream->channel[1]) {
4314 outpad = stream->channelpad[1];
4320 /* take a look at the body to figure out what we have */
4321 gst_rtsp_message_get_body (message, &data, &size);
4323 goto invalid_length;
4325 /* channels are not correct on some servers, do extra check */
4326 if (data[1] >= 200 && data[1] <= 204) {
4327 /* hmm RTCP message switch to the RTCP pad of the same stream. */
4328 outpad = stream->channelpad[1];
4332 /* we have no clue what this is, just ignore then. */
4334 goto unknown_stream;
4336 /* take the message body for further processing */
4337 gst_rtsp_message_steal_body (message, &data, &size);
4339 /* strip the trailing \0 */
4342 buf = gst_buffer_new ();
4343 gst_buffer_append_memory (buf,
4344 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4346 /* don't need message anymore */
4347 gst_rtsp_message_unset (message);
4349 GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4352 if (src->need_activate) {
4358 guint group_id = gst_util_group_id_next ();
4360 /* generate an SHA256 sum of the URI */
4361 cs = g_checksum_new (G_CHECKSUM_SHA256);
4362 uri = src->conninfo.location;
4363 g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4365 for (streams = src->streams; streams; streams = g_list_next (streams)) {
4366 GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4369 g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4370 event = gst_event_new_stream_start (stream_id);
4371 gst_event_set_group_id (event, group_id);
4374 gst_rtspsrc_stream_push_event (src, ostream, event);
4376 g_checksum_free (cs);
4378 gst_rtspsrc_activate_streams (src);
4379 src->need_activate = FALSE;
4381 if ((event = src->start_segment) != NULL) {
4382 src->start_segment = NULL;
4383 gst_rtspsrc_push_event (src, event);
4386 if (src->base_time == -1) {
4387 /* Take current running_time. This timestamp will be put on
4388 * the first buffer of each stream because we are a live source and so we
4389 * timestamp with the running_time. When we are dealing with TCP, we also
4390 * only timestamp the first buffer (using the DISCONT flag) because a server
4391 * typically bursts data, for which we don't want to compensate by speeding
4392 * up the media. The other timestamps will be interpollated from this one
4393 * using the RTP timestamps. */
4394 GST_OBJECT_LOCK (src);
4395 if (GST_ELEMENT_CLOCK (src)) {
4397 GstClockTime base_time;
4399 now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4400 base_time = GST_ELEMENT_CAST (src)->base_time;
4402 src->base_time = now - base_time;
4404 GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4405 GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4407 GST_OBJECT_UNLOCK (src);
4410 if (stream->discont && !is_rtcp) {
4411 /* mark first RTP buffer as discont */
4412 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4413 stream->discont = FALSE;
4414 /* first buffer gets the timestamp, other buffers are not timestamped and
4415 * their presentation time will be interpollated from the rtp timestamps. */
4416 GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4417 GST_TIME_ARGS (src->base_time));
4419 GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4422 /* chain to the peer pad */
4423 if (GST_PAD_IS_SINK (outpad))
4424 ret = gst_pad_chain (outpad, buf);
4426 ret = gst_pad_push (outpad, buf);
4429 /* combine all stream flows for the data transport */
4430 ret = gst_rtspsrc_combine_flows (src, stream, ret);
4437 GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4438 gst_rtsp_message_unset (message);
4443 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4444 ("Short message received, ignoring."));
4445 gst_rtsp_message_unset (message);
4450 static GstFlowReturn
4451 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4453 GstRTSPMessage message = { 0 };
4455 GstFlowReturn ret = GST_FLOW_OK;
4456 GTimeVal tv_timeout;
4459 /* get the next timeout interval */
4460 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4462 /* see if the timeout period expired */
4463 if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4464 GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4465 /* send keep-alive, only act on interrupt, a warning will be posted for
4467 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4469 /* get new timeout */
4470 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4473 GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4474 tv_timeout.tv_sec, tv_timeout.tv_usec);
4476 /* protect the connection with the connection lock so that we can see when
4477 * we are finished doing server communication */
4479 gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4480 &message, src->ptcp_timeout);
4484 GST_DEBUG_OBJECT (src, "we received a server message");
4486 case GST_RTSP_EINTR:
4487 /* we got interrupted this means we need to stop */
4489 case GST_RTSP_ETIMEOUT:
4490 /* no reply, send keep alive */
4491 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4492 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4496 /* go EOS when the server closed the connection */
4502 switch (message.type) {
4503 case GST_RTSP_MESSAGE_REQUEST:
4504 /* server sends us a request message, handle it */
4506 gst_rtspsrc_handle_request (src, src->conninfo.connection,
4508 if (res == GST_RTSP_EEOF)
4511 goto handle_request_failed;
4513 case GST_RTSP_MESSAGE_RESPONSE:
4514 /* we ignore response messages */
4515 GST_DEBUG_OBJECT (src, "ignoring response message");
4517 gst_rtsp_message_dump (&message);
4519 case GST_RTSP_MESSAGE_DATA:
4520 GST_DEBUG_OBJECT (src, "got data message");
4521 ret = gst_rtspsrc_handle_data (src, &message);
4522 if (ret != GST_FLOW_OK)
4523 goto handle_data_failed;
4526 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4531 g_assert_not_reached ();
4536 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4537 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4538 ("The server closed the connection."));
4539 src->conninfo.connected = FALSE;
4540 gst_rtsp_message_unset (&message);
4541 return GST_FLOW_EOS;
4545 gst_rtsp_message_unset (&message);
4546 GST_DEBUG_OBJECT (src, "got interrupted");
4547 return GST_FLOW_FLUSHING;
4551 gchar *str = gst_rtsp_strresult (res);
4553 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4554 ("Could not receive message. (%s)", str));
4557 gst_rtsp_message_unset (&message);
4558 return GST_FLOW_ERROR;
4560 handle_request_failed:
4562 gchar *str = gst_rtsp_strresult (res);
4564 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4565 ("Could not handle server message. (%s)", str));
4567 gst_rtsp_message_unset (&message);
4568 return GST_FLOW_ERROR;
4572 GST_DEBUG_OBJECT (src, "could no handle data message");
4577 static GstFlowReturn
4578 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4581 GstRTSPMessage message = { 0 };
4585 GTimeVal tv_timeout;
4587 /* get the next timeout interval */
4588 gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4590 GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4591 (gint) tv_timeout.tv_sec);
4593 gst_rtsp_message_unset (&message);
4595 /* we should continue reading the TCP socket because the server might
4596 * send us requests. When the session timeout expires, we need to send a
4597 * keep-alive request to keep the session open. */
4598 res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4599 &message, &tv_timeout);
4603 GST_DEBUG_OBJECT (src, "we received a server message");
4605 case GST_RTSP_EINTR:
4606 /* we got interrupted, see what we have to do */
4608 case GST_RTSP_ETIMEOUT:
4609 /* send keep-alive, ignore the result, a warning will be posted. */
4610 GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4611 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4615 /* server closed the connection. not very fatal for UDP, reconnect and
4616 * see what happens. */
4617 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4618 ("The server closed the connection."));
4619 if (src->udp_reconnect) {
4621 gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4628 GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4630 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4631 ("Unhandled return value %d.", res));
4635 switch (message.type) {
4636 case GST_RTSP_MESSAGE_REQUEST:
4637 /* server sends us a request message, handle it */
4639 gst_rtspsrc_handle_request (src, src->conninfo.connection,
4641 if (res == GST_RTSP_EEOF)
4644 goto handle_request_failed;
4646 case GST_RTSP_MESSAGE_RESPONSE:
4647 /* we ignore response and data messages */
4648 GST_DEBUG_OBJECT (src, "ignoring response message");
4650 gst_rtsp_message_dump (&message);
4651 if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4652 GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4653 if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4654 GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4655 if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4662 case GST_RTSP_MESSAGE_DATA:
4663 /* we ignore response and data messages */
4664 GST_DEBUG_OBJECT (src, "ignoring data message");
4667 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4672 g_assert_not_reached ();
4674 /* we get here when the connection got interrupted */
4677 gst_rtsp_message_unset (&message);
4678 GST_DEBUG_OBJECT (src, "got interrupted");
4679 return GST_FLOW_FLUSHING;
4683 gchar *str = gst_rtsp_strresult (res);
4686 src->conninfo.connected = FALSE;
4687 if (res != GST_RTSP_EINTR) {
4688 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4689 ("Could not connect to server. (%s)", str));
4691 ret = GST_FLOW_ERROR;
4693 ret = GST_FLOW_FLUSHING;
4699 gchar *str = gst_rtsp_strresult (res);
4701 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4702 ("Could not receive message. (%s)", str));
4704 return GST_FLOW_ERROR;
4706 handle_request_failed:
4708 gchar *str = gst_rtsp_strresult (res);
4711 gst_rtsp_message_unset (&message);
4712 if (res != GST_RTSP_EINTR) {
4713 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4714 ("Could not handle server message. (%s)", str));
4716 ret = GST_FLOW_ERROR;
4718 ret = GST_FLOW_FLUSHING;
4724 GST_DEBUG_OBJECT (src, "we got an eof from the server");
4725 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4726 ("The server closed the connection."));
4727 src->conninfo.connected = FALSE;
4728 gst_rtsp_message_unset (&message);
4729 return GST_FLOW_EOS;
4733 static GstRTSPResult
4734 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4736 GstRTSPResult res = GST_RTSP_OK;
4739 GST_DEBUG_OBJECT (src, "doing reconnect");
4741 GST_OBJECT_LOCK (src);
4742 /* only restart when the pads were not yet activated, else we were
4743 * streaming over UDP */
4744 restart = src->need_activate;
4745 GST_OBJECT_UNLOCK (src);
4747 /* no need to restart, we're done */
4751 /* we can try only TCP now */
4752 src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4754 /* close and cleanup our state */
4755 if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4758 /* see if we have TCP left to try. Also don't try TCP when we were configured
4760 if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4763 /* We post a warning message now to inform the user
4764 * that nothing happened. It's most likely a firewall thing. */
4765 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4766 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4767 "firewall is blocking it. Retrying using a TCP connection.",
4768 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4770 /* open new connection using tcp */
4771 if (gst_rtspsrc_open (src, async) < 0)
4774 /* start playback */
4775 if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4784 src->cur_protocols = 0;
4785 /* no transport possible, post an error and stop */
4786 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4787 ("Could not receive any UDP packets for %.4f seconds, maybe your "
4788 "firewall is blocking it. No other protocols to try.",
4789 gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4790 return GST_RTSP_ERROR;
4794 GST_DEBUG_OBJECT (src, "open failed");
4799 GST_DEBUG_OBJECT (src, "play failed");
4805 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4809 GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4812 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4815 GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4818 GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4826 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4830 GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4833 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4836 GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4839 GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4847 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4851 GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4854 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4857 GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4860 GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4868 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4872 GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4875 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4878 GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4881 GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4889 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4891 if (ret == GST_RTSP_OK)
4892 gst_rtspsrc_loop_complete_cmd (src, cmd);
4893 else if (ret == GST_RTSP_EINTR)
4894 gst_rtspsrc_loop_cancel_cmd (src, cmd);
4896 gst_rtspsrc_loop_error_cmd (src, cmd);
4900 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4903 gboolean flushed = FALSE;
4905 /* start new request */
4906 gst_rtspsrc_loop_start_cmd (src, cmd);
4908 GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4910 GST_OBJECT_LOCK (src);
4911 old = src->pending_cmd;
4912 if (old == CMD_RECONNECT) {
4913 GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4914 cmd = CMD_RECONNECT;
4916 if (old != CMD_WAIT) {
4917 src->pending_cmd = CMD_WAIT;
4918 GST_OBJECT_UNLOCK (src);
4919 /* cancel previous request */
4920 GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4921 gst_rtspsrc_loop_cancel_cmd (src, old);
4922 GST_OBJECT_LOCK (src);
4924 src->pending_cmd = cmd;
4925 /* interrupt if allowed */
4926 if (src->busy_cmd & mask) {
4927 GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4928 gst_rtspsrc_connection_flush (src, TRUE);
4931 GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4934 gst_task_start (src->task);
4935 GST_OBJECT_UNLOCK (src);
4941 gst_rtspsrc_loop (GstRTSPSrc * src)
4945 if (!src->conninfo.connection || !src->conninfo.connected)
4948 if (src->interleaved)
4949 ret = gst_rtspsrc_loop_interleaved (src);
4951 ret = gst_rtspsrc_loop_udp (src);
4953 if (ret != GST_FLOW_OK)
4961 GST_WARNING_OBJECT (src, "we are not connected");
4962 ret = GST_FLOW_FLUSHING;
4967 const gchar *reason = gst_flow_get_name (ret);
4969 GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4970 src->running = FALSE;
4971 if (ret == GST_FLOW_EOS) {
4972 /* perform EOS logic */
4973 if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4974 gst_element_post_message (GST_ELEMENT_CAST (src),
4975 gst_message_new_segment_done (GST_OBJECT_CAST (src),
4976 src->segment.format, src->segment.position));
4977 gst_rtspsrc_push_event (src,
4978 gst_event_new_segment_done (src->segment.format,
4979 src->segment.position));
4981 gst_rtspsrc_push_event (src, gst_event_new_eos ());
4983 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4984 /* for fatal errors we post an error message, post the error before the
4985 * EOS so the app knows about the error first. */
4986 GST_ELEMENT_ERROR (src, STREAM, FAILED,
4987 ("Internal data flow error."),
4988 ("streaming task paused, reason %s (%d)", reason, ret));
4989 gst_rtspsrc_push_event (src, gst_event_new_eos ());
4991 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
4996 #ifndef GST_DISABLE_GST_DEBUG
4997 static const gchar *
4998 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5002 while (method != 0) {
5019 static const gchar *
5020 gst_rtspsrc_skip_lws (const gchar * s)
5022 while (g_ascii_isspace (*s))
5027 static const gchar *
5028 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
5030 while (s > start && g_ascii_isspace (*(s - 1)))
5035 static const gchar *
5036 gst_rtspsrc_skip_commas (const gchar * s)
5038 /* The grammar allows for multiple commas */
5039 while (g_ascii_isspace (*s) || *s == ',')
5044 static const gchar *
5045 gst_rtspsrc_skip_item (const gchar * s)
5047 gboolean quoted = FALSE;
5048 const gchar *start = s;
5050 /* A list item ends at the last non-whitespace character
5051 * before a comma which is not inside a quoted-string. Or at
5052 * the end of the string.
5058 if (*s == '\\' && *(s + 1))
5067 return gst_rtspsrc_unskip_lws (s, start);
5071 gst_rtsp_decode_quoted_string (gchar * quoted_string)
5075 src = quoted_string + 1;
5076 dst = quoted_string;
5077 while (*src && *src != '"') {
5078 if (*src == '\\' && *(src + 1))
5085 /* Extract the authentication tokens that the server provided for each method
5086 * into an array of structures and give those to the connection object.
5089 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
5090 const gchar * header, gboolean * stale)
5092 GSList *list = NULL, *iter;
5094 gchar *item, *eq, *name_end, *value;
5096 g_return_if_fail (stale != NULL);
5098 gst_rtsp_connection_clear_auth_params (conn);
5101 /* Parse a header whose content is described by RFC2616 as
5102 * "#something", where "something" does not itself contain commas,
5103 * except as part of quoted-strings, into a list of allocated strings.
5105 header = gst_rtspsrc_skip_commas (header);
5107 end = gst_rtspsrc_skip_item (header);
5108 list = g_slist_prepend (list, g_strndup (header, end - header));
5109 header = gst_rtspsrc_skip_commas (end);
5114 list = g_slist_reverse (list);
5115 for (iter = list; iter; iter = iter->next) {
5118 eq = strchr (item, '=');
5120 name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
5121 if (name_end == item) {
5122 /* That's no good... */
5129 value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
5131 gst_rtsp_decode_quoted_string (value);
5135 if (item && (strcmp (item, "stale") == 0) &&
5136 value && (strcmp (value, "TRUE") == 0))
5138 gst_rtsp_connection_set_auth_param (conn, item, value);
5142 g_slist_free (list);
5145 /* Parse a WWW-Authenticate Response header and determine the
5146 * available authentication methods
5148 * This code should also cope with the fact that each WWW-Authenticate
5149 * header can contain multiple challenge methods + tokens
5151 * At the moment, for Basic auth, we just do a minimal check and don't
5152 * even parse out the realm */
5154 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
5155 GstRTSPConnection * conn, gboolean * stale)
5159 g_return_if_fail (hdr != NULL);
5160 g_return_if_fail (methods != NULL);
5161 g_return_if_fail (stale != NULL);
5163 /* Skip whitespace at the start of the string */
5164 for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
5166 if (g_ascii_strncasecmp (start, "basic", 5) == 0)
5167 *methods |= GST_RTSP_AUTH_BASIC;
5168 else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
5169 *methods |= GST_RTSP_AUTH_DIGEST;
5170 gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
5175 * gst_rtspsrc_setup_auth:
5176 * @src: the rtsp source
5178 * Configure a username and password and auth method on the
5179 * connection object based on a response we received from the
5182 * Currently, this requires that a username and password were supplied
5183 * in the uri. In the future, they may be requested on demand by sending
5184 * a message up the bus.
5186 * Returns: TRUE if authentication information could be set up correctly.
5189 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5193 GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5194 GstRTSPAuthMethod method;
5195 GstRTSPResult auth_result;
5197 GstRTSPConnection *conn;
5199 gboolean stale = FALSE;
5201 conn = src->conninfo.connection;
5203 /* Identify the available auth methods and see if any are supported */
5204 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
5205 &hdr, 0) == GST_RTSP_OK) {
5206 gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
5209 if (avail_methods == GST_RTSP_AUTH_NONE)
5210 goto no_auth_available;
5212 /* For digest auth, if the response indicates that the session
5213 * data are stale, we just update them in the connection object and
5214 * return TRUE to retry the request */
5216 src->tried_url_auth = FALSE;
5218 url = gst_rtsp_connection_get_url (conn);
5220 /* Do we have username and password available? */
5221 if (url != NULL && !src->tried_url_auth && url->user != NULL
5222 && url->passwd != NULL) {
5225 src->tried_url_auth = TRUE;
5226 GST_DEBUG_OBJECT (src,
5227 "Attempting authentication using credentials from the URL");
5229 user = src->user_id;
5230 pass = src->user_pw;
5231 GST_DEBUG_OBJECT (src,
5232 "Attempting authentication using credentials from the properties");
5235 /* FIXME: If the url didn't contain username and password or we tried them
5236 * already, request a username and passwd from the application via some kind
5237 * of credentials request message */
5239 /* If we don't have a username and passwd at this point, bail out. */
5240 if (user == NULL || pass == NULL)
5243 /* Try to configure for each available authentication method, strongest to
5245 for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5246 /* Check if this method is available on the server */
5247 if ((method & avail_methods) == 0)
5250 /* Pass the credentials to the connection to try on the next request */
5251 auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5252 /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5253 * ignore it and end up retrying later */
5254 if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5255 GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5256 gst_rtsp_auth_method_to_string (method));
5261 if (method == GST_RTSP_AUTH_NONE)
5262 goto no_auth_available;
5268 /* Output an error indicating that we couldn't connect because there were
5269 * no supported authentication protocols */
5270 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5271 ("No supported authentication protocol was found"));
5276 /* We don't fire an error message, we just return FALSE and let the
5277 * normal NOT_AUTHORIZED error be propagated */
5282 static GstRTSPResult
5283 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5284 GstRTSPMessage * request, GstRTSPMessage * response,
5285 GstRTSPStatusCode * code)
5288 GstRTSPStatusCode thecode;
5289 gchar *content_base = NULL;
5293 if (!src->short_header)
5294 gst_rtsp_ext_list_before_send (src->extensions, request);
5296 GST_DEBUG_OBJECT (src, "sending message");
5299 gst_rtsp_message_dump (request);
5301 res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
5305 gst_rtsp_connection_reset_timeout (conn);
5308 res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
5313 gst_rtsp_message_dump (response);
5315 switch (response->type) {
5316 case GST_RTSP_MESSAGE_REQUEST:
5317 res = gst_rtspsrc_handle_request (src, conn, response);
5318 if (res == GST_RTSP_EEOF)
5321 goto handle_request_failed;
5323 case GST_RTSP_MESSAGE_RESPONSE:
5324 /* ok, a response is good */
5325 GST_DEBUG_OBJECT (src, "received response message");
5327 case GST_RTSP_MESSAGE_DATA:
5328 /* get next response */
5329 GST_DEBUG_OBJECT (src, "handle data response message");
5330 gst_rtspsrc_handle_data (src, response);
5333 GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5338 thecode = response->type_data.response.code;
5340 GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5342 /* if the caller wanted the result code, we store it. */
5346 /* If the request didn't succeed, bail out before doing any more */
5347 if (thecode != GST_RTSP_STS_OK)
5350 /* store new content base if any */
5351 gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5354 g_free (src->content_base);
5355 src->content_base = g_strdup (content_base);
5357 gst_rtsp_ext_list_after_send (src->extensions, request, response);
5364 gchar *str = gst_rtsp_strresult (res);
5366 if (res != GST_RTSP_EINTR) {
5367 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5368 ("Could not send message. (%s)", str));
5370 GST_WARNING_OBJECT (src, "send interrupted");
5379 GST_WARNING_OBJECT (src, "server closed connection");
5380 if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5382 /* if reconnect succeeds, try again */
5384 gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5388 /* only try once after reconnect, then fallthrough and error out */
5391 gchar *str = gst_rtsp_strresult (res);
5393 if (res != GST_RTSP_EINTR) {
5394 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5395 ("Could not receive message. (%s)", str));
5397 GST_WARNING_OBJECT (src, "receive interrupted");
5405 handle_request_failed:
5407 /* ERROR was posted */
5408 gst_rtsp_message_unset (response);
5413 GST_DEBUG_OBJECT (src, "we got an eof from the server");
5414 GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5415 ("The server closed the connection."));
5416 gst_rtsp_message_unset (response);
5423 * @src: the rtsp source
5424 * @conn: the connection to send on
5425 * @request: must point to a valid request
5426 * @response: must point to an empty #GstRTSPMessage
5427 * @code: an optional code result
5429 * send @request and retrieve the response in @response. optionally @code can be
5430 * non-NULL in which case it will contain the status code of the response.
5432 * If This function returns #GST_RTSP_OK, @response will contain a valid response
5433 * message that should be cleaned with gst_rtsp_message_unset() after usage.
5435 * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5436 * @response message) if the response code was not 200 (OK).
5438 * If the attempt results in an authentication failure, then this will attempt
5439 * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5442 * Returns: #GST_RTSP_OK if the processing was successful.
5444 static GstRTSPResult
5445 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5446 GstRTSPMessage * request, GstRTSPMessage * response,
5447 GstRTSPStatusCode * code)
5449 GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5450 GstRTSPResult res = GST_RTSP_ERROR;
5453 GstRTSPMethod method = GST_RTSP_INVALID;
5459 /* make sure we don't loop forever */
5463 /* save method so we can disable it when the server complains */
5464 method = request->type_data.request.method;
5467 gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5471 case GST_RTSP_STS_UNAUTHORIZED:
5472 if (gst_rtspsrc_setup_auth (src, response)) {
5473 /* Try the request/response again after configuring the auth info
5481 } while (retry == TRUE);
5483 /* If the user requested the code, let them handle errors, otherwise
5484 * post an error below */
5487 else if (int_code != GST_RTSP_STS_OK)
5488 goto error_response;
5495 GST_DEBUG_OBJECT (src, "got error %d", res);
5500 res = GST_RTSP_ERROR;
5502 switch (response->type_data.response.code) {
5503 case GST_RTSP_STS_NOT_FOUND:
5504 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5505 response->type_data.response.reason));
5507 case GST_RTSP_STS_MOVED_PERMANENTLY:
5508 case GST_RTSP_STS_MOVE_TEMPORARILY:
5510 gchar *new_location;
5511 GstRTSPLowerTrans transports;
5513 GST_DEBUG_OBJECT (src, "got redirection");
5514 /* if we don't have a Location Header, we must error */
5515 if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5516 &new_location, 0) < 0)
5519 /* When we receive a redirect result, we go back to the INIT state after
5520 * parsing the new URI. The caller should do the needed steps to issue
5521 * a new setup when it detects this state change. */
5522 GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5524 /* save current transports */
5525 if (src->conninfo.url)
5526 transports = src->conninfo.url->transports;
5528 transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5530 gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5532 /* set old transports */
5533 if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5534 src->conninfo.url->transports = transports;
5536 src->need_redirect = TRUE;
5537 src->state = GST_RTSP_STATE_INIT;
5541 case GST_RTSP_STS_NOT_ACCEPTABLE:
5542 case GST_RTSP_STS_NOT_IMPLEMENTED:
5543 case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5544 GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5545 gst_rtsp_method_as_text (method));
5546 src->methods &= ~method;
5550 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5551 ("Got error response: %d (%s).", response->type_data.response.code,
5552 response->type_data.response.reason));
5555 /* if we return ERROR we should unset the response ourselves */
5556 if (res == GST_RTSP_ERROR)
5557 gst_rtsp_message_unset (response);
5563 static GstRTSPResult
5564 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5565 GstRTSPMessage * response, GstRTSPSrc * src)
5567 return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5572 /* parse the response and collect all the supported methods. We need this
5573 * information so that we don't try to send an unsupported request to the
5577 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5579 GstRTSPHeaderField field;
5583 /* reset supported methods */
5586 /* Try Allow Header first */
5587 field = GST_RTSP_HDR_ALLOW;
5590 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5591 if (indx == 0 && !respoptions) {
5592 /* if no Allow header was found then try the Public header... */
5593 field = GST_RTSP_HDR_PUBLIC;
5594 gst_rtsp_message_get_header (response, field, &respoptions, indx);
5599 src->methods |= gst_rtsp_options_from_text (respoptions);
5604 if (src->methods == 0) {
5605 /* neither Allow nor Public are required, assume the server supports
5606 * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5608 GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5609 src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5611 /* always assume PLAY, FIXME, extensions should be able to override
5613 src->methods |= GST_RTSP_PLAY;
5614 /* also assume it will support Range */
5615 src->seekable = TRUE;
5617 /* we need describe and setup */
5618 if (!(src->methods & GST_RTSP_DESCRIBE))
5620 if (!(src->methods & GST_RTSP_SETUP))
5628 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5629 ("Server does not support DESCRIBE."));
5634 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5635 ("Server does not support SETUP."));
5640 /* masks to be kept in sync with the hardcoded protocol order of preference
5642 static guint protocol_masks[] = {
5643 GST_RTSP_LOWER_TRANS_UDP,
5644 GST_RTSP_LOWER_TRANS_UDP_MCAST,
5645 GST_RTSP_LOWER_TRANS_TCP,
5649 static GstRTSPResult
5650 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5651 GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
5655 gboolean add_udp_str;
5660 gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5665 GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5667 /* extension listed transports, use those */
5668 if (*transports != NULL)
5671 /* it's the default */
5672 add_udp_str = FALSE;
5674 /* the default RTSP transports */
5675 result = g_string_new ("RTP");
5678 case GST_RTSP_PROFILE_AVP:
5679 g_string_append (result, "/AVP");
5681 case GST_RTSP_PROFILE_SAVP:
5682 g_string_append (result, "/SAVP");
5684 case GST_RTSP_PROFILE_AVPF:
5685 g_string_append (result, "/AVPF");
5687 case GST_RTSP_PROFILE_SAVPF:
5688 g_string_append (result, "/SAVPF");
5694 if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5695 GST_DEBUG_OBJECT (src, "adding UDP unicast");
5697 g_string_append (result, "/UDP");
5698 g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5699 } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5700 GST_DEBUG_OBJECT (src, "adding UDP multicast");
5701 /* we don't have to allocate any UDP ports yet, if the selected transport
5702 * turns out to be multicast we can create them and join the multicast
5703 * group indicated in the transport reply */
5705 g_string_append (result, "/UDP");
5706 g_string_append (result, ";multicast");
5707 if (src->next_port_num != 0) {
5708 if (src->client_port_range.max > 0 &&
5709 src->next_port_num >= src->client_port_range.max)
5712 g_string_append_printf (result, ";client_port=%d-%d",
5713 src->next_port_num, src->next_port_num + 1);
5715 } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5716 GST_DEBUG_OBJECT (src, "adding TCP");
5718 g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
5720 *transports = g_string_free (result, FALSE);
5722 GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5729 GST_ERROR ("extension gave error %d", res);
5734 GST_ERROR ("no more ports available");
5735 return GST_RTSP_ERROR;
5739 static GstRTSPResult
5740 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5741 gint orig_rtpport, gint orig_rtcpport)
5744 gint nr_udp, nr_int;
5746 gint rtpport = 0, rtcpport = 0;
5749 src = stream->parent;
5751 /* find number of placeholders first */
5752 if (strstr (*transports, "%%i2"))
5754 else if (strstr (*transports, "%%i1"))
5759 if (strstr (*transports, "%%u2"))
5761 else if (strstr (*transports, "%%u1"))
5766 if (nr_udp == 0 && nr_int == 0)
5770 if (!orig_rtpport || !orig_rtcpport) {
5771 if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5774 rtpport = orig_rtpport;
5775 rtcpport = orig_rtcpport;
5779 str = g_string_new ("");
5781 while ((next = strstr (p, "%%"))) {
5782 g_string_append_len (str, p, next - p);
5783 if (next[2] == 'u') {
5785 g_string_append_printf (str, "%d", rtpport);
5786 else if (next[3] == '2')
5787 g_string_append_printf (str, "%d", rtcpport);
5789 if (next[2] == 'i') {
5791 g_string_append_printf (str, "%d", src->free_channel);
5792 else if (next[3] == '2')
5793 g_string_append_printf (str, "%d", src->free_channel + 1);
5798 /* append final part */
5799 g_string_append (str, p);
5801 g_free (*transports);
5802 *transports = g_string_free (str, FALSE);
5810 GST_ERROR ("failed to allocate udp ports");
5811 return GST_RTSP_ERROR;
5816 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
5819 gchar *result, *base64;
5824 GstMIKEYMessage *msg;
5825 GstMIKEYPayload *payload, *pkd;
5829 key_data = g_malloc (KEY_SIZE);
5830 for (i = 0; i < KEY_SIZE; i += 4)
5831 GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
5834 gst_buffer_unref (stream->key);
5835 stream->key = gst_buffer_new_wrapped (key_data, KEY_SIZE);
5837 msg = gst_mikey_message_new ();
5838 /* unencrypted MIKEY message, we send this over TLS so this is allowed */
5839 gst_mikey_message_set_info (msg, GST_MIKEY_VERSION, GST_MIKEY_TYPE_PSK_INIT,
5840 FALSE, GST_MIKEY_PRF_MIKEY_1, g_random_int (), GST_MIKEY_MAP_TYPE_SRTP);
5841 /* add policy '0' for our SSRC */
5842 stream->send_ssrc = g_random_int ();
5843 gst_mikey_message_add_cs_srtp (msg, 0, stream->send_ssrc, 0);
5844 /* timestamp is now */
5845 gst_mikey_message_add_t_now_ntp_utc (msg);
5846 /* add some random data */
5847 gst_mikey_message_add_rand_len (msg, 16);
5849 /* the policy '0' is SRTP */
5850 payload = gst_mikey_payload_new (GST_MIKEY_PT_SP);
5851 gst_mikey_payload_sp_set (payload, 0, GST_MIKEY_SEC_PROTO_SRTP);
5853 /* only AES-CM is supported */
5855 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_ALG, 1, &byte);
5856 /* only HMAC-SHA1 */
5857 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_ALG, 1,
5859 /* we enable encryption on RTP and RTCP */
5860 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_ENC, 1,
5862 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTCP_ENC, 1,
5864 /* we enable authentication on RTP and RTCP */
5865 gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_AUTH, 1,
5867 gst_mikey_message_add_payload (msg, payload);
5869 /* make unencrypted KEMAC */
5870 payload = gst_mikey_payload_new (GST_MIKEY_PT_KEMAC);
5871 gst_mikey_payload_kemac_set (payload, GST_MIKEY_ENC_NULL, GST_MIKEY_MAC_NULL);
5872 /* add the key in KEMAC */
5873 pkd = gst_mikey_payload_new (GST_MIKEY_PT_KEY_DATA);
5874 gst_mikey_payload_key_data_set_key (pkd, GST_MIKEY_KD_TEK, KEY_SIZE,
5876 gst_mikey_payload_kemac_add_sub (payload, pkd);
5877 gst_mikey_message_add_payload (msg, payload);
5879 /* now serialize this to bytes */
5880 bytes = gst_mikey_message_to_bytes (msg, NULL, NULL);
5881 gst_mikey_message_free (msg);
5882 /* and make it into base64 */
5883 data = g_bytes_get_data (bytes, &size);
5884 base64 = g_base64_encode (data, size);
5885 g_bytes_unref (bytes);
5887 result = g_strdup_printf ("prot=mikey;uri=\"%s\";data=\"%s\"",
5888 stream->conninfo.location, base64);
5895 /* Perform the SETUP request for all the streams.
5897 * We ask the server for a specific transport, which initially includes all the
5898 * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5899 * two local UDP ports that we send to the server.
5901 * Once the server replied with a transport, we configure the other streams
5902 * with the same transport.
5904 * This function will also configure the stream for the selected transport,
5905 * which basically means creating the pipeline.
5907 static GstRTSPResult
5908 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5911 GstRTSPResult res = GST_RTSP_ERROR;
5912 GstRTSPMessage request = { 0 };
5913 GstRTSPMessage response = { 0 };
5914 GstRTSPStream *stream = NULL;
5915 GstRTSPLowerTrans protocols;
5916 GstRTSPStatusCode code;
5917 gboolean unsupported_real = FALSE;
5918 gint rtpport, rtcpport;
5922 if (src->conninfo.connection) {
5923 url = gst_rtsp_connection_get_url (src->conninfo.connection);
5924 /* we initially allow all configured lower transports. based on the URL
5925 * transports and the replies from the server we narrow them down. */
5926 protocols = url->transports & src->cur_protocols;
5929 protocols = src->cur_protocols;
5935 /* reset some state */
5936 src->free_channel = 0;
5937 src->interleaved = FALSE;
5938 src->need_activate = FALSE;
5939 /* keep track of next port number, 0 is random */
5940 src->next_port_num = src->client_port_range.min;
5941 rtpport = rtcpport = 0;
5943 if (G_UNLIKELY (src->streams == NULL))
5946 for (walk = src->streams; walk; walk = g_list_next (walk)) {
5947 GstRTSPConnection *conn;
5954 stream = (GstRTSPStream *) walk->data;
5956 caps = stream_get_caps_for_pt (stream, stream->default_pt);
5958 GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
5962 if (stream->skipped) {
5963 GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
5967 /* see if we need to configure this stream */
5968 if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
5969 GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5974 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
5975 stream->id, caps, &selected);
5977 GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
5981 /* merge/overwrite global caps */
5986 s = gst_caps_get_structure (caps, 0);
5988 num = gst_structure_n_fields (src->props);
5989 for (j = 0; j < num; j++) {
5993 name = gst_structure_nth_field_name (src->props, j);
5994 val = gst_structure_get_value (src->props, name);
5995 gst_structure_set_value (s, name, val);
5997 GST_DEBUG_OBJECT (src, "copied %s", name);
6001 /* skip setup if we have no URL for it */
6002 if (stream->conninfo.location == NULL) {
6003 GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6007 if (src->conninfo.connection == NULL) {
6008 if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6009 GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6012 conn = stream->conninfo.connection;
6014 conn = src->conninfo.connection;
6016 GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6017 stream->conninfo.location);
6019 /* if we have a multicast connection, only suggest multicast from now on */
6020 if (stream->is_multicast)
6021 protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6024 /* first selectable protocol */
6025 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6027 if (!protocol_masks[mask])
6031 GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6032 protocol_masks[mask]);
6033 /* create a string with first transport in line */
6035 res = gst_rtspsrc_create_transports_string (src,
6036 protocols & protocol_masks[mask], stream->profile, &transports);
6037 if (res < 0 || transports == NULL)
6038 goto setup_transport_failed;
6040 if (strlen (transports) == 0) {
6041 g_free (transports);
6042 GST_DEBUG_OBJECT (src, "no transports found");
6047 GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6049 /* replace placeholders with real values, this function will optionally
6050 * allocate UDP ports and other info needed to execute the setup request */
6051 res = gst_rtspsrc_prepare_transports (stream, &transports,
6052 retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6054 g_free (transports);
6055 goto setup_transport_failed;
6058 GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6060 /* create SETUP request */
6062 gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
6063 stream->conninfo.location);
6065 g_free (transports);
6066 goto create_request_failed;
6069 /* select transport */
6070 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6073 if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6074 stream->profile == GST_RTSP_PROFILE_SAVPF) {
6075 hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6076 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6079 /* if the user wants a non default RTP packet size we add the blocksize
6081 if (src->rtp_blocksize > 0) {
6082 hval = g_strdup_printf ("%d", src->rtp_blocksize);
6083 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6087 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6090 /* handle the code ourselves */
6091 if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
6095 case GST_RTSP_STS_OK:
6097 case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6098 gst_rtsp_message_unset (&request);
6099 gst_rtsp_message_unset (&response);
6100 /* cleanup of leftover transport */
6101 gst_rtspsrc_stream_free_udp (stream);
6102 /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6103 * we might be in this case */
6104 if (stream->container && rtpport && rtcpport && !retry) {
6105 GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6110 /* this transport did not go down well, but we may have others to try
6111 * that we did not send yet, try those and only give up then
6112 * but not without checking for lost cause/extension so we can
6113 * post a nicer/more useful error message later */
6114 if (!unsupported_real)
6115 unsupported_real = stream->is_real;
6116 /* select next available protocol, give up on this stream if none */
6118 while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6120 if (!protocol_masks[mask] || unsupported_real)
6125 /* cleanup of leftover transport and move to the next stream */
6126 gst_rtspsrc_stream_free_udp (stream);
6127 goto response_error;
6130 /* parse response transport */
6132 gchar *resptrans = NULL;
6133 GstRTSPTransport transport = { 0 };
6135 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
6138 gst_rtspsrc_stream_free_udp (stream);
6142 /* parse transport, go to next stream on parse error */
6143 if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6144 GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6148 /* update allowed transports for other streams. once the transport of
6149 * one stream has been determined, we make sure that all other streams
6150 * are configured in the same way */
6151 switch (transport.lower_transport) {
6152 case GST_RTSP_LOWER_TRANS_TCP:
6153 GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6154 protocols = GST_RTSP_LOWER_TRANS_TCP;
6155 src->interleaved = TRUE;
6156 /* update free channels */
6158 MAX (transport.interleaved.min, src->free_channel);
6160 MAX (transport.interleaved.max, src->free_channel);
6161 src->free_channel++;
6163 case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6164 /* only allow multicast for other streams */
6165 GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6166 protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6167 /* if the server selected our ports, increment our counters so that
6168 * we select a new port later */
6169 if (src->next_port_num == transport.port.min &&
6170 src->next_port_num + 1 == transport.port.max) {
6171 src->next_port_num += 2;
6174 case GST_RTSP_LOWER_TRANS_UDP:
6175 /* only allow unicast for other streams */
6176 GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6177 protocols = GST_RTSP_LOWER_TRANS_UDP;
6180 GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6181 transport.lower_transport);
6185 if (!stream->container || (!src->interleaved && !retry)) {
6186 /* now configure the stream with the selected transport */
6187 if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6188 GST_DEBUG_OBJECT (src,
6189 "could not configure stream %p transport, skipping stream",
6192 } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
6193 /* retain the first allocated UDP port pair */
6194 g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
6195 g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
6198 /* we need to activate at least one streams when we detect activity */
6199 src->need_activate = TRUE;
6201 /* stream is setup now */
6202 stream->setup = TRUE;
6207 GstRTSPStream *sskip;
6209 skip = g_list_next (skip);
6213 sskip = (GstRTSPStream *) skip->data;
6215 /* skip all streams with the same control url */
6216 if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6217 GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6218 sskip, sskip->conninfo.location);
6219 sskip->skipped = TRUE;
6224 /* clean up our transport struct */
6225 gst_rtsp_transport_init (&transport);
6226 /* clean up used RTSP messages */
6227 gst_rtsp_message_unset (&request);
6228 gst_rtsp_message_unset (&response);
6232 /* store the transport protocol that was configured */
6233 src->cur_protocols = protocols;
6235 gst_rtsp_ext_list_stream_select (src->extensions, url);
6237 /* if there is nothing to activate, error out */
6238 if (!src->need_activate)
6239 goto nothing_to_activate;
6246 /* no transport possible, post an error and stop */
6247 GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6248 ("Could not connect to server, no protocols left"));
6249 return GST_RTSP_ERROR;
6253 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6254 ("SDP contains no streams"));
6255 return GST_RTSP_ERROR;
6257 create_request_failed:
6259 gchar *str = gst_rtsp_strresult (res);
6261 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6262 ("Could not create request. (%s)", str));
6266 setup_transport_failed:
6268 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6269 ("Could not setup transport."));
6270 res = GST_RTSP_ERROR;
6275 const gchar *str = gst_rtsp_status_as_text (code);
6277 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6278 ("Error (%d): %s", code, GST_STR_NULL (str)));
6279 res = GST_RTSP_ERROR;
6284 gchar *str = gst_rtsp_strresult (res);
6286 if (res != GST_RTSP_EINTR) {
6287 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6288 ("Could not send message. (%s)", str));
6290 GST_WARNING_OBJECT (src, "send interrupted");
6297 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6298 ("Server did not select transport."));
6299 res = GST_RTSP_ERROR;
6302 nothing_to_activate:
6304 /* none of the available error codes is really right .. */
6305 if (unsupported_real) {
6306 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6307 (_("No supported stream was found. You might need to install a "
6308 "GStreamer RTSP extension plugin for Real media streams.")),
6311 GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6312 (_("No supported stream was found. You might need to allow "
6313 "more transport protocols or may otherwise be missing "
6314 "the right GStreamer RTSP extension plugin.")), (NULL));
6316 return GST_RTSP_ERROR;
6320 gst_rtsp_message_unset (&request);
6321 gst_rtsp_message_unset (&response);
6327 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6328 GstSegment * segment)
6331 GstRTSPTimeRange *therange;
6334 gst_rtsp_range_free (src->range);
6336 if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6337 GST_DEBUG_OBJECT (src, "parsed range %s", range);
6338 src->range = therange;
6340 GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6342 gst_segment_init (segment, GST_FORMAT_TIME);
6346 GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d, max %f ",
6347 therange->min.type, therange->min.seconds, therange->max.type,
6348 therange->max.seconds);
6350 if (therange->min.type == GST_RTSP_TIME_NOW)
6352 else if (therange->min.type == GST_RTSP_TIME_END)
6355 seconds = therange->min.seconds * GST_SECOND;
6357 GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6358 GST_TIME_ARGS (seconds));
6360 /* we need to start playback without clipping from the position reported by
6362 segment->start = seconds;
6363 segment->position = seconds;
6365 if (therange->max.type == GST_RTSP_TIME_NOW)
6367 else if (therange->max.type == GST_RTSP_TIME_END)
6370 seconds = therange->max.seconds * GST_SECOND;
6372 GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6373 GST_TIME_ARGS (seconds));
6375 /* live (WMS) server might send overflowed large max as its idea of infinity,
6376 * compensate to prevent problems later on */
6377 if (seconds != -1 && seconds < 0) {
6379 GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6382 /* live (WMS) might send min == max, which is not worth recording */
6383 if (segment->duration == -1 && seconds == segment->start)
6386 /* don't change duration with unknown value, we might have a valid value
6387 * there that we want to keep. */
6389 segment->duration = seconds;
6394 /* Parse clock profived by the server with following syntax:
6396 * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6399 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6401 gboolean res = FALSE;
6403 if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6404 gchar **fields = NULL, **parts = NULL;
6405 gchar *remote_ip, *str;
6407 GstClockTime base_time;
6410 fields = g_strsplit (gstclock, " ", 0);
6412 /* wrapped clock, not very interesting for now */
6413 if (fields[1] == NULL)
6416 /* remote IP address and port */
6417 if ((str = fields[2]) == NULL)
6420 parts = g_strsplit (str, ":", 0);
6422 if ((remote_ip = parts[0]) == NULL)
6425 if ((str = parts[1]) == NULL)
6433 if ((str = fields[3]) == NULL)
6436 base_time = g_ascii_strtoull (str, NULL, 10);
6439 gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
6442 if (src->provided_clock)
6443 gst_object_unref (src->provided_clock);
6444 src->provided_clock = netclock;
6446 gst_element_post_message (GST_ELEMENT_CAST (src),
6447 gst_message_new_clock_provide (GST_OBJECT_CAST (src),
6448 src->provided_clock, TRUE));
6452 g_strfreev (fields);
6458 /* must be called with the RTSP state lock */
6459 static GstRTSPResult
6460 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
6466 /* prepare global stream caps properties */
6468 gst_structure_remove_all_fields (src->props);
6470 src->props = gst_structure_new_empty ("RTSPProperties");
6473 gst_sdp_message_dump (sdp);
6475 gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
6477 /* let the app inspect and change the SDP */
6478 g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
6480 gst_segment_init (&src->segment, GST_FORMAT_TIME);
6482 /* parse range for duration reporting. */
6487 range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
6491 /* keep track of the range and configure it in the segment */
6492 if (gst_rtspsrc_parse_range (src, range, &src->segment))
6496 /* parse clock information. This is GStreamer specific, a server can tell the
6497 * client what clock it is using and wrap that in a network clock. The
6498 * advantage of that is that we can slave to it. */
6500 const gchar *gstclock;
6503 gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6504 if (gstclock == NULL)
6507 /* parse the clock and expose it in the provide_clock method */
6508 if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6512 /* try to find a global control attribute. Note that a '*' means that we should
6513 * do aggregate control with the current url (so we don't do anything and
6514 * leave the current connection as is) */
6516 const gchar *control;
6519 control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6520 if (control == NULL)
6523 /* only take fully qualified urls */
6524 if (g_str_has_prefix (control, "rtsp://"))
6528 g_free (src->conninfo.location);
6529 src->conninfo.location = g_strdup (control);
6530 /* make a connection for this, if there was a connection already, nothing
6532 if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6533 GST_ERROR_OBJECT (src, "could not connect");
6536 /* we need to keep the control url separate from the connection url because
6537 * the rules for constructing the media control url need it */
6538 g_free (src->control);
6539 src->control = g_strdup (control);
6542 /* create streams */
6543 n_streams = gst_sdp_message_medias_len (sdp);
6544 for (i = 0; i < n_streams; i++) {
6545 gst_rtspsrc_create_stream (src, sdp, i);
6548 src->state = GST_RTSP_STATE_INIT;
6551 if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
6554 /* reset our state */
6555 src->need_range = TRUE;
6558 src->state = GST_RTSP_STATE_READY;
6565 GST_ERROR_OBJECT (src, "setup failed");
6566 gst_rtspsrc_cleanup (src);
6571 static GstRTSPResult
6572 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6576 GstRTSPMessage request = { 0 };
6577 GstRTSPMessage response = { 0 };
6580 gchar *respcont = NULL;
6583 src->need_redirect = FALSE;
6585 /* can't continue without a valid url */
6586 if (G_UNLIKELY (src->conninfo.url == NULL)) {
6587 res = GST_RTSP_EINVAL;
6590 src->tried_url_auth = FALSE;
6592 if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
6593 goto connect_failed;
6595 /* create OPTIONS */
6596 GST_DEBUG_OBJECT (src, "create options...");
6598 gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
6599 src->conninfo.url_str);
6601 goto create_request_failed;
6604 GST_DEBUG_OBJECT (src, "send options...");
6607 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
6610 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6615 if (!gst_rtspsrc_parse_methods (src, &response))
6618 /* create DESCRIBE */
6619 GST_DEBUG_OBJECT (src, "create describe...");
6621 gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
6622 src->conninfo.url_str);
6624 goto create_request_failed;
6626 /* we only accept SDP for now */
6627 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
6631 GST_DEBUG_OBJECT (src, "send describe...");
6634 GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
6637 gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6641 /* we only perform redirect for the describe, currently */
6642 if (src->need_redirect) {
6643 /* close connection, we don't have to send a TEARDOWN yet, ignore the
6645 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6647 gst_rtsp_message_unset (&request);
6648 gst_rtsp_message_unset (&response);
6654 /* it could be that the DESCRIBE method was not implemented */
6655 if (!src->methods & GST_RTSP_DESCRIBE)
6658 /* check if reply is SDP */
6659 gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6661 /* could not be set but since the request returned OK, we assume it
6662 * was SDP, else check it. */
6664 if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6665 goto wrong_content_type;
6668 /* get message body and parse as SDP */
6669 gst_rtsp_message_get_body (&response, &data, &size);
6670 if (data == NULL || size == 0)
6673 GST_DEBUG_OBJECT (src, "parse SDP...");
6674 gst_sdp_message_new (sdp);
6675 gst_sdp_message_parse_buffer (data, size, *sdp);
6677 /* clean up any messages */
6678 gst_rtsp_message_unset (&request);
6679 gst_rtsp_message_unset (&response);
6686 GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6687 ("No valid RTSP URL was provided"));
6692 gchar *str = gst_rtsp_strresult (res);
6694 if (res != GST_RTSP_EINTR) {
6695 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6696 ("Failed to connect. (%s)", str));
6698 GST_WARNING_OBJECT (src, "connect interrupted");
6703 create_request_failed:
6705 gchar *str = gst_rtsp_strresult (res);
6707 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6708 ("Could not create request. (%s)", str));
6714 /* Don't post a message - the rtsp_send method will have
6715 * taken care of it because we passed NULL for the response code */
6720 /* error was posted */
6721 res = GST_RTSP_ERROR;
6726 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6727 ("Server does not support SDP, got %s.", respcont));
6728 res = GST_RTSP_ERROR;
6733 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6734 ("Server can not provide an SDP."));
6735 res = GST_RTSP_ERROR;
6740 if (src->conninfo.connection) {
6741 GST_DEBUG_OBJECT (src, "free connection");
6742 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6744 gst_rtsp_message_unset (&request);
6745 gst_rtsp_message_unset (&response);
6750 static GstRTSPResult
6751 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6756 GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6758 if (src->sdp == NULL) {
6759 if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6763 if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6768 gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6775 GST_WARNING_OBJECT (src, "can't get sdp");
6776 src->open_error = TRUE;
6781 GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6782 src->open_error = TRUE;
6787 static GstRTSPResult
6788 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6790 GstRTSPMessage request = { 0 };
6791 GstRTSPMessage response = { 0 };
6792 GstRTSPResult res = GST_RTSP_OK;
6794 const gchar *control;
6796 GST_DEBUG_OBJECT (src, "TEARDOWN...");
6798 gst_rtspsrc_set_state (src, GST_STATE_READY);
6800 if (src->state < GST_RTSP_STATE_READY) {
6801 GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6808 /* construct a control url */
6809 control = get_aggregate_control (src);
6811 if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6814 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6815 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6816 const gchar *setup_url;
6817 GstRTSPConnInfo *info;
6819 /* try aggregate control first but do non-aggregate control otherwise */
6821 setup_url = control;
6822 else if ((setup_url = stream->conninfo.location) == NULL)
6825 if (src->conninfo.connection) {
6826 info = &src->conninfo;
6827 } else if (stream->conninfo.connection) {
6828 info = &stream->conninfo;
6832 if (!info->connected)
6837 gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6839 goto create_request_failed;
6842 GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6845 gst_rtspsrc_send (src, info->connection, &request, &response,
6849 /* FIXME, parse result? */
6850 gst_rtsp_message_unset (&request);
6851 gst_rtsp_message_unset (&response);
6854 /* early exit when we did aggregate control */
6860 /* close connections */
6861 GST_DEBUG_OBJECT (src, "closing connection...");
6862 gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6863 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6864 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6865 gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6869 gst_rtspsrc_cleanup (src);
6871 src->state = GST_RTSP_STATE_INVALID;
6874 gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6879 create_request_failed:
6881 gchar *str = gst_rtsp_strresult (res);
6883 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6884 ("Could not create request. (%s)", str));
6890 gchar *str = gst_rtsp_strresult (res);
6892 gst_rtsp_message_unset (&request);
6893 if (res != GST_RTSP_EINTR) {
6894 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6895 ("Could not send message. (%s)", str));
6897 GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
6904 GST_DEBUG_OBJECT (src,
6905 "TEARDOWN and PLAY not supported, can't do TEARDOWN");
6910 /* RTP-Info is of the format:
6912 * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
6914 * rtptime corresponds to the timestamp for the NPT time given in the header
6915 * seqbase corresponds to the next sequence number we received. This number
6916 * indicates the first seqnum after the seek and should be used to discard
6917 * packets that are from before the seek.
6920 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
6925 GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
6927 infos = g_strsplit (rtpinfo, ",", 0);
6928 for (i = 0; infos[i]; i++) {
6930 GstRTSPStream *stream;
6934 GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
6936 /* init values, types of seqbase and timebase are bigger than needed so we
6937 * can store -1 as uninitialized values */
6942 /* parse url, find stream for url.
6943 * parse seq and rtptime. The seq number should be configured in the rtp
6944 * depayloader or session manager to detect gaps. Same for the rtptime, it
6945 * should be used to create an initial time newsegment. */
6946 fields = g_strsplit (infos[i], ";", 0);
6947 for (j = 0; fields[j]; j++) {
6948 GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
6949 /* remove leading whitespace */
6950 fields[j] = g_strchug (fields[j]);
6951 if (g_str_has_prefix (fields[j], "url=")) {
6952 /* get the url and the stream */
6954 find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
6955 } else if (g_str_has_prefix (fields[j], "seq=")) {
6956 seqbase = atoi (fields[j] + 4);
6957 } else if (g_str_has_prefix (fields[j], "rtptime=")) {
6958 timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
6961 g_strfreev (fields);
6962 /* now we need to store the values for the caps of the stream */
6963 if (stream != NULL) {
6964 GST_DEBUG_OBJECT (src,
6965 "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
6966 stream, seqbase, timebase);
6968 /* we have a stream, configure detected params */
6969 stream->seqbase = seqbase;
6970 stream->timebase = timebase;
6979 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
6984 interval = strtoul (rtcp, NULL, 10);
6985 GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
6990 interval *= GST_MSECOND;
6992 for (walk = src->streams; walk; walk = g_list_next (walk)) {
6993 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6995 /* already (optionally) retrieved this when configuring manager */
6996 if (stream->session) {
6997 GObject *rtpsession = stream->session;
6999 GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7001 g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7005 /* now it happens that (Xenon) server sending this may also provide bogus
7006 * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7007 * and just use RTP-Info to sync */
7009 GObjectClass *klass;
7011 klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7012 if (g_object_class_find_property (klass, "rtcp-sync")) {
7013 GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7014 g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7020 gst_rtspsrc_get_float (const gchar * dstr)
7022 gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7024 /* canonicalise floating point string so we can handle float strings
7025 * in the form "24.930" or "24,930" irrespective of the current locale */
7026 g_strlcpy (s, dstr, sizeof (s));
7027 g_strdelimit (s, ",", '.');
7028 return g_ascii_strtod (s, NULL);
7032 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7034 gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7036 if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7037 g_strlcpy (val_str, "now", sizeof (val_str));
7039 if (segment->position == 0) {
7040 g_strlcpy (val_str, "0", sizeof (val_str));
7042 g_ascii_dtostr (val_str, sizeof (val_str),
7043 ((gdouble) segment->position) / GST_SECOND);
7046 return g_strdup_printf ("npt=%s-", val_str);
7050 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7054 stream->timebase = -1;
7055 stream->seqbase = -1;
7057 len = stream->ptmap->len;
7058 for (i = 0; i < len; i++) {
7059 PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7062 if (item->caps == NULL)
7065 item->caps = gst_caps_make_writable (item->caps);
7066 s = gst_caps_get_structure (item->caps, 0);
7067 gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7071 static GstRTSPResult
7072 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7074 GstRTSPResult res = GST_RTSP_OK;
7076 if (src->state < GST_RTSP_STATE_READY) {
7077 res = GST_RTSP_ERROR;
7078 if (src->open_error) {
7079 GST_DEBUG_OBJECT (src, "the stream was in error");
7083 gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7085 if ((res = gst_rtspsrc_open (src, async)) < 0) {
7086 GST_DEBUG_OBJECT (src, "failed to open stream");
7095 static GstRTSPResult
7096 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
7098 GstRTSPMessage request = { 0 };
7099 GstRTSPMessage response = { 0 };
7100 GstRTSPResult res = GST_RTSP_OK;
7104 const gchar *control;
7106 GST_DEBUG_OBJECT (src, "PLAY...");
7108 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7111 if (!(src->methods & GST_RTSP_PLAY))
7114 if (src->state == GST_RTSP_STATE_PLAYING)
7117 if (!src->conninfo.connection || !src->conninfo.connected)
7120 /* send some dummy packets before we activate the receive in the
7122 gst_rtspsrc_send_dummy_packets (src);
7124 /* require new SR packets */
7126 g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7128 gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7130 /* construct a control url */
7131 control = get_aggregate_control (src);
7133 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7134 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7135 const gchar *setup_url;
7136 GstRTSPConnection *conn;
7138 /* try aggregate control first but do non-aggregate control otherwise */
7140 setup_url = control;
7141 else if ((setup_url = stream->conninfo.location) == NULL)
7144 if (src->conninfo.connection) {
7145 conn = src->conninfo.connection;
7146 } else if (stream->conninfo.connection) {
7147 conn = stream->conninfo.connection;
7153 res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
7155 goto create_request_failed;
7157 if (src->need_range) {
7158 hval = gen_range_header (src, segment);
7160 gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7162 /* store the newsegment event so it can be sent from the streaming thread. */
7163 if (src->start_segment)
7164 gst_event_unref (src->start_segment);
7165 src->start_segment = gst_event_new_segment (&src->segment);
7168 if (segment->rate != 1.0) {
7169 gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7171 g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7173 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7175 gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7179 GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7181 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7184 /* seek may have silently failed as it is not supported */
7185 if (!(src->methods & GST_RTSP_PLAY)) {
7186 GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7187 /* obviously it is supported as we made it here */
7188 src->methods |= GST_RTSP_PLAY;
7189 src->seekable = FALSE;
7190 /* but there is nothing to parse in the response,
7191 * so convey we have no idea and not to expect anything particular */
7192 clear_rtp_base (src, stream);
7196 /* need to do for all streams */
7197 for (run = src->streams; run; run = g_list_next (run))
7198 clear_rtp_base (src, (GstRTSPStream *) run->data);
7200 /* NOTE the above also disables npt based eos detection */
7201 /* and below forces position to 0,
7202 * which is visible feedback we lost the plot */
7203 segment->start = segment->position = src->last_pos;
7206 gst_rtsp_message_unset (&request);
7208 /* parse RTP npt field. This is the current position in the stream (Normal
7209 * Play Time) and should be put in the NEWSEGMENT position field. */
7210 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7212 gst_rtspsrc_parse_range (src, hval, segment);
7214 /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7215 segment->rate = 1.0;
7217 /* parse Speed header. This is the intended playback rate of the stream
7218 * and should be put in the NEWSEGMENT rate field. */
7219 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7220 0) == GST_RTSP_OK) {
7221 segment->rate = gst_rtspsrc_get_float (hval);
7222 } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7223 &hval, 0) == GST_RTSP_OK) {
7224 segment->rate = gst_rtspsrc_get_float (hval);
7227 /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7228 * for the RTP packets. If this is not present, we assume all starts from 0...
7229 * This is info for the RTP session manager that we pass to it in caps. */
7231 while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7232 &hval, hval_idx++) == GST_RTSP_OK)
7233 gst_rtspsrc_parse_rtpinfo (src, hval);
7235 /* some servers indicate RTCP parameters in PLAY response,
7236 * rather than properly in SDP */
7237 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7238 &hval, 0) == GST_RTSP_OK)
7239 gst_rtspsrc_handle_rtcp_interval (src, hval);
7241 gst_rtsp_message_unset (&response);
7243 /* early exit when we did aggregate control */
7247 /* configure the caps of the streams after we parsed all headers. Only reset
7248 * the manager object when we set a new Range header (we did a seek) */
7249 gst_rtspsrc_configure_caps (src, segment, src->need_range);
7251 /* set again when needed */
7252 src->need_range = FALSE;
7254 src->running = TRUE;
7255 src->base_time = -1;
7256 src->state = GST_RTSP_STATE_PLAYING;
7259 GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7260 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7261 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7262 stream->discont = TRUE;
7267 gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7274 GST_DEBUG_OBJECT (src, "failed to open stream");
7279 GST_DEBUG_OBJECT (src, "PLAY is not supported");
7284 GST_DEBUG_OBJECT (src, "we were already PLAYING");
7287 create_request_failed:
7289 gchar *str = gst_rtsp_strresult (res);
7291 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7292 ("Could not create request. (%s)", str));
7298 gchar *str = gst_rtsp_strresult (res);
7300 gst_rtsp_message_unset (&request);
7301 if (res != GST_RTSP_EINTR) {
7302 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7303 ("Could not send message. (%s)", str));
7305 GST_WARNING_OBJECT (src, "PLAY interrupted");
7312 static GstRTSPResult
7313 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7315 GstRTSPResult res = GST_RTSP_OK;
7316 GstRTSPMessage request = { 0 };
7317 GstRTSPMessage response = { 0 };
7319 const gchar *control;
7321 GST_DEBUG_OBJECT (src, "PAUSE...");
7323 if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7326 if (!(src->methods & GST_RTSP_PAUSE))
7329 if (src->state == GST_RTSP_STATE_READY)
7332 if (!src->conninfo.connection || !src->conninfo.connected)
7335 /* construct a control url */
7336 control = get_aggregate_control (src);
7338 /* loop over the streams. We might exit the loop early when we could do an
7339 * aggregate control */
7340 for (walk = src->streams; walk; walk = g_list_next (walk)) {
7341 GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7342 GstRTSPConnection *conn;
7343 const gchar *setup_url;
7345 /* try aggregate control first but do non-aggregate control otherwise */
7347 setup_url = control;
7348 else if ((setup_url = stream->conninfo.location) == NULL)
7351 if (src->conninfo.connection) {
7352 conn = src->conninfo.connection;
7353 } else if (stream->conninfo.connection) {
7354 conn = stream->conninfo.connection;
7360 GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7361 ("Sending PAUSE request"));
7364 gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
7366 goto create_request_failed;
7368 if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7371 gst_rtsp_message_unset (&request);
7372 gst_rtsp_message_unset (&response);
7374 /* exit early when we did agregate control */
7379 /* change element states now */
7380 gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7383 src->state = GST_RTSP_STATE_READY;
7387 gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7394 GST_DEBUG_OBJECT (src, "failed to open stream");
7399 GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7404 GST_DEBUG_OBJECT (src, "we were already PAUSED");
7407 create_request_failed:
7409 gchar *str = gst_rtsp_strresult (res);
7411 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7412 ("Could not create request. (%s)", str));
7418 gchar *str = gst_rtsp_strresult (res);
7420 gst_rtsp_message_unset (&request);
7421 if (res != GST_RTSP_EINTR) {
7422 GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7423 ("Could not send message. (%s)", str));
7425 GST_WARNING_OBJECT (src, "PAUSE interrupted");
7433 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
7435 GstRTSPSrc *rtspsrc;
7437 rtspsrc = GST_RTSPSRC (bin);
7439 switch (GST_MESSAGE_TYPE (message)) {
7440 case GST_MESSAGE_EOS:
7441 gst_message_unref (message);
7443 case GST_MESSAGE_ELEMENT:
7445 const GstStructure *s = gst_message_get_structure (message);
7447 if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
7448 gboolean ignore_timeout;
7450 GST_DEBUG_OBJECT (bin, "timeout on UDP port");
7452 GST_OBJECT_LOCK (rtspsrc);
7453 ignore_timeout = rtspsrc->ignore_timeout;
7454 rtspsrc->ignore_timeout = TRUE;
7455 GST_OBJECT_UNLOCK (rtspsrc);
7457 /* we only act on the first udp timeout message, others are irrelevant
7458 * and can be ignored. */
7459 if (!ignore_timeout)
7460 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
7462 gst_message_unref (message);
7465 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7468 case GST_MESSAGE_ERROR:
7471 GstRTSPStream *stream;
7474 udpsrc = GST_MESSAGE_SRC (message);
7476 GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
7477 GST_ELEMENT_NAME (udpsrc));
7479 stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
7483 /* we ignore the RTCP udpsrc */
7484 if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
7487 /* if we get error messages from the udp sources, that's not a problem as
7488 * long as not all of them error out. We also don't really know what the
7489 * problem is, the message does not give enough detail... */
7490 ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
7491 GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7492 if (ret != GST_FLOW_OK)
7496 gst_message_unref (message);
7500 /* fatal but not our message, forward */
7501 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7506 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7512 /* the thread where everything happens */
7514 gst_rtspsrc_thread (GstRTSPSrc * src)
7518 GST_OBJECT_LOCK (src);
7519 cmd = src->pending_cmd;
7520 if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7521 || cmd == CMD_LOOP || cmd == CMD_OPEN)
7522 src->pending_cmd = CMD_LOOP;
7524 src->pending_cmd = CMD_WAIT;
7525 GST_DEBUG_OBJECT (src, "got command %d", cmd);
7527 /* we got the message command, so ensure communication is possible again */
7528 gst_rtspsrc_connection_flush (src, FALSE);
7530 src->busy_cmd = cmd;
7531 GST_OBJECT_UNLOCK (src);
7535 gst_rtspsrc_open (src, TRUE);
7538 gst_rtspsrc_play (src, &src->segment, TRUE);
7541 gst_rtspsrc_pause (src, TRUE);
7544 gst_rtspsrc_close (src, TRUE, FALSE);
7547 gst_rtspsrc_loop (src);
7550 gst_rtspsrc_reconnect (src, FALSE);
7556 GST_OBJECT_LOCK (src);
7557 /* and go back to sleep */
7558 if (src->pending_cmd == CMD_WAIT) {
7560 gst_task_pause (src->task);
7563 src->busy_cmd = CMD_WAIT;
7564 GST_OBJECT_UNLOCK (src);
7568 gst_rtspsrc_start (GstRTSPSrc * src)
7570 GST_DEBUG_OBJECT (src, "starting");
7572 GST_OBJECT_LOCK (src);
7574 src->pending_cmd = CMD_WAIT;
7576 if (src->task == NULL) {
7577 src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
7578 if (src->task == NULL)
7581 gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
7583 GST_OBJECT_UNLOCK (src);
7590 GST_OBJECT_UNLOCK (src);
7591 GST_ERROR_OBJECT (src, "failed to create task");
7597 gst_rtspsrc_stop (GstRTSPSrc * src)
7601 GST_DEBUG_OBJECT (src, "stopping");
7603 /* also cancels pending task */
7604 gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
7606 GST_OBJECT_LOCK (src);
7607 if ((task = src->task)) {
7609 GST_OBJECT_UNLOCK (src);
7611 gst_task_stop (task);
7613 /* make sure it is not running */
7614 GST_RTSP_STREAM_LOCK (src);
7615 GST_RTSP_STREAM_UNLOCK (src);
7617 /* now wait for the task to finish */
7618 gst_task_join (task);
7620 /* and free the task */
7621 gst_object_unref (GST_OBJECT (task));
7623 GST_OBJECT_LOCK (src);
7625 GST_OBJECT_UNLOCK (src);
7627 /* ensure synchronously all is closed and clean */
7628 gst_rtspsrc_close (src, FALSE, TRUE);
7633 static GstStateChangeReturn
7634 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
7636 GstRTSPSrc *rtspsrc;
7637 GstStateChangeReturn ret;
7639 rtspsrc = GST_RTSPSRC (element);
7641 switch (transition) {
7642 case GST_STATE_CHANGE_NULL_TO_READY:
7643 if (!gst_rtspsrc_start (rtspsrc))
7646 case GST_STATE_CHANGE_READY_TO_PAUSED:
7647 /* init some state */
7648 rtspsrc->cur_protocols = rtspsrc->protocols;
7649 /* first attempt, don't ignore timeouts */
7650 rtspsrc->ignore_timeout = FALSE;
7651 rtspsrc->open_error = FALSE;
7652 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
7654 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7655 set_manager_buffer_mode (rtspsrc);
7657 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7658 /* unblock the tcp tasks and make the loop waiting */
7659 if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
7660 /* make sure it is waiting before we send PAUSE or PLAY below */
7661 GST_RTSP_STREAM_LOCK (rtspsrc);
7662 GST_RTSP_STREAM_UNLOCK (rtspsrc);
7665 case GST_STATE_CHANGE_PAUSED_TO_READY:
7671 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7672 if (ret == GST_STATE_CHANGE_FAILURE)
7675 switch (transition) {
7676 case GST_STATE_CHANGE_NULL_TO_READY:
7677 ret = GST_STATE_CHANGE_SUCCESS;
7679 case GST_STATE_CHANGE_READY_TO_PAUSED:
7680 ret = GST_STATE_CHANGE_NO_PREROLL;
7682 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7683 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7684 ret = GST_STATE_CHANGE_SUCCESS;
7686 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7687 /* send pause request and keep the idle task around */
7688 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7689 ret = GST_STATE_CHANGE_NO_PREROLL;
7691 case GST_STATE_CHANGE_PAUSED_TO_READY:
7692 gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7693 ret = GST_STATE_CHANGE_SUCCESS;
7695 case GST_STATE_CHANGE_READY_TO_NULL:
7696 gst_rtspsrc_stop (rtspsrc);
7697 ret = GST_STATE_CHANGE_SUCCESS;
7708 GST_DEBUG_OBJECT (rtspsrc, "start failed");
7709 return GST_STATE_CHANGE_FAILURE;
7714 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7717 GstRTSPSrc *rtspsrc;
7719 rtspsrc = GST_RTSPSRC (element);
7721 if (GST_EVENT_IS_DOWNSTREAM (event)) {
7722 res = gst_rtspsrc_push_event (rtspsrc, event);
7724 res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7731 /*** GSTURIHANDLER INTERFACE *************************************************/
7734 gst_rtspsrc_uri_get_type (GType type)
7739 static const gchar *const *
7740 gst_rtspsrc_uri_get_protocols (GType type)
7742 static const gchar *protocols[] =
7743 { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7744 "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7751 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7753 GstRTSPSrc *src = GST_RTSPSRC (handler);
7755 /* FIXME: make thread-safe */
7756 return g_strdup (src->conninfo.location);
7760 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7765 GstRTSPUrl *newurl = NULL;
7766 GstSDPMessage *sdp = NULL;
7768 src = GST_RTSPSRC (handler);
7770 /* same URI, we're fine */
7771 if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7774 if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7775 if ((res = gst_sdp_message_new (&sdp) < 0))
7778 GST_DEBUG_OBJECT (src, "parsing SDP message");
7779 if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7783 GST_DEBUG_OBJECT (src, "parsing URI");
7784 if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7788 /* if worked, free previous and store new url object along with the original
7790 GST_DEBUG_OBJECT (src, "configuring URI");
7791 g_free (src->conninfo.location);
7792 src->conninfo.location = g_strdup (uri);
7793 gst_rtsp_url_free (src->conninfo.url);
7794 src->conninfo.url = newurl;
7795 g_free (src->conninfo.url_str);
7797 src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7799 src->conninfo.url_str = NULL;
7802 gst_sdp_message_free (src->sdp);
7804 src->from_sdp = sdp != NULL;
7806 GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7807 GST_DEBUG_OBJECT (src, "request uri is: %s",
7808 GST_STR_NULL (src->conninfo.url_str));
7815 GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7820 GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7821 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7822 "Could not create SDP");
7827 GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7828 GST_STR_NULL (uri));
7829 gst_sdp_message_free (sdp);
7830 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7836 GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7837 GST_STR_NULL (uri), res);
7838 g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7839 "Invalid RTSP URI");
7845 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7847 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7849 iface->get_type = gst_rtspsrc_uri_get_type;
7850 iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7851 iface->get_uri = gst_rtspsrc_uri_get_uri;
7852 iface->set_uri = gst_rtspsrc_uri_set_uri;