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