rtspsrc: fix 'make check'
[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   if (src->manager == NULL)
2647     return;
2648
2649   klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2650
2651   if (!g_object_class_find_property (klass, "buffer-mode"))
2652     return;
2653
2654   if (src->buffer_mode != BUFFER_MODE_AUTO) {
2655     g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2656
2657     return;
2658   }
2659
2660   GST_DEBUG_OBJECT (src,
2661       "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
2662
2663   if (src->provided_clock) {
2664     GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
2665
2666     if (clock == src->provided_clock) {
2667       GST_DEBUG_OBJECT (src, "selected synced");
2668       g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
2669
2670       if (clock)
2671         gst_object_unref (clock);
2672
2673       return;
2674     }
2675
2676     /* Otherwise fall-through and use another buffer mode */
2677     if (clock)
2678       gst_object_unref (clock);
2679   }
2680
2681   GST_DEBUG_OBJECT (src, "auto buffering mode");
2682   if (src->use_buffering) {
2683     GST_DEBUG_OBJECT (src, "selected buffer");
2684     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
2685   } else {
2686     GST_DEBUG_OBJECT (src, "selected slave");
2687     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2688   }
2689 }
2690
2691 /* try to get and configure a manager */
2692 static gboolean
2693 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
2694     GstRTSPTransport * transport)
2695 {
2696   const gchar *manager;
2697   gchar *name;
2698   GstStateChangeReturn ret;
2699
2700   /* find a manager */
2701   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
2702     goto no_manager;
2703
2704   if (manager) {
2705     GST_DEBUG_OBJECT (src, "using manager %s", manager);
2706
2707     /* configure the manager */
2708     if (src->manager == NULL) {
2709       GObjectClass *klass;
2710       GstStructure *s;
2711       const gchar *encoding;
2712       gboolean need_slave;
2713
2714       if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
2715         /* fallback */
2716         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
2717           goto no_manager;
2718
2719         if (!manager)
2720           goto use_no_manager;
2721
2722         if (!(src->manager = gst_element_factory_make (manager, "manager")))
2723           goto manager_failed;
2724       }
2725
2726       /* we manage this element */
2727       gst_element_set_locked_state (src->manager, TRUE);
2728       gst_bin_add (GST_BIN_CAST (src), src->manager);
2729
2730       ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
2731       if (ret == GST_STATE_CHANGE_FAILURE)
2732         goto start_manager_failure;
2733
2734       g_object_set (src->manager, "latency", src->latency, NULL);
2735
2736       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2737
2738       if (g_object_class_find_property (klass, "ntp-sync")) {
2739         g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
2740       }
2741
2742       if (g_object_class_find_property (klass, "use-pipeline-clock")) {
2743         g_object_set (src->manager, "use-pipeline-clock",
2744             src->use_pipeline_clock, NULL);
2745       }
2746
2747       if (src->sdes && g_object_class_find_property (klass, "sdes")) {
2748         g_object_set (src->manager, "sdes", src->sdes, NULL);
2749       }
2750
2751       if (g_object_class_find_property (klass, "drop-on-latency")) {
2752         g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
2753             NULL);
2754       }
2755
2756       /* buffer mode pauses are handled by adding offsets to buffer times,
2757        * but some depayloaders may have a hard time syncing output times
2758        * with such input times, e.g. container ones, most notably ASF */
2759       /* TODO alternatives are having an event that indicates these shifts,
2760        * or having rtsp extensions provide suggestion on buffer mode */
2761       need_slave = stream->container;
2762       if (stream->caps && (s = gst_caps_get_structure (stream->caps, 0)) &&
2763           (encoding = gst_structure_get_string (s, "encoding-name")))
2764         need_slave = need_slave || (strcmp (encoding, "X-ASF-PF") == 0);
2765       /* valid duration implies not likely live pipeline,
2766        * so slaving in jitterbuffer does not make much sense
2767        * (and might mess things up due to bursts) */
2768       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
2769           src->segment.duration && !need_slave) {
2770         src->use_buffering = TRUE;
2771       } else {
2772         src->use_buffering = FALSE;
2773       }
2774
2775       set_manager_buffer_mode (src);
2776
2777       /* connect to signals if we did not already do so */
2778       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
2779           stream);
2780       src->manager_sig_id =
2781           g_signal_connect (src->manager, "pad-added",
2782           (GCallback) new_manager_pad, src);
2783       src->manager_ptmap_id =
2784           g_signal_connect (src->manager, "request-pt-map",
2785           (GCallback) request_pt_map, src);
2786
2787       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
2788           src);
2789     }
2790
2791     /* we stream directly to the manager, get some pads. Each RTSP stream goes
2792      * into a separate RTP session. */
2793     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
2794     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
2795     g_free (name);
2796     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
2797     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
2798     g_free (name);
2799
2800     /* now configure the bandwidth in the manager */
2801     if (g_signal_lookup ("get-internal-session",
2802             G_OBJECT_TYPE (src->manager)) != 0) {
2803       GObject *rtpsession;
2804
2805       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
2806           &rtpsession);
2807       if (rtpsession) {
2808         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
2809
2810         stream->session = rtpsession;
2811
2812         if (stream->as_bandwidth != -1) {
2813           GST_INFO_OBJECT (src, "setting AS: %f",
2814               (gdouble) (stream->as_bandwidth * 1000));
2815           g_object_set (rtpsession, "bandwidth",
2816               (gdouble) (stream->as_bandwidth * 1000), NULL);
2817         }
2818         if (stream->rr_bandwidth != -1) {
2819           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
2820           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
2821               NULL);
2822         }
2823         if (stream->rs_bandwidth != -1) {
2824           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
2825           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
2826               NULL);
2827         }
2828
2829         g_object_set (rtpsession, "probation", src->probation, NULL);
2830
2831         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
2832             stream);
2833         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
2834             stream);
2835         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
2836             stream);
2837         g_signal_connect (rtpsession, "on-ssrc-active",
2838             (GCallback) on_ssrc_active, stream);
2839       }
2840     }
2841   }
2842
2843 use_no_manager:
2844   return TRUE;
2845
2846   /* ERRORS */
2847 no_manager:
2848   {
2849     GST_DEBUG_OBJECT (src, "cannot get a session manager");
2850     return FALSE;
2851   }
2852 manager_failed:
2853   {
2854     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
2855     return FALSE;
2856   }
2857 start_manager_failure:
2858   {
2859     GST_DEBUG_OBJECT (src, "could not start session manager");
2860     return FALSE;
2861   }
2862 }
2863
2864 /* free the UDP sources allocated when negotiating a transport.
2865  * This function is called when the server negotiated to a transport where the
2866  * UDP sources are not needed anymore, such as TCP or multicast. */
2867 static void
2868 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
2869 {
2870   gint i;
2871
2872   for (i = 0; i < 2; i++) {
2873     if (stream->udpsrc[i]) {
2874       GST_DEBUG ("free UDP source %d for stream %p", i, stream);
2875       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
2876       gst_object_unref (stream->udpsrc[i]);
2877       stream->udpsrc[i] = NULL;
2878     }
2879   }
2880 }
2881
2882 /* for TCP, create pads to send and receive data to and from the manager and to
2883  * intercept various events and queries
2884  */
2885 static gboolean
2886 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
2887     GstRTSPTransport * transport, GstPad ** outpad)
2888 {
2889   gchar *name;
2890   GstPadTemplate *template;
2891   GstPad *pad0, *pad1;
2892
2893   /* configure for interleaved delivery, nothing needs to be done
2894    * here, the loop function will call the chain functions of the
2895    * session manager. */
2896   stream->channel[0] = transport->interleaved.min;
2897   stream->channel[1] = transport->interleaved.max;
2898   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
2899       stream->channel[0], stream->channel[1]);
2900
2901   /* we can remove the allocated UDP ports now */
2902   gst_rtspsrc_stream_free_udp (stream);
2903
2904   /* no session manager, send data to srcpad directly */
2905   if (!stream->channelpad[0]) {
2906     GST_DEBUG_OBJECT (src, "no manager, creating pad");
2907
2908     /* create a new pad we will use to stream to */
2909     name = g_strdup_printf ("stream_%u", stream->id);
2910     template = gst_static_pad_template_get (&rtptemplate);
2911     stream->channelpad[0] = gst_pad_new_from_template (template, name);
2912     gst_object_unref (template);
2913     g_free (name);
2914
2915     /* set caps and activate */
2916     gst_pad_use_fixed_caps (stream->channelpad[0]);
2917     gst_pad_set_active (stream->channelpad[0], TRUE);
2918
2919     *outpad = gst_object_ref (stream->channelpad[0]);
2920   } else {
2921     GST_DEBUG_OBJECT (src, "using manager source pad");
2922
2923     template = gst_static_pad_template_get (&anysrctemplate);
2924
2925     /* allocate pads for sending the channel data into the manager */
2926     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
2927     gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
2928     gst_object_unref (stream->channelpad[0]);
2929     stream->channelpad[0] = pad0;
2930     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
2931     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
2932     gst_pad_set_element_private (pad0, src);
2933     gst_pad_set_active (pad0, TRUE);
2934
2935     if (stream->channelpad[1]) {
2936       /* if we have a sinkpad for the other channel, create a pad and link to the
2937        * manager. */
2938       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
2939       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
2940       gst_pad_link_full (pad1, stream->channelpad[1],
2941           GST_PAD_LINK_CHECK_NOTHING);
2942       gst_object_unref (stream->channelpad[1]);
2943       stream->channelpad[1] = pad1;
2944       gst_pad_set_active (pad1, TRUE);
2945     }
2946     gst_object_unref (template);
2947   }
2948   /* setup RTCP transport back to the server if we have to. */
2949   if (src->manager && src->do_rtcp) {
2950     GstPad *pad;
2951
2952     template = gst_static_pad_template_get (&anysinktemplate);
2953
2954     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
2955     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
2956     gst_pad_set_element_private (stream->rtcppad, stream);
2957     gst_pad_set_active (stream->rtcppad, TRUE);
2958
2959     /* get session RTCP pad */
2960     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2961     pad = gst_element_get_request_pad (src->manager, name);
2962     g_free (name);
2963
2964     /* and link */
2965     if (pad) {
2966       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
2967       gst_object_unref (pad);
2968     }
2969
2970     gst_object_unref (template);
2971   }
2972   return TRUE;
2973 }
2974
2975 static void
2976 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
2977     GstRTSPTransport * transport, const gchar ** destination, gint * min,
2978     gint * max, guint * ttl)
2979 {
2980   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
2981     if (destination) {
2982       if (!(*destination = transport->destination))
2983         *destination = stream->destination;
2984     }
2985     if (min && max) {
2986       /* transport first */
2987       *min = transport->port.min;
2988       *max = transport->port.max;
2989       if (*min == -1 && *max == -1) {
2990         /* then try from SDP */
2991         if (stream->port != 0) {
2992           *min = stream->port;
2993           *max = stream->port + 1;
2994         }
2995       }
2996     }
2997
2998     if (ttl) {
2999       if (!(*ttl = transport->ttl))
3000         *ttl = stream->ttl;
3001     }
3002   } else {
3003     if (destination) {
3004       /* first take the source, then the endpoint to figure out where to send
3005        * the RTCP. */
3006       if (!(*destination = transport->source)) {
3007         if (src->conninfo.connection)
3008           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3009         else if (stream->conninfo.connection)
3010           *destination =
3011               gst_rtsp_connection_get_ip (stream->conninfo.connection);
3012       }
3013     }
3014     if (min && max) {
3015       /* for unicast we only expect the ports here */
3016       *min = transport->server_port.min;
3017       *max = transport->server_port.max;
3018     }
3019   }
3020 }
3021
3022 /* For multicast create UDP sources and join the multicast group. */
3023 static gboolean
3024 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3025     GstRTSPTransport * transport, GstPad ** outpad)
3026 {
3027   gchar *uri;
3028   const gchar *destination;
3029   gint min, max;
3030
3031   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3032
3033   /* we can remove the allocated UDP ports now */
3034   gst_rtspsrc_stream_free_udp (stream);
3035
3036   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3037       &max, NULL);
3038
3039   /* we need a destination now */
3040   if (destination == NULL)
3041     goto no_destination;
3042
3043   /* we really need ports now or we won't be able to receive anything at all */
3044   if (min == -1 && max == -1)
3045     goto no_ports;
3046
3047   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3048       destination, min, max);
3049
3050   /* creating UDP source for RTP */
3051   if (min != -1) {
3052     uri = g_strdup_printf ("udp://%s:%d", destination, min);
3053     stream->udpsrc[0] =
3054         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3055     g_free (uri);
3056     if (stream->udpsrc[0] == NULL)
3057       goto no_element;
3058
3059     /* take ownership */
3060     gst_object_ref_sink (stream->udpsrc[0]);
3061
3062     if (src->udp_buffer_size != 0)
3063       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3064           src->udp_buffer_size, NULL);
3065
3066     if (src->multi_iface != NULL)
3067       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3068           src->multi_iface, NULL);
3069
3070     /* change state */
3071     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3072     gst_element_set_state (stream->udpsrc[0], GST_STATE_PAUSED);
3073   }
3074
3075   /* creating another UDP source for RTCP */
3076   if (max != -1) {
3077     GstCaps *caps;
3078
3079     uri = g_strdup_printf ("udp://%s:%d", destination, max);
3080     stream->udpsrc[1] =
3081         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3082     g_free (uri);
3083     if (stream->udpsrc[1] == NULL)
3084       goto no_element;
3085
3086     caps = gst_caps_new_empty_simple ("application/x-rtcp");
3087     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3088     gst_caps_unref (caps);
3089
3090     /* take ownership */
3091     gst_object_ref_sink (stream->udpsrc[1]);
3092
3093     if (src->multi_iface != NULL)
3094       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3095           src->multi_iface, NULL);
3096
3097     gst_element_set_state (stream->udpsrc[1], GST_STATE_PAUSED);
3098   }
3099   return TRUE;
3100
3101   /* ERRORS */
3102 no_element:
3103   {
3104     GST_DEBUG_OBJECT (src, "no UDP source element found");
3105     return FALSE;
3106   }
3107 no_destination:
3108   {
3109     GST_DEBUG_OBJECT (src, "no destination found");
3110     return FALSE;
3111   }
3112 no_ports:
3113   {
3114     GST_DEBUG_OBJECT (src, "no ports found");
3115     return FALSE;
3116   }
3117 }
3118
3119 /* configure the remainder of the UDP ports */
3120 static gboolean
3121 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3122     GstRTSPTransport * transport, GstPad ** outpad)
3123 {
3124   /* we manage the UDP elements now. For unicast, the UDP sources where
3125    * allocated in the stream when we suggested a transport. */
3126   if (stream->udpsrc[0]) {
3127     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3128     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3129
3130     GST_DEBUG_OBJECT (src, "setting up UDP source");
3131
3132     /* configure a timeout on the UDP port. When the timeout message is
3133      * posted, we assume UDP transport is not possible. We reconnect using TCP
3134      * if we can. */
3135     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3136         src->udp_timeout * 1000, NULL);
3137
3138     /* get output pad of the UDP source. */
3139     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3140
3141     /* save it so we can unblock */
3142     stream->blockedpad = *outpad;
3143
3144     /* configure pad block on the pad. As soon as there is dataflow on the
3145      * UDP source, we know that UDP is not blocked by a firewall and we can
3146      * configure all the streams to let the application autoplug decoders. */
3147     stream->blockid =
3148         gst_pad_add_probe (stream->blockedpad,
3149         GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked, src, NULL);
3150
3151     if (stream->channelpad[0]) {
3152       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3153       /* configure for UDP delivery, we need to connect the UDP pads to
3154        * the session plugin. */
3155       gst_pad_link_full (*outpad, stream->channelpad[0],
3156           GST_PAD_LINK_CHECK_NOTHING);
3157       gst_object_unref (*outpad);
3158       *outpad = NULL;
3159       /* we connected to pad-added signal to get pads from the manager */
3160     } else {
3161       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3162     }
3163   }
3164
3165   /* RTCP port */
3166   if (stream->udpsrc[1]) {
3167     GstCaps *caps;
3168
3169     gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3170     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3171
3172     caps = gst_caps_new_empty_simple ("application/x-rtcp");
3173     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3174     gst_caps_unref (caps);
3175
3176     if (stream->channelpad[1]) {
3177       GstPad *pad;
3178
3179       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3180
3181       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3182       gst_pad_link_full (pad, stream->channelpad[1],
3183           GST_PAD_LINK_CHECK_NOTHING);
3184       gst_object_unref (pad);
3185     } else {
3186       /* leave unlinked */
3187     }
3188   }
3189   return TRUE;
3190 }
3191
3192 /* configure the UDP sink back to the server for status reports */
3193 static gboolean
3194 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3195     GstRTSPStream * stream, GstRTSPTransport * transport)
3196 {
3197   GstPad *pad;
3198   gint rtp_port, rtcp_port;
3199   gboolean do_rtp, do_rtcp;
3200   const gchar *destination;
3201   gchar *uri, *name;
3202   guint ttl = 0;
3203   GSocket *socket;
3204
3205   /* get transport info */
3206   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3207       &rtp_port, &rtcp_port, &ttl);
3208
3209   /* see what we need to do */
3210   do_rtp = (rtp_port != -1);
3211   /* it's possible that the server does not want us to send RTCP in which case
3212    * the port is -1 */
3213   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3214
3215   /* we need a destination when we have RTP or RTCP ports */
3216   if (destination == NULL && (do_rtp || do_rtcp))
3217     goto no_destination;
3218
3219   /* try to construct the fakesrc to the RTP port of the server to open up any
3220    * NAT firewalls */
3221   if (do_rtp) {
3222     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3223         rtp_port);
3224
3225     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3226     stream->udpsink[0] =
3227         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3228     g_free (uri);
3229     if (stream->udpsink[0] == NULL)
3230       goto no_sink_element;
3231
3232     /* don't join multicast group, we will have the source socket do that */
3233     /* no sync or async state changes needed */
3234     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3235         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3236     if (ttl > 0)
3237       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3238
3239     if (stream->udpsrc[0]) {
3240       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3241        * so that NAT firewalls will open a hole for us */
3242       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3243       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3244       /* configure socket and make sure udpsink does not close it when shutting
3245        * down, it belongs to udpsrc after all. */
3246       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3247           "close-socket", FALSE, NULL);
3248       g_object_unref (socket);
3249     }
3250
3251     /* the source for the dummy packets to open up NAT */
3252     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3253     if (stream->fakesrc == NULL)
3254       goto no_fakesrc_element;
3255
3256     /* random data in 5 buffers, a size of 200 bytes should be fine */
3257     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3258         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3259
3260     /* we don't want to consider this a sink */
3261     GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
3262
3263     /* keep everything locked */
3264     gst_element_set_locked_state (stream->udpsink[0], TRUE);
3265     gst_element_set_locked_state (stream->fakesrc, TRUE);
3266
3267     gst_object_ref (stream->udpsink[0]);
3268     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3269     gst_object_ref (stream->fakesrc);
3270     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3271
3272     gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
3273         "sink", GST_PAD_LINK_CHECK_NOTHING);
3274   }
3275   if (do_rtcp) {
3276     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3277         rtcp_port);
3278
3279     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3280     stream->udpsink[1] =
3281         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3282     g_free (uri);
3283     if (stream->udpsink[1] == NULL)
3284       goto no_sink_element;
3285
3286     /* don't join multicast group, we will have the source socket do that */
3287     /* no sync or async state changes needed */
3288     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3289         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3290     if (ttl > 0)
3291       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3292
3293     if (stream->udpsrc[1]) {
3294       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3295        * because some servers check the port number of where it sends RTCP to identify
3296        * the RTCP packets it receives */
3297       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3298       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3299       /* configure socket and make sure udpsink does not close it when shutting
3300        * down, it belongs to udpsrc after all. */
3301       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3302           "close-socket", FALSE, NULL);
3303       g_object_unref (socket);
3304     }
3305
3306     /* we don't want to consider this a sink */
3307     GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
3308
3309     /* we keep this playing always */
3310     gst_element_set_locked_state (stream->udpsink[1], TRUE);
3311     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3312
3313     gst_object_ref (stream->udpsink[1]);
3314     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3315
3316     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3317
3318     /* get session RTCP pad */
3319     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3320     pad = gst_element_get_request_pad (src->manager, name);
3321     g_free (name);
3322
3323     /* and link */
3324     if (pad) {
3325       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3326       gst_object_unref (pad);
3327     }
3328   }
3329
3330   return TRUE;
3331
3332   /* ERRORS */
3333 no_destination:
3334   {
3335     GST_DEBUG_OBJECT (src, "no destination address specified");
3336     return FALSE;
3337   }
3338 no_sink_element:
3339   {
3340     GST_DEBUG_OBJECT (src, "no UDP sink element found");
3341     return FALSE;
3342   }
3343 no_fakesrc_element:
3344   {
3345     GST_DEBUG_OBJECT (src, "no fakesrc element found");
3346     return FALSE;
3347   }
3348 }
3349
3350 /* sets up all elements needed for streaming over the specified transport.
3351  * Does not yet expose the element pads, this will be done when there is actuall
3352  * dataflow detected, which might never happen when UDP is blocked in a
3353  * firewall, for example.
3354  */
3355 static gboolean
3356 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3357     GstRTSPTransport * transport)
3358 {
3359   GstRTSPSrc *src;
3360   GstPad *outpad = NULL;
3361   GstPadTemplate *template;
3362   gchar *name;
3363   GstStructure *s;
3364   const gchar *mime;
3365
3366   src = stream->parent;
3367
3368   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3369
3370   s = gst_caps_get_structure (stream->caps, 0);
3371
3372   /* get the proper mime type for this stream now */
3373   if (gst_rtsp_transport_get_mime (transport->trans, &mime) < 0)
3374     goto unknown_transport;
3375   if (!mime)
3376     goto unknown_transport;
3377
3378   /* configure the final mime type */
3379   GST_DEBUG_OBJECT (src, "setting mime to %s", mime);
3380   gst_structure_set_name (s, mime);
3381
3382   /* try to get and configure a manager, channelpad[0-1] will be configured with
3383    * the pads for the manager, or NULL when no manager is needed. */
3384   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3385     goto no_manager;
3386
3387   switch (transport->lower_transport) {
3388     case GST_RTSP_LOWER_TRANS_TCP:
3389       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3390         goto transport_failed;
3391       break;
3392     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3393       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3394         goto transport_failed;
3395       /* fallthrough, the rest is the same for UDP and MCAST */
3396     case GST_RTSP_LOWER_TRANS_UDP:
3397       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3398         goto transport_failed;
3399       /* configure udpsinks back to the server for RTCP messages and for the
3400        * dummy RTP messages to open NAT. */
3401       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3402         goto transport_failed;
3403       break;
3404     default:
3405       goto unknown_transport;
3406   }
3407
3408   if (outpad) {
3409     GST_DEBUG_OBJECT (src, "creating ghostpad");
3410
3411     gst_pad_use_fixed_caps (outpad);
3412
3413     /* create ghostpad, don't add just yet, this will be done when we activate
3414      * the stream. */
3415     name = g_strdup_printf ("stream_%u", stream->id);
3416     template = gst_static_pad_template_get (&rtptemplate);
3417     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3418     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3419     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3420     gst_object_unref (template);
3421     g_free (name);
3422
3423     gst_object_unref (outpad);
3424   }
3425   /* mark pad as ok */
3426   stream->last_ret = GST_FLOW_OK;
3427
3428   return TRUE;
3429
3430   /* ERRORS */
3431 transport_failed:
3432   {
3433     GST_DEBUG_OBJECT (src, "failed to configure transport");
3434     return FALSE;
3435   }
3436 unknown_transport:
3437   {
3438     GST_DEBUG_OBJECT (src, "unknown transport");
3439     return FALSE;
3440   }
3441 no_manager:
3442   {
3443     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3444     return FALSE;
3445   }
3446 }
3447
3448 /* send a couple of dummy random packets on the receiver RTP port to the server,
3449  * this should make a firewall think we initiated the data transfer and
3450  * hopefully allow packets to go from the sender port to our RTP receiver port */
3451 static gboolean
3452 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3453 {
3454   GList *walk;
3455
3456   if (src->nat_method != GST_RTSP_NAT_DUMMY)
3457     return TRUE;
3458
3459   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3460     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3461
3462     if (stream->fakesrc && stream->udpsink[0]) {
3463       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3464       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3465       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3466       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3467       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3468     }
3469   }
3470   return TRUE;
3471 }
3472
3473 /* Adds the source pads of all configured streams to the element.
3474  * This code is performed when we detected dataflow.
3475  *
3476  * We detect dataflow from either the _loop function or with pad probes on the
3477  * udp sources.
3478  */
3479 static gboolean
3480 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3481 {
3482   GList *walk;
3483
3484   GST_DEBUG_OBJECT (src, "activating streams");
3485
3486   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3487     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3488
3489     if (stream->udpsrc[0]) {
3490       /* remove timeout, we are streaming now and timeouts will be handled by
3491        * the session manager and jitter buffer */
3492       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3493     }
3494     if (stream->srcpad) {
3495       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3496       gst_pad_set_active (stream->srcpad, TRUE);
3497
3498       /* if we don't have a session manager, set the caps now. If we have a
3499        * session, we will get a notification of the pad and the caps. */
3500       if (!src->manager) {
3501         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3502         gst_pad_set_caps (stream->srcpad, stream->caps);
3503       }
3504       /* add the pad */
3505       if (!stream->added) {
3506         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3507         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3508         stream->added = TRUE;
3509       }
3510     }
3511   }
3512
3513   /* unblock all pads */
3514   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3515     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3516
3517     if (stream->blockid) {
3518       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3519       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3520       stream->blockid = 0;
3521     }
3522   }
3523
3524   return TRUE;
3525 }
3526
3527 static void
3528 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3529     gboolean reset_manager)
3530 {
3531   GList *walk;
3532   guint64 start, stop;
3533   gdouble play_speed, play_scale;
3534
3535   GST_DEBUG_OBJECT (src, "configuring stream caps");
3536
3537   start = segment->position;
3538   stop = segment->duration;
3539   play_speed = segment->rate;
3540   play_scale = segment->applied_rate;
3541
3542   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3543     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3544     GstCaps *caps;
3545
3546     if ((caps = stream->caps)) {
3547       caps = gst_caps_make_writable (caps);
3548       /* update caps */
3549       if (stream->timebase != -1)
3550         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3551             (guint) stream->timebase, NULL);
3552       if (stream->seqbase != -1)
3553         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3554             (guint) stream->seqbase, NULL);
3555       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3556       if (stop != -1)
3557         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3558       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3559       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3560
3561       stream->caps = caps;
3562     }
3563     GST_DEBUG_OBJECT (src, "stream %p, caps %" GST_PTR_FORMAT, stream, caps);
3564   }
3565   if (reset_manager && src->manager) {
3566     GST_DEBUG_OBJECT (src, "clear session");
3567     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3568   }
3569 }
3570
3571 static GstFlowReturn
3572 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3573     GstFlowReturn ret)
3574 {
3575   GList *streams;
3576
3577   /* store the value */
3578   stream->last_ret = ret;
3579
3580   /* if it's success we can return the value right away */
3581   if (ret == GST_FLOW_OK)
3582     goto done;
3583
3584   /* any other error that is not-linked can be returned right
3585    * away */
3586   if (ret != GST_FLOW_NOT_LINKED)
3587     goto done;
3588
3589   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3590   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3591     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3592
3593     ret = ostream->last_ret;
3594     /* some other return value (must be SUCCESS but we can return
3595      * other values as well) */
3596     if (ret != GST_FLOW_NOT_LINKED)
3597       goto done;
3598   }
3599   /* if we get here, all other pads were unlinked and we return
3600    * NOT_LINKED then */
3601 done:
3602   return ret;
3603 }
3604
3605 static gboolean
3606 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
3607     GstEvent * event)
3608 {
3609   gboolean res = TRUE;
3610
3611   /* only streams that have a connection to the outside world */
3612   if (stream->container || stream->disabled)
3613     goto done;
3614
3615   if (stream->udpsrc[0]) {
3616     gst_event_ref (event);
3617     res = gst_element_send_event (stream->udpsrc[0], event);
3618   } else if (stream->channelpad[0]) {
3619     gst_event_ref (event);
3620     if (GST_PAD_IS_SRC (stream->channelpad[0]))
3621       res = gst_pad_push_event (stream->channelpad[0], event);
3622     else
3623       res = gst_pad_send_event (stream->channelpad[0], event);
3624   }
3625
3626   if (stream->udpsrc[1]) {
3627     gst_event_ref (event);
3628     res &= gst_element_send_event (stream->udpsrc[1], event);
3629   } else if (stream->channelpad[1]) {
3630     gst_event_ref (event);
3631     if (GST_PAD_IS_SRC (stream->channelpad[1]))
3632       res &= gst_pad_push_event (stream->channelpad[1], event);
3633     else
3634       res &= gst_pad_send_event (stream->channelpad[1], event);
3635   }
3636
3637 done:
3638   gst_event_unref (event);
3639
3640   return res;
3641 }
3642
3643 static gboolean
3644 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
3645 {
3646   GList *streams;
3647   gboolean res = TRUE;
3648
3649   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3650     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3651
3652     gst_event_ref (event);
3653     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
3654   }
3655   gst_event_unref (event);
3656
3657   return res;
3658 }
3659
3660 static GstRTSPResult
3661 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3662     gboolean async)
3663 {
3664   GstRTSPResult res;
3665
3666   if (info->connection == NULL) {
3667     if (info->url == NULL) {
3668       GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
3669       if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
3670         goto parse_error;
3671     }
3672
3673     /* create connection */
3674     GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
3675     if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
3676       goto could_not_create;
3677
3678     if (info->url_str)
3679       g_free (info->url_str);
3680     info->url_str = gst_rtsp_url_get_request_uri (info->url);
3681
3682     GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
3683
3684     if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
3685       if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
3686               src->tls_validation_flags))
3687         GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
3688     }
3689
3690     if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
3691       gst_rtsp_connection_set_tunneled (info->connection, TRUE);
3692
3693     if (src->proxy_host) {
3694       GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
3695           src->proxy_port);
3696       gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
3697           src->proxy_port);
3698     }
3699   }
3700
3701   if (!info->connected) {
3702     /* connect */
3703     if (async)
3704       GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
3705           ("Connecting to %s", info->location));
3706     GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
3707     if ((res =
3708             gst_rtsp_connection_connect (info->connection,
3709                 src->ptcp_timeout)) < 0)
3710       goto could_not_connect;
3711
3712     info->connected = TRUE;
3713   }
3714   return GST_RTSP_OK;
3715
3716   /* ERRORS */
3717 parse_error:
3718   {
3719     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
3720     return res;
3721   }
3722 could_not_create:
3723   {
3724     gchar *str = gst_rtsp_strresult (res);
3725     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
3726     g_free (str);
3727     return res;
3728   }
3729 could_not_connect:
3730   {
3731     gchar *str = gst_rtsp_strresult (res);
3732     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
3733     g_free (str);
3734     return res;
3735   }
3736 }
3737
3738 static GstRTSPResult
3739 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
3740     gboolean free)
3741 {
3742   GST_RTSP_STATE_LOCK (src);
3743   if (info->connected) {
3744     GST_DEBUG_OBJECT (src, "closing connection...");
3745     gst_rtsp_connection_close (info->connection);
3746     info->connected = FALSE;
3747   }
3748   if (free && info->connection) {
3749     /* free connection */
3750     GST_DEBUG_OBJECT (src, "freeing connection...");
3751     gst_rtsp_connection_free (info->connection);
3752     info->connection = NULL;
3753   }
3754   GST_RTSP_STATE_UNLOCK (src);
3755   return GST_RTSP_OK;
3756 }
3757
3758 static GstRTSPResult
3759 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3760     gboolean async)
3761 {
3762   GstRTSPResult res;
3763
3764   GST_DEBUG_OBJECT (src, "reconnecting connection...");
3765   gst_rtsp_conninfo_close (src, info, FALSE);
3766   res = gst_rtsp_conninfo_connect (src, info, async);
3767
3768   return res;
3769 }
3770
3771 static void
3772 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
3773 {
3774   GList *walk;
3775
3776   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
3777   GST_RTSP_STATE_LOCK (src);
3778   if (src->conninfo.connection && src->conninfo.flushing != flush) {
3779     GST_DEBUG_OBJECT (src, "connection flush");
3780     gst_rtsp_connection_flush (src->conninfo.connection, flush);
3781     src->conninfo.flushing = flush;
3782   }
3783   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3784     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3785     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
3786       GST_DEBUG_OBJECT (src, "stream %p flush", stream);
3787       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
3788       stream->conninfo.flushing = flush;
3789     }
3790   }
3791   GST_RTSP_STATE_UNLOCK (src);
3792 }
3793
3794 /* FIXME, handle server request, reply with OK, for now */
3795 static GstRTSPResult
3796 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
3797     GstRTSPMessage * request)
3798 {
3799   GstRTSPMessage response = { 0 };
3800   GstRTSPResult res;
3801
3802   GST_DEBUG_OBJECT (src, "got server request message");
3803
3804   if (src->debug)
3805     gst_rtsp_message_dump (request);
3806
3807   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
3808
3809   if (res == GST_RTSP_ENOTIMPL) {
3810     /* default implementation, send OK */
3811     GST_DEBUG_OBJECT (src, "prepare OK reply");
3812     res =
3813         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
3814         request);
3815     if (res < 0)
3816       goto send_error;
3817
3818     /* let app parse and reply */
3819     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
3820         0, request, &response);
3821
3822     if (src->debug)
3823       gst_rtsp_message_dump (&response);
3824
3825     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
3826     if (res < 0)
3827       goto send_error;
3828
3829     gst_rtsp_message_unset (&response);
3830   } else if (res == GST_RTSP_EEOF)
3831     return res;
3832
3833   return GST_RTSP_OK;
3834
3835   /* ERRORS */
3836 send_error:
3837   {
3838     gst_rtsp_message_unset (&response);
3839     return res;
3840   }
3841 }
3842
3843 /* send server keep-alive */
3844 static GstRTSPResult
3845 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
3846 {
3847   GstRTSPMessage request = { 0 };
3848   GstRTSPResult res;
3849   GstRTSPMethod method;
3850   gchar *control;
3851
3852   if (src->do_rtsp_keep_alive == FALSE) {
3853     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
3854     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3855     return GST_RTSP_OK;
3856   }
3857
3858   GST_DEBUG_OBJECT (src, "creating server keep-alive");
3859
3860   /* find a method to use for keep-alive */
3861   if (src->methods & GST_RTSP_GET_PARAMETER)
3862     method = GST_RTSP_GET_PARAMETER;
3863   else
3864     method = GST_RTSP_OPTIONS;
3865
3866   if (src->control)
3867     control = src->control;
3868   else
3869     control = src->conninfo.url_str;
3870
3871   if (control == NULL)
3872     goto no_control;
3873
3874   res = gst_rtsp_message_init_request (&request, method, control);
3875   if (res < 0)
3876     goto send_error;
3877
3878   if (src->debug)
3879     gst_rtsp_message_dump (&request);
3880
3881   res =
3882       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
3883       NULL);
3884   if (res < 0)
3885     goto send_error;
3886
3887   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3888   gst_rtsp_message_unset (&request);
3889
3890   return GST_RTSP_OK;
3891
3892   /* ERRORS */
3893 no_control:
3894   {
3895     GST_WARNING_OBJECT (src, "no control url to send keepalive");
3896     return GST_RTSP_OK;
3897   }
3898 send_error:
3899   {
3900     gchar *str = gst_rtsp_strresult (res);
3901
3902     gst_rtsp_message_unset (&request);
3903     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
3904         ("Could not send keep-alive. (%s)", str));
3905     g_free (str);
3906     return res;
3907   }
3908 }
3909
3910 static GstFlowReturn
3911 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
3912 {
3913   GstFlowReturn ret = GST_FLOW_OK;
3914   gint channel;
3915   GstRTSPStream *stream;
3916   GstPad *outpad = NULL;
3917   guint8 *data;
3918   guint size;
3919   GstBuffer *buf;
3920   gboolean is_rtcp;
3921   GstEvent *event;
3922
3923   channel = message->type_data.data.channel;
3924
3925   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
3926   if (!stream)
3927     goto unknown_stream;
3928
3929   if (channel == stream->channel[0]) {
3930     outpad = stream->channelpad[0];
3931     is_rtcp = FALSE;
3932   } else if (channel == stream->channel[1]) {
3933     outpad = stream->channelpad[1];
3934     is_rtcp = TRUE;
3935   } else {
3936     is_rtcp = FALSE;
3937   }
3938
3939   /* take a look at the body to figure out what we have */
3940   gst_rtsp_message_get_body (message, &data, &size);
3941   if (size < 2)
3942     goto invalid_length;
3943
3944   /* channels are not correct on some servers, do extra check */
3945   if (data[1] >= 200 && data[1] <= 204) {
3946     /* hmm RTCP message switch to the RTCP pad of the same stream. */
3947     outpad = stream->channelpad[1];
3948     is_rtcp = TRUE;
3949   }
3950
3951   /* we have no clue what this is, just ignore then. */
3952   if (outpad == NULL)
3953     goto unknown_stream;
3954
3955   /* take the message body for further processing */
3956   gst_rtsp_message_steal_body (message, &data, &size);
3957
3958   /* strip the trailing \0 */
3959   size -= 1;
3960
3961   buf = gst_buffer_new ();
3962   gst_buffer_append_memory (buf,
3963       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
3964
3965   /* don't need message anymore */
3966   gst_rtsp_message_unset (message);
3967
3968   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
3969       channel);
3970
3971   if (src->need_activate) {
3972     gchar *stream_id;
3973     GstEvent *event;
3974     GChecksum *cs;
3975     gchar *uri;
3976     GList *streams;
3977     guint group_id = gst_util_group_id_next ();
3978
3979     /* generate an SHA256 sum of the URI */
3980     cs = g_checksum_new (G_CHECKSUM_SHA256);
3981     uri = src->conninfo.location;
3982     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
3983
3984     for (streams = src->streams; streams; streams = g_list_next (streams)) {
3985       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3986
3987       stream_id =
3988           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
3989       event = gst_event_new_stream_start (stream_id);
3990       gst_event_set_group_id (event, group_id);
3991
3992       g_free (stream_id);
3993       gst_rtspsrc_stream_push_event (src, ostream, event);
3994     }
3995     g_checksum_free (cs);
3996
3997     gst_rtspsrc_activate_streams (src);
3998     src->need_activate = FALSE;
3999   }
4000   if ((event = src->start_segment) != NULL) {
4001     src->start_segment = NULL;
4002     gst_rtspsrc_push_event (src, event);
4003   }
4004
4005   if (src->base_time == -1) {
4006     /* Take current running_time. This timestamp will be put on
4007      * the first buffer of each stream because we are a live source and so we
4008      * timestamp with the running_time. When we are dealing with TCP, we also
4009      * only timestamp the first buffer (using the DISCONT flag) because a server
4010      * typically bursts data, for which we don't want to compensate by speeding
4011      * up the media. The other timestamps will be interpollated from this one
4012      * using the RTP timestamps. */
4013     GST_OBJECT_LOCK (src);
4014     if (GST_ELEMENT_CLOCK (src)) {
4015       GstClockTime now;
4016       GstClockTime base_time;
4017
4018       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4019       base_time = GST_ELEMENT_CAST (src)->base_time;
4020
4021       src->base_time = now - base_time;
4022
4023       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4024           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4025     }
4026     GST_OBJECT_UNLOCK (src);
4027   }
4028
4029   if (stream->discont && !is_rtcp) {
4030     /* mark first RTP buffer as discont */
4031     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4032     stream->discont = FALSE;
4033     /* first buffer gets the timestamp, other buffers are not timestamped and
4034      * their presentation time will be interpollated from the rtp timestamps. */
4035     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4036         GST_TIME_ARGS (src->base_time));
4037
4038     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4039   }
4040
4041   /* chain to the peer pad */
4042   if (GST_PAD_IS_SINK (outpad))
4043     ret = gst_pad_chain (outpad, buf);
4044   else
4045     ret = gst_pad_push (outpad, buf);
4046
4047   if (!is_rtcp) {
4048     /* combine all stream flows for the data transport */
4049     ret = gst_rtspsrc_combine_flows (src, stream, ret);
4050   }
4051   return ret;
4052
4053   /* ERRORS */
4054 unknown_stream:
4055   {
4056     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4057     gst_rtsp_message_unset (message);
4058     return GST_FLOW_OK;
4059   }
4060 invalid_length:
4061   {
4062     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4063         ("Short message received, ignoring."));
4064     gst_rtsp_message_unset (message);
4065     return GST_FLOW_OK;
4066   }
4067 }
4068
4069 static GstFlowReturn
4070 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4071 {
4072   GstRTSPMessage message = { 0 };
4073   GstRTSPResult res;
4074   GstFlowReturn ret = GST_FLOW_OK;
4075   GTimeVal tv_timeout;
4076
4077   while (TRUE) {
4078     /* get the next timeout interval */
4079     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4080
4081     /* see if the timeout period expired */
4082     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4083       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4084       /* send keep-alive, only act on interrupt, a warning will be posted for
4085        * other errors. */
4086       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4087         goto interrupt;
4088       /* get new timeout */
4089       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4090     }
4091
4092     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4093         tv_timeout.tv_sec, tv_timeout.tv_usec);
4094
4095     /* protect the connection with the connection lock so that we can see when
4096      * we are finished doing server communication */
4097     res =
4098         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4099         &message, src->ptcp_timeout);
4100
4101     switch (res) {
4102       case GST_RTSP_OK:
4103         GST_DEBUG_OBJECT (src, "we received a server message");
4104         break;
4105       case GST_RTSP_EINTR:
4106         /* we got interrupted this means we need to stop */
4107         goto interrupt;
4108       case GST_RTSP_ETIMEOUT:
4109         /* no reply, send keep alive */
4110         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4111         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4112           goto interrupt;
4113         continue;
4114       case GST_RTSP_EEOF:
4115         /* go EOS when the server closed the connection */
4116         goto server_eof;
4117       default:
4118         goto receive_error;
4119     }
4120
4121     switch (message.type) {
4122       case GST_RTSP_MESSAGE_REQUEST:
4123         /* server sends us a request message, handle it */
4124         res =
4125             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4126             &message);
4127         if (res == GST_RTSP_EEOF)
4128           goto server_eof;
4129         else if (res < 0)
4130           goto handle_request_failed;
4131         break;
4132       case GST_RTSP_MESSAGE_RESPONSE:
4133         /* we ignore response messages */
4134         GST_DEBUG_OBJECT (src, "ignoring response message");
4135         if (src->debug)
4136           gst_rtsp_message_dump (&message);
4137         break;
4138       case GST_RTSP_MESSAGE_DATA:
4139         GST_DEBUG_OBJECT (src, "got data message");
4140         ret = gst_rtspsrc_handle_data (src, &message);
4141         if (ret != GST_FLOW_OK)
4142           goto handle_data_failed;
4143         break;
4144       default:
4145         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4146             message.type);
4147         break;
4148     }
4149   }
4150   g_assert_not_reached ();
4151
4152   /* ERRORS */
4153 server_eof:
4154   {
4155     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4156     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4157         ("The server closed the connection."));
4158     src->conninfo.connected = FALSE;
4159     gst_rtsp_message_unset (&message);
4160     return GST_FLOW_EOS;
4161   }
4162 interrupt:
4163   {
4164     gst_rtsp_message_unset (&message);
4165     GST_DEBUG_OBJECT (src, "got interrupted");
4166     return GST_FLOW_FLUSHING;
4167   }
4168 receive_error:
4169   {
4170     gchar *str = gst_rtsp_strresult (res);
4171
4172     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4173         ("Could not receive message. (%s)", str));
4174     g_free (str);
4175
4176     gst_rtsp_message_unset (&message);
4177     return GST_FLOW_ERROR;
4178   }
4179 handle_request_failed:
4180   {
4181     gchar *str = gst_rtsp_strresult (res);
4182
4183     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4184         ("Could not handle server message. (%s)", str));
4185     g_free (str);
4186     gst_rtsp_message_unset (&message);
4187     return GST_FLOW_ERROR;
4188   }
4189 handle_data_failed:
4190   {
4191     GST_DEBUG_OBJECT (src, "could no handle data message");
4192     return ret;
4193   }
4194 }
4195
4196 static GstFlowReturn
4197 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4198 {
4199   GstRTSPResult res;
4200   GstRTSPMessage message = { 0 };
4201   gint retry = 0;
4202
4203   while (TRUE) {
4204     GTimeVal tv_timeout;
4205
4206     /* get the next timeout interval */
4207     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4208
4209     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4210         (gint) tv_timeout.tv_sec);
4211
4212     gst_rtsp_message_unset (&message);
4213
4214     /* we should continue reading the TCP socket because the server might
4215      * send us requests. When the session timeout expires, we need to send a
4216      * keep-alive request to keep the session open. */
4217     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4218         &message, &tv_timeout);
4219
4220     switch (res) {
4221       case GST_RTSP_OK:
4222         GST_DEBUG_OBJECT (src, "we received a server message");
4223         break;
4224       case GST_RTSP_EINTR:
4225         /* we got interrupted, see what we have to do */
4226         goto interrupt;
4227       case GST_RTSP_ETIMEOUT:
4228         /* send keep-alive, ignore the result, a warning will be posted. */
4229         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4230         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4231           goto interrupt;
4232         continue;
4233       case GST_RTSP_EEOF:
4234         /* server closed the connection. not very fatal for UDP, reconnect and
4235          * see what happens. */
4236         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4237             ("The server closed the connection."));
4238         if (src->udp_reconnect) {
4239           if ((res =
4240                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4241             goto connect_error;
4242         } else {
4243           goto server_eof;
4244         }
4245         continue;
4246       case GST_RTSP_ENET:
4247         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4248       default:
4249         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4250             ("Unhandled return value %d.", res));
4251         goto receive_error;
4252     }
4253
4254     switch (message.type) {
4255       case GST_RTSP_MESSAGE_REQUEST:
4256         /* server sends us a request message, handle it */
4257         res =
4258             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4259             &message);
4260         if (res == GST_RTSP_EEOF)
4261           goto server_eof;
4262         else if (res < 0)
4263           goto handle_request_failed;
4264         break;
4265       case GST_RTSP_MESSAGE_RESPONSE:
4266         /* we ignore response and data messages */
4267         GST_DEBUG_OBJECT (src, "ignoring response message");
4268         if (src->debug)
4269           gst_rtsp_message_dump (&message);
4270         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4271           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4272           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4273             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4274             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4275               goto interrupt;
4276           }
4277         } else {
4278           retry = 0;
4279         }
4280         break;
4281       case GST_RTSP_MESSAGE_DATA:
4282         /* we ignore response and data messages */
4283         GST_DEBUG_OBJECT (src, "ignoring data message");
4284         break;
4285       default:
4286         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4287             message.type);
4288         break;
4289     }
4290   }
4291   g_assert_not_reached ();
4292
4293   /* we get here when the connection got interrupted */
4294 interrupt:
4295   {
4296     gst_rtsp_message_unset (&message);
4297     GST_DEBUG_OBJECT (src, "got interrupted");
4298     return GST_FLOW_FLUSHING;
4299   }
4300 connect_error:
4301   {
4302     gchar *str = gst_rtsp_strresult (res);
4303     GstFlowReturn ret;
4304
4305     src->conninfo.connected = FALSE;
4306     if (res != GST_RTSP_EINTR) {
4307       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4308           ("Could not connect to server. (%s)", str));
4309       g_free (str);
4310       ret = GST_FLOW_ERROR;
4311     } else {
4312       ret = GST_FLOW_FLUSHING;
4313     }
4314     return ret;
4315   }
4316 receive_error:
4317   {
4318     gchar *str = gst_rtsp_strresult (res);
4319
4320     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4321         ("Could not receive message. (%s)", str));
4322     g_free (str);
4323     return GST_FLOW_ERROR;
4324   }
4325 handle_request_failed:
4326   {
4327     gchar *str = gst_rtsp_strresult (res);
4328     GstFlowReturn ret;
4329
4330     gst_rtsp_message_unset (&message);
4331     if (res != GST_RTSP_EINTR) {
4332       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4333           ("Could not handle server message. (%s)", str));
4334       g_free (str);
4335       ret = GST_FLOW_ERROR;
4336     } else {
4337       ret = GST_FLOW_FLUSHING;
4338     }
4339     return ret;
4340   }
4341 server_eof:
4342   {
4343     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4344     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4345         ("The server closed the connection."));
4346     src->conninfo.connected = FALSE;
4347     gst_rtsp_message_unset (&message);
4348     return GST_FLOW_EOS;
4349   }
4350 }
4351
4352 static GstRTSPResult
4353 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4354 {
4355   GstRTSPResult res = GST_RTSP_OK;
4356   gboolean restart;
4357
4358   GST_DEBUG_OBJECT (src, "doing reconnect");
4359
4360   GST_OBJECT_LOCK (src);
4361   /* only restart when the pads were not yet activated, else we were
4362    * streaming over UDP */
4363   restart = src->need_activate;
4364   GST_OBJECT_UNLOCK (src);
4365
4366   /* no need to restart, we're done */
4367   if (!restart)
4368     goto done;
4369
4370   /* we can try only TCP now */
4371   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4372
4373   /* close and cleanup our state */
4374   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4375     goto done;
4376
4377   /* see if we have TCP left to try. Also don't try TCP when we were configured
4378    * with an SDP. */
4379   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4380     goto no_protocols;
4381
4382   /* We post a warning message now to inform the user
4383    * that nothing happened. It's most likely a firewall thing. */
4384   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4385       ("Could not receive any UDP packets for %.4f seconds, maybe your "
4386           "firewall is blocking it. Retrying using a TCP connection.",
4387           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4388
4389   /* open new connection using tcp */
4390   if (gst_rtspsrc_open (src, async) < 0)
4391     goto open_failed;
4392
4393   /* start playback */
4394   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4395     goto play_failed;
4396
4397 done:
4398   return res;
4399
4400   /* ERRORS */
4401 no_protocols:
4402   {
4403     src->cur_protocols = 0;
4404     /* no transport possible, post an error and stop */
4405     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4406         ("Could not receive any UDP packets for %.4f seconds, maybe your "
4407             "firewall is blocking it. No other protocols to try.",
4408             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4409     return GST_RTSP_ERROR;
4410   }
4411 open_failed:
4412   {
4413     GST_DEBUG_OBJECT (src, "open failed");
4414     return GST_RTSP_OK;
4415   }
4416 play_failed:
4417   {
4418     GST_DEBUG_OBJECT (src, "play failed");
4419     return GST_RTSP_OK;
4420   }
4421 }
4422
4423 static void
4424 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4425 {
4426   switch (cmd) {
4427     case CMD_OPEN:
4428       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4429       break;
4430     case CMD_PLAY:
4431       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4432       break;
4433     case CMD_PAUSE:
4434       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4435       break;
4436     case CMD_CLOSE:
4437       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4438       break;
4439     default:
4440       break;
4441   }
4442 }
4443
4444 static void
4445 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4446 {
4447   switch (cmd) {
4448     case CMD_OPEN:
4449       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4450       break;
4451     case CMD_PLAY:
4452       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4453       break;
4454     case CMD_PAUSE:
4455       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4456       break;
4457     case CMD_CLOSE:
4458       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4459       break;
4460     default:
4461       break;
4462   }
4463 }
4464
4465 static void
4466 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4467 {
4468   switch (cmd) {
4469     case CMD_OPEN:
4470       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4471       break;
4472     case CMD_PLAY:
4473       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4474       break;
4475     case CMD_PAUSE:
4476       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4477       break;
4478     case CMD_CLOSE:
4479       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4480       break;
4481     default:
4482       break;
4483   }
4484 }
4485
4486 static void
4487 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4488 {
4489   switch (cmd) {
4490     case CMD_OPEN:
4491       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4492       break;
4493     case CMD_PLAY:
4494       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4495       break;
4496     case CMD_PAUSE:
4497       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4498       break;
4499     case CMD_CLOSE:
4500       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4501       break;
4502     default:
4503       break;
4504   }
4505 }
4506
4507 static void
4508 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4509 {
4510   if (ret == GST_RTSP_OK)
4511     gst_rtspsrc_loop_complete_cmd (src, cmd);
4512   else if (ret == GST_RTSP_EINTR)
4513     gst_rtspsrc_loop_cancel_cmd (src, cmd);
4514   else
4515     gst_rtspsrc_loop_error_cmd (src, cmd);
4516 }
4517
4518 static gboolean
4519 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4520 {
4521   gint old;
4522   gboolean flushed = FALSE;
4523
4524   /* start new request */
4525   gst_rtspsrc_loop_start_cmd (src, cmd);
4526
4527   GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4528
4529   GST_OBJECT_LOCK (src);
4530   old = src->pending_cmd;
4531   if (old == CMD_RECONNECT) {
4532     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4533     cmd = CMD_RECONNECT;
4534   }
4535   if (old != CMD_WAIT) {
4536     src->pending_cmd = CMD_WAIT;
4537     GST_OBJECT_UNLOCK (src);
4538     /* cancel previous request */
4539     GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4540     gst_rtspsrc_loop_cancel_cmd (src, old);
4541     GST_OBJECT_LOCK (src);
4542   }
4543   src->pending_cmd = cmd;
4544   /* interrupt if allowed */
4545   if (src->busy_cmd & mask) {
4546     GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4547     gst_rtspsrc_connection_flush (src, TRUE);
4548     flushed = TRUE;
4549   } else {
4550     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4551   }
4552   if (src->task)
4553     gst_task_start (src->task);
4554   GST_OBJECT_UNLOCK (src);
4555
4556   return flushed;
4557 }
4558
4559 static gboolean
4560 gst_rtspsrc_loop (GstRTSPSrc * src)
4561 {
4562   GstFlowReturn ret;
4563
4564   if (!src->conninfo.connection || !src->conninfo.connected)
4565     goto no_connection;
4566
4567   if (src->interleaved)
4568     ret = gst_rtspsrc_loop_interleaved (src);
4569   else
4570     ret = gst_rtspsrc_loop_udp (src);
4571
4572   if (ret != GST_FLOW_OK)
4573     goto pause;
4574
4575   return TRUE;
4576
4577   /* ERRORS */
4578 no_connection:
4579   {
4580     GST_WARNING_OBJECT (src, "we are not connected");
4581     ret = GST_FLOW_FLUSHING;
4582     goto pause;
4583   }
4584 pause:
4585   {
4586     const gchar *reason = gst_flow_get_name (ret);
4587
4588     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4589     src->running = FALSE;
4590     if (ret == GST_FLOW_EOS) {
4591       /* perform EOS logic */
4592       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4593         gst_element_post_message (GST_ELEMENT_CAST (src),
4594             gst_message_new_segment_done (GST_OBJECT_CAST (src),
4595                 src->segment.format, src->segment.position));
4596         gst_rtspsrc_push_event (src,
4597             gst_event_new_segment_done (src->segment.format,
4598                 src->segment.position));
4599       } else {
4600         gst_rtspsrc_push_event (src, gst_event_new_eos ());
4601       }
4602     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4603       /* for fatal errors we post an error message, post the error before the
4604        * EOS so the app knows about the error first. */
4605       GST_ELEMENT_ERROR (src, STREAM, FAILED,
4606           ("Internal data flow error."),
4607           ("streaming task paused, reason %s (%d)", reason, ret));
4608       gst_rtspsrc_push_event (src, gst_event_new_eos ());
4609     }
4610     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
4611     return FALSE;
4612   }
4613 }
4614
4615 #ifndef GST_DISABLE_GST_DEBUG
4616 static const gchar *
4617 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4618 {
4619   gint index = 0;
4620
4621   while (method != 0) {
4622     index++;
4623     method >>= 1;
4624   }
4625   switch (index) {
4626     case 0:
4627       return "None";
4628     case 1:
4629       return "Basic";
4630     case 2:
4631       return "Digest";
4632   }
4633
4634   return "Unknown";
4635 }
4636 #endif
4637
4638 static const gchar *
4639 gst_rtspsrc_skip_lws (const gchar * s)
4640 {
4641   while (g_ascii_isspace (*s))
4642     s++;
4643   return s;
4644 }
4645
4646 static const gchar *
4647 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4648 {
4649   while (s > start && g_ascii_isspace (*(s - 1)))
4650     s--;
4651   return s;
4652 }
4653
4654 static const gchar *
4655 gst_rtspsrc_skip_commas (const gchar * s)
4656 {
4657   /* The grammar allows for multiple commas */
4658   while (g_ascii_isspace (*s) || *s == ',')
4659     s++;
4660   return s;
4661 }
4662
4663 static const gchar *
4664 gst_rtspsrc_skip_item (const gchar * s)
4665 {
4666   gboolean quoted = FALSE;
4667   const gchar *start = s;
4668
4669   /* A list item ends at the last non-whitespace character
4670    * before a comma which is not inside a quoted-string. Or at
4671    * the end of the string.
4672    */
4673   while (*s) {
4674     if (*s == '"')
4675       quoted = !quoted;
4676     else if (quoted) {
4677       if (*s == '\\' && *(s + 1))
4678         s++;
4679     } else {
4680       if (*s == ',')
4681         break;
4682     }
4683     s++;
4684   }
4685
4686   return gst_rtspsrc_unskip_lws (s, start);
4687 }
4688
4689 static void
4690 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4691 {
4692   gchar *src, *dst;
4693
4694   src = quoted_string + 1;
4695   dst = quoted_string;
4696   while (*src && *src != '"') {
4697     if (*src == '\\' && *(src + 1))
4698       src++;
4699     *dst++ = *src++;
4700   }
4701   *dst = '\0';
4702 }
4703
4704 /* Extract the authentication tokens that the server provided for each method
4705  * into an array of structures and give those to the connection object.
4706  */
4707 static void
4708 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4709     const gchar * header, gboolean * stale)
4710 {
4711   GSList *list = NULL, *iter;
4712   const gchar *end;
4713   gchar *item, *eq, *name_end, *value;
4714
4715   g_return_if_fail (stale != NULL);
4716
4717   gst_rtsp_connection_clear_auth_params (conn);
4718   *stale = FALSE;
4719
4720   /* Parse a header whose content is described by RFC2616 as
4721    * "#something", where "something" does not itself contain commas,
4722    * except as part of quoted-strings, into a list of allocated strings.
4723    */
4724   header = gst_rtspsrc_skip_commas (header);
4725   while (*header) {
4726     end = gst_rtspsrc_skip_item (header);
4727     list = g_slist_prepend (list, g_strndup (header, end - header));
4728     header = gst_rtspsrc_skip_commas (end);
4729   }
4730   if (!list)
4731     return;
4732
4733   list = g_slist_reverse (list);
4734   for (iter = list; iter; iter = iter->next) {
4735     item = iter->data;
4736
4737     eq = strchr (item, '=');
4738     if (eq) {
4739       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4740       if (name_end == item) {
4741         /* That's no good... */
4742         g_free (item);
4743         continue;
4744       }
4745
4746       *name_end = '\0';
4747
4748       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4749       if (*value == '"')
4750         gst_rtsp_decode_quoted_string (value);
4751     } else
4752       value = NULL;
4753
4754     if (item && (strcmp (item, "stale") == 0) &&
4755         value && (strcmp (value, "TRUE") == 0))
4756       *stale = TRUE;
4757     gst_rtsp_connection_set_auth_param (conn, item, value);
4758     g_free (item);
4759   }
4760
4761   g_slist_free (list);
4762 }
4763
4764 /* Parse a WWW-Authenticate Response header and determine the
4765  * available authentication methods
4766  *
4767  * This code should also cope with the fact that each WWW-Authenticate
4768  * header can contain multiple challenge methods + tokens
4769  *
4770  * At the moment, for Basic auth, we just do a minimal check and don't
4771  * even parse out the realm */
4772 static void
4773 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4774     GstRTSPConnection * conn, gboolean * stale)
4775 {
4776   gchar *start;
4777
4778   g_return_if_fail (hdr != NULL);
4779   g_return_if_fail (methods != NULL);
4780   g_return_if_fail (stale != NULL);
4781
4782   /* Skip whitespace at the start of the string */
4783   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4784
4785   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4786     *methods |= GST_RTSP_AUTH_BASIC;
4787   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4788     *methods |= GST_RTSP_AUTH_DIGEST;
4789     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4790   }
4791 }
4792
4793 /**
4794  * gst_rtspsrc_setup_auth:
4795  * @src: the rtsp source
4796  *
4797  * Configure a username and password and auth method on the
4798  * connection object based on a response we received from the
4799  * peer.
4800  *
4801  * Currently, this requires that a username and password were supplied
4802  * in the uri. In the future, they may be requested on demand by sending
4803  * a message up the bus.
4804  *
4805  * Returns: TRUE if authentication information could be set up correctly.
4806  */
4807 static gboolean
4808 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4809 {
4810   gchar *user = NULL;
4811   gchar *pass = NULL;
4812   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4813   GstRTSPAuthMethod method;
4814   GstRTSPResult auth_result;
4815   GstRTSPUrl *url;
4816   GstRTSPConnection *conn;
4817   gchar *hdr;
4818   gboolean stale = FALSE;
4819
4820   conn = src->conninfo.connection;
4821
4822   /* Identify the available auth methods and see if any are supported */
4823   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4824           &hdr, 0) == GST_RTSP_OK) {
4825     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4826   }
4827
4828   if (avail_methods == GST_RTSP_AUTH_NONE)
4829     goto no_auth_available;
4830
4831   /* For digest auth, if the response indicates that the session
4832    * data are stale, we just update them in the connection object and
4833    * return TRUE to retry the request */
4834   if (stale)
4835     src->tried_url_auth = FALSE;
4836
4837   url = gst_rtsp_connection_get_url (conn);
4838
4839   /* Do we have username and password available? */
4840   if (url != NULL && !src->tried_url_auth && url->user != NULL
4841       && url->passwd != NULL) {
4842     user = url->user;
4843     pass = url->passwd;
4844     src->tried_url_auth = TRUE;
4845     GST_DEBUG_OBJECT (src,
4846         "Attempting authentication using credentials from the URL");
4847   } else {
4848     user = src->user_id;
4849     pass = src->user_pw;
4850     GST_DEBUG_OBJECT (src,
4851         "Attempting authentication using credentials from the properties");
4852   }
4853
4854   /* FIXME: If the url didn't contain username and password or we tried them
4855    * already, request a username and passwd from the application via some kind
4856    * of credentials request message */
4857
4858   /* If we don't have a username and passwd at this point, bail out. */
4859   if (user == NULL || pass == NULL)
4860     goto no_user_pass;
4861
4862   /* Try to configure for each available authentication method, strongest to
4863    * weakest */
4864   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4865     /* Check if this method is available on the server */
4866     if ((method & avail_methods) == 0)
4867       continue;
4868
4869     /* Pass the credentials to the connection to try on the next request */
4870     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4871     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4872      * ignore it and end up retrying later */
4873     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4874       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4875           gst_rtsp_auth_method_to_string (method));
4876       break;
4877     }
4878   }
4879
4880   if (method == GST_RTSP_AUTH_NONE)
4881     goto no_auth_available;
4882
4883   return TRUE;
4884
4885 no_auth_available:
4886   {
4887     /* Output an error indicating that we couldn't connect because there were
4888      * no supported authentication protocols */
4889     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4890         ("No supported authentication protocol was found"));
4891     return FALSE;
4892   }
4893 no_user_pass:
4894   {
4895     /* We don't fire an error message, we just return FALSE and let the
4896      * normal NOT_AUTHORIZED error be propagated */
4897     return FALSE;
4898   }
4899 }
4900
4901 static GstRTSPResult
4902 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4903     GstRTSPMessage * request, GstRTSPMessage * response,
4904     GstRTSPStatusCode * code)
4905 {
4906   GstRTSPResult res;
4907   GstRTSPStatusCode thecode;
4908   gchar *content_base = NULL;
4909   gint try = 0;
4910
4911 again:
4912   if (!src->short_header)
4913     gst_rtsp_ext_list_before_send (src->extensions, request);
4914
4915   GST_DEBUG_OBJECT (src, "sending message");
4916
4917   if (src->debug)
4918     gst_rtsp_message_dump (request);
4919
4920   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4921   if (res < 0)
4922     goto send_error;
4923
4924   gst_rtsp_connection_reset_timeout (conn);
4925
4926 next:
4927   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4928   if (res < 0)
4929     goto receive_error;
4930
4931   if (src->debug)
4932     gst_rtsp_message_dump (response);
4933
4934   switch (response->type) {
4935     case GST_RTSP_MESSAGE_REQUEST:
4936       res = gst_rtspsrc_handle_request (src, conn, response);
4937       if (res == GST_RTSP_EEOF)
4938         goto server_eof;
4939       else if (res < 0)
4940         goto handle_request_failed;
4941       goto next;
4942     case GST_RTSP_MESSAGE_RESPONSE:
4943       /* ok, a response is good */
4944       GST_DEBUG_OBJECT (src, "received response message");
4945       break;
4946     case GST_RTSP_MESSAGE_DATA:
4947       /* get next response */
4948       GST_DEBUG_OBJECT (src, "handle data response message");
4949       gst_rtspsrc_handle_data (src, response);
4950       goto next;
4951     default:
4952       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4953           response->type);
4954       goto next;
4955   }
4956
4957   thecode = response->type_data.response.code;
4958
4959   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4960
4961   /* if the caller wanted the result code, we store it. */
4962   if (code)
4963     *code = thecode;
4964
4965   /* If the request didn't succeed, bail out before doing any more */
4966   if (thecode != GST_RTSP_STS_OK)
4967     return GST_RTSP_OK;
4968
4969   /* store new content base if any */
4970   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4971       &content_base, 0);
4972   if (content_base) {
4973     g_free (src->content_base);
4974     src->content_base = g_strdup (content_base);
4975   }
4976   gst_rtsp_ext_list_after_send (src->extensions, request, response);
4977
4978   return GST_RTSP_OK;
4979
4980   /* ERRORS */
4981 send_error:
4982   {
4983     gchar *str = gst_rtsp_strresult (res);
4984
4985     if (res != GST_RTSP_EINTR) {
4986       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4987           ("Could not send message. (%s)", str));
4988     } else {
4989       GST_WARNING_OBJECT (src, "send interrupted");
4990     }
4991     g_free (str);
4992     return res;
4993   }
4994 receive_error:
4995   {
4996     switch (res) {
4997       case GST_RTSP_EEOF:
4998         GST_WARNING_OBJECT (src, "server closed connection");
4999         if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5000           try++;
5001           /* if reconnect succeeds, try again */
5002           if ((res =
5003                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5004                       FALSE)) == 0)
5005             goto again;
5006         }
5007         /* only try once after reconnect, then fallthrough and error out */
5008       default:
5009       {
5010         gchar *str = gst_rtsp_strresult (res);
5011
5012         if (res != GST_RTSP_EINTR) {
5013           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5014               ("Could not receive message. (%s)", str));
5015         } else {
5016           GST_WARNING_OBJECT (src, "receive interrupted");
5017         }
5018         g_free (str);
5019         break;
5020       }
5021     }
5022     return res;
5023   }
5024 handle_request_failed:
5025   {
5026     /* ERROR was posted */
5027     gst_rtsp_message_unset (response);
5028     return res;
5029   }
5030 server_eof:
5031   {
5032     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5033     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5034         ("The server closed the connection."));
5035     gst_rtsp_message_unset (response);
5036     return res;
5037   }
5038 }
5039
5040 /**
5041  * gst_rtspsrc_send:
5042  * @src: the rtsp source
5043  * @conn: the connection to send on
5044  * @request: must point to a valid request
5045  * @response: must point to an empty #GstRTSPMessage
5046  * @code: an optional code result
5047  *
5048  * send @request and retrieve the response in @response. optionally @code can be
5049  * non-NULL in which case it will contain the status code of the response.
5050  *
5051  * If This function returns #GST_RTSP_OK, @response will contain a valid response
5052  * message that should be cleaned with gst_rtsp_message_unset() after usage.
5053  *
5054  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5055  * @response message) if the response code was not 200 (OK).
5056  *
5057  * If the attempt results in an authentication failure, then this will attempt
5058  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5059  * the request.
5060  *
5061  * Returns: #GST_RTSP_OK if the processing was successful.
5062  */
5063 static GstRTSPResult
5064 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5065     GstRTSPMessage * request, GstRTSPMessage * response,
5066     GstRTSPStatusCode * code)
5067 {
5068   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5069   GstRTSPResult res = GST_RTSP_ERROR;
5070   gint count;
5071   gboolean retry;
5072   GstRTSPMethod method = GST_RTSP_INVALID;
5073
5074   count = 0;
5075   do {
5076     retry = FALSE;
5077
5078     /* make sure we don't loop forever */
5079     if (count++ > 8)
5080       break;
5081
5082     /* save method so we can disable it when the server complains */
5083     method = request->type_data.request.method;
5084
5085     if ((res =
5086             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5087       goto error;
5088
5089     switch (int_code) {
5090       case GST_RTSP_STS_UNAUTHORIZED:
5091         if (gst_rtspsrc_setup_auth (src, response)) {
5092           /* Try the request/response again after configuring the auth info
5093            * and loop again */
5094           retry = TRUE;
5095         }
5096         break;
5097       default:
5098         break;
5099     }
5100   } while (retry == TRUE);
5101
5102   /* If the user requested the code, let them handle errors, otherwise
5103    * post an error below */
5104   if (code != NULL)
5105     *code = int_code;
5106   else if (int_code != GST_RTSP_STS_OK)
5107     goto error_response;
5108
5109   return res;
5110
5111   /* ERRORS */
5112 error:
5113   {
5114     GST_DEBUG_OBJECT (src, "got error %d", res);
5115     return res;
5116   }
5117 error_response:
5118   {
5119     res = GST_RTSP_ERROR;
5120
5121     switch (response->type_data.response.code) {
5122       case GST_RTSP_STS_NOT_FOUND:
5123         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5124                 response->type_data.response.reason));
5125         break;
5126       case GST_RTSP_STS_MOVED_PERMANENTLY:
5127       case GST_RTSP_STS_MOVE_TEMPORARILY:
5128       {
5129         gchar *new_location;
5130         GstRTSPLowerTrans transports;
5131
5132         GST_DEBUG_OBJECT (src, "got redirection");
5133         /* if we don't have a Location Header, we must error */
5134         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5135                 &new_location, 0) < 0)
5136           break;
5137
5138         /* When we receive a redirect result, we go back to the INIT state after
5139          * parsing the new URI. The caller should do the needed steps to issue
5140          * a new setup when it detects this state change. */
5141         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5142
5143         /* save current transports */
5144         if (src->conninfo.url)
5145           transports = src->conninfo.url->transports;
5146         else
5147           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5148
5149         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5150
5151         /* set old transports */
5152         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5153           src->conninfo.url->transports = transports;
5154
5155         src->need_redirect = TRUE;
5156         src->state = GST_RTSP_STATE_INIT;
5157         res = GST_RTSP_OK;
5158         break;
5159       }
5160       case GST_RTSP_STS_NOT_ACCEPTABLE:
5161       case GST_RTSP_STS_NOT_IMPLEMENTED:
5162       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5163         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5164             gst_rtsp_method_as_text (method));
5165         src->methods &= ~method;
5166         res = GST_RTSP_OK;
5167         break;
5168       default:
5169         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5170             ("Got error response: %d (%s).", response->type_data.response.code,
5171                 response->type_data.response.reason));
5172         break;
5173     }
5174     /* if we return ERROR we should unset the response ourselves */
5175     if (res == GST_RTSP_ERROR)
5176       gst_rtsp_message_unset (response);
5177
5178     return res;
5179   }
5180 }
5181
5182 static GstRTSPResult
5183 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5184     GstRTSPMessage * response, GstRTSPSrc * src)
5185 {
5186   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5187       NULL);
5188 }
5189
5190
5191 /* parse the response and collect all the supported methods. We need this
5192  * information so that we don't try to send an unsupported request to the
5193  * server.
5194  */
5195 static gboolean
5196 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5197 {
5198   GstRTSPHeaderField field;
5199   gchar *respoptions;
5200   gint indx = 0;
5201
5202   /* reset supported methods */
5203   src->methods = 0;
5204
5205   /* Try Allow Header first */
5206   field = GST_RTSP_HDR_ALLOW;
5207   while (TRUE) {
5208     respoptions = NULL;
5209     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5210     if (indx == 0 && !respoptions) {
5211       /* if no Allow header was found then try the Public header... */
5212       field = GST_RTSP_HDR_PUBLIC;
5213       gst_rtsp_message_get_header (response, field, &respoptions, indx);
5214     }
5215     if (!respoptions)
5216       break;
5217
5218     src->methods |= gst_rtsp_options_from_text (respoptions);
5219
5220     indx++;
5221   }
5222
5223   if (src->methods == 0) {
5224     /* neither Allow nor Public are required, assume the server supports
5225      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5226      * well. */
5227     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5228     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5229   }
5230   /* always assume PLAY, FIXME, extensions should be able to override
5231    * this */
5232   src->methods |= GST_RTSP_PLAY;
5233   /* also assume it will support Range */
5234   src->seekable = TRUE;
5235
5236   /* we need describe and setup */
5237   if (!(src->methods & GST_RTSP_DESCRIBE))
5238     goto no_describe;
5239   if (!(src->methods & GST_RTSP_SETUP))
5240     goto no_setup;
5241
5242   return TRUE;
5243
5244   /* ERRORS */
5245 no_describe:
5246   {
5247     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5248         ("Server does not support DESCRIBE."));
5249     return FALSE;
5250   }
5251 no_setup:
5252   {
5253     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5254         ("Server does not support SETUP."));
5255     return FALSE;
5256   }
5257 }
5258
5259 /* masks to be kept in sync with the hardcoded protocol order of preference
5260  * in code below */
5261 static guint protocol_masks[] = {
5262   GST_RTSP_LOWER_TRANS_UDP,
5263   GST_RTSP_LOWER_TRANS_UDP_MCAST,
5264   GST_RTSP_LOWER_TRANS_TCP,
5265   0
5266 };
5267
5268 static GstRTSPResult
5269 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5270     GstRTSPLowerTrans protocols, gchar ** transports)
5271 {
5272   GstRTSPResult res;
5273   GString *result;
5274   gboolean add_udp_str;
5275
5276   *transports = NULL;
5277
5278   res =
5279       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5280
5281   if (res < 0)
5282     goto failed;
5283
5284   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5285
5286   /* extension listed transports, use those */
5287   if (*transports != NULL)
5288     return GST_RTSP_OK;
5289
5290   /* it's the default */
5291   add_udp_str = FALSE;
5292
5293   /* the default RTSP transports */
5294   result = g_string_new ("");
5295   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5296     GST_DEBUG_OBJECT (src, "adding UDP unicast");
5297
5298     g_string_append (result, "RTP/AVP");
5299     if (add_udp_str)
5300       g_string_append (result, "/UDP");
5301     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5302   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5303     GST_DEBUG_OBJECT (src, "adding UDP multicast");
5304
5305     /* we don't have to allocate any UDP ports yet, if the selected transport
5306      * turns out to be multicast we can create them and join the multicast
5307      * group indicated in the transport reply */
5308     if (result->len > 0)
5309       g_string_append (result, ",");
5310     g_string_append (result, "RTP/AVP");
5311     if (add_udp_str)
5312       g_string_append (result, "/UDP");
5313     g_string_append (result, ";multicast");
5314     if (src->next_port_num != 0) {
5315       if (src->client_port_range.max > 0 &&
5316           src->next_port_num >= src->client_port_range.max)
5317         goto no_ports;
5318
5319       g_string_append_printf (result, ";client_port=%d-%d",
5320           src->next_port_num, src->next_port_num + 1);
5321     }
5322   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5323     GST_DEBUG_OBJECT (src, "adding TCP");
5324
5325     if (result->len > 0)
5326       g_string_append (result, ",");
5327     g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
5328   }
5329   *transports = g_string_free (result, FALSE);
5330
5331   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5332
5333   return GST_RTSP_OK;
5334
5335   /* ERRORS */
5336 failed:
5337   {
5338     GST_ERROR ("extension gave error %d", res);
5339     return res;
5340   }
5341 no_ports:
5342   {
5343     GST_ERROR ("no more ports available");
5344     return GST_RTSP_ERROR;
5345   }
5346 }
5347
5348 static GstRTSPResult
5349 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5350     gint orig_rtpport, gint orig_rtcpport)
5351 {
5352   GstRTSPSrc *src;
5353   gint nr_udp, nr_int;
5354   gchar *next, *p;
5355   gint rtpport = 0, rtcpport = 0;
5356   GString *str;
5357
5358   src = stream->parent;
5359
5360   /* find number of placeholders first */
5361   if (strstr (*transports, "%%i2"))
5362     nr_int = 2;
5363   else if (strstr (*transports, "%%i1"))
5364     nr_int = 1;
5365   else
5366     nr_int = 0;
5367
5368   if (strstr (*transports, "%%u2"))
5369     nr_udp = 2;
5370   else if (strstr (*transports, "%%u1"))
5371     nr_udp = 1;
5372   else
5373     nr_udp = 0;
5374
5375   if (nr_udp == 0 && nr_int == 0)
5376     goto done;
5377
5378   if (nr_udp > 0) {
5379     if (!orig_rtpport || !orig_rtcpport) {
5380       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5381         goto failed;
5382     } else {
5383       rtpport = orig_rtpport;
5384       rtcpport = orig_rtcpport;
5385     }
5386   }
5387
5388   str = g_string_new ("");
5389   p = *transports;
5390   while ((next = strstr (p, "%%"))) {
5391     g_string_append_len (str, p, next - p);
5392     if (next[2] == 'u') {
5393       if (next[3] == '1')
5394         g_string_append_printf (str, "%d", rtpport);
5395       else if (next[3] == '2')
5396         g_string_append_printf (str, "%d", rtcpport);
5397     }
5398     if (next[2] == 'i') {
5399       if (next[3] == '1')
5400         g_string_append_printf (str, "%d", src->free_channel);
5401       else if (next[3] == '2')
5402         g_string_append_printf (str, "%d", src->free_channel + 1);
5403     }
5404
5405     p = next + 4;
5406   }
5407   /* append final part */
5408   g_string_append (str, p);
5409
5410   g_free (*transports);
5411   *transports = g_string_free (str, FALSE);
5412
5413 done:
5414   return GST_RTSP_OK;
5415
5416   /* ERRORS */
5417 failed:
5418   {
5419     GST_ERROR ("failed to allocate udp ports");
5420     return GST_RTSP_ERROR;
5421   }
5422 }
5423
5424 static gboolean
5425 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5426 {
5427   gboolean res = FALSE;
5428
5429   if (stream->caps) {
5430     GstStructure *s;
5431     const gchar *enc = NULL;
5432
5433     s = gst_caps_get_structure (stream->caps, 0);
5434     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5435       res = (strstr (enc, "-REAL") != NULL);
5436     }
5437   }
5438   return res;
5439 }
5440
5441 /* Perform the SETUP request for all the streams.
5442  *
5443  * We ask the server for a specific transport, which initially includes all the
5444  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5445  * two local UDP ports that we send to the server.
5446  *
5447  * Once the server replied with a transport, we configure the other streams
5448  * with the same transport.
5449  *
5450  * This function will also configure the stream for the selected transport,
5451  * which basically means creating the pipeline.
5452  */
5453 static GstRTSPResult
5454 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5455 {
5456   GList *walk;
5457   GstRTSPResult res = GST_RTSP_ERROR;
5458   GstRTSPMessage request = { 0 };
5459   GstRTSPMessage response = { 0 };
5460   GstRTSPStream *stream = NULL;
5461   GstRTSPLowerTrans protocols;
5462   GstRTSPStatusCode code;
5463   gboolean unsupported_real = FALSE;
5464   gint rtpport, rtcpport;
5465   GstRTSPUrl *url;
5466   gchar *hval;
5467
5468   if (src->conninfo.connection) {
5469     url = gst_rtsp_connection_get_url (src->conninfo.connection);
5470     /* we initially allow all configured lower transports. based on the URL
5471      * transports and the replies from the server we narrow them down. */
5472     protocols = url->transports & src->cur_protocols;
5473   } else {
5474     url = NULL;
5475     protocols = src->cur_protocols;
5476   }
5477
5478   if (protocols == 0)
5479     goto no_protocols;
5480
5481   /* reset some state */
5482   src->free_channel = 0;
5483   src->interleaved = FALSE;
5484   src->need_activate = FALSE;
5485   /* keep track of next port number, 0 is random */
5486   src->next_port_num = src->client_port_range.min;
5487   rtpport = rtcpport = 0;
5488
5489   if (G_UNLIKELY (src->streams == NULL))
5490     goto no_streams;
5491
5492   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5493     GstRTSPConnection *conn;
5494     gchar *transports;
5495     gint retry = 0;
5496     guint mask = 0;
5497     gboolean selected;
5498
5499     stream = (GstRTSPStream *) walk->data;
5500
5501     /* see if we need to configure this stream */
5502     if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5503       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5504           stream);
5505       stream->disabled = TRUE;
5506       continue;
5507     }
5508
5509     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
5510         stream->id, stream->caps, &selected);
5511     if (!selected) {
5512       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
5513       stream->disabled = TRUE;
5514       continue;
5515     }
5516     stream->disabled = FALSE;
5517
5518     /* merge/overwrite global caps */
5519     if (stream->caps) {
5520       guint j, num;
5521       GstStructure *s;
5522
5523       s = gst_caps_get_structure (stream->caps, 0);
5524
5525       num = gst_structure_n_fields (src->props);
5526       for (j = 0; j < num; j++) {
5527         const gchar *name;
5528         const GValue *val;
5529
5530         name = gst_structure_nth_field_name (src->props, j);
5531         val = gst_structure_get_value (src->props, name);
5532         gst_structure_set_value (s, name, val);
5533
5534         GST_DEBUG_OBJECT (src, "copied %s", name);
5535       }
5536     }
5537
5538     /* skip setup if we have no URL for it */
5539     if (stream->conninfo.location == NULL) {
5540       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5541       continue;
5542     }
5543
5544     if (src->conninfo.connection == NULL) {
5545       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5546         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5547         continue;
5548       }
5549       conn = stream->conninfo.connection;
5550     } else {
5551       conn = src->conninfo.connection;
5552     }
5553     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5554         stream->conninfo.location);
5555
5556     /* if we have a multicast connection, only suggest multicast from now on */
5557     if (stream->is_multicast)
5558       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5559
5560   next_protocol:
5561     /* first selectable protocol */
5562     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5563       mask++;
5564     if (!protocol_masks[mask])
5565       goto no_protocols;
5566
5567   retry:
5568     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5569         protocol_masks[mask]);
5570     /* create a string with first transport in line */
5571     transports = NULL;
5572     res = gst_rtspsrc_create_transports_string (src,
5573         protocols & protocol_masks[mask], &transports);
5574     if (res < 0 || transports == NULL)
5575       goto setup_transport_failed;
5576
5577     if (strlen (transports) == 0) {
5578       g_free (transports);
5579       GST_DEBUG_OBJECT (src, "no transports found");
5580       mask++;
5581       goto next_protocol;
5582     }
5583
5584     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5585
5586     /* replace placeholders with real values, this function will optionally
5587      * allocate UDP ports and other info needed to execute the setup request */
5588     res = gst_rtspsrc_prepare_transports (stream, &transports,
5589         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5590     if (res < 0) {
5591       g_free (transports);
5592       goto setup_transport_failed;
5593     }
5594
5595     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5596
5597     /* create SETUP request */
5598     res =
5599         gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5600         stream->conninfo.location);
5601     if (res < 0) {
5602       g_free (transports);
5603       goto create_request_failed;
5604     }
5605
5606     /* select transport */
5607     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5608
5609     /* if the user wants a non default RTP packet size we add the blocksize
5610      * parameter */
5611     if (src->rtp_blocksize > 0) {
5612       hval = g_strdup_printf ("%d", src->rtp_blocksize);
5613       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5614     }
5615
5616     if (async)
5617       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5618               stream->id));
5619
5620     /* handle the code ourselves */
5621     if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5622       goto send_error;
5623
5624     switch (code) {
5625       case GST_RTSP_STS_OK:
5626         break;
5627       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5628         gst_rtsp_message_unset (&request);
5629         gst_rtsp_message_unset (&response);
5630         /* cleanup of leftover transport */
5631         gst_rtspsrc_stream_free_udp (stream);
5632         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5633          * we might be in this case */
5634         if (stream->container && rtpport && rtcpport && !retry) {
5635           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5636               rtpport, rtcpport);
5637           retry++;
5638           goto retry;
5639         }
5640         /* this transport did not go down well, but we may have others to try
5641          * that we did not send yet, try those and only give up then
5642          * but not without checking for lost cause/extension so we can
5643          * post a nicer/more useful error message later */
5644         if (!unsupported_real)
5645           unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5646         /* select next available protocol, give up on this stream if none */
5647         mask++;
5648         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5649           mask++;
5650         if (!protocol_masks[mask] || unsupported_real)
5651           continue;
5652         else
5653           goto retry;
5654       default:
5655         /* cleanup of leftover transport and move to the next stream */
5656         gst_rtspsrc_stream_free_udp (stream);
5657         goto response_error;
5658     }
5659
5660     /* parse response transport */
5661     {
5662       gchar *resptrans = NULL;
5663       GstRTSPTransport transport = { 0 };
5664
5665       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5666           &resptrans, 0);
5667       if (!resptrans) {
5668         gst_rtspsrc_stream_free_udp (stream);
5669         goto no_transport;
5670       }
5671
5672       /* parse transport, go to next stream on parse error */
5673       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5674         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5675         goto next;
5676       }
5677
5678       /* update allowed transports for other streams. once the transport of
5679        * one stream has been determined, we make sure that all other streams
5680        * are configured in the same way */
5681       switch (transport.lower_transport) {
5682         case GST_RTSP_LOWER_TRANS_TCP:
5683           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5684           protocols = GST_RTSP_LOWER_TRANS_TCP;
5685           src->interleaved = TRUE;
5686           /* update free channels */
5687           src->free_channel =
5688               MAX (transport.interleaved.min, src->free_channel);
5689           src->free_channel =
5690               MAX (transport.interleaved.max, src->free_channel);
5691           src->free_channel++;
5692           break;
5693         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5694           /* only allow multicast for other streams */
5695           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5696           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5697           /* if the server selected our ports, increment our counters so that
5698            * we select a new port later */
5699           if (src->next_port_num == transport.port.min &&
5700               src->next_port_num + 1 == transport.port.max) {
5701             src->next_port_num += 2;
5702           }
5703           break;
5704         case GST_RTSP_LOWER_TRANS_UDP:
5705           /* only allow unicast for other streams */
5706           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5707           protocols = GST_RTSP_LOWER_TRANS_UDP;
5708           break;
5709         default:
5710           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5711               transport.lower_transport);
5712           break;
5713       }
5714
5715       if (!stream->container || (!src->interleaved && !retry)) {
5716         /* now configure the stream with the selected transport */
5717         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5718           GST_DEBUG_OBJECT (src,
5719               "could not configure stream %p transport, skipping stream",
5720               stream);
5721           goto next;
5722         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5723           /* retain the first allocated UDP port pair */
5724           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5725           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5726         }
5727       }
5728       /* we need to activate at least one streams when we detect activity */
5729       src->need_activate = TRUE;
5730     next:
5731       /* clean up our transport struct */
5732       gst_rtsp_transport_init (&transport);
5733       /* clean up used RTSP messages */
5734       gst_rtsp_message_unset (&request);
5735       gst_rtsp_message_unset (&response);
5736     }
5737   }
5738
5739   /* store the transport protocol that was configured */
5740   src->cur_protocols = protocols;
5741
5742   gst_rtsp_ext_list_stream_select (src->extensions, url);
5743
5744   /* if there is nothing to activate, error out */
5745   if (!src->need_activate)
5746     goto nothing_to_activate;
5747
5748   return res;
5749
5750   /* ERRORS */
5751 no_protocols:
5752   {
5753     /* no transport possible, post an error and stop */
5754     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5755         ("Could not connect to server, no protocols left"));
5756     return GST_RTSP_ERROR;
5757   }
5758 no_streams:
5759   {
5760     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5761         ("SDP contains no streams"));
5762     return GST_RTSP_ERROR;
5763   }
5764 create_request_failed:
5765   {
5766     gchar *str = gst_rtsp_strresult (res);
5767
5768     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5769         ("Could not create request. (%s)", str));
5770     g_free (str);
5771     goto cleanup_error;
5772   }
5773 setup_transport_failed:
5774   {
5775     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5776         ("Could not setup transport."));
5777     res = GST_RTSP_ERROR;
5778     goto cleanup_error;
5779   }
5780 response_error:
5781   {
5782     const gchar *str = gst_rtsp_status_as_text (code);
5783
5784     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5785         ("Error (%d): %s", code, GST_STR_NULL (str)));
5786     res = GST_RTSP_ERROR;
5787     goto cleanup_error;
5788   }
5789 send_error:
5790   {
5791     gchar *str = gst_rtsp_strresult (res);
5792
5793     if (res != GST_RTSP_EINTR) {
5794       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5795           ("Could not send message. (%s)", str));
5796     } else {
5797       GST_WARNING_OBJECT (src, "send interrupted");
5798     }
5799     g_free (str);
5800     goto cleanup_error;
5801   }
5802 no_transport:
5803   {
5804     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5805         ("Server did not select transport."));
5806     res = GST_RTSP_ERROR;
5807     goto cleanup_error;
5808   }
5809 nothing_to_activate:
5810   {
5811     /* none of the available error codes is really right .. */
5812     if (unsupported_real) {
5813       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5814           (_("No supported stream was found. You might need to install a "
5815                   "GStreamer RTSP extension plugin for Real media streams.")),
5816           (NULL));
5817     } else {
5818       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5819           (_("No supported stream was found. You might need to allow "
5820                   "more transport protocols or may otherwise be missing "
5821                   "the right GStreamer RTSP extension plugin.")), (NULL));
5822     }
5823     return GST_RTSP_ERROR;
5824   }
5825 cleanup_error:
5826   {
5827     gst_rtsp_message_unset (&request);
5828     gst_rtsp_message_unset (&response);
5829     return res;
5830   }
5831 }
5832
5833 static gboolean
5834 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5835     GstSegment * segment)
5836 {
5837   gint64 seconds;
5838   GstRTSPTimeRange *therange;
5839
5840   if (src->range)
5841     gst_rtsp_range_free (src->range);
5842
5843   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5844     GST_DEBUG_OBJECT (src, "parsed range %s", range);
5845     src->range = therange;
5846   } else {
5847     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5848     src->range = NULL;
5849     gst_segment_init (segment, GST_FORMAT_TIME);
5850     return FALSE;
5851   }
5852
5853   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
5854       therange->min.type, therange->min.seconds, therange->max.type,
5855       therange->max.seconds);
5856
5857   if (therange->min.type == GST_RTSP_TIME_NOW)
5858     seconds = 0;
5859   else if (therange->min.type == GST_RTSP_TIME_END)
5860     seconds = 0;
5861   else
5862     seconds = therange->min.seconds * GST_SECOND;
5863
5864   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5865       GST_TIME_ARGS (seconds));
5866
5867   /* we need to start playback without clipping from the position reported by
5868    * the server */
5869   segment->start = seconds;
5870   segment->position = seconds;
5871
5872   if (therange->max.type == GST_RTSP_TIME_NOW)
5873     seconds = -1;
5874   else if (therange->max.type == GST_RTSP_TIME_END)
5875     seconds = -1;
5876   else
5877     seconds = therange->max.seconds * GST_SECOND;
5878
5879   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5880       GST_TIME_ARGS (seconds));
5881
5882   /* live (WMS) server might send overflowed large max as its idea of infinity,
5883    * compensate to prevent problems later on */
5884   if (seconds != -1 && seconds < 0) {
5885     seconds = -1;
5886     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5887   }
5888
5889   /* live (WMS) might send min == max, which is not worth recording */
5890   if (segment->duration == -1 && seconds == segment->start)
5891     seconds = -1;
5892
5893   /* don't change duration with unknown value, we might have a valid value
5894    * there that we want to keep. */
5895   if (seconds != -1)
5896     segment->duration = seconds;
5897
5898   return TRUE;
5899 }
5900
5901 /* Parse clock profived by the server with following syntax:
5902  *
5903  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
5904  */
5905 static gboolean
5906 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
5907 {
5908   gboolean res = FALSE;
5909
5910   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
5911     gchar **fields = NULL, **parts = NULL;
5912     gchar *remote_ip, *str;
5913     gint port;
5914     GstClockTime base_time;
5915     GstClock *netclock;
5916
5917     fields = g_strsplit (gstclock, " ", 0);
5918
5919     /* wrapped clock, not very interesting for now */
5920     if (fields[1] == NULL)
5921       goto cleanup;
5922
5923     /* remote IP address and port */
5924     if ((str = fields[2]) == NULL)
5925       goto cleanup;
5926
5927     parts = g_strsplit (str, ":", 0);
5928
5929     if ((remote_ip = parts[0]) == NULL)
5930       goto cleanup;
5931
5932     if ((str = parts[1]) == NULL)
5933       goto cleanup;
5934
5935     port = atoi (str);
5936     if (port == 0)
5937       goto cleanup;
5938
5939     /* base-time */
5940     if ((str = fields[3]) == NULL)
5941       goto cleanup;
5942
5943     base_time = g_ascii_strtoull (str, NULL, 10);
5944
5945     netclock =
5946         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
5947         base_time);
5948
5949     if (src->provided_clock)
5950       gst_object_unref (src->provided_clock);
5951     src->provided_clock = netclock;
5952
5953     gst_element_post_message (GST_ELEMENT_CAST (src),
5954         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
5955             src->provided_clock, TRUE));
5956
5957     res = TRUE;
5958   cleanup:
5959     g_strfreev (fields);
5960     g_strfreev (parts);
5961   }
5962   return res;
5963 }
5964
5965 /* must be called with the RTSP state lock */
5966 static GstRTSPResult
5967 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5968     gboolean async)
5969 {
5970   GstRTSPResult res;
5971   gint i, n_streams;
5972
5973   /* prepare global stream caps properties */
5974   if (src->props)
5975     gst_structure_remove_all_fields (src->props);
5976   else
5977     src->props = gst_structure_new_empty ("RTSPProperties");
5978
5979   if (src->debug)
5980     gst_sdp_message_dump (sdp);
5981
5982   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5983
5984   /* let the app inspect and change the SDP */
5985   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
5986
5987   gst_segment_init (&src->segment, GST_FORMAT_TIME);
5988
5989   /* parse range for duration reporting. */
5990   {
5991     const gchar *range;
5992
5993     for (i = 0;; i++) {
5994       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5995       if (range == NULL)
5996         break;
5997
5998       /* keep track of the range and configure it in the segment */
5999       if (gst_rtspsrc_parse_range (src, range, &src->segment))
6000         break;
6001     }
6002   }
6003   /* parse clock information. This is GStreamer specific, a server can tell the
6004    * client what clock it is using and wrap that in a network clock. The
6005    * advantage of that is that we can slave to it. */
6006   {
6007     const gchar *gstclock;
6008
6009     for (i = 0;; i++) {
6010       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6011       if (gstclock == NULL)
6012         break;
6013
6014       /* parse the clock and expose it in the provide_clock method */
6015       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6016         break;
6017     }
6018   }
6019   /* try to find a global control attribute. Note that a '*' means that we should
6020    * do aggregate control with the current url (so we don't do anything and
6021    * leave the current connection as is) */
6022   {
6023     const gchar *control;
6024
6025     for (i = 0;; i++) {
6026       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6027       if (control == NULL)
6028         break;
6029
6030       /* only take fully qualified urls */
6031       if (g_str_has_prefix (control, "rtsp://"))
6032         break;
6033     }
6034     if (control) {
6035       g_free (src->conninfo.location);
6036       src->conninfo.location = g_strdup (control);
6037       /* make a connection for this, if there was a connection already, nothing
6038        * happens. */
6039       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6040         GST_ERROR_OBJECT (src, "could not connect");
6041       }
6042     }
6043     /* we need to keep the control url separate from the connection url because
6044      * the rules for constructing the media control url need it */
6045     g_free (src->control);
6046     src->control = g_strdup (control);
6047   }
6048
6049   /* create streams */
6050   n_streams = gst_sdp_message_medias_len (sdp);
6051   for (i = 0; i < n_streams; i++) {
6052     gst_rtspsrc_create_stream (src, sdp, i);
6053   }
6054
6055   src->state = GST_RTSP_STATE_INIT;
6056
6057   /* setup streams */
6058   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
6059     goto setup_failed;
6060
6061   /* reset our state */
6062   src->need_range = TRUE;
6063   src->skip = FALSE;
6064
6065   src->state = GST_RTSP_STATE_READY;
6066
6067   return res;
6068
6069   /* ERRORS */
6070 setup_failed:
6071   {
6072     GST_ERROR_OBJECT (src, "setup failed");
6073     gst_rtspsrc_cleanup (src);
6074     return res;
6075   }
6076 }
6077
6078 static GstRTSPResult
6079 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6080     gboolean async)
6081 {
6082   GstRTSPResult res;
6083   GstRTSPMessage request = { 0 };
6084   GstRTSPMessage response = { 0 };
6085   guint8 *data;
6086   guint size;
6087   gchar *respcont = NULL;
6088
6089 restart:
6090   src->need_redirect = FALSE;
6091
6092   /* can't continue without a valid url */
6093   if (G_UNLIKELY (src->conninfo.url == NULL)) {
6094     res = GST_RTSP_EINVAL;
6095     goto no_url;
6096   }
6097   src->tried_url_auth = FALSE;
6098
6099   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
6100     goto connect_failed;
6101
6102   /* create OPTIONS */
6103   GST_DEBUG_OBJECT (src, "create options...");
6104   res =
6105       gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
6106       src->conninfo.url_str);
6107   if (res < 0)
6108     goto create_request_failed;
6109
6110   /* send OPTIONS */
6111   GST_DEBUG_OBJECT (src, "send options...");
6112
6113   if (async)
6114     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
6115
6116   if ((res =
6117           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6118               NULL)) < 0)
6119     goto send_error;
6120
6121   /* parse OPTIONS */
6122   if (!gst_rtspsrc_parse_methods (src, &response))
6123     goto methods_error;
6124
6125   /* create DESCRIBE */
6126   GST_DEBUG_OBJECT (src, "create describe...");
6127   res =
6128       gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
6129       src->conninfo.url_str);
6130   if (res < 0)
6131     goto create_request_failed;
6132
6133   /* we only accept SDP for now */
6134   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
6135       "application/sdp");
6136
6137   /* send DESCRIBE */
6138   GST_DEBUG_OBJECT (src, "send describe...");
6139
6140   if (async)
6141     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
6142
6143   if ((res =
6144           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6145               NULL)) < 0)
6146     goto send_error;
6147
6148   /* we only perform redirect for the describe, currently */
6149   if (src->need_redirect) {
6150     /* close connection, we don't have to send a TEARDOWN yet, ignore the
6151      * result. */
6152     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6153
6154     gst_rtsp_message_unset (&request);
6155     gst_rtsp_message_unset (&response);
6156
6157     /* and now retry */
6158     goto restart;
6159   }
6160
6161   /* it could be that the DESCRIBE method was not implemented */
6162   if (!src->methods & GST_RTSP_DESCRIBE)
6163     goto no_describe;
6164
6165   /* check if reply is SDP */
6166   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6167       0);
6168   /* could not be set but since the request returned OK, we assume it
6169    * was SDP, else check it. */
6170   if (respcont) {
6171     if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6172       goto wrong_content_type;
6173   }
6174
6175   /* get message body and parse as SDP */
6176   gst_rtsp_message_get_body (&response, &data, &size);
6177   if (data == NULL || size == 0)
6178     goto no_describe;
6179
6180   GST_DEBUG_OBJECT (src, "parse SDP...");
6181   gst_sdp_message_new (sdp);
6182   gst_sdp_message_parse_buffer (data, size, *sdp);
6183
6184   /* clean up any messages */
6185   gst_rtsp_message_unset (&request);
6186   gst_rtsp_message_unset (&response);
6187
6188   return res;
6189
6190   /* ERRORS */
6191 no_url:
6192   {
6193     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6194         ("No valid RTSP URL was provided"));
6195     goto cleanup_error;
6196   }
6197 connect_failed:
6198   {
6199     gchar *str = gst_rtsp_strresult (res);
6200
6201     if (res != GST_RTSP_EINTR) {
6202       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6203           ("Failed to connect. (%s)", str));
6204     } else {
6205       GST_WARNING_OBJECT (src, "connect interrupted");
6206     }
6207     g_free (str);
6208     goto cleanup_error;
6209   }
6210 create_request_failed:
6211   {
6212     gchar *str = gst_rtsp_strresult (res);
6213
6214     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6215         ("Could not create request. (%s)", str));
6216     g_free (str);
6217     goto cleanup_error;
6218   }
6219 send_error:
6220   {
6221     /* Don't post a message - the rtsp_send method will have
6222      * taken care of it because we passed NULL for the response code */
6223     goto cleanup_error;
6224   }
6225 methods_error:
6226   {
6227     /* error was posted */
6228     res = GST_RTSP_ERROR;
6229     goto cleanup_error;
6230   }
6231 wrong_content_type:
6232   {
6233     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6234         ("Server does not support SDP, got %s.", respcont));
6235     res = GST_RTSP_ERROR;
6236     goto cleanup_error;
6237   }
6238 no_describe:
6239   {
6240     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6241         ("Server can not provide an SDP."));
6242     res = GST_RTSP_ERROR;
6243     goto cleanup_error;
6244   }
6245 cleanup_error:
6246   {
6247     if (src->conninfo.connection) {
6248       GST_DEBUG_OBJECT (src, "free connection");
6249       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6250     }
6251     gst_rtsp_message_unset (&request);
6252     gst_rtsp_message_unset (&response);
6253     return res;
6254   }
6255 }
6256
6257 static GstRTSPResult
6258 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6259 {
6260   GstRTSPResult ret;
6261
6262   src->methods =
6263       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6264
6265   if (src->sdp == NULL) {
6266     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6267       goto no_sdp;
6268   }
6269
6270   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6271     goto open_failed;
6272
6273 done:
6274   if (async)
6275     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6276
6277   return ret;
6278
6279   /* ERRORS */
6280 no_sdp:
6281   {
6282     GST_WARNING_OBJECT (src, "can't get sdp");
6283     src->open_error = TRUE;
6284     goto done;
6285   }
6286 open_failed:
6287   {
6288     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6289     src->open_error = TRUE;
6290     goto done;
6291   }
6292 }
6293
6294 static GstRTSPResult
6295 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6296 {
6297   GstRTSPMessage request = { 0 };
6298   GstRTSPMessage response = { 0 };
6299   GstRTSPResult res = GST_RTSP_OK;
6300   GList *walk;
6301   gchar *control;
6302
6303   GST_DEBUG_OBJECT (src, "TEARDOWN...");
6304
6305   gst_rtspsrc_set_state (src, GST_STATE_READY);
6306
6307   if (src->state < GST_RTSP_STATE_READY) {
6308     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6309     goto close;
6310   }
6311
6312   if (only_close)
6313     goto close;
6314
6315   /* construct a control url */
6316   if (src->control)
6317     control = src->control;
6318   else
6319     control = src->conninfo.url_str;
6320
6321   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6322     goto not_supported;
6323
6324   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6325     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6326     gchar *setup_url;
6327     GstRTSPConnInfo *info;
6328
6329     /* try aggregate control first but do non-aggregate control otherwise */
6330     if (control)
6331       setup_url = control;
6332     else if ((setup_url = stream->conninfo.location) == NULL)
6333       continue;
6334
6335     if (src->conninfo.connection) {
6336       info = &src->conninfo;
6337     } else if (stream->conninfo.connection) {
6338       info = &stream->conninfo;
6339     } else {
6340       continue;
6341     }
6342     if (!info->connected)
6343       goto next;
6344
6345     /* do TEARDOWN */
6346     res =
6347         gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6348     if (res < 0)
6349       goto create_request_failed;
6350
6351     if (async)
6352       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6353
6354     if ((res =
6355             gst_rtspsrc_send (src, info->connection, &request, &response,
6356                 NULL)) < 0)
6357       goto send_error;
6358
6359     /* FIXME, parse result? */
6360     gst_rtsp_message_unset (&request);
6361     gst_rtsp_message_unset (&response);
6362
6363   next:
6364     /* early exit when we did aggregate control */
6365     if (control)
6366       break;
6367   }
6368
6369 close:
6370   /* close connections */
6371   GST_DEBUG_OBJECT (src, "closing connection...");
6372   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6373   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6374     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6375     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6376   }
6377
6378   /* cleanup */
6379   gst_rtspsrc_cleanup (src);
6380
6381   src->state = GST_RTSP_STATE_INVALID;
6382
6383   if (async)
6384     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6385
6386   return res;
6387
6388   /* ERRORS */
6389 create_request_failed:
6390   {
6391     gchar *str = gst_rtsp_strresult (res);
6392
6393     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6394         ("Could not create request. (%s)", str));
6395     g_free (str);
6396     goto close;
6397   }
6398 send_error:
6399   {
6400     gchar *str = gst_rtsp_strresult (res);
6401
6402     gst_rtsp_message_unset (&request);
6403     if (res != GST_RTSP_EINTR) {
6404       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6405           ("Could not send message. (%s)", str));
6406     } else {
6407       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
6408     }
6409     g_free (str);
6410     goto close;
6411   }
6412 not_supported:
6413   {
6414     GST_DEBUG_OBJECT (src,
6415         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
6416     goto close;
6417   }
6418 }
6419
6420 /* RTP-Info is of the format:
6421  *
6422  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
6423  *
6424  * rtptime corresponds to the timestamp for the NPT time given in the header
6425  * seqbase corresponds to the next sequence number we received. This number
6426  * indicates the first seqnum after the seek and should be used to discard
6427  * packets that are from before the seek.
6428  */
6429 static gboolean
6430 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
6431 {
6432   gchar **infos;
6433   gint i, j;
6434
6435   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
6436
6437   infos = g_strsplit (rtpinfo, ",", 0);
6438   for (i = 0; infos[i]; i++) {
6439     gchar **fields;
6440     GstRTSPStream *stream;
6441     gint32 seqbase;
6442     gint64 timebase;
6443
6444     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
6445
6446     /* init values, types of seqbase and timebase are bigger than needed so we
6447      * can store -1 as uninitialized values */
6448     stream = NULL;
6449     seqbase = -1;
6450     timebase = -1;
6451
6452     /* parse url, find stream for url.
6453      * parse seq and rtptime. The seq number should be configured in the rtp
6454      * depayloader or session manager to detect gaps. Same for the rtptime, it
6455      * should be used to create an initial time newsegment. */
6456     fields = g_strsplit (infos[i], ";", 0);
6457     for (j = 0; fields[j]; j++) {
6458       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
6459       /* remove leading whitespace */
6460       fields[j] = g_strchug (fields[j]);
6461       if (g_str_has_prefix (fields[j], "url=")) {
6462         /* get the url and the stream */
6463         stream =
6464             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
6465       } else if (g_str_has_prefix (fields[j], "seq=")) {
6466         seqbase = atoi (fields[j] + 4);
6467       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
6468         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
6469       }
6470     }
6471     g_strfreev (fields);
6472     /* now we need to store the values for the caps of the stream */
6473     if (stream != NULL) {
6474       GST_DEBUG_OBJECT (src,
6475           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
6476           stream, seqbase, timebase);
6477
6478       /* we have a stream, configure detected params */
6479       stream->seqbase = seqbase;
6480       stream->timebase = timebase;
6481     }
6482   }
6483   g_strfreev (infos);
6484
6485   return TRUE;
6486 }
6487
6488 static void
6489 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
6490 {
6491   guint64 interval;
6492   GList *walk;
6493
6494   interval = strtoul (rtcp, NULL, 10);
6495   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
6496
6497   if (!interval)
6498     return;
6499
6500   interval *= GST_MSECOND;
6501
6502   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6503     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6504
6505     /* already (optionally) retrieved this when configuring manager */
6506     if (stream->session) {
6507       GObject *rtpsession = stream->session;
6508
6509       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
6510           rtpsession);
6511       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
6512     }
6513   }
6514
6515   /* now it happens that (Xenon) server sending this may also provide bogus
6516    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
6517    * and just use RTP-Info to sync */
6518   if (src->manager) {
6519     GObjectClass *klass;
6520
6521     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6522     if (g_object_class_find_property (klass, "rtcp-sync")) {
6523       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6524       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6525     }
6526   }
6527 }
6528
6529 static gdouble
6530 gst_rtspsrc_get_float (const gchar * dstr)
6531 {
6532   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6533
6534   /* canonicalise floating point string so we can handle float strings
6535    * in the form "24.930" or "24,930" irrespective of the current locale */
6536   g_strlcpy (s, dstr, sizeof (s));
6537   g_strdelimit (s, ",", '.');
6538   return g_ascii_strtod (s, NULL);
6539 }
6540
6541 static gchar *
6542 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6543 {
6544   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6545
6546   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6547     g_strlcpy (val_str, "now", sizeof (val_str));
6548   } else {
6549     if (segment->position == 0) {
6550       g_strlcpy (val_str, "0", sizeof (val_str));
6551     } else {
6552       g_ascii_dtostr (val_str, sizeof (val_str),
6553           ((gdouble) segment->position) / GST_SECOND);
6554     }
6555   }
6556   return g_strdup_printf ("npt=%s-", val_str);
6557 }
6558
6559 static void
6560 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6561 {
6562   stream->timebase = -1;
6563   stream->seqbase = -1;
6564   if (stream->caps) {
6565     GstStructure *s;
6566
6567     stream->caps = gst_caps_make_writable (stream->caps);
6568     s = gst_caps_get_structure (stream->caps, 0);
6569     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6570   }
6571 }
6572
6573 static GstRTSPResult
6574 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6575 {
6576   GstRTSPResult res = GST_RTSP_OK;
6577
6578   if (src->state < GST_RTSP_STATE_READY) {
6579     res = GST_RTSP_ERROR;
6580     if (src->open_error) {
6581       GST_DEBUG_OBJECT (src, "the stream was in error");
6582       goto done;
6583     }
6584     if (async)
6585       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6586
6587     if ((res = gst_rtspsrc_open (src, async)) < 0) {
6588       GST_DEBUG_OBJECT (src, "failed to open stream");
6589       goto done;
6590     }
6591   }
6592
6593 done:
6594   return res;
6595 }
6596
6597 static GstRTSPResult
6598 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6599 {
6600   GstRTSPMessage request = { 0 };
6601   GstRTSPMessage response = { 0 };
6602   GstRTSPResult res = GST_RTSP_OK;
6603   GList *walk;
6604   gchar *hval;
6605   gint hval_idx;
6606   gchar *control;
6607
6608   GST_DEBUG_OBJECT (src, "PLAY...");
6609
6610   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6611     goto open_failed;
6612
6613   if (!(src->methods & GST_RTSP_PLAY))
6614     goto not_supported;
6615
6616   if (src->state == GST_RTSP_STATE_PLAYING)
6617     goto was_playing;
6618
6619   if (!src->conninfo.connection || !src->conninfo.connected)
6620     goto done;
6621
6622   /* send some dummy packets before we activate the receive in the
6623    * udp sources */
6624   gst_rtspsrc_send_dummy_packets (src);
6625
6626   /* require new SR packets */
6627   if (src->manager)
6628     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
6629
6630   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
6631
6632   /* construct a control url */
6633   if (src->control)
6634     control = src->control;
6635   else
6636     control = src->conninfo.url_str;
6637
6638   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6639     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6640     gchar *setup_url;
6641     GstRTSPConnection *conn;
6642
6643     /* try aggregate control first but do non-aggregate control otherwise */
6644     if (control)
6645       setup_url = control;
6646     else if ((setup_url = stream->conninfo.location) == NULL)
6647       continue;
6648
6649     if (src->conninfo.connection) {
6650       conn = src->conninfo.connection;
6651     } else if (stream->conninfo.connection) {
6652       conn = stream->conninfo.connection;
6653     } else {
6654       continue;
6655     }
6656
6657     /* do play */
6658     res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6659     if (res < 0)
6660       goto create_request_failed;
6661
6662     if (src->need_range) {
6663       hval = gen_range_header (src, segment);
6664
6665       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
6666
6667       /* store the newsegment event so it can be sent from the streaming thread. */
6668       if (src->start_segment)
6669         gst_event_unref (src->start_segment);
6670       src->start_segment = gst_event_new_segment (&src->segment);
6671     }
6672
6673     if (segment->rate != 1.0) {
6674       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6675
6676       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6677       if (src->skip)
6678         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6679       else
6680         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6681     }
6682
6683     if (async)
6684       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6685
6686     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6687       goto send_error;
6688
6689     /* seek may have silently failed as it is not supported */
6690     if (!(src->methods & GST_RTSP_PLAY)) {
6691       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6692       /* obviously it is supported as we made it here */
6693       src->methods |= GST_RTSP_PLAY;
6694       src->seekable = FALSE;
6695       /* but there is nothing to parse in the response,
6696        * so convey we have no idea and not to expect anything particular */
6697       clear_rtp_base (src, stream);
6698       if (control) {
6699         GList *run;
6700
6701         /* need to do for all streams */
6702         for (run = src->streams; run; run = g_list_next (run))
6703           clear_rtp_base (src, (GstRTSPStream *) run->data);
6704       }
6705       /* NOTE the above also disables npt based eos detection */
6706       /* and below forces position to 0,
6707        * which is visible feedback we lost the plot */
6708       segment->start = segment->position = src->last_pos;
6709     }
6710
6711     gst_rtsp_message_unset (&request);
6712
6713     /* parse RTP npt field. This is the current position in the stream (Normal
6714      * Play Time) and should be put in the NEWSEGMENT position field. */
6715     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6716             0) == GST_RTSP_OK)
6717       gst_rtspsrc_parse_range (src, hval, segment);
6718
6719     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6720     segment->rate = 1.0;
6721
6722     /* parse Speed header. This is the intended playback rate of the stream
6723      * and should be put in the NEWSEGMENT rate field. */
6724     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6725             0) == GST_RTSP_OK) {
6726       segment->rate = gst_rtspsrc_get_float (hval);
6727     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6728             &hval, 0) == GST_RTSP_OK) {
6729       segment->rate = gst_rtspsrc_get_float (hval);
6730     }
6731
6732     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6733      * for the RTP packets. If this is not present, we assume all starts from 0...
6734      * This is info for the RTP session manager that we pass to it in caps. */
6735     hval_idx = 0;
6736     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6737             &hval, hval_idx++) == GST_RTSP_OK)
6738       gst_rtspsrc_parse_rtpinfo (src, hval);
6739
6740     /* some servers indicate RTCP parameters in PLAY response,
6741      * rather than properly in SDP */
6742     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6743             &hval, 0) == GST_RTSP_OK)
6744       gst_rtspsrc_handle_rtcp_interval (src, hval);
6745
6746     gst_rtsp_message_unset (&response);
6747
6748     /* early exit when we did aggregate control */
6749     if (control)
6750       break;
6751   }
6752   /* configure the caps of the streams after we parsed all headers. Only reset
6753    * the manager object when we set a new Range header (we did a seek) */
6754   gst_rtspsrc_configure_caps (src, segment, src->need_range);
6755
6756   /* set again when needed */
6757   src->need_range = FALSE;
6758
6759   src->running = TRUE;
6760   src->base_time = -1;
6761   src->state = GST_RTSP_STATE_PLAYING;
6762
6763   /* mark discont */
6764   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6765   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6766     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6767     stream->discont = TRUE;
6768   }
6769
6770 done:
6771   if (async)
6772     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6773
6774   return res;
6775
6776   /* ERRORS */
6777 open_failed:
6778   {
6779     GST_DEBUG_OBJECT (src, "failed to open stream");
6780     goto done;
6781   }
6782 not_supported:
6783   {
6784     GST_DEBUG_OBJECT (src, "PLAY is not supported");
6785     goto done;
6786   }
6787 was_playing:
6788   {
6789     GST_DEBUG_OBJECT (src, "we were already PLAYING");
6790     goto done;
6791   }
6792 create_request_failed:
6793   {
6794     gchar *str = gst_rtsp_strresult (res);
6795
6796     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6797         ("Could not create request. (%s)", str));
6798     g_free (str);
6799     goto done;
6800   }
6801 send_error:
6802   {
6803     gchar *str = gst_rtsp_strresult (res);
6804
6805     gst_rtsp_message_unset (&request);
6806     if (res != GST_RTSP_EINTR) {
6807       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6808           ("Could not send message. (%s)", str));
6809     } else {
6810       GST_WARNING_OBJECT (src, "PLAY interrupted");
6811     }
6812     g_free (str);
6813     goto done;
6814   }
6815 }
6816
6817 static GstRTSPResult
6818 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
6819 {
6820   GstRTSPResult res = GST_RTSP_OK;
6821   GstRTSPMessage request = { 0 };
6822   GstRTSPMessage response = { 0 };
6823   GList *walk;
6824   gchar *control;
6825
6826   GST_DEBUG_OBJECT (src, "PAUSE...");
6827
6828   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6829     goto open_failed;
6830
6831   if (!(src->methods & GST_RTSP_PAUSE))
6832     goto not_supported;
6833
6834   if (src->state == GST_RTSP_STATE_READY)
6835     goto was_paused;
6836
6837   if (!src->conninfo.connection || !src->conninfo.connected)
6838     goto no_connection;
6839
6840   /* construct a control url */
6841   if (src->control)
6842     control = src->control;
6843   else
6844     control = src->conninfo.url_str;
6845
6846   /* loop over the streams. We might exit the loop early when we could do an
6847    * aggregate control */
6848   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6849     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6850     GstRTSPConnection *conn;
6851     gchar *setup_url;
6852
6853     /* try aggregate control first but do non-aggregate control otherwise */
6854     if (control)
6855       setup_url = control;
6856     else if ((setup_url = stream->conninfo.location) == NULL)
6857       continue;
6858
6859     if (src->conninfo.connection) {
6860       conn = src->conninfo.connection;
6861     } else if (stream->conninfo.connection) {
6862       conn = stream->conninfo.connection;
6863     } else {
6864       continue;
6865     }
6866
6867     if (async)
6868       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6869           ("Sending PAUSE request"));
6870
6871     if ((res =
6872             gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6873                 setup_url)) < 0)
6874       goto create_request_failed;
6875
6876     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6877       goto send_error;
6878
6879     gst_rtsp_message_unset (&request);
6880     gst_rtsp_message_unset (&response);
6881
6882     /* exit early when we did agregate control */
6883     if (control)
6884       break;
6885   }
6886
6887   /* change element states now */
6888   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
6889
6890 no_connection:
6891   src->state = GST_RTSP_STATE_READY;
6892
6893 done:
6894   if (async)
6895     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6896
6897   return res;
6898
6899   /* ERRORS */
6900 open_failed:
6901   {
6902     GST_DEBUG_OBJECT (src, "failed to open stream");
6903     goto done;
6904   }
6905 not_supported:
6906   {
6907     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6908     goto done;
6909   }
6910 was_paused:
6911   {
6912     GST_DEBUG_OBJECT (src, "we were already PAUSED");
6913     goto done;
6914   }
6915 create_request_failed:
6916   {
6917     gchar *str = gst_rtsp_strresult (res);
6918
6919     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6920         ("Could not create request. (%s)", str));
6921     g_free (str);
6922     goto done;
6923   }
6924 send_error:
6925   {
6926     gchar *str = gst_rtsp_strresult (res);
6927
6928     gst_rtsp_message_unset (&request);
6929     if (res != GST_RTSP_EINTR) {
6930       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6931           ("Could not send message. (%s)", str));
6932     } else {
6933       GST_WARNING_OBJECT (src, "PAUSE interrupted");
6934     }
6935     g_free (str);
6936     goto done;
6937   }
6938 }
6939
6940 static void
6941 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6942 {
6943   GstRTSPSrc *rtspsrc;
6944
6945   rtspsrc = GST_RTSPSRC (bin);
6946
6947   switch (GST_MESSAGE_TYPE (message)) {
6948     case GST_MESSAGE_EOS:
6949       gst_message_unref (message);
6950       break;
6951     case GST_MESSAGE_ELEMENT:
6952     {
6953       const GstStructure *s = gst_message_get_structure (message);
6954
6955       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6956         gboolean ignore_timeout;
6957
6958         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6959
6960         GST_OBJECT_LOCK (rtspsrc);
6961         ignore_timeout = rtspsrc->ignore_timeout;
6962         rtspsrc->ignore_timeout = TRUE;
6963         GST_OBJECT_UNLOCK (rtspsrc);
6964
6965         /* we only act on the first udp timeout message, others are irrelevant
6966          * and can be ignored. */
6967         if (!ignore_timeout)
6968           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
6969         /* eat and free */
6970         gst_message_unref (message);
6971         return;
6972       }
6973       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6974       break;
6975     }
6976     case GST_MESSAGE_ERROR:
6977     {
6978       GstObject *udpsrc;
6979       GstRTSPStream *stream;
6980       GstFlowReturn ret;
6981
6982       udpsrc = GST_MESSAGE_SRC (message);
6983
6984       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6985           GST_ELEMENT_NAME (udpsrc));
6986
6987       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6988       if (!stream)
6989         goto forward;
6990
6991       /* we ignore the RTCP udpsrc */
6992       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6993         goto done;
6994
6995       /* if we get error messages from the udp sources, that's not a problem as
6996        * long as not all of them error out. We also don't really know what the
6997        * problem is, the message does not give enough detail... */
6998       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6999       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7000       if (ret != GST_FLOW_OK)
7001         goto forward;
7002
7003     done:
7004       gst_message_unref (message);
7005       break;
7006
7007     forward:
7008       /* fatal but not our message, forward */
7009       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7010       break;
7011     }
7012     default:
7013     {
7014       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7015       break;
7016     }
7017   }
7018 }
7019
7020 /* the thread where everything happens */
7021 static void
7022 gst_rtspsrc_thread (GstRTSPSrc * src)
7023 {
7024   gint cmd;
7025
7026   GST_OBJECT_LOCK (src);
7027   cmd = src->pending_cmd;
7028   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7029       || cmd == CMD_LOOP || cmd == CMD_OPEN)
7030     src->pending_cmd = CMD_LOOP;
7031   else
7032     src->pending_cmd = CMD_WAIT;
7033   GST_DEBUG_OBJECT (src, "got command %d", cmd);
7034
7035   /* we got the message command, so ensure communication is possible again */
7036   gst_rtspsrc_connection_flush (src, FALSE);
7037
7038   src->busy_cmd = cmd;
7039   GST_OBJECT_UNLOCK (src);
7040
7041   switch (cmd) {
7042     case CMD_OPEN:
7043       gst_rtspsrc_open (src, TRUE);
7044       break;
7045     case CMD_PLAY:
7046       gst_rtspsrc_play (src, &src->segment, TRUE);
7047       break;
7048     case CMD_PAUSE:
7049       gst_rtspsrc_pause (src, TRUE);
7050       break;
7051     case CMD_CLOSE:
7052       gst_rtspsrc_close (src, TRUE, FALSE);
7053       break;
7054     case CMD_LOOP:
7055       gst_rtspsrc_loop (src);
7056       break;
7057     case CMD_RECONNECT:
7058       gst_rtspsrc_reconnect (src, FALSE);
7059       break;
7060     default:
7061       break;
7062   }
7063
7064   GST_OBJECT_LOCK (src);
7065   /* and go back to sleep */
7066   if (src->pending_cmd == CMD_WAIT) {
7067     if (src->task)
7068       gst_task_pause (src->task);
7069   }
7070   /* reset waiting */
7071   src->busy_cmd = CMD_WAIT;
7072   GST_OBJECT_UNLOCK (src);
7073 }
7074
7075 static gboolean
7076 gst_rtspsrc_start (GstRTSPSrc * src)
7077 {
7078   GST_DEBUG_OBJECT (src, "starting");
7079
7080   GST_OBJECT_LOCK (src);
7081
7082   src->pending_cmd = CMD_WAIT;
7083
7084   if (src->task == NULL) {
7085     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
7086     if (src->task == NULL)
7087       goto task_error;
7088
7089     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
7090   }
7091   GST_OBJECT_UNLOCK (src);
7092
7093   return TRUE;
7094
7095   /* ERRORS */
7096 task_error:
7097   {
7098     GST_ERROR_OBJECT (src, "failed to create task");
7099     return FALSE;
7100   }
7101 }
7102
7103 static gboolean
7104 gst_rtspsrc_stop (GstRTSPSrc * src)
7105 {
7106   GstTask *task;
7107
7108   GST_DEBUG_OBJECT (src, "stopping");
7109
7110   /* also cancels pending task */
7111   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
7112
7113   GST_OBJECT_LOCK (src);
7114   if ((task = src->task)) {
7115     src->task = NULL;
7116     GST_OBJECT_UNLOCK (src);
7117
7118     gst_task_stop (task);
7119
7120     /* make sure it is not running */
7121     GST_RTSP_STREAM_LOCK (src);
7122     GST_RTSP_STREAM_UNLOCK (src);
7123
7124     /* now wait for the task to finish */
7125     gst_task_join (task);
7126
7127     /* and free the task */
7128     gst_object_unref (GST_OBJECT (task));
7129
7130     GST_OBJECT_LOCK (src);
7131   }
7132   GST_OBJECT_UNLOCK (src);
7133
7134   /* ensure synchronously all is closed and clean */
7135   gst_rtspsrc_close (src, FALSE, TRUE);
7136
7137   return TRUE;
7138 }
7139
7140 static GstStateChangeReturn
7141 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
7142 {
7143   GstRTSPSrc *rtspsrc;
7144   GstStateChangeReturn ret;
7145
7146   rtspsrc = GST_RTSPSRC (element);
7147
7148   switch (transition) {
7149     case GST_STATE_CHANGE_NULL_TO_READY:
7150       if (!gst_rtspsrc_start (rtspsrc))
7151         goto start_failed;
7152       break;
7153     case GST_STATE_CHANGE_READY_TO_PAUSED:
7154       /* init some state */
7155       rtspsrc->cur_protocols = rtspsrc->protocols;
7156       /* first attempt, don't ignore timeouts */
7157       rtspsrc->ignore_timeout = FALSE;
7158       rtspsrc->open_error = FALSE;
7159       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
7160       break;
7161     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7162       set_manager_buffer_mode (rtspsrc);
7163       /* fall-through */
7164     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7165       /* unblock the tcp tasks and make the loop waiting */
7166       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
7167         /* make sure it is waiting before we send PAUSE or PLAY below */
7168         GST_RTSP_STREAM_LOCK (rtspsrc);
7169         GST_RTSP_STREAM_UNLOCK (rtspsrc);
7170       }
7171       break;
7172     case GST_STATE_CHANGE_PAUSED_TO_READY:
7173       break;
7174     default:
7175       break;
7176   }
7177
7178   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7179   if (ret == GST_STATE_CHANGE_FAILURE)
7180     goto done;
7181
7182   switch (transition) {
7183     case GST_STATE_CHANGE_NULL_TO_READY:
7184       ret = GST_STATE_CHANGE_SUCCESS;
7185       break;
7186     case GST_STATE_CHANGE_READY_TO_PAUSED:
7187       ret = GST_STATE_CHANGE_NO_PREROLL;
7188       break;
7189     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7190       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7191       ret = GST_STATE_CHANGE_SUCCESS;
7192       break;
7193     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7194       /* send pause request and keep the idle task around */
7195       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7196       ret = GST_STATE_CHANGE_NO_PREROLL;
7197       break;
7198     case GST_STATE_CHANGE_PAUSED_TO_READY:
7199       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7200       ret = GST_STATE_CHANGE_SUCCESS;
7201       break;
7202     case GST_STATE_CHANGE_READY_TO_NULL:
7203       gst_rtspsrc_stop (rtspsrc);
7204       ret = GST_STATE_CHANGE_SUCCESS;
7205       break;
7206     default:
7207       break;
7208   }
7209
7210 done:
7211   return ret;
7212
7213 start_failed:
7214   {
7215     GST_DEBUG_OBJECT (rtspsrc, "start failed");
7216     return GST_STATE_CHANGE_FAILURE;
7217   }
7218 }
7219
7220 static gboolean
7221 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7222 {
7223   gboolean res;
7224   GstRTSPSrc *rtspsrc;
7225
7226   rtspsrc = GST_RTSPSRC (element);
7227
7228   if (GST_EVENT_IS_DOWNSTREAM (event)) {
7229     res = gst_rtspsrc_push_event (rtspsrc, event);
7230   } else {
7231     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7232   }
7233
7234   return res;
7235 }
7236
7237
7238 /*** GSTURIHANDLER INTERFACE *************************************************/
7239
7240 static GstURIType
7241 gst_rtspsrc_uri_get_type (GType type)
7242 {
7243   return GST_URI_SRC;
7244 }
7245
7246 static const gchar *const *
7247 gst_rtspsrc_uri_get_protocols (GType type)
7248 {
7249   static const gchar *protocols[] =
7250       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7251     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7252   };
7253
7254   return protocols;
7255 }
7256
7257 static gchar *
7258 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7259 {
7260   GstRTSPSrc *src = GST_RTSPSRC (handler);
7261
7262   /* FIXME: make thread-safe */
7263   return g_strdup (src->conninfo.location);
7264 }
7265
7266 static gboolean
7267 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7268     GError ** error)
7269 {
7270   GstRTSPSrc *src;
7271   GstRTSPResult res;
7272   GstRTSPUrl *newurl = NULL;
7273   GstSDPMessage *sdp = NULL;
7274
7275   src = GST_RTSPSRC (handler);
7276
7277   /* same URI, we're fine */
7278   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7279     goto was_ok;
7280
7281   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7282     if ((res = gst_sdp_message_new (&sdp) < 0))
7283       goto sdp_failed;
7284
7285     GST_DEBUG_OBJECT (src, "parsing SDP message");
7286     if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7287       goto invalid_sdp;
7288   } else {
7289     /* try to parse */
7290     GST_DEBUG_OBJECT (src, "parsing URI");
7291     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7292       goto parse_error;
7293   }
7294
7295   /* if worked, free previous and store new url object along with the original
7296    * location. */
7297   GST_DEBUG_OBJECT (src, "configuring URI");
7298   g_free (src->conninfo.location);
7299   src->conninfo.location = g_strdup (uri);
7300   gst_rtsp_url_free (src->conninfo.url);
7301   src->conninfo.url = newurl;
7302   g_free (src->conninfo.url_str);
7303   if (newurl)
7304     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7305   else
7306     src->conninfo.url_str = NULL;
7307
7308   if (src->sdp)
7309     gst_sdp_message_free (src->sdp);
7310   src->sdp = sdp;
7311   src->from_sdp = sdp != NULL;
7312
7313   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7314   GST_DEBUG_OBJECT (src, "request uri is: %s",
7315       GST_STR_NULL (src->conninfo.url_str));
7316
7317   return TRUE;
7318
7319   /* Special cases */
7320 was_ok:
7321   {
7322     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7323     return TRUE;
7324   }
7325 sdp_failed:
7326   {
7327     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7328     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7329         "Could not create SDP");
7330     return FALSE;
7331   }
7332 invalid_sdp:
7333   {
7334     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7335         GST_STR_NULL (uri));
7336     gst_sdp_message_free (sdp);
7337     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7338         "Invalid SDP");
7339     return FALSE;
7340   }
7341 parse_error:
7342   {
7343     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7344         GST_STR_NULL (uri), res);
7345     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7346         "Invalid RTSP URI");
7347     return FALSE;
7348   }
7349 }
7350
7351 static void
7352 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7353 {
7354   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7355
7356   iface->get_type = gst_rtspsrc_uri_get_type;
7357   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7358   iface->get_uri = gst_rtspsrc_uri_get_uri;
7359   iface->set_uri = gst_rtspsrc_uri_set_uri;
7360 }