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