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