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