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