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