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