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