rtspsrc: answer URI query
[platform/upstream/gstreamer.git] / gst / rtsp / gstrtspsrc.c
1 /* GStreamer
2  * Copyright (C) <2005,2006> Wim Taymans <wim at fluendo dot com>
3  *               <2006> Lutz Mueller <lutz at topfrose dot de>
4  *
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.
9  *
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.
14  *
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., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20 /*
21  * Unless otherwise indicated, Source Code is licensed under MIT license.
22  * See further explanation attached in License Statement (distributed in the file
23  * LICENSE).
24  *
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:
31  *
32  * The above copyright notice and this permission notice shall be included in all
33  * copies or substantial portions of the Software.
34  *
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
41  * SOFTWARE.
42  */
43 /**
44  * SECTION:element-rtspsrc
45  *
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.
49  *
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.
54  *
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
59  * element.
60  *
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.
65  *
66  * rtspsrc acts like a live source and will therefore only generate data in the
67  * PLAYING state.
68  *
69  * <refsect2>
70  * <title>Example launch line</title>
71  * |[
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
74  * fakesink.
75  * </refsect2>
76  *
77  * Last reviewed on 2006-08-18 (0.10.5)
78  */
79
80 #ifdef HAVE_CONFIG_H
81 #include "config.h"
82 #endif
83
84 #ifdef HAVE_UNISTD_H
85 #include <unistd.h>
86 #endif /* HAVE_UNISTD_H */
87 #include <stdlib.h>
88 #include <string.h>
89 #include <locale.h>
90 #include <stdio.h>
91 #include <stdarg.h>
92
93 #include <gst/sdp/gstsdpmessage.h>
94 #include <gst/rtp/gstrtppayloads.h>
95
96 #include "gst/gst-i18n-plugin.h"
97
98 #include "gstrtspsrc.h"
99
100 GST_DEBUG_CATEGORY_STATIC (rtspsrc_debug);
101 #define GST_CAT_DEFAULT (rtspsrc_debug)
102
103 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream_%u",
104     GST_PAD_SRC,
105     GST_PAD_SOMETIMES,
106     GST_STATIC_CAPS ("application/x-rtp; application/x-rdt"));
107
108 /* templates used internally */
109 static GstStaticPadTemplate anysrctemplate =
110 GST_STATIC_PAD_TEMPLATE ("internalsrc_%u",
111     GST_PAD_SRC,
112     GST_PAD_SOMETIMES,
113     GST_STATIC_CAPS_ANY);
114
115 static GstStaticPadTemplate anysinktemplate =
116 GST_STATIC_PAD_TEMPLATE ("internalsink_%u",
117     GST_PAD_SINK,
118     GST_PAD_SOMETIMES,
119     GST_STATIC_CAPS_ANY);
120
121 enum
122 {
123   /* FILL ME */
124   LAST_SIGNAL
125 };
126
127 enum _GstRtspSrcRtcpSyncMode
128 {
129   RTCP_SYNC_ALWAYS,
130   RTCP_SYNC_INITIAL,
131   RTCP_SYNC_RTP
132 };
133
134 enum _GstRtspSrcBufferMode
135 {
136   BUFFER_MODE_NONE,
137   BUFFER_MODE_SLAVE,
138   BUFFER_MODE_BUFFER,
139   BUFFER_MODE_AUTO
140 };
141
142 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
143 static GType
144 gst_rtsp_src_buffer_mode_get_type (void)
145 {
146   static GType buffer_mode_type = 0;
147   static const GEnumValue buffer_modes[] = {
148     {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
149     {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
150     {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
151     {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
152     {0, NULL, NULL},
153   };
154
155   if (!buffer_mode_type) {
156     buffer_mode_type =
157         g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
158   }
159   return buffer_mode_type;
160 }
161
162 #define DEFAULT_LOCATION         NULL
163 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
164 #define DEFAULT_DEBUG            FALSE
165 #define DEFAULT_RETRY            20
166 #define DEFAULT_TIMEOUT          5000000
167 #define DEFAULT_UDP_BUFFER_SIZE  0x80000
168 #define DEFAULT_TCP_TIMEOUT      20000000
169 #define DEFAULT_LATENCY_MS       2000
170 #define DEFAULT_DROP_ON_LATENCY  FALSE
171 #define DEFAULT_CONNECTION_SPEED 0
172 #define DEFAULT_NAT_METHOD       GST_RTSP_NAT_DUMMY
173 #define DEFAULT_DO_RTCP          TRUE
174 #define DEFAULT_DO_RTSP_KEEP_ALIVE       TRUE
175 #define DEFAULT_PROXY            NULL
176 #define DEFAULT_RTP_BLOCKSIZE    0
177 #define DEFAULT_USER_ID          NULL
178 #define DEFAULT_USER_PW          NULL
179 #define DEFAULT_BUFFER_MODE      BUFFER_MODE_AUTO
180 #define DEFAULT_PORT_RANGE       NULL
181 #define DEFAULT_SHORT_HEADER     FALSE
182 #define DEFAULT_PROBATION        2
183
184 enum
185 {
186   PROP_0,
187   PROP_LOCATION,
188   PROP_PROTOCOLS,
189   PROP_DEBUG,
190   PROP_RETRY,
191   PROP_TIMEOUT,
192   PROP_TCP_TIMEOUT,
193   PROP_LATENCY,
194   PROP_DROP_ON_LATENCY,
195   PROP_CONNECTION_SPEED,
196   PROP_NAT_METHOD,
197   PROP_DO_RTCP,
198   PROP_DO_RTSP_KEEP_ALIVE,
199   PROP_PROXY,
200   PROP_RTP_BLOCKSIZE,
201   PROP_USER_ID,
202   PROP_USER_PW,
203   PROP_BUFFER_MODE,
204   PROP_PORT_RANGE,
205   PROP_UDP_BUFFER_SIZE,
206   PROP_SHORT_HEADER,
207   PROP_PROBATION,
208   PROP_LAST
209 };
210
211 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
212 static GType
213 gst_rtsp_nat_method_get_type (void)
214 {
215   static GType rtsp_nat_method_type = 0;
216   static const GEnumValue rtsp_nat_method[] = {
217     {GST_RTSP_NAT_NONE, "None", "none"},
218     {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
219     {0, NULL, NULL},
220   };
221
222   if (!rtsp_nat_method_type) {
223     rtsp_nat_method_type =
224         g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
225   }
226   return rtsp_nat_method_type;
227 }
228
229 static void gst_rtspsrc_finalize (GObject * object);
230
231 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
232     const GValue * value, GParamSpec * pspec);
233 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
234     GValue * value, GParamSpec * pspec);
235
236 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
237     gpointer iface_data);
238
239 static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
240     GstCaps * caps);
241
242 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
243 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
244
245 static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
246
247 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
248     GstStateChange transition);
249 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
250 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
251
252 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
253     GstRTSPMessage * response);
254
255 static void gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask);
256 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
257     GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
258
259 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
260 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
261     gboolean async);
262 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
263 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
264     gboolean only_close);
265
266 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
267     const gchar * uri, GError ** error);
268 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
269
270 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
271 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
272 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
273     GstRTSPStream * stream, GstEvent * event);
274 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
275
276 /* commands we send to out loop to notify it of events */
277 #define CMD_OPEN        (1 << 0)
278 #define CMD_PLAY        (1 << 1)
279 #define CMD_PAUSE       (1 << 2)
280 #define CMD_CLOSE       (1 << 3)
281 #define CMD_WAIT        (1 << 4)
282 #define CMD_RECONNECT   (1 << 5)
283 #define CMD_LOOP        (1 << 6)
284
285 #define GST_ELEMENT_PROGRESS(el, type, code, text)      \
286 G_STMT_START {                                          \
287   gchar *__txt = _gst_element_error_printf text;        \
288   gst_element_post_message (GST_ELEMENT_CAST (el),      \
289       gst_message_new_progress (GST_OBJECT_CAST (el),   \
290           GST_PROGRESS_TYPE_ ##type, code, __txt));     \
291   g_free (__txt);                                       \
292 } G_STMT_END
293
294 /*static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 }; */
295 #define gst_rtspsrc_parent_class parent_class
296 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
297     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
298
299 static void
300 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
301 {
302   GObjectClass *gobject_class;
303   GstElementClass *gstelement_class;
304   GstBinClass *gstbin_class;
305
306   gobject_class = (GObjectClass *) klass;
307   gstelement_class = (GstElementClass *) klass;
308   gstbin_class = (GstBinClass *) klass;
309
310   GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
311
312   gobject_class->set_property = gst_rtspsrc_set_property;
313   gobject_class->get_property = gst_rtspsrc_get_property;
314
315   gobject_class->finalize = gst_rtspsrc_finalize;
316
317   g_object_class_install_property (gobject_class, PROP_LOCATION,
318       g_param_spec_string ("location", "RTSP Location",
319           "Location of the RTSP url to read",
320           DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
321
322   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
323       g_param_spec_flags ("protocols", "Protocols",
324           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
325           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
326
327   g_object_class_install_property (gobject_class, PROP_DEBUG,
328       g_param_spec_boolean ("debug", "Debug",
329           "Dump request and response messages to stdout",
330           DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331
332   g_object_class_install_property (gobject_class, PROP_RETRY,
333       g_param_spec_uint ("retry", "Retry",
334           "Max number of retries when allocating RTP ports.",
335           0, G_MAXUINT16, DEFAULT_RETRY,
336           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
337
338   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
339       g_param_spec_uint64 ("timeout", "Timeout",
340           "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
341           0, G_MAXUINT64, DEFAULT_TIMEOUT,
342           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
343
344   g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
345       g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
346           "Fail after timeout microseconds on TCP connections (0 = disabled)",
347           0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
348           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
349
350   g_object_class_install_property (gobject_class, PROP_LATENCY,
351       g_param_spec_uint ("latency", "Buffer latency in ms",
352           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
353           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
354
355   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
356       g_param_spec_boolean ("drop-on-latency",
357           "Drop buffers when maximum latency is reached",
358           "Tells the jitterbuffer to never exceed the given latency in size",
359           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
360
361   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
362       g_param_spec_uint64 ("connection-speed", "Connection Speed",
363           "Network connection speed in kbps (0 = unknown)",
364           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
365           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
366
367   g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
368       g_param_spec_enum ("nat-method", "NAT Method",
369           "Method to use for traversing firewalls and NAT",
370           GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
371           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
372
373   /**
374    * GstRTSPSrc::do-rtcp
375    *
376    * Enable RTCP support. Some old server don't like RTCP and then this property
377    * needs to be set to FALSE.
378    *
379    * Since: 0.10.15
380    */
381   g_object_class_install_property (gobject_class, PROP_DO_RTCP,
382       g_param_spec_boolean ("do-rtcp", "Do RTCP",
383           "Send RTCP packets, disable for old incompatible server.",
384           DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
385
386   /**
387    * GstRTSPSrc::do-rtsp-keep-alive
388    *
389    * Enable RTSP keep laive support. Some old server don't like RTSP
390    * keep alive and then this property needs to be set to FALSE.
391    *
392    * Since: 0.10.32
393    */
394   g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
395       g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
396           "Send RTSP keep alive packets, disable for old incompatible server.",
397           DEFAULT_DO_RTSP_KEEP_ALIVE,
398           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
399
400   /**
401    * GstRTSPSrc::proxy
402    *
403    * Set the proxy parameters. This has to be a string of the format
404    * [http://][user:passwd@]host[:port].
405    *
406    * Since: 0.10.15
407    */
408   g_object_class_install_property (gobject_class, PROP_PROXY,
409       g_param_spec_string ("proxy", "Proxy",
410           "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
411           DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
412
413   /**
414    * GstRTSPSrc::rtp_blocksize
415    *
416    * RTP package size to suggest to server.
417    *
418    * Since: 0.10.16
419    */
420   g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
421       g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
422           "RTP package size to suggest to server (0 = disabled)",
423           0, 65536, DEFAULT_RTP_BLOCKSIZE,
424           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
425
426   g_object_class_install_property (gobject_class,
427       PROP_USER_ID,
428       g_param_spec_string ("user-id", "user-id",
429           "RTSP location URI user id for authentication", DEFAULT_USER_ID,
430           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
431   g_object_class_install_property (gobject_class, PROP_USER_PW,
432       g_param_spec_string ("user-pw", "user-pw",
433           "RTSP location URI user password for authentication", DEFAULT_USER_PW,
434           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
435
436   /**
437    * GstRTSPSrc::buffer-mode:
438    *
439    * Control the buffering and timestamping mode used by the jitterbuffer.
440    *
441    * Since: 0.10.22
442    */
443   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
444       g_param_spec_enum ("buffer-mode", "Buffer Mode",
445           "Control the buffering algorithm in use",
446           GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
447           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
448
449   /**
450    * GstRTSPSrc::port-range:
451    *
452    * Configure the client port numbers that can be used to recieve RTP and
453    * RTCP.
454    *
455    * Since: 0.10.25
456    */
457   g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
458       g_param_spec_string ("port-range", "Port range",
459           "Client port range that can be used to receive RTP and RTCP data, "
460           "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
461           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
462
463   /**
464    * GstRTSPSrc::udp-buffer-size:
465    *
466    * Size of the kernel UDP receive buffer in bytes.
467    *
468    * Since: 0.10.26
469    */
470   g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
471       g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
472           "Size of the kernel UDP receive buffer in bytes, 0=default",
473           0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
474           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
475
476   /**
477    * GstRTSPSrc::short-header:
478    *
479    * Only send the basic RTSP headers for broken encoders.
480    *
481    * Since: 0.10.31
482    */
483   g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
484       g_param_spec_boolean ("short-header", "Short Header",
485           "Only send the basic RTSP headers for broken encoders",
486           DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
487
488   g_object_class_install_property (gobject_class, PROP_PROBATION,
489       g_param_spec_uint ("probation", "Number of probations",
490           "Consecutive packet sequence numbers to accept the source",
491           0, G_MAXUINT, DEFAULT_PROBATION,
492           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
493
494   gstelement_class->send_event = gst_rtspsrc_send_event;
495   gstelement_class->change_state = gst_rtspsrc_change_state;
496
497   gst_element_class_add_pad_template (gstelement_class,
498       gst_static_pad_template_get (&rtptemplate));
499
500   gst_element_class_set_static_metadata (gstelement_class,
501       "RTSP packet receiver", "Source/Network",
502       "Receive data over the network via RTSP (RFC 2326)",
503       "Wim Taymans <wim@fluendo.com>, "
504       "Thijs Vermeir <thijs.vermeir@barco.com>, "
505       "Lutz Mueller <lutz@topfrose.de>");
506
507   gstbin_class->handle_message = gst_rtspsrc_handle_message;
508
509   gst_rtsp_ext_list_init ();
510 }
511
512
513 static void
514 gst_rtspsrc_init (GstRTSPSrc * src)
515 {
516   src->conninfo.location = g_strdup (DEFAULT_LOCATION);
517   src->protocols = DEFAULT_PROTOCOLS;
518   src->debug = DEFAULT_DEBUG;
519   src->retry = DEFAULT_RETRY;
520   src->udp_timeout = DEFAULT_TIMEOUT;
521   gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
522   src->latency = DEFAULT_LATENCY_MS;
523   src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
524   src->connection_speed = DEFAULT_CONNECTION_SPEED;
525   src->nat_method = DEFAULT_NAT_METHOD;
526   src->do_rtcp = DEFAULT_DO_RTCP;
527   src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
528   gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
529   src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
530   src->user_id = g_strdup (DEFAULT_USER_ID);
531   src->user_pw = g_strdup (DEFAULT_USER_PW);
532   src->buffer_mode = DEFAULT_BUFFER_MODE;
533   src->client_port_range.min = 0;
534   src->client_port_range.max = 0;
535   src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
536   src->short_header = DEFAULT_SHORT_HEADER;
537   src->probation = DEFAULT_PROBATION;
538
539   /* get a list of all extensions */
540   src->extensions = gst_rtsp_ext_list_get ();
541
542   /* connect to send signal */
543   gst_rtsp_ext_list_connect (src->extensions, "send",
544       (GCallback) gst_rtspsrc_send_cb, src);
545
546   /* protects the streaming thread in interleaved mode or the polling
547    * thread in UDP mode. */
548   g_rec_mutex_init (&src->stream_rec_lock);
549
550   /* protects our state changes from multiple invocations */
551   g_rec_mutex_init (&src->state_rec_lock);
552
553   src->state = GST_RTSP_STATE_INVALID;
554
555   GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
556 }
557
558 static void
559 gst_rtspsrc_finalize (GObject * object)
560 {
561   GstRTSPSrc *rtspsrc;
562
563   rtspsrc = GST_RTSPSRC (object);
564
565   gst_rtsp_ext_list_free (rtspsrc->extensions);
566   g_free (rtspsrc->conninfo.location);
567   gst_rtsp_url_free (rtspsrc->conninfo.url);
568   g_free (rtspsrc->conninfo.url_str);
569   g_free (rtspsrc->user_id);
570   g_free (rtspsrc->user_pw);
571
572   if (rtspsrc->sdp) {
573     gst_sdp_message_free (rtspsrc->sdp);
574     rtspsrc->sdp = NULL;
575   }
576
577   /* free locks */
578   g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
579   g_rec_mutex_clear (&rtspsrc->state_rec_lock);
580
581   G_OBJECT_CLASS (parent_class)->finalize (object);
582 }
583
584 /* a proxy string of the format [user:passwd@]host[:port] */
585 static gboolean
586 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
587 {
588   gchar *p, *at, *col;
589
590   g_free (rtsp->proxy_user);
591   rtsp->proxy_user = NULL;
592   g_free (rtsp->proxy_passwd);
593   rtsp->proxy_passwd = NULL;
594   g_free (rtsp->proxy_host);
595   rtsp->proxy_host = NULL;
596   rtsp->proxy_port = 0;
597
598   p = (gchar *) proxy;
599
600   if (p == NULL)
601     return TRUE;
602
603   /* we allow http:// in front but ignore it */
604   if (g_str_has_prefix (p, "http://"))
605     p += 7;
606
607   at = strchr (p, '@');
608   if (at) {
609     /* look for user:passwd */
610     col = strchr (proxy, ':');
611     if (col == NULL || col > at)
612       return FALSE;
613
614     rtsp->proxy_user = g_strndup (p, col - p);
615     col++;
616     rtsp->proxy_passwd = g_strndup (col, at - col);
617
618     /* move to host */
619     p = at + 1;
620   }
621   col = strchr (p, ':');
622
623   if (col) {
624     /* everything before the colon is the hostname */
625     rtsp->proxy_host = g_strndup (p, col - p);
626     p = col + 1;
627     rtsp->proxy_port = strtoul (p, (char **) &p, 10);
628   } else {
629     rtsp->proxy_host = g_strdup (p);
630     rtsp->proxy_port = 8080;
631   }
632   return TRUE;
633 }
634
635 static void
636 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
637 {
638   rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
639   rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
640
641   if (timeout != 0)
642     rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
643   else
644     rtspsrc->ptcp_timeout = NULL;
645 }
646
647 static void
648 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
649     GParamSpec * pspec)
650 {
651   GstRTSPSrc *rtspsrc;
652
653   rtspsrc = GST_RTSPSRC (object);
654
655   switch (prop_id) {
656     case PROP_LOCATION:
657       gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
658           g_value_get_string (value), NULL);
659       break;
660     case PROP_PROTOCOLS:
661       rtspsrc->protocols = g_value_get_flags (value);
662       break;
663     case PROP_DEBUG:
664       rtspsrc->debug = g_value_get_boolean (value);
665       break;
666     case PROP_RETRY:
667       rtspsrc->retry = g_value_get_uint (value);
668       break;
669     case PROP_TIMEOUT:
670       rtspsrc->udp_timeout = g_value_get_uint64 (value);
671       break;
672     case PROP_TCP_TIMEOUT:
673       gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
674       break;
675     case PROP_LATENCY:
676       rtspsrc->latency = g_value_get_uint (value);
677       break;
678     case PROP_DROP_ON_LATENCY:
679       rtspsrc->drop_on_latency = g_value_get_boolean (value);
680       break;
681     case PROP_CONNECTION_SPEED:
682       rtspsrc->connection_speed = g_value_get_uint64 (value);
683       break;
684     case PROP_NAT_METHOD:
685       rtspsrc->nat_method = g_value_get_enum (value);
686       break;
687     case PROP_DO_RTCP:
688       rtspsrc->do_rtcp = g_value_get_boolean (value);
689       break;
690     case PROP_DO_RTSP_KEEP_ALIVE:
691       rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
692       break;
693     case PROP_PROXY:
694       gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
695       break;
696     case PROP_RTP_BLOCKSIZE:
697       rtspsrc->rtp_blocksize = g_value_get_uint (value);
698       break;
699     case PROP_USER_ID:
700       if (rtspsrc->user_id)
701         g_free (rtspsrc->user_id);
702       rtspsrc->user_id = g_value_dup_string (value);
703       break;
704     case PROP_USER_PW:
705       if (rtspsrc->user_pw)
706         g_free (rtspsrc->user_pw);
707       rtspsrc->user_pw = g_value_dup_string (value);
708       break;
709     case PROP_BUFFER_MODE:
710       rtspsrc->buffer_mode = g_value_get_enum (value);
711       break;
712     case PROP_PORT_RANGE:
713     {
714       const gchar *str;
715
716       str = g_value_get_string (value);
717       if (str) {
718         sscanf (str, "%u-%u",
719             &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
720       } else {
721         rtspsrc->client_port_range.min = 0;
722         rtspsrc->client_port_range.max = 0;
723       }
724       break;
725     }
726     case PROP_UDP_BUFFER_SIZE:
727       rtspsrc->udp_buffer_size = g_value_get_int (value);
728       break;
729     case PROP_SHORT_HEADER:
730       rtspsrc->short_header = g_value_get_boolean (value);
731       break;
732     case PROP_PROBATION:
733       rtspsrc->probation = g_value_get_uint (value);
734       break;
735     default:
736       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
737       break;
738   }
739 }
740
741 static void
742 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
743     GParamSpec * pspec)
744 {
745   GstRTSPSrc *rtspsrc;
746
747   rtspsrc = GST_RTSPSRC (object);
748
749   switch (prop_id) {
750     case PROP_LOCATION:
751       g_value_set_string (value, rtspsrc->conninfo.location);
752       break;
753     case PROP_PROTOCOLS:
754       g_value_set_flags (value, rtspsrc->protocols);
755       break;
756     case PROP_DEBUG:
757       g_value_set_boolean (value, rtspsrc->debug);
758       break;
759     case PROP_RETRY:
760       g_value_set_uint (value, rtspsrc->retry);
761       break;
762     case PROP_TIMEOUT:
763       g_value_set_uint64 (value, rtspsrc->udp_timeout);
764       break;
765     case PROP_TCP_TIMEOUT:
766     {
767       guint64 timeout;
768
769       timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
770           rtspsrc->tcp_timeout.tv_usec;
771       g_value_set_uint64 (value, timeout);
772       break;
773     }
774     case PROP_LATENCY:
775       g_value_set_uint (value, rtspsrc->latency);
776       break;
777     case PROP_DROP_ON_LATENCY:
778       g_value_set_boolean (value, rtspsrc->drop_on_latency);
779       break;
780     case PROP_CONNECTION_SPEED:
781       g_value_set_uint64 (value, rtspsrc->connection_speed);
782       break;
783     case PROP_NAT_METHOD:
784       g_value_set_enum (value, rtspsrc->nat_method);
785       break;
786     case PROP_DO_RTCP:
787       g_value_set_boolean (value, rtspsrc->do_rtcp);
788       break;
789     case PROP_DO_RTSP_KEEP_ALIVE:
790       g_value_set_boolean (value, rtspsrc->do_rtsp_keep_alive);
791       break;
792     case PROP_PROXY:
793     {
794       gchar *str;
795
796       if (rtspsrc->proxy_host) {
797         str =
798             g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
799       } else {
800         str = NULL;
801       }
802       g_value_take_string (value, str);
803       break;
804     }
805     case PROP_RTP_BLOCKSIZE:
806       g_value_set_uint (value, rtspsrc->rtp_blocksize);
807       break;
808     case PROP_USER_ID:
809       g_value_set_string (value, rtspsrc->user_id);
810       break;
811     case PROP_USER_PW:
812       g_value_set_string (value, rtspsrc->user_pw);
813       break;
814     case PROP_BUFFER_MODE:
815       g_value_set_enum (value, rtspsrc->buffer_mode);
816       break;
817     case PROP_PORT_RANGE:
818     {
819       gchar *str;
820
821       if (rtspsrc->client_port_range.min != 0) {
822         str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
823             rtspsrc->client_port_range.max);
824       } else {
825         str = NULL;
826       }
827       g_value_take_string (value, str);
828       break;
829     }
830     case PROP_UDP_BUFFER_SIZE:
831       g_value_set_int (value, rtspsrc->udp_buffer_size);
832       break;
833     case PROP_SHORT_HEADER:
834       g_value_set_boolean (value, rtspsrc->short_header);
835       break;
836     case PROP_PROBATION:
837       g_value_set_uint (value, rtspsrc->probation);
838       break;
839     default:
840       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
841       break;
842   }
843 }
844
845 static gint
846 find_stream_by_id (GstRTSPStream * stream, gint * id)
847 {
848   if (stream->id == *id)
849     return 0;
850
851   return -1;
852 }
853
854 static gint
855 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
856 {
857   if (stream->channel[0] == *channel || stream->channel[1] == *channel)
858     return 0;
859
860   return -1;
861 }
862
863 static gint
864 find_stream_by_pt (GstRTSPStream * stream, gint * pt)
865 {
866   if (stream->pt == *pt)
867     return 0;
868
869   return -1;
870 }
871
872 static gint
873 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
874 {
875   GstElement *src = (GstElement *) a;
876
877   if (stream->udpsrc[0] == src)
878     return 0;
879   if (stream->udpsrc[1] == src)
880     return 0;
881
882   return -1;
883 }
884
885 static gint
886 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
887 {
888   /* check qualified setup_url */
889   if (!strcmp (stream->conninfo.location, (gchar *) a))
890     return 0;
891   /* check original control_url */
892   if (!strcmp (stream->control_url, (gchar *) a))
893     return 0;
894
895   /* check if qualified setup_url ends with string */
896   if (g_str_has_suffix (stream->control_url, (gchar *) a))
897     return 0;
898
899   return -1;
900 }
901
902 static GstRTSPStream *
903 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
904 {
905   GList *lstream;
906
907   /* find and get stream */
908   if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
909     return (GstRTSPStream *) lstream->data;
910
911   return NULL;
912 }
913
914 static const GstSDPBandwidth *
915 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
916     const GstSDPMedia * media, const gchar * type)
917 {
918   guint i, len;
919
920   /* first look in the media specific section */
921   len = gst_sdp_media_bandwidths_len (media);
922   for (i = 0; i < len; i++) {
923     const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
924
925     if (strcmp (bw->bwtype, type) == 0)
926       return bw;
927   }
928   /* then look in the message specific section */
929   len = gst_sdp_message_bandwidths_len (sdp);
930   for (i = 0; i < len; i++) {
931     const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
932
933     if (strcmp (bw->bwtype, type) == 0)
934       return bw;
935   }
936   return NULL;
937 }
938
939 static void
940 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
941     const GstSDPMedia * media, GstRTSPStream * stream)
942 {
943   const GstSDPBandwidth *bw;
944
945   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
946     stream->as_bandwidth = bw->bandwidth;
947   else
948     stream->as_bandwidth = -1;
949
950   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
951     stream->rr_bandwidth = bw->bandwidth;
952   else
953     stream->rr_bandwidth = -1;
954
955   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
956     stream->rs_bandwidth = bw->bandwidth;
957   else
958     stream->rs_bandwidth = -1;
959 }
960
961 static void
962 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
963     const GstSDPConnection * conn)
964 {
965   if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
966     return;
967
968   if (conn->addrtype == NULL)
969     return;
970
971   /* check for IPV6 */
972   if (strcmp (conn->addrtype, "IP4") == 0)
973     stream->is_ipv6 = FALSE;
974   else if (strcmp (conn->addrtype, "IP6") == 0)
975     stream->is_ipv6 = TRUE;
976   else
977     return;
978
979   /* save address */
980   g_free (stream->destination);
981   stream->destination = g_strdup (conn->address);
982
983   /* check for multicast */
984   stream->is_multicast =
985       gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
986       conn->address);
987   stream->ttl = conn->ttl;
988 }
989
990 /* Go over the connections for a stream.
991  * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
992  *   receiving.
993  * - If we are dealing with a localhost address, we disable multicast
994  */
995 static void
996 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
997     const GstSDPMedia * media, GstRTSPStream * stream)
998 {
999   const GstSDPConnection *conn;
1000   guint i, len;
1001
1002   /* first look in the media specific section */
1003   len = gst_sdp_media_connections_len (media);
1004   for (i = 0; i < len; i++) {
1005     conn = gst_sdp_media_get_connection (media, i);
1006
1007     gst_rtspsrc_do_stream_connection (src, stream, conn);
1008   }
1009   /* then look in the message specific section */
1010   if ((conn = gst_sdp_message_get_connection (sdp))) {
1011     gst_rtspsrc_do_stream_connection (src, stream, conn);
1012   }
1013 }
1014
1015 static GstRTSPStream *
1016 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
1017 {
1018   GstRTSPStream *stream;
1019   const gchar *control_url;
1020   const gchar *payload;
1021   const GstSDPMedia *media;
1022
1023   /* get media, should not return NULL */
1024   media = gst_sdp_message_get_media (sdp, idx);
1025   if (media == NULL)
1026     return NULL;
1027
1028   stream = g_new0 (GstRTSPStream, 1);
1029   stream->parent = src;
1030   /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1031    * the element. */
1032   stream->last_ret = GST_FLOW_NOT_LINKED;
1033   stream->added = FALSE;
1034   stream->disabled = FALSE;
1035   stream->id = src->numstreams++;
1036   stream->eos = FALSE;
1037   stream->discont = TRUE;
1038   stream->seqbase = -1;
1039   stream->timebase = -1;
1040
1041   /* collect bandwidth information for this steam. FIXME, configure in the RTP
1042    * session manager to scale RTCP. */
1043   gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1044
1045   /* collect connection info */
1046   gst_rtspsrc_collect_connections (src, sdp, media, stream);
1047
1048   /* we must have a payload. No payload means we cannot create caps */
1049   /* FIXME, handle multiple formats. The problem here is that we just want to
1050    * take the first available format that we can handle but in order to do that
1051    * we need to scan for depayloader plugins. Scanning for payloader plugins is
1052    * also suboptimal because the user maybe just wants to save the raw stream
1053    * and then we don't care. */
1054   if ((payload = gst_sdp_media_get_format (media, 0))) {
1055     stream->pt = atoi (payload);
1056     /* convert caps */
1057     stream->caps = gst_rtspsrc_media_to_caps (stream->pt, media);
1058
1059     GST_DEBUG ("mapping sdp session level attributes to caps");
1060     gst_rtspsrc_sdp_attributes_to_caps (sdp->attributes, stream->caps);
1061     GST_DEBUG ("mapping sdp media level attributes to caps");
1062     gst_rtspsrc_sdp_attributes_to_caps (media->attributes, stream->caps);
1063
1064     if (stream->pt >= 96) {
1065       /* If we have a dynamic payload type, see if we have a stream with the
1066        * same payload number. If there is one, they are part of the same
1067        * container and we only need to add one pad. */
1068       if (find_stream (src, &stream->pt, (gpointer) find_stream_by_pt)) {
1069         stream->container = TRUE;
1070         GST_DEBUG ("found another stream with pt %d, marking as container",
1071             stream->pt);
1072       }
1073     }
1074   }
1075   /* collect port number */
1076   stream->port = gst_sdp_media_get_port (media);
1077
1078   /* get control url to construct the setup url. The setup url is used to
1079    * configure the transport of the stream and is used to identity the stream in
1080    * the RTP-Info header field returned from PLAY. */
1081   control_url = gst_sdp_media_get_attribute_val (media, "control");
1082   if (control_url == NULL)
1083     control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1084
1085   GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1086   GST_DEBUG_OBJECT (src, " pt: %d", stream->pt);
1087   GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1088   GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1089   GST_DEBUG_OBJECT (src, " caps: %" GST_PTR_FORMAT, stream->caps);
1090   GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1091
1092   if (control_url != NULL) {
1093     stream->control_url = g_strdup (control_url);
1094     /* Build a fully qualified url using the content_base if any or by prefixing
1095      * the original request.
1096      * If the control_url starts with a '/' or a non rtsp: protocol we will most
1097      * likely build a URL that the server will fail to understand, this is ok,
1098      * we will fail then. */
1099     if (g_str_has_prefix (control_url, "rtsp://"))
1100       stream->conninfo.location = g_strdup (control_url);
1101     else {
1102       const gchar *base;
1103       gboolean has_slash;
1104
1105       if (g_strcmp0 (control_url, "*") == 0)
1106         control_url = "";
1107
1108       if (src->control)
1109         base = src->control;
1110       else if (src->content_base)
1111         base = src->content_base;
1112       else if (src->conninfo.url_str)
1113         base = src->conninfo.url_str;
1114       else
1115         base = "/";
1116
1117       /* check if the base ends or control starts with / */
1118       has_slash = g_str_has_prefix (control_url, "/");
1119       has_slash = has_slash || g_str_has_suffix (base, "/");
1120
1121       /* concatenate the two strings, insert / when not present */
1122       stream->conninfo.location =
1123           g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1124     }
1125   }
1126   GST_DEBUG_OBJECT (src, " setup: %s",
1127       GST_STR_NULL (stream->conninfo.location));
1128
1129   /* we keep track of all streams */
1130   src->streams = g_list_append (src->streams, stream);
1131
1132   return stream;
1133
1134   /* ERRORS */
1135 }
1136
1137 static void
1138 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1139 {
1140   gint i;
1141
1142   GST_DEBUG_OBJECT (src, "free stream %p", stream);
1143
1144   if (stream->caps)
1145     gst_caps_unref (stream->caps);
1146
1147   g_free (stream->destination);
1148   g_free (stream->control_url);
1149   g_free (stream->conninfo.location);
1150
1151   for (i = 0; i < 2; i++) {
1152     if (stream->udpsrc[i]) {
1153       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1154       gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1155       gst_object_unref (stream->udpsrc[i]);
1156       stream->udpsrc[i] = NULL;
1157     }
1158     if (stream->channelpad[i]) {
1159       gst_object_unref (stream->channelpad[i]);
1160       stream->channelpad[i] = NULL;
1161     }
1162     if (stream->udpsink[i]) {
1163       gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1164       gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1165       gst_object_unref (stream->udpsink[i]);
1166       stream->udpsink[i] = NULL;
1167     }
1168   }
1169   if (stream->fakesrc) {
1170     gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1171     gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1172     gst_object_unref (stream->fakesrc);
1173     stream->fakesrc = NULL;
1174   }
1175   if (stream->srcpad) {
1176     gst_pad_set_active (stream->srcpad, FALSE);
1177     if (stream->added) {
1178       gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1179       stream->added = FALSE;
1180     }
1181     stream->srcpad = NULL;
1182   }
1183   if (stream->rtcppad) {
1184     gst_object_unref (stream->rtcppad);
1185     stream->rtcppad = NULL;
1186   }
1187   if (stream->session) {
1188     g_object_unref (stream->session);
1189     stream->session = NULL;
1190   }
1191   g_free (stream);
1192 }
1193
1194 static void
1195 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1196 {
1197   GList *walk;
1198
1199   GST_DEBUG_OBJECT (src, "cleanup");
1200
1201   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1202     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1203
1204     gst_rtspsrc_stream_free (src, stream);
1205   }
1206   g_list_free (src->streams);
1207   src->streams = NULL;
1208   if (src->manager) {
1209     if (src->manager_sig_id) {
1210       g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1211       src->manager_sig_id = 0;
1212     }
1213     gst_element_set_state (src->manager, GST_STATE_NULL);
1214     gst_bin_remove (GST_BIN_CAST (src), src->manager);
1215     src->manager = NULL;
1216   }
1217   src->numstreams = 0;
1218   if (src->props)
1219     gst_structure_free (src->props);
1220   src->props = NULL;
1221
1222   g_free (src->content_base);
1223   src->content_base = NULL;
1224
1225   g_free (src->control);
1226   src->control = NULL;
1227
1228   if (src->range)
1229     gst_rtsp_range_free (src->range);
1230   src->range = NULL;
1231
1232   /* don't clear the SDP when it was used in the url */
1233   if (src->sdp && !src->from_sdp) {
1234     gst_sdp_message_free (src->sdp);
1235     src->sdp = NULL;
1236   }
1237 }
1238
1239 #define PARSE_INT(p, del, res)          \
1240 G_STMT_START {                          \
1241   gchar *t = p;                         \
1242   p = strstr (p, del);                  \
1243   if (p == NULL)                        \
1244     res = -1;                           \
1245   else {                                \
1246     *p = '\0';                          \
1247     p++;                                \
1248     res = atoi (t);                     \
1249   }                                     \
1250 } G_STMT_END
1251
1252 #define PARSE_STRING(p, del, res)       \
1253 G_STMT_START {                          \
1254   gchar *t = p;                         \
1255   p = strstr (p, del);                  \
1256   if (p == NULL) {                      \
1257     res = NULL;                         \
1258     p = t;                              \
1259   }                                     \
1260   else {                                \
1261     *p = '\0';                          \
1262     p++;                                \
1263     res = t;                            \
1264   }                                     \
1265 } G_STMT_END
1266
1267 #define SKIP_SPACES(p)                  \
1268   while (*p && g_ascii_isspace (*p))    \
1269     p++;
1270
1271 /* rtpmap contains:
1272  *
1273  *  <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1274  */
1275 static gboolean
1276 gst_rtspsrc_parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
1277     gint * rate, gchar ** params)
1278 {
1279   gchar *p, *t;
1280
1281   p = (gchar *) rtpmap;
1282
1283   PARSE_INT (p, " ", *payload);
1284   if (*payload == -1)
1285     return FALSE;
1286
1287   SKIP_SPACES (p);
1288   if (*p == '\0')
1289     return FALSE;
1290
1291   PARSE_STRING (p, "/", *name);
1292   if (*name == NULL) {
1293     GST_DEBUG ("no rate, name %s", p);
1294     /* no rate, assume -1 then, this is not supposed to happen but RealMedia
1295      * streams seem to omit the rate. */
1296     *name = p;
1297     *rate = -1;
1298     return TRUE;
1299   }
1300
1301   t = p;
1302   p = strstr (p, "/");
1303   if (p == NULL) {
1304     *rate = atoi (t);
1305     return TRUE;
1306   }
1307   *p = '\0';
1308   p++;
1309   *rate = atoi (t);
1310
1311   t = p;
1312   if (*p == '\0')
1313     return TRUE;
1314   *params = t;
1315
1316   return TRUE;
1317 }
1318
1319 /*
1320  * Mapping SDP attributes to caps
1321  *
1322  * prepend 'a-' to IANA registered sdp attributes names
1323  * (ie: not prefixed with 'x-') in order to avoid
1324  * collision with gstreamer standard caps properties names
1325  */
1326 static void
1327 gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
1328 {
1329   if (attributes->len > 0) {
1330     GstStructure *s;
1331     guint i;
1332
1333     s = gst_caps_get_structure (caps, 0);
1334
1335     for (i = 0; i < attributes->len; i++) {
1336       GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
1337       gchar *tofree, *key;
1338
1339       key = attr->key;
1340
1341       /* skip some of the attribute we already handle */
1342       if (!strcmp (key, "fmtp"))
1343         continue;
1344       if (!strcmp (key, "rtpmap"))
1345         continue;
1346       if (!strcmp (key, "control"))
1347         continue;
1348       if (!strcmp (key, "range"))
1349         continue;
1350
1351       /* string must be valid UTF8 */
1352       if (!g_utf8_validate (attr->value, -1, NULL))
1353         continue;
1354
1355       if (!g_str_has_prefix (key, "x-"))
1356         tofree = key = g_strdup_printf ("a-%s", key);
1357       else
1358         tofree = NULL;
1359
1360       GST_DEBUG ("adding caps: %s=%s", key, attr->value);
1361       gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
1362       g_free (tofree);
1363     }
1364   }
1365 }
1366
1367 /*
1368  *  Mapping of caps to and from SDP fields:
1369  *
1370  *   m=<media> <UDP port> RTP/AVP <payload>
1371  *   a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1372  *   a=fmtp:<payload> <param>[=<value>];...
1373  */
1374 static GstCaps *
1375 gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
1376 {
1377   GstCaps *caps;
1378   const gchar *rtpmap;
1379   const gchar *fmtp;
1380   gchar *name = NULL;
1381   gint rate = -1;
1382   gchar *params = NULL;
1383   gchar *tmp;
1384   GstStructure *s;
1385   gint payload = 0;
1386   gboolean ret;
1387
1388   /* get and parse rtpmap */
1389   if ((rtpmap = gst_sdp_media_get_attribute_val (media, "rtpmap"))) {
1390     ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, &params);
1391     if (ret) {
1392       if (payload != pt) {
1393         /* we ignore the rtpmap if the payload type is different. */
1394         g_warning ("rtpmap of wrong payload type, ignoring");
1395         name = NULL;
1396         rate = -1;
1397         params = NULL;
1398       }
1399     } else {
1400       /* if we failed to parse the rtpmap for a dynamic payload type, we have an
1401        * error */
1402       if (pt >= 96)
1403         goto no_rtpmap;
1404       /* else we can ignore */
1405       g_warning ("error parsing rtpmap, ignoring");
1406     }
1407   } else {
1408     /* dynamic payloads need rtpmap or we fail */
1409     if (pt >= 96)
1410       goto no_rtpmap;
1411   }
1412   /* check if we have a rate, if not, we need to look up the rate from the
1413    * default rates based on the payload types. */
1414   if (rate == -1) {
1415     const GstRTPPayloadInfo *info;
1416
1417     if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
1418       /* dynamic types, use media and encoding_name */
1419       tmp = g_ascii_strdown (media->media, -1);
1420       info = gst_rtp_payload_info_for_name (tmp, name);
1421       g_free (tmp);
1422     } else {
1423       /* static types, use payload type */
1424       info = gst_rtp_payload_info_for_pt (pt);
1425     }
1426
1427     if (info) {
1428       if ((rate = info->clock_rate) == 0)
1429         rate = -1;
1430     }
1431     /* we fail if we cannot find one */
1432     if (rate == -1)
1433       goto no_rate;
1434   }
1435
1436   tmp = g_ascii_strdown (media->media, -1);
1437   caps = gst_caps_new_simple ("application/x-unknown",
1438       "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
1439   g_free (tmp);
1440   s = gst_caps_get_structure (caps, 0);
1441
1442   gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
1443
1444   /* encoding name must be upper case */
1445   if (name != NULL) {
1446     tmp = g_ascii_strup (name, -1);
1447     gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
1448     g_free (tmp);
1449   }
1450
1451   /* params must be lower case */
1452   if (params != NULL) {
1453     tmp = g_ascii_strdown (params, -1);
1454     gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
1455     g_free (tmp);
1456   }
1457
1458   /* parse optional fmtp: field */
1459   if ((fmtp = gst_sdp_media_get_attribute_val (media, "fmtp"))) {
1460     gchar *p;
1461     gint payload = 0;
1462
1463     p = (gchar *) fmtp;
1464
1465     /* p is now of the format <payload> <param>[=<value>];... */
1466     PARSE_INT (p, " ", payload);
1467     if (payload != -1 && payload == pt) {
1468       gchar **pairs;
1469       gint i;
1470
1471       /* <param>[=<value>] are separated with ';' */
1472       pairs = g_strsplit (p, ";", 0);
1473       for (i = 0; pairs[i]; i++) {
1474         gchar *valpos;
1475         const gchar *val, *key;
1476
1477         /* the key may not have a '=', the value can have other '='s */
1478         valpos = strstr (pairs[i], "=");
1479         if (valpos) {
1480           /* we have a '=' and thus a value, remove the '=' with \0 */
1481           *valpos = '\0';
1482           /* value is everything between '=' and ';'. We split the pairs at ;
1483            * boundaries so we can take the remainder of the value. Some servers
1484            * put spaces around the value which we strip off here. Alternatively
1485            * we could strip those spaces in the depayloaders should these spaces
1486            * actually carry any meaning in the future. */
1487           val = g_strstrip (valpos + 1);
1488         } else {
1489           /* simple <param>;.. is translated into <param>=1;... */
1490           val = "1";
1491         }
1492         /* strip the key of spaces, convert key to lowercase but not the value. */
1493         key = g_strstrip (pairs[i]);
1494         if (strlen (key) > 1) {
1495           tmp = g_ascii_strdown (key, -1);
1496           gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
1497           g_free (tmp);
1498         }
1499       }
1500       g_strfreev (pairs);
1501     }
1502   }
1503   return caps;
1504
1505   /* ERRORS */
1506 no_rtpmap:
1507   {
1508     g_warning ("rtpmap type not given for dynamic payload %d", pt);
1509     return NULL;
1510   }
1511 no_rate:
1512   {
1513     g_warning ("rate unknown for payload type %d", pt);
1514     return NULL;
1515   }
1516 }
1517
1518 static gboolean
1519 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
1520     gint * rtpport, gint * rtcpport)
1521 {
1522   GstRTSPSrc *src;
1523   GstStateChangeReturn ret;
1524   GstElement *udpsrc0, *udpsrc1;
1525   gint tmp_rtp, tmp_rtcp;
1526   guint count;
1527   const gchar *host;
1528
1529   src = stream->parent;
1530
1531   udpsrc0 = NULL;
1532   udpsrc1 = NULL;
1533   count = 0;
1534
1535   /* Start at next port */
1536   tmp_rtp = src->next_port_num;
1537
1538   if (stream->is_ipv6)
1539     host = "udp://[::0]";
1540   else
1541     host = "udp://0.0.0.0";
1542
1543   /* try to allocate 2 UDP ports, the RTP port should be an even
1544    * number and the RTCP port should be the next (uneven) port */
1545 again:
1546
1547   if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
1548       tmp_rtp >= src->client_port_range.max)
1549     goto no_ports;
1550
1551   udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1552   if (udpsrc0 == NULL)
1553     goto no_udp_protocol;
1554   g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
1555
1556   if (src->udp_buffer_size != 0)
1557     g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
1558         NULL);
1559
1560   ret = gst_element_set_state (udpsrc0, GST_STATE_PAUSED);
1561   if (ret == GST_STATE_CHANGE_FAILURE) {
1562     if (tmp_rtp != 0) {
1563       GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
1564
1565       tmp_rtp += 2;
1566       if (++count > src->retry)
1567         goto no_ports;
1568
1569       GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1570       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1571       gst_object_unref (udpsrc0);
1572
1573       GST_DEBUG_OBJECT (src, "retry %d", count);
1574       goto again;
1575     }
1576     goto no_udp_protocol;
1577   }
1578
1579   g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
1580   GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
1581
1582   /* check if port is even */
1583   if ((tmp_rtp & 0x01) != 0) {
1584     /* port not even, close and allocate another */
1585     if (++count > src->retry)
1586       goto no_ports;
1587
1588     GST_DEBUG_OBJECT (src, "RTP port not even");
1589
1590     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1591     gst_element_set_state (udpsrc0, GST_STATE_NULL);
1592     gst_object_unref (udpsrc0);
1593
1594     GST_DEBUG_OBJECT (src, "retry %d", count);
1595     tmp_rtp++;
1596     goto again;
1597   }
1598
1599   /* allocate port+1 for RTCP now */
1600   udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1601   if (udpsrc1 == NULL)
1602     goto no_udp_rtcp_protocol;
1603
1604   /* set port */
1605   tmp_rtcp = tmp_rtp + 1;
1606   if (src->client_port_range.max > 0 && tmp_rtcp >= src->client_port_range.max)
1607     goto no_ports;
1608
1609   g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
1610
1611   GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
1612   ret = gst_element_set_state (udpsrc1, GST_STATE_PAUSED);
1613   /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
1614   if (ret == GST_STATE_CHANGE_FAILURE) {
1615     GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
1616
1617     if (++count > src->retry)
1618       goto no_ports;
1619
1620     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1621     gst_element_set_state (udpsrc0, GST_STATE_NULL);
1622     gst_object_unref (udpsrc0);
1623
1624     GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
1625     gst_element_set_state (udpsrc1, GST_STATE_NULL);
1626     gst_object_unref (udpsrc1);
1627     udpsrc1 = NULL;
1628
1629     tmp_rtp += 2;
1630     GST_DEBUG_OBJECT (src, "retry %d", count);
1631     goto again;
1632   }
1633
1634   /* all fine, do port check */
1635   g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
1636   g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
1637
1638   /* this should not happen... */
1639   if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
1640     goto port_error;
1641
1642   /* we keep these elements, we configure all in configure_transport when the
1643    * server told us to really use the UDP ports. */
1644   stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
1645   stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
1646
1647   /* keep track of next available port number when we have a range
1648    * configured */
1649   if (src->next_port_num != 0)
1650     src->next_port_num = tmp_rtcp + 1;
1651
1652   return TRUE;
1653
1654   /* ERRORS */
1655 no_udp_protocol:
1656   {
1657     GST_DEBUG_OBJECT (src, "could not get UDP source");
1658     goto cleanup;
1659   }
1660 no_ports:
1661   {
1662     GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
1663         count);
1664     goto cleanup;
1665   }
1666 no_udp_rtcp_protocol:
1667   {
1668     GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
1669     goto cleanup;
1670   }
1671 port_error:
1672   {
1673     GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
1674         tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
1675     goto cleanup;
1676   }
1677 cleanup:
1678   {
1679     if (udpsrc0) {
1680       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1681       gst_object_unref (udpsrc0);
1682     }
1683     if (udpsrc1) {
1684       gst_element_set_state (udpsrc1, GST_STATE_NULL);
1685       gst_object_unref (udpsrc1);
1686     }
1687     return FALSE;
1688   }
1689 }
1690
1691 static void
1692 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
1693 {
1694   GstEvent *event;
1695   gint cmd, i;
1696   GstState state;
1697   GList *walk;
1698
1699   if (flush) {
1700     event = gst_event_new_flush_start ();
1701     GST_DEBUG_OBJECT (src, "start flush");
1702     cmd = CMD_WAIT;
1703     state = GST_STATE_PAUSED;
1704   } else {
1705     event = gst_event_new_flush_stop (FALSE);
1706     GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
1707     cmd = CMD_LOOP;
1708     if (playing)
1709       state = GST_STATE_PLAYING;
1710     else
1711       state = GST_STATE_PAUSED;
1712   }
1713   gst_rtspsrc_push_event (src, event);
1714   gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
1715
1716   /* to manage jitterbuffer buffer mode */
1717   if (src->manager)
1718     gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
1719
1720   /* make running time start start at 0 again */
1721   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1722     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1723
1724     for (i = 0; i < 2; i++) {
1725       /* for udp case */
1726       if (stream->udpsrc[i]) {
1727         gst_element_set_state (stream->udpsrc[i], state);
1728       }
1729     }
1730   }
1731 }
1732
1733 static GstRTSPResult
1734 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
1735     GstRTSPMessage * message, GTimeVal * timeout)
1736 {
1737   GstRTSPResult ret;
1738
1739   if (conn)
1740     ret = gst_rtsp_connection_send (conn, message, timeout);
1741   else
1742     ret = GST_RTSP_ERROR;
1743
1744   return ret;
1745 }
1746
1747 static GstRTSPResult
1748 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
1749     GstRTSPMessage * message, GTimeVal * timeout)
1750 {
1751   GstRTSPResult ret;
1752
1753   if (conn)
1754     ret = gst_rtsp_connection_receive (conn, message, timeout);
1755   else
1756     ret = GST_RTSP_ERROR;
1757
1758   return ret;
1759 }
1760
1761 static void
1762 gst_rtspsrc_get_position (GstRTSPSrc * src)
1763 {
1764   GstQuery *query;
1765   GList *walk;
1766
1767   query = gst_query_new_position (GST_FORMAT_TIME);
1768   /*  should be known somewhere down the stream (e.g. jitterbuffer) */
1769   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1770     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1771     GstFormat fmt;
1772     gint64 pos;
1773
1774     if (stream->srcpad) {
1775       if (gst_pad_query (stream->srcpad, query)) {
1776         gst_query_parse_position (query, &fmt, &pos);
1777         GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
1778             GST_TIME_ARGS (pos));
1779         src->last_pos = pos;
1780         return;
1781       }
1782     }
1783   }
1784
1785   src->last_pos = 0;
1786 }
1787
1788 static gboolean
1789 gst_rtspsrc_do_seek (GstRTSPSrc * src, GstSegment * segment)
1790 {
1791   src->state = GST_RTSP_STATE_SEEKING;
1792   /* PLAY will add the range header now. */
1793   src->need_range = TRUE;
1794
1795   return TRUE;
1796 }
1797
1798 static gboolean
1799 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
1800 {
1801   gdouble rate;
1802   GstFormat format;
1803   GstSeekFlags flags;
1804   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
1805   gint64 cur, stop;
1806   gboolean flush, skip;
1807   gboolean update;
1808   gboolean playing;
1809   GstSegment seeksegment = { 0, };
1810   GList *walk;
1811
1812   if (event) {
1813     GST_DEBUG_OBJECT (src, "doing seek with event");
1814
1815     gst_event_parse_seek (event, &rate, &format, &flags,
1816         &cur_type, &cur, &stop_type, &stop);
1817
1818     /* no negative rates yet */
1819     if (rate < 0.0)
1820       goto negative_rate;
1821
1822     /* we need TIME format */
1823     if (format != src->segment.format)
1824       goto no_format;
1825   } else {
1826     GST_DEBUG_OBJECT (src, "doing seek without event");
1827     flags = 0;
1828     cur_type = GST_SEEK_TYPE_SET;
1829     stop_type = GST_SEEK_TYPE_SET;
1830   }
1831
1832   /* get flush flag */
1833   flush = flags & GST_SEEK_FLAG_FLUSH;
1834   skip = flags & GST_SEEK_FLAG_SKIP;
1835
1836   /* now we need to make sure the streaming thread is stopped. We do this by
1837    * either sending a FLUSH_START event downstream which will cause the
1838    * streaming thread to stop with a WRONG_STATE.
1839    * For a non-flushing seek we simply pause the task, which will happen as soon
1840    * as it completes one iteration (and thus might block when the sink is
1841    * blocking in preroll). */
1842   if (flush) {
1843     GST_DEBUG_OBJECT (src, "starting flush");
1844     gst_rtspsrc_flush (src, TRUE, FALSE);
1845   } else {
1846     if (src->task) {
1847       gst_task_pause (src->task);
1848     }
1849   }
1850
1851   /* we should now be able to grab the streaming thread because we stopped it
1852    * with the above flush/pause code */
1853   GST_RTSP_STREAM_LOCK (src);
1854
1855   GST_DEBUG_OBJECT (src, "stopped streaming");
1856
1857   /* copy segment, we need this because we still need the old
1858    * segment when we close the current segment. */
1859   memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
1860
1861   /* configure the seek parameters in the seeksegment. We will then have the
1862    * right values in the segment to perform the seek */
1863   if (event) {
1864     GST_DEBUG_OBJECT (src, "configuring seek");
1865     gst_segment_do_seek (&seeksegment, rate, format, flags,
1866         cur_type, cur, stop_type, stop, &update);
1867   }
1868
1869   /* figure out the last position we need to play. If it's configured (stop !=
1870    * -1), use that, else we play until the total duration of the file */
1871   if ((stop = seeksegment.stop) == -1)
1872     stop = seeksegment.duration;
1873
1874   playing = (src->state == GST_RTSP_STATE_PLAYING);
1875
1876   /* if we were playing, pause first */
1877   if (playing) {
1878     /* obtain current position in case seek fails */
1879     gst_rtspsrc_get_position (src);
1880     gst_rtspsrc_pause (src, FALSE);
1881   }
1882   src->skip = skip;
1883
1884   gst_rtspsrc_do_seek (src, &seeksegment);
1885
1886   /* and continue playing */
1887   if (playing)
1888     gst_rtspsrc_play (src, &seeksegment, FALSE);
1889
1890   /* prepare for streaming again */
1891   if (flush) {
1892     /* if we started flush, we stop now */
1893     GST_DEBUG_OBJECT (src, "stopping flush");
1894     gst_rtspsrc_flush (src, FALSE, playing);
1895   }
1896
1897   /* now we did the seek and can activate the new segment values */
1898   memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
1899
1900   /* if we're doing a segment seek, post a SEGMENT_START message */
1901   if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1902     gst_element_post_message (GST_ELEMENT_CAST (src),
1903         gst_message_new_segment_start (GST_OBJECT_CAST (src),
1904             src->segment.format, src->segment.position));
1905   }
1906
1907   /* now create the newsegment */
1908   GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
1909       " to %" G_GINT64_FORMAT, src->segment.position, stop);
1910
1911   /* store the newsegment event so it can be sent from the streaming thread. */
1912   if (src->start_segment)
1913     gst_event_unref (src->start_segment);
1914   src->start_segment = gst_event_new_segment (&src->segment);
1915
1916   /* mark discont */
1917   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
1918   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1919     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1920     stream->discont = TRUE;
1921   }
1922
1923   GST_RTSP_STREAM_UNLOCK (src);
1924
1925   return TRUE;
1926
1927   /* ERRORS */
1928 negative_rate:
1929   {
1930     GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
1931     return FALSE;
1932   }
1933 no_format:
1934   {
1935     GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
1936     return FALSE;
1937   }
1938 }
1939
1940 static gboolean
1941 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
1942     GstEvent * event)
1943 {
1944   GstRTSPSrc *src;
1945   gboolean res = TRUE;
1946   gboolean forward;
1947
1948   src = GST_RTSPSRC_CAST (parent);
1949
1950   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
1951       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
1952
1953   switch (GST_EVENT_TYPE (event)) {
1954     case GST_EVENT_SEEK:
1955       res = gst_rtspsrc_perform_seek (src, event);
1956       forward = FALSE;
1957       break;
1958     case GST_EVENT_QOS:
1959     case GST_EVENT_NAVIGATION:
1960     case GST_EVENT_LATENCY:
1961     default:
1962       forward = TRUE;
1963       break;
1964   }
1965   if (forward) {
1966     GstPad *target;
1967
1968     if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
1969       res = gst_pad_send_event (target, event);
1970       gst_object_unref (target);
1971     } else {
1972       gst_event_unref (event);
1973     }
1974   } else {
1975     gst_event_unref (event);
1976   }
1977
1978   return res;
1979 }
1980
1981 /* this is the final event function we receive on the internal source pad when
1982  * we deal with TCP connections */
1983 static gboolean
1984 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
1985     GstEvent * event)
1986 {
1987   gboolean res;
1988
1989   GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
1990
1991   switch (GST_EVENT_TYPE (event)) {
1992     case GST_EVENT_SEEK:
1993     case GST_EVENT_QOS:
1994     case GST_EVENT_NAVIGATION:
1995     case GST_EVENT_LATENCY:
1996     default:
1997       gst_event_unref (event);
1998       res = TRUE;
1999       break;
2000   }
2001   return res;
2002 }
2003
2004 /* this is the final query function we receive on the internal source pad when
2005  * we deal with TCP connections */
2006 static gboolean
2007 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2008     GstQuery * query)
2009 {
2010   GstRTSPSrc *src;
2011   gboolean res = TRUE;
2012
2013   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2014
2015   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2016       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2017
2018   switch (GST_QUERY_TYPE (query)) {
2019     case GST_QUERY_POSITION:
2020     {
2021       /* no idea */
2022       break;
2023     }
2024     case GST_QUERY_DURATION:
2025     {
2026       GstFormat format;
2027
2028       gst_query_parse_duration (query, &format, NULL);
2029
2030       switch (format) {
2031         case GST_FORMAT_TIME:
2032           gst_query_set_duration (query, format, src->segment.duration);
2033           break;
2034         default:
2035           res = FALSE;
2036           break;
2037       }
2038       break;
2039     }
2040     case GST_QUERY_LATENCY:
2041     {
2042       /* we are live with a min latency of 0 and unlimited max latency, this
2043        * result will be updated by the session manager if there is any. */
2044       gst_query_set_latency (query, TRUE, 0, -1);
2045       break;
2046     }
2047     default:
2048       break;
2049   }
2050
2051   return res;
2052 }
2053
2054 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2055 static gboolean
2056 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2057     GstQuery * query)
2058 {
2059   GstRTSPSrc *src;
2060   gboolean res = FALSE;
2061
2062   src = GST_RTSPSRC_CAST (parent);
2063
2064   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2065       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2066
2067   switch (GST_QUERY_TYPE (query)) {
2068     case GST_QUERY_DURATION:
2069     {
2070       GstFormat format;
2071
2072       gst_query_parse_duration (query, &format, NULL);
2073
2074       switch (format) {
2075         case GST_FORMAT_TIME:
2076           gst_query_set_duration (query, format, src->segment.duration);
2077           res = TRUE;
2078           break;
2079         default:
2080           break;
2081       }
2082       break;
2083     }
2084     case GST_QUERY_SEEKING:
2085     {
2086       GstFormat format;
2087
2088       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2089       if (format == GST_FORMAT_TIME) {
2090         gboolean seekable =
2091             src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2092
2093         /* seeking without duration is unlikely */
2094         seekable = seekable && src->seekable && src->segment.duration &&
2095             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2096
2097         /* FIXME ?? should we have 0 and segment.duration here; see demuxers */
2098         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
2099             src->segment.start, src->segment.stop);
2100         res = TRUE;
2101       }
2102       break;
2103     }
2104     case GST_QUERY_URI:
2105     {
2106       gchar *uri;
2107
2108       uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2109       if (uri != NULL) {
2110         gst_query_set_uri (query, uri);
2111         g_free (uri);
2112         res = TRUE;
2113       }
2114       break;
2115     }
2116     default:
2117     {
2118       GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2119
2120       /* forward the query to the proxy target pad */
2121       if (target) {
2122         res = gst_pad_query (target, query);
2123         gst_object_unref (target);
2124       }
2125       break;
2126     }
2127   }
2128
2129   return res;
2130 }
2131
2132 /* callback for RTCP messages to be sent to the server when operating in TCP
2133  * mode. */
2134 static GstFlowReturn
2135 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2136 {
2137   GstRTSPSrc *src;
2138   GstRTSPStream *stream;
2139   GstFlowReturn res = GST_FLOW_OK;
2140   GstMapInfo map;
2141   guint8 *data;
2142   guint size;
2143   GstRTSPResult ret;
2144   GstRTSPMessage message = { 0 };
2145   GstRTSPConnection *conn;
2146
2147   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2148   src = stream->parent;
2149
2150   gst_buffer_map (buffer, &map, GST_MAP_READ);
2151   size = map.size;
2152   data = map.data;
2153
2154   gst_rtsp_message_init_data (&message, stream->channel[1]);
2155
2156   /* lend the body data to the message */
2157   gst_rtsp_message_take_body (&message, data, size);
2158
2159   if (stream->conninfo.connection)
2160     conn = stream->conninfo.connection;
2161   else
2162     conn = src->conninfo.connection;
2163
2164   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2165   ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2166   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2167
2168   /* and steal it away again because we will free it when unreffing the
2169    * buffer */
2170   gst_rtsp_message_steal_body (&message, &data, &size);
2171   gst_rtsp_message_unset (&message);
2172
2173   gst_buffer_unmap (buffer, &map);
2174   gst_buffer_unref (buffer);
2175
2176   return res;
2177 }
2178
2179 static GstPadProbeReturn
2180 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2181 {
2182   GstRTSPSrc *src = user_data;
2183
2184   GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2185       GST_DEBUG_PAD_NAME (pad));
2186
2187   /* activate the streams */
2188   GST_OBJECT_LOCK (src);
2189   if (!src->need_activate)
2190     goto was_ok;
2191
2192   src->need_activate = FALSE;
2193   GST_OBJECT_UNLOCK (src);
2194
2195   gst_rtspsrc_activate_streams (src);
2196
2197   return GST_PAD_PROBE_OK;
2198
2199 was_ok:
2200   {
2201     GST_OBJECT_UNLOCK (src);
2202     return GST_PAD_PROBE_OK;
2203   }
2204 }
2205
2206 /* this callback is called when the session manager generated a new src pad with
2207  * payloaded RTP packets. We simply ghost the pad here. */
2208 static void
2209 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2210 {
2211   gchar *name;
2212   GstPadTemplate *template;
2213   gint id, ssrc, pt;
2214   GList *lstream;
2215   GstRTSPStream *stream;
2216   gboolean all_added;
2217
2218   GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2219
2220   GST_RTSP_STATE_LOCK (src);
2221   /* find stream */
2222   name = gst_object_get_name (GST_OBJECT_CAST (pad));
2223   if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2224     goto unknown_stream;
2225
2226   GST_DEBUG_OBJECT (src, "stream: %u, SSRC %d, PT %d", id, ssrc, pt);
2227
2228   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2229   if (stream == NULL)
2230     goto unknown_stream;
2231
2232   /* create a new pad we will use to stream to */
2233   template = gst_static_pad_template_get (&rtptemplate);
2234   stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2235   gst_object_unref (template);
2236   g_free (name);
2237
2238   stream->added = TRUE;
2239   gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2240   gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2241   gst_pad_set_active (stream->srcpad, TRUE);
2242   gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2243
2244   /* check if we added all streams */
2245   all_added = TRUE;
2246   for (lstream = src->streams; lstream; lstream = g_list_next (lstream)) {
2247     stream = (GstRTSPStream *) lstream->data;
2248
2249     GST_DEBUG_OBJECT (src, "stream %p, container %d, disabled %d, added %d",
2250         stream, stream->container, stream->disabled, stream->added);
2251
2252     /* a container stream only needs one pad added. Also disabled streams don't
2253      * count */
2254     if (!stream->container && !stream->disabled && !stream->added) {
2255       all_added = FALSE;
2256       break;
2257     }
2258   }
2259   GST_RTSP_STATE_UNLOCK (src);
2260
2261   if (all_added) {
2262     GST_DEBUG_OBJECT (src, "We added all streams");
2263     /* when we get here, all stream are added and we can fire the no-more-pads
2264      * signal. */
2265     gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2266   }
2267
2268   return;
2269
2270   /* ERRORS */
2271 unknown_stream:
2272   {
2273     GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2274     GST_RTSP_STATE_UNLOCK (src);
2275     g_free (name);
2276     return;
2277   }
2278 }
2279
2280 static GstCaps *
2281 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2282 {
2283   GstRTSPStream *stream;
2284   GstCaps *caps;
2285
2286   GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2287
2288   GST_RTSP_STATE_LOCK (src);
2289   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2290   if (!stream)
2291     goto unknown_stream;
2292
2293   caps = stream->caps;
2294   if (caps)
2295     gst_caps_ref (caps);
2296   GST_RTSP_STATE_UNLOCK (src);
2297
2298   return caps;
2299
2300 unknown_stream:
2301   {
2302     GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2303     GST_RTSP_STATE_UNLOCK (src);
2304     return NULL;
2305   }
2306 }
2307
2308 static void
2309 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2310 {
2311   GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2312
2313   if (stream->eos)
2314     goto was_eos;
2315
2316   stream->eos = TRUE;
2317   gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
2318   return;
2319
2320   /* ERRORS */
2321 was_eos:
2322   {
2323     GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2324     return;
2325   }
2326 }
2327
2328 static void
2329 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2330 {
2331   GstRTSPSrc *src = stream->parent;
2332
2333   GST_DEBUG_OBJECT (src, "source in session %u received BYE", stream->id);
2334
2335   gst_rtspsrc_do_stream_eos (src, stream);
2336 }
2337
2338 static void
2339 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2340 {
2341   GstRTSPSrc *src = stream->parent;
2342
2343   GST_DEBUG_OBJECT (src, "source in session %u timed out", stream->id);
2344
2345   gst_rtspsrc_do_stream_eos (src, stream);
2346 }
2347
2348 static void
2349 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2350 {
2351   GstRTSPStream *stream;
2352
2353   GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2354
2355   /* get stream for session */
2356   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2357   if (stream) {
2358     gst_rtspsrc_do_stream_eos (src, stream);
2359   }
2360 }
2361
2362 static void
2363 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2364 {
2365   GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2366       stream->id);
2367 }
2368
2369 /* try to get and configure a manager */
2370 static gboolean
2371 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
2372     GstRTSPTransport * transport)
2373 {
2374   const gchar *manager;
2375   gchar *name;
2376   GstStateChangeReturn ret;
2377
2378   /* find a manager */
2379   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
2380     goto no_manager;
2381
2382   if (manager) {
2383     GST_DEBUG_OBJECT (src, "using manager %s", manager);
2384
2385     /* configure the manager */
2386     if (src->manager == NULL) {
2387       GObjectClass *klass;
2388       GstState target;
2389
2390       if (!(src->manager = gst_element_factory_make (manager, NULL))) {
2391         /* fallback */
2392         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
2393           goto no_manager;
2394
2395         if (!manager)
2396           goto use_no_manager;
2397
2398         if (!(src->manager = gst_element_factory_make (manager, NULL)))
2399           goto manager_failed;
2400       }
2401
2402       /* we manage this element */
2403       gst_bin_add (GST_BIN_CAST (src), src->manager);
2404
2405       GST_OBJECT_LOCK (src);
2406       target = GST_STATE_TARGET (src);
2407       GST_OBJECT_UNLOCK (src);
2408
2409       ret = gst_element_set_state (src->manager, target);
2410       if (ret == GST_STATE_CHANGE_FAILURE)
2411         goto start_manager_failure;
2412
2413       g_object_set (src->manager, "latency", src->latency, NULL);
2414
2415       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2416       if (g_object_class_find_property (klass, "drop-on-latency")) {
2417         g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
2418             NULL);
2419       }
2420
2421       if (g_object_class_find_property (klass, "buffer-mode")) {
2422         if (src->buffer_mode != BUFFER_MODE_AUTO) {
2423           g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2424         } else {
2425           gboolean need_slave;
2426           GstStructure *s;
2427           const gchar *encoding;
2428
2429           /* buffer mode pauses are handled by adding offsets to buffer times,
2430            * but some depayloaders may have a hard time syncing output times
2431            * with such input times, e.g. container ones, most notably ASF */
2432           /* TODO alternatives are having an event that indicates these shifts,
2433            * or having rtsp extensions provide suggestion on buffer mode */
2434           need_slave = stream->container;
2435           if (stream->caps && (s = gst_caps_get_structure (stream->caps, 0)) &&
2436               (encoding = gst_structure_get_string (s, "encoding-name")))
2437             need_slave = need_slave || (strcmp (encoding, "X-ASF-PF") == 0);
2438           GST_DEBUG_OBJECT (src, "auto buffering mode, need_slave %d",
2439               need_slave);
2440           /* valid duration implies not likely live pipeline,
2441            * so slaving in jitterbuffer does not make much sense
2442            * (and might mess things up due to bursts) */
2443           if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
2444               src->segment.duration && !need_slave) {
2445             GST_DEBUG_OBJECT (src, "selected buffer");
2446             g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER,
2447                 NULL);
2448           } else {
2449             GST_DEBUG_OBJECT (src, "selected slave");
2450             g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2451           }
2452         }
2453       }
2454
2455       /* connect to signals if we did not already do so */
2456       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
2457           stream);
2458       src->manager_sig_id =
2459           g_signal_connect (src->manager, "pad-added",
2460           (GCallback) new_manager_pad, src);
2461       src->manager_ptmap_id =
2462           g_signal_connect (src->manager, "request-pt-map",
2463           (GCallback) request_pt_map, src);
2464
2465       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
2466           src);
2467     }
2468
2469     /* we stream directly to the manager, get some pads. Each RTSP stream goes
2470      * into a separate RTP session. */
2471     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
2472     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
2473     g_free (name);
2474     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
2475     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
2476     g_free (name);
2477
2478     /* now configure the bandwidth in the manager */
2479     if (g_signal_lookup ("get-internal-session",
2480             G_OBJECT_TYPE (src->manager)) != 0) {
2481       GObject *rtpsession;
2482
2483       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
2484           &rtpsession);
2485       if (rtpsession) {
2486         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
2487
2488         stream->session = rtpsession;
2489
2490         if (stream->as_bandwidth != -1) {
2491           GST_INFO_OBJECT (src, "setting AS: %f",
2492               (gdouble) (stream->as_bandwidth * 1000));
2493           g_object_set (rtpsession, "bandwidth",
2494               (gdouble) (stream->as_bandwidth * 1000), NULL);
2495         }
2496         if (stream->rr_bandwidth != -1) {
2497           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
2498           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
2499               NULL);
2500         }
2501         if (stream->rs_bandwidth != -1) {
2502           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
2503           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
2504               NULL);
2505         }
2506
2507         g_object_set (rtpsession, "probation", src->probation, NULL);
2508
2509         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
2510             stream);
2511         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
2512             stream);
2513         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
2514             stream);
2515         g_signal_connect (rtpsession, "on-ssrc-active",
2516             (GCallback) on_ssrc_active, stream);
2517       }
2518     }
2519   }
2520
2521 use_no_manager:
2522   return TRUE;
2523
2524   /* ERRORS */
2525 no_manager:
2526   {
2527     GST_DEBUG_OBJECT (src, "cannot get a session manager");
2528     return FALSE;
2529   }
2530 manager_failed:
2531   {
2532     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
2533     return FALSE;
2534   }
2535 start_manager_failure:
2536   {
2537     GST_DEBUG_OBJECT (src, "could not start session manager");
2538     return FALSE;
2539   }
2540 }
2541
2542 /* free the UDP sources allocated when negotiating a transport.
2543  * This function is called when the server negotiated to a transport where the
2544  * UDP sources are not needed anymore, such as TCP or multicast. */
2545 static void
2546 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
2547 {
2548   gint i;
2549
2550   for (i = 0; i < 2; i++) {
2551     if (stream->udpsrc[i]) {
2552       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
2553       gst_object_unref (stream->udpsrc[i]);
2554       stream->udpsrc[i] = NULL;
2555     }
2556   }
2557 }
2558
2559 /* for TCP, create pads to send and receive data to and from the manager and to
2560  * intercept various events and queries
2561  */
2562 static gboolean
2563 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
2564     GstRTSPTransport * transport, GstPad ** outpad)
2565 {
2566   gchar *name;
2567   GstPadTemplate *template;
2568   GstPad *pad0, *pad1;
2569
2570   /* configure for interleaved delivery, nothing needs to be done
2571    * here, the loop function will call the chain functions of the
2572    * session manager. */
2573   stream->channel[0] = transport->interleaved.min;
2574   stream->channel[1] = transport->interleaved.max;
2575   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
2576       stream->channel[0], stream->channel[1]);
2577
2578   /* we can remove the allocated UDP ports now */
2579   gst_rtspsrc_stream_free_udp (stream);
2580
2581   /* no session manager, send data to srcpad directly */
2582   if (!stream->channelpad[0]) {
2583     GST_DEBUG_OBJECT (src, "no manager, creating pad");
2584
2585     /* create a new pad we will use to stream to */
2586     name = g_strdup_printf ("stream_%u", stream->id);
2587     template = gst_static_pad_template_get (&rtptemplate);
2588     stream->channelpad[0] = gst_pad_new_from_template (template, name);
2589     gst_object_unref (template);
2590     g_free (name);
2591
2592     /* set caps and activate */
2593     gst_pad_use_fixed_caps (stream->channelpad[0]);
2594     gst_pad_set_active (stream->channelpad[0], TRUE);
2595
2596     *outpad = gst_object_ref (stream->channelpad[0]);
2597   } else {
2598     GST_DEBUG_OBJECT (src, "using manager source pad");
2599
2600     template = gst_static_pad_template_get (&anysrctemplate);
2601
2602     /* allocate pads for sending the channel data into the manager */
2603     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
2604     gst_pad_link (pad0, stream->channelpad[0]);
2605     gst_object_unref (stream->channelpad[0]);
2606     stream->channelpad[0] = pad0;
2607     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
2608     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
2609     gst_pad_set_element_private (pad0, src);
2610     gst_pad_set_active (pad0, TRUE);
2611
2612     if (stream->channelpad[1]) {
2613       /* if we have a sinkpad for the other channel, create a pad and link to the
2614        * manager. */
2615       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
2616       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
2617       gst_pad_link (pad1, stream->channelpad[1]);
2618       gst_object_unref (stream->channelpad[1]);
2619       stream->channelpad[1] = pad1;
2620       gst_pad_set_active (pad1, TRUE);
2621     }
2622     gst_object_unref (template);
2623   }
2624   /* setup RTCP transport back to the server if we have to. */
2625   if (src->manager && src->do_rtcp) {
2626     GstPad *pad;
2627
2628     template = gst_static_pad_template_get (&anysinktemplate);
2629
2630     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
2631     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
2632     gst_pad_set_element_private (stream->rtcppad, stream);
2633     gst_pad_set_active (stream->rtcppad, TRUE);
2634
2635     /* get session RTCP pad */
2636     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2637     pad = gst_element_get_request_pad (src->manager, name);
2638     g_free (name);
2639
2640     /* and link */
2641     if (pad) {
2642       gst_pad_link (pad, stream->rtcppad);
2643       gst_object_unref (pad);
2644     }
2645
2646     gst_object_unref (template);
2647   }
2648   return TRUE;
2649 }
2650
2651 static void
2652 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
2653     GstRTSPTransport * transport, const gchar ** destination, gint * min,
2654     gint * max, guint * ttl)
2655 {
2656   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
2657     if (destination) {
2658       if (!(*destination = transport->destination))
2659         *destination = stream->destination;
2660     }
2661     if (min && max) {
2662       /* transport first */
2663       *min = transport->port.min;
2664       *max = transport->port.max;
2665       if (*min == -1 && *max == -1) {
2666         /* then try from SDP */
2667         if (stream->port != 0) {
2668           *min = stream->port;
2669           *max = stream->port + 1;
2670         }
2671       }
2672     }
2673
2674     if (ttl) {
2675       if (!(*ttl = transport->ttl))
2676         *ttl = stream->ttl;
2677     }
2678   } else {
2679     if (destination) {
2680       /* first take the source, then the endpoint to figure out where to send
2681        * the RTCP. */
2682       if (!(*destination = transport->source)) {
2683         if (src->conninfo.connection)
2684           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
2685         else if (stream->conninfo.connection)
2686           *destination =
2687               gst_rtsp_connection_get_ip (stream->conninfo.connection);
2688       }
2689     }
2690     if (min && max) {
2691       /* for unicast we only expect the ports here */
2692       *min = transport->server_port.min;
2693       *max = transport->server_port.max;
2694     }
2695   }
2696 }
2697
2698 /* For multicast create UDP sources and join the multicast group. */
2699 static gboolean
2700 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
2701     GstRTSPTransport * transport, GstPad ** outpad)
2702 {
2703   gchar *uri;
2704   const gchar *destination;
2705   gint min, max;
2706
2707   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
2708
2709   /* we can remove the allocated UDP ports now */
2710   gst_rtspsrc_stream_free_udp (stream);
2711
2712   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
2713       &max, NULL);
2714
2715   /* we need a destination now */
2716   if (destination == NULL)
2717     goto no_destination;
2718
2719   /* we really need ports now or we won't be able to receive anything at all */
2720   if (min == -1 && max == -1)
2721     goto no_ports;
2722
2723   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
2724       destination, min, max);
2725
2726   /* creating UDP source for RTP */
2727   if (min != -1) {
2728     uri = g_strdup_printf ("udp://%s:%d", destination, min);
2729     stream->udpsrc[0] =
2730         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
2731     g_free (uri);
2732     if (stream->udpsrc[0] == NULL)
2733       goto no_element;
2734
2735     /* take ownership */
2736     gst_object_ref_sink (stream->udpsrc[0]);
2737
2738     if (src->udp_buffer_size != 0)
2739       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
2740           src->udp_buffer_size, NULL);
2741
2742     /* change state */
2743     gst_element_set_state (stream->udpsrc[0], GST_STATE_PAUSED);
2744   }
2745
2746   /* creating another UDP source for RTCP */
2747   if (max != -1) {
2748     uri = g_strdup_printf ("udp://%s:%d", destination, max);
2749     stream->udpsrc[1] =
2750         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
2751     g_free (uri);
2752     if (stream->udpsrc[1] == NULL)
2753       goto no_element;
2754
2755     /* take ownership */
2756     gst_object_ref_sink (stream->udpsrc[1]);
2757
2758     gst_element_set_state (stream->udpsrc[1], GST_STATE_PAUSED);
2759   }
2760   return TRUE;
2761
2762   /* ERRORS */
2763 no_element:
2764   {
2765     GST_DEBUG_OBJECT (src, "no UDP source element found");
2766     return FALSE;
2767   }
2768 no_destination:
2769   {
2770     GST_DEBUG_OBJECT (src, "no destination found");
2771     return FALSE;
2772   }
2773 no_ports:
2774   {
2775     GST_DEBUG_OBJECT (src, "no ports found");
2776     return FALSE;
2777   }
2778 }
2779
2780 /* configure the remainder of the UDP ports */
2781 static gboolean
2782 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
2783     GstRTSPTransport * transport, GstPad ** outpad)
2784 {
2785   /* we manage the UDP elements now. For unicast, the UDP sources where
2786    * allocated in the stream when we suggested a transport. */
2787   if (stream->udpsrc[0]) {
2788     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
2789
2790     GST_DEBUG_OBJECT (src, "setting up UDP source");
2791
2792     /* configure a timeout on the UDP port. When the timeout message is
2793      * posted, we assume UDP transport is not possible. We reconnect using TCP
2794      * if we can. */
2795     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", src->udp_timeout,
2796         NULL);
2797
2798     /* get output pad of the UDP source. */
2799     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
2800
2801     /* save it so we can unblock */
2802     stream->blockedpad = *outpad;
2803
2804     /* configure pad block on the pad. As soon as there is dataflow on the
2805      * UDP source, we know that UDP is not blocked by a firewall and we can
2806      * configure all the streams to let the application autoplug decoders. */
2807     stream->blockid =
2808         gst_pad_add_probe (stream->blockedpad,
2809         GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked, src, NULL);
2810
2811     if (stream->channelpad[0]) {
2812       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
2813       /* configure for UDP delivery, we need to connect the UDP pads to
2814        * the session plugin. */
2815       gst_pad_link (*outpad, stream->channelpad[0]);
2816       gst_object_unref (*outpad);
2817       *outpad = NULL;
2818       /* we connected to pad-added signal to get pads from the manager */
2819     } else {
2820       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
2821     }
2822   }
2823
2824   /* RTCP port */
2825   if (stream->udpsrc[1]) {
2826     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
2827
2828     if (stream->channelpad[1]) {
2829       GstPad *pad;
2830
2831       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
2832
2833       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
2834       gst_pad_link (pad, stream->channelpad[1]);
2835       gst_object_unref (pad);
2836     } else {
2837       /* leave unlinked */
2838     }
2839   }
2840   return TRUE;
2841 }
2842
2843 /* configure the UDP sink back to the server for status reports */
2844 static gboolean
2845 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
2846     GstRTSPStream * stream, GstRTSPTransport * transport)
2847 {
2848   GstPad *pad;
2849   gint rtp_port, rtcp_port;
2850   gboolean do_rtp, do_rtcp;
2851   const gchar *destination;
2852   gchar *uri, *name;
2853   guint ttl = 0;
2854   GSocket *socket;
2855
2856   /* get transport info */
2857   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
2858       &rtp_port, &rtcp_port, &ttl);
2859
2860   /* see what we need to do */
2861   do_rtp = (rtp_port != -1);
2862   /* it's possible that the server does not want us to send RTCP in which case
2863    * the port is -1 */
2864   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
2865
2866   /* we need a destination when we have RTP or RTCP ports */
2867   if (destination == NULL && (do_rtp || do_rtcp))
2868     goto no_destination;
2869
2870   /* try to construct the fakesrc to the RTP port of the server to open up any
2871    * NAT firewalls */
2872   if (do_rtp) {
2873     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
2874         rtp_port);
2875
2876     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
2877     stream->udpsink[0] =
2878         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
2879     g_free (uri);
2880     if (stream->udpsink[0] == NULL)
2881       goto no_sink_element;
2882
2883     /* don't join multicast group, we will have the source socket do that */
2884     /* no sync or async state changes needed */
2885     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
2886         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
2887     if (ttl > 0)
2888       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
2889
2890     if (stream->udpsrc[0]) {
2891       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
2892        * so that NAT firewalls will open a hole for us */
2893       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
2894       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
2895       /* configure socket and make sure udpsink does not close it when shutting
2896        * down, it belongs to udpsrc after all. */
2897       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
2898           "close-socket", FALSE, NULL);
2899       g_object_unref (socket);
2900     }
2901
2902     /* the source for the dummy packets to open up NAT */
2903     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
2904     if (stream->fakesrc == NULL)
2905       goto no_fakesrc_element;
2906
2907     /* random data in 5 buffers, a size of 200 bytes should be fine */
2908     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
2909         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
2910
2911     /* we don't want to consider this a sink */
2912     GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
2913
2914     /* keep everything locked */
2915     gst_element_set_locked_state (stream->udpsink[0], TRUE);
2916     gst_element_set_locked_state (stream->fakesrc, TRUE);
2917
2918     gst_object_ref (stream->udpsink[0]);
2919     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
2920     gst_object_ref (stream->fakesrc);
2921     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
2922
2923     gst_element_link (stream->fakesrc, stream->udpsink[0]);
2924   }
2925   if (do_rtcp) {
2926     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
2927         rtcp_port);
2928
2929     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
2930     stream->udpsink[1] =
2931         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
2932     g_free (uri);
2933     if (stream->udpsink[1] == NULL)
2934       goto no_sink_element;
2935
2936     /* don't join multicast group, we will have the source socket do that */
2937     /* no sync or async state changes needed */
2938     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
2939         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
2940     if (ttl > 0)
2941       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
2942
2943     if (stream->udpsrc[1]) {
2944       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
2945        * because some servers check the port number of where it sends RTCP to identify
2946        * the RTCP packets it receives */
2947       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
2948       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
2949       /* configure socket and make sure udpsink does not close it when shutting
2950        * down, it belongs to udpsrc after all. */
2951       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
2952           "close-socket", FALSE, NULL);
2953       g_object_unref (socket);
2954     }
2955
2956     /* we don't want to consider this a sink */
2957     GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
2958
2959     /* we keep this playing always */
2960     gst_element_set_locked_state (stream->udpsink[1], TRUE);
2961     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
2962
2963     gst_object_ref (stream->udpsink[1]);
2964     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
2965
2966     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
2967
2968     /* get session RTCP pad */
2969     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2970     pad = gst_element_get_request_pad (src->manager, name);
2971     g_free (name);
2972
2973     /* and link */
2974     if (pad) {
2975       gst_pad_link (pad, stream->rtcppad);
2976       gst_object_unref (pad);
2977     }
2978   }
2979
2980   return TRUE;
2981
2982   /* ERRORS */
2983 no_destination:
2984   {
2985     GST_DEBUG_OBJECT (src, "no destination address specified");
2986     return FALSE;
2987   }
2988 no_sink_element:
2989   {
2990     GST_DEBUG_OBJECT (src, "no UDP sink element found");
2991     return FALSE;
2992   }
2993 no_fakesrc_element:
2994   {
2995     GST_DEBUG_OBJECT (src, "no fakesrc element found");
2996     return FALSE;
2997   }
2998 }
2999
3000 /* sets up all elements needed for streaming over the specified transport.
3001  * Does not yet expose the element pads, this will be done when there is actuall
3002  * dataflow detected, which might never happen when UDP is blocked in a
3003  * firewall, for example.
3004  */
3005 static gboolean
3006 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3007     GstRTSPTransport * transport)
3008 {
3009   GstRTSPSrc *src;
3010   GstPad *outpad = NULL;
3011   GstPadTemplate *template;
3012   gchar *name;
3013   GstStructure *s;
3014   const gchar *mime;
3015
3016   src = stream->parent;
3017
3018   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3019
3020   s = gst_caps_get_structure (stream->caps, 0);
3021
3022   /* get the proper mime type for this stream now */
3023   if (gst_rtsp_transport_get_mime (transport->trans, &mime) < 0)
3024     goto unknown_transport;
3025   if (!mime)
3026     goto unknown_transport;
3027
3028   /* configure the final mime type */
3029   GST_DEBUG_OBJECT (src, "setting mime to %s", mime);
3030   gst_structure_set_name (s, mime);
3031
3032   /* try to get and configure a manager, channelpad[0-1] will be configured with
3033    * the pads for the manager, or NULL when no manager is needed. */
3034   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3035     goto no_manager;
3036
3037   switch (transport->lower_transport) {
3038     case GST_RTSP_LOWER_TRANS_TCP:
3039       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3040         goto transport_failed;
3041       break;
3042     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3043       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3044         goto transport_failed;
3045       /* fallthrough, the rest is the same for UDP and MCAST */
3046     case GST_RTSP_LOWER_TRANS_UDP:
3047       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3048         goto transport_failed;
3049       /* configure udpsinks back to the server for RTCP messages and for the
3050        * dummy RTP messages to open NAT. */
3051       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3052         goto transport_failed;
3053       break;
3054     default:
3055       goto unknown_transport;
3056   }
3057
3058   if (outpad) {
3059     GST_DEBUG_OBJECT (src, "creating ghostpad");
3060
3061     gst_pad_use_fixed_caps (outpad);
3062
3063     /* create ghostpad, don't add just yet, this will be done when we activate
3064      * the stream. */
3065     name = g_strdup_printf ("stream_%u", stream->id);
3066     template = gst_static_pad_template_get (&rtptemplate);
3067     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3068     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3069     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3070     gst_object_unref (template);
3071     g_free (name);
3072
3073     gst_object_unref (outpad);
3074   }
3075   /* mark pad as ok */
3076   stream->last_ret = GST_FLOW_OK;
3077
3078   return TRUE;
3079
3080   /* ERRORS */
3081 transport_failed:
3082   {
3083     GST_DEBUG_OBJECT (src, "failed to configure transport");
3084     return FALSE;
3085   }
3086 unknown_transport:
3087   {
3088     GST_DEBUG_OBJECT (src, "unknown transport");
3089     return FALSE;
3090   }
3091 no_manager:
3092   {
3093     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3094     return FALSE;
3095   }
3096 }
3097
3098 /* send a couple of dummy random packets on the receiver RTP port to the server,
3099  * this should make a firewall think we initiated the data transfer and
3100  * hopefully allow packets to go from the sender port to our RTP receiver port */
3101 static gboolean
3102 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3103 {
3104   GList *walk;
3105
3106   if (src->nat_method != GST_RTSP_NAT_DUMMY)
3107     return TRUE;
3108
3109   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3110     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3111
3112     if (stream->fakesrc && stream->udpsink[0]) {
3113       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3114       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3115       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3116       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3117       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3118     }
3119   }
3120   return TRUE;
3121 }
3122
3123 /* Adds the source pads of all configured streams to the element.
3124  * This code is performed when we detected dataflow.
3125  *
3126  * We detect dataflow from either the _loop function or with pad probes on the
3127  * udp sources.
3128  */
3129 static gboolean
3130 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3131 {
3132   GList *walk;
3133
3134   GST_DEBUG_OBJECT (src, "activating streams");
3135
3136   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3137     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3138
3139     if (stream->udpsrc[0]) {
3140       /* remove timeout, we are streaming now and timeouts will be handled by
3141        * the session manager and jitter buffer */
3142       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3143     }
3144     if (stream->srcpad) {
3145       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3146       gst_pad_set_active (stream->srcpad, TRUE);
3147
3148       /* if we don't have a session manager, set the caps now. If we have a
3149        * session, we will get a notification of the pad and the caps. */
3150       if (!src->manager) {
3151         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3152         gst_pad_set_caps (stream->srcpad, stream->caps);
3153       }
3154       /* add the pad */
3155       if (!stream->added) {
3156         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3157         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3158         stream->added = TRUE;
3159       }
3160     }
3161   }
3162
3163   /* unblock all pads */
3164   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3165     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3166
3167     if (stream->blockid) {
3168       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3169       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3170       stream->blockid = 0;
3171     }
3172   }
3173
3174   return TRUE;
3175 }
3176
3177 static void
3178 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3179     gboolean reset_manager)
3180 {
3181   GList *walk;
3182   guint64 start, stop;
3183   gdouble play_speed, play_scale;
3184
3185   GST_DEBUG_OBJECT (src, "configuring stream caps");
3186
3187   start = segment->position;
3188   stop = segment->duration;
3189   play_speed = segment->rate;
3190   play_scale = segment->applied_rate;
3191
3192   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3193     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3194     GstCaps *caps;
3195
3196     if ((caps = stream->caps)) {
3197       caps = gst_caps_make_writable (caps);
3198       /* update caps */
3199       if (stream->timebase != -1)
3200         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3201             (guint) stream->timebase, NULL);
3202       if (stream->seqbase != -1)
3203         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3204             (guint) stream->seqbase, NULL);
3205       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3206       if (stop != -1)
3207         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3208       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3209       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3210
3211       stream->caps = caps;
3212     }
3213     GST_DEBUG_OBJECT (src, "stream %p, caps %" GST_PTR_FORMAT, stream, caps);
3214   }
3215   if (reset_manager && src->manager) {
3216     GST_DEBUG_OBJECT (src, "clear session");
3217     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3218   }
3219 }
3220
3221 static GstFlowReturn
3222 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3223     GstFlowReturn ret)
3224 {
3225   GList *streams;
3226
3227   /* store the value */
3228   stream->last_ret = ret;
3229
3230   /* if it's success we can return the value right away */
3231   if (ret == GST_FLOW_OK)
3232     goto done;
3233
3234   /* any other error that is not-linked can be returned right
3235    * away */
3236   if (ret != GST_FLOW_NOT_LINKED)
3237     goto done;
3238
3239   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3240   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3241     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3242
3243     ret = ostream->last_ret;
3244     /* some other return value (must be SUCCESS but we can return
3245      * other values as well) */
3246     if (ret != GST_FLOW_NOT_LINKED)
3247       goto done;
3248   }
3249   /* if we get here, all other pads were unlinked and we return
3250    * NOT_LINKED then */
3251 done:
3252   return ret;
3253 }
3254
3255 static gboolean
3256 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
3257     GstEvent * event)
3258 {
3259   gboolean res = TRUE;
3260
3261   /* only streams that have a connection to the outside world */
3262   if (stream->srcpad == NULL)
3263     goto done;
3264
3265   if (stream->udpsrc[0]) {
3266     gst_event_ref (event);
3267     res = gst_element_send_event (stream->udpsrc[0], event);
3268   } else if (stream->channelpad[0]) {
3269     gst_event_ref (event);
3270     if (GST_PAD_IS_SRC (stream->channelpad[0]))
3271       res = gst_pad_push_event (stream->channelpad[0], event);
3272     else
3273       res = gst_pad_send_event (stream->channelpad[0], event);
3274   }
3275
3276   if (stream->udpsrc[1]) {
3277     gst_event_ref (event);
3278     res &= gst_element_send_event (stream->udpsrc[1], event);
3279   } else if (stream->channelpad[1]) {
3280     gst_event_ref (event);
3281     if (GST_PAD_IS_SRC (stream->channelpad[1]))
3282       res &= gst_pad_push_event (stream->channelpad[1], event);
3283     else
3284       res &= gst_pad_send_event (stream->channelpad[1], event);
3285   }
3286
3287 done:
3288   gst_event_unref (event);
3289
3290   return res;
3291 }
3292
3293 static gboolean
3294 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
3295 {
3296   GList *streams;
3297   gboolean res = TRUE;
3298
3299   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3300     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3301
3302     gst_event_ref (event);
3303     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
3304   }
3305   gst_event_unref (event);
3306
3307   return res;
3308 }
3309
3310 static GstRTSPResult
3311 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3312     gboolean async)
3313 {
3314   GstRTSPResult res;
3315
3316   if (info->connection == NULL) {
3317     if (info->url == NULL) {
3318       GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
3319       if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
3320         goto parse_error;
3321     }
3322
3323     /* create connection */
3324     GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
3325     if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
3326       goto could_not_create;
3327
3328     if (info->url_str)
3329       g_free (info->url_str);
3330     info->url_str = gst_rtsp_url_get_request_uri (info->url);
3331
3332     GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
3333
3334     if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
3335       gst_rtsp_connection_set_tunneled (info->connection, TRUE);
3336
3337     if (src->proxy_host) {
3338       GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
3339           src->proxy_port);
3340       gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
3341           src->proxy_port);
3342     }
3343   }
3344
3345   if (!info->connected) {
3346     /* connect */
3347     if (async)
3348       GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
3349           ("Connecting to %s", info->location));
3350     GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
3351     if ((res =
3352             gst_rtsp_connection_connect (info->connection,
3353                 src->ptcp_timeout)) < 0)
3354       goto could_not_connect;
3355
3356     info->connected = TRUE;
3357   }
3358   return GST_RTSP_OK;
3359
3360   /* ERRORS */
3361 parse_error:
3362   {
3363     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
3364     return res;
3365   }
3366 could_not_create:
3367   {
3368     gchar *str = gst_rtsp_strresult (res);
3369     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
3370     g_free (str);
3371     return res;
3372   }
3373 could_not_connect:
3374   {
3375     gchar *str = gst_rtsp_strresult (res);
3376     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
3377     g_free (str);
3378     return res;
3379   }
3380 }
3381
3382 static GstRTSPResult
3383 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
3384     gboolean free)
3385 {
3386   GST_RTSP_STATE_LOCK (src);
3387   if (info->connected) {
3388     GST_DEBUG_OBJECT (src, "closing connection...");
3389     gst_rtsp_connection_close (info->connection);
3390     info->connected = FALSE;
3391   }
3392   if (free && info->connection) {
3393     /* free connection */
3394     GST_DEBUG_OBJECT (src, "freeing connection...");
3395     gst_rtsp_connection_free (info->connection);
3396     info->connection = NULL;
3397   }
3398   GST_RTSP_STATE_UNLOCK (src);
3399   return GST_RTSP_OK;
3400 }
3401
3402 static GstRTSPResult
3403 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3404     gboolean async)
3405 {
3406   GstRTSPResult res;
3407
3408   GST_DEBUG_OBJECT (src, "reconnecting connection...");
3409   gst_rtsp_conninfo_close (src, info, FALSE);
3410   res = gst_rtsp_conninfo_connect (src, info, async);
3411
3412   return res;
3413 }
3414
3415 static void
3416 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
3417 {
3418   GList *walk;
3419
3420   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
3421   GST_RTSP_STATE_LOCK (src);
3422   if (src->conninfo.connection) {
3423     GST_DEBUG_OBJECT (src, "connection flush");
3424     gst_rtsp_connection_flush (src->conninfo.connection, flush);
3425   }
3426   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3427     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3428     GST_DEBUG_OBJECT (src, "stream %p flush", stream);
3429     if (stream->conninfo.connection)
3430       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
3431   }
3432   GST_RTSP_STATE_UNLOCK (src);
3433 }
3434
3435 /* FIXME, handle server request, reply with OK, for now */
3436 static GstRTSPResult
3437 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
3438     GstRTSPMessage * request)
3439 {
3440   GstRTSPMessage response = { 0 };
3441   GstRTSPResult res;
3442
3443   GST_DEBUG_OBJECT (src, "got server request message");
3444
3445   if (src->debug)
3446     gst_rtsp_message_dump (request);
3447
3448   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
3449
3450   if (res == GST_RTSP_ENOTIMPL) {
3451     /* default implementation, send OK */
3452     res =
3453         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
3454         request);
3455     if (res < 0)
3456       goto send_error;
3457
3458     GST_DEBUG_OBJECT (src, "replying with OK");
3459
3460     if (src->debug)
3461       gst_rtsp_message_dump (&response);
3462
3463     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
3464     if (res < 0)
3465       goto send_error;
3466
3467     gst_rtsp_message_unset (&response);
3468   } else if (res == GST_RTSP_EEOF)
3469     return res;
3470
3471   return GST_RTSP_OK;
3472
3473   /* ERRORS */
3474 send_error:
3475   {
3476     gst_rtsp_message_unset (&response);
3477     return res;
3478   }
3479 }
3480
3481 /* send server keep-alive */
3482 static GstRTSPResult
3483 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
3484 {
3485   GstRTSPMessage request = { 0 };
3486   GstRTSPResult res;
3487   GstRTSPMethod method;
3488   gchar *control;
3489
3490   if (src->do_rtsp_keep_alive == FALSE) {
3491     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
3492     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3493     return GST_RTSP_OK;
3494   }
3495
3496   GST_DEBUG_OBJECT (src, "creating server keep-alive");
3497
3498   /* find a method to use for keep-alive */
3499   if (src->methods & GST_RTSP_GET_PARAMETER)
3500     method = GST_RTSP_GET_PARAMETER;
3501   else
3502     method = GST_RTSP_OPTIONS;
3503
3504   if (src->control)
3505     control = src->control;
3506   else
3507     control = src->conninfo.url_str;
3508
3509   if (control == NULL)
3510     goto no_control;
3511
3512   res = gst_rtsp_message_init_request (&request, method, control);
3513   if (res < 0)
3514     goto send_error;
3515
3516   if (src->debug)
3517     gst_rtsp_message_dump (&request);
3518
3519   res =
3520       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
3521       NULL);
3522   if (res < 0)
3523     goto send_error;
3524
3525   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3526   gst_rtsp_message_unset (&request);
3527
3528   return GST_RTSP_OK;
3529
3530   /* ERRORS */
3531 no_control:
3532   {
3533     GST_WARNING_OBJECT (src, "no control url to send keepalive");
3534     return GST_RTSP_OK;
3535   }
3536 send_error:
3537   {
3538     gchar *str = gst_rtsp_strresult (res);
3539
3540     gst_rtsp_message_unset (&request);
3541     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
3542         ("Could not send keep-alive. (%s)", str));
3543     g_free (str);
3544     return res;
3545   }
3546 }
3547
3548 static GstFlowReturn
3549 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
3550 {
3551   GstRTSPMessage message = { 0 };
3552   GstRTSPResult res;
3553   gint channel;
3554   GstRTSPStream *stream;
3555   GstPad *outpad = NULL;
3556   guint8 *data;
3557   guint size;
3558   GstFlowReturn ret = GST_FLOW_OK;
3559   GstBuffer *buf;
3560   gboolean is_rtcp, have_data;
3561
3562   /* here we are only interested in data messages */
3563   have_data = FALSE;
3564   do {
3565     GTimeVal tv_timeout;
3566
3567     /* get the next timeout interval */
3568     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3569
3570     /* see if the timeout period expired */
3571     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
3572       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
3573       /* send keep-alive, only act on interrupt, a warning will be posted for
3574        * other errors. */
3575       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3576         goto interrupt;
3577       /* get new timeout */
3578       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3579     }
3580
3581     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
3582         tv_timeout.tv_sec, tv_timeout.tv_usec);
3583
3584     /* protect the connection with the connection lock so that we can see when
3585      * we are finished doing server communication */
3586     res =
3587         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
3588         &message, src->ptcp_timeout);
3589
3590     switch (res) {
3591       case GST_RTSP_OK:
3592         GST_DEBUG_OBJECT (src, "we received a server message");
3593         break;
3594       case GST_RTSP_EINTR:
3595         /* we got interrupted this means we need to stop */
3596         goto interrupt;
3597       case GST_RTSP_ETIMEOUT:
3598         /* no reply, send keep alive */
3599         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
3600         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3601           goto interrupt;
3602         continue;
3603       case GST_RTSP_EEOF:
3604         /* go EOS when the server closed the connection */
3605         goto server_eof;
3606       default:
3607         goto receive_error;
3608     }
3609
3610     switch (message.type) {
3611       case GST_RTSP_MESSAGE_REQUEST:
3612         /* server sends us a request message, handle it */
3613         res =
3614             gst_rtspsrc_handle_request (src, src->conninfo.connection,
3615             &message);
3616         if (res == GST_RTSP_EEOF)
3617           goto server_eof;
3618         else if (res < 0)
3619           goto handle_request_failed;
3620         break;
3621       case GST_RTSP_MESSAGE_RESPONSE:
3622         /* we ignore response messages */
3623         GST_DEBUG_OBJECT (src, "ignoring response message");
3624         if (src->debug)
3625           gst_rtsp_message_dump (&message);
3626         break;
3627       case GST_RTSP_MESSAGE_DATA:
3628         GST_DEBUG_OBJECT (src, "got data message");
3629         have_data = TRUE;
3630         break;
3631       default:
3632         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
3633             message.type);
3634         break;
3635     }
3636   }
3637   while (!have_data);
3638
3639   channel = message.type_data.data.channel;
3640
3641   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
3642   if (!stream)
3643     goto unknown_stream;
3644
3645   if (channel == stream->channel[0]) {
3646     outpad = stream->channelpad[0];
3647     is_rtcp = FALSE;
3648   } else if (channel == stream->channel[1]) {
3649     outpad = stream->channelpad[1];
3650     is_rtcp = TRUE;
3651   } else {
3652     is_rtcp = FALSE;
3653   }
3654
3655   /* take a look at the body to figure out what we have */
3656   gst_rtsp_message_get_body (&message, &data, &size);
3657   if (size < 2)
3658     goto invalid_length;
3659
3660   /* channels are not correct on some servers, do extra check */
3661   if (data[1] >= 200 && data[1] <= 204) {
3662     /* hmm RTCP message switch to the RTCP pad of the same stream. */
3663     outpad = stream->channelpad[1];
3664     is_rtcp = TRUE;
3665   }
3666
3667   /* we have no clue what this is, just ignore then. */
3668   if (outpad == NULL)
3669     goto unknown_stream;
3670
3671   /* take the message body for further processing */
3672   gst_rtsp_message_steal_body (&message, &data, &size);
3673
3674   /* strip the trailing \0 */
3675   size -= 1;
3676
3677   buf = gst_buffer_new ();
3678   gst_buffer_append_memory (buf,
3679       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
3680
3681   /* don't need message anymore */
3682   gst_rtsp_message_unset (&message);
3683
3684   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
3685       channel);
3686
3687   if (src->need_activate) {
3688     gst_rtspsrc_activate_streams (src);
3689     src->need_activate = FALSE;
3690   }
3691
3692   if (src->base_time == -1) {
3693     /* Take current running_time. This timestamp will be put on
3694      * the first buffer of each stream because we are a live source and so we
3695      * timestamp with the running_time. When we are dealing with TCP, we also
3696      * only timestamp the first buffer (using the DISCONT flag) because a server
3697      * typically bursts data, for which we don't want to compensate by speeding
3698      * up the media. The other timestamps will be interpollated from this one
3699      * using the RTP timestamps. */
3700     GST_OBJECT_LOCK (src);
3701     if (GST_ELEMENT_CLOCK (src)) {
3702       GstClockTime now;
3703       GstClockTime base_time;
3704
3705       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
3706       base_time = GST_ELEMENT_CAST (src)->base_time;
3707
3708       src->base_time = now - base_time;
3709
3710       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
3711           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
3712     }
3713     GST_OBJECT_UNLOCK (src);
3714   }
3715
3716   if (stream->discont && !is_rtcp) {
3717     /* mark first RTP buffer as discont */
3718     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3719     stream->discont = FALSE;
3720     /* first buffer gets the timestamp, other buffers are not timestamped and
3721      * their presentation time will be interpollated from the rtp timestamps. */
3722     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
3723         GST_TIME_ARGS (src->base_time));
3724
3725     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
3726   }
3727
3728   /* chain to the peer pad */
3729   if (GST_PAD_IS_SINK (outpad))
3730     ret = gst_pad_chain (outpad, buf);
3731   else
3732     ret = gst_pad_push (outpad, buf);
3733
3734   if (!is_rtcp) {
3735     /* combine all stream flows for the data transport */
3736     ret = gst_rtspsrc_combine_flows (src, stream, ret);
3737   }
3738   return ret;
3739
3740   /* ERRORS */
3741 unknown_stream:
3742   {
3743     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
3744     gst_rtsp_message_unset (&message);
3745     return GST_FLOW_OK;
3746   }
3747 server_eof:
3748   {
3749     GST_DEBUG_OBJECT (src, "we got an eof from the server");
3750     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3751         ("The server closed the connection."));
3752     src->conninfo.connected = FALSE;
3753     gst_rtsp_message_unset (&message);
3754     return GST_FLOW_EOS;
3755   }
3756 interrupt:
3757   {
3758     gst_rtsp_message_unset (&message);
3759     GST_DEBUG_OBJECT (src, "got interrupted: stop connection flush");
3760     gst_rtspsrc_connection_flush (src, FALSE);
3761     return GST_FLOW_FLUSHING;
3762   }
3763 receive_error:
3764   {
3765     gchar *str = gst_rtsp_strresult (res);
3766
3767     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
3768         ("Could not receive message. (%s)", str));
3769     g_free (str);
3770
3771     gst_rtsp_message_unset (&message);
3772     return GST_FLOW_ERROR;
3773   }
3774 handle_request_failed:
3775   {
3776     gchar *str = gst_rtsp_strresult (res);
3777
3778     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
3779         ("Could not handle server message. (%s)", str));
3780     g_free (str);
3781     gst_rtsp_message_unset (&message);
3782     return GST_FLOW_ERROR;
3783   }
3784 invalid_length:
3785   {
3786     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3787         ("Short message received, ignoring."));
3788     gst_rtsp_message_unset (&message);
3789     return GST_FLOW_OK;
3790   }
3791 }
3792
3793 static GstFlowReturn
3794 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
3795 {
3796   GstRTSPResult res;
3797   GstRTSPMessage message = { 0 };
3798   gint retry = 0;
3799
3800   while (TRUE) {
3801     GTimeVal tv_timeout;
3802
3803     /* get the next timeout interval */
3804     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3805
3806     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
3807         (gint) tv_timeout.tv_sec);
3808
3809     gst_rtsp_message_unset (&message);
3810
3811     /* we should continue reading the TCP socket because the server might
3812      * send us requests. When the session timeout expires, we need to send a
3813      * keep-alive request to keep the session open. */
3814     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
3815         &message, &tv_timeout);
3816
3817     switch (res) {
3818       case GST_RTSP_OK:
3819         GST_DEBUG_OBJECT (src, "we received a server message");
3820         break;
3821       case GST_RTSP_EINTR:
3822         /* we got interrupted, see what we have to do */
3823         goto interrupt;
3824       case GST_RTSP_ETIMEOUT:
3825         /* send keep-alive, ignore the result, a warning will be posted. */
3826         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
3827         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3828           goto interrupt;
3829         continue;
3830       case GST_RTSP_EEOF:
3831         /* server closed the connection. not very fatal for UDP, reconnect and
3832          * see what happens. */
3833         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3834             ("The server closed the connection."));
3835         if ((res =
3836                 gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
3837           goto connect_error;
3838
3839         continue;
3840       case GST_RTSP_ENET:
3841         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
3842       default:
3843         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3844             ("Unhandled return value %d.", res));
3845         goto receive_error;
3846     }
3847
3848     switch (message.type) {
3849       case GST_RTSP_MESSAGE_REQUEST:
3850         /* server sends us a request message, handle it */
3851         res =
3852             gst_rtspsrc_handle_request (src, src->conninfo.connection,
3853             &message);
3854         if (res == GST_RTSP_EEOF)
3855           goto server_eof;
3856         else if (res < 0)
3857           goto handle_request_failed;
3858         break;
3859       case GST_RTSP_MESSAGE_RESPONSE:
3860         /* we ignore response and data messages */
3861         GST_DEBUG_OBJECT (src, "ignoring response message");
3862         if (src->debug)
3863           gst_rtsp_message_dump (&message);
3864         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
3865           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
3866           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
3867             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
3868             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3869               goto interrupt;
3870           }
3871         } else {
3872           retry = 0;
3873         }
3874         break;
3875       case GST_RTSP_MESSAGE_DATA:
3876         /* we ignore response and data messages */
3877         GST_DEBUG_OBJECT (src, "ignoring data message");
3878         break;
3879       default:
3880         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
3881             message.type);
3882         break;
3883     }
3884   }
3885
3886   /* we get here when the connection got interrupted */
3887 interrupt:
3888   {
3889     gst_rtsp_message_unset (&message);
3890     GST_DEBUG_OBJECT (src, "got interrupted: stop connection flush");
3891     gst_rtspsrc_connection_flush (src, FALSE);
3892     return GST_FLOW_FLUSHING;
3893   }
3894 connect_error:
3895   {
3896     gchar *str = gst_rtsp_strresult (res);
3897     GstFlowReturn ret;
3898
3899     src->conninfo.connected = FALSE;
3900     if (res != GST_RTSP_EINTR) {
3901       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
3902           ("Could not connect to server. (%s)", str));
3903       g_free (str);
3904       ret = GST_FLOW_ERROR;
3905     } else {
3906       ret = GST_FLOW_FLUSHING;
3907     }
3908     return ret;
3909   }
3910 receive_error:
3911   {
3912     gchar *str = gst_rtsp_strresult (res);
3913
3914     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
3915         ("Could not receive message. (%s)", str));
3916     g_free (str);
3917     return GST_FLOW_ERROR;
3918   }
3919 handle_request_failed:
3920   {
3921     gchar *str = gst_rtsp_strresult (res);
3922     GstFlowReturn ret;
3923
3924     gst_rtsp_message_unset (&message);
3925     if (res != GST_RTSP_EINTR) {
3926       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
3927           ("Could not handle server message. (%s)", str));
3928       g_free (str);
3929       ret = GST_FLOW_ERROR;
3930     } else {
3931       ret = GST_FLOW_FLUSHING;
3932     }
3933     return ret;
3934   }
3935 server_eof:
3936   {
3937     GST_DEBUG_OBJECT (src, "we got an eof from the server");
3938     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3939         ("The server closed the connection."));
3940     src->conninfo.connected = FALSE;
3941     gst_rtsp_message_unset (&message);
3942     return GST_FLOW_EOS;
3943   }
3944 }
3945
3946 static GstRTSPResult
3947 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
3948 {
3949   GstRTSPResult res = GST_RTSP_OK;
3950   gboolean restart;
3951
3952   GST_DEBUG_OBJECT (src, "doing reconnect");
3953
3954   GST_OBJECT_LOCK (src);
3955   /* only restart when the pads were not yet activated, else we were
3956    * streaming over UDP */
3957   restart = src->need_activate;
3958   GST_OBJECT_UNLOCK (src);
3959
3960   /* no need to restart, we're done */
3961   if (!restart)
3962     goto done;
3963
3964   /* we can try only TCP now */
3965   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
3966
3967   /* close and cleanup our state */
3968   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
3969     goto done;
3970
3971   /* see if we have TCP left to try. Also don't try TCP when we were configured
3972    * with an SDP. */
3973   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
3974     goto no_protocols;
3975
3976   /* We post a warning message now to inform the user
3977    * that nothing happened. It's most likely a firewall thing. */
3978   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3979       ("Could not receive any UDP packets for %.4f seconds, maybe your "
3980           "firewall is blocking it. Retrying using a TCP connection.",
3981           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
3982
3983   /* open new connection using tcp */
3984   if (gst_rtspsrc_open (src, async) < 0)
3985     goto open_failed;
3986
3987   /* start playback */
3988   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
3989     goto play_failed;
3990
3991 done:
3992   return res;
3993
3994   /* ERRORS */
3995 no_protocols:
3996   {
3997     src->cur_protocols = 0;
3998     /* no transport possible, post an error and stop */
3999     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4000         ("Could not receive any UDP packets for %.4f seconds, maybe your "
4001             "firewall is blocking it. No other protocols to try.",
4002             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4003     return GST_RTSP_ERROR;
4004   }
4005 open_failed:
4006   {
4007     GST_DEBUG_OBJECT (src, "open failed");
4008     return GST_RTSP_OK;
4009   }
4010 play_failed:
4011   {
4012     GST_DEBUG_OBJECT (src, "play failed");
4013     return GST_RTSP_OK;
4014   }
4015 }
4016
4017 static void
4018 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4019 {
4020   switch (cmd) {
4021     case CMD_OPEN:
4022       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4023       break;
4024     case CMD_PLAY:
4025       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4026       break;
4027     case CMD_PAUSE:
4028       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4029       break;
4030     case CMD_CLOSE:
4031       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4032       break;
4033     default:
4034       break;
4035   }
4036 }
4037
4038 static void
4039 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4040 {
4041   switch (cmd) {
4042     case CMD_OPEN:
4043       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4044       break;
4045     case CMD_PLAY:
4046       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4047       break;
4048     case CMD_PAUSE:
4049       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4050       break;
4051     case CMD_CLOSE:
4052       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4053       break;
4054     default:
4055       break;
4056   }
4057 }
4058
4059 static void
4060 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4061 {
4062   switch (cmd) {
4063     case CMD_OPEN:
4064       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4065       break;
4066     case CMD_PLAY:
4067       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4068       break;
4069     case CMD_PAUSE:
4070       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4071       break;
4072     case CMD_CLOSE:
4073       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4074       break;
4075     default:
4076       break;
4077   }
4078 }
4079
4080 static void
4081 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4082 {
4083   switch (cmd) {
4084     case CMD_OPEN:
4085       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4086       break;
4087     case CMD_PLAY:
4088       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4089       break;
4090     case CMD_PAUSE:
4091       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4092       break;
4093     case CMD_CLOSE:
4094       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4095       break;
4096     default:
4097       break;
4098   }
4099 }
4100
4101 static void
4102 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4103 {
4104   if (ret == GST_RTSP_OK)
4105     gst_rtspsrc_loop_complete_cmd (src, cmd);
4106   else if (ret == GST_RTSP_EINTR)
4107     gst_rtspsrc_loop_cancel_cmd (src, cmd);
4108   else
4109     gst_rtspsrc_loop_error_cmd (src, cmd);
4110 }
4111
4112 static void
4113 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4114 {
4115   gint old;
4116
4117   /* start new request */
4118   gst_rtspsrc_loop_start_cmd (src, cmd);
4119
4120   GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4121
4122   GST_OBJECT_LOCK (src);
4123   old = src->pending_cmd;
4124   if (old != CMD_WAIT) {
4125     src->pending_cmd = CMD_WAIT;
4126     GST_OBJECT_UNLOCK (src);
4127     /* cancel previous request */
4128     gst_rtspsrc_loop_cancel_cmd (src, old);
4129     GST_OBJECT_LOCK (src);
4130   }
4131   src->pending_cmd = cmd;
4132   /* interrupt if allowed */
4133   if (src->busy_cmd & mask) {
4134     GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4135     gst_rtspsrc_connection_flush (src, TRUE);
4136   } else {
4137     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4138   }
4139   if (src->task)
4140     gst_task_start (src->task);
4141   GST_OBJECT_UNLOCK (src);
4142 }
4143
4144 static gboolean
4145 gst_rtspsrc_loop (GstRTSPSrc * src)
4146 {
4147   GstFlowReturn ret;
4148
4149   if (!src->conninfo.connection || !src->conninfo.connected)
4150     goto no_connection;
4151
4152   if (src->interleaved)
4153     ret = gst_rtspsrc_loop_interleaved (src);
4154   else
4155     ret = gst_rtspsrc_loop_udp (src);
4156
4157   if (ret != GST_FLOW_OK)
4158     goto pause;
4159
4160   return TRUE;
4161
4162   /* ERRORS */
4163 no_connection:
4164   {
4165     GST_WARNING_OBJECT (src, "we are not connected");
4166     ret = GST_FLOW_FLUSHING;
4167     goto pause;
4168   }
4169 pause:
4170   {
4171     const gchar *reason = gst_flow_get_name (ret);
4172
4173     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4174     src->running = FALSE;
4175     if (ret == GST_FLOW_EOS) {
4176       /* perform EOS logic */
4177       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4178         gst_element_post_message (GST_ELEMENT_CAST (src),
4179             gst_message_new_segment_done (GST_OBJECT_CAST (src),
4180                 src->segment.format, src->segment.position));
4181         gst_rtspsrc_push_event (src,
4182             gst_event_new_segment_done (src->segment.format,
4183                 src->segment.position));
4184       } else {
4185         gst_rtspsrc_push_event (src, gst_event_new_eos ());
4186       }
4187     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4188       /* for fatal errors we post an error message, post the error before the
4189        * EOS so the app knows about the error first. */
4190       GST_ELEMENT_ERROR (src, STREAM, FAILED,
4191           ("Internal data flow error."),
4192           ("streaming task paused, reason %s (%d)", reason, ret));
4193       gst_rtspsrc_push_event (src, gst_event_new_eos ());
4194     }
4195     return FALSE;
4196   }
4197 }
4198
4199 #ifndef GST_DISABLE_GST_DEBUG
4200 static const gchar *
4201 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4202 {
4203   gint index = 0;
4204
4205   while (method != 0) {
4206     index++;
4207     method >>= 1;
4208   }
4209   switch (index) {
4210     case 0:
4211       return "None";
4212     case 1:
4213       return "Basic";
4214     case 2:
4215       return "Digest";
4216   }
4217
4218   return "Unknown";
4219 }
4220 #endif
4221
4222 static const gchar *
4223 gst_rtspsrc_skip_lws (const gchar * s)
4224 {
4225   while (g_ascii_isspace (*s))
4226     s++;
4227   return s;
4228 }
4229
4230 static const gchar *
4231 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4232 {
4233   while (s > start && g_ascii_isspace (*(s - 1)))
4234     s--;
4235   return s;
4236 }
4237
4238 static const gchar *
4239 gst_rtspsrc_skip_commas (const gchar * s)
4240 {
4241   /* The grammar allows for multiple commas */
4242   while (g_ascii_isspace (*s) || *s == ',')
4243     s++;
4244   return s;
4245 }
4246
4247 static const gchar *
4248 gst_rtspsrc_skip_item (const gchar * s)
4249 {
4250   gboolean quoted = FALSE;
4251   const gchar *start = s;
4252
4253   /* A list item ends at the last non-whitespace character
4254    * before a comma which is not inside a quoted-string. Or at
4255    * the end of the string.
4256    */
4257   while (*s) {
4258     if (*s == '"')
4259       quoted = !quoted;
4260     else if (quoted) {
4261       if (*s == '\\' && *(s + 1))
4262         s++;
4263     } else {
4264       if (*s == ',')
4265         break;
4266     }
4267     s++;
4268   }
4269
4270   return gst_rtspsrc_unskip_lws (s, start);
4271 }
4272
4273 static void
4274 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4275 {
4276   gchar *src, *dst;
4277
4278   src = quoted_string + 1;
4279   dst = quoted_string;
4280   while (*src && *src != '"') {
4281     if (*src == '\\' && *(src + 1))
4282       src++;
4283     *dst++ = *src++;
4284   }
4285   *dst = '\0';
4286 }
4287
4288 /* Extract the authentication tokens that the server provided for each method
4289  * into an array of structures and give those to the connection object.
4290  */
4291 static void
4292 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4293     const gchar * header, gboolean * stale)
4294 {
4295   GSList *list = NULL, *iter;
4296   const gchar *end;
4297   gchar *item, *eq, *name_end, *value;
4298
4299   g_return_if_fail (stale != NULL);
4300
4301   gst_rtsp_connection_clear_auth_params (conn);
4302   *stale = FALSE;
4303
4304   /* Parse a header whose content is described by RFC2616 as
4305    * "#something", where "something" does not itself contain commas,
4306    * except as part of quoted-strings, into a list of allocated strings.
4307    */
4308   header = gst_rtspsrc_skip_commas (header);
4309   while (*header) {
4310     end = gst_rtspsrc_skip_item (header);
4311     list = g_slist_prepend (list, g_strndup (header, end - header));
4312     header = gst_rtspsrc_skip_commas (end);
4313   }
4314   if (!list)
4315     return;
4316
4317   list = g_slist_reverse (list);
4318   for (iter = list; iter; iter = iter->next) {
4319     item = iter->data;
4320
4321     eq = strchr (item, '=');
4322     if (eq) {
4323       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4324       if (name_end == item) {
4325         /* That's no good... */
4326         g_free (item);
4327         continue;
4328       }
4329
4330       *name_end = '\0';
4331
4332       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4333       if (*value == '"')
4334         gst_rtsp_decode_quoted_string (value);
4335     } else
4336       value = NULL;
4337
4338     if (item && (strcmp (item, "stale") == 0) &&
4339         value && (strcmp (value, "TRUE") == 0))
4340       *stale = TRUE;
4341     gst_rtsp_connection_set_auth_param (conn, item, value);
4342     g_free (item);
4343   }
4344
4345   g_slist_free (list);
4346 }
4347
4348 /* Parse a WWW-Authenticate Response header and determine the
4349  * available authentication methods
4350  *
4351  * This code should also cope with the fact that each WWW-Authenticate
4352  * header can contain multiple challenge methods + tokens
4353  *
4354  * At the moment, for Basic auth, we just do a minimal check and don't
4355  * even parse out the realm */
4356 static void
4357 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4358     GstRTSPConnection * conn, gboolean * stale)
4359 {
4360   gchar *start;
4361
4362   g_return_if_fail (hdr != NULL);
4363   g_return_if_fail (methods != NULL);
4364   g_return_if_fail (stale != NULL);
4365
4366   /* Skip whitespace at the start of the string */
4367   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4368
4369   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4370     *methods |= GST_RTSP_AUTH_BASIC;
4371   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4372     *methods |= GST_RTSP_AUTH_DIGEST;
4373     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4374   }
4375 }
4376
4377 /**
4378  * gst_rtspsrc_setup_auth:
4379  * @src: the rtsp source
4380  *
4381  * Configure a username and password and auth method on the
4382  * connection object based on a response we received from the
4383  * peer.
4384  *
4385  * Currently, this requires that a username and password were supplied
4386  * in the uri. In the future, they may be requested on demand by sending
4387  * a message up the bus.
4388  *
4389  * Returns: TRUE if authentication information could be set up correctly.
4390  */
4391 static gboolean
4392 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4393 {
4394   gchar *user = NULL;
4395   gchar *pass = NULL;
4396   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4397   GstRTSPAuthMethod method;
4398   GstRTSPResult auth_result;
4399   GstRTSPUrl *url;
4400   GstRTSPConnection *conn;
4401   gchar *hdr;
4402   gboolean stale = FALSE;
4403
4404   conn = src->conninfo.connection;
4405
4406   /* Identify the available auth methods and see if any are supported */
4407   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4408           &hdr, 0) == GST_RTSP_OK) {
4409     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4410   }
4411
4412   if (avail_methods == GST_RTSP_AUTH_NONE)
4413     goto no_auth_available;
4414
4415   /* For digest auth, if the response indicates that the session
4416    * data are stale, we just update them in the connection object and
4417    * return TRUE to retry the request */
4418   if (stale)
4419     src->tried_url_auth = FALSE;
4420
4421   url = gst_rtsp_connection_get_url (conn);
4422
4423   /* Do we have username and password available? */
4424   if (url != NULL && !src->tried_url_auth && url->user != NULL
4425       && url->passwd != NULL) {
4426     user = url->user;
4427     pass = url->passwd;
4428     src->tried_url_auth = TRUE;
4429     GST_DEBUG_OBJECT (src,
4430         "Attempting authentication using credentials from the URL");
4431   } else {
4432     user = src->user_id;
4433     pass = src->user_pw;
4434     GST_DEBUG_OBJECT (src,
4435         "Attempting authentication using credentials from the properties");
4436   }
4437
4438   /* FIXME: If the url didn't contain username and password or we tried them
4439    * already, request a username and passwd from the application via some kind
4440    * of credentials request message */
4441
4442   /* If we don't have a username and passwd at this point, bail out. */
4443   if (user == NULL || pass == NULL)
4444     goto no_user_pass;
4445
4446   /* Try to configure for each available authentication method, strongest to
4447    * weakest */
4448   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4449     /* Check if this method is available on the server */
4450     if ((method & avail_methods) == 0)
4451       continue;
4452
4453     /* Pass the credentials to the connection to try on the next request */
4454     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4455     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4456      * ignore it and end up retrying later */
4457     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4458       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4459           gst_rtsp_auth_method_to_string (method));
4460       break;
4461     }
4462   }
4463
4464   if (method == GST_RTSP_AUTH_NONE)
4465     goto no_auth_available;
4466
4467   return TRUE;
4468
4469 no_auth_available:
4470   {
4471     /* Output an error indicating that we couldn't connect because there were
4472      * no supported authentication protocols */
4473     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4474         ("No supported authentication protocol was found"));
4475     return FALSE;
4476   }
4477 no_user_pass:
4478   {
4479     /* We don't fire an error message, we just return FALSE and let the
4480      * normal NOT_AUTHORIZED error be propagated */
4481     return FALSE;
4482   }
4483 }
4484
4485 static GstRTSPResult
4486 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4487     GstRTSPMessage * request, GstRTSPMessage * response,
4488     GstRTSPStatusCode * code)
4489 {
4490   GstRTSPResult res;
4491   GstRTSPStatusCode thecode;
4492   gchar *content_base = NULL;
4493   gint try = 0;
4494
4495 again:
4496   if (!src->short_header)
4497     gst_rtsp_ext_list_before_send (src->extensions, request);
4498
4499   GST_DEBUG_OBJECT (src, "sending message");
4500
4501   if (src->debug)
4502     gst_rtsp_message_dump (request);
4503
4504   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4505   if (res < 0)
4506     goto send_error;
4507
4508   gst_rtsp_connection_reset_timeout (conn);
4509
4510 next:
4511   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4512   if (res < 0)
4513     goto receive_error;
4514
4515   if (src->debug)
4516     gst_rtsp_message_dump (response);
4517
4518   switch (response->type) {
4519     case GST_RTSP_MESSAGE_REQUEST:
4520       res = gst_rtspsrc_handle_request (src, conn, response);
4521       if (res == GST_RTSP_EEOF)
4522         goto server_eof;
4523       else if (res < 0)
4524         goto handle_request_failed;
4525       goto next;
4526     case GST_RTSP_MESSAGE_RESPONSE:
4527       /* ok, a response is good */
4528       GST_DEBUG_OBJECT (src, "received response message");
4529       break;
4530     case GST_RTSP_MESSAGE_DATA:
4531       /* get next response */
4532       GST_DEBUG_OBJECT (src, "ignoring data response message");
4533       goto next;
4534     default:
4535       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4536           response->type);
4537       goto next;
4538   }
4539
4540   thecode = response->type_data.response.code;
4541
4542   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4543
4544   /* if the caller wanted the result code, we store it. */
4545   if (code)
4546     *code = thecode;
4547
4548   /* If the request didn't succeed, bail out before doing any more */
4549   if (thecode != GST_RTSP_STS_OK)
4550     return GST_RTSP_OK;
4551
4552   /* store new content base if any */
4553   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4554       &content_base, 0);
4555   if (content_base) {
4556     g_free (src->content_base);
4557     src->content_base = g_strdup (content_base);
4558   }
4559   gst_rtsp_ext_list_after_send (src->extensions, request, response);
4560
4561   return GST_RTSP_OK;
4562
4563   /* ERRORS */
4564 send_error:
4565   {
4566     gchar *str = gst_rtsp_strresult (res);
4567
4568     if (res != GST_RTSP_EINTR) {
4569       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4570           ("Could not send message. (%s)", str));
4571     } else {
4572       GST_WARNING_OBJECT (src, "send interrupted");
4573     }
4574     g_free (str);
4575     return res;
4576   }
4577 receive_error:
4578   {
4579     switch (res) {
4580       case GST_RTSP_EEOF:
4581         GST_WARNING_OBJECT (src, "server closed connection, doing reconnect");
4582         if (try == 0) {
4583           try++;
4584           /* if reconnect succeeds, try again */
4585           if ((res =
4586                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
4587                       FALSE)) == 0)
4588             goto again;
4589         }
4590         /* only try once after reconnect, then fallthrough and error out */
4591       default:
4592       {
4593         gchar *str = gst_rtsp_strresult (res);
4594
4595         if (res != GST_RTSP_EINTR) {
4596           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4597               ("Could not receive message. (%s)", str));
4598         } else {
4599           GST_WARNING_OBJECT (src, "receive interrupted");
4600         }
4601         g_free (str);
4602         break;
4603       }
4604     }
4605     return res;
4606   }
4607 handle_request_failed:
4608   {
4609     /* ERROR was posted */
4610     gst_rtsp_message_unset (response);
4611     return res;
4612   }
4613 server_eof:
4614   {
4615     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4616     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4617         ("The server closed the connection."));
4618     gst_rtsp_message_unset (response);
4619     return res;
4620   }
4621 }
4622
4623 /**
4624  * gst_rtspsrc_send:
4625  * @src: the rtsp source
4626  * @conn: the connection to send on
4627  * @request: must point to a valid request
4628  * @response: must point to an empty #GstRTSPMessage
4629  * @code: an optional code result
4630  *
4631  * send @request and retrieve the response in @response. optionally @code can be
4632  * non-NULL in which case it will contain the status code of the response.
4633  *
4634  * If This function returns #GST_RTSP_OK, @response will contain a valid response
4635  * message that should be cleaned with gst_rtsp_message_unset() after usage.
4636  *
4637  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
4638  * @response message) if the response code was not 200 (OK).
4639  *
4640  * If the attempt results in an authentication failure, then this will attempt
4641  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
4642  * the request.
4643  *
4644  * Returns: #GST_RTSP_OK if the processing was successful.
4645  */
4646 static GstRTSPResult
4647 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4648     GstRTSPMessage * request, GstRTSPMessage * response,
4649     GstRTSPStatusCode * code)
4650 {
4651   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
4652   GstRTSPResult res = GST_RTSP_ERROR;
4653   gint count;
4654   gboolean retry;
4655   GstRTSPMethod method = GST_RTSP_INVALID;
4656
4657   count = 0;
4658   do {
4659     retry = FALSE;
4660
4661     /* make sure we don't loop forever */
4662     if (count++ > 8)
4663       break;
4664
4665     /* save method so we can disable it when the server complains */
4666     method = request->type_data.request.method;
4667
4668     if ((res =
4669             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
4670       goto error;
4671
4672     switch (int_code) {
4673       case GST_RTSP_STS_UNAUTHORIZED:
4674         if (gst_rtspsrc_setup_auth (src, response)) {
4675           /* Try the request/response again after configuring the auth info
4676            * and loop again */
4677           retry = TRUE;
4678         }
4679         break;
4680       default:
4681         break;
4682     }
4683   } while (retry == TRUE);
4684
4685   /* If the user requested the code, let them handle errors, otherwise
4686    * post an error below */
4687   if (code != NULL)
4688     *code = int_code;
4689   else if (int_code != GST_RTSP_STS_OK)
4690     goto error_response;
4691
4692   return res;
4693
4694   /* ERRORS */
4695 error:
4696   {
4697     GST_DEBUG_OBJECT (src, "got error %d", res);
4698     return res;
4699   }
4700 error_response:
4701   {
4702     res = GST_RTSP_ERROR;
4703
4704     switch (response->type_data.response.code) {
4705       case GST_RTSP_STS_NOT_FOUND:
4706         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
4707                 response->type_data.response.reason));
4708         break;
4709       case GST_RTSP_STS_MOVED_PERMANENTLY:
4710       case GST_RTSP_STS_MOVE_TEMPORARILY:
4711       {
4712         gchar *new_location;
4713         GstRTSPLowerTrans transports;
4714
4715         GST_DEBUG_OBJECT (src, "got redirection");
4716         /* if we don't have a Location Header, we must error */
4717         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
4718                 &new_location, 0) < 0)
4719           break;
4720
4721         /* When we receive a redirect result, we go back to the INIT state after
4722          * parsing the new URI. The caller should do the needed steps to issue
4723          * a new setup when it detects this state change. */
4724         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
4725
4726         /* save current transports */
4727         if (src->conninfo.url)
4728           transports = src->conninfo.url->transports;
4729         else
4730           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
4731
4732         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
4733
4734         /* set old transports */
4735         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
4736           src->conninfo.url->transports = transports;
4737
4738         src->need_redirect = TRUE;
4739         src->state = GST_RTSP_STATE_INIT;
4740         res = GST_RTSP_OK;
4741         break;
4742       }
4743       case GST_RTSP_STS_NOT_ACCEPTABLE:
4744       case GST_RTSP_STS_NOT_IMPLEMENTED:
4745       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
4746         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
4747             gst_rtsp_method_as_text (method));
4748         src->methods &= ~method;
4749         res = GST_RTSP_OK;
4750         break;
4751       default:
4752         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4753             ("Got error response: %d (%s).", response->type_data.response.code,
4754                 response->type_data.response.reason));
4755         break;
4756     }
4757     /* if we return ERROR we should unset the response ourselves */
4758     if (res == GST_RTSP_ERROR)
4759       gst_rtsp_message_unset (response);
4760
4761     return res;
4762   }
4763 }
4764
4765 static GstRTSPResult
4766 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
4767     GstRTSPMessage * response, GstRTSPSrc * src)
4768 {
4769   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
4770       NULL);
4771 }
4772
4773
4774 /* parse the response and collect all the supported methods. We need this
4775  * information so that we don't try to send an unsupported request to the
4776  * server.
4777  */
4778 static gboolean
4779 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
4780 {
4781   GstRTSPHeaderField field;
4782   gchar *respoptions;
4783   gchar **options;
4784   gint indx = 0;
4785   gint i;
4786
4787   /* reset supported methods */
4788   src->methods = 0;
4789
4790   /* Try Allow Header first */
4791   field = GST_RTSP_HDR_ALLOW;
4792   while (TRUE) {
4793     respoptions = NULL;
4794     gst_rtsp_message_get_header (response, field, &respoptions, indx);
4795     if (indx == 0 && !respoptions) {
4796       /* if no Allow header was found then try the Public header... */
4797       field = GST_RTSP_HDR_PUBLIC;
4798       gst_rtsp_message_get_header (response, field, &respoptions, indx);
4799     }
4800     if (!respoptions)
4801       break;
4802
4803     /* If we get here, the server gave a list of supported methods, parse
4804      * them here. The string is like:
4805      *
4806      * OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, ...
4807      */
4808     options = g_strsplit (respoptions, ",", 0);
4809
4810     for (i = 0; options[i]; i++) {
4811       gchar *stripped;
4812       gint method;
4813
4814       stripped = g_strstrip (options[i]);
4815       method = gst_rtsp_find_method (stripped);
4816
4817       /* keep bitfield of supported methods */
4818       if (method != GST_RTSP_INVALID)
4819         src->methods |= method;
4820     }
4821     g_strfreev (options);
4822
4823     indx++;
4824   }
4825
4826   if (src->methods == 0) {
4827     /* neither Allow nor Public are required, assume the server supports
4828      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
4829      * well. */
4830     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
4831     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
4832   }
4833   /* always assume PLAY, FIXME, extensions should be able to override
4834    * this */
4835   src->methods |= GST_RTSP_PLAY;
4836   /* also assume it will support Range */
4837   src->seekable = TRUE;
4838
4839   /* we need describe and setup */
4840   if (!(src->methods & GST_RTSP_DESCRIBE))
4841     goto no_describe;
4842   if (!(src->methods & GST_RTSP_SETUP))
4843     goto no_setup;
4844
4845   return TRUE;
4846
4847   /* ERRORS */
4848 no_describe:
4849   {
4850     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4851         ("Server does not support DESCRIBE."));
4852     return FALSE;
4853   }
4854 no_setup:
4855   {
4856     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4857         ("Server does not support SETUP."));
4858     return FALSE;
4859   }
4860 }
4861
4862 /* masks to be kept in sync with the hardcoded protocol order of preference
4863  * in code below */
4864 static guint protocol_masks[] = {
4865   GST_RTSP_LOWER_TRANS_UDP,
4866   GST_RTSP_LOWER_TRANS_UDP_MCAST,
4867   GST_RTSP_LOWER_TRANS_TCP,
4868   0
4869 };
4870
4871 static GstRTSPResult
4872 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
4873     GstRTSPLowerTrans protocols, gchar ** transports)
4874 {
4875   GstRTSPResult res;
4876   GString *result;
4877   gboolean add_udp_str;
4878
4879   *transports = NULL;
4880
4881   res =
4882       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
4883
4884   if (res < 0)
4885     goto failed;
4886
4887   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
4888
4889   /* extension listed transports, use those */
4890   if (*transports != NULL)
4891     return GST_RTSP_OK;
4892
4893   /* it's the default */
4894   add_udp_str = FALSE;
4895
4896   /* the default RTSP transports */
4897   result = g_string_new ("");
4898   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
4899     GST_DEBUG_OBJECT (src, "adding UDP unicast");
4900
4901     g_string_append (result, "RTP/AVP");
4902     if (add_udp_str)
4903       g_string_append (result, "/UDP");
4904     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
4905   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
4906     GST_DEBUG_OBJECT (src, "adding UDP multicast");
4907
4908     /* we don't have to allocate any UDP ports yet, if the selected transport
4909      * turns out to be multicast we can create them and join the multicast
4910      * group indicated in the transport reply */
4911     if (result->len > 0)
4912       g_string_append (result, ",");
4913     g_string_append (result, "RTP/AVP");
4914     if (add_udp_str)
4915       g_string_append (result, "/UDP");
4916     g_string_append (result, ";multicast");
4917   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
4918     GST_DEBUG_OBJECT (src, "adding TCP");
4919
4920     if (result->len > 0)
4921       g_string_append (result, ",");
4922     g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
4923   }
4924   *transports = g_string_free (result, FALSE);
4925
4926   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
4927
4928   return GST_RTSP_OK;
4929
4930   /* ERRORS */
4931 failed:
4932   {
4933     return res;
4934   }
4935 }
4936
4937 static GstRTSPResult
4938 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
4939     gint orig_rtpport, gint orig_rtcpport)
4940 {
4941   GstRTSPSrc *src;
4942   gint nr_udp, nr_int;
4943   gchar *next, *p;
4944   gint rtpport = 0, rtcpport = 0;
4945   GString *str;
4946
4947   src = stream->parent;
4948
4949   /* find number of placeholders first */
4950   if (strstr (*transports, "%%i2"))
4951     nr_int = 2;
4952   else if (strstr (*transports, "%%i1"))
4953     nr_int = 1;
4954   else
4955     nr_int = 0;
4956
4957   if (strstr (*transports, "%%u2"))
4958     nr_udp = 2;
4959   else if (strstr (*transports, "%%u1"))
4960     nr_udp = 1;
4961   else
4962     nr_udp = 0;
4963
4964   if (nr_udp == 0 && nr_int == 0)
4965     goto done;
4966
4967   if (nr_udp > 0) {
4968     if (!orig_rtpport || !orig_rtcpport) {
4969       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
4970         goto failed;
4971     } else {
4972       rtpport = orig_rtpport;
4973       rtcpport = orig_rtcpport;
4974     }
4975   }
4976
4977   str = g_string_new ("");
4978   p = *transports;
4979   while ((next = strstr (p, "%%"))) {
4980     g_string_append_len (str, p, next - p);
4981     if (next[2] == 'u') {
4982       if (next[3] == '1')
4983         g_string_append_printf (str, "%d", rtpport);
4984       else if (next[3] == '2')
4985         g_string_append_printf (str, "%d", rtcpport);
4986     }
4987     if (next[2] == 'i') {
4988       if (next[3] == '1')
4989         g_string_append_printf (str, "%d", src->free_channel);
4990       else if (next[3] == '2')
4991         g_string_append_printf (str, "%d", src->free_channel + 1);
4992     }
4993
4994     p = next + 4;
4995   }
4996   /* append final part */
4997   g_string_append (str, p);
4998
4999   g_free (*transports);
5000   *transports = g_string_free (str, FALSE);
5001
5002 done:
5003   return GST_RTSP_OK;
5004
5005   /* ERRORS */
5006 failed:
5007   {
5008     return GST_RTSP_ERROR;
5009   }
5010 }
5011
5012 static gboolean
5013 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5014 {
5015   gboolean res = FALSE;
5016
5017   if (stream->caps) {
5018     GstStructure *s;
5019     const gchar *enc = NULL;
5020
5021     s = gst_caps_get_structure (stream->caps, 0);
5022     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5023       res = (strstr (enc, "-REAL") != NULL);
5024     }
5025   }
5026   return res;
5027 }
5028
5029 /* Perform the SETUP request for all the streams.
5030  *
5031  * We ask the server for a specific transport, which initially includes all the
5032  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5033  * two local UDP ports that we send to the server.
5034  *
5035  * Once the server replied with a transport, we configure the other streams
5036  * with the same transport.
5037  *
5038  * This function will also configure the stream for the selected transport,
5039  * which basically means creating the pipeline.
5040  */
5041 static GstRTSPResult
5042 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5043 {
5044   GList *walk;
5045   GstRTSPResult res = GST_RTSP_ERROR;
5046   GstRTSPMessage request = { 0 };
5047   GstRTSPMessage response = { 0 };
5048   GstRTSPStream *stream = NULL;
5049   GstRTSPLowerTrans protocols;
5050   GstRTSPStatusCode code;
5051   gboolean unsupported_real = FALSE;
5052   gint rtpport, rtcpport;
5053   GstRTSPUrl *url;
5054   gchar *hval;
5055
5056   if (src->conninfo.connection) {
5057     url = gst_rtsp_connection_get_url (src->conninfo.connection);
5058     /* we initially allow all configured lower transports. based on the URL
5059      * transports and the replies from the server we narrow them down. */
5060     protocols = url->transports & src->cur_protocols;
5061   } else {
5062     url = NULL;
5063     protocols = src->cur_protocols;
5064   }
5065
5066   if (protocols == 0)
5067     goto no_protocols;
5068
5069   /* reset some state */
5070   src->free_channel = 0;
5071   src->interleaved = FALSE;
5072   src->need_activate = FALSE;
5073   /* keep track of next port number, 0 is random */
5074   src->next_port_num = src->client_port_range.min;
5075   rtpport = rtcpport = 0;
5076
5077   if (G_UNLIKELY (src->streams == NULL))
5078     goto no_streams;
5079
5080   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5081     GstRTSPConnection *conn;
5082     gchar *transports;
5083     gint retry = 0;
5084     guint mask = 0;
5085
5086     stream = (GstRTSPStream *) walk->data;
5087
5088     /* see if we need to configure this stream */
5089     if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5090       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5091           stream);
5092       stream->disabled = TRUE;
5093       continue;
5094     }
5095
5096     /* merge/overwrite global caps */
5097     if (stream->caps) {
5098       guint j, num;
5099       GstStructure *s;
5100
5101       s = gst_caps_get_structure (stream->caps, 0);
5102
5103       num = gst_structure_n_fields (src->props);
5104       for (j = 0; j < num; j++) {
5105         const gchar *name;
5106         const GValue *val;
5107
5108         name = gst_structure_nth_field_name (src->props, j);
5109         val = gst_structure_get_value (src->props, name);
5110         gst_structure_set_value (s, name, val);
5111
5112         GST_DEBUG_OBJECT (src, "copied %s", name);
5113       }
5114     }
5115
5116     /* skip setup if we have no URL for it */
5117     if (stream->conninfo.location == NULL) {
5118       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5119       continue;
5120     }
5121
5122     if (src->conninfo.connection == NULL) {
5123       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5124         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5125         continue;
5126       }
5127       conn = stream->conninfo.connection;
5128     } else {
5129       conn = src->conninfo.connection;
5130     }
5131     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5132         stream->conninfo.location);
5133
5134     /* if we have a multicast connection, only suggest multicast from now on */
5135     if (stream->is_multicast)
5136       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5137
5138   next_protocol:
5139     /* first selectable protocol */
5140     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5141       mask++;
5142     if (!protocol_masks[mask])
5143       goto no_protocols;
5144
5145   retry:
5146     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5147         protocol_masks[mask]);
5148     /* create a string with first transport in line */
5149     transports = NULL;
5150     res = gst_rtspsrc_create_transports_string (src,
5151         protocols & protocol_masks[mask], &transports);
5152     if (res < 0 || transports == NULL)
5153       goto setup_transport_failed;
5154
5155     if (strlen (transports) == 0) {
5156       g_free (transports);
5157       GST_DEBUG_OBJECT (src, "no transports found");
5158       mask++;
5159       goto next_protocol;
5160     }
5161
5162     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5163
5164     /* replace placeholders with real values, this function will optionally
5165      * allocate UDP ports and other info needed to execute the setup request */
5166     res = gst_rtspsrc_prepare_transports (stream, &transports,
5167         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5168     if (res < 0) {
5169       g_free (transports);
5170       goto setup_transport_failed;
5171     }
5172
5173     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5174
5175     /* create SETUP request */
5176     res =
5177         gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5178         stream->conninfo.location);
5179     if (res < 0) {
5180       g_free (transports);
5181       goto create_request_failed;
5182     }
5183
5184     /* select transport, copy is made when adding to header so we can free it. */
5185     gst_rtsp_message_add_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5186     g_free (transports);
5187
5188     /* if the user wants a non default RTP packet size we add the blocksize
5189      * parameter */
5190     if (src->rtp_blocksize > 0) {
5191       hval = g_strdup_printf ("%d", src->rtp_blocksize);
5192       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5193       g_free (hval);
5194     }
5195
5196     if (async)
5197       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5198               stream->id));
5199
5200     /* handle the code ourselves */
5201     if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5202       goto send_error;
5203
5204     switch (code) {
5205       case GST_RTSP_STS_OK:
5206         break;
5207       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5208         gst_rtsp_message_unset (&request);
5209         gst_rtsp_message_unset (&response);
5210         /* cleanup of leftover transport */
5211         gst_rtspsrc_stream_free_udp (stream);
5212         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5213          * we might be in this case */
5214         if (stream->container && rtpport && rtcpport && !retry) {
5215           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5216               rtpport, rtcpport);
5217           retry++;
5218           goto retry;
5219         }
5220         /* this transport did not go down well, but we may have others to try
5221          * that we did not send yet, try those and only give up then
5222          * but not without checking for lost cause/extension so we can
5223          * post a nicer/more useful error message later */
5224         if (!unsupported_real)
5225           unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5226         /* select next available protocol, give up on this stream if none */
5227         mask++;
5228         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5229           mask++;
5230         if (!protocol_masks[mask] || unsupported_real)
5231           continue;
5232         else
5233           goto retry;
5234       default:
5235         /* cleanup of leftover transport and move to the next stream */
5236         gst_rtspsrc_stream_free_udp (stream);
5237         goto response_error;
5238     }
5239
5240     /* parse response transport */
5241     {
5242       gchar *resptrans = NULL;
5243       GstRTSPTransport transport = { 0 };
5244
5245       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5246           &resptrans, 0);
5247       if (!resptrans) {
5248         gst_rtspsrc_stream_free_udp (stream);
5249         goto no_transport;
5250       }
5251
5252       /* parse transport, go to next stream on parse error */
5253       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5254         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5255         goto next;
5256       }
5257
5258       /* update allowed transports for other streams. once the transport of
5259        * one stream has been determined, we make sure that all other streams
5260        * are configured in the same way */
5261       switch (transport.lower_transport) {
5262         case GST_RTSP_LOWER_TRANS_TCP:
5263           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5264           protocols = GST_RTSP_LOWER_TRANS_TCP;
5265           src->interleaved = TRUE;
5266           /* update free channels */
5267           src->free_channel =
5268               MAX (transport.interleaved.min, src->free_channel);
5269           src->free_channel =
5270               MAX (transport.interleaved.max, src->free_channel);
5271           src->free_channel++;
5272           break;
5273         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5274           /* only allow multicast for other streams */
5275           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5276           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5277           break;
5278         case GST_RTSP_LOWER_TRANS_UDP:
5279           /* only allow unicast for other streams */
5280           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5281           protocols = GST_RTSP_LOWER_TRANS_UDP;
5282           break;
5283         default:
5284           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5285               transport.lower_transport);
5286           break;
5287       }
5288
5289       if (!stream->container || (!src->interleaved && !retry)) {
5290         /* now configure the stream with the selected transport */
5291         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5292           GST_DEBUG_OBJECT (src,
5293               "could not configure stream %p transport, skipping stream",
5294               stream);
5295           goto next;
5296         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5297           /* retain the first allocated UDP port pair */
5298           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5299           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5300         }
5301       }
5302       /* we need to activate at least one streams when we detect activity */
5303       src->need_activate = TRUE;
5304     next:
5305       /* clean up our transport struct */
5306       gst_rtsp_transport_init (&transport);
5307       /* clean up used RTSP messages */
5308       gst_rtsp_message_unset (&request);
5309       gst_rtsp_message_unset (&response);
5310     }
5311   }
5312
5313   /* store the transport protocol that was configured */
5314   src->cur_protocols = protocols;
5315
5316   gst_rtsp_ext_list_stream_select (src->extensions, url);
5317
5318   /* if there is nothing to activate, error out */
5319   if (!src->need_activate)
5320     goto nothing_to_activate;
5321
5322   return res;
5323
5324   /* ERRORS */
5325 no_protocols:
5326   {
5327     /* no transport possible, post an error and stop */
5328     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5329         ("Could not connect to server, no protocols left"));
5330     return GST_RTSP_ERROR;
5331   }
5332 no_streams:
5333   {
5334     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5335         ("SDP contains no streams"));
5336     return GST_RTSP_ERROR;
5337   }
5338 create_request_failed:
5339   {
5340     gchar *str = gst_rtsp_strresult (res);
5341
5342     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5343         ("Could not create request. (%s)", str));
5344     g_free (str);
5345     goto cleanup_error;
5346   }
5347 setup_transport_failed:
5348   {
5349     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5350         ("Could not setup transport."));
5351     res = GST_RTSP_ERROR;
5352     goto cleanup_error;
5353   }
5354 response_error:
5355   {
5356     const gchar *str = gst_rtsp_status_as_text (code);
5357
5358     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5359         ("Error (%d): %s", code, GST_STR_NULL (str)));
5360     res = GST_RTSP_ERROR;
5361     goto cleanup_error;
5362   }
5363 send_error:
5364   {
5365     gchar *str = gst_rtsp_strresult (res);
5366
5367     if (res != GST_RTSP_EINTR) {
5368       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5369           ("Could not send message. (%s)", str));
5370     } else {
5371       GST_WARNING_OBJECT (src, "send interrupted");
5372     }
5373     g_free (str);
5374     goto cleanup_error;
5375   }
5376 no_transport:
5377   {
5378     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5379         ("Server did not select transport."));
5380     res = GST_RTSP_ERROR;
5381     goto cleanup_error;
5382   }
5383 nothing_to_activate:
5384   {
5385     /* none of the available error codes is really right .. */
5386     if (unsupported_real) {
5387       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5388           (_("No supported stream was found. You might need to install a "
5389                   "GStreamer RTSP extension plugin for Real media streams.")),
5390           (NULL));
5391     } else {
5392       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5393           (_("No supported stream was found. You might need to allow "
5394                   "more transport protocols or may otherwise be missing "
5395                   "the right GStreamer RTSP extension plugin.")), (NULL));
5396     }
5397     return GST_RTSP_ERROR;
5398   }
5399 cleanup_error:
5400   {
5401     gst_rtsp_message_unset (&request);
5402     gst_rtsp_message_unset (&response);
5403     return res;
5404   }
5405 }
5406
5407 static gboolean
5408 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5409     GstSegment * segment)
5410 {
5411   gint64 seconds;
5412   GstRTSPTimeRange *therange;
5413
5414   if (src->range)
5415     gst_rtsp_range_free (src->range);
5416
5417   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5418     GST_DEBUG_OBJECT (src, "parsed range %s", range);
5419     src->range = therange;
5420   } else {
5421     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5422     src->range = NULL;
5423     gst_segment_init (segment, GST_FORMAT_TIME);
5424     return FALSE;
5425   }
5426
5427   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
5428       therange->min.type, therange->min.seconds, therange->max.type,
5429       therange->max.seconds);
5430
5431   if (therange->min.type == GST_RTSP_TIME_NOW)
5432     seconds = 0;
5433   else if (therange->min.type == GST_RTSP_TIME_END)
5434     seconds = 0;
5435   else
5436     seconds = therange->min.seconds * GST_SECOND;
5437
5438   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5439       GST_TIME_ARGS (seconds));
5440
5441   /* we need to start playback without clipping from the position reported by
5442    * the server */
5443   segment->start = seconds;
5444   segment->position = seconds;
5445
5446   if (therange->max.type == GST_RTSP_TIME_NOW)
5447     seconds = -1;
5448   else if (therange->max.type == GST_RTSP_TIME_END)
5449     seconds = -1;
5450   else
5451     seconds = therange->max.seconds * GST_SECOND;
5452
5453   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5454       GST_TIME_ARGS (seconds));
5455
5456   /* live (WMS) server might send overflowed large max as its idea of infinity,
5457    * compensate to prevent problems later on */
5458   if (seconds != -1 && seconds < 0) {
5459     seconds = -1;
5460     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5461   }
5462
5463   /* live (WMS) might send min == max, which is not worth recording */
5464   if (segment->duration == -1 && seconds == segment->start)
5465     seconds = -1;
5466
5467   /* don't change duration with unknown value, we might have a valid value
5468    * there that we want to keep. */
5469   if (seconds != -1)
5470     segment->duration = seconds;
5471
5472   return TRUE;
5473 }
5474
5475 /* must be called with the RTSP state lock */
5476 static GstRTSPResult
5477 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5478     gboolean async)
5479 {
5480   GstRTSPResult res;
5481   gint i, n_streams;
5482
5483   /* prepare global stream caps properties */
5484   if (src->props)
5485     gst_structure_remove_all_fields (src->props);
5486   else
5487     src->props = gst_structure_new_empty ("RTSPProperties");
5488
5489   if (src->debug)
5490     gst_sdp_message_dump (sdp);
5491
5492   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5493
5494   gst_segment_init (&src->segment, GST_FORMAT_TIME);
5495
5496   /* parse range for duration reporting. */
5497   {
5498     const gchar *range;
5499
5500     for (i = 0;; i++) {
5501       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5502       if (range == NULL)
5503         break;
5504
5505       /* keep track of the range and configure it in the segment */
5506       if (gst_rtspsrc_parse_range (src, range, &src->segment))
5507         break;
5508     }
5509   }
5510   /* try to find a global control attribute. Note that a '*' means that we should
5511    * do aggregate control with the current url (so we don't do anything and
5512    * leave the current connection as is) */
5513   {
5514     const gchar *control;
5515
5516     for (i = 0;; i++) {
5517       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
5518       if (control == NULL)
5519         break;
5520
5521       /* only take fully qualified urls */
5522       if (g_str_has_prefix (control, "rtsp://"))
5523         break;
5524     }
5525     if (control) {
5526       g_free (src->conninfo.location);
5527       src->conninfo.location = g_strdup (control);
5528       /* make a connection for this, if there was a connection already, nothing
5529        * happens. */
5530       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
5531         GST_ERROR_OBJECT (src, "could not connect");
5532       }
5533     }
5534     /* we need to keep the control url separate from the connection url because
5535      * the rules for constructing the media control url need it */
5536     g_free (src->control);
5537     src->control = g_strdup (control);
5538   }
5539
5540   /* create streams */
5541   n_streams = gst_sdp_message_medias_len (sdp);
5542   for (i = 0; i < n_streams; i++) {
5543     gst_rtspsrc_create_stream (src, sdp, i);
5544   }
5545
5546   src->state = GST_RTSP_STATE_INIT;
5547
5548   /* setup streams */
5549   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
5550     goto setup_failed;
5551
5552   /* reset our state */
5553   src->need_range = TRUE;
5554   src->skip = FALSE;
5555
5556   src->state = GST_RTSP_STATE_READY;
5557
5558   return res;
5559
5560   /* ERRORS */
5561 setup_failed:
5562   {
5563     GST_ERROR_OBJECT (src, "setup failed");
5564     gst_rtspsrc_cleanup (src);
5565     return res;
5566   }
5567 }
5568
5569 static GstRTSPResult
5570 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
5571     gboolean async)
5572 {
5573   GstRTSPResult res;
5574   GstRTSPMessage request = { 0 };
5575   GstRTSPMessage response = { 0 };
5576   guint8 *data;
5577   guint size;
5578   gchar *respcont = NULL;
5579
5580 restart:
5581   src->need_redirect = FALSE;
5582
5583   /* can't continue without a valid url */
5584   if (G_UNLIKELY (src->conninfo.url == NULL)) {
5585     res = GST_RTSP_EINVAL;
5586     goto no_url;
5587   }
5588   src->tried_url_auth = FALSE;
5589
5590   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
5591     goto connect_failed;
5592
5593   /* create OPTIONS */
5594   GST_DEBUG_OBJECT (src, "create options...");
5595   res =
5596       gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
5597       src->conninfo.url_str);
5598   if (res < 0)
5599     goto create_request_failed;
5600
5601   /* send OPTIONS */
5602   GST_DEBUG_OBJECT (src, "send options...");
5603
5604   if (async)
5605     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
5606
5607   if ((res =
5608           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5609               NULL)) < 0)
5610     goto send_error;
5611
5612   /* parse OPTIONS */
5613   if (!gst_rtspsrc_parse_methods (src, &response))
5614     goto methods_error;
5615
5616   /* create DESCRIBE */
5617   GST_DEBUG_OBJECT (src, "create describe...");
5618   res =
5619       gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
5620       src->conninfo.url_str);
5621   if (res < 0)
5622     goto create_request_failed;
5623
5624   /* we only accept SDP for now */
5625   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
5626       "application/sdp");
5627
5628   /* send DESCRIBE */
5629   GST_DEBUG_OBJECT (src, "send describe...");
5630
5631   if (async)
5632     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
5633
5634   if ((res =
5635           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5636               NULL)) < 0)
5637     goto send_error;
5638
5639   /* we only perform redirect for the describe, currently */
5640   if (src->need_redirect) {
5641     /* close connection, we don't have to send a TEARDOWN yet, ignore the
5642      * result. */
5643     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5644
5645     gst_rtsp_message_unset (&request);
5646     gst_rtsp_message_unset (&response);
5647
5648     /* and now retry */
5649     goto restart;
5650   }
5651
5652   /* it could be that the DESCRIBE method was not implemented */
5653   if (!src->methods & GST_RTSP_DESCRIBE)
5654     goto no_describe;
5655
5656   /* check if reply is SDP */
5657   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
5658       0);
5659   /* could not be set but since the request returned OK, we assume it
5660    * was SDP, else check it. */
5661   if (respcont) {
5662     if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
5663       goto wrong_content_type;
5664   }
5665
5666   /* get message body and parse as SDP */
5667   gst_rtsp_message_get_body (&response, &data, &size);
5668   if (data == NULL || size == 0)
5669     goto no_describe;
5670
5671   GST_DEBUG_OBJECT (src, "parse SDP...");
5672   gst_sdp_message_new (sdp);
5673   gst_sdp_message_parse_buffer (data, size, *sdp);
5674
5675   /* clean up any messages */
5676   gst_rtsp_message_unset (&request);
5677   gst_rtsp_message_unset (&response);
5678
5679   return res;
5680
5681   /* ERRORS */
5682 no_url:
5683   {
5684     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
5685         ("No valid RTSP URL was provided"));
5686     goto cleanup_error;
5687   }
5688 connect_failed:
5689   {
5690     gchar *str = gst_rtsp_strresult (res);
5691
5692     if (res != GST_RTSP_EINTR) {
5693       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5694           ("Failed to connect. (%s)", str));
5695     } else {
5696       GST_WARNING_OBJECT (src, "connect interrupted");
5697     }
5698     g_free (str);
5699     goto cleanup_error;
5700   }
5701 create_request_failed:
5702   {
5703     gchar *str = gst_rtsp_strresult (res);
5704
5705     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5706         ("Could not create request. (%s)", str));
5707     g_free (str);
5708     goto cleanup_error;
5709   }
5710 send_error:
5711   {
5712     /* Don't post a message - the rtsp_send method will have
5713      * taken care of it because we passed NULL for the response code */
5714     goto cleanup_error;
5715   }
5716 methods_error:
5717   {
5718     /* error was posted */
5719     res = GST_RTSP_ERROR;
5720     goto cleanup_error;
5721   }
5722 wrong_content_type:
5723   {
5724     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5725         ("Server does not support SDP, got %s.", respcont));
5726     res = GST_RTSP_ERROR;
5727     goto cleanup_error;
5728   }
5729 no_describe:
5730   {
5731     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5732         ("Server can not provide an SDP."));
5733     res = GST_RTSP_ERROR;
5734     goto cleanup_error;
5735   }
5736 cleanup_error:
5737   {
5738     if (src->conninfo.connection) {
5739       GST_DEBUG_OBJECT (src, "free connection");
5740       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5741     }
5742     gst_rtsp_message_unset (&request);
5743     gst_rtsp_message_unset (&response);
5744     return res;
5745   }
5746 }
5747
5748 static GstRTSPResult
5749 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
5750 {
5751   GstRTSPResult ret;
5752
5753   src->methods =
5754       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
5755
5756   if (src->sdp == NULL) {
5757     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
5758       goto no_sdp;
5759   }
5760
5761   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
5762     goto open_failed;
5763
5764 done:
5765   if (async)
5766     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
5767
5768   return ret;
5769
5770   /* ERRORS */
5771 no_sdp:
5772   {
5773     GST_WARNING_OBJECT (src, "can't get sdp");
5774     src->open_error = TRUE;
5775     goto done;
5776   }
5777 open_failed:
5778   {
5779     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
5780     src->open_error = TRUE;
5781     goto done;
5782   }
5783 }
5784
5785 static GstRTSPResult
5786 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
5787 {
5788   GstRTSPMessage request = { 0 };
5789   GstRTSPMessage response = { 0 };
5790   GstRTSPResult res = GST_RTSP_OK;
5791   GList *walk;
5792   gchar *control;
5793
5794   GST_DEBUG_OBJECT (src, "TEARDOWN...");
5795
5796   if (src->state < GST_RTSP_STATE_READY) {
5797     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
5798     goto close;
5799   }
5800
5801   if (only_close)
5802     goto close;
5803
5804   /* construct a control url */
5805   if (src->control)
5806     control = src->control;
5807   else
5808     control = src->conninfo.url_str;
5809
5810   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
5811     goto not_supported;
5812
5813   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5814     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5815     gchar *setup_url;
5816     GstRTSPConnInfo *info;
5817
5818     /* try aggregate control first but do non-aggregate control otherwise */
5819     if (control)
5820       setup_url = control;
5821     else if ((setup_url = stream->conninfo.location) == NULL)
5822       continue;
5823
5824     if (src->conninfo.connection) {
5825       info = &src->conninfo;
5826     } else if (stream->conninfo.connection) {
5827       info = &stream->conninfo;
5828     } else {
5829       continue;
5830     }
5831     if (!info->connected)
5832       goto next;
5833
5834     /* do TEARDOWN */
5835     res =
5836         gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
5837     if (res < 0)
5838       goto create_request_failed;
5839
5840     if (async)
5841       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
5842
5843     if ((res =
5844             gst_rtspsrc_send (src, info->connection, &request, &response,
5845                 NULL)) < 0)
5846       goto send_error;
5847
5848     /* FIXME, parse result? */
5849     gst_rtsp_message_unset (&request);
5850     gst_rtsp_message_unset (&response);
5851
5852   next:
5853     /* early exit when we did aggregate control */
5854     if (control)
5855       break;
5856   }
5857
5858 close:
5859   /* close connections */
5860   GST_DEBUG_OBJECT (src, "closing connection...");
5861   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5862   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5863     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5864     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
5865   }
5866
5867   /* cleanup */
5868   gst_rtspsrc_cleanup (src);
5869
5870   src->state = GST_RTSP_STATE_INVALID;
5871
5872   if (async)
5873     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
5874
5875   return res;
5876
5877   /* ERRORS */
5878 create_request_failed:
5879   {
5880     gchar *str = gst_rtsp_strresult (res);
5881
5882     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5883         ("Could not create request. (%s)", str));
5884     g_free (str);
5885     goto close;
5886   }
5887 send_error:
5888   {
5889     gchar *str = gst_rtsp_strresult (res);
5890
5891     gst_rtsp_message_unset (&request);
5892     if (res != GST_RTSP_EINTR) {
5893       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5894           ("Could not send message. (%s)", str));
5895     } else {
5896       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
5897     }
5898     g_free (str);
5899     goto close;
5900   }
5901 not_supported:
5902   {
5903     GST_DEBUG_OBJECT (src,
5904         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
5905     goto close;
5906   }
5907 }
5908
5909 /* RTP-Info is of the format:
5910  *
5911  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
5912  *
5913  * rtptime corresponds to the timestamp for the NPT time given in the header
5914  * seqbase corresponds to the next sequence number we received. This number
5915  * indicates the first seqnum after the seek and should be used to discard
5916  * packets that are from before the seek.
5917  */
5918 static gboolean
5919 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
5920 {
5921   gchar **infos;
5922   gint i, j;
5923
5924   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
5925
5926   infos = g_strsplit (rtpinfo, ",", 0);
5927   for (i = 0; infos[i]; i++) {
5928     gchar **fields;
5929     GstRTSPStream *stream;
5930     gint32 seqbase;
5931     gint64 timebase;
5932
5933     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
5934
5935     /* init values, types of seqbase and timebase are bigger than needed so we
5936      * can store -1 as uninitialized values */
5937     stream = NULL;
5938     seqbase = -1;
5939     timebase = -1;
5940
5941     /* parse url, find stream for url.
5942      * parse seq and rtptime. The seq number should be configured in the rtp
5943      * depayloader or session manager to detect gaps. Same for the rtptime, it
5944      * should be used to create an initial time newsegment. */
5945     fields = g_strsplit (infos[i], ";", 0);
5946     for (j = 0; fields[j]; j++) {
5947       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
5948       /* remove leading whitespace */
5949       fields[j] = g_strchug (fields[j]);
5950       if (g_str_has_prefix (fields[j], "url=")) {
5951         /* get the url and the stream */
5952         stream =
5953             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
5954       } else if (g_str_has_prefix (fields[j], "seq=")) {
5955         seqbase = atoi (fields[j] + 4);
5956       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
5957         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
5958       }
5959     }
5960     g_strfreev (fields);
5961     /* now we need to store the values for the caps of the stream */
5962     if (stream != NULL) {
5963       GST_DEBUG_OBJECT (src,
5964           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
5965           stream, seqbase, timebase);
5966
5967       /* we have a stream, configure detected params */
5968       stream->seqbase = seqbase;
5969       stream->timebase = timebase;
5970     }
5971   }
5972   g_strfreev (infos);
5973
5974   return TRUE;
5975 }
5976
5977 static void
5978 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
5979 {
5980   guint64 interval;
5981   GList *walk;
5982
5983   interval = strtoul (rtcp, NULL, 10);
5984   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
5985
5986   if (!interval)
5987     return;
5988
5989   interval *= GST_MSECOND;
5990
5991   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5992     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5993
5994     /* already (optionally) retrieved this when configuring manager */
5995     if (stream->session) {
5996       GObject *rtpsession = stream->session;
5997
5998       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
5999           rtpsession);
6000       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
6001     }
6002   }
6003
6004   /* now it happens that (Xenon) server sending this may also provide bogus
6005    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
6006    * and just use RTP-Info to sync */
6007   if (src->manager) {
6008     GObjectClass *klass;
6009
6010     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6011     if (g_object_class_find_property (klass, "rtcp-sync")) {
6012       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6013       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6014     }
6015   }
6016 }
6017
6018 static gdouble
6019 gst_rtspsrc_get_float (const gchar * dstr)
6020 {
6021   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6022
6023   /* canonicalise floating point string so we can handle float strings
6024    * in the form "24.930" or "24,930" irrespective of the current locale */
6025   g_strlcpy (s, dstr, sizeof (s));
6026   g_strdelimit (s, ",", '.');
6027   return g_ascii_strtod (s, NULL);
6028 }
6029
6030 static gchar *
6031 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6032 {
6033   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6034
6035   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6036     g_strlcpy (val_str, "now", sizeof (val_str));
6037   } else {
6038     if (segment->position == 0) {
6039       g_strlcpy (val_str, "0", sizeof (val_str));
6040     } else {
6041       g_ascii_dtostr (val_str, sizeof (val_str),
6042           ((gdouble) segment->position) / GST_SECOND);
6043     }
6044   }
6045   return g_strdup_printf ("npt=%s-", val_str);
6046 }
6047
6048 static void
6049 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6050 {
6051   stream->timebase = -1;
6052   stream->seqbase = -1;
6053   if (stream->caps) {
6054     GstStructure *s;
6055
6056     stream->caps = gst_caps_make_writable (stream->caps);
6057     s = gst_caps_get_structure (stream->caps, 0);
6058     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6059   }
6060 }
6061
6062 static GstRTSPResult
6063 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6064 {
6065   GstRTSPResult res = GST_RTSP_OK;
6066
6067   if (src->state < GST_RTSP_STATE_READY) {
6068     res = GST_RTSP_ERROR;
6069     if (src->open_error) {
6070       GST_DEBUG_OBJECT (src, "the stream was in error");
6071       goto done;
6072     }
6073     if (async)
6074       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6075
6076     if ((res = gst_rtspsrc_open (src, async)) < 0) {
6077       GST_DEBUG_OBJECT (src, "failed to open stream");
6078       goto done;
6079     }
6080   }
6081
6082 done:
6083   return res;
6084 }
6085
6086 static GstRTSPResult
6087 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6088 {
6089   GstRTSPMessage request = { 0 };
6090   GstRTSPMessage response = { 0 };
6091   GstRTSPResult res = GST_RTSP_OK;
6092   GList *walk;
6093   gchar *hval;
6094   gint hval_idx;
6095   gchar *control;
6096
6097   GST_DEBUG_OBJECT (src, "PLAY...");
6098
6099   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6100     goto open_failed;
6101
6102   if (!(src->methods & GST_RTSP_PLAY))
6103     goto not_supported;
6104
6105   if (src->state == GST_RTSP_STATE_PLAYING)
6106     goto was_playing;
6107
6108   if (!src->conninfo.connection || !src->conninfo.connected)
6109     goto done;
6110
6111   /* send some dummy packets before we activate the receive in the
6112    * udp sources */
6113   gst_rtspsrc_send_dummy_packets (src);
6114
6115   /* activate receive elements;
6116    * only in async case, since receive elements may not have been affected
6117    * by overall state change (e.g. not around yet),
6118    * do not mess with state in sync case (e.g. seeking) */
6119   if (async)
6120     gst_element_set_state (GST_ELEMENT_CAST (src), GST_STATE_PLAYING);
6121
6122   /* construct a control url */
6123   if (src->control)
6124     control = src->control;
6125   else
6126     control = src->conninfo.url_str;
6127
6128   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6129     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6130     gchar *setup_url;
6131     GstRTSPConnection *conn;
6132
6133     /* try aggregate control first but do non-aggregate control otherwise */
6134     if (control)
6135       setup_url = control;
6136     else if ((setup_url = stream->conninfo.location) == NULL)
6137       continue;
6138
6139     if (src->conninfo.connection) {
6140       conn = src->conninfo.connection;
6141     } else if (stream->conninfo.connection) {
6142       conn = stream->conninfo.connection;
6143     } else {
6144       continue;
6145     }
6146
6147     /* do play */
6148     res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6149     if (res < 0)
6150       goto create_request_failed;
6151
6152     if (src->need_range) {
6153       hval = gen_range_header (src, segment);
6154
6155       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_RANGE, hval);
6156       g_free (hval);
6157     }
6158
6159     if (segment->rate != 1.0) {
6160       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6161
6162       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6163       if (src->skip)
6164         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6165       else
6166         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6167     }
6168
6169     if (async)
6170       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6171
6172     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6173       goto send_error;
6174
6175     /* seek may have silently failed as it is not supported */
6176     if (!(src->methods & GST_RTSP_PLAY)) {
6177       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6178       /* obviously it is supported as we made it here */
6179       src->methods |= GST_RTSP_PLAY;
6180       src->seekable = FALSE;
6181       /* but there is nothing to parse in the response,
6182        * so convey we have no idea and not to expect anything particular */
6183       clear_rtp_base (src, stream);
6184       if (control) {
6185         GList *run;
6186
6187         /* need to do for all streams */
6188         for (run = src->streams; run; run = g_list_next (run))
6189           clear_rtp_base (src, (GstRTSPStream *) run->data);
6190       }
6191       /* NOTE the above also disables npt based eos detection */
6192       /* and below forces position to 0,
6193        * which is visible feedback we lost the plot */
6194       segment->start = segment->position = src->last_pos;
6195     }
6196
6197     gst_rtsp_message_unset (&request);
6198
6199     /* parse RTP npt field. This is the current position in the stream (Normal
6200      * Play Time) and should be put in the NEWSEGMENT position field. */
6201     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6202             0) == GST_RTSP_OK)
6203       gst_rtspsrc_parse_range (src, hval, segment);
6204
6205     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6206     segment->rate = 1.0;
6207
6208     /* parse Speed header. This is the intended playback rate of the stream
6209      * and should be put in the NEWSEGMENT rate field. */
6210     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6211             0) == GST_RTSP_OK) {
6212       segment->rate = gst_rtspsrc_get_float (hval);
6213     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6214             &hval, 0) == GST_RTSP_OK) {
6215       segment->rate = gst_rtspsrc_get_float (hval);
6216     }
6217
6218     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6219      * for the RTP packets. If this is not present, we assume all starts from 0...
6220      * This is info for the RTP session manager that we pass to it in caps. */
6221     hval_idx = 0;
6222     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6223             &hval, hval_idx++) == GST_RTSP_OK)
6224       gst_rtspsrc_parse_rtpinfo (src, hval);
6225
6226     /* some servers indicate RTCP parameters in PLAY response,
6227      * rather than properly in SDP */
6228     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6229             &hval, 0) == GST_RTSP_OK)
6230       gst_rtspsrc_handle_rtcp_interval (src, hval);
6231
6232     gst_rtsp_message_unset (&response);
6233
6234     /* early exit when we did aggregate control */
6235     if (control)
6236       break;
6237   }
6238   /* configure the caps of the streams after we parsed all headers. Only reset
6239    * the manager object when we set a new Range header (we did a seek) */
6240   gst_rtspsrc_configure_caps (src, segment, src->need_range);
6241
6242   /* set again when needed */
6243   src->need_range = FALSE;
6244
6245   src->running = TRUE;
6246   src->base_time = -1;
6247   src->state = GST_RTSP_STATE_PLAYING;
6248
6249   /* mark discont */
6250   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6251   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6252     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6253     stream->discont = TRUE;
6254   }
6255
6256 done:
6257   if (async)
6258     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6259
6260   return res;
6261
6262   /* ERRORS */
6263 open_failed:
6264   {
6265     GST_DEBUG_OBJECT (src, "failed to open stream");
6266     goto done;
6267   }
6268 not_supported:
6269   {
6270     GST_DEBUG_OBJECT (src, "PLAY is not supported");
6271     goto done;
6272   }
6273 was_playing:
6274   {
6275     GST_DEBUG_OBJECT (src, "we were already PLAYING");
6276     goto done;
6277   }
6278 create_request_failed:
6279   {
6280     gchar *str = gst_rtsp_strresult (res);
6281
6282     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6283         ("Could not create request. (%s)", str));
6284     g_free (str);
6285     goto done;
6286   }
6287 send_error:
6288   {
6289     gchar *str = gst_rtsp_strresult (res);
6290
6291     gst_rtsp_message_unset (&request);
6292     if (res != GST_RTSP_EINTR) {
6293       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6294           ("Could not send message. (%s)", str));
6295     } else {
6296       GST_WARNING_OBJECT (src, "PLAY interrupted");
6297     }
6298     g_free (str);
6299     goto done;
6300   }
6301 }
6302
6303 static GstRTSPResult
6304 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
6305 {
6306   GstRTSPResult res = GST_RTSP_OK;
6307   GstRTSPMessage request = { 0 };
6308   GstRTSPMessage response = { 0 };
6309   GList *walk;
6310   gchar *control;
6311
6312   GST_DEBUG_OBJECT (src, "PAUSE...");
6313
6314   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6315     goto open_failed;
6316
6317   if (!(src->methods & GST_RTSP_PAUSE))
6318     goto not_supported;
6319
6320   if (src->state == GST_RTSP_STATE_READY)
6321     goto was_paused;
6322
6323   if (!src->conninfo.connection || !src->conninfo.connected)
6324     goto no_connection;
6325
6326   /* construct a control url */
6327   if (src->control)
6328     control = src->control;
6329   else
6330     control = src->conninfo.url_str;
6331
6332   /* loop over the streams. We might exit the loop early when we could do an
6333    * aggregate control */
6334   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6335     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6336     GstRTSPConnection *conn;
6337     gchar *setup_url;
6338
6339     /* try aggregate control first but do non-aggregate control otherwise */
6340     if (control)
6341       setup_url = control;
6342     else if ((setup_url = stream->conninfo.location) == NULL)
6343       continue;
6344
6345     if (src->conninfo.connection) {
6346       conn = src->conninfo.connection;
6347     } else if (stream->conninfo.connection) {
6348       conn = stream->conninfo.connection;
6349     } else {
6350       continue;
6351     }
6352
6353     if (async)
6354       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6355           ("Sending PAUSE request"));
6356
6357     if ((res =
6358             gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6359                 setup_url)) < 0)
6360       goto create_request_failed;
6361
6362     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6363       goto send_error;
6364
6365     gst_rtsp_message_unset (&request);
6366     gst_rtsp_message_unset (&response);
6367
6368     /* exit early when we did agregate control */
6369     if (control)
6370       break;
6371   }
6372
6373 no_connection:
6374   src->state = GST_RTSP_STATE_READY;
6375
6376 done:
6377   if (async)
6378     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6379
6380   return res;
6381
6382   /* ERRORS */
6383 open_failed:
6384   {
6385     GST_DEBUG_OBJECT (src, "failed to open stream");
6386     goto done;
6387   }
6388 not_supported:
6389   {
6390     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6391     goto done;
6392   }
6393 was_paused:
6394   {
6395     GST_DEBUG_OBJECT (src, "we were already PAUSED");
6396     goto done;
6397   }
6398 create_request_failed:
6399   {
6400     gchar *str = gst_rtsp_strresult (res);
6401
6402     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6403         ("Could not create request. (%s)", str));
6404     g_free (str);
6405     goto done;
6406   }
6407 send_error:
6408   {
6409     gchar *str = gst_rtsp_strresult (res);
6410
6411     gst_rtsp_message_unset (&request);
6412     if (res != GST_RTSP_EINTR) {
6413       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6414           ("Could not send message. (%s)", str));
6415     } else {
6416       GST_WARNING_OBJECT (src, "PAUSE interrupted");
6417     }
6418     g_free (str);
6419     goto done;
6420   }
6421 }
6422
6423 static void
6424 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6425 {
6426   GstRTSPSrc *rtspsrc;
6427
6428   rtspsrc = GST_RTSPSRC (bin);
6429
6430   switch (GST_MESSAGE_TYPE (message)) {
6431     case GST_MESSAGE_EOS:
6432       gst_message_unref (message);
6433       break;
6434     case GST_MESSAGE_ELEMENT:
6435     {
6436       const GstStructure *s = gst_message_get_structure (message);
6437
6438       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6439         gboolean ignore_timeout;
6440
6441         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6442
6443         GST_OBJECT_LOCK (rtspsrc);
6444         ignore_timeout = rtspsrc->ignore_timeout;
6445         rtspsrc->ignore_timeout = TRUE;
6446         GST_OBJECT_UNLOCK (rtspsrc);
6447
6448         /* we only act on the first udp timeout message, others are irrelevant
6449          * and can be ignored. */
6450         if (!ignore_timeout)
6451           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
6452         /* eat and free */
6453         gst_message_unref (message);
6454         return;
6455       }
6456       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6457       break;
6458     }
6459     case GST_MESSAGE_ERROR:
6460     {
6461       GstObject *udpsrc;
6462       GstRTSPStream *stream;
6463       GstFlowReturn ret;
6464
6465       udpsrc = GST_MESSAGE_SRC (message);
6466
6467       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6468           GST_ELEMENT_NAME (udpsrc));
6469
6470       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6471       if (!stream)
6472         goto forward;
6473
6474       /* we ignore the RTCP udpsrc */
6475       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6476         goto done;
6477
6478       /* if we get error messages from the udp sources, that's not a problem as
6479        * long as not all of them error out. We also don't really know what the
6480        * problem is, the message does not give enough detail... */
6481       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6482       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
6483       if (ret != GST_FLOW_OK)
6484         goto forward;
6485
6486     done:
6487       gst_message_unref (message);
6488       break;
6489
6490     forward:
6491       /* fatal but not our message, forward */
6492       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6493       break;
6494     }
6495     default:
6496     {
6497       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6498       break;
6499     }
6500   }
6501 }
6502
6503 /* the thread where everything happens */
6504 static void
6505 gst_rtspsrc_thread (GstRTSPSrc * src)
6506 {
6507   gint cmd;
6508
6509   GST_OBJECT_LOCK (src);
6510   cmd = src->pending_cmd;
6511   if (cmd == CMD_PLAY || cmd == CMD_LOOP)
6512     src->pending_cmd = CMD_LOOP;
6513   else
6514     src->pending_cmd = CMD_WAIT;
6515   GST_DEBUG_OBJECT (src, "got command %d", cmd);
6516
6517   /* we got the message command, so ensure communication is possible again */
6518   gst_rtspsrc_connection_flush (src, FALSE);
6519
6520   src->busy_cmd = cmd;
6521   GST_OBJECT_UNLOCK (src);
6522
6523   switch (cmd) {
6524     case CMD_OPEN:
6525       gst_rtspsrc_open (src, TRUE);
6526       break;
6527     case CMD_PLAY:
6528       gst_rtspsrc_play (src, &src->segment, TRUE);
6529       break;
6530     case CMD_PAUSE:
6531       gst_rtspsrc_pause (src, TRUE);
6532       break;
6533     case CMD_CLOSE:
6534       gst_rtspsrc_close (src, TRUE, FALSE);
6535       break;
6536     case CMD_LOOP:
6537       gst_rtspsrc_loop (src);
6538       break;
6539     case CMD_RECONNECT:
6540       gst_rtspsrc_reconnect (src, FALSE);
6541       break;
6542     default:
6543       break;
6544   }
6545
6546   GST_OBJECT_LOCK (src);
6547   /* and go back to sleep */
6548   if (src->pending_cmd == CMD_WAIT) {
6549     if (src->task)
6550       gst_task_pause (src->task);
6551   }
6552   /* reset waiting */
6553   src->busy_cmd = CMD_WAIT;
6554   GST_OBJECT_UNLOCK (src);
6555 }
6556
6557 static gboolean
6558 gst_rtspsrc_start (GstRTSPSrc * src)
6559 {
6560   GST_DEBUG_OBJECT (src, "starting");
6561
6562   GST_OBJECT_LOCK (src);
6563
6564   src->pending_cmd = CMD_WAIT;
6565
6566   if (src->task == NULL) {
6567     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
6568     if (src->task == NULL)
6569       goto task_error;
6570
6571     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
6572   }
6573   GST_OBJECT_UNLOCK (src);
6574
6575   return TRUE;
6576
6577   /* ERRORS */
6578 task_error:
6579   {
6580     GST_ERROR_OBJECT (src, "failed to create task");
6581     return FALSE;
6582   }
6583 }
6584
6585 static gboolean
6586 gst_rtspsrc_stop (GstRTSPSrc * src)
6587 {
6588   GstTask *task;
6589
6590   GST_DEBUG_OBJECT (src, "stopping");
6591
6592   /* also cancels pending task */
6593   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_CLOSE);
6594
6595   GST_OBJECT_LOCK (src);
6596   if ((task = src->task)) {
6597     src->task = NULL;
6598     GST_OBJECT_UNLOCK (src);
6599
6600     gst_task_stop (task);
6601
6602     /* make sure it is not running */
6603     GST_RTSP_STREAM_LOCK (src);
6604     GST_RTSP_STREAM_UNLOCK (src);
6605
6606     /* now wait for the task to finish */
6607     gst_task_join (task);
6608
6609     /* and free the task */
6610     gst_object_unref (GST_OBJECT (task));
6611
6612     GST_OBJECT_LOCK (src);
6613   }
6614   GST_OBJECT_UNLOCK (src);
6615
6616   /* ensure synchronously all is closed and clean */
6617   gst_rtspsrc_close (src, FALSE, TRUE);
6618
6619   return TRUE;
6620 }
6621
6622 static GstStateChangeReturn
6623 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
6624 {
6625   GstRTSPSrc *rtspsrc;
6626   GstStateChangeReturn ret;
6627
6628   rtspsrc = GST_RTSPSRC (element);
6629
6630   switch (transition) {
6631     case GST_STATE_CHANGE_NULL_TO_READY:
6632       if (!gst_rtspsrc_start (rtspsrc))
6633         goto start_failed;
6634       break;
6635     case GST_STATE_CHANGE_READY_TO_PAUSED:
6636       /* init some state */
6637       rtspsrc->cur_protocols = rtspsrc->protocols;
6638       /* first attempt, don't ignore timeouts */
6639       rtspsrc->ignore_timeout = FALSE;
6640       rtspsrc->open_error = FALSE;
6641       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
6642       break;
6643     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6644     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6645       /* unblock the tcp tasks and make the loop waiting */
6646       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP);
6647       break;
6648     case GST_STATE_CHANGE_PAUSED_TO_READY:
6649       break;
6650     default:
6651       break;
6652   }
6653
6654   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6655   if (ret == GST_STATE_CHANGE_FAILURE)
6656     goto done;
6657
6658   switch (transition) {
6659     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6660       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
6661       break;
6662     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6663       /* send pause request and keep the idle task around */
6664       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
6665       ret = GST_STATE_CHANGE_NO_PREROLL;
6666       break;
6667     case GST_STATE_CHANGE_READY_TO_PAUSED:
6668       ret = GST_STATE_CHANGE_NO_PREROLL;
6669       break;
6670     case GST_STATE_CHANGE_PAUSED_TO_READY:
6671       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
6672       break;
6673     case GST_STATE_CHANGE_READY_TO_NULL:
6674       gst_rtspsrc_stop (rtspsrc);
6675       break;
6676     default:
6677       break;
6678   }
6679
6680 done:
6681   return ret;
6682
6683 start_failed:
6684   {
6685     GST_DEBUG_OBJECT (rtspsrc, "start failed");
6686     return GST_STATE_CHANGE_FAILURE;
6687   }
6688 }
6689
6690 static gboolean
6691 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
6692 {
6693   gboolean res;
6694   GstRTSPSrc *rtspsrc;
6695
6696   rtspsrc = GST_RTSPSRC (element);
6697
6698   if (GST_EVENT_IS_DOWNSTREAM (event)) {
6699     res = gst_rtspsrc_push_event (rtspsrc, event);
6700   } else {
6701     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
6702   }
6703
6704   return res;
6705 }
6706
6707
6708 /*** GSTURIHANDLER INTERFACE *************************************************/
6709
6710 static GstURIType
6711 gst_rtspsrc_uri_get_type (GType type)
6712 {
6713   return GST_URI_SRC;
6714 }
6715
6716 static const gchar *const *
6717 gst_rtspsrc_uri_get_protocols (GType type)
6718 {
6719   static const gchar *protocols[] =
6720       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp", NULL };
6721
6722   return protocols;
6723 }
6724
6725 static gchar *
6726 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
6727 {
6728   GstRTSPSrc *src = GST_RTSPSRC (handler);
6729
6730   /* FIXME: make thread-safe */
6731   return g_strdup (src->conninfo.location);
6732 }
6733
6734 static gboolean
6735 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
6736     GError ** error)
6737 {
6738   GstRTSPSrc *src;
6739   GstRTSPResult res;
6740   GstRTSPUrl *newurl = NULL;
6741   GstSDPMessage *sdp = NULL;
6742
6743   src = GST_RTSPSRC (handler);
6744
6745   /* same URI, we're fine */
6746   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
6747     goto was_ok;
6748
6749   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
6750     if ((res = gst_sdp_message_new (&sdp) < 0))
6751       goto sdp_failed;
6752
6753     GST_DEBUG_OBJECT (src, "parsing SDP message");
6754     if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
6755       goto invalid_sdp;
6756   } else {
6757     /* try to parse */
6758     GST_DEBUG_OBJECT (src, "parsing URI");
6759     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
6760       goto parse_error;
6761   }
6762
6763   /* if worked, free previous and store new url object along with the original
6764    * location. */
6765   GST_DEBUG_OBJECT (src, "configuring URI");
6766   g_free (src->conninfo.location);
6767   src->conninfo.location = g_strdup (uri);
6768   gst_rtsp_url_free (src->conninfo.url);
6769   src->conninfo.url = newurl;
6770   g_free (src->conninfo.url_str);
6771   if (newurl)
6772     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
6773   else
6774     src->conninfo.url_str = NULL;
6775
6776   if (src->sdp)
6777     gst_sdp_message_free (src->sdp);
6778   src->sdp = sdp;
6779   src->from_sdp = sdp != NULL;
6780
6781   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
6782   GST_DEBUG_OBJECT (src, "request uri is: %s",
6783       GST_STR_NULL (src->conninfo.url_str));
6784
6785   return TRUE;
6786
6787   /* Special cases */
6788 was_ok:
6789   {
6790     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
6791     return TRUE;
6792   }
6793 sdp_failed:
6794   {
6795     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
6796     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
6797         "Could not create SDP");
6798     return FALSE;
6799   }
6800 invalid_sdp:
6801   {
6802     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
6803         GST_STR_NULL (uri));
6804     gst_sdp_message_free (sdp);
6805     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
6806         "Invalid SDP");
6807     return FALSE;
6808   }
6809 parse_error:
6810   {
6811     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
6812         GST_STR_NULL (uri), res);
6813     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
6814         "Invalid RTSP URI");
6815     return FALSE;
6816   }
6817 }
6818
6819 static void
6820 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
6821 {
6822   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
6823
6824   iface->get_type = gst_rtspsrc_uri_get_type;
6825   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
6826   iface->get_uri = gst_rtspsrc_uri_get_uri;
6827   iface->set_uri = gst_rtspsrc_uri_set_uri;
6828 }