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