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