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