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