rtspsrc: Only free GCheckSum after its last usage
[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     GList *streams;
3897     guint group_id = gst_util_group_id_next ();
3898
3899     /* generate an SHA256 sum of the URI */
3900     cs = g_checksum_new (G_CHECKSUM_SHA256);
3901     uri = src->conninfo.location;
3902     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
3903
3904     for (streams = src->streams; streams; streams = g_list_next (streams)) {
3905       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3906
3907       stream_id =
3908           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
3909       event = gst_event_new_stream_start (stream_id);
3910       gst_event_set_group_id (event, group_id);
3911
3912       g_free (stream_id);
3913       gst_rtspsrc_stream_push_event (src, ostream, event);
3914     }
3915     g_checksum_free (cs);
3916
3917     gst_rtspsrc_activate_streams (src);
3918     src->need_activate = FALSE;
3919   }
3920   if ((event = src->start_segment) != NULL) {
3921     src->start_segment = NULL;
3922     gst_rtspsrc_push_event (src, event);
3923   }
3924
3925   if (src->base_time == -1) {
3926     /* Take current running_time. This timestamp will be put on
3927      * the first buffer of each stream because we are a live source and so we
3928      * timestamp with the running_time. When we are dealing with TCP, we also
3929      * only timestamp the first buffer (using the DISCONT flag) because a server
3930      * typically bursts data, for which we don't want to compensate by speeding
3931      * up the media. The other timestamps will be interpollated from this one
3932      * using the RTP timestamps. */
3933     GST_OBJECT_LOCK (src);
3934     if (GST_ELEMENT_CLOCK (src)) {
3935       GstClockTime now;
3936       GstClockTime base_time;
3937
3938       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
3939       base_time = GST_ELEMENT_CAST (src)->base_time;
3940
3941       src->base_time = now - base_time;
3942
3943       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
3944           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
3945     }
3946     GST_OBJECT_UNLOCK (src);
3947   }
3948
3949   if (stream->discont && !is_rtcp) {
3950     /* mark first RTP buffer as discont */
3951     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3952     stream->discont = FALSE;
3953     /* first buffer gets the timestamp, other buffers are not timestamped and
3954      * their presentation time will be interpollated from the rtp timestamps. */
3955     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
3956         GST_TIME_ARGS (src->base_time));
3957
3958     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
3959   }
3960
3961   /* chain to the peer pad */
3962   if (GST_PAD_IS_SINK (outpad))
3963     ret = gst_pad_chain (outpad, buf);
3964   else
3965     ret = gst_pad_push (outpad, buf);
3966
3967   if (!is_rtcp) {
3968     /* combine all stream flows for the data transport */
3969     ret = gst_rtspsrc_combine_flows (src, stream, ret);
3970   }
3971   return ret;
3972
3973   /* ERRORS */
3974 unknown_stream:
3975   {
3976     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
3977     gst_rtsp_message_unset (message);
3978     return GST_FLOW_OK;
3979   }
3980 invalid_length:
3981   {
3982     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3983         ("Short message received, ignoring."));
3984     gst_rtsp_message_unset (message);
3985     return GST_FLOW_OK;
3986   }
3987 }
3988
3989 static GstFlowReturn
3990 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
3991 {
3992   GstRTSPMessage message = { 0 };
3993   GstRTSPResult res;
3994   GstFlowReturn ret = GST_FLOW_OK;
3995   GTimeVal tv_timeout;
3996
3997   while (TRUE) {
3998     /* get the next timeout interval */
3999     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4000
4001     /* see if the timeout period expired */
4002     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4003       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4004       /* send keep-alive, only act on interrupt, a warning will be posted for
4005        * other errors. */
4006       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4007         goto interrupt;
4008       /* get new timeout */
4009       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4010     }
4011
4012     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4013         tv_timeout.tv_sec, tv_timeout.tv_usec);
4014
4015     /* protect the connection with the connection lock so that we can see when
4016      * we are finished doing server communication */
4017     res =
4018         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4019         &message, src->ptcp_timeout);
4020
4021     switch (res) {
4022       case GST_RTSP_OK:
4023         GST_DEBUG_OBJECT (src, "we received a server message");
4024         break;
4025       case GST_RTSP_EINTR:
4026         /* we got interrupted this means we need to stop */
4027         goto interrupt;
4028       case GST_RTSP_ETIMEOUT:
4029         /* no reply, send keep alive */
4030         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4031         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4032           goto interrupt;
4033         continue;
4034       case GST_RTSP_EEOF:
4035         /* go EOS when the server closed the connection */
4036         goto server_eof;
4037       default:
4038         goto receive_error;
4039     }
4040
4041     switch (message.type) {
4042       case GST_RTSP_MESSAGE_REQUEST:
4043         /* server sends us a request message, handle it */
4044         res =
4045             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4046             &message);
4047         if (res == GST_RTSP_EEOF)
4048           goto server_eof;
4049         else if (res < 0)
4050           goto handle_request_failed;
4051         break;
4052       case GST_RTSP_MESSAGE_RESPONSE:
4053         /* we ignore response messages */
4054         GST_DEBUG_OBJECT (src, "ignoring response message");
4055         if (src->debug)
4056           gst_rtsp_message_dump (&message);
4057         break;
4058       case GST_RTSP_MESSAGE_DATA:
4059         GST_DEBUG_OBJECT (src, "got data message");
4060         ret = gst_rtspsrc_handle_data (src, &message);
4061         if (ret != GST_FLOW_OK)
4062           goto handle_data_failed;
4063         break;
4064       default:
4065         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4066             message.type);
4067         break;
4068     }
4069   }
4070   g_assert_not_reached ();
4071
4072   /* ERRORS */
4073 server_eof:
4074   {
4075     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4076     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4077         ("The server closed the connection."));
4078     src->conninfo.connected = FALSE;
4079     gst_rtsp_message_unset (&message);
4080     return GST_FLOW_EOS;
4081   }
4082 interrupt:
4083   {
4084     gst_rtsp_message_unset (&message);
4085     GST_DEBUG_OBJECT (src, "got interrupted");
4086     return GST_FLOW_FLUSHING;
4087   }
4088 receive_error:
4089   {
4090     gchar *str = gst_rtsp_strresult (res);
4091
4092     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4093         ("Could not receive message. (%s)", str));
4094     g_free (str);
4095
4096     gst_rtsp_message_unset (&message);
4097     return GST_FLOW_ERROR;
4098   }
4099 handle_request_failed:
4100   {
4101     gchar *str = gst_rtsp_strresult (res);
4102
4103     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4104         ("Could not handle server message. (%s)", str));
4105     g_free (str);
4106     gst_rtsp_message_unset (&message);
4107     return GST_FLOW_ERROR;
4108   }
4109 handle_data_failed:
4110   {
4111     GST_DEBUG_OBJECT (src, "could no handle data message");
4112     return ret;
4113   }
4114 }
4115
4116 static GstFlowReturn
4117 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4118 {
4119   GstRTSPResult res;
4120   GstRTSPMessage message = { 0 };
4121   gint retry = 0;
4122
4123   while (TRUE) {
4124     GTimeVal tv_timeout;
4125
4126     /* get the next timeout interval */
4127     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4128
4129     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4130         (gint) tv_timeout.tv_sec);
4131
4132     gst_rtsp_message_unset (&message);
4133
4134     /* we should continue reading the TCP socket because the server might
4135      * send us requests. When the session timeout expires, we need to send a
4136      * keep-alive request to keep the session open. */
4137     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4138         &message, &tv_timeout);
4139
4140     switch (res) {
4141       case GST_RTSP_OK:
4142         GST_DEBUG_OBJECT (src, "we received a server message");
4143         break;
4144       case GST_RTSP_EINTR:
4145         /* we got interrupted, see what we have to do */
4146         goto interrupt;
4147       case GST_RTSP_ETIMEOUT:
4148         /* send keep-alive, ignore the result, a warning will be posted. */
4149         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4150         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4151           goto interrupt;
4152         continue;
4153       case GST_RTSP_EEOF:
4154         /* server closed the connection. not very fatal for UDP, reconnect and
4155          * see what happens. */
4156         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4157             ("The server closed the connection."));
4158         if (src->udp_reconnect) {
4159           if ((res =
4160                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4161             goto connect_error;
4162         } else {
4163           goto server_eof;
4164         }
4165         continue;
4166       case GST_RTSP_ENET:
4167         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4168       default:
4169         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4170             ("Unhandled return value %d.", res));
4171         goto receive_error;
4172     }
4173
4174     switch (message.type) {
4175       case GST_RTSP_MESSAGE_REQUEST:
4176         /* server sends us a request message, handle it */
4177         res =
4178             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4179             &message);
4180         if (res == GST_RTSP_EEOF)
4181           goto server_eof;
4182         else if (res < 0)
4183           goto handle_request_failed;
4184         break;
4185       case GST_RTSP_MESSAGE_RESPONSE:
4186         /* we ignore response and data messages */
4187         GST_DEBUG_OBJECT (src, "ignoring response message");
4188         if (src->debug)
4189           gst_rtsp_message_dump (&message);
4190         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4191           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4192           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4193             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4194             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4195               goto interrupt;
4196           }
4197         } else {
4198           retry = 0;
4199         }
4200         break;
4201       case GST_RTSP_MESSAGE_DATA:
4202         /* we ignore response and data messages */
4203         GST_DEBUG_OBJECT (src, "ignoring data message");
4204         break;
4205       default:
4206         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4207             message.type);
4208         break;
4209     }
4210   }
4211   g_assert_not_reached ();
4212
4213   /* we get here when the connection got interrupted */
4214 interrupt:
4215   {
4216     gst_rtsp_message_unset (&message);
4217     GST_DEBUG_OBJECT (src, "got interrupted");
4218     return GST_FLOW_FLUSHING;
4219   }
4220 connect_error:
4221   {
4222     gchar *str = gst_rtsp_strresult (res);
4223     GstFlowReturn ret;
4224
4225     src->conninfo.connected = FALSE;
4226     if (res != GST_RTSP_EINTR) {
4227       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4228           ("Could not connect to server. (%s)", str));
4229       g_free (str);
4230       ret = GST_FLOW_ERROR;
4231     } else {
4232       ret = GST_FLOW_FLUSHING;
4233     }
4234     return ret;
4235   }
4236 receive_error:
4237   {
4238     gchar *str = gst_rtsp_strresult (res);
4239
4240     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4241         ("Could not receive message. (%s)", str));
4242     g_free (str);
4243     return GST_FLOW_ERROR;
4244   }
4245 handle_request_failed:
4246   {
4247     gchar *str = gst_rtsp_strresult (res);
4248     GstFlowReturn ret;
4249
4250     gst_rtsp_message_unset (&message);
4251     if (res != GST_RTSP_EINTR) {
4252       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4253           ("Could not handle server message. (%s)", str));
4254       g_free (str);
4255       ret = GST_FLOW_ERROR;
4256     } else {
4257       ret = GST_FLOW_FLUSHING;
4258     }
4259     return ret;
4260   }
4261 server_eof:
4262   {
4263     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4264     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4265         ("The server closed the connection."));
4266     src->conninfo.connected = FALSE;
4267     gst_rtsp_message_unset (&message);
4268     return GST_FLOW_EOS;
4269   }
4270 }
4271
4272 static GstRTSPResult
4273 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4274 {
4275   GstRTSPResult res = GST_RTSP_OK;
4276   gboolean restart;
4277
4278   GST_DEBUG_OBJECT (src, "doing reconnect");
4279
4280   GST_OBJECT_LOCK (src);
4281   /* only restart when the pads were not yet activated, else we were
4282    * streaming over UDP */
4283   restart = src->need_activate;
4284   GST_OBJECT_UNLOCK (src);
4285
4286   /* no need to restart, we're done */
4287   if (!restart)
4288     goto done;
4289
4290   /* we can try only TCP now */
4291   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4292
4293   /* close and cleanup our state */
4294   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4295     goto done;
4296
4297   /* see if we have TCP left to try. Also don't try TCP when we were configured
4298    * with an SDP. */
4299   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4300     goto no_protocols;
4301
4302   /* We post a warning message now to inform the user
4303    * that nothing happened. It's most likely a firewall thing. */
4304   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4305       ("Could not receive any UDP packets for %.4f seconds, maybe your "
4306           "firewall is blocking it. Retrying using a TCP connection.",
4307           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4308
4309   /* open new connection using tcp */
4310   if (gst_rtspsrc_open (src, async) < 0)
4311     goto open_failed;
4312
4313   /* start playback */
4314   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4315     goto play_failed;
4316
4317 done:
4318   return res;
4319
4320   /* ERRORS */
4321 no_protocols:
4322   {
4323     src->cur_protocols = 0;
4324     /* no transport possible, post an error and stop */
4325     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4326         ("Could not receive any UDP packets for %.4f seconds, maybe your "
4327             "firewall is blocking it. No other protocols to try.",
4328             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4329     return GST_RTSP_ERROR;
4330   }
4331 open_failed:
4332   {
4333     GST_DEBUG_OBJECT (src, "open failed");
4334     return GST_RTSP_OK;
4335   }
4336 play_failed:
4337   {
4338     GST_DEBUG_OBJECT (src, "play failed");
4339     return GST_RTSP_OK;
4340   }
4341 }
4342
4343 static void
4344 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4345 {
4346   switch (cmd) {
4347     case CMD_OPEN:
4348       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4349       break;
4350     case CMD_PLAY:
4351       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4352       break;
4353     case CMD_PAUSE:
4354       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4355       break;
4356     case CMD_CLOSE:
4357       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4358       break;
4359     default:
4360       break;
4361   }
4362 }
4363
4364 static void
4365 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4366 {
4367   switch (cmd) {
4368     case CMD_OPEN:
4369       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4370       break;
4371     case CMD_PLAY:
4372       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4373       break;
4374     case CMD_PAUSE:
4375       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4376       break;
4377     case CMD_CLOSE:
4378       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4379       break;
4380     default:
4381       break;
4382   }
4383 }
4384
4385 static void
4386 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4387 {
4388   switch (cmd) {
4389     case CMD_OPEN:
4390       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4391       break;
4392     case CMD_PLAY:
4393       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4394       break;
4395     case CMD_PAUSE:
4396       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4397       break;
4398     case CMD_CLOSE:
4399       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4400       break;
4401     default:
4402       break;
4403   }
4404 }
4405
4406 static void
4407 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4408 {
4409   switch (cmd) {
4410     case CMD_OPEN:
4411       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4412       break;
4413     case CMD_PLAY:
4414       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4415       break;
4416     case CMD_PAUSE:
4417       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4418       break;
4419     case CMD_CLOSE:
4420       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4421       break;
4422     default:
4423       break;
4424   }
4425 }
4426
4427 static void
4428 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4429 {
4430   if (ret == GST_RTSP_OK)
4431     gst_rtspsrc_loop_complete_cmd (src, cmd);
4432   else if (ret == GST_RTSP_EINTR)
4433     gst_rtspsrc_loop_cancel_cmd (src, cmd);
4434   else
4435     gst_rtspsrc_loop_error_cmd (src, cmd);
4436 }
4437
4438 static void
4439 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4440 {
4441   gint old;
4442
4443   /* start new request */
4444   gst_rtspsrc_loop_start_cmd (src, cmd);
4445
4446   GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4447
4448   GST_OBJECT_LOCK (src);
4449   old = src->pending_cmd;
4450   if (old == CMD_RECONNECT) {
4451     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4452     cmd = CMD_RECONNECT;
4453   }
4454   if (old != CMD_WAIT) {
4455     src->pending_cmd = CMD_WAIT;
4456     GST_OBJECT_UNLOCK (src);
4457     /* cancel previous request */
4458     GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4459     gst_rtspsrc_loop_cancel_cmd (src, old);
4460     GST_OBJECT_LOCK (src);
4461   }
4462   src->pending_cmd = cmd;
4463   /* interrupt if allowed */
4464   if (src->busy_cmd & mask) {
4465     GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4466     gst_rtspsrc_connection_flush (src, TRUE);
4467   } else {
4468     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4469   }
4470   if (src->task)
4471     gst_task_start (src->task);
4472   GST_OBJECT_UNLOCK (src);
4473 }
4474
4475 static gboolean
4476 gst_rtspsrc_loop (GstRTSPSrc * src)
4477 {
4478   GstFlowReturn ret;
4479
4480   if (!src->conninfo.connection || !src->conninfo.connected)
4481     goto no_connection;
4482
4483   if (src->interleaved)
4484     ret = gst_rtspsrc_loop_interleaved (src);
4485   else
4486     ret = gst_rtspsrc_loop_udp (src);
4487
4488   if (ret != GST_FLOW_OK)
4489     goto pause;
4490
4491   return TRUE;
4492
4493   /* ERRORS */
4494 no_connection:
4495   {
4496     GST_WARNING_OBJECT (src, "we are not connected");
4497     ret = GST_FLOW_FLUSHING;
4498     goto pause;
4499   }
4500 pause:
4501   {
4502     const gchar *reason = gst_flow_get_name (ret);
4503
4504     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4505     src->running = FALSE;
4506     if (ret == GST_FLOW_EOS) {
4507       /* perform EOS logic */
4508       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4509         gst_element_post_message (GST_ELEMENT_CAST (src),
4510             gst_message_new_segment_done (GST_OBJECT_CAST (src),
4511                 src->segment.format, src->segment.position));
4512         gst_rtspsrc_push_event (src,
4513             gst_event_new_segment_done (src->segment.format,
4514                 src->segment.position));
4515       } else {
4516         gst_rtspsrc_push_event (src, gst_event_new_eos ());
4517       }
4518     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4519       /* for fatal errors we post an error message, post the error before the
4520        * EOS so the app knows about the error first. */
4521       GST_ELEMENT_ERROR (src, STREAM, FAILED,
4522           ("Internal data flow error."),
4523           ("streaming task paused, reason %s (%d)", reason, ret));
4524       gst_rtspsrc_push_event (src, gst_event_new_eos ());
4525     }
4526     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
4527     return FALSE;
4528   }
4529 }
4530
4531 #ifndef GST_DISABLE_GST_DEBUG
4532 static const gchar *
4533 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4534 {
4535   gint index = 0;
4536
4537   while (method != 0) {
4538     index++;
4539     method >>= 1;
4540   }
4541   switch (index) {
4542     case 0:
4543       return "None";
4544     case 1:
4545       return "Basic";
4546     case 2:
4547       return "Digest";
4548   }
4549
4550   return "Unknown";
4551 }
4552 #endif
4553
4554 static const gchar *
4555 gst_rtspsrc_skip_lws (const gchar * s)
4556 {
4557   while (g_ascii_isspace (*s))
4558     s++;
4559   return s;
4560 }
4561
4562 static const gchar *
4563 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4564 {
4565   while (s > start && g_ascii_isspace (*(s - 1)))
4566     s--;
4567   return s;
4568 }
4569
4570 static const gchar *
4571 gst_rtspsrc_skip_commas (const gchar * s)
4572 {
4573   /* The grammar allows for multiple commas */
4574   while (g_ascii_isspace (*s) || *s == ',')
4575     s++;
4576   return s;
4577 }
4578
4579 static const gchar *
4580 gst_rtspsrc_skip_item (const gchar * s)
4581 {
4582   gboolean quoted = FALSE;
4583   const gchar *start = s;
4584
4585   /* A list item ends at the last non-whitespace character
4586    * before a comma which is not inside a quoted-string. Or at
4587    * the end of the string.
4588    */
4589   while (*s) {
4590     if (*s == '"')
4591       quoted = !quoted;
4592     else if (quoted) {
4593       if (*s == '\\' && *(s + 1))
4594         s++;
4595     } else {
4596       if (*s == ',')
4597         break;
4598     }
4599     s++;
4600   }
4601
4602   return gst_rtspsrc_unskip_lws (s, start);
4603 }
4604
4605 static void
4606 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4607 {
4608   gchar *src, *dst;
4609
4610   src = quoted_string + 1;
4611   dst = quoted_string;
4612   while (*src && *src != '"') {
4613     if (*src == '\\' && *(src + 1))
4614       src++;
4615     *dst++ = *src++;
4616   }
4617   *dst = '\0';
4618 }
4619
4620 /* Extract the authentication tokens that the server provided for each method
4621  * into an array of structures and give those to the connection object.
4622  */
4623 static void
4624 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4625     const gchar * header, gboolean * stale)
4626 {
4627   GSList *list = NULL, *iter;
4628   const gchar *end;
4629   gchar *item, *eq, *name_end, *value;
4630
4631   g_return_if_fail (stale != NULL);
4632
4633   gst_rtsp_connection_clear_auth_params (conn);
4634   *stale = FALSE;
4635
4636   /* Parse a header whose content is described by RFC2616 as
4637    * "#something", where "something" does not itself contain commas,
4638    * except as part of quoted-strings, into a list of allocated strings.
4639    */
4640   header = gst_rtspsrc_skip_commas (header);
4641   while (*header) {
4642     end = gst_rtspsrc_skip_item (header);
4643     list = g_slist_prepend (list, g_strndup (header, end - header));
4644     header = gst_rtspsrc_skip_commas (end);
4645   }
4646   if (!list)
4647     return;
4648
4649   list = g_slist_reverse (list);
4650   for (iter = list; iter; iter = iter->next) {
4651     item = iter->data;
4652
4653     eq = strchr (item, '=');
4654     if (eq) {
4655       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4656       if (name_end == item) {
4657         /* That's no good... */
4658         g_free (item);
4659         continue;
4660       }
4661
4662       *name_end = '\0';
4663
4664       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4665       if (*value == '"')
4666         gst_rtsp_decode_quoted_string (value);
4667     } else
4668       value = NULL;
4669
4670     if (item && (strcmp (item, "stale") == 0) &&
4671         value && (strcmp (value, "TRUE") == 0))
4672       *stale = TRUE;
4673     gst_rtsp_connection_set_auth_param (conn, item, value);
4674     g_free (item);
4675   }
4676
4677   g_slist_free (list);
4678 }
4679
4680 /* Parse a WWW-Authenticate Response header and determine the
4681  * available authentication methods
4682  *
4683  * This code should also cope with the fact that each WWW-Authenticate
4684  * header can contain multiple challenge methods + tokens
4685  *
4686  * At the moment, for Basic auth, we just do a minimal check and don't
4687  * even parse out the realm */
4688 static void
4689 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4690     GstRTSPConnection * conn, gboolean * stale)
4691 {
4692   gchar *start;
4693
4694   g_return_if_fail (hdr != NULL);
4695   g_return_if_fail (methods != NULL);
4696   g_return_if_fail (stale != NULL);
4697
4698   /* Skip whitespace at the start of the string */
4699   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4700
4701   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4702     *methods |= GST_RTSP_AUTH_BASIC;
4703   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4704     *methods |= GST_RTSP_AUTH_DIGEST;
4705     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4706   }
4707 }
4708
4709 /**
4710  * gst_rtspsrc_setup_auth:
4711  * @src: the rtsp source
4712  *
4713  * Configure a username and password and auth method on the
4714  * connection object based on a response we received from the
4715  * peer.
4716  *
4717  * Currently, this requires that a username and password were supplied
4718  * in the uri. In the future, they may be requested on demand by sending
4719  * a message up the bus.
4720  *
4721  * Returns: TRUE if authentication information could be set up correctly.
4722  */
4723 static gboolean
4724 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4725 {
4726   gchar *user = NULL;
4727   gchar *pass = NULL;
4728   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4729   GstRTSPAuthMethod method;
4730   GstRTSPResult auth_result;
4731   GstRTSPUrl *url;
4732   GstRTSPConnection *conn;
4733   gchar *hdr;
4734   gboolean stale = FALSE;
4735
4736   conn = src->conninfo.connection;
4737
4738   /* Identify the available auth methods and see if any are supported */
4739   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4740           &hdr, 0) == GST_RTSP_OK) {
4741     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4742   }
4743
4744   if (avail_methods == GST_RTSP_AUTH_NONE)
4745     goto no_auth_available;
4746
4747   /* For digest auth, if the response indicates that the session
4748    * data are stale, we just update them in the connection object and
4749    * return TRUE to retry the request */
4750   if (stale)
4751     src->tried_url_auth = FALSE;
4752
4753   url = gst_rtsp_connection_get_url (conn);
4754
4755   /* Do we have username and password available? */
4756   if (url != NULL && !src->tried_url_auth && url->user != NULL
4757       && url->passwd != NULL) {
4758     user = url->user;
4759     pass = url->passwd;
4760     src->tried_url_auth = TRUE;
4761     GST_DEBUG_OBJECT (src,
4762         "Attempting authentication using credentials from the URL");
4763   } else {
4764     user = src->user_id;
4765     pass = src->user_pw;
4766     GST_DEBUG_OBJECT (src,
4767         "Attempting authentication using credentials from the properties");
4768   }
4769
4770   /* FIXME: If the url didn't contain username and password or we tried them
4771    * already, request a username and passwd from the application via some kind
4772    * of credentials request message */
4773
4774   /* If we don't have a username and passwd at this point, bail out. */
4775   if (user == NULL || pass == NULL)
4776     goto no_user_pass;
4777
4778   /* Try to configure for each available authentication method, strongest to
4779    * weakest */
4780   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4781     /* Check if this method is available on the server */
4782     if ((method & avail_methods) == 0)
4783       continue;
4784
4785     /* Pass the credentials to the connection to try on the next request */
4786     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4787     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4788      * ignore it and end up retrying later */
4789     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4790       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4791           gst_rtsp_auth_method_to_string (method));
4792       break;
4793     }
4794   }
4795
4796   if (method == GST_RTSP_AUTH_NONE)
4797     goto no_auth_available;
4798
4799   return TRUE;
4800
4801 no_auth_available:
4802   {
4803     /* Output an error indicating that we couldn't connect because there were
4804      * no supported authentication protocols */
4805     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4806         ("No supported authentication protocol was found"));
4807     return FALSE;
4808   }
4809 no_user_pass:
4810   {
4811     /* We don't fire an error message, we just return FALSE and let the
4812      * normal NOT_AUTHORIZED error be propagated */
4813     return FALSE;
4814   }
4815 }
4816
4817 static GstRTSPResult
4818 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4819     GstRTSPMessage * request, GstRTSPMessage * response,
4820     GstRTSPStatusCode * code)
4821 {
4822   GstRTSPResult res;
4823   GstRTSPStatusCode thecode;
4824   gchar *content_base = NULL;
4825   gint try = 0;
4826
4827 again:
4828   if (!src->short_header)
4829     gst_rtsp_ext_list_before_send (src->extensions, request);
4830
4831   GST_DEBUG_OBJECT (src, "sending message");
4832
4833   if (src->debug)
4834     gst_rtsp_message_dump (request);
4835
4836   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4837   if (res < 0)
4838     goto send_error;
4839
4840   gst_rtsp_connection_reset_timeout (conn);
4841
4842 next:
4843   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4844   if (res < 0)
4845     goto receive_error;
4846
4847   if (src->debug)
4848     gst_rtsp_message_dump (response);
4849
4850   switch (response->type) {
4851     case GST_RTSP_MESSAGE_REQUEST:
4852       res = gst_rtspsrc_handle_request (src, conn, response);
4853       if (res == GST_RTSP_EEOF)
4854         goto server_eof;
4855       else if (res < 0)
4856         goto handle_request_failed;
4857       goto next;
4858     case GST_RTSP_MESSAGE_RESPONSE:
4859       /* ok, a response is good */
4860       GST_DEBUG_OBJECT (src, "received response message");
4861       break;
4862     case GST_RTSP_MESSAGE_DATA:
4863       /* get next response */
4864       GST_DEBUG_OBJECT (src, "handle data response message");
4865       gst_rtspsrc_handle_data (src, response);
4866       goto next;
4867     default:
4868       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4869           response->type);
4870       goto next;
4871   }
4872
4873   thecode = response->type_data.response.code;
4874
4875   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4876
4877   /* if the caller wanted the result code, we store it. */
4878   if (code)
4879     *code = thecode;
4880
4881   /* If the request didn't succeed, bail out before doing any more */
4882   if (thecode != GST_RTSP_STS_OK)
4883     return GST_RTSP_OK;
4884
4885   /* store new content base if any */
4886   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4887       &content_base, 0);
4888   if (content_base) {
4889     g_free (src->content_base);
4890     src->content_base = g_strdup (content_base);
4891   }
4892   gst_rtsp_ext_list_after_send (src->extensions, request, response);
4893
4894   return GST_RTSP_OK;
4895
4896   /* ERRORS */
4897 send_error:
4898   {
4899     gchar *str = gst_rtsp_strresult (res);
4900
4901     if (res != GST_RTSP_EINTR) {
4902       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4903           ("Could not send message. (%s)", str));
4904     } else {
4905       GST_WARNING_OBJECT (src, "send interrupted");
4906     }
4907     g_free (str);
4908     return res;
4909   }
4910 receive_error:
4911   {
4912     switch (res) {
4913       case GST_RTSP_EEOF:
4914         GST_WARNING_OBJECT (src, "server closed connection");
4915         if ((try == 0) && !src->interleaved && src->udp_reconnect) {
4916           try++;
4917           /* if reconnect succeeds, try again */
4918           if ((res =
4919                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
4920                       FALSE)) == 0)
4921             goto again;
4922         }
4923         /* only try once after reconnect, then fallthrough and error out */
4924       default:
4925       {
4926         gchar *str = gst_rtsp_strresult (res);
4927
4928         if (res != GST_RTSP_EINTR) {
4929           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4930               ("Could not receive message. (%s)", str));
4931         } else {
4932           GST_WARNING_OBJECT (src, "receive interrupted");
4933         }
4934         g_free (str);
4935         break;
4936       }
4937     }
4938     return res;
4939   }
4940 handle_request_failed:
4941   {
4942     /* ERROR was posted */
4943     gst_rtsp_message_unset (response);
4944     return res;
4945   }
4946 server_eof:
4947   {
4948     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4949     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4950         ("The server closed the connection."));
4951     gst_rtsp_message_unset (response);
4952     return res;
4953   }
4954 }
4955
4956 /**
4957  * gst_rtspsrc_send:
4958  * @src: the rtsp source
4959  * @conn: the connection to send on
4960  * @request: must point to a valid request
4961  * @response: must point to an empty #GstRTSPMessage
4962  * @code: an optional code result
4963  *
4964  * send @request and retrieve the response in @response. optionally @code can be
4965  * non-NULL in which case it will contain the status code of the response.
4966  *
4967  * If This function returns #GST_RTSP_OK, @response will contain a valid response
4968  * message that should be cleaned with gst_rtsp_message_unset() after usage.
4969  *
4970  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
4971  * @response message) if the response code was not 200 (OK).
4972  *
4973  * If the attempt results in an authentication failure, then this will attempt
4974  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
4975  * the request.
4976  *
4977  * Returns: #GST_RTSP_OK if the processing was successful.
4978  */
4979 static GstRTSPResult
4980 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4981     GstRTSPMessage * request, GstRTSPMessage * response,
4982     GstRTSPStatusCode * code)
4983 {
4984   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
4985   GstRTSPResult res = GST_RTSP_ERROR;
4986   gint count;
4987   gboolean retry;
4988   GstRTSPMethod method = GST_RTSP_INVALID;
4989
4990   count = 0;
4991   do {
4992     retry = FALSE;
4993
4994     /* make sure we don't loop forever */
4995     if (count++ > 8)
4996       break;
4997
4998     /* save method so we can disable it when the server complains */
4999     method = request->type_data.request.method;
5000
5001     if ((res =
5002             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5003       goto error;
5004
5005     switch (int_code) {
5006       case GST_RTSP_STS_UNAUTHORIZED:
5007         if (gst_rtspsrc_setup_auth (src, response)) {
5008           /* Try the request/response again after configuring the auth info
5009            * and loop again */
5010           retry = TRUE;
5011         }
5012         break;
5013       default:
5014         break;
5015     }
5016   } while (retry == TRUE);
5017
5018   /* If the user requested the code, let them handle errors, otherwise
5019    * post an error below */
5020   if (code != NULL)
5021     *code = int_code;
5022   else if (int_code != GST_RTSP_STS_OK)
5023     goto error_response;
5024
5025   return res;
5026
5027   /* ERRORS */
5028 error:
5029   {
5030     GST_DEBUG_OBJECT (src, "got error %d", res);
5031     return res;
5032   }
5033 error_response:
5034   {
5035     res = GST_RTSP_ERROR;
5036
5037     switch (response->type_data.response.code) {
5038       case GST_RTSP_STS_NOT_FOUND:
5039         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5040                 response->type_data.response.reason));
5041         break;
5042       case GST_RTSP_STS_MOVED_PERMANENTLY:
5043       case GST_RTSP_STS_MOVE_TEMPORARILY:
5044       {
5045         gchar *new_location;
5046         GstRTSPLowerTrans transports;
5047
5048         GST_DEBUG_OBJECT (src, "got redirection");
5049         /* if we don't have a Location Header, we must error */
5050         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5051                 &new_location, 0) < 0)
5052           break;
5053
5054         /* When we receive a redirect result, we go back to the INIT state after
5055          * parsing the new URI. The caller should do the needed steps to issue
5056          * a new setup when it detects this state change. */
5057         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5058
5059         /* save current transports */
5060         if (src->conninfo.url)
5061           transports = src->conninfo.url->transports;
5062         else
5063           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5064
5065         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5066
5067         /* set old transports */
5068         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5069           src->conninfo.url->transports = transports;
5070
5071         src->need_redirect = TRUE;
5072         src->state = GST_RTSP_STATE_INIT;
5073         res = GST_RTSP_OK;
5074         break;
5075       }
5076       case GST_RTSP_STS_NOT_ACCEPTABLE:
5077       case GST_RTSP_STS_NOT_IMPLEMENTED:
5078       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5079         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5080             gst_rtsp_method_as_text (method));
5081         src->methods &= ~method;
5082         res = GST_RTSP_OK;
5083         break;
5084       default:
5085         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5086             ("Got error response: %d (%s).", response->type_data.response.code,
5087                 response->type_data.response.reason));
5088         break;
5089     }
5090     /* if we return ERROR we should unset the response ourselves */
5091     if (res == GST_RTSP_ERROR)
5092       gst_rtsp_message_unset (response);
5093
5094     return res;
5095   }
5096 }
5097
5098 static GstRTSPResult
5099 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5100     GstRTSPMessage * response, GstRTSPSrc * src)
5101 {
5102   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5103       NULL);
5104 }
5105
5106
5107 /* parse the response and collect all the supported methods. We need this
5108  * information so that we don't try to send an unsupported request to the
5109  * server.
5110  */
5111 static gboolean
5112 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5113 {
5114   GstRTSPHeaderField field;
5115   gchar *respoptions;
5116   gint indx = 0;
5117
5118   /* reset supported methods */
5119   src->methods = 0;
5120
5121   /* Try Allow Header first */
5122   field = GST_RTSP_HDR_ALLOW;
5123   while (TRUE) {
5124     respoptions = NULL;
5125     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5126     if (indx == 0 && !respoptions) {
5127       /* if no Allow header was found then try the Public header... */
5128       field = GST_RTSP_HDR_PUBLIC;
5129       gst_rtsp_message_get_header (response, field, &respoptions, indx);
5130     }
5131     if (!respoptions)
5132       break;
5133
5134     src->methods |= gst_rtsp_options_from_text (respoptions);
5135
5136     indx++;
5137   }
5138
5139   if (src->methods == 0) {
5140     /* neither Allow nor Public are required, assume the server supports
5141      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5142      * well. */
5143     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5144     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5145   }
5146   /* always assume PLAY, FIXME, extensions should be able to override
5147    * this */
5148   src->methods |= GST_RTSP_PLAY;
5149   /* also assume it will support Range */
5150   src->seekable = TRUE;
5151
5152   /* we need describe and setup */
5153   if (!(src->methods & GST_RTSP_DESCRIBE))
5154     goto no_describe;
5155   if (!(src->methods & GST_RTSP_SETUP))
5156     goto no_setup;
5157
5158   return TRUE;
5159
5160   /* ERRORS */
5161 no_describe:
5162   {
5163     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5164         ("Server does not support DESCRIBE."));
5165     return FALSE;
5166   }
5167 no_setup:
5168   {
5169     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5170         ("Server does not support SETUP."));
5171     return FALSE;
5172   }
5173 }
5174
5175 /* masks to be kept in sync with the hardcoded protocol order of preference
5176  * in code below */
5177 static guint protocol_masks[] = {
5178   GST_RTSP_LOWER_TRANS_UDP,
5179   GST_RTSP_LOWER_TRANS_UDP_MCAST,
5180   GST_RTSP_LOWER_TRANS_TCP,
5181   0
5182 };
5183
5184 static GstRTSPResult
5185 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5186     GstRTSPLowerTrans protocols, gchar ** transports)
5187 {
5188   GstRTSPResult res;
5189   GString *result;
5190   gboolean add_udp_str;
5191
5192   *transports = NULL;
5193
5194   res =
5195       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5196
5197   if (res < 0)
5198     goto failed;
5199
5200   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5201
5202   /* extension listed transports, use those */
5203   if (*transports != NULL)
5204     return GST_RTSP_OK;
5205
5206   /* it's the default */
5207   add_udp_str = FALSE;
5208
5209   /* the default RTSP transports */
5210   result = g_string_new ("");
5211   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5212     GST_DEBUG_OBJECT (src, "adding UDP unicast");
5213
5214     g_string_append (result, "RTP/AVP");
5215     if (add_udp_str)
5216       g_string_append (result, "/UDP");
5217     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5218   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5219     GST_DEBUG_OBJECT (src, "adding UDP multicast");
5220
5221     /* we don't have to allocate any UDP ports yet, if the selected transport
5222      * turns out to be multicast we can create them and join the multicast
5223      * group indicated in the transport reply */
5224     if (result->len > 0)
5225       g_string_append (result, ",");
5226     g_string_append (result, "RTP/AVP");
5227     if (add_udp_str)
5228       g_string_append (result, "/UDP");
5229     g_string_append (result, ";multicast");
5230     if (src->next_port_num != 0) {
5231       if (src->client_port_range.max > 0 &&
5232           src->next_port_num >= src->client_port_range.max)
5233         goto no_ports;
5234
5235       g_string_append_printf (result, ";client_port=%d-%d",
5236           src->next_port_num, src->next_port_num + 1);
5237     }
5238   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5239     GST_DEBUG_OBJECT (src, "adding TCP");
5240
5241     if (result->len > 0)
5242       g_string_append (result, ",");
5243     g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
5244   }
5245   *transports = g_string_free (result, FALSE);
5246
5247   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5248
5249   return GST_RTSP_OK;
5250
5251   /* ERRORS */
5252 failed:
5253   {
5254     GST_ERROR ("extension gave error %d", res);
5255     return res;
5256   }
5257 no_ports:
5258   {
5259     GST_ERROR ("no more ports available");
5260     return GST_RTSP_ERROR;
5261   }
5262 }
5263
5264 static GstRTSPResult
5265 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5266     gint orig_rtpport, gint orig_rtcpport)
5267 {
5268   GstRTSPSrc *src;
5269   gint nr_udp, nr_int;
5270   gchar *next, *p;
5271   gint rtpport = 0, rtcpport = 0;
5272   GString *str;
5273
5274   src = stream->parent;
5275
5276   /* find number of placeholders first */
5277   if (strstr (*transports, "%%i2"))
5278     nr_int = 2;
5279   else if (strstr (*transports, "%%i1"))
5280     nr_int = 1;
5281   else
5282     nr_int = 0;
5283
5284   if (strstr (*transports, "%%u2"))
5285     nr_udp = 2;
5286   else if (strstr (*transports, "%%u1"))
5287     nr_udp = 1;
5288   else
5289     nr_udp = 0;
5290
5291   if (nr_udp == 0 && nr_int == 0)
5292     goto done;
5293
5294   if (nr_udp > 0) {
5295     if (!orig_rtpport || !orig_rtcpport) {
5296       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5297         goto failed;
5298     } else {
5299       rtpport = orig_rtpport;
5300       rtcpport = orig_rtcpport;
5301     }
5302   }
5303
5304   str = g_string_new ("");
5305   p = *transports;
5306   while ((next = strstr (p, "%%"))) {
5307     g_string_append_len (str, p, next - p);
5308     if (next[2] == 'u') {
5309       if (next[3] == '1')
5310         g_string_append_printf (str, "%d", rtpport);
5311       else if (next[3] == '2')
5312         g_string_append_printf (str, "%d", rtcpport);
5313     }
5314     if (next[2] == 'i') {
5315       if (next[3] == '1')
5316         g_string_append_printf (str, "%d", src->free_channel);
5317       else if (next[3] == '2')
5318         g_string_append_printf (str, "%d", src->free_channel + 1);
5319     }
5320
5321     p = next + 4;
5322   }
5323   /* append final part */
5324   g_string_append (str, p);
5325
5326   g_free (*transports);
5327   *transports = g_string_free (str, FALSE);
5328
5329 done:
5330   return GST_RTSP_OK;
5331
5332   /* ERRORS */
5333 failed:
5334   {
5335     GST_ERROR ("failed to allocate udp ports");
5336     return GST_RTSP_ERROR;
5337   }
5338 }
5339
5340 static gboolean
5341 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5342 {
5343   gboolean res = FALSE;
5344
5345   if (stream->caps) {
5346     GstStructure *s;
5347     const gchar *enc = NULL;
5348
5349     s = gst_caps_get_structure (stream->caps, 0);
5350     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5351       res = (strstr (enc, "-REAL") != NULL);
5352     }
5353   }
5354   return res;
5355 }
5356
5357 /* Perform the SETUP request for all the streams.
5358  *
5359  * We ask the server for a specific transport, which initially includes all the
5360  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5361  * two local UDP ports that we send to the server.
5362  *
5363  * Once the server replied with a transport, we configure the other streams
5364  * with the same transport.
5365  *
5366  * This function will also configure the stream for the selected transport,
5367  * which basically means creating the pipeline.
5368  */
5369 static GstRTSPResult
5370 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5371 {
5372   GList *walk;
5373   GstRTSPResult res = GST_RTSP_ERROR;
5374   GstRTSPMessage request = { 0 };
5375   GstRTSPMessage response = { 0 };
5376   GstRTSPStream *stream = NULL;
5377   GstRTSPLowerTrans protocols;
5378   GstRTSPStatusCode code;
5379   gboolean unsupported_real = FALSE;
5380   gint rtpport, rtcpport;
5381   GstRTSPUrl *url;
5382   gchar *hval;
5383
5384   if (src->conninfo.connection) {
5385     url = gst_rtsp_connection_get_url (src->conninfo.connection);
5386     /* we initially allow all configured lower transports. based on the URL
5387      * transports and the replies from the server we narrow them down. */
5388     protocols = url->transports & src->cur_protocols;
5389   } else {
5390     url = NULL;
5391     protocols = src->cur_protocols;
5392   }
5393
5394   if (protocols == 0)
5395     goto no_protocols;
5396
5397   /* reset some state */
5398   src->free_channel = 0;
5399   src->interleaved = FALSE;
5400   src->need_activate = FALSE;
5401   /* keep track of next port number, 0 is random */
5402   src->next_port_num = src->client_port_range.min;
5403   rtpport = rtcpport = 0;
5404
5405   if (G_UNLIKELY (src->streams == NULL))
5406     goto no_streams;
5407
5408   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5409     GstRTSPConnection *conn;
5410     gchar *transports;
5411     gint retry = 0;
5412     guint mask = 0;
5413     gboolean selected;
5414
5415     stream = (GstRTSPStream *) walk->data;
5416
5417     /* see if we need to configure this stream */
5418     if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5419       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5420           stream);
5421       stream->disabled = TRUE;
5422       continue;
5423     }
5424
5425     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
5426         stream->id, stream->caps, &selected);
5427     if (!selected) {
5428       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
5429       stream->disabled = TRUE;
5430       continue;
5431     }
5432     stream->disabled = FALSE;
5433
5434     /* merge/overwrite global caps */
5435     if (stream->caps) {
5436       guint j, num;
5437       GstStructure *s;
5438
5439       s = gst_caps_get_structure (stream->caps, 0);
5440
5441       num = gst_structure_n_fields (src->props);
5442       for (j = 0; j < num; j++) {
5443         const gchar *name;
5444         const GValue *val;
5445
5446         name = gst_structure_nth_field_name (src->props, j);
5447         val = gst_structure_get_value (src->props, name);
5448         gst_structure_set_value (s, name, val);
5449
5450         GST_DEBUG_OBJECT (src, "copied %s", name);
5451       }
5452     }
5453
5454     /* skip setup if we have no URL for it */
5455     if (stream->conninfo.location == NULL) {
5456       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5457       continue;
5458     }
5459
5460     if (src->conninfo.connection == NULL) {
5461       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5462         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5463         continue;
5464       }
5465       conn = stream->conninfo.connection;
5466     } else {
5467       conn = src->conninfo.connection;
5468     }
5469     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5470         stream->conninfo.location);
5471
5472     /* if we have a multicast connection, only suggest multicast from now on */
5473     if (stream->is_multicast)
5474       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5475
5476   next_protocol:
5477     /* first selectable protocol */
5478     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5479       mask++;
5480     if (!protocol_masks[mask])
5481       goto no_protocols;
5482
5483   retry:
5484     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5485         protocol_masks[mask]);
5486     /* create a string with first transport in line */
5487     transports = NULL;
5488     res = gst_rtspsrc_create_transports_string (src,
5489         protocols & protocol_masks[mask], &transports);
5490     if (res < 0 || transports == NULL)
5491       goto setup_transport_failed;
5492
5493     if (strlen (transports) == 0) {
5494       g_free (transports);
5495       GST_DEBUG_OBJECT (src, "no transports found");
5496       mask++;
5497       goto next_protocol;
5498     }
5499
5500     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5501
5502     /* replace placeholders with real values, this function will optionally
5503      * allocate UDP ports and other info needed to execute the setup request */
5504     res = gst_rtspsrc_prepare_transports (stream, &transports,
5505         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5506     if (res < 0) {
5507       g_free (transports);
5508       goto setup_transport_failed;
5509     }
5510
5511     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5512
5513     /* create SETUP request */
5514     res =
5515         gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5516         stream->conninfo.location);
5517     if (res < 0) {
5518       g_free (transports);
5519       goto create_request_failed;
5520     }
5521
5522     /* select transport */
5523     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5524
5525     /* if the user wants a non default RTP packet size we add the blocksize
5526      * parameter */
5527     if (src->rtp_blocksize > 0) {
5528       hval = g_strdup_printf ("%d", src->rtp_blocksize);
5529       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5530     }
5531
5532     if (async)
5533       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5534               stream->id));
5535
5536     /* handle the code ourselves */
5537     if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5538       goto send_error;
5539
5540     switch (code) {
5541       case GST_RTSP_STS_OK:
5542         break;
5543       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5544         gst_rtsp_message_unset (&request);
5545         gst_rtsp_message_unset (&response);
5546         /* cleanup of leftover transport */
5547         gst_rtspsrc_stream_free_udp (stream);
5548         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5549          * we might be in this case */
5550         if (stream->container && rtpport && rtcpport && !retry) {
5551           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5552               rtpport, rtcpport);
5553           retry++;
5554           goto retry;
5555         }
5556         /* this transport did not go down well, but we may have others to try
5557          * that we did not send yet, try those and only give up then
5558          * but not without checking for lost cause/extension so we can
5559          * post a nicer/more useful error message later */
5560         if (!unsupported_real)
5561           unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5562         /* select next available protocol, give up on this stream if none */
5563         mask++;
5564         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5565           mask++;
5566         if (!protocol_masks[mask] || unsupported_real)
5567           continue;
5568         else
5569           goto retry;
5570       default:
5571         /* cleanup of leftover transport and move to the next stream */
5572         gst_rtspsrc_stream_free_udp (stream);
5573         goto response_error;
5574     }
5575
5576     /* parse response transport */
5577     {
5578       gchar *resptrans = NULL;
5579       GstRTSPTransport transport = { 0 };
5580
5581       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5582           &resptrans, 0);
5583       if (!resptrans) {
5584         gst_rtspsrc_stream_free_udp (stream);
5585         goto no_transport;
5586       }
5587
5588       /* parse transport, go to next stream on parse error */
5589       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5590         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5591         goto next;
5592       }
5593
5594       /* update allowed transports for other streams. once the transport of
5595        * one stream has been determined, we make sure that all other streams
5596        * are configured in the same way */
5597       switch (transport.lower_transport) {
5598         case GST_RTSP_LOWER_TRANS_TCP:
5599           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5600           protocols = GST_RTSP_LOWER_TRANS_TCP;
5601           src->interleaved = TRUE;
5602           /* update free channels */
5603           src->free_channel =
5604               MAX (transport.interleaved.min, src->free_channel);
5605           src->free_channel =
5606               MAX (transport.interleaved.max, src->free_channel);
5607           src->free_channel++;
5608           break;
5609         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5610           /* only allow multicast for other streams */
5611           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5612           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5613           /* if the server selected our ports, increment our counters so that
5614            * we select a new port later */
5615           if (src->next_port_num == transport.port.min &&
5616               src->next_port_num + 1 == transport.port.max) {
5617             src->next_port_num += 2;
5618           }
5619           break;
5620         case GST_RTSP_LOWER_TRANS_UDP:
5621           /* only allow unicast for other streams */
5622           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5623           protocols = GST_RTSP_LOWER_TRANS_UDP;
5624           break;
5625         default:
5626           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5627               transport.lower_transport);
5628           break;
5629       }
5630
5631       if (!stream->container || (!src->interleaved && !retry)) {
5632         /* now configure the stream with the selected transport */
5633         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5634           GST_DEBUG_OBJECT (src,
5635               "could not configure stream %p transport, skipping stream",
5636               stream);
5637           goto next;
5638         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5639           /* retain the first allocated UDP port pair */
5640           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5641           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5642         }
5643       }
5644       /* we need to activate at least one streams when we detect activity */
5645       src->need_activate = TRUE;
5646     next:
5647       /* clean up our transport struct */
5648       gst_rtsp_transport_init (&transport);
5649       /* clean up used RTSP messages */
5650       gst_rtsp_message_unset (&request);
5651       gst_rtsp_message_unset (&response);
5652     }
5653   }
5654
5655   /* store the transport protocol that was configured */
5656   src->cur_protocols = protocols;
5657
5658   gst_rtsp_ext_list_stream_select (src->extensions, url);
5659
5660   /* if there is nothing to activate, error out */
5661   if (!src->need_activate)
5662     goto nothing_to_activate;
5663
5664   return res;
5665
5666   /* ERRORS */
5667 no_protocols:
5668   {
5669     /* no transport possible, post an error and stop */
5670     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5671         ("Could not connect to server, no protocols left"));
5672     return GST_RTSP_ERROR;
5673   }
5674 no_streams:
5675   {
5676     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5677         ("SDP contains no streams"));
5678     return GST_RTSP_ERROR;
5679   }
5680 create_request_failed:
5681   {
5682     gchar *str = gst_rtsp_strresult (res);
5683
5684     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5685         ("Could not create request. (%s)", str));
5686     g_free (str);
5687     goto cleanup_error;
5688   }
5689 setup_transport_failed:
5690   {
5691     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5692         ("Could not setup transport."));
5693     res = GST_RTSP_ERROR;
5694     goto cleanup_error;
5695   }
5696 response_error:
5697   {
5698     const gchar *str = gst_rtsp_status_as_text (code);
5699
5700     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5701         ("Error (%d): %s", code, GST_STR_NULL (str)));
5702     res = GST_RTSP_ERROR;
5703     goto cleanup_error;
5704   }
5705 send_error:
5706   {
5707     gchar *str = gst_rtsp_strresult (res);
5708
5709     if (res != GST_RTSP_EINTR) {
5710       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5711           ("Could not send message. (%s)", str));
5712     } else {
5713       GST_WARNING_OBJECT (src, "send interrupted");
5714     }
5715     g_free (str);
5716     goto cleanup_error;
5717   }
5718 no_transport:
5719   {
5720     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5721         ("Server did not select transport."));
5722     res = GST_RTSP_ERROR;
5723     goto cleanup_error;
5724   }
5725 nothing_to_activate:
5726   {
5727     /* none of the available error codes is really right .. */
5728     if (unsupported_real) {
5729       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5730           (_("No supported stream was found. You might need to install a "
5731                   "GStreamer RTSP extension plugin for Real media streams.")),
5732           (NULL));
5733     } else {
5734       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5735           (_("No supported stream was found. You might need to allow "
5736                   "more transport protocols or may otherwise be missing "
5737                   "the right GStreamer RTSP extension plugin.")), (NULL));
5738     }
5739     return GST_RTSP_ERROR;
5740   }
5741 cleanup_error:
5742   {
5743     gst_rtsp_message_unset (&request);
5744     gst_rtsp_message_unset (&response);
5745     return res;
5746   }
5747 }
5748
5749 static gboolean
5750 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5751     GstSegment * segment)
5752 {
5753   gint64 seconds;
5754   GstRTSPTimeRange *therange;
5755
5756   if (src->range)
5757     gst_rtsp_range_free (src->range);
5758
5759   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5760     GST_DEBUG_OBJECT (src, "parsed range %s", range);
5761     src->range = therange;
5762   } else {
5763     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5764     src->range = NULL;
5765     gst_segment_init (segment, GST_FORMAT_TIME);
5766     return FALSE;
5767   }
5768
5769   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
5770       therange->min.type, therange->min.seconds, therange->max.type,
5771       therange->max.seconds);
5772
5773   if (therange->min.type == GST_RTSP_TIME_NOW)
5774     seconds = 0;
5775   else if (therange->min.type == GST_RTSP_TIME_END)
5776     seconds = 0;
5777   else
5778     seconds = therange->min.seconds * GST_SECOND;
5779
5780   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5781       GST_TIME_ARGS (seconds));
5782
5783   /* we need to start playback without clipping from the position reported by
5784    * the server */
5785   segment->start = seconds;
5786   segment->position = seconds;
5787
5788   if (therange->max.type == GST_RTSP_TIME_NOW)
5789     seconds = -1;
5790   else if (therange->max.type == GST_RTSP_TIME_END)
5791     seconds = -1;
5792   else
5793     seconds = therange->max.seconds * GST_SECOND;
5794
5795   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5796       GST_TIME_ARGS (seconds));
5797
5798   /* live (WMS) server might send overflowed large max as its idea of infinity,
5799    * compensate to prevent problems later on */
5800   if (seconds != -1 && seconds < 0) {
5801     seconds = -1;
5802     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5803   }
5804
5805   /* live (WMS) might send min == max, which is not worth recording */
5806   if (segment->duration == -1 && seconds == segment->start)
5807     seconds = -1;
5808
5809   /* don't change duration with unknown value, we might have a valid value
5810    * there that we want to keep. */
5811   if (seconds != -1)
5812     segment->duration = seconds;
5813
5814   return TRUE;
5815 }
5816
5817 /* Parse clock profived by the server with following syntax:
5818  *
5819  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
5820  */
5821 static gboolean
5822 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
5823 {
5824   gboolean res = FALSE;
5825
5826   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
5827     gchar **fields = NULL, **parts = NULL;
5828     gchar *remote_ip, *str;
5829     gint port;
5830     GstClockTime base_time;
5831     GstClock *netclock;
5832
5833     fields = g_strsplit (gstclock, " ", 0);
5834
5835     /* wrapped clock, not very interesting for now */
5836     if (fields[1] == NULL)
5837       goto cleanup;
5838
5839     /* remote IP address and port */
5840     if ((str = fields[2]) == NULL)
5841       goto cleanup;
5842
5843     parts = g_strsplit (str, ":", 0);
5844
5845     if ((remote_ip = parts[0]) == NULL)
5846       goto cleanup;
5847
5848     if ((str = parts[1]) == NULL)
5849       goto cleanup;
5850
5851     port = atoi (str);
5852     if (port == 0)
5853       goto cleanup;
5854
5855     /* base-time */
5856     if ((str = fields[3]) == NULL)
5857       goto cleanup;
5858
5859     base_time = g_ascii_strtoull (str, NULL, 10);
5860
5861     netclock =
5862         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
5863         base_time);
5864
5865     if (src->provided_clock)
5866       gst_object_unref (src->provided_clock);
5867     src->provided_clock = netclock;
5868
5869     gst_element_post_message (GST_ELEMENT_CAST (src),
5870         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
5871             src->provided_clock, TRUE));
5872
5873     res = TRUE;
5874   cleanup:
5875     g_strfreev (fields);
5876     g_strfreev (parts);
5877   }
5878   return res;
5879 }
5880
5881 /* must be called with the RTSP state lock */
5882 static GstRTSPResult
5883 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5884     gboolean async)
5885 {
5886   GstRTSPResult res;
5887   gint i, n_streams;
5888
5889   /* prepare global stream caps properties */
5890   if (src->props)
5891     gst_structure_remove_all_fields (src->props);
5892   else
5893     src->props = gst_structure_new_empty ("RTSPProperties");
5894
5895   if (src->debug)
5896     gst_sdp_message_dump (sdp);
5897
5898   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5899
5900   /* let the app inspect and change the SDP */
5901   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
5902
5903   gst_segment_init (&src->segment, GST_FORMAT_TIME);
5904
5905   /* parse range for duration reporting. */
5906   {
5907     const gchar *range;
5908
5909     for (i = 0;; i++) {
5910       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5911       if (range == NULL)
5912         break;
5913
5914       /* keep track of the range and configure it in the segment */
5915       if (gst_rtspsrc_parse_range (src, range, &src->segment))
5916         break;
5917     }
5918   }
5919   /* parse clock information. This is GStreamer specific, a server can tell the
5920    * client what clock it is using and wrap that in a network clock. The
5921    * advantage of that is that we can slave to it. */
5922   {
5923     const gchar *gstclock;
5924
5925     for (i = 0;; i++) {
5926       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
5927       if (gstclock == NULL)
5928         break;
5929
5930       /* parse the clock and expose it in the provide_clock method */
5931       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
5932         break;
5933     }
5934   }
5935   /* try to find a global control attribute. Note that a '*' means that we should
5936    * do aggregate control with the current url (so we don't do anything and
5937    * leave the current connection as is) */
5938   {
5939     const gchar *control;
5940
5941     for (i = 0;; i++) {
5942       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
5943       if (control == NULL)
5944         break;
5945
5946       /* only take fully qualified urls */
5947       if (g_str_has_prefix (control, "rtsp://"))
5948         break;
5949     }
5950     if (control) {
5951       g_free (src->conninfo.location);
5952       src->conninfo.location = g_strdup (control);
5953       /* make a connection for this, if there was a connection already, nothing
5954        * happens. */
5955       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
5956         GST_ERROR_OBJECT (src, "could not connect");
5957       }
5958     }
5959     /* we need to keep the control url separate from the connection url because
5960      * the rules for constructing the media control url need it */
5961     g_free (src->control);
5962     src->control = g_strdup (control);
5963   }
5964
5965   /* create streams */
5966   n_streams = gst_sdp_message_medias_len (sdp);
5967   for (i = 0; i < n_streams; i++) {
5968     gst_rtspsrc_create_stream (src, sdp, i);
5969   }
5970
5971   src->state = GST_RTSP_STATE_INIT;
5972
5973   /* setup streams */
5974   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
5975     goto setup_failed;
5976
5977   /* reset our state */
5978   src->need_range = TRUE;
5979   src->skip = FALSE;
5980
5981   src->state = GST_RTSP_STATE_READY;
5982
5983   return res;
5984
5985   /* ERRORS */
5986 setup_failed:
5987   {
5988     GST_ERROR_OBJECT (src, "setup failed");
5989     gst_rtspsrc_cleanup (src);
5990     return res;
5991   }
5992 }
5993
5994 static GstRTSPResult
5995 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
5996     gboolean async)
5997 {
5998   GstRTSPResult res;
5999   GstRTSPMessage request = { 0 };
6000   GstRTSPMessage response = { 0 };
6001   guint8 *data;
6002   guint size;
6003   gchar *respcont = NULL;
6004
6005 restart:
6006   src->need_redirect = FALSE;
6007
6008   /* can't continue without a valid url */
6009   if (G_UNLIKELY (src->conninfo.url == NULL)) {
6010     res = GST_RTSP_EINVAL;
6011     goto no_url;
6012   }
6013   src->tried_url_auth = FALSE;
6014
6015   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
6016     goto connect_failed;
6017
6018   /* create OPTIONS */
6019   GST_DEBUG_OBJECT (src, "create options...");
6020   res =
6021       gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
6022       src->conninfo.url_str);
6023   if (res < 0)
6024     goto create_request_failed;
6025
6026   /* send OPTIONS */
6027   GST_DEBUG_OBJECT (src, "send options...");
6028
6029   if (async)
6030     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
6031
6032   if ((res =
6033           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6034               NULL)) < 0)
6035     goto send_error;
6036
6037   /* parse OPTIONS */
6038   if (!gst_rtspsrc_parse_methods (src, &response))
6039     goto methods_error;
6040
6041   /* create DESCRIBE */
6042   GST_DEBUG_OBJECT (src, "create describe...");
6043   res =
6044       gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
6045       src->conninfo.url_str);
6046   if (res < 0)
6047     goto create_request_failed;
6048
6049   /* we only accept SDP for now */
6050   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
6051       "application/sdp");
6052
6053   /* send DESCRIBE */
6054   GST_DEBUG_OBJECT (src, "send describe...");
6055
6056   if (async)
6057     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
6058
6059   if ((res =
6060           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6061               NULL)) < 0)
6062     goto send_error;
6063
6064   /* we only perform redirect for the describe, currently */
6065   if (src->need_redirect) {
6066     /* close connection, we don't have to send a TEARDOWN yet, ignore the
6067      * result. */
6068     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6069
6070     gst_rtsp_message_unset (&request);
6071     gst_rtsp_message_unset (&response);
6072
6073     /* and now retry */
6074     goto restart;
6075   }
6076
6077   /* it could be that the DESCRIBE method was not implemented */
6078   if (!src->methods & GST_RTSP_DESCRIBE)
6079     goto no_describe;
6080
6081   /* check if reply is SDP */
6082   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6083       0);
6084   /* could not be set but since the request returned OK, we assume it
6085    * was SDP, else check it. */
6086   if (respcont) {
6087     if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6088       goto wrong_content_type;
6089   }
6090
6091   /* get message body and parse as SDP */
6092   gst_rtsp_message_get_body (&response, &data, &size);
6093   if (data == NULL || size == 0)
6094     goto no_describe;
6095
6096   GST_DEBUG_OBJECT (src, "parse SDP...");
6097   gst_sdp_message_new (sdp);
6098   gst_sdp_message_parse_buffer (data, size, *sdp);
6099
6100   /* clean up any messages */
6101   gst_rtsp_message_unset (&request);
6102   gst_rtsp_message_unset (&response);
6103
6104   return res;
6105
6106   /* ERRORS */
6107 no_url:
6108   {
6109     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6110         ("No valid RTSP URL was provided"));
6111     goto cleanup_error;
6112   }
6113 connect_failed:
6114   {
6115     gchar *str = gst_rtsp_strresult (res);
6116
6117     if (res != GST_RTSP_EINTR) {
6118       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6119           ("Failed to connect. (%s)", str));
6120     } else {
6121       GST_WARNING_OBJECT (src, "connect interrupted");
6122     }
6123     g_free (str);
6124     goto cleanup_error;
6125   }
6126 create_request_failed:
6127   {
6128     gchar *str = gst_rtsp_strresult (res);
6129
6130     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6131         ("Could not create request. (%s)", str));
6132     g_free (str);
6133     goto cleanup_error;
6134   }
6135 send_error:
6136   {
6137     /* Don't post a message - the rtsp_send method will have
6138      * taken care of it because we passed NULL for the response code */
6139     goto cleanup_error;
6140   }
6141 methods_error:
6142   {
6143     /* error was posted */
6144     res = GST_RTSP_ERROR;
6145     goto cleanup_error;
6146   }
6147 wrong_content_type:
6148   {
6149     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6150         ("Server does not support SDP, got %s.", respcont));
6151     res = GST_RTSP_ERROR;
6152     goto cleanup_error;
6153   }
6154 no_describe:
6155   {
6156     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6157         ("Server can not provide an SDP."));
6158     res = GST_RTSP_ERROR;
6159     goto cleanup_error;
6160   }
6161 cleanup_error:
6162   {
6163     if (src->conninfo.connection) {
6164       GST_DEBUG_OBJECT (src, "free connection");
6165       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6166     }
6167     gst_rtsp_message_unset (&request);
6168     gst_rtsp_message_unset (&response);
6169     return res;
6170   }
6171 }
6172
6173 static GstRTSPResult
6174 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6175 {
6176   GstRTSPResult ret;
6177
6178   src->methods =
6179       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6180
6181   if (src->sdp == NULL) {
6182     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6183       goto no_sdp;
6184   }
6185
6186   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6187     goto open_failed;
6188
6189 done:
6190   if (async)
6191     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6192
6193   return ret;
6194
6195   /* ERRORS */
6196 no_sdp:
6197   {
6198     GST_WARNING_OBJECT (src, "can't get sdp");
6199     src->open_error = TRUE;
6200     goto done;
6201   }
6202 open_failed:
6203   {
6204     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6205     src->open_error = TRUE;
6206     goto done;
6207   }
6208 }
6209
6210 static GstRTSPResult
6211 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6212 {
6213   GstRTSPMessage request = { 0 };
6214   GstRTSPMessage response = { 0 };
6215   GstRTSPResult res = GST_RTSP_OK;
6216   GList *walk;
6217   gchar *control;
6218
6219   GST_DEBUG_OBJECT (src, "TEARDOWN...");
6220
6221   gst_rtspsrc_set_state (src, GST_STATE_READY);
6222
6223   if (src->state < GST_RTSP_STATE_READY) {
6224     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6225     goto close;
6226   }
6227
6228   if (only_close)
6229     goto close;
6230
6231   /* construct a control url */
6232   if (src->control)
6233     control = src->control;
6234   else
6235     control = src->conninfo.url_str;
6236
6237   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6238     goto not_supported;
6239
6240   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6241     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6242     gchar *setup_url;
6243     GstRTSPConnInfo *info;
6244
6245     /* try aggregate control first but do non-aggregate control otherwise */
6246     if (control)
6247       setup_url = control;
6248     else if ((setup_url = stream->conninfo.location) == NULL)
6249       continue;
6250
6251     if (src->conninfo.connection) {
6252       info = &src->conninfo;
6253     } else if (stream->conninfo.connection) {
6254       info = &stream->conninfo;
6255     } else {
6256       continue;
6257     }
6258     if (!info->connected)
6259       goto next;
6260
6261     /* do TEARDOWN */
6262     res =
6263         gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6264     if (res < 0)
6265       goto create_request_failed;
6266
6267     if (async)
6268       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6269
6270     if ((res =
6271             gst_rtspsrc_send (src, info->connection, &request, &response,
6272                 NULL)) < 0)
6273       goto send_error;
6274
6275     /* FIXME, parse result? */
6276     gst_rtsp_message_unset (&request);
6277     gst_rtsp_message_unset (&response);
6278
6279   next:
6280     /* early exit when we did aggregate control */
6281     if (control)
6282       break;
6283   }
6284
6285 close:
6286   /* close connections */
6287   GST_DEBUG_OBJECT (src, "closing connection...");
6288   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6289   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6290     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6291     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6292   }
6293
6294   /* cleanup */
6295   gst_rtspsrc_cleanup (src);
6296
6297   src->state = GST_RTSP_STATE_INVALID;
6298
6299   if (async)
6300     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6301
6302   return res;
6303
6304   /* ERRORS */
6305 create_request_failed:
6306   {
6307     gchar *str = gst_rtsp_strresult (res);
6308
6309     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6310         ("Could not create request. (%s)", str));
6311     g_free (str);
6312     goto close;
6313   }
6314 send_error:
6315   {
6316     gchar *str = gst_rtsp_strresult (res);
6317
6318     gst_rtsp_message_unset (&request);
6319     if (res != GST_RTSP_EINTR) {
6320       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6321           ("Could not send message. (%s)", str));
6322     } else {
6323       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
6324     }
6325     g_free (str);
6326     goto close;
6327   }
6328 not_supported:
6329   {
6330     GST_DEBUG_OBJECT (src,
6331         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
6332     goto close;
6333   }
6334 }
6335
6336 /* RTP-Info is of the format:
6337  *
6338  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
6339  *
6340  * rtptime corresponds to the timestamp for the NPT time given in the header
6341  * seqbase corresponds to the next sequence number we received. This number
6342  * indicates the first seqnum after the seek and should be used to discard
6343  * packets that are from before the seek.
6344  */
6345 static gboolean
6346 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
6347 {
6348   gchar **infos;
6349   gint i, j;
6350
6351   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
6352
6353   infos = g_strsplit (rtpinfo, ",", 0);
6354   for (i = 0; infos[i]; i++) {
6355     gchar **fields;
6356     GstRTSPStream *stream;
6357     gint32 seqbase;
6358     gint64 timebase;
6359
6360     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
6361
6362     /* init values, types of seqbase and timebase are bigger than needed so we
6363      * can store -1 as uninitialized values */
6364     stream = NULL;
6365     seqbase = -1;
6366     timebase = -1;
6367
6368     /* parse url, find stream for url.
6369      * parse seq and rtptime. The seq number should be configured in the rtp
6370      * depayloader or session manager to detect gaps. Same for the rtptime, it
6371      * should be used to create an initial time newsegment. */
6372     fields = g_strsplit (infos[i], ";", 0);
6373     for (j = 0; fields[j]; j++) {
6374       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
6375       /* remove leading whitespace */
6376       fields[j] = g_strchug (fields[j]);
6377       if (g_str_has_prefix (fields[j], "url=")) {
6378         /* get the url and the stream */
6379         stream =
6380             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
6381       } else if (g_str_has_prefix (fields[j], "seq=")) {
6382         seqbase = atoi (fields[j] + 4);
6383       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
6384         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
6385       }
6386     }
6387     g_strfreev (fields);
6388     /* now we need to store the values for the caps of the stream */
6389     if (stream != NULL) {
6390       GST_DEBUG_OBJECT (src,
6391           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
6392           stream, seqbase, timebase);
6393
6394       /* we have a stream, configure detected params */
6395       stream->seqbase = seqbase;
6396       stream->timebase = timebase;
6397     }
6398   }
6399   g_strfreev (infos);
6400
6401   return TRUE;
6402 }
6403
6404 static void
6405 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
6406 {
6407   guint64 interval;
6408   GList *walk;
6409
6410   interval = strtoul (rtcp, NULL, 10);
6411   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
6412
6413   if (!interval)
6414     return;
6415
6416   interval *= GST_MSECOND;
6417
6418   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6419     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6420
6421     /* already (optionally) retrieved this when configuring manager */
6422     if (stream->session) {
6423       GObject *rtpsession = stream->session;
6424
6425       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
6426           rtpsession);
6427       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
6428     }
6429   }
6430
6431   /* now it happens that (Xenon) server sending this may also provide bogus
6432    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
6433    * and just use RTP-Info to sync */
6434   if (src->manager) {
6435     GObjectClass *klass;
6436
6437     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6438     if (g_object_class_find_property (klass, "rtcp-sync")) {
6439       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6440       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6441     }
6442   }
6443 }
6444
6445 static gdouble
6446 gst_rtspsrc_get_float (const gchar * dstr)
6447 {
6448   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6449
6450   /* canonicalise floating point string so we can handle float strings
6451    * in the form "24.930" or "24,930" irrespective of the current locale */
6452   g_strlcpy (s, dstr, sizeof (s));
6453   g_strdelimit (s, ",", '.');
6454   return g_ascii_strtod (s, NULL);
6455 }
6456
6457 static gchar *
6458 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6459 {
6460   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6461
6462   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6463     g_strlcpy (val_str, "now", sizeof (val_str));
6464   } else {
6465     if (segment->position == 0) {
6466       g_strlcpy (val_str, "0", sizeof (val_str));
6467     } else {
6468       g_ascii_dtostr (val_str, sizeof (val_str),
6469           ((gdouble) segment->position) / GST_SECOND);
6470     }
6471   }
6472   return g_strdup_printf ("npt=%s-", val_str);
6473 }
6474
6475 static void
6476 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6477 {
6478   stream->timebase = -1;
6479   stream->seqbase = -1;
6480   if (stream->caps) {
6481     GstStructure *s;
6482
6483     stream->caps = gst_caps_make_writable (stream->caps);
6484     s = gst_caps_get_structure (stream->caps, 0);
6485     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6486   }
6487 }
6488
6489 static GstRTSPResult
6490 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6491 {
6492   GstRTSPResult res = GST_RTSP_OK;
6493
6494   if (src->state < GST_RTSP_STATE_READY) {
6495     res = GST_RTSP_ERROR;
6496     if (src->open_error) {
6497       GST_DEBUG_OBJECT (src, "the stream was in error");
6498       goto done;
6499     }
6500     if (async)
6501       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6502
6503     if ((res = gst_rtspsrc_open (src, async)) < 0) {
6504       GST_DEBUG_OBJECT (src, "failed to open stream");
6505       goto done;
6506     }
6507   }
6508
6509 done:
6510   return res;
6511 }
6512
6513 static GstRTSPResult
6514 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6515 {
6516   GstRTSPMessage request = { 0 };
6517   GstRTSPMessage response = { 0 };
6518   GstRTSPResult res = GST_RTSP_OK;
6519   GList *walk;
6520   gchar *hval;
6521   gint hval_idx;
6522   gchar *control;
6523
6524   GST_DEBUG_OBJECT (src, "PLAY...");
6525
6526   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6527     goto open_failed;
6528
6529   if (!(src->methods & GST_RTSP_PLAY))
6530     goto not_supported;
6531
6532   if (src->state == GST_RTSP_STATE_PLAYING)
6533     goto was_playing;
6534
6535   if (!src->conninfo.connection || !src->conninfo.connected)
6536     goto done;
6537
6538   /* send some dummy packets before we activate the receive in the
6539    * udp sources */
6540   gst_rtspsrc_send_dummy_packets (src);
6541
6542   /* require new SR packets */
6543   if (src->manager)
6544     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
6545
6546   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
6547
6548   /* construct a control url */
6549   if (src->control)
6550     control = src->control;
6551   else
6552     control = src->conninfo.url_str;
6553
6554   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6555     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6556     gchar *setup_url;
6557     GstRTSPConnection *conn;
6558
6559     /* try aggregate control first but do non-aggregate control otherwise */
6560     if (control)
6561       setup_url = control;
6562     else if ((setup_url = stream->conninfo.location) == NULL)
6563       continue;
6564
6565     if (src->conninfo.connection) {
6566       conn = src->conninfo.connection;
6567     } else if (stream->conninfo.connection) {
6568       conn = stream->conninfo.connection;
6569     } else {
6570       continue;
6571     }
6572
6573     /* do play */
6574     res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6575     if (res < 0)
6576       goto create_request_failed;
6577
6578     if (src->need_range) {
6579       hval = gen_range_header (src, segment);
6580
6581       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
6582
6583       /* store the newsegment event so it can be sent from the streaming thread. */
6584       if (src->start_segment)
6585         gst_event_unref (src->start_segment);
6586       src->start_segment = gst_event_new_segment (&src->segment);
6587     }
6588
6589     if (segment->rate != 1.0) {
6590       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6591
6592       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6593       if (src->skip)
6594         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6595       else
6596         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6597     }
6598
6599     if (async)
6600       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6601
6602     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6603       goto send_error;
6604
6605     /* seek may have silently failed as it is not supported */
6606     if (!(src->methods & GST_RTSP_PLAY)) {
6607       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6608       /* obviously it is supported as we made it here */
6609       src->methods |= GST_RTSP_PLAY;
6610       src->seekable = FALSE;
6611       /* but there is nothing to parse in the response,
6612        * so convey we have no idea and not to expect anything particular */
6613       clear_rtp_base (src, stream);
6614       if (control) {
6615         GList *run;
6616
6617         /* need to do for all streams */
6618         for (run = src->streams; run; run = g_list_next (run))
6619           clear_rtp_base (src, (GstRTSPStream *) run->data);
6620       }
6621       /* NOTE the above also disables npt based eos detection */
6622       /* and below forces position to 0,
6623        * which is visible feedback we lost the plot */
6624       segment->start = segment->position = src->last_pos;
6625     }
6626
6627     gst_rtsp_message_unset (&request);
6628
6629     /* parse RTP npt field. This is the current position in the stream (Normal
6630      * Play Time) and should be put in the NEWSEGMENT position field. */
6631     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6632             0) == GST_RTSP_OK)
6633       gst_rtspsrc_parse_range (src, hval, segment);
6634
6635     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6636     segment->rate = 1.0;
6637
6638     /* parse Speed header. This is the intended playback rate of the stream
6639      * and should be put in the NEWSEGMENT rate field. */
6640     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6641             0) == GST_RTSP_OK) {
6642       segment->rate = gst_rtspsrc_get_float (hval);
6643     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6644             &hval, 0) == GST_RTSP_OK) {
6645       segment->rate = gst_rtspsrc_get_float (hval);
6646     }
6647
6648     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6649      * for the RTP packets. If this is not present, we assume all starts from 0...
6650      * This is info for the RTP session manager that we pass to it in caps. */
6651     hval_idx = 0;
6652     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6653             &hval, hval_idx++) == GST_RTSP_OK)
6654       gst_rtspsrc_parse_rtpinfo (src, hval);
6655
6656     /* some servers indicate RTCP parameters in PLAY response,
6657      * rather than properly in SDP */
6658     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6659             &hval, 0) == GST_RTSP_OK)
6660       gst_rtspsrc_handle_rtcp_interval (src, hval);
6661
6662     gst_rtsp_message_unset (&response);
6663
6664     /* early exit when we did aggregate control */
6665     if (control)
6666       break;
6667   }
6668   /* configure the caps of the streams after we parsed all headers. Only reset
6669    * the manager object when we set a new Range header (we did a seek) */
6670   gst_rtspsrc_configure_caps (src, segment, src->need_range);
6671
6672   /* set again when needed */
6673   src->need_range = FALSE;
6674
6675   src->running = TRUE;
6676   src->base_time = -1;
6677   src->state = GST_RTSP_STATE_PLAYING;
6678
6679   /* mark discont */
6680   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6681   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6682     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6683     stream->discont = TRUE;
6684   }
6685
6686 done:
6687   if (async)
6688     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6689
6690   return res;
6691
6692   /* ERRORS */
6693 open_failed:
6694   {
6695     GST_DEBUG_OBJECT (src, "failed to open stream");
6696     goto done;
6697   }
6698 not_supported:
6699   {
6700     GST_DEBUG_OBJECT (src, "PLAY is not supported");
6701     goto done;
6702   }
6703 was_playing:
6704   {
6705     GST_DEBUG_OBJECT (src, "we were already PLAYING");
6706     goto done;
6707   }
6708 create_request_failed:
6709   {
6710     gchar *str = gst_rtsp_strresult (res);
6711
6712     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6713         ("Could not create request. (%s)", str));
6714     g_free (str);
6715     goto done;
6716   }
6717 send_error:
6718   {
6719     gchar *str = gst_rtsp_strresult (res);
6720
6721     gst_rtsp_message_unset (&request);
6722     if (res != GST_RTSP_EINTR) {
6723       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6724           ("Could not send message. (%s)", str));
6725     } else {
6726       GST_WARNING_OBJECT (src, "PLAY interrupted");
6727     }
6728     g_free (str);
6729     goto done;
6730   }
6731 }
6732
6733 static GstRTSPResult
6734 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
6735 {
6736   GstRTSPResult res = GST_RTSP_OK;
6737   GstRTSPMessage request = { 0 };
6738   GstRTSPMessage response = { 0 };
6739   GList *walk;
6740   gchar *control;
6741
6742   GST_DEBUG_OBJECT (src, "PAUSE...");
6743
6744   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6745     goto open_failed;
6746
6747   if (!(src->methods & GST_RTSP_PAUSE))
6748     goto not_supported;
6749
6750   if (src->state == GST_RTSP_STATE_READY)
6751     goto was_paused;
6752
6753   if (!src->conninfo.connection || !src->conninfo.connected)
6754     goto no_connection;
6755
6756   /* construct a control url */
6757   if (src->control)
6758     control = src->control;
6759   else
6760     control = src->conninfo.url_str;
6761
6762   /* loop over the streams. We might exit the loop early when we could do an
6763    * aggregate control */
6764   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6765     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6766     GstRTSPConnection *conn;
6767     gchar *setup_url;
6768
6769     /* try aggregate control first but do non-aggregate control otherwise */
6770     if (control)
6771       setup_url = control;
6772     else if ((setup_url = stream->conninfo.location) == NULL)
6773       continue;
6774
6775     if (src->conninfo.connection) {
6776       conn = src->conninfo.connection;
6777     } else if (stream->conninfo.connection) {
6778       conn = stream->conninfo.connection;
6779     } else {
6780       continue;
6781     }
6782
6783     if (async)
6784       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6785           ("Sending PAUSE request"));
6786
6787     if ((res =
6788             gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6789                 setup_url)) < 0)
6790       goto create_request_failed;
6791
6792     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6793       goto send_error;
6794
6795     gst_rtsp_message_unset (&request);
6796     gst_rtsp_message_unset (&response);
6797
6798     /* exit early when we did agregate control */
6799     if (control)
6800       break;
6801   }
6802
6803   /* change element states now */
6804   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
6805
6806 no_connection:
6807   src->state = GST_RTSP_STATE_READY;
6808
6809 done:
6810   if (async)
6811     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6812
6813   return res;
6814
6815   /* ERRORS */
6816 open_failed:
6817   {
6818     GST_DEBUG_OBJECT (src, "failed to open stream");
6819     goto done;
6820   }
6821 not_supported:
6822   {
6823     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6824     goto done;
6825   }
6826 was_paused:
6827   {
6828     GST_DEBUG_OBJECT (src, "we were already PAUSED");
6829     goto done;
6830   }
6831 create_request_failed:
6832   {
6833     gchar *str = gst_rtsp_strresult (res);
6834
6835     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6836         ("Could not create request. (%s)", str));
6837     g_free (str);
6838     goto done;
6839   }
6840 send_error:
6841   {
6842     gchar *str = gst_rtsp_strresult (res);
6843
6844     gst_rtsp_message_unset (&request);
6845     if (res != GST_RTSP_EINTR) {
6846       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6847           ("Could not send message. (%s)", str));
6848     } else {
6849       GST_WARNING_OBJECT (src, "PAUSE interrupted");
6850     }
6851     g_free (str);
6852     goto done;
6853   }
6854 }
6855
6856 static void
6857 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6858 {
6859   GstRTSPSrc *rtspsrc;
6860
6861   rtspsrc = GST_RTSPSRC (bin);
6862
6863   switch (GST_MESSAGE_TYPE (message)) {
6864     case GST_MESSAGE_EOS:
6865       gst_message_unref (message);
6866       break;
6867     case GST_MESSAGE_ELEMENT:
6868     {
6869       const GstStructure *s = gst_message_get_structure (message);
6870
6871       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6872         gboolean ignore_timeout;
6873
6874         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6875
6876         GST_OBJECT_LOCK (rtspsrc);
6877         ignore_timeout = rtspsrc->ignore_timeout;
6878         rtspsrc->ignore_timeout = TRUE;
6879         GST_OBJECT_UNLOCK (rtspsrc);
6880
6881         /* we only act on the first udp timeout message, others are irrelevant
6882          * and can be ignored. */
6883         if (!ignore_timeout)
6884           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
6885         /* eat and free */
6886         gst_message_unref (message);
6887         return;
6888       }
6889       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6890       break;
6891     }
6892     case GST_MESSAGE_ERROR:
6893     {
6894       GstObject *udpsrc;
6895       GstRTSPStream *stream;
6896       GstFlowReturn ret;
6897
6898       udpsrc = GST_MESSAGE_SRC (message);
6899
6900       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6901           GST_ELEMENT_NAME (udpsrc));
6902
6903       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6904       if (!stream)
6905         goto forward;
6906
6907       /* we ignore the RTCP udpsrc */
6908       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6909         goto done;
6910
6911       /* if we get error messages from the udp sources, that's not a problem as
6912        * long as not all of them error out. We also don't really know what the
6913        * problem is, the message does not give enough detail... */
6914       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6915       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
6916       if (ret != GST_FLOW_OK)
6917         goto forward;
6918
6919     done:
6920       gst_message_unref (message);
6921       break;
6922
6923     forward:
6924       /* fatal but not our message, forward */
6925       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6926       break;
6927     }
6928     default:
6929     {
6930       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6931       break;
6932     }
6933   }
6934 }
6935
6936 /* the thread where everything happens */
6937 static void
6938 gst_rtspsrc_thread (GstRTSPSrc * src)
6939 {
6940   gint cmd;
6941
6942   GST_OBJECT_LOCK (src);
6943   cmd = src->pending_cmd;
6944   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
6945       || cmd == CMD_LOOP)
6946     src->pending_cmd = CMD_LOOP;
6947   else
6948     src->pending_cmd = CMD_WAIT;
6949   GST_DEBUG_OBJECT (src, "got command %d", cmd);
6950
6951   /* we got the message command, so ensure communication is possible again */
6952   gst_rtspsrc_connection_flush (src, FALSE);
6953
6954   src->busy_cmd = cmd;
6955   GST_OBJECT_UNLOCK (src);
6956
6957   switch (cmd) {
6958     case CMD_OPEN:
6959       gst_rtspsrc_open (src, TRUE);
6960       break;
6961     case CMD_PLAY:
6962       gst_rtspsrc_play (src, &src->segment, TRUE);
6963       break;
6964     case CMD_PAUSE:
6965       gst_rtspsrc_pause (src, TRUE);
6966       break;
6967     case CMD_CLOSE:
6968       gst_rtspsrc_close (src, TRUE, FALSE);
6969       break;
6970     case CMD_LOOP:
6971       gst_rtspsrc_loop (src);
6972       break;
6973     case CMD_RECONNECT:
6974       gst_rtspsrc_reconnect (src, FALSE);
6975       break;
6976     default:
6977       break;
6978   }
6979
6980   GST_OBJECT_LOCK (src);
6981   /* and go back to sleep */
6982   if (src->pending_cmd == CMD_WAIT) {
6983     if (src->task)
6984       gst_task_pause (src->task);
6985   }
6986   /* reset waiting */
6987   src->busy_cmd = CMD_WAIT;
6988   GST_OBJECT_UNLOCK (src);
6989 }
6990
6991 static gboolean
6992 gst_rtspsrc_start (GstRTSPSrc * src)
6993 {
6994   GST_DEBUG_OBJECT (src, "starting");
6995
6996   GST_OBJECT_LOCK (src);
6997
6998   src->pending_cmd = CMD_WAIT;
6999
7000   if (src->task == NULL) {
7001     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
7002     if (src->task == NULL)
7003       goto task_error;
7004
7005     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
7006   }
7007   GST_OBJECT_UNLOCK (src);
7008
7009   return TRUE;
7010
7011   /* ERRORS */
7012 task_error:
7013   {
7014     GST_ERROR_OBJECT (src, "failed to create task");
7015     return FALSE;
7016   }
7017 }
7018
7019 static gboolean
7020 gst_rtspsrc_stop (GstRTSPSrc * src)
7021 {
7022   GstTask *task;
7023
7024   GST_DEBUG_OBJECT (src, "stopping");
7025
7026   /* also cancels pending task */
7027   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
7028
7029   GST_OBJECT_LOCK (src);
7030   if ((task = src->task)) {
7031     src->task = NULL;
7032     GST_OBJECT_UNLOCK (src);
7033
7034     gst_task_stop (task);
7035
7036     /* make sure it is not running */
7037     GST_RTSP_STREAM_LOCK (src);
7038     GST_RTSP_STREAM_UNLOCK (src);
7039
7040     /* now wait for the task to finish */
7041     gst_task_join (task);
7042
7043     /* and free the task */
7044     gst_object_unref (GST_OBJECT (task));
7045
7046     GST_OBJECT_LOCK (src);
7047   }
7048   GST_OBJECT_UNLOCK (src);
7049
7050   /* ensure synchronously all is closed and clean */
7051   gst_rtspsrc_close (src, FALSE, TRUE);
7052
7053   return TRUE;
7054 }
7055
7056 static GstStateChangeReturn
7057 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
7058 {
7059   GstRTSPSrc *rtspsrc;
7060   GstStateChangeReturn ret;
7061
7062   rtspsrc = GST_RTSPSRC (element);
7063
7064   switch (transition) {
7065     case GST_STATE_CHANGE_NULL_TO_READY:
7066       if (!gst_rtspsrc_start (rtspsrc))
7067         goto start_failed;
7068       break;
7069     case GST_STATE_CHANGE_READY_TO_PAUSED:
7070       /* init some state */
7071       rtspsrc->cur_protocols = rtspsrc->protocols;
7072       /* first attempt, don't ignore timeouts */
7073       rtspsrc->ignore_timeout = FALSE;
7074       rtspsrc->open_error = FALSE;
7075       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
7076       break;
7077     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7078     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7079       /* unblock the tcp tasks and make the loop waiting */
7080       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP);
7081       /* make sure it is waiting before we send PAUSE or PLAY below */
7082       GST_RTSP_STREAM_LOCK (rtspsrc);
7083       GST_RTSP_STREAM_UNLOCK (rtspsrc);
7084       break;
7085     case GST_STATE_CHANGE_PAUSED_TO_READY:
7086       break;
7087     default:
7088       break;
7089   }
7090
7091   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7092   if (ret == GST_STATE_CHANGE_FAILURE)
7093     goto done;
7094
7095   switch (transition) {
7096     case GST_STATE_CHANGE_NULL_TO_READY:
7097       ret = GST_STATE_CHANGE_SUCCESS;
7098       break;
7099     case GST_STATE_CHANGE_READY_TO_PAUSED:
7100       ret = GST_STATE_CHANGE_NO_PREROLL;
7101       break;
7102     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7103       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7104       ret = GST_STATE_CHANGE_SUCCESS;
7105       break;
7106     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7107       /* send pause request and keep the idle task around */
7108       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7109       ret = GST_STATE_CHANGE_NO_PREROLL;
7110       break;
7111     case GST_STATE_CHANGE_PAUSED_TO_READY:
7112       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7113       ret = GST_STATE_CHANGE_SUCCESS;
7114       break;
7115     case GST_STATE_CHANGE_READY_TO_NULL:
7116       gst_rtspsrc_stop (rtspsrc);
7117       ret = GST_STATE_CHANGE_SUCCESS;
7118       break;
7119     default:
7120       break;
7121   }
7122
7123 done:
7124   return ret;
7125
7126 start_failed:
7127   {
7128     GST_DEBUG_OBJECT (rtspsrc, "start failed");
7129     return GST_STATE_CHANGE_FAILURE;
7130   }
7131 }
7132
7133 static gboolean
7134 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7135 {
7136   gboolean res;
7137   GstRTSPSrc *rtspsrc;
7138
7139   rtspsrc = GST_RTSPSRC (element);
7140
7141   if (GST_EVENT_IS_DOWNSTREAM (event)) {
7142     res = gst_rtspsrc_push_event (rtspsrc, event);
7143   } else {
7144     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7145   }
7146
7147   return res;
7148 }
7149
7150
7151 /*** GSTURIHANDLER INTERFACE *************************************************/
7152
7153 static GstURIType
7154 gst_rtspsrc_uri_get_type (GType type)
7155 {
7156   return GST_URI_SRC;
7157 }
7158
7159 static const gchar *const *
7160 gst_rtspsrc_uri_get_protocols (GType type)
7161 {
7162   static const gchar *protocols[] =
7163       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7164     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7165   };
7166
7167   return protocols;
7168 }
7169
7170 static gchar *
7171 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7172 {
7173   GstRTSPSrc *src = GST_RTSPSRC (handler);
7174
7175   /* FIXME: make thread-safe */
7176   return g_strdup (src->conninfo.location);
7177 }
7178
7179 static gboolean
7180 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7181     GError ** error)
7182 {
7183   GstRTSPSrc *src;
7184   GstRTSPResult res;
7185   GstRTSPUrl *newurl = NULL;
7186   GstSDPMessage *sdp = NULL;
7187
7188   src = GST_RTSPSRC (handler);
7189
7190   /* same URI, we're fine */
7191   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7192     goto was_ok;
7193
7194   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7195     if ((res = gst_sdp_message_new (&sdp) < 0))
7196       goto sdp_failed;
7197
7198     GST_DEBUG_OBJECT (src, "parsing SDP message");
7199     if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7200       goto invalid_sdp;
7201   } else {
7202     /* try to parse */
7203     GST_DEBUG_OBJECT (src, "parsing URI");
7204     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7205       goto parse_error;
7206   }
7207
7208   /* if worked, free previous and store new url object along with the original
7209    * location. */
7210   GST_DEBUG_OBJECT (src, "configuring URI");
7211   g_free (src->conninfo.location);
7212   src->conninfo.location = g_strdup (uri);
7213   gst_rtsp_url_free (src->conninfo.url);
7214   src->conninfo.url = newurl;
7215   g_free (src->conninfo.url_str);
7216   if (newurl)
7217     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7218   else
7219     src->conninfo.url_str = NULL;
7220
7221   if (src->sdp)
7222     gst_sdp_message_free (src->sdp);
7223   src->sdp = sdp;
7224   src->from_sdp = sdp != NULL;
7225
7226   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7227   GST_DEBUG_OBJECT (src, "request uri is: %s",
7228       GST_STR_NULL (src->conninfo.url_str));
7229
7230   return TRUE;
7231
7232   /* Special cases */
7233 was_ok:
7234   {
7235     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7236     return TRUE;
7237   }
7238 sdp_failed:
7239   {
7240     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7241     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7242         "Could not create SDP");
7243     return FALSE;
7244   }
7245 invalid_sdp:
7246   {
7247     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7248         GST_STR_NULL (uri));
7249     gst_sdp_message_free (sdp);
7250     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7251         "Invalid SDP");
7252     return FALSE;
7253   }
7254 parse_error:
7255   {
7256     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7257         GST_STR_NULL (uri), res);
7258     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7259         "Invalid RTSP URI");
7260     return FALSE;
7261   }
7262 }
7263
7264 static void
7265 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7266 {
7267   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7268
7269   iface->get_type = gst_rtspsrc_uri_get_type;
7270   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7271   iface->get_uri = gst_rtspsrc_uri_get_uri;
7272   iface->set_uri = gst_rtspsrc_uri_set_uri;
7273 }