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