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