rtspsrc: Fix SRTP + RTX, auth access, a leak, and an invalid memory access.
[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   gsize size;
1862   guchar *data;
1863   GstMIKEYMessage *msg;
1864   const GstMIKEYPayload *payload;
1865   const gchar *srtp_cipher;
1866   const gchar *srtp_auth;
1867
1868   {
1869     gchar *orig_value;
1870     gchar *p, *kmpid;
1871
1872     p = orig_value = g_strdup (keymgmt);
1873
1874     SKIP_SPACES (p);
1875     if (*p == '\0') {
1876       g_free (orig_value);
1877       return FALSE;
1878     }
1879
1880     PARSE_STRING (p, " ", kmpid);
1881     if (kmpid == NULL || !g_str_equal (kmpid, "mikey")) {
1882       g_free (orig_value);
1883       return FALSE;
1884     }
1885     data = g_base64_decode (p, &size);
1886
1887     g_free (orig_value);        /* Don't need this any more */
1888   }
1889
1890   if (data == NULL)
1891     return FALSE;
1892
1893   msg = gst_mikey_message_new_from_data (data, size, NULL, NULL);
1894   g_free (data);
1895   if (msg == NULL)
1896     return FALSE;
1897
1898   srtp_cipher = "aes-128-icm";
1899   srtp_auth = "hmac-sha1-80";
1900
1901   /* check the Security policy if any */
1902   if ((payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, 0))) {
1903     GstMIKEYPayloadSP *p = (GstMIKEYPayloadSP *) payload;
1904     guint len, i;
1905
1906     if (p->proto != GST_MIKEY_SEC_PROTO_SRTP)
1907       goto done;
1908
1909     len = gst_mikey_payload_sp_get_n_params (payload);
1910     for (i = 0; i < len; i++) {
1911       const GstMIKEYPayloadSPParam *param =
1912           gst_mikey_payload_sp_get_param (payload, i);
1913
1914       switch (param->type) {
1915         case GST_MIKEY_SP_SRTP_ENC_ALG:
1916           switch (param->val[0]) {
1917             case 0:
1918               srtp_cipher = "null";
1919               break;
1920             case 2:
1921             case 1:
1922               srtp_cipher = "aes-128-icm";
1923               break;
1924             default:
1925               break;
1926           }
1927           break;
1928         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
1929           switch (param->val[0]) {
1930             case AES_128_KEY_LEN:
1931               srtp_cipher = "aes-128-icm";
1932               break;
1933             case AES_256_KEY_LEN:
1934               srtp_cipher = "aes-256-icm";
1935               break;
1936             default:
1937               break;
1938           }
1939           break;
1940         case GST_MIKEY_SP_SRTP_AUTH_ALG:
1941           switch (param->val[0]) {
1942             case 0:
1943               srtp_auth = "null";
1944               break;
1945             case 2:
1946             case 1:
1947               srtp_auth = "hmac-sha1-80";
1948               break;
1949             default:
1950               break;
1951           }
1952           break;
1953         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
1954           switch (param->val[0]) {
1955             case HMAC_32_KEY_LEN:
1956               srtp_auth = "hmac-sha1-32";
1957               break;
1958             case HMAC_80_KEY_LEN:
1959               srtp_auth = "hmac-sha1-80";
1960               break;
1961             default:
1962               break;
1963           }
1964           break;
1965         case GST_MIKEY_SP_SRTP_SRTP_ENC:
1966           break;
1967         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
1968           break;
1969         default:
1970           break;
1971       }
1972     }
1973   }
1974
1975   if (!(payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_KEMAC, 0)))
1976     goto done;
1977   else {
1978     GstMIKEYPayloadKEMAC *p = (GstMIKEYPayloadKEMAC *) payload;
1979     const GstMIKEYPayload *sub;
1980     GstMIKEYPayloadKeyData *pkd;
1981     GstBuffer *buf;
1982
1983     if (p->enc_alg != GST_MIKEY_ENC_NULL || p->mac_alg != GST_MIKEY_MAC_NULL)
1984       goto done;
1985
1986     if (!(sub = gst_mikey_payload_kemac_get_sub (payload, 0)))
1987       goto done;
1988
1989     if (sub->type != GST_MIKEY_PT_KEY_DATA)
1990       goto done;
1991
1992     pkd = (GstMIKEYPayloadKeyData *) sub;
1993     buf =
1994         gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1995         pkd->key_len);
1996     gst_caps_set_simple (caps, "srtp-key", GST_TYPE_BUFFER, buf, NULL);
1997     gst_buffer_unref (buf);
1998   }
1999
2000   gst_caps_set_simple (caps,
2001       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
2002       "srtp-auth", G_TYPE_STRING, srtp_auth,
2003       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
2004       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
2005
2006   res = TRUE;
2007 done:
2008   gst_mikey_message_unref (msg);
2009
2010   return res;
2011 }
2012
2013 /*
2014  * Mapping SDP attributes to caps
2015  *
2016  * prepend 'a-' to IANA registered sdp attributes names
2017  * (ie: not prefixed with 'x-') in order to avoid
2018  * collision with gstreamer standard caps properties names
2019  */
2020 static void
2021 gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
2022 {
2023   if (attributes->len > 0) {
2024     GstStructure *s;
2025     guint i;
2026
2027     s = gst_caps_get_structure (caps, 0);
2028
2029     for (i = 0; i < attributes->len; i++) {
2030       GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
2031       gchar *tofree, *key;
2032
2033       key = attr->key;
2034
2035       /* skip some of the attribute we already handle */
2036       if (!strcmp (key, "fmtp"))
2037         continue;
2038       if (!strcmp (key, "rtpmap"))
2039         continue;
2040       if (!strcmp (key, "control"))
2041         continue;
2042       if (!strcmp (key, "range"))
2043         continue;
2044       if (!strcmp (key, "framesize"))
2045         continue;
2046       if (g_str_equal (key, "key-mgmt")) {
2047         parse_keymgmt (attr->value, caps);
2048         continue;
2049       }
2050
2051       /* string must be valid UTF8 */
2052       if (!g_utf8_validate (attr->value, -1, NULL))
2053         continue;
2054
2055       if (!g_str_has_prefix (key, "x-"))
2056         tofree = key = g_strdup_printf ("a-%s", key);
2057       else
2058         tofree = NULL;
2059
2060       GST_DEBUG ("adding caps: %s=%s", key, attr->value);
2061       gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
2062       g_free (tofree);
2063     }
2064   }
2065 }
2066
2067 static const gchar *
2068 rtsp_get_attribute_for_pt (const GstSDPMedia * media, const gchar * name,
2069     gint pt)
2070 {
2071   guint i;
2072
2073   for (i = 0;; i++) {
2074     const gchar *attr;
2075     gint val;
2076
2077     if ((attr = gst_sdp_media_get_attribute_val_n (media, name, i)) == NULL)
2078       break;
2079
2080     if (sscanf (attr, "%d ", &val) != 1)
2081       continue;
2082
2083     if (val == pt)
2084       return attr;
2085   }
2086   return NULL;
2087 }
2088
2089 /*
2090  *  Mapping of caps to and from SDP fields:
2091  *
2092  *   a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
2093  *   a=framesize:<payload> <width>-<height>
2094  *   a=fmtp:<payload> <param>[=<value>];...
2095  */
2096 static GstCaps *
2097 gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
2098 {
2099   GstCaps *caps;
2100   const gchar *rtpmap;
2101   const gchar *fmtp;
2102   const gchar *framesize;
2103   gchar *name = NULL;
2104   gint rate = -1;
2105   gchar *params = NULL;
2106   gchar *tmp;
2107   GstStructure *s;
2108   gint payload = 0;
2109   gboolean ret;
2110
2111   /* get and parse rtpmap */
2112   rtpmap = rtsp_get_attribute_for_pt (media, "rtpmap", pt);
2113
2114   if (rtpmap) {
2115     ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, &params);
2116     if (!ret) {
2117       g_warning ("error parsing rtpmap, ignoring");
2118       rtpmap = NULL;
2119     }
2120   }
2121   /* dynamic payloads need rtpmap or we fail */
2122   if (rtpmap == NULL && pt >= 96)
2123     goto no_rtpmap;
2124
2125   /* check if we have a rate, if not, we need to look up the rate from the
2126    * default rates based on the payload types. */
2127   if (rate == -1) {
2128     const GstRTPPayloadInfo *info;
2129
2130     if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
2131       /* dynamic types, use media and encoding_name */
2132       tmp = g_ascii_strdown (media->media, -1);
2133       info = gst_rtp_payload_info_for_name (tmp, name);
2134       g_free (tmp);
2135     } else {
2136       /* static types, use payload type */
2137       info = gst_rtp_payload_info_for_pt (pt);
2138     }
2139
2140     if (info) {
2141       if ((rate = info->clock_rate) == 0)
2142         rate = -1;
2143     }
2144     /* we fail if we cannot find one */
2145     if (rate == -1)
2146       goto no_rate;
2147   }
2148
2149   tmp = g_ascii_strdown (media->media, -1);
2150   caps = gst_caps_new_simple ("application/x-unknown",
2151       "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
2152   g_free (tmp);
2153   s = gst_caps_get_structure (caps, 0);
2154
2155   gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
2156
2157   /* encoding name must be upper case */
2158   if (name != NULL) {
2159     tmp = g_ascii_strup (name, -1);
2160     gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
2161     g_free (tmp);
2162   }
2163
2164   /* params must be lower case */
2165   if (params != NULL) {
2166     tmp = g_ascii_strdown (params, -1);
2167     gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
2168     g_free (tmp);
2169   }
2170
2171   /* parse optional fmtp: field */
2172   if ((fmtp = rtsp_get_attribute_for_pt (media, "fmtp", pt))) {
2173     gchar *p;
2174     gint payload = 0;
2175
2176     p = (gchar *) fmtp;
2177
2178     /* p is now of the format <payload> <param>[=<value>];... */
2179     PARSE_INT (p, " ", payload);
2180     if (payload != -1 && payload == pt) {
2181       gchar **pairs;
2182       gint i;
2183
2184       /* <param>[=<value>] are separated with ';' */
2185       pairs = g_strsplit (p, ";", 0);
2186       for (i = 0; pairs[i]; i++) {
2187         gchar *valpos;
2188         const gchar *val, *key;
2189         gint j;
2190         const gchar *reserved_keys[] =
2191             { "media", "payload", "clock-rate", "encoding-name",
2192           "encoding-params"
2193         };
2194
2195         /* the key may not have a '=', the value can have other '='s */
2196         valpos = strstr (pairs[i], "=");
2197         if (valpos) {
2198           /* we have a '=' and thus a value, remove the '=' with \0 */
2199           *valpos = '\0';
2200           /* value is everything between '=' and ';'. We split the pairs at ;
2201            * boundaries so we can take the remainder of the value. Some servers
2202            * put spaces around the value which we strip off here. Alternatively
2203            * we could strip those spaces in the depayloaders should these spaces
2204            * actually carry any meaning in the future. */
2205           val = g_strstrip (valpos + 1);
2206         } else {
2207           /* simple <param>;.. is translated into <param>=1;... */
2208           val = "1";
2209         }
2210         /* strip the key of spaces, convert key to lowercase but not the value. */
2211         key = g_strstrip (pairs[i]);
2212
2213         /* skip keys from the fmtp, which we already use ourselves for the
2214          * caps. Some software is adding random things like clock-rate into
2215          * the fmtp, and we would otherwise here set a string-typed clock-rate
2216          * in the caps... and thus fail to create valid RTP caps
2217          */
2218         for (j = 0; j < G_N_ELEMENTS (reserved_keys); j++) {
2219           if (g_ascii_strcasecmp (reserved_keys[j], key) == 0) {
2220             key = "";
2221             break;
2222           }
2223         }
2224
2225         if (strlen (key) > 1) {
2226           tmp = g_ascii_strdown (key, -1);
2227           gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
2228           g_free (tmp);
2229         }
2230       }
2231       g_strfreev (pairs);
2232     }
2233   }
2234
2235   /* parse framesize: field */
2236   if ((framesize = gst_sdp_media_get_attribute_val (media, "framesize"))) {
2237     gchar *p;
2238
2239     /* p is now of the format <payload> <width>-<height> */
2240     p = (gchar *) framesize;
2241
2242     PARSE_INT (p, " ", payload);
2243     if (payload != -1 && payload == pt) {
2244       gst_structure_set (s, "a-framesize", G_TYPE_STRING, p, NULL);
2245     }
2246   }
2247   return caps;
2248
2249   /* ERRORS */
2250 no_rtpmap:
2251   {
2252     g_warning ("rtpmap type not given for dynamic payload %d", pt);
2253     return NULL;
2254   }
2255 no_rate:
2256   {
2257     g_warning ("rate unknown for payload type %d", pt);
2258     return NULL;
2259   }
2260 }
2261
2262 static gboolean
2263 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
2264     gint * rtpport, gint * rtcpport)
2265 {
2266   GstRTSPSrc *src;
2267   GstStateChangeReturn ret;
2268   GstElement *udpsrc0, *udpsrc1;
2269   gint tmp_rtp, tmp_rtcp;
2270   guint count;
2271   const gchar *host;
2272
2273   src = stream->parent;
2274
2275   udpsrc0 = NULL;
2276   udpsrc1 = NULL;
2277   count = 0;
2278
2279   /* Start at next port */
2280   tmp_rtp = src->next_port_num;
2281
2282   if (stream->is_ipv6)
2283     host = "udp://[::0]";
2284   else
2285     host = "udp://0.0.0.0";
2286
2287   /* try to allocate 2 UDP ports, the RTP port should be an even
2288    * number and the RTCP port should be the next (uneven) port */
2289 again:
2290
2291   if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
2292       tmp_rtp >= src->client_port_range.max)
2293     goto no_ports;
2294
2295   udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2296   if (udpsrc0 == NULL)
2297     goto no_udp_protocol;
2298   g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
2299
2300   if (src->udp_buffer_size != 0)
2301     g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
2302         NULL);
2303
2304   ret = gst_element_set_state (udpsrc0, GST_STATE_READY);
2305   if (ret == GST_STATE_CHANGE_FAILURE) {
2306     if (tmp_rtp != 0) {
2307       GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
2308
2309       tmp_rtp += 2;
2310       if (++count > src->retry)
2311         goto no_ports;
2312
2313       GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2314       gst_element_set_state (udpsrc0, GST_STATE_NULL);
2315       gst_object_unref (udpsrc0);
2316       udpsrc0 = NULL;
2317
2318       GST_DEBUG_OBJECT (src, "retry %d", count);
2319       goto again;
2320     }
2321     goto no_udp_protocol;
2322   }
2323
2324   g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
2325   GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
2326
2327   /* check if port is even */
2328   if ((tmp_rtp & 0x01) != 0) {
2329     /* port not even, close and allocate another */
2330     if (++count > src->retry)
2331       goto no_ports;
2332
2333     GST_DEBUG_OBJECT (src, "RTP port not even");
2334
2335     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2336     gst_element_set_state (udpsrc0, GST_STATE_NULL);
2337     gst_object_unref (udpsrc0);
2338     udpsrc0 = NULL;
2339
2340     GST_DEBUG_OBJECT (src, "retry %d", count);
2341     tmp_rtp++;
2342     goto again;
2343   }
2344
2345   /* allocate port+1 for RTCP now */
2346   udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2347   if (udpsrc1 == NULL)
2348     goto no_udp_rtcp_protocol;
2349
2350   /* set port */
2351   tmp_rtcp = tmp_rtp + 1;
2352   if (src->client_port_range.max > 0 && tmp_rtcp > src->client_port_range.max)
2353     goto no_ports;
2354
2355   g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
2356
2357   GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
2358   ret = gst_element_set_state (udpsrc1, GST_STATE_READY);
2359   /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
2360   if (ret == GST_STATE_CHANGE_FAILURE) {
2361     GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
2362
2363     if (++count > src->retry)
2364       goto no_ports;
2365
2366     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2367     gst_element_set_state (udpsrc0, GST_STATE_NULL);
2368     gst_object_unref (udpsrc0);
2369     udpsrc0 = NULL;
2370
2371     GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
2372     gst_element_set_state (udpsrc1, GST_STATE_NULL);
2373     gst_object_unref (udpsrc1);
2374     udpsrc1 = NULL;
2375
2376     tmp_rtp += 2;
2377     GST_DEBUG_OBJECT (src, "retry %d", count);
2378     goto again;
2379   }
2380
2381   /* all fine, do port check */
2382   g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
2383   g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
2384
2385   /* this should not happen... */
2386   if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
2387     goto port_error;
2388
2389   /* we keep these elements, we configure all in configure_transport when the
2390    * server told us to really use the UDP ports. */
2391   stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
2392   stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
2393   gst_element_set_locked_state (stream->udpsrc[0], TRUE);
2394   gst_element_set_locked_state (stream->udpsrc[1], TRUE);
2395
2396   /* keep track of next available port number when we have a range
2397    * configured */
2398   if (src->next_port_num != 0)
2399     src->next_port_num = tmp_rtcp + 1;
2400
2401   return TRUE;
2402
2403   /* ERRORS */
2404 no_udp_protocol:
2405   {
2406     GST_DEBUG_OBJECT (src, "could not get UDP source");
2407     goto cleanup;
2408   }
2409 no_ports:
2410   {
2411     GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
2412         count);
2413     goto cleanup;
2414   }
2415 no_udp_rtcp_protocol:
2416   {
2417     GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
2418     goto cleanup;
2419   }
2420 port_error:
2421   {
2422     GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
2423         tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
2424     goto cleanup;
2425   }
2426 cleanup:
2427   {
2428     if (udpsrc0) {
2429       gst_element_set_state (udpsrc0, GST_STATE_NULL);
2430       gst_object_unref (udpsrc0);
2431     }
2432     if (udpsrc1) {
2433       gst_element_set_state (udpsrc1, GST_STATE_NULL);
2434       gst_object_unref (udpsrc1);
2435     }
2436     return FALSE;
2437   }
2438 }
2439
2440 static void
2441 gst_rtspsrc_set_state (GstRTSPSrc * src, GstState state)
2442 {
2443   GList *walk;
2444
2445   if (src->manager)
2446     gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
2447
2448   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2449     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2450     gint i;
2451
2452     for (i = 0; i < 2; i++) {
2453       if (stream->udpsrc[i])
2454         gst_element_set_state (stream->udpsrc[i], state);
2455     }
2456   }
2457 }
2458
2459 static void
2460 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
2461 {
2462   GstEvent *event;
2463   gint cmd;
2464   GstState state;
2465
2466   if (flush) {
2467     event = gst_event_new_flush_start ();
2468     GST_DEBUG_OBJECT (src, "start flush");
2469     cmd = CMD_WAIT;
2470     state = GST_STATE_PAUSED;
2471   } else {
2472     event = gst_event_new_flush_stop (FALSE);
2473     GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
2474     cmd = CMD_LOOP;
2475     if (playing)
2476       state = GST_STATE_PLAYING;
2477     else
2478       state = GST_STATE_PAUSED;
2479   }
2480   gst_rtspsrc_push_event (src, event);
2481   gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
2482   gst_rtspsrc_set_state (src, state);
2483 }
2484
2485 static GstRTSPResult
2486 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
2487     GstRTSPMessage * message, GTimeVal * timeout)
2488 {
2489   GstRTSPResult ret;
2490
2491   if (conn)
2492     ret = gst_rtsp_connection_send (conn, message, timeout);
2493   else
2494     ret = GST_RTSP_ERROR;
2495
2496   return ret;
2497 }
2498
2499 static GstRTSPResult
2500 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
2501     GstRTSPMessage * message, GTimeVal * timeout)
2502 {
2503   GstRTSPResult ret;
2504
2505   if (conn)
2506     ret = gst_rtsp_connection_receive (conn, message, timeout);
2507   else
2508     ret = GST_RTSP_ERROR;
2509
2510   return ret;
2511 }
2512
2513 static void
2514 gst_rtspsrc_get_position (GstRTSPSrc * src)
2515 {
2516   GstQuery *query;
2517   GList *walk;
2518
2519   query = gst_query_new_position (GST_FORMAT_TIME);
2520   /*  should be known somewhere down the stream (e.g. jitterbuffer) */
2521   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2522     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2523     GstFormat fmt;
2524     gint64 pos;
2525
2526     if (stream->srcpad) {
2527       if (gst_pad_query (stream->srcpad, query)) {
2528         gst_query_parse_position (query, &fmt, &pos);
2529         GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
2530             GST_TIME_ARGS (pos));
2531         src->last_pos = pos;
2532         goto out;
2533       }
2534     }
2535   }
2536
2537   src->last_pos = 0;
2538
2539 out:
2540
2541   gst_query_unref (query);
2542 }
2543
2544 static gboolean
2545 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
2546 {
2547   gdouble rate;
2548   GstFormat format;
2549   GstSeekFlags flags;
2550   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2551   gint64 cur, stop;
2552   gboolean flush, skip;
2553   gboolean update;
2554   gboolean playing;
2555   GstSegment seeksegment = { 0, };
2556   GList *walk;
2557
2558   if (event) {
2559     GST_DEBUG_OBJECT (src, "doing seek with event");
2560
2561     gst_event_parse_seek (event, &rate, &format, &flags,
2562         &cur_type, &cur, &stop_type, &stop);
2563
2564     /* no negative rates yet */
2565     if (rate < 0.0)
2566       goto negative_rate;
2567
2568     /* we need TIME format */
2569     if (format != src->segment.format)
2570       goto no_format;
2571   } else {
2572     GST_DEBUG_OBJECT (src, "doing seek without event");
2573     flags = 0;
2574     cur_type = GST_SEEK_TYPE_SET;
2575     stop_type = GST_SEEK_TYPE_SET;
2576   }
2577
2578   /* get flush flag */
2579   flush = flags & GST_SEEK_FLAG_FLUSH;
2580   skip = flags & GST_SEEK_FLAG_SKIP;
2581
2582   /* now we need to make sure the streaming thread is stopped. We do this by
2583    * either sending a FLUSH_START event downstream which will cause the
2584    * streaming thread to stop with a WRONG_STATE.
2585    * For a non-flushing seek we simply pause the task, which will happen as soon
2586    * as it completes one iteration (and thus might block when the sink is
2587    * blocking in preroll). */
2588   if (flush) {
2589     GST_DEBUG_OBJECT (src, "starting flush");
2590     gst_rtspsrc_flush (src, TRUE, FALSE);
2591   } else {
2592     if (src->task) {
2593       gst_task_pause (src->task);
2594     }
2595   }
2596
2597   /* we should now be able to grab the streaming thread because we stopped it
2598    * with the above flush/pause code */
2599   GST_RTSP_STREAM_LOCK (src);
2600
2601   GST_DEBUG_OBJECT (src, "stopped streaming");
2602
2603   /* stop flushing the rtsp connection so we can send PAUSE/PLAY below */
2604   gst_rtspsrc_connection_flush (src, FALSE);
2605
2606   /* copy segment, we need this because we still need the old
2607    * segment when we close the current segment. */
2608   memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2609
2610   /* configure the seek parameters in the seeksegment. We will then have the
2611    * right values in the segment to perform the seek */
2612   if (event) {
2613     GST_DEBUG_OBJECT (src, "configuring seek");
2614     gst_segment_do_seek (&seeksegment, rate, format, flags,
2615         cur_type, cur, stop_type, stop, &update);
2616   }
2617
2618   /* figure out the last position we need to play. If it's configured (stop !=
2619    * -1), use that, else we play until the total duration of the file */
2620   if ((stop = seeksegment.stop) == -1)
2621     stop = seeksegment.duration;
2622
2623   playing = (src->state == GST_RTSP_STATE_PLAYING);
2624
2625   /* if we were playing, pause first */
2626   if (playing) {
2627     /* obtain current position in case seek fails */
2628     gst_rtspsrc_get_position (src);
2629     gst_rtspsrc_pause (src, FALSE);
2630   }
2631   src->skip = skip;
2632
2633   src->state = GST_RTSP_STATE_SEEKING;
2634
2635   /* PLAY will add the range header now. */
2636   src->need_range = TRUE;
2637
2638   /* and continue playing */
2639   if (playing)
2640     gst_rtspsrc_play (src, &seeksegment, FALSE);
2641
2642   /* prepare for streaming again */
2643   if (flush) {
2644     /* if we started flush, we stop now */
2645     GST_DEBUG_OBJECT (src, "stopping flush");
2646     gst_rtspsrc_flush (src, FALSE, playing);
2647   }
2648
2649   /* now we did the seek and can activate the new segment values */
2650   memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2651
2652   /* if we're doing a segment seek, post a SEGMENT_START message */
2653   if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2654     gst_element_post_message (GST_ELEMENT_CAST (src),
2655         gst_message_new_segment_start (GST_OBJECT_CAST (src),
2656             src->segment.format, src->segment.position));
2657   }
2658
2659   /* now create the newsegment */
2660   GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2661       " to %" G_GINT64_FORMAT, src->segment.position, stop);
2662
2663   /* mark discont */
2664   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2665   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2666     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2667     stream->discont = TRUE;
2668   }
2669
2670   GST_RTSP_STREAM_UNLOCK (src);
2671
2672   return TRUE;
2673
2674   /* ERRORS */
2675 negative_rate:
2676   {
2677     GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2678     return FALSE;
2679   }
2680 no_format:
2681   {
2682     GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2683     return FALSE;
2684   }
2685 }
2686
2687 static gboolean
2688 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2689     GstEvent * event)
2690 {
2691   GstRTSPSrc *src;
2692   gboolean res = TRUE;
2693   gboolean forward;
2694
2695   src = GST_RTSPSRC_CAST (parent);
2696
2697   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2698       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2699
2700   switch (GST_EVENT_TYPE (event)) {
2701     case GST_EVENT_SEEK:
2702       res = gst_rtspsrc_perform_seek (src, event);
2703       forward = FALSE;
2704       break;
2705     case GST_EVENT_QOS:
2706     case GST_EVENT_NAVIGATION:
2707     case GST_EVENT_LATENCY:
2708     default:
2709       forward = TRUE;
2710       break;
2711   }
2712   if (forward) {
2713     GstPad *target;
2714
2715     if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2716       res = gst_pad_send_event (target, event);
2717       gst_object_unref (target);
2718     } else {
2719       gst_event_unref (event);
2720     }
2721   } else {
2722     gst_event_unref (event);
2723   }
2724
2725   return res;
2726 }
2727
2728 /* this is the final event function we receive on the internal source pad when
2729  * we deal with TCP connections */
2730 static gboolean
2731 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2732     GstEvent * event)
2733 {
2734   gboolean res;
2735
2736   GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2737
2738   switch (GST_EVENT_TYPE (event)) {
2739     case GST_EVENT_SEEK:
2740     case GST_EVENT_QOS:
2741     case GST_EVENT_NAVIGATION:
2742     case GST_EVENT_LATENCY:
2743     default:
2744       gst_event_unref (event);
2745       res = TRUE;
2746       break;
2747   }
2748   return res;
2749 }
2750
2751 /* this is the final query function we receive on the internal source pad when
2752  * we deal with TCP connections */
2753 static gboolean
2754 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2755     GstQuery * query)
2756 {
2757   GstRTSPSrc *src;
2758   gboolean res = TRUE;
2759
2760   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2761
2762   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2763       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2764
2765   switch (GST_QUERY_TYPE (query)) {
2766     case GST_QUERY_POSITION:
2767     {
2768       /* no idea */
2769       break;
2770     }
2771     case GST_QUERY_DURATION:
2772     {
2773       GstFormat format;
2774
2775       gst_query_parse_duration (query, &format, NULL);
2776
2777       switch (format) {
2778         case GST_FORMAT_TIME:
2779           gst_query_set_duration (query, format, src->segment.duration);
2780           break;
2781         default:
2782           res = FALSE;
2783           break;
2784       }
2785       break;
2786     }
2787     case GST_QUERY_LATENCY:
2788     {
2789       /* we are live with a min latency of 0 and unlimited max latency, this
2790        * result will be updated by the session manager if there is any. */
2791       gst_query_set_latency (query, TRUE, 0, -1);
2792       break;
2793     }
2794     default:
2795       break;
2796   }
2797
2798   return res;
2799 }
2800
2801 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2802 static gboolean
2803 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2804     GstQuery * query)
2805 {
2806   GstRTSPSrc *src;
2807   gboolean res = FALSE;
2808
2809   src = GST_RTSPSRC_CAST (parent);
2810
2811   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2812       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2813
2814   switch (GST_QUERY_TYPE (query)) {
2815     case GST_QUERY_DURATION:
2816     {
2817       GstFormat format;
2818
2819       gst_query_parse_duration (query, &format, NULL);
2820
2821       switch (format) {
2822         case GST_FORMAT_TIME:
2823           gst_query_set_duration (query, format, src->segment.duration);
2824           res = TRUE;
2825           break;
2826         default:
2827           break;
2828       }
2829       break;
2830     }
2831     case GST_QUERY_SEEKING:
2832     {
2833       GstFormat format;
2834
2835       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2836       if (format == GST_FORMAT_TIME) {
2837         gboolean seekable =
2838             src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2839
2840         /* seeking without duration is unlikely */
2841         seekable = seekable && src->seekable && src->segment.duration &&
2842             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2843
2844         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0,
2845             src->segment.duration);
2846         res = TRUE;
2847       }
2848       break;
2849     }
2850     case GST_QUERY_URI:
2851     {
2852       gchar *uri;
2853
2854       uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2855       if (uri != NULL) {
2856         gst_query_set_uri (query, uri);
2857         g_free (uri);
2858         res = TRUE;
2859       }
2860       break;
2861     }
2862     default:
2863     {
2864       GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2865
2866       /* forward the query to the proxy target pad */
2867       if (target) {
2868         res = gst_pad_query (target, query);
2869         gst_object_unref (target);
2870       }
2871       break;
2872     }
2873   }
2874
2875   return res;
2876 }
2877
2878 /* callback for RTCP messages to be sent to the server when operating in TCP
2879  * mode. */
2880 static GstFlowReturn
2881 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2882 {
2883   GstRTSPSrc *src;
2884   GstRTSPStream *stream;
2885   GstFlowReturn res = GST_FLOW_OK;
2886   GstMapInfo map;
2887   guint8 *data;
2888   guint size;
2889   GstRTSPResult ret;
2890   GstRTSPMessage message = { 0 };
2891   GstRTSPConnection *conn;
2892
2893   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2894   src = stream->parent;
2895
2896   gst_buffer_map (buffer, &map, GST_MAP_READ);
2897   size = map.size;
2898   data = map.data;
2899
2900   gst_rtsp_message_init_data (&message, stream->channel[1]);
2901
2902   /* lend the body data to the message */
2903   gst_rtsp_message_take_body (&message, data, size);
2904
2905   if (stream->conninfo.connection)
2906     conn = stream->conninfo.connection;
2907   else
2908     conn = src->conninfo.connection;
2909
2910   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2911   ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2912   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2913
2914   /* and steal it away again because we will free it when unreffing the
2915    * buffer */
2916   gst_rtsp_message_steal_body (&message, &data, &size);
2917   gst_rtsp_message_unset (&message);
2918
2919   gst_buffer_unmap (buffer, &map);
2920   gst_buffer_unref (buffer);
2921
2922   return res;
2923 }
2924
2925 static GstPadProbeReturn
2926 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2927 {
2928   GstRTSPSrc *src = user_data;
2929
2930   GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2931       GST_DEBUG_PAD_NAME (pad));
2932
2933   /* activate the streams */
2934   GST_OBJECT_LOCK (src);
2935   if (!src->need_activate)
2936     goto was_ok;
2937
2938   src->need_activate = FALSE;
2939   GST_OBJECT_UNLOCK (src);
2940
2941   gst_rtspsrc_activate_streams (src);
2942
2943   return GST_PAD_PROBE_OK;
2944
2945 was_ok:
2946   {
2947     GST_OBJECT_UNLOCK (src);
2948     return GST_PAD_PROBE_OK;
2949   }
2950 }
2951
2952 static gboolean
2953 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
2954 {
2955   GstPad *gpad = GST_PAD_CAST (user_data);
2956
2957   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
2958   gst_pad_store_sticky_event (gpad, *event);
2959
2960   return TRUE;
2961 }
2962
2963 /* this callback is called when the session manager generated a new src pad with
2964  * payloaded RTP packets. We simply ghost the pad here. */
2965 static void
2966 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2967 {
2968   gchar *name;
2969   GstPadTemplate *template;
2970   gint id, ssrc, pt;
2971   GList *ostreams;
2972   GstRTSPStream *stream;
2973   gboolean all_added;
2974
2975   GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2976
2977   GST_RTSP_STATE_LOCK (src);
2978   /* find stream */
2979   name = gst_object_get_name (GST_OBJECT_CAST (pad));
2980   if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2981     goto unknown_stream;
2982
2983   GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2984
2985   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2986   if (stream == NULL)
2987     goto unknown_stream;
2988
2989   /* save SSRC */
2990   stream->ssrc = ssrc;
2991
2992   /* we'll add it later see below */
2993   stream->added = TRUE;
2994
2995   /* check if we added all streams */
2996   all_added = TRUE;
2997   for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
2998     GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
2999
3000     GST_DEBUG_OBJECT (src, "stream %p, container %d, added %d, setup %d",
3001         ostream, ostream->container, ostream->added, ostream->setup);
3002
3003     /* if we find a stream for which we did a setup that is not added, we
3004      * need to wait some more */
3005     if (ostream->setup && !ostream->added) {
3006       all_added = FALSE;
3007       break;
3008     }
3009   }
3010   GST_RTSP_STATE_UNLOCK (src);
3011
3012   /* create a new pad we will use to stream to */
3013   template = gst_static_pad_template_get (&rtptemplate);
3014   stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
3015   gst_object_unref (template);
3016   g_free (name);
3017
3018   gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3019   gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3020   gst_pad_set_active (stream->srcpad, TRUE);
3021   gst_pad_sticky_events_foreach (pad, copy_sticky_events, stream->srcpad);
3022   gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3023
3024   if (all_added) {
3025     GST_DEBUG_OBJECT (src, "We added all streams");
3026     /* when we get here, all stream are added and we can fire the no-more-pads
3027      * signal. */
3028     gst_element_no_more_pads (GST_ELEMENT_CAST (src));
3029   }
3030
3031   return;
3032
3033   /* ERRORS */
3034 unknown_stream:
3035   {
3036     GST_DEBUG_OBJECT (src, "ignoring unknown stream");
3037     GST_RTSP_STATE_UNLOCK (src);
3038     g_free (name);
3039     return;
3040   }
3041 }
3042
3043 static GstCaps *
3044 stream_get_caps_for_pt (GstRTSPStream * stream, guint pt)
3045 {
3046   guint i, len;
3047
3048   len = stream->ptmap->len;
3049   for (i = 0; i < len; i++) {
3050     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3051     if (item->pt == pt)
3052       return item->caps;
3053   }
3054   return NULL;
3055 }
3056
3057 static GstCaps *
3058 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
3059 {
3060   GstRTSPStream *stream;
3061   GstCaps *caps;
3062
3063   GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
3064
3065   GST_RTSP_STATE_LOCK (src);
3066   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
3067   if (!stream)
3068     goto unknown_stream;
3069
3070   if ((caps = stream_get_caps_for_pt (stream, pt)))
3071     gst_caps_ref (caps);
3072   GST_RTSP_STATE_UNLOCK (src);
3073
3074   return caps;
3075
3076 unknown_stream:
3077   {
3078     GST_DEBUG_OBJECT (src, "unknown stream %d", session);
3079     GST_RTSP_STATE_UNLOCK (src);
3080     return NULL;
3081   }
3082 }
3083
3084 static void
3085 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
3086 {
3087   GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
3088
3089   if (stream->eos)
3090     goto was_eos;
3091
3092   stream->eos = TRUE;
3093   gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
3094   return;
3095
3096   /* ERRORS */
3097 was_eos:
3098   {
3099     GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
3100     return;
3101   }
3102 }
3103
3104 static void
3105 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
3106 {
3107   GstRTSPSrc *src = stream->parent;
3108   guint ssrc;
3109
3110   g_object_get (source, "ssrc", &ssrc, NULL);
3111
3112   GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
3113       ssrc, stream->ssrc, stream->id);
3114
3115   if (ssrc == stream->ssrc)
3116     gst_rtspsrc_do_stream_eos (src, stream);
3117 }
3118
3119 static void
3120 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
3121 {
3122   GstRTSPSrc *src = stream->parent;
3123   guint ssrc;
3124
3125   g_object_get (source, "ssrc", &ssrc, NULL);
3126
3127   GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
3128       ssrc, stream->ssrc, stream->id);
3129
3130   if (ssrc == stream->ssrc)
3131     gst_rtspsrc_do_stream_eos (src, stream);
3132 }
3133
3134 static void
3135 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
3136 {
3137   GstRTSPStream *stream;
3138
3139   GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
3140
3141   /* get stream for session */
3142   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
3143   if (stream) {
3144     gst_rtspsrc_do_stream_eos (src, stream);
3145   }
3146 }
3147
3148 static void
3149 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
3150 {
3151   GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
3152       stream->id);
3153 }
3154
3155 static void
3156 set_manager_buffer_mode (GstRTSPSrc * src)
3157 {
3158   GObjectClass *klass;
3159
3160   if (src->manager == NULL)
3161     return;
3162
3163   klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3164
3165   if (!g_object_class_find_property (klass, "buffer-mode"))
3166     return;
3167
3168   if (src->buffer_mode != BUFFER_MODE_AUTO) {
3169     g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
3170
3171     return;
3172   }
3173
3174   GST_DEBUG_OBJECT (src,
3175       "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
3176
3177   if (src->provided_clock) {
3178     GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
3179
3180     if (clock == src->provided_clock) {
3181       GST_DEBUG_OBJECT (src, "selected synced");
3182       g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
3183
3184       if (clock)
3185         gst_object_unref (clock);
3186
3187       return;
3188     }
3189
3190     /* Otherwise fall-through and use another buffer mode */
3191     if (clock)
3192       gst_object_unref (clock);
3193   }
3194
3195   GST_DEBUG_OBJECT (src, "auto buffering mode");
3196   if (src->use_buffering) {
3197     GST_DEBUG_OBJECT (src, "selected buffer");
3198     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
3199   } else {
3200     GST_DEBUG_OBJECT (src, "selected slave");
3201     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
3202   }
3203 }
3204
3205 static GstCaps *
3206 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
3207 {
3208   GST_DEBUG ("request key %u", ssrc);
3209   return gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
3210 }
3211
3212 static GstElement *
3213 request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
3214 {
3215   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3216   if (stream->id != session)
3217     return NULL;
3218
3219   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3220       stream->profile != GST_RTSP_PROFILE_SAVPF)
3221     return NULL;
3222
3223   if (stream->srtpdec == NULL) {
3224     gchar *name;
3225
3226     name = g_strdup_printf ("srtpdec_%u", session);
3227     stream->srtpdec = gst_element_factory_make ("srtpdec", name);
3228     g_free (name);
3229
3230     g_signal_connect (stream->srtpdec, "request-key",
3231         (GCallback) request_key, stream);
3232   }
3233   return gst_object_ref (stream->srtpdec);
3234 }
3235
3236 static GstElement *
3237 request_rtcp_encoder (GstElement * rtpbin, guint session,
3238     GstRTSPStream * stream)
3239 {
3240   gchar *name;
3241   GstPad *pad;
3242
3243   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3244   if (stream->id != session)
3245     return NULL;
3246
3247   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3248       stream->profile != GST_RTSP_PROFILE_SAVPF)
3249     return NULL;
3250
3251   if (stream->srtpenc == NULL) {
3252     GstStructure *s;
3253
3254     name = g_strdup_printf ("srtpenc_%u", session);
3255     stream->srtpenc = gst_element_factory_make ("srtpenc", name);
3256     g_free (name);
3257
3258     /* get RTCP crypto parameters from caps */
3259     s = gst_caps_get_structure (stream->srtcpparams, 0);
3260     if (s) {
3261       GstBuffer *buf;
3262       const gchar *str;
3263       GType ciphertype, authtype;
3264       GValue rtcp_cipher = G_VALUE_INIT, rtcp_auth = G_VALUE_INIT;
3265
3266       ciphertype = g_type_from_name ("GstSrtpCipherType");
3267       authtype = g_type_from_name ("GstSrtpAuthType");
3268       g_value_init (&rtcp_cipher, ciphertype);
3269       g_value_init (&rtcp_auth, authtype);
3270
3271       str = gst_structure_get_string (s, "srtcp-cipher");
3272       gst_value_deserialize (&rtcp_cipher, str);
3273       str = gst_structure_get_string (s, "srtcp-auth");
3274       gst_value_deserialize (&rtcp_auth, str);
3275       gst_structure_get (s, "srtp-key", GST_TYPE_BUFFER, &buf, NULL);
3276
3277       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-cipher",
3278           &rtcp_cipher);
3279       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-auth",
3280           &rtcp_auth);
3281       g_object_set (stream->srtpenc, "key", buf, NULL);
3282
3283       g_value_unset (&rtcp_cipher);
3284       g_value_unset (&rtcp_auth);
3285       gst_buffer_unref (buf);
3286     }
3287   }
3288   name = g_strdup_printf ("rtcp_sink_%d", session);
3289   pad = gst_element_get_request_pad (stream->srtpenc, name);
3290   g_free (name);
3291   gst_object_unref (pad);
3292
3293   return gst_object_ref (stream->srtpenc);
3294 }
3295
3296 static GstElement *
3297 request_aux_receiver (GstElement * rtpbin, guint sessid, GstRTSPSrc * src)
3298 {
3299   GstElement *rtx, *bin;
3300   GstPad *pad;
3301   gchar *name;
3302   GstRTSPStream *stream;
3303
3304   stream = find_stream (src, &sessid, (gpointer) find_stream_by_id);
3305   if (!stream) {
3306     GST_WARNING_OBJECT (src, "Stream %u not found", sessid);
3307     return NULL;
3308   }
3309
3310   GST_INFO_OBJECT (src, "creating retransmision receiver for session %u "
3311       "with map %" GST_PTR_FORMAT, sessid, stream->rtx_pt_map);
3312   bin = gst_bin_new (NULL);
3313   rtx = gst_element_factory_make ("rtprtxreceive", NULL);
3314   g_object_set (rtx, "payload-type-map", stream->rtx_pt_map, NULL);
3315   gst_bin_add (GST_BIN (bin), rtx);
3316
3317   pad = gst_element_get_static_pad (rtx, "src");
3318   name = g_strdup_printf ("src_%u", sessid);
3319   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3320   g_free (name);
3321   gst_object_unref (pad);
3322
3323   pad = gst_element_get_static_pad (rtx, "sink");
3324   name = g_strdup_printf ("sink_%u", sessid);
3325   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3326   g_free (name);
3327   gst_object_unref (pad);
3328
3329   return bin;
3330 }
3331
3332 static void
3333 add_retransmission (GstRTSPSrc * src, GstRTSPTransport * transport)
3334 {
3335   GList *walk;
3336   guint signal_id;
3337   gboolean do_retransmission = FALSE;
3338
3339   if (transport->trans != GST_RTSP_TRANS_RTP)
3340     return;
3341   if (transport->profile != GST_RTSP_PROFILE_AVPF &&
3342       transport->profile != GST_RTSP_PROFILE_SAVPF)
3343     return;
3344
3345   signal_id = g_signal_lookup ("request-aux-receiver",
3346       G_OBJECT_TYPE (src->manager));
3347   /* there's already something connected */
3348   if (g_signal_handler_find (src->manager, G_SIGNAL_MATCH_ID, signal_id, 0,
3349           NULL, NULL, NULL) != 0) {
3350     GST_DEBUG_OBJECT (src, "Not adding RTX AUX element as "
3351         "\"request-aux-receiver\" signal is "
3352         "already used by the application");
3353     return;
3354   }
3355
3356   /* build the retransmission payload type map */
3357   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3358     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3359     gboolean do_retransmission_stream = FALSE;
3360     int i;
3361
3362     if (stream->rtx_pt_map)
3363       gst_structure_free (stream->rtx_pt_map);
3364     stream->rtx_pt_map = gst_structure_new_empty ("application/x-rtp-pt-map");
3365
3366     for (i = 0; i < stream->ptmap->len; i++) {
3367       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3368       GstStructure *s = gst_caps_get_structure (item->caps, 0);
3369       const gchar *encoding;
3370
3371       /* we only care about RTX streams */
3372       if ((encoding = gst_structure_get_string (s, "encoding-name"))
3373           && g_strcmp0 (encoding, "RTX") == 0) {
3374         const gchar *stream_pt_s;
3375         gint rtx_pt;
3376
3377         if (gst_structure_get_int (s, "payload", &rtx_pt)
3378             && (stream_pt_s = gst_structure_get_string (s, "apt"))) {
3379
3380           if (rtx_pt != 0) {
3381             gst_structure_set (stream->rtx_pt_map, stream_pt_s, G_TYPE_UINT,
3382                 rtx_pt, NULL);
3383             do_retransmission_stream = TRUE;
3384           }
3385         }
3386       }
3387     }
3388
3389     if (do_retransmission_stream) {
3390       GST_DEBUG_OBJECT (src, "built retransmission payload map for stream "
3391           "id %i: %" GST_PTR_FORMAT, stream->id, stream->rtx_pt_map);
3392       do_retransmission = TRUE;
3393     } else {
3394       GST_DEBUG_OBJECT (src, "no retransmission payload map for stream "
3395           "id %i", stream->id);
3396       gst_structure_free (stream->rtx_pt_map);
3397       stream->rtx_pt_map = NULL;
3398     }
3399   }
3400
3401   if (do_retransmission) {
3402     GST_DEBUG_OBJECT (src, "Enabling retransmissions");
3403
3404     g_object_set (src->manager, "do-retransmission", TRUE, NULL);
3405
3406     /* enable RFC4588 retransmission handling by setting rtprtxreceive
3407      * as the "aux" element of rtpbin */
3408     g_signal_connect (src->manager, "request-aux-receiver",
3409         (GCallback) request_aux_receiver, src);
3410   } else {
3411     GST_DEBUG_OBJECT (src,
3412         "Not enabling retransmissions as no stream had a retransmission payload map");
3413   }
3414 }
3415
3416 /* try to get and configure a manager */
3417 static gboolean
3418 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
3419     GstRTSPTransport * transport)
3420 {
3421   const gchar *manager;
3422   gchar *name;
3423   GstStateChangeReturn ret;
3424
3425   /* find a manager */
3426   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
3427     goto no_manager;
3428
3429   if (manager) {
3430     GST_DEBUG_OBJECT (src, "using manager %s", manager);
3431
3432     /* configure the manager */
3433     if (src->manager == NULL) {
3434       GObjectClass *klass;
3435
3436       if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
3437         /* fallback */
3438         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
3439           goto no_manager;
3440
3441         if (!manager)
3442           goto use_no_manager;
3443
3444         if (!(src->manager = gst_element_factory_make (manager, "manager")))
3445           goto manager_failed;
3446       }
3447
3448       /* we manage this element */
3449       gst_element_set_locked_state (src->manager, TRUE);
3450       gst_bin_add (GST_BIN_CAST (src), src->manager);
3451
3452       ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
3453       if (ret == GST_STATE_CHANGE_FAILURE)
3454         goto start_manager_failure;
3455
3456       g_object_set (src->manager, "latency", src->latency, NULL);
3457
3458       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3459
3460       if (g_object_class_find_property (klass, "ntp-sync")) {
3461         g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
3462       }
3463
3464       if (src->use_pipeline_clock) {
3465         if (g_object_class_find_property (klass, "use-pipeline-clock")) {
3466           g_object_set (src->manager, "use-pipeline-clock", TRUE, NULL);
3467         }
3468       } else {
3469         if (g_object_class_find_property (klass, "ntp-time-source")) {
3470           g_object_set (src->manager, "ntp-time-source", src->ntp_time_source,
3471               NULL);
3472         }
3473       }
3474
3475       if (src->sdes && g_object_class_find_property (klass, "sdes")) {
3476         g_object_set (src->manager, "sdes", src->sdes, NULL);
3477       }
3478
3479       if (g_object_class_find_property (klass, "drop-on-latency")) {
3480         g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
3481             NULL);
3482       }
3483
3484       /* buffer mode pauses are handled by adding offsets to buffer times,
3485        * but some depayloaders may have a hard time syncing output times
3486        * with such input times, e.g. container ones, most notably ASF */
3487       /* TODO alternatives are having an event that indicates these shifts,
3488        * or having rtsp extensions provide suggestion on buffer mode */
3489       /* valid duration implies not likely live pipeline,
3490        * so slaving in jitterbuffer does not make much sense
3491        * (and might mess things up due to bursts) */
3492       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
3493           src->segment.duration && stream->container) {
3494         src->use_buffering = TRUE;
3495       } else {
3496         src->use_buffering = FALSE;
3497       }
3498
3499       set_manager_buffer_mode (src);
3500
3501       /* connect to signals */
3502       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
3503           stream);
3504       src->manager_sig_id =
3505           g_signal_connect (src->manager, "pad-added",
3506           (GCallback) new_manager_pad, src);
3507       src->manager_ptmap_id =
3508           g_signal_connect (src->manager, "request-pt-map",
3509           (GCallback) request_pt_map, src);
3510
3511       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
3512           src);
3513
3514       g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
3515           src->manager);
3516
3517       if (src->do_retransmission)
3518         add_retransmission (src, transport);
3519     }
3520     g_signal_connect (src->manager, "request-rtp-decoder",
3521         (GCallback) request_rtp_decoder, stream);
3522     g_signal_connect (src->manager, "request-rtcp-decoder",
3523         (GCallback) request_rtp_decoder, stream);
3524     g_signal_connect (src->manager, "request-rtcp-encoder",
3525         (GCallback) request_rtcp_encoder, stream);
3526
3527     /* we stream directly to the manager, get some pads. Each RTSP stream goes
3528      * into a separate RTP session. */
3529     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
3530     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
3531     g_free (name);
3532     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
3533     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
3534     g_free (name);
3535
3536     /* now configure the bandwidth in the manager */
3537     if (g_signal_lookup ("get-internal-session",
3538             G_OBJECT_TYPE (src->manager)) != 0) {
3539       GObject *rtpsession;
3540
3541       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
3542           &rtpsession);
3543       if (rtpsession) {
3544         GstRTPProfile rtp_profile;
3545
3546         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
3547
3548         stream->session = rtpsession;
3549
3550         if (stream->as_bandwidth != -1) {
3551           GST_INFO_OBJECT (src, "setting AS: %f",
3552               (gdouble) (stream->as_bandwidth * 1000));
3553           g_object_set (rtpsession, "bandwidth",
3554               (gdouble) (stream->as_bandwidth * 1000), NULL);
3555         }
3556         if (stream->rr_bandwidth != -1) {
3557           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
3558           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
3559               NULL);
3560         }
3561         if (stream->rs_bandwidth != -1) {
3562           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
3563           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
3564               NULL);
3565         }
3566
3567         switch (stream->profile) {
3568           case GST_RTSP_PROFILE_AVPF:
3569             rtp_profile = GST_RTP_PROFILE_AVPF;
3570             break;
3571           case GST_RTSP_PROFILE_SAVP:
3572             rtp_profile = GST_RTP_PROFILE_SAVP;
3573             break;
3574           case GST_RTSP_PROFILE_SAVPF:
3575             rtp_profile = GST_RTP_PROFILE_SAVPF;
3576             break;
3577           case GST_RTSP_PROFILE_AVP:
3578           default:
3579             rtp_profile = GST_RTP_PROFILE_AVP;
3580             break;
3581         }
3582
3583         g_object_set (rtpsession, "rtp-profile", rtp_profile, NULL);
3584
3585         g_object_set (rtpsession, "probation", src->probation, NULL);
3586
3587         g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
3588
3589         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
3590             stream);
3591         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
3592             stream);
3593         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
3594             stream);
3595         g_signal_connect (rtpsession, "on-ssrc-active",
3596             (GCallback) on_ssrc_active, stream);
3597       }
3598     }
3599   }
3600
3601 use_no_manager:
3602   return TRUE;
3603
3604   /* ERRORS */
3605 no_manager:
3606   {
3607     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3608     return FALSE;
3609   }
3610 manager_failed:
3611   {
3612     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
3613     return FALSE;
3614   }
3615 start_manager_failure:
3616   {
3617     GST_DEBUG_OBJECT (src, "could not start session manager");
3618     return FALSE;
3619   }
3620 }
3621
3622 /* free the UDP sources allocated when negotiating a transport.
3623  * This function is called when the server negotiated to a transport where the
3624  * UDP sources are not needed anymore, such as TCP or multicast. */
3625 static void
3626 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
3627 {
3628   gint i;
3629
3630   for (i = 0; i < 2; i++) {
3631     if (stream->udpsrc[i]) {
3632       GST_DEBUG ("free UDP source %d for stream %p", i, stream);
3633       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
3634       gst_object_unref (stream->udpsrc[i]);
3635       stream->udpsrc[i] = NULL;
3636     }
3637   }
3638 }
3639
3640 /* for TCP, create pads to send and receive data to and from the manager and to
3641  * intercept various events and queries
3642  */
3643 static gboolean
3644 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
3645     GstRTSPTransport * transport, GstPad ** outpad)
3646 {
3647   gchar *name;
3648   GstPadTemplate *template;
3649   GstPad *pad0, *pad1;
3650
3651   /* configure for interleaved delivery, nothing needs to be done
3652    * here, the loop function will call the chain functions of the
3653    * session manager. */
3654   stream->channel[0] = transport->interleaved.min;
3655   stream->channel[1] = transport->interleaved.max;
3656   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
3657       stream->channel[0], stream->channel[1]);
3658
3659   /* we can remove the allocated UDP ports now */
3660   gst_rtspsrc_stream_free_udp (stream);
3661
3662   /* no session manager, send data to srcpad directly */
3663   if (!stream->channelpad[0]) {
3664     GST_DEBUG_OBJECT (src, "no manager, creating pad");
3665
3666     /* create a new pad we will use to stream to */
3667     name = g_strdup_printf ("stream_%u", stream->id);
3668     template = gst_static_pad_template_get (&rtptemplate);
3669     stream->channelpad[0] = gst_pad_new_from_template (template, name);
3670     gst_object_unref (template);
3671     g_free (name);
3672
3673     /* set caps and activate */
3674     gst_pad_use_fixed_caps (stream->channelpad[0]);
3675     gst_pad_set_active (stream->channelpad[0], TRUE);
3676
3677     *outpad = gst_object_ref (stream->channelpad[0]);
3678   } else {
3679     GST_DEBUG_OBJECT (src, "using manager source pad");
3680
3681     template = gst_static_pad_template_get (&anysrctemplate);
3682
3683     /* allocate pads for sending the channel data into the manager */
3684     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
3685     gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
3686     gst_object_unref (stream->channelpad[0]);
3687     stream->channelpad[0] = pad0;
3688     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
3689     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
3690     gst_pad_set_element_private (pad0, src);
3691     gst_pad_set_active (pad0, TRUE);
3692
3693     if (stream->channelpad[1]) {
3694       /* if we have a sinkpad for the other channel, create a pad and link to the
3695        * manager. */
3696       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
3697       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
3698       gst_pad_link_full (pad1, stream->channelpad[1],
3699           GST_PAD_LINK_CHECK_NOTHING);
3700       gst_object_unref (stream->channelpad[1]);
3701       stream->channelpad[1] = pad1;
3702       gst_pad_set_active (pad1, TRUE);
3703     }
3704     gst_object_unref (template);
3705   }
3706   /* setup RTCP transport back to the server if we have to. */
3707   if (src->manager && src->do_rtcp) {
3708     GstPad *pad;
3709
3710     template = gst_static_pad_template_get (&anysinktemplate);
3711
3712     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
3713     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
3714     gst_pad_set_element_private (stream->rtcppad, stream);
3715     gst_pad_set_active (stream->rtcppad, TRUE);
3716
3717     /* get session RTCP pad */
3718     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3719     pad = gst_element_get_request_pad (src->manager, name);
3720     g_free (name);
3721
3722     /* and link */
3723     if (pad) {
3724       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3725       gst_object_unref (pad);
3726     }
3727
3728     gst_object_unref (template);
3729   }
3730   return TRUE;
3731 }
3732
3733 static void
3734 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3735     GstRTSPTransport * transport, const gchar ** destination, gint * min,
3736     gint * max, guint * ttl)
3737 {
3738   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3739     if (destination) {
3740       if (!(*destination = transport->destination))
3741         *destination = stream->destination;
3742     }
3743     if (min && max) {
3744       /* transport first */
3745       *min = transport->port.min;
3746       *max = transport->port.max;
3747       if (*min == -1 && *max == -1) {
3748         /* then try from SDP */
3749         if (stream->port != 0) {
3750           *min = stream->port;
3751           *max = stream->port + 1;
3752         }
3753       }
3754     }
3755
3756     if (ttl) {
3757       if (!(*ttl = transport->ttl))
3758         *ttl = stream->ttl;
3759     }
3760   } else {
3761     if (destination) {
3762       /* first take the source, then the endpoint to figure out where to send
3763        * the RTCP. */
3764       if (!(*destination = transport->source)) {
3765         if (src->conninfo.connection)
3766           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3767         else if (stream->conninfo.connection)
3768           *destination =
3769               gst_rtsp_connection_get_ip (stream->conninfo.connection);
3770       }
3771     }
3772     if (min && max) {
3773       /* for unicast we only expect the ports here */
3774       *min = transport->server_port.min;
3775       *max = transport->server_port.max;
3776     }
3777   }
3778 }
3779
3780 /* For multicast create UDP sources and join the multicast group. */
3781 static gboolean
3782 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3783     GstRTSPTransport * transport, GstPad ** outpad)
3784 {
3785   gchar *uri;
3786   const gchar *destination;
3787   gint min, max;
3788
3789   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3790
3791   /* we can remove the allocated UDP ports now */
3792   gst_rtspsrc_stream_free_udp (stream);
3793
3794   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3795       &max, NULL);
3796
3797   /* we need a destination now */
3798   if (destination == NULL)
3799     goto no_destination;
3800
3801   /* we really need ports now or we won't be able to receive anything at all */
3802   if (min == -1 && max == -1)
3803     goto no_ports;
3804
3805   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3806       destination, min, max);
3807
3808   /* creating UDP source for RTP */
3809   if (min != -1) {
3810     uri = g_strdup_printf ("udp://%s:%d", destination, min);
3811     stream->udpsrc[0] =
3812         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3813     g_free (uri);
3814     if (stream->udpsrc[0] == NULL)
3815       goto no_element;
3816
3817     /* take ownership */
3818     gst_object_ref_sink (stream->udpsrc[0]);
3819
3820     if (src->udp_buffer_size != 0)
3821       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3822           src->udp_buffer_size, NULL);
3823
3824     if (src->multi_iface != NULL)
3825       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3826           src->multi_iface, NULL);
3827
3828     /* change state */
3829     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3830     gst_element_set_state (stream->udpsrc[0], GST_STATE_READY);
3831   }
3832
3833   /* creating another UDP source for RTCP */
3834   if (max != -1) {
3835     GstCaps *caps;
3836
3837     uri = g_strdup_printf ("udp://%s:%d", destination, max);
3838     stream->udpsrc[1] =
3839         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3840     g_free (uri);
3841     if (stream->udpsrc[1] == NULL)
3842       goto no_element;
3843
3844     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3845         stream->profile == GST_RTSP_PROFILE_SAVPF)
3846       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3847     else
3848       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3849     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3850     gst_caps_unref (caps);
3851
3852     /* take ownership */
3853     gst_object_ref_sink (stream->udpsrc[1]);
3854
3855     if (src->multi_iface != NULL)
3856       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3857           src->multi_iface, NULL);
3858
3859     gst_element_set_state (stream->udpsrc[1], GST_STATE_READY);
3860   }
3861   return TRUE;
3862
3863   /* ERRORS */
3864 no_element:
3865   {
3866     GST_DEBUG_OBJECT (src, "no UDP source element found");
3867     return FALSE;
3868   }
3869 no_destination:
3870   {
3871     GST_DEBUG_OBJECT (src, "no destination found");
3872     return FALSE;
3873   }
3874 no_ports:
3875   {
3876     GST_DEBUG_OBJECT (src, "no ports found");
3877     return FALSE;
3878   }
3879 }
3880
3881 /* configure the remainder of the UDP ports */
3882 static gboolean
3883 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3884     GstRTSPTransport * transport, GstPad ** outpad)
3885 {
3886   /* we manage the UDP elements now. For unicast, the UDP sources where
3887    * allocated in the stream when we suggested a transport. */
3888   if (stream->udpsrc[0]) {
3889     GstCaps *caps;
3890
3891     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3892     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3893
3894     GST_DEBUG_OBJECT (src, "setting up UDP source");
3895
3896     /* configure a timeout on the UDP port. When the timeout message is
3897      * posted, we assume UDP transport is not possible. We reconnect using TCP
3898      * if we can. */
3899     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3900         src->udp_timeout * 1000, NULL);
3901
3902     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt)))
3903       g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3904
3905     /* get output pad of the UDP source. */
3906     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3907
3908     /* save it so we can unblock */
3909     stream->blockedpad = *outpad;
3910
3911     /* configure pad block on the pad. As soon as there is dataflow on the
3912      * UDP source, we know that UDP is not blocked by a firewall and we can
3913      * configure all the streams to let the application autoplug decoders. */
3914     stream->blockid =
3915         gst_pad_add_probe (stream->blockedpad,
3916         GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
3917         GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
3918
3919     if (stream->channelpad[0]) {
3920       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3921       /* configure for UDP delivery, we need to connect the UDP pads to
3922        * the session plugin. */
3923       gst_pad_link_full (*outpad, stream->channelpad[0],
3924           GST_PAD_LINK_CHECK_NOTHING);
3925       gst_object_unref (*outpad);
3926       *outpad = NULL;
3927       /* we connected to pad-added signal to get pads from the manager */
3928     } else {
3929       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3930     }
3931   }
3932
3933   /* RTCP port */
3934   if (stream->udpsrc[1]) {
3935     GstCaps *caps;
3936
3937     gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3938     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3939
3940     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3941         stream->profile == GST_RTSP_PROFILE_SAVPF)
3942       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3943     else
3944       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3945     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3946     gst_caps_unref (caps);
3947
3948     if (stream->channelpad[1]) {
3949       GstPad *pad;
3950
3951       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3952
3953       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3954       gst_pad_link_full (pad, stream->channelpad[1],
3955           GST_PAD_LINK_CHECK_NOTHING);
3956       gst_object_unref (pad);
3957     } else {
3958       /* leave unlinked */
3959     }
3960   }
3961   return TRUE;
3962 }
3963
3964 /* configure the UDP sink back to the server for status reports */
3965 static gboolean
3966 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3967     GstRTSPStream * stream, GstRTSPTransport * transport)
3968 {
3969   GstPad *pad;
3970   gint rtp_port, rtcp_port;
3971   gboolean do_rtp, do_rtcp;
3972   const gchar *destination;
3973   gchar *uri, *name;
3974   guint ttl = 0;
3975   GSocket *socket;
3976
3977   /* get transport info */
3978   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3979       &rtp_port, &rtcp_port, &ttl);
3980
3981   /* see what we need to do */
3982   do_rtp = (rtp_port != -1);
3983   /* it's possible that the server does not want us to send RTCP in which case
3984    * the port is -1 */
3985   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3986
3987   /* we need a destination when we have RTP or RTCP ports */
3988   if (destination == NULL && (do_rtp || do_rtcp))
3989     goto no_destination;
3990
3991   /* try to construct the fakesrc to the RTP port of the server to open up any
3992    * NAT firewalls */
3993   if (do_rtp) {
3994     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3995         rtp_port);
3996
3997     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3998     stream->udpsink[0] =
3999         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
4000     g_free (uri);
4001     if (stream->udpsink[0] == NULL)
4002       goto no_sink_element;
4003
4004     /* don't join multicast group, we will have the source socket do that */
4005     /* no sync or async state changes needed */
4006     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
4007         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
4008     if (ttl > 0)
4009       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
4010
4011     if (stream->udpsrc[0]) {
4012       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
4013        * so that NAT firewalls will open a hole for us */
4014       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
4015       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
4016       /* configure socket and make sure udpsink does not close it when shutting
4017        * down, it belongs to udpsrc after all. */
4018       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
4019           "close-socket", FALSE, NULL);
4020       g_object_unref (socket);
4021     }
4022
4023     /* the source for the dummy packets to open up NAT */
4024     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
4025     if (stream->fakesrc == NULL)
4026       goto no_fakesrc_element;
4027
4028     /* random data in 5 buffers, a size of 200 bytes should be fine */
4029     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
4030         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
4031
4032     /* we don't want to consider this a sink */
4033     GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
4034
4035     /* keep everything locked */
4036     gst_element_set_locked_state (stream->udpsink[0], TRUE);
4037     gst_element_set_locked_state (stream->fakesrc, TRUE);
4038
4039     gst_object_ref (stream->udpsink[0]);
4040     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
4041     gst_object_ref (stream->fakesrc);
4042     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
4043
4044     gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
4045         "sink", GST_PAD_LINK_CHECK_NOTHING);
4046   }
4047   if (do_rtcp) {
4048     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
4049         rtcp_port);
4050
4051     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
4052     stream->udpsink[1] =
4053         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
4054     g_free (uri);
4055     if (stream->udpsink[1] == NULL)
4056       goto no_sink_element;
4057
4058     /* don't join multicast group, we will have the source socket do that */
4059     /* no sync or async state changes needed */
4060     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
4061         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
4062     if (ttl > 0)
4063       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
4064
4065     if (stream->udpsrc[1]) {
4066       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
4067        * because some servers check the port number of where it sends RTCP to identify
4068        * the RTCP packets it receives */
4069       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
4070       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
4071       /* configure socket and make sure udpsink does not close it when shutting
4072        * down, it belongs to udpsrc after all. */
4073       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
4074           "close-socket", FALSE, NULL);
4075       g_object_unref (socket);
4076     }
4077
4078     /* we don't want to consider this a sink */
4079     GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
4080
4081     /* we keep this playing always */
4082     gst_element_set_locked_state (stream->udpsink[1], TRUE);
4083     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
4084
4085     gst_object_ref (stream->udpsink[1]);
4086     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
4087
4088     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
4089
4090     /* get session RTCP pad */
4091     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
4092     pad = gst_element_get_request_pad (src->manager, name);
4093     g_free (name);
4094
4095     /* and link */
4096     if (pad) {
4097       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
4098       gst_object_unref (pad);
4099     }
4100   }
4101
4102   return TRUE;
4103
4104   /* ERRORS */
4105 no_destination:
4106   {
4107     GST_DEBUG_OBJECT (src, "no destination address specified");
4108     return FALSE;
4109   }
4110 no_sink_element:
4111   {
4112     GST_DEBUG_OBJECT (src, "no UDP sink element found");
4113     return FALSE;
4114   }
4115 no_fakesrc_element:
4116   {
4117     GST_DEBUG_OBJECT (src, "no fakesrc element found");
4118     return FALSE;
4119   }
4120 }
4121
4122 /* sets up all elements needed for streaming over the specified transport.
4123  * Does not yet expose the element pads, this will be done when there is actuall
4124  * dataflow detected, which might never happen when UDP is blocked in a
4125  * firewall, for example.
4126  */
4127 static gboolean
4128 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
4129     GstRTSPTransport * transport)
4130 {
4131   GstRTSPSrc *src;
4132   GstPad *outpad = NULL;
4133   GstPadTemplate *template;
4134   gchar *name;
4135   const gchar *media_type;
4136   guint i, len;
4137
4138   src = stream->parent;
4139
4140   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
4141
4142   /* get the proper media type for this stream now */
4143   if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
4144     goto unknown_transport;
4145   if (!media_type)
4146     goto unknown_transport;
4147
4148   /* configure the final media type */
4149   GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
4150
4151   len = stream->ptmap->len;
4152   for (i = 0; i < len; i++) {
4153     GstStructure *s;
4154     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
4155
4156     if (item->caps == NULL)
4157       continue;
4158
4159     s = gst_caps_get_structure (item->caps, 0);
4160     gst_structure_set_name (s, media_type);
4161     /* set ssrc if known */
4162     if (transport->ssrc)
4163       gst_structure_set (s, "ssrc", G_TYPE_UINT, transport->ssrc, NULL);
4164   }
4165
4166   /* try to get and configure a manager, channelpad[0-1] will be configured with
4167    * the pads for the manager, or NULL when no manager is needed. */
4168   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
4169     goto no_manager;
4170
4171   switch (transport->lower_transport) {
4172     case GST_RTSP_LOWER_TRANS_TCP:
4173       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
4174         goto transport_failed;
4175       break;
4176     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
4177       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
4178         goto transport_failed;
4179       /* fallthrough, the rest is the same for UDP and MCAST */
4180     case GST_RTSP_LOWER_TRANS_UDP:
4181       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
4182         goto transport_failed;
4183       /* configure udpsinks back to the server for RTCP messages and for the
4184        * dummy RTP messages to open NAT. */
4185       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
4186         goto transport_failed;
4187       break;
4188     default:
4189       goto unknown_transport;
4190   }
4191
4192   if (outpad) {
4193     GST_DEBUG_OBJECT (src, "creating ghostpad");
4194
4195     gst_pad_use_fixed_caps (outpad);
4196
4197     /* create ghostpad, don't add just yet, this will be done when we activate
4198      * the stream. */
4199     name = g_strdup_printf ("stream_%u", stream->id);
4200     template = gst_static_pad_template_get (&rtptemplate);
4201     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
4202     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
4203     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
4204     gst_object_unref (template);
4205     g_free (name);
4206
4207     gst_object_unref (outpad);
4208   }
4209   /* mark pad as ok */
4210   stream->last_ret = GST_FLOW_OK;
4211
4212   return TRUE;
4213
4214   /* ERRORS */
4215 transport_failed:
4216   {
4217     GST_DEBUG_OBJECT (src, "failed to configure transport");
4218     return FALSE;
4219   }
4220 unknown_transport:
4221   {
4222     GST_DEBUG_OBJECT (src, "unknown transport");
4223     return FALSE;
4224   }
4225 no_manager:
4226   {
4227     GST_DEBUG_OBJECT (src, "cannot get a session manager");
4228     return FALSE;
4229   }
4230 }
4231
4232 /* send a couple of dummy random packets on the receiver RTP port to the server,
4233  * this should make a firewall think we initiated the data transfer and
4234  * hopefully allow packets to go from the sender port to our RTP receiver port */
4235 static gboolean
4236 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
4237 {
4238   GList *walk;
4239
4240   if (src->nat_method != GST_RTSP_NAT_DUMMY)
4241     return TRUE;
4242
4243   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4244     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4245
4246     if (stream->fakesrc && stream->udpsink[0]) {
4247       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
4248       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
4249       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
4250       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
4251       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
4252     }
4253   }
4254   return TRUE;
4255 }
4256
4257 /* Adds the source pads of all configured streams to the element.
4258  * This code is performed when we detected dataflow.
4259  *
4260  * We detect dataflow from either the _loop function or with pad probes on the
4261  * udp sources.
4262  */
4263 static gboolean
4264 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
4265 {
4266   GList *walk;
4267
4268   GST_DEBUG_OBJECT (src, "activating streams");
4269
4270   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4271     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4272
4273     if (stream->udpsrc[0]) {
4274       /* remove timeout, we are streaming now and timeouts will be handled by
4275        * the session manager and jitter buffer */
4276       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
4277     }
4278     if (stream->srcpad) {
4279       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
4280       gst_pad_set_active (stream->srcpad, TRUE);
4281
4282       /* if we don't have a session manager, set the caps now. If we have a
4283        * session, we will get a notification of the pad and the caps. */
4284       if (!src->manager) {
4285         GstCaps *caps;
4286
4287         caps = stream_get_caps_for_pt (stream, stream->default_pt);
4288         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
4289         gst_pad_set_caps (stream->srcpad, caps);
4290       }
4291       /* add the pad */
4292       if (!stream->added) {
4293         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
4294         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
4295         stream->added = TRUE;
4296       }
4297     }
4298   }
4299
4300   /* unblock all pads */
4301   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4302     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4303
4304     if (stream->blockid) {
4305       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
4306       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
4307       stream->blockid = 0;
4308     }
4309   }
4310
4311   return TRUE;
4312 }
4313
4314 static void
4315 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
4316     gboolean reset_manager)
4317 {
4318   GList *walk;
4319   guint64 start, stop;
4320   gdouble play_speed, play_scale;
4321
4322   GST_DEBUG_OBJECT (src, "configuring stream caps");
4323
4324   start = segment->position;
4325   stop = segment->duration;
4326   play_speed = segment->rate;
4327   play_scale = segment->applied_rate;
4328
4329   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4330     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4331     guint j, len;
4332
4333     if (!stream->setup)
4334       continue;
4335
4336     len = stream->ptmap->len;
4337     for (j = 0; j < len; j++) {
4338       GstCaps *caps;
4339       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, j);
4340
4341       if (item->caps == NULL)
4342         continue;
4343
4344       caps = gst_caps_make_writable (item->caps);
4345       /* update caps */
4346       if (stream->timebase != -1)
4347         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
4348             (guint) stream->timebase, NULL);
4349       if (stream->seqbase != -1)
4350         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
4351             (guint) stream->seqbase, NULL);
4352       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
4353       if (stop != -1)
4354         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
4355       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
4356       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
4357
4358       item->caps = caps;
4359       GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
4360           item->pt, caps);
4361
4362       if (item->pt == stream->default_pt && stream->udpsrc[0]) {
4363         g_object_set (stream->udpsrc[0], "caps", caps, NULL);
4364       }
4365     }
4366   }
4367   if (reset_manager && src->manager) {
4368     GST_DEBUG_OBJECT (src, "clear session");
4369     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
4370   }
4371 }
4372
4373 static GstFlowReturn
4374 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
4375     GstFlowReturn ret)
4376 {
4377   GList *streams;
4378
4379   /* store the value */
4380   stream->last_ret = ret;
4381
4382   /* if it's success we can return the value right away */
4383   if (ret == GST_FLOW_OK)
4384     goto done;
4385
4386   /* any other error that is not-linked can be returned right
4387    * away */
4388   if (ret != GST_FLOW_NOT_LINKED)
4389     goto done;
4390
4391   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4392   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4393     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4394
4395     ret = ostream->last_ret;
4396     /* some other return value (must be SUCCESS but we can return
4397      * other values as well) */
4398     if (ret != GST_FLOW_NOT_LINKED)
4399       goto done;
4400   }
4401   /* if we get here, all other pads were unlinked and we return
4402    * NOT_LINKED then */
4403 done:
4404   return ret;
4405 }
4406
4407 static gboolean
4408 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
4409     GstEvent * event)
4410 {
4411   gboolean res = TRUE;
4412
4413   /* only streams that have a connection to the outside world */
4414   if (!stream->setup)
4415     goto done;
4416
4417   if (stream->udpsrc[0]) {
4418     gst_event_ref (event);
4419     res = gst_element_send_event (stream->udpsrc[0], event);
4420   } else if (stream->channelpad[0]) {
4421     gst_event_ref (event);
4422     if (GST_PAD_IS_SRC (stream->channelpad[0]))
4423       res = gst_pad_push_event (stream->channelpad[0], event);
4424     else
4425       res = gst_pad_send_event (stream->channelpad[0], event);
4426   }
4427
4428   if (stream->udpsrc[1]) {
4429     gst_event_ref (event);
4430     res &= gst_element_send_event (stream->udpsrc[1], event);
4431   } else if (stream->channelpad[1]) {
4432     gst_event_ref (event);
4433     if (GST_PAD_IS_SRC (stream->channelpad[1]))
4434       res &= gst_pad_push_event (stream->channelpad[1], event);
4435     else
4436       res &= gst_pad_send_event (stream->channelpad[1], event);
4437   }
4438
4439 done:
4440   gst_event_unref (event);
4441
4442   return res;
4443 }
4444
4445 static gboolean
4446 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
4447 {
4448   GList *streams;
4449   gboolean res = TRUE;
4450
4451   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4452     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4453
4454     gst_event_ref (event);
4455     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
4456   }
4457   gst_event_unref (event);
4458
4459   return res;
4460 }
4461
4462 static GstRTSPResult
4463 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4464     gboolean async)
4465 {
4466   GstRTSPResult res;
4467
4468   if (info->connection == NULL) {
4469     if (info->url == NULL) {
4470       GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
4471       if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
4472         goto parse_error;
4473     }
4474
4475     /* create connection */
4476     GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
4477     if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
4478       goto could_not_create;
4479
4480     if (info->url_str)
4481       g_free (info->url_str);
4482     info->url_str = gst_rtsp_url_get_request_uri (info->url);
4483
4484     GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
4485
4486     if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
4487       if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
4488               src->tls_validation_flags))
4489         GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
4490
4491       if (src->tls_database)
4492         gst_rtsp_connection_set_tls_database (info->connection,
4493             src->tls_database);
4494
4495       if (src->tls_interaction)
4496         gst_rtsp_connection_set_tls_interaction (info->connection,
4497             src->tls_interaction);
4498     }
4499
4500     if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
4501       gst_rtsp_connection_set_tunneled (info->connection, TRUE);
4502
4503     if (src->proxy_host) {
4504       GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
4505           src->proxy_port);
4506       gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
4507           src->proxy_port);
4508     }
4509   }
4510
4511   if (!info->connected) {
4512     /* connect */
4513     if (async)
4514       GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
4515           ("Connecting to %s", info->location));
4516     GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
4517     if ((res =
4518             gst_rtsp_connection_connect (info->connection,
4519                 src->ptcp_timeout)) < 0)
4520       goto could_not_connect;
4521
4522     info->connected = TRUE;
4523   }
4524   return GST_RTSP_OK;
4525
4526   /* ERRORS */
4527 parse_error:
4528   {
4529     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
4530     return res;
4531   }
4532 could_not_create:
4533   {
4534     gchar *str = gst_rtsp_strresult (res);
4535     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
4536     g_free (str);
4537     return res;
4538   }
4539 could_not_connect:
4540   {
4541     gchar *str = gst_rtsp_strresult (res);
4542     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
4543     g_free (str);
4544     return res;
4545   }
4546 }
4547
4548 static GstRTSPResult
4549 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
4550     gboolean free)
4551 {
4552   GST_RTSP_STATE_LOCK (src);
4553   if (info->connected) {
4554     GST_DEBUG_OBJECT (src, "closing connection...");
4555     gst_rtsp_connection_close (info->connection);
4556     info->connected = FALSE;
4557   }
4558   if (free && info->connection) {
4559     /* free connection */
4560     GST_DEBUG_OBJECT (src, "freeing connection...");
4561     gst_rtsp_connection_free (info->connection);
4562     info->connection = NULL;
4563   }
4564   GST_RTSP_STATE_UNLOCK (src);
4565   return GST_RTSP_OK;
4566 }
4567
4568 static GstRTSPResult
4569 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4570     gboolean async)
4571 {
4572   GstRTSPResult res;
4573
4574   GST_DEBUG_OBJECT (src, "reconnecting connection...");
4575   gst_rtsp_conninfo_close (src, info, FALSE);
4576   res = gst_rtsp_conninfo_connect (src, info, async);
4577
4578   return res;
4579 }
4580
4581 static void
4582 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
4583 {
4584   GList *walk;
4585
4586   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
4587   GST_RTSP_STATE_LOCK (src);
4588   if (src->conninfo.connection && src->conninfo.flushing != flush) {
4589     GST_DEBUG_OBJECT (src, "connection flush");
4590     gst_rtsp_connection_flush (src->conninfo.connection, flush);
4591     src->conninfo.flushing = flush;
4592   }
4593   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4594     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4595     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
4596       GST_DEBUG_OBJECT (src, "stream %p flush", stream);
4597       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
4598       stream->conninfo.flushing = flush;
4599     }
4600   }
4601   GST_RTSP_STATE_UNLOCK (src);
4602 }
4603
4604 static GstRTSPResult
4605 gst_rtspsrc_init_request (GstRTSPSrc * src, GstRTSPMessage * msg,
4606     GstRTSPMethod method, const gchar * uri)
4607 {
4608   GstRTSPResult res;
4609
4610   res = gst_rtsp_message_init_request (msg, method, uri);
4611   if (res < 0)
4612     return res;
4613
4614   /* set user-agent */
4615   if (src->user_agent)
4616     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_USER_AGENT, src->user_agent);
4617
4618   return res;
4619 }
4620
4621 /* FIXME, handle server request, reply with OK, for now */
4622 static GstRTSPResult
4623 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
4624     GstRTSPMessage * request)
4625 {
4626   GstRTSPMessage response = { 0 };
4627   GstRTSPResult res;
4628
4629   GST_DEBUG_OBJECT (src, "got server request message");
4630
4631   if (src->debug)
4632     gst_rtsp_message_dump (request);
4633
4634   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4635
4636   if (res == GST_RTSP_ENOTIMPL) {
4637     /* default implementation, send OK */
4638     GST_DEBUG_OBJECT (src, "prepare OK reply");
4639     res =
4640         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4641         request);
4642     if (res < 0)
4643       goto send_error;
4644
4645     /* let app parse and reply */
4646     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4647         0, request, &response);
4648
4649     if (src->debug)
4650       gst_rtsp_message_dump (&response);
4651
4652     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
4653     if (res < 0)
4654       goto send_error;
4655
4656     gst_rtsp_message_unset (&response);
4657   } else if (res == GST_RTSP_EEOF)
4658     return res;
4659
4660   return GST_RTSP_OK;
4661
4662   /* ERRORS */
4663 send_error:
4664   {
4665     gst_rtsp_message_unset (&response);
4666     return res;
4667   }
4668 }
4669
4670 /* send server keep-alive */
4671 static GstRTSPResult
4672 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4673 {
4674   GstRTSPMessage request = { 0 };
4675   GstRTSPResult res;
4676   GstRTSPMethod method;
4677   const gchar *control;
4678
4679   if (src->do_rtsp_keep_alive == FALSE) {
4680     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4681     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4682     return GST_RTSP_OK;
4683   }
4684
4685   GST_DEBUG_OBJECT (src, "creating server keep-alive");
4686
4687   /* find a method to use for keep-alive */
4688   if (src->methods & GST_RTSP_GET_PARAMETER)
4689     method = GST_RTSP_GET_PARAMETER;
4690   else
4691     method = GST_RTSP_OPTIONS;
4692
4693   control = get_aggregate_control (src);
4694   if (control == NULL)
4695     goto no_control;
4696
4697   res = gst_rtspsrc_init_request (src, &request, method, control);
4698   if (res < 0)
4699     goto send_error;
4700
4701   if (src->debug)
4702     gst_rtsp_message_dump (&request);
4703
4704   res =
4705       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
4706       NULL);
4707   if (res < 0)
4708     goto send_error;
4709
4710   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4711   gst_rtsp_message_unset (&request);
4712
4713   return GST_RTSP_OK;
4714
4715   /* ERRORS */
4716 no_control:
4717   {
4718     GST_WARNING_OBJECT (src, "no control url to send keepalive");
4719     return GST_RTSP_OK;
4720   }
4721 send_error:
4722   {
4723     gchar *str = gst_rtsp_strresult (res);
4724
4725     gst_rtsp_message_unset (&request);
4726     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4727         ("Could not send keep-alive. (%s)", str));
4728     g_free (str);
4729     return res;
4730   }
4731 }
4732
4733 static GstFlowReturn
4734 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4735 {
4736   GstFlowReturn ret = GST_FLOW_OK;
4737   gint channel;
4738   GstRTSPStream *stream;
4739   GstPad *outpad = NULL;
4740   guint8 *data;
4741   guint size;
4742   GstBuffer *buf;
4743   gboolean is_rtcp;
4744
4745   channel = message->type_data.data.channel;
4746
4747   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4748   if (!stream)
4749     goto unknown_stream;
4750
4751   if (channel == stream->channel[0]) {
4752     outpad = stream->channelpad[0];
4753     is_rtcp = FALSE;
4754   } else if (channel == stream->channel[1]) {
4755     outpad = stream->channelpad[1];
4756     is_rtcp = TRUE;
4757   } else {
4758     is_rtcp = FALSE;
4759   }
4760
4761   /* take a look at the body to figure out what we have */
4762   gst_rtsp_message_get_body (message, &data, &size);
4763   if (size < 2)
4764     goto invalid_length;
4765
4766   /* channels are not correct on some servers, do extra check */
4767   if (data[1] >= 200 && data[1] <= 204) {
4768     /* hmm RTCP message switch to the RTCP pad of the same stream. */
4769     outpad = stream->channelpad[1];
4770     is_rtcp = TRUE;
4771   }
4772
4773   /* we have no clue what this is, just ignore then. */
4774   if (outpad == NULL)
4775     goto unknown_stream;
4776
4777   /* take the message body for further processing */
4778   gst_rtsp_message_steal_body (message, &data, &size);
4779
4780   /* strip the trailing \0 */
4781   size -= 1;
4782
4783   buf = gst_buffer_new ();
4784   gst_buffer_append_memory (buf,
4785       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4786
4787   /* don't need message anymore */
4788   gst_rtsp_message_unset (message);
4789
4790   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4791       channel);
4792
4793   if (src->need_activate) {
4794     gchar *stream_id;
4795     GstEvent *event;
4796     GChecksum *cs;
4797     gchar *uri;
4798     GList *streams;
4799     guint group_id = gst_util_group_id_next ();
4800
4801     /* generate an SHA256 sum of the URI */
4802     cs = g_checksum_new (G_CHECKSUM_SHA256);
4803     uri = src->conninfo.location;
4804     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4805
4806     for (streams = src->streams; streams; streams = g_list_next (streams)) {
4807       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4808       GstCaps *caps;
4809
4810       stream_id =
4811           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4812       event = gst_event_new_stream_start (stream_id);
4813       gst_event_set_group_id (event, group_id);
4814
4815       g_free (stream_id);
4816       gst_rtspsrc_stream_push_event (src, ostream, event);
4817
4818       if ((caps = stream_get_caps_for_pt (ostream, ostream->default_pt))) {
4819         /* only streams that have a connection to the outside world */
4820         if (ostream->setup) {
4821           if (ostream->udpsrc[0]) {
4822             gst_element_send_event (ostream->udpsrc[0],
4823                 gst_event_new_caps (caps));
4824           } else if (ostream->channelpad[0]) {
4825             if (GST_PAD_IS_SRC (ostream->channelpad[0]))
4826               gst_pad_push_event (ostream->channelpad[0],
4827                   gst_event_new_caps (caps));
4828             else
4829               gst_pad_send_event (ostream->channelpad[0],
4830                   gst_event_new_caps (caps));
4831           }
4832
4833           caps = gst_caps_new_empty_simple ("application/x-rtcp");
4834
4835           if (ostream->udpsrc[1]) {
4836             gst_element_send_event (ostream->udpsrc[1],
4837                 gst_event_new_caps (caps));
4838           } else if (ostream->channelpad[1]) {
4839             if (GST_PAD_IS_SRC (ostream->channelpad[1]))
4840               gst_pad_push_event (ostream->channelpad[1],
4841                   gst_event_new_caps (caps));
4842             else
4843               gst_pad_send_event (ostream->channelpad[1],
4844                   gst_event_new_caps (caps));
4845           }
4846
4847           gst_caps_unref (caps);
4848         }
4849       }
4850     }
4851     g_checksum_free (cs);
4852
4853     gst_rtspsrc_activate_streams (src);
4854     src->need_activate = FALSE;
4855     src->need_segment = TRUE;
4856   }
4857
4858   if (src->base_time == -1) {
4859     /* Take current running_time. This timestamp will be put on
4860      * the first buffer of each stream because we are a live source and so we
4861      * timestamp with the running_time. When we are dealing with TCP, we also
4862      * only timestamp the first buffer (using the DISCONT flag) because a server
4863      * typically bursts data, for which we don't want to compensate by speeding
4864      * up the media. The other timestamps will be interpollated from this one
4865      * using the RTP timestamps. */
4866     GST_OBJECT_LOCK (src);
4867     if (GST_ELEMENT_CLOCK (src)) {
4868       GstClockTime now;
4869       GstClockTime base_time;
4870
4871       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4872       base_time = GST_ELEMENT_CAST (src)->base_time;
4873
4874       src->base_time = now - base_time;
4875
4876       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4877           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4878     }
4879     GST_OBJECT_UNLOCK (src);
4880   }
4881
4882   /* If needed send a new segment, don't forget we are live and buffer are
4883    * timestamped with running time */
4884   if (src->need_segment) {
4885     GstSegment segment;
4886     src->need_segment = FALSE;
4887     gst_segment_init (&segment, GST_FORMAT_TIME);
4888     gst_rtspsrc_push_event (src, gst_event_new_segment (&segment));
4889   }
4890
4891   if (stream->discont && !is_rtcp) {
4892     /* mark first RTP buffer as discont */
4893     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4894     stream->discont = FALSE;
4895     /* first buffer gets the timestamp, other buffers are not timestamped and
4896      * their presentation time will be interpollated from the rtp timestamps. */
4897     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4898         GST_TIME_ARGS (src->base_time));
4899
4900     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4901   }
4902
4903   /* chain to the peer pad */
4904   if (GST_PAD_IS_SINK (outpad))
4905     ret = gst_pad_chain (outpad, buf);
4906   else
4907     ret = gst_pad_push (outpad, buf);
4908
4909   if (!is_rtcp) {
4910     /* combine all stream flows for the data transport */
4911     ret = gst_rtspsrc_combine_flows (src, stream, ret);
4912   }
4913   return ret;
4914
4915   /* ERRORS */
4916 unknown_stream:
4917   {
4918     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4919     gst_rtsp_message_unset (message);
4920     return GST_FLOW_OK;
4921   }
4922 invalid_length:
4923   {
4924     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4925         ("Short message received, ignoring."));
4926     gst_rtsp_message_unset (message);
4927     return GST_FLOW_OK;
4928   }
4929 }
4930
4931 static GstFlowReturn
4932 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4933 {
4934   GstRTSPMessage message = { 0 };
4935   GstRTSPResult res;
4936   GstFlowReturn ret = GST_FLOW_OK;
4937   GTimeVal tv_timeout;
4938
4939   while (TRUE) {
4940     /* get the next timeout interval */
4941     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4942
4943     /* see if the timeout period expired */
4944     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4945       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4946       /* send keep-alive, only act on interrupt, a warning will be posted for
4947        * other errors. */
4948       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4949         goto interrupt;
4950       /* get new timeout */
4951       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4952     }
4953
4954     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4955         tv_timeout.tv_sec, tv_timeout.tv_usec);
4956
4957     /* protect the connection with the connection lock so that we can see when
4958      * we are finished doing server communication */
4959     res =
4960         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4961         &message, src->ptcp_timeout);
4962
4963     switch (res) {
4964       case GST_RTSP_OK:
4965         GST_DEBUG_OBJECT (src, "we received a server message");
4966         break;
4967       case GST_RTSP_EINTR:
4968         /* we got interrupted this means we need to stop */
4969         goto interrupt;
4970       case GST_RTSP_ETIMEOUT:
4971         /* no reply, send keep alive */
4972         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4973         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4974           goto interrupt;
4975         continue;
4976       case GST_RTSP_EEOF:
4977         /* go EOS when the server closed the connection */
4978         goto server_eof;
4979       default:
4980         goto receive_error;
4981     }
4982
4983     switch (message.type) {
4984       case GST_RTSP_MESSAGE_REQUEST:
4985         /* server sends us a request message, handle it */
4986         res =
4987             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4988             &message);
4989         if (res == GST_RTSP_EEOF)
4990           goto server_eof;
4991         else if (res < 0)
4992           goto handle_request_failed;
4993         break;
4994       case GST_RTSP_MESSAGE_RESPONSE:
4995         /* we ignore response messages */
4996         GST_DEBUG_OBJECT (src, "ignoring response message");
4997         if (src->debug)
4998           gst_rtsp_message_dump (&message);
4999         break;
5000       case GST_RTSP_MESSAGE_DATA:
5001         GST_DEBUG_OBJECT (src, "got data message");
5002         ret = gst_rtspsrc_handle_data (src, &message);
5003         if (ret != GST_FLOW_OK)
5004           goto handle_data_failed;
5005         break;
5006       default:
5007         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5008             message.type);
5009         break;
5010     }
5011   }
5012   g_assert_not_reached ();
5013
5014   /* ERRORS */
5015 server_eof:
5016   {
5017     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5018     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5019         ("The server closed the connection."));
5020     src->conninfo.connected = FALSE;
5021     gst_rtsp_message_unset (&message);
5022     return GST_FLOW_EOS;
5023   }
5024 interrupt:
5025   {
5026     gst_rtsp_message_unset (&message);
5027     GST_DEBUG_OBJECT (src, "got interrupted");
5028     return GST_FLOW_FLUSHING;
5029   }
5030 receive_error:
5031   {
5032     gchar *str = gst_rtsp_strresult (res);
5033
5034     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5035         ("Could not receive message. (%s)", str));
5036     g_free (str);
5037
5038     gst_rtsp_message_unset (&message);
5039     return GST_FLOW_ERROR;
5040   }
5041 handle_request_failed:
5042   {
5043     gchar *str = gst_rtsp_strresult (res);
5044
5045     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5046         ("Could not handle server message. (%s)", str));
5047     g_free (str);
5048     gst_rtsp_message_unset (&message);
5049     return GST_FLOW_ERROR;
5050   }
5051 handle_data_failed:
5052   {
5053     GST_DEBUG_OBJECT (src, "could no handle data message");
5054     return ret;
5055   }
5056 }
5057
5058 static GstFlowReturn
5059 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
5060 {
5061   GstRTSPResult res;
5062   GstRTSPMessage message = { 0 };
5063   gint retry = 0;
5064
5065   while (TRUE) {
5066     GTimeVal tv_timeout;
5067
5068     /* get the next timeout interval */
5069     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
5070
5071     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
5072         (gint) tv_timeout.tv_sec);
5073
5074     gst_rtsp_message_unset (&message);
5075
5076     /* we should continue reading the TCP socket because the server might
5077      * send us requests. When the session timeout expires, we need to send a
5078      * keep-alive request to keep the session open. */
5079     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
5080         &message, &tv_timeout);
5081
5082     switch (res) {
5083       case GST_RTSP_OK:
5084         GST_DEBUG_OBJECT (src, "we received a server message");
5085         break;
5086       case GST_RTSP_EINTR:
5087         /* we got interrupted, see what we have to do */
5088         goto interrupt;
5089       case GST_RTSP_ETIMEOUT:
5090         /* send keep-alive, ignore the result, a warning will be posted. */
5091         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
5092         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5093           goto interrupt;
5094         continue;
5095       case GST_RTSP_EEOF:
5096         /* server closed the connection. not very fatal for UDP, reconnect and
5097          * see what happens. */
5098         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5099             ("The server closed the connection."));
5100         if (src->udp_reconnect) {
5101           if ((res =
5102                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
5103             goto connect_error;
5104         } else {
5105           goto server_eof;
5106         }
5107         continue;
5108       case GST_RTSP_ENET:
5109         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
5110       default:
5111         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5112             ("Unhandled return value %d.", res));
5113         goto receive_error;
5114     }
5115
5116     switch (message.type) {
5117       case GST_RTSP_MESSAGE_REQUEST:
5118         /* server sends us a request message, handle it */
5119         res =
5120             gst_rtspsrc_handle_request (src, src->conninfo.connection,
5121             &message);
5122         if (res == GST_RTSP_EEOF)
5123           goto server_eof;
5124         else if (res < 0)
5125           goto handle_request_failed;
5126         break;
5127       case GST_RTSP_MESSAGE_RESPONSE:
5128         /* we ignore response and data messages */
5129         GST_DEBUG_OBJECT (src, "ignoring response message");
5130         if (src->debug)
5131           gst_rtsp_message_dump (&message);
5132         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
5133           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
5134           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
5135             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
5136             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5137               goto interrupt;
5138           }
5139         } else {
5140           retry = 0;
5141         }
5142         break;
5143       case GST_RTSP_MESSAGE_DATA:
5144         /* we ignore response and data messages */
5145         GST_DEBUG_OBJECT (src, "ignoring data message");
5146         break;
5147       default:
5148         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5149             message.type);
5150         break;
5151     }
5152   }
5153   g_assert_not_reached ();
5154
5155   /* we get here when the connection got interrupted */
5156 interrupt:
5157   {
5158     gst_rtsp_message_unset (&message);
5159     GST_DEBUG_OBJECT (src, "got interrupted");
5160     return GST_FLOW_FLUSHING;
5161   }
5162 connect_error:
5163   {
5164     gchar *str = gst_rtsp_strresult (res);
5165     GstFlowReturn ret;
5166
5167     src->conninfo.connected = FALSE;
5168     if (res != GST_RTSP_EINTR) {
5169       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5170           ("Could not connect to server. (%s)", str));
5171       g_free (str);
5172       ret = GST_FLOW_ERROR;
5173     } else {
5174       ret = GST_FLOW_FLUSHING;
5175     }
5176     return ret;
5177   }
5178 receive_error:
5179   {
5180     gchar *str = gst_rtsp_strresult (res);
5181
5182     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5183         ("Could not receive message. (%s)", str));
5184     g_free (str);
5185     return GST_FLOW_ERROR;
5186   }
5187 handle_request_failed:
5188   {
5189     gchar *str = gst_rtsp_strresult (res);
5190     GstFlowReturn ret;
5191
5192     gst_rtsp_message_unset (&message);
5193     if (res != GST_RTSP_EINTR) {
5194       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5195           ("Could not handle server message. (%s)", str));
5196       g_free (str);
5197       ret = GST_FLOW_ERROR;
5198     } else {
5199       ret = GST_FLOW_FLUSHING;
5200     }
5201     return ret;
5202   }
5203 server_eof:
5204   {
5205     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5206     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5207         ("The server closed the connection."));
5208     src->conninfo.connected = FALSE;
5209     gst_rtsp_message_unset (&message);
5210     return GST_FLOW_EOS;
5211   }
5212 }
5213
5214 static GstRTSPResult
5215 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
5216 {
5217   GstRTSPResult res = GST_RTSP_OK;
5218   gboolean restart;
5219
5220   GST_DEBUG_OBJECT (src, "doing reconnect");
5221
5222   GST_OBJECT_LOCK (src);
5223   /* only restart when the pads were not yet activated, else we were
5224    * streaming over UDP */
5225   restart = src->need_activate;
5226   GST_OBJECT_UNLOCK (src);
5227
5228   /* no need to restart, we're done */
5229   if (!restart)
5230     goto done;
5231
5232   /* we can try only TCP now */
5233   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
5234
5235   /* close and cleanup our state */
5236   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
5237     goto done;
5238
5239   /* see if we have TCP left to try. Also don't try TCP when we were configured
5240    * with an SDP. */
5241   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
5242     goto no_protocols;
5243
5244   /* We post a warning message now to inform the user
5245    * that nothing happened. It's most likely a firewall thing. */
5246   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5247       ("Could not receive any UDP packets for %.4f seconds, maybe your "
5248           "firewall is blocking it. Retrying using a TCP connection.",
5249           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
5250
5251   /* open new connection using tcp */
5252   if (gst_rtspsrc_open (src, async) < 0)
5253     goto open_failed;
5254
5255   /* start playback */
5256   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
5257     goto play_failed;
5258
5259 done:
5260   return res;
5261
5262   /* ERRORS */
5263 no_protocols:
5264   {
5265     src->cur_protocols = 0;
5266     /* no transport possible, post an error and stop */
5267     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5268         ("Could not receive any UDP packets for %.4f seconds, maybe your "
5269             "firewall is blocking it. No other protocols to try.",
5270             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
5271     return GST_RTSP_ERROR;
5272   }
5273 open_failed:
5274   {
5275     GST_DEBUG_OBJECT (src, "open failed");
5276     return GST_RTSP_OK;
5277   }
5278 play_failed:
5279   {
5280     GST_DEBUG_OBJECT (src, "play failed");
5281     return GST_RTSP_OK;
5282   }
5283 }
5284
5285 static void
5286 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
5287 {
5288   switch (cmd) {
5289     case CMD_OPEN:
5290       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
5291       break;
5292     case CMD_PLAY:
5293       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
5294       break;
5295     case CMD_PAUSE:
5296       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
5297       break;
5298     case CMD_CLOSE:
5299       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
5300       break;
5301     default:
5302       break;
5303   }
5304 }
5305
5306 static void
5307 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
5308 {
5309   switch (cmd) {
5310     case CMD_OPEN:
5311       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
5312       break;
5313     case CMD_PLAY:
5314       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
5315       break;
5316     case CMD_PAUSE:
5317       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
5318       break;
5319     case CMD_CLOSE:
5320       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
5321       break;
5322     default:
5323       break;
5324   }
5325 }
5326
5327 static void
5328 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
5329 {
5330   switch (cmd) {
5331     case CMD_OPEN:
5332       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
5333       break;
5334     case CMD_PLAY:
5335       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
5336       break;
5337     case CMD_PAUSE:
5338       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
5339       break;
5340     case CMD_CLOSE:
5341       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
5342       break;
5343     default:
5344       break;
5345   }
5346 }
5347
5348 static void
5349 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
5350 {
5351   switch (cmd) {
5352     case CMD_OPEN:
5353       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
5354       break;
5355     case CMD_PLAY:
5356       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
5357       break;
5358     case CMD_PAUSE:
5359       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
5360       break;
5361     case CMD_CLOSE:
5362       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
5363       break;
5364     default:
5365       break;
5366   }
5367 }
5368
5369 static void
5370 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
5371 {
5372   if (ret == GST_RTSP_OK)
5373     gst_rtspsrc_loop_complete_cmd (src, cmd);
5374   else if (ret == GST_RTSP_EINTR)
5375     gst_rtspsrc_loop_cancel_cmd (src, cmd);
5376   else
5377     gst_rtspsrc_loop_error_cmd (src, cmd);
5378 }
5379
5380 static gboolean
5381 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
5382 {
5383   gint old;
5384   gboolean flushed = FALSE;
5385
5386   /* start new request */
5387   gst_rtspsrc_loop_start_cmd (src, cmd);
5388
5389   GST_DEBUG_OBJECT (src, "sending cmd %s", cmd_to_string (cmd));
5390
5391   GST_OBJECT_LOCK (src);
5392   old = src->pending_cmd;
5393   if (old == CMD_RECONNECT) {
5394     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
5395     cmd = CMD_RECONNECT;
5396   }
5397   if (old != CMD_WAIT) {
5398     src->pending_cmd = CMD_WAIT;
5399     GST_OBJECT_UNLOCK (src);
5400     /* cancel previous request */
5401     GST_DEBUG_OBJECT (src, "cancel previous request %s", cmd_to_string (old));
5402     gst_rtspsrc_loop_cancel_cmd (src, old);
5403     GST_OBJECT_LOCK (src);
5404   }
5405   src->pending_cmd = cmd;
5406   /* interrupt if allowed */
5407   if (src->busy_cmd & mask) {
5408     GST_DEBUG_OBJECT (src, "connection flush busy %s",
5409         cmd_to_string (src->busy_cmd));
5410     gst_rtspsrc_connection_flush (src, TRUE);
5411     flushed = TRUE;
5412   } else {
5413     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
5414         cmd_to_string (src->busy_cmd));
5415   }
5416   if (src->task)
5417     gst_task_start (src->task);
5418   GST_OBJECT_UNLOCK (src);
5419
5420   return flushed;
5421 }
5422
5423 static gboolean
5424 gst_rtspsrc_loop (GstRTSPSrc * src)
5425 {
5426   GstFlowReturn ret;
5427
5428   if (!src->conninfo.connection || !src->conninfo.connected)
5429     goto no_connection;
5430
5431   if (src->interleaved)
5432     ret = gst_rtspsrc_loop_interleaved (src);
5433   else
5434     ret = gst_rtspsrc_loop_udp (src);
5435
5436   if (ret != GST_FLOW_OK)
5437     goto pause;
5438
5439   return TRUE;
5440
5441   /* ERRORS */
5442 no_connection:
5443   {
5444     GST_WARNING_OBJECT (src, "we are not connected");
5445     ret = GST_FLOW_FLUSHING;
5446     goto pause;
5447   }
5448 pause:
5449   {
5450     const gchar *reason = gst_flow_get_name (ret);
5451
5452     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
5453     src->running = FALSE;
5454     if (ret == GST_FLOW_EOS) {
5455       /* perform EOS logic */
5456       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5457         gst_element_post_message (GST_ELEMENT_CAST (src),
5458             gst_message_new_segment_done (GST_OBJECT_CAST (src),
5459                 src->segment.format, src->segment.position));
5460         gst_rtspsrc_push_event (src,
5461             gst_event_new_segment_done (src->segment.format,
5462                 src->segment.position));
5463       } else {
5464         gst_rtspsrc_push_event (src, gst_event_new_eos ());
5465       }
5466     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
5467       /* for fatal errors we post an error message, post the error before the
5468        * EOS so the app knows about the error first. */
5469       GST_ELEMENT_ERROR (src, STREAM, FAILED,
5470           ("Internal data flow error."),
5471           ("streaming task paused, reason %s (%d)", reason, ret));
5472       gst_rtspsrc_push_event (src, gst_event_new_eos ());
5473     }
5474     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
5475     return FALSE;
5476   }
5477 }
5478
5479 #ifndef GST_DISABLE_GST_DEBUG
5480 static const gchar *
5481 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5482 {
5483   gint index = 0;
5484
5485   while (method != 0) {
5486     index++;
5487     method >>= 1;
5488   }
5489   switch (index) {
5490     case 0:
5491       return "None";
5492     case 1:
5493       return "Basic";
5494     case 2:
5495       return "Digest";
5496   }
5497
5498   return "Unknown";
5499 }
5500 #endif
5501
5502 static const gchar *
5503 gst_rtspsrc_skip_lws (const gchar * s)
5504 {
5505   while (g_ascii_isspace (*s))
5506     s++;
5507   return s;
5508 }
5509
5510 static const gchar *
5511 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
5512 {
5513   while (s > start && g_ascii_isspace (*(s - 1)))
5514     s--;
5515   return s;
5516 }
5517
5518 static const gchar *
5519 gst_rtspsrc_skip_commas (const gchar * s)
5520 {
5521   /* The grammar allows for multiple commas */
5522   while (g_ascii_isspace (*s) || *s == ',')
5523     s++;
5524   return s;
5525 }
5526
5527 static const gchar *
5528 gst_rtspsrc_skip_item (const gchar * s)
5529 {
5530   gboolean quoted = FALSE;
5531   const gchar *start = s;
5532
5533   /* A list item ends at the last non-whitespace character
5534    * before a comma which is not inside a quoted-string. Or at
5535    * the end of the string.
5536    */
5537   while (*s) {
5538     if (*s == '"')
5539       quoted = !quoted;
5540     else if (quoted) {
5541       if (*s == '\\' && *(s + 1))
5542         s++;
5543     } else {
5544       if (*s == ',')
5545         break;
5546     }
5547     s++;
5548   }
5549
5550   return gst_rtspsrc_unskip_lws (s, start);
5551 }
5552
5553 static void
5554 gst_rtsp_decode_quoted_string (gchar * quoted_string)
5555 {
5556   gchar *src, *dst;
5557
5558   src = quoted_string + 1;
5559   dst = quoted_string;
5560   while (*src && *src != '"') {
5561     if (*src == '\\' && *(src + 1))
5562       src++;
5563     *dst++ = *src++;
5564   }
5565   *dst = '\0';
5566 }
5567
5568 /* Extract the authentication tokens that the server provided for each method
5569  * into an array of structures and give those to the connection object.
5570  */
5571 static void
5572 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
5573     const gchar * header, gboolean * stale)
5574 {
5575   GSList *list = NULL, *iter;
5576   const gchar *end;
5577   gchar *item, *eq, *name_end, *value;
5578
5579   g_return_if_fail (stale != NULL);
5580
5581   gst_rtsp_connection_clear_auth_params (conn);
5582   *stale = FALSE;
5583
5584   /* Parse a header whose content is described by RFC2616 as
5585    * "#something", where "something" does not itself contain commas,
5586    * except as part of quoted-strings, into a list of allocated strings.
5587    */
5588   header = gst_rtspsrc_skip_commas (header);
5589   while (*header) {
5590     end = gst_rtspsrc_skip_item (header);
5591     list = g_slist_prepend (list, g_strndup (header, end - header));
5592     header = gst_rtspsrc_skip_commas (end);
5593   }
5594   if (!list)
5595     return;
5596
5597   list = g_slist_reverse (list);
5598   for (iter = list; iter; iter = iter->next) {
5599     item = iter->data;
5600
5601     eq = strchr (item, '=');
5602     if (eq) {
5603       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
5604       if (name_end == item) {
5605         /* That's no good... */
5606         g_free (item);
5607         continue;
5608       }
5609
5610       *name_end = '\0';
5611
5612       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
5613       if (*value == '"')
5614         gst_rtsp_decode_quoted_string (value);
5615     } else
5616       value = NULL;
5617
5618     if (value && strcmp (item, "stale") == 0 && strcmp (value, "TRUE") == 0)
5619       *stale = TRUE;
5620     gst_rtsp_connection_set_auth_param (conn, item, value);
5621     g_free (item);
5622   }
5623
5624   g_slist_free (list);
5625 }
5626
5627 /* Parse a WWW-Authenticate Response header and determine the
5628  * available authentication methods
5629  *
5630  * This code should also cope with the fact that each WWW-Authenticate
5631  * header can contain multiple challenge methods + tokens
5632  *
5633  * At the moment, for Basic auth, we just do a minimal check and don't
5634  * even parse out the realm */
5635 static void
5636 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
5637     GstRTSPConnection * conn, gboolean * stale)
5638 {
5639   gchar *start;
5640
5641   g_return_if_fail (hdr != NULL);
5642   g_return_if_fail (methods != NULL);
5643   g_return_if_fail (stale != NULL);
5644
5645   /* Skip whitespace at the start of the string */
5646   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
5647
5648   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
5649     *methods |= GST_RTSP_AUTH_BASIC;
5650   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
5651     *methods |= GST_RTSP_AUTH_DIGEST;
5652     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
5653   }
5654 }
5655
5656 /**
5657  * gst_rtspsrc_setup_auth:
5658  * @src: the rtsp source
5659  *
5660  * Configure a username and password and auth method on the
5661  * connection object based on a response we received from the
5662  * peer.
5663  *
5664  * Currently, this requires that a username and password were supplied
5665  * in the uri. In the future, they may be requested on demand by sending
5666  * a message up the bus.
5667  *
5668  * Returns: TRUE if authentication information could be set up correctly.
5669  */
5670 static gboolean
5671 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5672 {
5673   gchar *user = NULL;
5674   gchar *pass = NULL;
5675   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5676   GstRTSPAuthMethod method;
5677   GstRTSPResult auth_result;
5678   GstRTSPUrl *url;
5679   GstRTSPConnection *conn;
5680   gchar *hdr;
5681   gboolean stale = FALSE;
5682
5683   conn = src->conninfo.connection;
5684
5685   /* Identify the available auth methods and see if any are supported */
5686   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
5687           &hdr, 0) == GST_RTSP_OK) {
5688     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
5689   }
5690
5691   if (avail_methods == GST_RTSP_AUTH_NONE)
5692     goto no_auth_available;
5693
5694   /* For digest auth, if the response indicates that the session
5695    * data are stale, we just update them in the connection object and
5696    * return TRUE to retry the request */
5697   if (stale)
5698     src->tried_url_auth = FALSE;
5699
5700   url = gst_rtsp_connection_get_url (conn);
5701
5702   /* Do we have username and password available? */
5703   if (url != NULL && !src->tried_url_auth && url->user != NULL
5704       && url->passwd != NULL) {
5705     user = url->user;
5706     pass = url->passwd;
5707     src->tried_url_auth = TRUE;
5708     GST_DEBUG_OBJECT (src,
5709         "Attempting authentication using credentials from the URL");
5710   } else {
5711     user = src->user_id;
5712     pass = src->user_pw;
5713     GST_DEBUG_OBJECT (src,
5714         "Attempting authentication using credentials from the properties");
5715   }
5716
5717   /* FIXME: If the url didn't contain username and password or we tried them
5718    * already, request a username and passwd from the application via some kind
5719    * of credentials request message */
5720
5721   /* If we don't have a username and passwd at this point, bail out. */
5722   if (user == NULL || pass == NULL)
5723     goto no_user_pass;
5724
5725   /* Try to configure for each available authentication method, strongest to
5726    * weakest */
5727   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5728     /* Check if this method is available on the server */
5729     if ((method & avail_methods) == 0)
5730       continue;
5731
5732     /* Pass the credentials to the connection to try on the next request */
5733     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5734     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5735      * ignore it and end up retrying later */
5736     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5737       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5738           gst_rtsp_auth_method_to_string (method));
5739       break;
5740     }
5741   }
5742
5743   if (method == GST_RTSP_AUTH_NONE)
5744     goto no_auth_available;
5745
5746   return TRUE;
5747
5748 no_auth_available:
5749   {
5750     /* Output an error indicating that we couldn't connect because there were
5751      * no supported authentication protocols */
5752     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5753         ("No supported authentication protocol was found"));
5754     return FALSE;
5755   }
5756 no_user_pass:
5757   {
5758     /* We don't fire an error message, we just return FALSE and let the
5759      * normal NOT_AUTHORIZED error be propagated */
5760     return FALSE;
5761   }
5762 }
5763
5764 static GstRTSPResult
5765 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5766     GstRTSPMessage * request, GstRTSPMessage * response,
5767     GstRTSPStatusCode * code)
5768 {
5769   GstRTSPResult res;
5770   GstRTSPStatusCode thecode;
5771   gchar *content_base = NULL;
5772   gint try = 0;
5773
5774 again:
5775   if (!src->short_header)
5776     gst_rtsp_ext_list_before_send (src->extensions, request);
5777
5778   GST_DEBUG_OBJECT (src, "sending message");
5779
5780   if (src->debug)
5781     gst_rtsp_message_dump (request);
5782
5783   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
5784   if (res < 0)
5785     goto send_error;
5786
5787   gst_rtsp_connection_reset_timeout (conn);
5788
5789 next:
5790   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
5791   if (res < 0)
5792     goto receive_error;
5793
5794   if (src->debug)
5795     gst_rtsp_message_dump (response);
5796
5797   switch (response->type) {
5798     case GST_RTSP_MESSAGE_REQUEST:
5799       res = gst_rtspsrc_handle_request (src, conn, response);
5800       if (res == GST_RTSP_EEOF)
5801         goto server_eof;
5802       else if (res < 0)
5803         goto handle_request_failed;
5804       goto next;
5805     case GST_RTSP_MESSAGE_RESPONSE:
5806       /* ok, a response is good */
5807       GST_DEBUG_OBJECT (src, "received response message");
5808       break;
5809     case GST_RTSP_MESSAGE_DATA:
5810       /* get next response */
5811       GST_DEBUG_OBJECT (src, "handle data response message");
5812       gst_rtspsrc_handle_data (src, response);
5813       goto next;
5814     default:
5815       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5816           response->type);
5817       goto next;
5818   }
5819
5820   thecode = response->type_data.response.code;
5821
5822   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5823
5824   /* if the caller wanted the result code, we store it. */
5825   if (code)
5826     *code = thecode;
5827
5828   /* If the request didn't succeed, bail out before doing any more */
5829   if (thecode != GST_RTSP_STS_OK)
5830     return GST_RTSP_OK;
5831
5832   /* store new content base if any */
5833   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5834       &content_base, 0);
5835   if (content_base) {
5836     g_free (src->content_base);
5837     src->content_base = g_strdup (content_base);
5838   }
5839   gst_rtsp_ext_list_after_send (src->extensions, request, response);
5840
5841   return GST_RTSP_OK;
5842
5843   /* ERRORS */
5844 send_error:
5845   {
5846     gchar *str = gst_rtsp_strresult (res);
5847
5848     if (res != GST_RTSP_EINTR) {
5849       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5850           ("Could not send message. (%s)", str));
5851     } else {
5852       GST_WARNING_OBJECT (src, "send interrupted");
5853     }
5854     g_free (str);
5855     return res;
5856   }
5857 receive_error:
5858   {
5859     switch (res) {
5860       case GST_RTSP_EEOF:
5861         GST_WARNING_OBJECT (src, "server closed connection");
5862         if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5863           try++;
5864           /* if reconnect succeeds, try again */
5865           if ((res =
5866                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5867                       FALSE)) == 0)
5868             goto again;
5869         }
5870         /* only try once after reconnect, then fallthrough and error out */
5871       default:
5872       {
5873         gchar *str = gst_rtsp_strresult (res);
5874
5875         if (res != GST_RTSP_EINTR) {
5876           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5877               ("Could not receive message. (%s)", str));
5878         } else {
5879           GST_WARNING_OBJECT (src, "receive interrupted");
5880         }
5881         g_free (str);
5882         break;
5883       }
5884     }
5885     return res;
5886   }
5887 handle_request_failed:
5888   {
5889     /* ERROR was posted */
5890     gst_rtsp_message_unset (response);
5891     return res;
5892   }
5893 server_eof:
5894   {
5895     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5896     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5897         ("The server closed the connection."));
5898     gst_rtsp_message_unset (response);
5899     return res;
5900   }
5901 }
5902
5903 /**
5904  * gst_rtspsrc_send:
5905  * @src: the rtsp source
5906  * @conn: the connection to send on
5907  * @request: must point to a valid request
5908  * @response: must point to an empty #GstRTSPMessage
5909  * @code: an optional code result
5910  *
5911  * send @request and retrieve the response in @response. optionally @code can be
5912  * non-NULL in which case it will contain the status code of the response.
5913  *
5914  * If This function returns #GST_RTSP_OK, @response will contain a valid response
5915  * message that should be cleaned with gst_rtsp_message_unset() after usage.
5916  *
5917  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5918  * @response message) if the response code was not 200 (OK).
5919  *
5920  * If the attempt results in an authentication failure, then this will attempt
5921  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5922  * the request.
5923  *
5924  * Returns: #GST_RTSP_OK if the processing was successful.
5925  */
5926 static GstRTSPResult
5927 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5928     GstRTSPMessage * request, GstRTSPMessage * response,
5929     GstRTSPStatusCode * code)
5930 {
5931   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5932   GstRTSPResult res = GST_RTSP_ERROR;
5933   gint count;
5934   gboolean retry;
5935   GstRTSPMethod method = GST_RTSP_INVALID;
5936
5937   count = 0;
5938   do {
5939     retry = FALSE;
5940
5941     /* make sure we don't loop forever */
5942     if (count++ > 8)
5943       break;
5944
5945     /* save method so we can disable it when the server complains */
5946     method = request->type_data.request.method;
5947
5948     if ((res =
5949             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5950       goto error;
5951
5952     switch (int_code) {
5953       case GST_RTSP_STS_UNAUTHORIZED:
5954       case GST_RTSP_STS_NOT_FOUND:
5955         if (gst_rtspsrc_setup_auth (src, response)) {
5956           /* Try the request/response again after configuring the auth info
5957            * and loop again */
5958           retry = TRUE;
5959         }
5960         break;
5961       default:
5962         break;
5963     }
5964   } while (retry == TRUE);
5965
5966   /* If the user requested the code, let them handle errors, otherwise
5967    * post an error below */
5968   if (code != NULL)
5969     *code = int_code;
5970   else if (int_code != GST_RTSP_STS_OK)
5971     goto error_response;
5972
5973   return res;
5974
5975   /* ERRORS */
5976 error:
5977   {
5978     GST_DEBUG_OBJECT (src, "got error %d", res);
5979     return res;
5980   }
5981 error_response:
5982   {
5983     res = GST_RTSP_ERROR;
5984
5985     switch (response->type_data.response.code) {
5986       case GST_RTSP_STS_NOT_FOUND:
5987         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5988                 response->type_data.response.reason));
5989         break;
5990       case GST_RTSP_STS_UNAUTHORIZED:
5991         GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED, (NULL), ("%s",
5992                 response->type_data.response.reason));
5993         break;
5994       case GST_RTSP_STS_MOVED_PERMANENTLY:
5995       case GST_RTSP_STS_MOVE_TEMPORARILY:
5996       {
5997         gchar *new_location;
5998         GstRTSPLowerTrans transports;
5999
6000         GST_DEBUG_OBJECT (src, "got redirection");
6001         /* if we don't have a Location Header, we must error */
6002         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
6003                 &new_location, 0) < 0)
6004           break;
6005
6006         /* When we receive a redirect result, we go back to the INIT state after
6007          * parsing the new URI. The caller should do the needed steps to issue
6008          * a new setup when it detects this state change. */
6009         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
6010
6011         /* save current transports */
6012         if (src->conninfo.url)
6013           transports = src->conninfo.url->transports;
6014         else
6015           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
6016
6017         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
6018
6019         /* set old transports */
6020         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
6021           src->conninfo.url->transports = transports;
6022
6023         src->need_redirect = TRUE;
6024         src->state = GST_RTSP_STATE_INIT;
6025         res = GST_RTSP_OK;
6026         break;
6027       }
6028       case GST_RTSP_STS_NOT_ACCEPTABLE:
6029       case GST_RTSP_STS_NOT_IMPLEMENTED:
6030       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
6031         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
6032             gst_rtsp_method_as_text (method));
6033         src->methods &= ~method;
6034         res = GST_RTSP_OK;
6035         break;
6036       default:
6037         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6038             ("Got error response: %d (%s).", response->type_data.response.code,
6039                 response->type_data.response.reason));
6040         break;
6041     }
6042     /* if we return ERROR we should unset the response ourselves */
6043     if (res == GST_RTSP_ERROR)
6044       gst_rtsp_message_unset (response);
6045
6046     return res;
6047   }
6048 }
6049
6050 static GstRTSPResult
6051 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
6052     GstRTSPMessage * response, GstRTSPSrc * src)
6053 {
6054   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
6055       NULL);
6056 }
6057
6058
6059 /* parse the response and collect all the supported methods. We need this
6060  * information so that we don't try to send an unsupported request to the
6061  * server.
6062  */
6063 static gboolean
6064 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
6065 {
6066   GstRTSPHeaderField field;
6067   gchar *respoptions;
6068   gint indx = 0;
6069
6070   /* reset supported methods */
6071   src->methods = 0;
6072
6073   /* Try Allow Header first */
6074   field = GST_RTSP_HDR_ALLOW;
6075   while (TRUE) {
6076     respoptions = NULL;
6077     gst_rtsp_message_get_header (response, field, &respoptions, indx);
6078     if (indx == 0 && !respoptions) {
6079       /* if no Allow header was found then try the Public header... */
6080       field = GST_RTSP_HDR_PUBLIC;
6081       gst_rtsp_message_get_header (response, field, &respoptions, indx);
6082     }
6083     if (!respoptions)
6084       break;
6085
6086     src->methods |= gst_rtsp_options_from_text (respoptions);
6087
6088     indx++;
6089   }
6090
6091   if (src->methods == 0) {
6092     /* neither Allow nor Public are required, assume the server supports
6093      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
6094      * well. */
6095     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
6096     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
6097   }
6098   /* always assume PLAY, FIXME, extensions should be able to override
6099    * this */
6100   src->methods |= GST_RTSP_PLAY;
6101   /* also assume it will support Range */
6102   src->seekable = TRUE;
6103
6104   /* we need describe and setup */
6105   if (!(src->methods & GST_RTSP_DESCRIBE))
6106     goto no_describe;
6107   if (!(src->methods & GST_RTSP_SETUP))
6108     goto no_setup;
6109
6110   return TRUE;
6111
6112   /* ERRORS */
6113 no_describe:
6114   {
6115     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
6116         ("Server does not support DESCRIBE."));
6117     return FALSE;
6118   }
6119 no_setup:
6120   {
6121     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
6122         ("Server does not support SETUP."));
6123     return FALSE;
6124   }
6125 }
6126
6127 /* masks to be kept in sync with the hardcoded protocol order of preference
6128  * in code below */
6129 static const guint protocol_masks[] = {
6130   GST_RTSP_LOWER_TRANS_UDP,
6131   GST_RTSP_LOWER_TRANS_UDP_MCAST,
6132   GST_RTSP_LOWER_TRANS_TCP,
6133   0
6134 };
6135
6136 static GstRTSPResult
6137 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
6138     GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
6139 {
6140   GstRTSPResult res;
6141   GString *result;
6142   gboolean add_udp_str;
6143
6144   *transports = NULL;
6145
6146   res =
6147       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
6148
6149   if (res < 0)
6150     goto failed;
6151
6152   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
6153
6154   /* extension listed transports, use those */
6155   if (*transports != NULL)
6156     return GST_RTSP_OK;
6157
6158   /* it's the default */
6159   add_udp_str = FALSE;
6160
6161   /* the default RTSP transports */
6162   result = g_string_new ("RTP");
6163
6164   switch (profile) {
6165     case GST_RTSP_PROFILE_AVP:
6166       g_string_append (result, "/AVP");
6167       break;
6168     case GST_RTSP_PROFILE_SAVP:
6169       g_string_append (result, "/SAVP");
6170       break;
6171     case GST_RTSP_PROFILE_AVPF:
6172       g_string_append (result, "/AVPF");
6173       break;
6174     case GST_RTSP_PROFILE_SAVPF:
6175       g_string_append (result, "/SAVPF");
6176       break;
6177     default:
6178       break;
6179   }
6180
6181   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
6182     GST_DEBUG_OBJECT (src, "adding UDP unicast");
6183     if (add_udp_str)
6184       g_string_append (result, "/UDP");
6185     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
6186   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
6187     GST_DEBUG_OBJECT (src, "adding UDP multicast");
6188     /* we don't have to allocate any UDP ports yet, if the selected transport
6189      * turns out to be multicast we can create them and join the multicast
6190      * group indicated in the transport reply */
6191     if (add_udp_str)
6192       g_string_append (result, "/UDP");
6193     g_string_append (result, ";multicast");
6194     if (src->next_port_num != 0) {
6195       if (src->client_port_range.max > 0 &&
6196           src->next_port_num >= src->client_port_range.max)
6197         goto no_ports;
6198
6199       g_string_append_printf (result, ";client_port=%d-%d",
6200           src->next_port_num, src->next_port_num + 1);
6201     }
6202   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
6203     GST_DEBUG_OBJECT (src, "adding TCP");
6204
6205     g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
6206   }
6207   *transports = g_string_free (result, FALSE);
6208
6209   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
6210
6211   return GST_RTSP_OK;
6212
6213   /* ERRORS */
6214 failed:
6215   {
6216     GST_ERROR ("extension gave error %d", res);
6217     return res;
6218   }
6219 no_ports:
6220   {
6221     GST_ERROR ("no more ports available");
6222     return GST_RTSP_ERROR;
6223   }
6224 }
6225
6226 static GstRTSPResult
6227 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
6228     gint orig_rtpport, gint orig_rtcpport)
6229 {
6230   GstRTSPSrc *src;
6231   gint nr_udp, nr_int;
6232   gchar *next, *p;
6233   gint rtpport = 0, rtcpport = 0;
6234   GString *str;
6235
6236   src = stream->parent;
6237
6238   /* find number of placeholders first */
6239   if (strstr (*transports, "%%i2"))
6240     nr_int = 2;
6241   else if (strstr (*transports, "%%i1"))
6242     nr_int = 1;
6243   else
6244     nr_int = 0;
6245
6246   if (strstr (*transports, "%%u2"))
6247     nr_udp = 2;
6248   else if (strstr (*transports, "%%u1"))
6249     nr_udp = 1;
6250   else
6251     nr_udp = 0;
6252
6253   if (nr_udp == 0 && nr_int == 0)
6254     goto done;
6255
6256   if (nr_udp > 0) {
6257     if (!orig_rtpport || !orig_rtcpport) {
6258       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
6259         goto failed;
6260     } else {
6261       rtpport = orig_rtpport;
6262       rtcpport = orig_rtcpport;
6263     }
6264   }
6265
6266   str = g_string_new ("");
6267   p = *transports;
6268   while ((next = strstr (p, "%%"))) {
6269     g_string_append_len (str, p, next - p);
6270     if (next[2] == 'u') {
6271       if (next[3] == '1')
6272         g_string_append_printf (str, "%d", rtpport);
6273       else if (next[3] == '2')
6274         g_string_append_printf (str, "%d", rtcpport);
6275     }
6276     if (next[2] == 'i') {
6277       if (next[3] == '1')
6278         g_string_append_printf (str, "%d", src->free_channel);
6279       else if (next[3] == '2')
6280         g_string_append_printf (str, "%d", src->free_channel + 1);
6281     }
6282
6283     p = next + 4;
6284   }
6285   /* append final part */
6286   g_string_append (str, p);
6287
6288   g_free (*transports);
6289   *transports = g_string_free (str, FALSE);
6290
6291 done:
6292   return GST_RTSP_OK;
6293
6294   /* ERRORS */
6295 failed:
6296   {
6297     GST_ERROR ("failed to allocate udp ports");
6298     return GST_RTSP_ERROR;
6299   }
6300 }
6301
6302 static guint8
6303 enc_key_length_from_cipher_name (const gchar * cipher)
6304 {
6305   if (g_strcmp0 (cipher, "aes-128-icm") == 0)
6306     return AES_128_KEY_LEN;
6307   else if (g_strcmp0 (cipher, "aes-256-icm") == 0)
6308     return AES_256_KEY_LEN;
6309   else {
6310     GST_ERROR ("encryption algorithm '%s' not supported", cipher);
6311     return 0;
6312   }
6313 }
6314
6315 static guint8
6316 auth_key_length_from_auth_name (const gchar * auth)
6317 {
6318   if (g_strcmp0 (auth, "hmac-sha1-32") == 0)
6319     return HMAC_32_KEY_LEN;
6320   else if (g_strcmp0 (auth, "hmac-sha1-80") == 0)
6321     return HMAC_80_KEY_LEN;
6322   else {
6323     GST_ERROR ("authentication algorithm '%s' not supported", auth);
6324     return 0;
6325   }
6326 }
6327
6328 static GstCaps *
6329 signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
6330 {
6331   GstCaps *caps = NULL;
6332
6333   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
6334       stream->id, &caps);
6335
6336   if (caps != NULL)
6337     GST_DEBUG_OBJECT (src, "SRTP parameters received");
6338
6339   return caps;
6340 }
6341
6342 static GstCaps *
6343 default_srtcp_params (void)
6344 {
6345   guint i;
6346   GstCaps *caps;
6347   GstBuffer *buf;
6348   guint8 *key_data;
6349 #define KEY_SIZE 30
6350   guint data_size = GST_ROUND_UP_4 (KEY_SIZE);
6351
6352   /* create a random key */
6353   key_data = g_malloc (data_size);
6354   for (i = 0; i < data_size; i += 4)
6355     GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
6356
6357   buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
6358
6359   caps = gst_caps_new_simple ("application/x-srtp",
6360       "srtp-key", GST_TYPE_BUFFER, buf,
6361       "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
6362       "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
6363
6364   gst_buffer_unref (buf);
6365
6366   return caps;
6367 }
6368
6369 static gchar *
6370 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
6371 {
6372   GBytes *bytes;
6373   gchar *result, *base64;
6374   const guint8 *data;
6375   gsize size;
6376   GstMIKEYMessage *msg;
6377   GstMIKEYPayload *payload, *pkd;
6378   guint8 byte;
6379   GstStructure *s;
6380   GstMapInfo info;
6381   GstBuffer *srtpkey;
6382   const GValue *val;
6383   const gchar *srtcpcipher, *srtcpauth;
6384
6385   stream->srtcpparams = signal_get_srtcp_params (src, stream);
6386   if (stream->srtcpparams == NULL)
6387     stream->srtcpparams = default_srtcp_params ();
6388
6389   s = gst_caps_get_structure (stream->srtcpparams, 0);
6390
6391   srtcpcipher = gst_structure_get_string (s, "srtcp-cipher");
6392   srtcpauth = gst_structure_get_string (s, "srtcp-auth");
6393   val = gst_structure_get_value (s, "srtp-key");
6394
6395   if (srtcpcipher == NULL || srtcpauth == NULL || val == NULL) {
6396     GST_ERROR_OBJECT (src, "could not find the right SRTP parameters in caps");
6397     return NULL;
6398   }
6399
6400   srtpkey = gst_value_get_buffer (val);
6401
6402   msg = gst_mikey_message_new ();
6403   /* unencrypted MIKEY message, we send this over TLS so this is allowed */
6404   gst_mikey_message_set_info (msg, GST_MIKEY_VERSION, GST_MIKEY_TYPE_PSK_INIT,
6405       FALSE, GST_MIKEY_PRF_MIKEY_1, g_random_int (), GST_MIKEY_MAP_TYPE_SRTP);
6406   /* add policy '0' for our SSRC */
6407   gst_mikey_message_add_cs_srtp (msg, 0, stream->send_ssrc, 0);
6408   /* timestamp is now */
6409   gst_mikey_message_add_t_now_ntp_utc (msg);
6410   /* add some random data */
6411   gst_mikey_message_add_rand_len (msg, 16);
6412
6413   /* the policy '0' is SRTP */
6414   payload = gst_mikey_payload_new (GST_MIKEY_PT_SP);
6415   gst_mikey_payload_sp_set (payload, 0, GST_MIKEY_SEC_PROTO_SRTP);
6416
6417   /* only AES-CM is supported */
6418   byte = 1;
6419   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_ALG, 1, &byte);
6420   /* encryption key length */
6421   byte = enc_key_length_from_cipher_name (srtcpcipher);
6422   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_KEY_LEN, 1,
6423       &byte);
6424   /* only HMAC-SHA1 */
6425   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_ALG, 1,
6426       &byte);
6427   /* authentication key length */
6428   byte = auth_key_length_from_auth_name (srtcpauth);
6429   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_KEY_LEN, 1,
6430       &byte);
6431   /* we enable encryption on RTP and RTCP */
6432   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_ENC, 1,
6433       &byte);
6434   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTCP_ENC, 1,
6435       &byte);
6436   /* we enable authentication on RTP and RTCP */
6437   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_AUTH, 1,
6438       &byte);
6439   gst_mikey_message_add_payload (msg, payload);
6440
6441   /* make unencrypted KEMAC */
6442   payload = gst_mikey_payload_new (GST_MIKEY_PT_KEMAC);
6443   gst_mikey_payload_kemac_set (payload, GST_MIKEY_ENC_NULL, GST_MIKEY_MAC_NULL);
6444   /* add the key in KEMAC */
6445   pkd = gst_mikey_payload_new (GST_MIKEY_PT_KEY_DATA);
6446   gst_buffer_map (srtpkey, &info, GST_MAP_READ);
6447   gst_mikey_payload_key_data_set_key (pkd, GST_MIKEY_KD_TEK, info.size,
6448       info.data);
6449   gst_buffer_unmap (srtpkey, &info);
6450   gst_mikey_payload_kemac_add_sub (payload, pkd);
6451   gst_mikey_message_add_payload (msg, payload);
6452
6453   /* now serialize this to bytes */
6454   bytes = gst_mikey_message_to_bytes (msg, NULL, NULL);
6455   gst_mikey_message_unref (msg);
6456   /* and make it into base64 */
6457   data = g_bytes_get_data (bytes, &size);
6458   base64 = g_base64_encode (data, size);
6459   g_bytes_unref (bytes);
6460
6461   result = g_strdup_printf ("prot=mikey;uri=\"%s\";data=\"%s\"",
6462       stream->conninfo.location, base64);
6463   g_free (base64);
6464
6465   return result;
6466 }
6467
6468
6469 /* Perform the SETUP request for all the streams.
6470  *
6471  * We ask the server for a specific transport, which initially includes all the
6472  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6473  * two local UDP ports that we send to the server.
6474  *
6475  * Once the server replied with a transport, we configure the other streams
6476  * with the same transport.
6477  *
6478  * This function will also configure the stream for the selected transport,
6479  * which basically means creating the pipeline.
6480  */
6481 static GstRTSPResult
6482 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
6483 {
6484   GList *walk;
6485   GstRTSPResult res = GST_RTSP_ERROR;
6486   GstRTSPMessage request = { 0 };
6487   GstRTSPMessage response = { 0 };
6488   GstRTSPStream *stream = NULL;
6489   GstRTSPLowerTrans protocols;
6490   GstRTSPStatusCode code;
6491   gboolean unsupported_real = FALSE;
6492   gint rtpport, rtcpport;
6493   GstRTSPUrl *url;
6494   gchar *hval;
6495
6496   if (src->conninfo.connection) {
6497     url = gst_rtsp_connection_get_url (src->conninfo.connection);
6498     /* we initially allow all configured lower transports. based on the URL
6499      * transports and the replies from the server we narrow them down. */
6500     protocols = url->transports & src->cur_protocols;
6501   } else {
6502     url = NULL;
6503     protocols = src->cur_protocols;
6504   }
6505
6506   if (protocols == 0)
6507     goto no_protocols;
6508
6509   /* reset some state */
6510   src->free_channel = 0;
6511   src->interleaved = FALSE;
6512   src->need_activate = FALSE;
6513   /* keep track of next port number, 0 is random */
6514   src->next_port_num = src->client_port_range.min;
6515   rtpport = rtcpport = 0;
6516
6517   if (G_UNLIKELY (src->streams == NULL))
6518     goto no_streams;
6519
6520   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6521     GstRTSPConnection *conn;
6522     gchar *transports;
6523     gint retry = 0;
6524     guint mask = 0;
6525     gboolean selected;
6526     GstCaps *caps;
6527
6528     stream = (GstRTSPStream *) walk->data;
6529
6530     caps = stream_get_caps_for_pt (stream, stream->default_pt);
6531     if (caps == NULL) {
6532       GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
6533       continue;
6534     }
6535
6536     if (stream->skipped) {
6537       GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6538       continue;
6539     }
6540
6541     /* see if we need to configure this stream */
6542     if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6543       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6544           stream);
6545       continue;
6546     }
6547
6548     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6549         stream->id, caps, &selected);
6550     if (!selected) {
6551       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6552       continue;
6553     }
6554
6555     /* merge/overwrite global caps */
6556     if (caps) {
6557       guint j, num;
6558       GstStructure *s;
6559
6560       s = gst_caps_get_structure (caps, 0);
6561
6562       num = gst_structure_n_fields (src->props);
6563       for (j = 0; j < num; j++) {
6564         const gchar *name;
6565         const GValue *val;
6566
6567         name = gst_structure_nth_field_name (src->props, j);
6568         val = gst_structure_get_value (src->props, name);
6569         gst_structure_set_value (s, name, val);
6570
6571         GST_DEBUG_OBJECT (src, "copied %s", name);
6572       }
6573     }
6574
6575     /* skip setup if we have no URL for it */
6576     if (stream->conninfo.location == NULL) {
6577       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6578       continue;
6579     }
6580
6581     if (src->conninfo.connection == NULL) {
6582       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6583         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6584         continue;
6585       }
6586       conn = stream->conninfo.connection;
6587     } else {
6588       conn = src->conninfo.connection;
6589     }
6590     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6591         stream->conninfo.location);
6592
6593     /* if we have a multicast connection, only suggest multicast from now on */
6594     if (stream->is_multicast)
6595       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6596
6597   next_protocol:
6598     /* first selectable protocol */
6599     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6600       mask++;
6601     if (!protocol_masks[mask])
6602       goto no_protocols;
6603
6604   retry:
6605     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6606         protocol_masks[mask]);
6607     /* create a string with first transport in line */
6608     transports = NULL;
6609     res = gst_rtspsrc_create_transports_string (src,
6610         protocols & protocol_masks[mask], stream->profile, &transports);
6611     if (res < 0 || transports == NULL)
6612       goto setup_transport_failed;
6613
6614     if (strlen (transports) == 0) {
6615       g_free (transports);
6616       GST_DEBUG_OBJECT (src, "no transports found");
6617       mask++;
6618       goto next_protocol;
6619     }
6620
6621     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6622
6623     /* replace placeholders with real values, this function will optionally
6624      * allocate UDP ports and other info needed to execute the setup request */
6625     res = gst_rtspsrc_prepare_transports (stream, &transports,
6626         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6627     if (res < 0) {
6628       g_free (transports);
6629       goto setup_transport_failed;
6630     }
6631
6632     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6633
6634     /* create SETUP request */
6635     res =
6636         gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
6637         stream->conninfo.location);
6638     if (res < 0) {
6639       g_free (transports);
6640       goto create_request_failed;
6641     }
6642
6643     /* select transport */
6644     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6645
6646     /* set up keys */
6647     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6648         stream->profile == GST_RTSP_PROFILE_SAVPF) {
6649       hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6650       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6651     }
6652
6653     /* if the user wants a non default RTP packet size we add the blocksize
6654      * parameter */
6655     if (src->rtp_blocksize > 0) {
6656       hval = g_strdup_printf ("%d", src->rtp_blocksize);
6657       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6658     }
6659
6660     if (async)
6661       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6662               stream->id));
6663
6664     /* handle the code ourselves */
6665     res = gst_rtspsrc_send (src, conn, &request, &response, &code);
6666     if (res < 0)
6667       goto send_error;
6668
6669     switch (code) {
6670       case GST_RTSP_STS_OK:
6671         break;
6672       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6673         gst_rtsp_message_unset (&request);
6674         gst_rtsp_message_unset (&response);
6675         /* cleanup of leftover transport */
6676         gst_rtspsrc_stream_free_udp (stream);
6677         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6678          * we might be in this case */
6679         if (stream->container && rtpport && rtcpport && !retry) {
6680           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6681               rtpport, rtcpport);
6682           retry++;
6683           goto retry;
6684         }
6685         /* this transport did not go down well, but we may have others to try
6686          * that we did not send yet, try those and only give up then
6687          * but not without checking for lost cause/extension so we can
6688          * post a nicer/more useful error message later */
6689         if (!unsupported_real)
6690           unsupported_real = stream->is_real;
6691         /* select next available protocol, give up on this stream if none */
6692         mask++;
6693         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6694           mask++;
6695         if (!protocol_masks[mask] || unsupported_real)
6696           continue;
6697         else
6698           goto retry;
6699       default:
6700         /* cleanup of leftover transport and move to the next stream */
6701         gst_rtspsrc_stream_free_udp (stream);
6702         goto response_error;
6703     }
6704
6705     /* parse response transport */
6706     {
6707       gchar *resptrans = NULL;
6708       GstRTSPTransport transport = { 0 };
6709
6710       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
6711           &resptrans, 0);
6712       if (!resptrans) {
6713         gst_rtspsrc_stream_free_udp (stream);
6714         goto no_transport;
6715       }
6716
6717       /* parse transport, go to next stream on parse error */
6718       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6719         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6720         goto next;
6721       }
6722
6723       /* update allowed transports for other streams. once the transport of
6724        * one stream has been determined, we make sure that all other streams
6725        * are configured in the same way */
6726       switch (transport.lower_transport) {
6727         case GST_RTSP_LOWER_TRANS_TCP:
6728           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6729           protocols = GST_RTSP_LOWER_TRANS_TCP;
6730           src->interleaved = TRUE;
6731           /* update free channels */
6732           src->free_channel =
6733               MAX (transport.interleaved.min, src->free_channel);
6734           src->free_channel =
6735               MAX (transport.interleaved.max, src->free_channel);
6736           src->free_channel++;
6737           break;
6738         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6739           /* only allow multicast for other streams */
6740           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6741           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6742           /* if the server selected our ports, increment our counters so that
6743            * we select a new port later */
6744           if (src->next_port_num == transport.port.min &&
6745               src->next_port_num + 1 == transport.port.max) {
6746             src->next_port_num += 2;
6747           }
6748           break;
6749         case GST_RTSP_LOWER_TRANS_UDP:
6750           /* only allow unicast for other streams */
6751           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6752           protocols = GST_RTSP_LOWER_TRANS_UDP;
6753           break;
6754         default:
6755           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6756               transport.lower_transport);
6757           break;
6758       }
6759
6760       if (!src->interleaved || !retry) {
6761         /* now configure the stream with the selected transport */
6762         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6763           GST_DEBUG_OBJECT (src,
6764               "could not configure stream %p transport, skipping stream",
6765               stream);
6766           goto next;
6767         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
6768           /* retain the first allocated UDP port pair */
6769           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
6770           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
6771         }
6772       }
6773       /* we need to activate at least one streams when we detect activity */
6774       src->need_activate = TRUE;
6775
6776       /* stream is setup now */
6777       stream->setup = TRUE;
6778       {
6779         GList *skip = walk;
6780
6781         while (TRUE) {
6782           GstRTSPStream *sskip;
6783
6784           skip = g_list_next (skip);
6785           if (skip == NULL)
6786             break;
6787
6788           sskip = (GstRTSPStream *) skip->data;
6789
6790           /* skip all streams with the same control url */
6791           if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6792             GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6793                 sskip, sskip->conninfo.location);
6794             sskip->skipped = TRUE;
6795           }
6796         }
6797       }
6798     next:
6799       /* clean up our transport struct */
6800       gst_rtsp_transport_init (&transport);
6801       /* clean up used RTSP messages */
6802       gst_rtsp_message_unset (&request);
6803       gst_rtsp_message_unset (&response);
6804     }
6805   }
6806
6807   /* store the transport protocol that was configured */
6808   src->cur_protocols = protocols;
6809
6810   gst_rtsp_ext_list_stream_select (src->extensions, url);
6811
6812   /* if there is nothing to activate, error out */
6813   if (!src->need_activate)
6814     goto nothing_to_activate;
6815
6816   return res;
6817
6818   /* ERRORS */
6819 no_protocols:
6820   {
6821     /* no transport possible, post an error and stop */
6822     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6823         ("Could not connect to server, no protocols left"));
6824     return GST_RTSP_ERROR;
6825   }
6826 no_streams:
6827   {
6828     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6829         ("SDP contains no streams"));
6830     return GST_RTSP_ERROR;
6831   }
6832 create_request_failed:
6833   {
6834     gchar *str = gst_rtsp_strresult (res);
6835
6836     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6837         ("Could not create request. (%s)", str));
6838     g_free (str);
6839     goto cleanup_error;
6840   }
6841 setup_transport_failed:
6842   {
6843     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6844         ("Could not setup transport."));
6845     res = GST_RTSP_ERROR;
6846     goto cleanup_error;
6847   }
6848 response_error:
6849   {
6850     const gchar *str = gst_rtsp_status_as_text (code);
6851
6852     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6853         ("Error (%d): %s", code, GST_STR_NULL (str)));
6854     res = GST_RTSP_ERROR;
6855     goto cleanup_error;
6856   }
6857 send_error:
6858   {
6859     gchar *str = gst_rtsp_strresult (res);
6860
6861     if (res != GST_RTSP_EINTR) {
6862       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6863           ("Could not send message. (%s)", str));
6864     } else {
6865       GST_WARNING_OBJECT (src, "send interrupted");
6866     }
6867     g_free (str);
6868     goto cleanup_error;
6869   }
6870 no_transport:
6871   {
6872     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6873         ("Server did not select transport."));
6874     res = GST_RTSP_ERROR;
6875     goto cleanup_error;
6876   }
6877 nothing_to_activate:
6878   {
6879     /* none of the available error codes is really right .. */
6880     if (unsupported_real) {
6881       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6882           (_("No supported stream was found. You might need to install a "
6883                   "GStreamer RTSP extension plugin for Real media streams.")),
6884           (NULL));
6885     } else {
6886       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6887           (_("No supported stream was found. You might need to allow "
6888                   "more transport protocols or may otherwise be missing "
6889                   "the right GStreamer RTSP extension plugin.")), (NULL));
6890     }
6891     return GST_RTSP_ERROR;
6892   }
6893 cleanup_error:
6894   {
6895     gst_rtsp_message_unset (&request);
6896     gst_rtsp_message_unset (&response);
6897     return res;
6898   }
6899 }
6900
6901 static gboolean
6902 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6903     GstSegment * segment)
6904 {
6905   gint64 seconds;
6906   GstRTSPTimeRange *therange;
6907
6908   if (src->range)
6909     gst_rtsp_range_free (src->range);
6910
6911   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6912     GST_DEBUG_OBJECT (src, "parsed range %s", range);
6913     src->range = therange;
6914   } else {
6915     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6916     src->range = NULL;
6917     gst_segment_init (segment, GST_FORMAT_TIME);
6918     return FALSE;
6919   }
6920
6921   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
6922       therange->min.type, therange->min.seconds, therange->max.type,
6923       therange->max.seconds);
6924
6925   if (therange->min.type == GST_RTSP_TIME_NOW)
6926     seconds = 0;
6927   else if (therange->min.type == GST_RTSP_TIME_END)
6928     seconds = 0;
6929   else
6930     seconds = therange->min.seconds * GST_SECOND;
6931
6932   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6933       GST_TIME_ARGS (seconds));
6934
6935   /* we need to start playback without clipping from the position reported by
6936    * the server */
6937   segment->start = seconds;
6938   segment->position = seconds;
6939
6940   if (therange->max.type == GST_RTSP_TIME_NOW)
6941     seconds = -1;
6942   else if (therange->max.type == GST_RTSP_TIME_END)
6943     seconds = -1;
6944   else
6945     seconds = therange->max.seconds * GST_SECOND;
6946
6947   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6948       GST_TIME_ARGS (seconds));
6949
6950   /* live (WMS) server might send overflowed large max as its idea of infinity,
6951    * compensate to prevent problems later on */
6952   if (seconds != -1 && seconds < 0) {
6953     seconds = -1;
6954     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6955   }
6956
6957   /* live (WMS) might send min == max, which is not worth recording */
6958   if (segment->duration == -1 && seconds == segment->start)
6959     seconds = -1;
6960
6961   /* don't change duration with unknown value, we might have a valid value
6962    * there that we want to keep. */
6963   if (seconds != -1)
6964     segment->duration = seconds;
6965
6966   return TRUE;
6967 }
6968
6969 /* Parse clock profived by the server with following syntax:
6970  *
6971  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6972  */
6973 static gboolean
6974 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6975 {
6976   gboolean res = FALSE;
6977
6978   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6979     gchar **fields = NULL, **parts = NULL;
6980     gchar *remote_ip, *str;
6981     gint port;
6982     GstClockTime base_time;
6983     GstClock *netclock;
6984
6985     fields = g_strsplit (gstclock, " ", 0);
6986
6987     /* wrapped clock, not very interesting for now */
6988     if (fields[1] == NULL)
6989       goto cleanup;
6990
6991     /* remote IP address and port */
6992     if ((str = fields[2]) == NULL)
6993       goto cleanup;
6994
6995     parts = g_strsplit (str, ":", 0);
6996
6997     if ((remote_ip = parts[0]) == NULL)
6998       goto cleanup;
6999
7000     if ((str = parts[1]) == NULL)
7001       goto cleanup;
7002
7003     port = atoi (str);
7004     if (port == 0)
7005       goto cleanup;
7006
7007     /* base-time */
7008     if ((str = fields[3]) == NULL)
7009       goto cleanup;
7010
7011     base_time = g_ascii_strtoull (str, NULL, 10);
7012
7013     netclock =
7014         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
7015         base_time);
7016
7017     if (src->provided_clock)
7018       gst_object_unref (src->provided_clock);
7019     src->provided_clock = netclock;
7020
7021     gst_element_post_message (GST_ELEMENT_CAST (src),
7022         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
7023             src->provided_clock, TRUE));
7024
7025     res = TRUE;
7026   cleanup:
7027     g_strfreev (fields);
7028     g_strfreev (parts);
7029   }
7030   return res;
7031 }
7032
7033 /* must be called with the RTSP state lock */
7034 static GstRTSPResult
7035 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
7036     gboolean async)
7037 {
7038   GstRTSPResult res;
7039   gint i, n_streams;
7040
7041   /* prepare global stream caps properties */
7042   if (src->props)
7043     gst_structure_remove_all_fields (src->props);
7044   else
7045     src->props = gst_structure_new_empty ("RTSPProperties");
7046
7047   if (src->debug)
7048     gst_sdp_message_dump (sdp);
7049
7050   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
7051
7052   /* let the app inspect and change the SDP */
7053   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
7054
7055   gst_segment_init (&src->segment, GST_FORMAT_TIME);
7056
7057   /* parse range for duration reporting. */
7058   {
7059     const gchar *range;
7060
7061     for (i = 0;; i++) {
7062       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
7063       if (range == NULL)
7064         break;
7065
7066       /* keep track of the range and configure it in the segment */
7067       if (gst_rtspsrc_parse_range (src, range, &src->segment))
7068         break;
7069     }
7070   }
7071   /* parse clock information. This is GStreamer specific, a server can tell the
7072    * client what clock it is using and wrap that in a network clock. The
7073    * advantage of that is that we can slave to it. */
7074   {
7075     const gchar *gstclock;
7076
7077     for (i = 0;; i++) {
7078       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
7079       if (gstclock == NULL)
7080         break;
7081
7082       /* parse the clock and expose it in the provide_clock method */
7083       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
7084         break;
7085     }
7086   }
7087   /* try to find a global control attribute. Note that a '*' means that we should
7088    * do aggregate control with the current url (so we don't do anything and
7089    * leave the current connection as is) */
7090   {
7091     const gchar *control;
7092
7093     for (i = 0;; i++) {
7094       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
7095       if (control == NULL)
7096         break;
7097
7098       /* only take fully qualified urls */
7099       if (g_str_has_prefix (control, "rtsp://"))
7100         break;
7101     }
7102     if (control) {
7103       g_free (src->conninfo.location);
7104       src->conninfo.location = g_strdup (control);
7105       /* make a connection for this, if there was a connection already, nothing
7106        * happens. */
7107       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
7108         GST_ERROR_OBJECT (src, "could not connect");
7109       }
7110     }
7111     /* we need to keep the control url separate from the connection url because
7112      * the rules for constructing the media control url need it */
7113     g_free (src->control);
7114     src->control = g_strdup (control);
7115   }
7116
7117   /* create streams */
7118   n_streams = gst_sdp_message_medias_len (sdp);
7119   for (i = 0; i < n_streams; i++) {
7120     gst_rtspsrc_create_stream (src, sdp, i);
7121   }
7122
7123   src->state = GST_RTSP_STATE_INIT;
7124
7125   /* setup streams */
7126   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
7127     goto setup_failed;
7128
7129   /* reset our state */
7130   src->need_range = TRUE;
7131   src->skip = FALSE;
7132
7133   src->state = GST_RTSP_STATE_READY;
7134
7135   return res;
7136
7137   /* ERRORS */
7138 setup_failed:
7139   {
7140     GST_ERROR_OBJECT (src, "setup failed");
7141     gst_rtspsrc_cleanup (src);
7142     return res;
7143   }
7144 }
7145
7146 static GstRTSPResult
7147 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
7148     gboolean async)
7149 {
7150   GstRTSPResult res;
7151   GstRTSPMessage request = { 0 };
7152   GstRTSPMessage response = { 0 };
7153   guint8 *data;
7154   guint size;
7155   gchar *respcont = NULL;
7156
7157 restart:
7158   src->need_redirect = FALSE;
7159
7160   /* can't continue without a valid url */
7161   if (G_UNLIKELY (src->conninfo.url == NULL)) {
7162     res = GST_RTSP_EINVAL;
7163     goto no_url;
7164   }
7165   src->tried_url_auth = FALSE;
7166
7167   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
7168     goto connect_failed;
7169
7170   /* create OPTIONS */
7171   GST_DEBUG_OBJECT (src, "create options...");
7172   res =
7173       gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
7174       src->conninfo.url_str);
7175   if (res < 0)
7176     goto create_request_failed;
7177
7178   /* send OPTIONS */
7179   GST_DEBUG_OBJECT (src, "send options...");
7180
7181   if (async)
7182     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
7183
7184   if ((res =
7185           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
7186               NULL)) < 0)
7187     goto send_error;
7188
7189   /* parse OPTIONS */
7190   if (!gst_rtspsrc_parse_methods (src, &response))
7191     goto methods_error;
7192
7193   /* create DESCRIBE */
7194   GST_DEBUG_OBJECT (src, "create describe...");
7195   res =
7196       gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
7197       src->conninfo.url_str);
7198   if (res < 0)
7199     goto create_request_failed;
7200
7201   /* we only accept SDP for now */
7202   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
7203       "application/sdp");
7204
7205   /* send DESCRIBE */
7206   GST_DEBUG_OBJECT (src, "send describe...");
7207
7208   if (async)
7209     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
7210
7211   if ((res =
7212           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
7213               NULL)) < 0)
7214     goto send_error;
7215
7216   /* we only perform redirect for the describe, currently */
7217   if (src->need_redirect) {
7218     /* close connection, we don't have to send a TEARDOWN yet, ignore the
7219      * result. */
7220     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7221
7222     gst_rtsp_message_unset (&request);
7223     gst_rtsp_message_unset (&response);
7224
7225     /* and now retry */
7226     goto restart;
7227   }
7228
7229   /* it could be that the DESCRIBE method was not implemented */
7230   if (!(src->methods & GST_RTSP_DESCRIBE))
7231     goto no_describe;
7232
7233   /* check if reply is SDP */
7234   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
7235       0);
7236   /* could not be set but since the request returned OK, we assume it
7237    * was SDP, else check it. */
7238   if (respcont) {
7239     if (g_ascii_strcasecmp (respcont, "application/sdp") != 0)
7240       goto wrong_content_type;
7241   }
7242
7243   /* get message body and parse as SDP */
7244   gst_rtsp_message_get_body (&response, &data, &size);
7245   if (data == NULL || size == 0)
7246     goto no_describe;
7247
7248   GST_DEBUG_OBJECT (src, "parse SDP...");
7249   gst_sdp_message_new (sdp);
7250   gst_sdp_message_parse_buffer (data, size, *sdp);
7251
7252   /* clean up any messages */
7253   gst_rtsp_message_unset (&request);
7254   gst_rtsp_message_unset (&response);
7255
7256   return res;
7257
7258   /* ERRORS */
7259 no_url:
7260   {
7261     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
7262         ("No valid RTSP URL was provided"));
7263     goto cleanup_error;
7264   }
7265 connect_failed:
7266   {
7267     gchar *str = gst_rtsp_strresult (res);
7268
7269     if (res != GST_RTSP_EINTR) {
7270       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
7271           ("Failed to connect. (%s)", str));
7272     } else {
7273       GST_WARNING_OBJECT (src, "connect interrupted");
7274     }
7275     g_free (str);
7276     goto cleanup_error;
7277   }
7278 create_request_failed:
7279   {
7280     gchar *str = gst_rtsp_strresult (res);
7281
7282     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7283         ("Could not create request. (%s)", str));
7284     g_free (str);
7285     goto cleanup_error;
7286   }
7287 send_error:
7288   {
7289     /* Don't post a message - the rtsp_send method will have
7290      * taken care of it because we passed NULL for the response code */
7291     goto cleanup_error;
7292   }
7293 methods_error:
7294   {
7295     /* error was posted */
7296     res = GST_RTSP_ERROR;
7297     goto cleanup_error;
7298   }
7299 wrong_content_type:
7300   {
7301     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7302         ("Server does not support SDP, got %s.", respcont));
7303     res = GST_RTSP_ERROR;
7304     goto cleanup_error;
7305   }
7306 no_describe:
7307   {
7308     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7309         ("Server can not provide an SDP."));
7310     res = GST_RTSP_ERROR;
7311     goto cleanup_error;
7312   }
7313 cleanup_error:
7314   {
7315     if (src->conninfo.connection) {
7316       GST_DEBUG_OBJECT (src, "free connection");
7317       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7318     }
7319     gst_rtsp_message_unset (&request);
7320     gst_rtsp_message_unset (&response);
7321     return res;
7322   }
7323 }
7324
7325 static GstRTSPResult
7326 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
7327 {
7328   GstRTSPResult ret;
7329
7330   src->methods =
7331       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
7332
7333   if (src->sdp == NULL) {
7334     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
7335       goto no_sdp;
7336   }
7337
7338   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
7339     goto open_failed;
7340
7341 done:
7342   if (async)
7343     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
7344
7345   return ret;
7346
7347   /* ERRORS */
7348 no_sdp:
7349   {
7350     GST_WARNING_OBJECT (src, "can't get sdp");
7351     src->open_error = TRUE;
7352     goto done;
7353   }
7354 open_failed:
7355   {
7356     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
7357     src->open_error = TRUE;
7358     goto done;
7359   }
7360 }
7361
7362 static GstRTSPResult
7363 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
7364 {
7365   GstRTSPMessage request = { 0 };
7366   GstRTSPMessage response = { 0 };
7367   GstRTSPResult res = GST_RTSP_OK;
7368   GList *walk;
7369   const gchar *control;
7370
7371   GST_DEBUG_OBJECT (src, "TEARDOWN...");
7372
7373   gst_rtspsrc_set_state (src, GST_STATE_READY);
7374
7375   if (src->state < GST_RTSP_STATE_READY) {
7376     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
7377     goto close;
7378   }
7379
7380   if (only_close)
7381     goto close;
7382
7383   /* construct a control url */
7384   control = get_aggregate_control (src);
7385
7386   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
7387     goto not_supported;
7388
7389   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7390     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7391     const gchar *setup_url;
7392     GstRTSPConnInfo *info;
7393
7394     /* try aggregate control first but do non-aggregate control otherwise */
7395     if (control)
7396       setup_url = control;
7397     else if ((setup_url = stream->conninfo.location) == NULL)
7398       continue;
7399
7400     if (src->conninfo.connection) {
7401       info = &src->conninfo;
7402     } else if (stream->conninfo.connection) {
7403       info = &stream->conninfo;
7404     } else {
7405       continue;
7406     }
7407     if (!info->connected)
7408       goto next;
7409
7410     /* do TEARDOWN */
7411     res =
7412         gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
7413     if (res < 0)
7414       goto create_request_failed;
7415
7416     if (async)
7417       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
7418
7419     if ((res =
7420             gst_rtspsrc_send (src, info->connection, &request, &response,
7421                 NULL)) < 0)
7422       goto send_error;
7423
7424     /* FIXME, parse result? */
7425     gst_rtsp_message_unset (&request);
7426     gst_rtsp_message_unset (&response);
7427
7428   next:
7429     /* early exit when we did aggregate control */
7430     if (control)
7431       break;
7432   }
7433
7434 close:
7435   /* close connections */
7436   GST_DEBUG_OBJECT (src, "closing connection...");
7437   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7438   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7439     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7440     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
7441   }
7442
7443   /* cleanup */
7444   gst_rtspsrc_cleanup (src);
7445
7446   src->state = GST_RTSP_STATE_INVALID;
7447
7448   if (async)
7449     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
7450
7451   return res;
7452
7453   /* ERRORS */
7454 create_request_failed:
7455   {
7456     gchar *str = gst_rtsp_strresult (res);
7457
7458     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7459         ("Could not create request. (%s)", str));
7460     g_free (str);
7461     goto close;
7462   }
7463 send_error:
7464   {
7465     gchar *str = gst_rtsp_strresult (res);
7466
7467     gst_rtsp_message_unset (&request);
7468     if (res != GST_RTSP_EINTR) {
7469       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7470           ("Could not send message. (%s)", str));
7471     } else {
7472       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7473     }
7474     g_free (str);
7475     goto close;
7476   }
7477 not_supported:
7478   {
7479     GST_DEBUG_OBJECT (src,
7480         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7481     goto close;
7482   }
7483 }
7484
7485 /* RTP-Info is of the format:
7486  *
7487  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7488  *
7489  * rtptime corresponds to the timestamp for the NPT time given in the header
7490  * seqbase corresponds to the next sequence number we received. This number
7491  * indicates the first seqnum after the seek and should be used to discard
7492  * packets that are from before the seek.
7493  */
7494 static gboolean
7495 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7496 {
7497   gchar **infos;
7498   gint i, j;
7499
7500   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7501
7502   infos = g_strsplit (rtpinfo, ",", 0);
7503   for (i = 0; infos[i]; i++) {
7504     gchar **fields;
7505     GstRTSPStream *stream;
7506     gint32 seqbase;
7507     gint64 timebase;
7508
7509     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7510
7511     /* init values, types of seqbase and timebase are bigger than needed so we
7512      * can store -1 as uninitialized values */
7513     stream = NULL;
7514     seqbase = -1;
7515     timebase = -1;
7516
7517     /* parse url, find stream for url.
7518      * parse seq and rtptime. The seq number should be configured in the rtp
7519      * depayloader or session manager to detect gaps. Same for the rtptime, it
7520      * should be used to create an initial time newsegment. */
7521     fields = g_strsplit (infos[i], ";", 0);
7522     for (j = 0; fields[j]; j++) {
7523       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7524       /* remove leading whitespace */
7525       fields[j] = g_strchug (fields[j]);
7526       if (g_str_has_prefix (fields[j], "url=")) {
7527         /* get the url and the stream */
7528         stream =
7529             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7530       } else if (g_str_has_prefix (fields[j], "seq=")) {
7531         seqbase = atoi (fields[j] + 4);
7532       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7533         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7534       }
7535     }
7536     g_strfreev (fields);
7537     /* now we need to store the values for the caps of the stream */
7538     if (stream != NULL) {
7539       GST_DEBUG_OBJECT (src,
7540           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7541           stream, seqbase, timebase);
7542
7543       /* we have a stream, configure detected params */
7544       stream->seqbase = seqbase;
7545       stream->timebase = timebase;
7546     }
7547   }
7548   g_strfreev (infos);
7549
7550   return TRUE;
7551 }
7552
7553 static void
7554 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7555 {
7556   guint64 interval;
7557   GList *walk;
7558
7559   interval = strtoul (rtcp, NULL, 10);
7560   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7561
7562   if (!interval)
7563     return;
7564
7565   interval *= GST_MSECOND;
7566
7567   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7568     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7569
7570     /* already (optionally) retrieved this when configuring manager */
7571     if (stream->session) {
7572       GObject *rtpsession = stream->session;
7573
7574       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7575           rtpsession);
7576       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7577     }
7578   }
7579
7580   /* now it happens that (Xenon) server sending this may also provide bogus
7581    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7582    * and just use RTP-Info to sync */
7583   if (src->manager) {
7584     GObjectClass *klass;
7585
7586     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7587     if (g_object_class_find_property (klass, "rtcp-sync")) {
7588       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7589       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7590     }
7591   }
7592 }
7593
7594 static gdouble
7595 gst_rtspsrc_get_float (const gchar * dstr)
7596 {
7597   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7598
7599   /* canonicalise floating point string so we can handle float strings
7600    * in the form "24.930" or "24,930" irrespective of the current locale */
7601   g_strlcpy (s, dstr, sizeof (s));
7602   g_strdelimit (s, ",", '.');
7603   return g_ascii_strtod (s, NULL);
7604 }
7605
7606 static gchar *
7607 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7608 {
7609   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7610
7611   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7612     g_strlcpy (val_str, "now", sizeof (val_str));
7613   } else {
7614     if (segment->position == 0) {
7615       g_strlcpy (val_str, "0", sizeof (val_str));
7616     } else {
7617       g_ascii_dtostr (val_str, sizeof (val_str),
7618           ((gdouble) segment->position) / GST_SECOND);
7619     }
7620   }
7621   return g_strdup_printf ("npt=%s-", val_str);
7622 }
7623
7624 static void
7625 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7626 {
7627   guint i, len;
7628
7629   stream->timebase = -1;
7630   stream->seqbase = -1;
7631
7632   len = stream->ptmap->len;
7633   for (i = 0; i < len; i++) {
7634     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7635     GstStructure *s;
7636
7637     if (item->caps == NULL)
7638       continue;
7639
7640     item->caps = gst_caps_make_writable (item->caps);
7641     s = gst_caps_get_structure (item->caps, 0);
7642     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7643   }
7644 }
7645
7646 static GstRTSPResult
7647 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7648 {
7649   GstRTSPResult res = GST_RTSP_OK;
7650
7651   if (src->state < GST_RTSP_STATE_READY) {
7652     res = GST_RTSP_ERROR;
7653     if (src->open_error) {
7654       GST_DEBUG_OBJECT (src, "the stream was in error");
7655       goto done;
7656     }
7657     if (async)
7658       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7659
7660     if ((res = gst_rtspsrc_open (src, async)) < 0) {
7661       GST_DEBUG_OBJECT (src, "failed to open stream");
7662       goto done;
7663     }
7664   }
7665
7666 done:
7667   return res;
7668 }
7669
7670 static GstRTSPResult
7671 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
7672 {
7673   GstRTSPMessage request = { 0 };
7674   GstRTSPMessage response = { 0 };
7675   GstRTSPResult res = GST_RTSP_OK;
7676   GList *walk;
7677   gchar *hval;
7678   gint hval_idx;
7679   const gchar *control;
7680
7681   GST_DEBUG_OBJECT (src, "PLAY...");
7682
7683   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7684     goto open_failed;
7685
7686   if (!(src->methods & GST_RTSP_PLAY))
7687     goto not_supported;
7688
7689   if (src->state == GST_RTSP_STATE_PLAYING)
7690     goto was_playing;
7691
7692   if (!src->conninfo.connection || !src->conninfo.connected)
7693     goto done;
7694
7695   /* send some dummy packets before we activate the receive in the
7696    * udp sources */
7697   gst_rtspsrc_send_dummy_packets (src);
7698
7699   /* require new SR packets */
7700   if (src->manager)
7701     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7702
7703   /* construct a control url */
7704   control = get_aggregate_control (src);
7705
7706   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7707     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7708     const gchar *setup_url;
7709     GstRTSPConnection *conn;
7710
7711     /* try aggregate control first but do non-aggregate control otherwise */
7712     if (control)
7713       setup_url = control;
7714     else if ((setup_url = stream->conninfo.location) == NULL)
7715       continue;
7716
7717     if (src->conninfo.connection) {
7718       conn = src->conninfo.connection;
7719     } else if (stream->conninfo.connection) {
7720       conn = stream->conninfo.connection;
7721     } else {
7722       continue;
7723     }
7724
7725     /* do play */
7726     res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
7727     if (res < 0)
7728       goto create_request_failed;
7729
7730     if (src->need_range) {
7731       hval = gen_range_header (src, segment);
7732
7733       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7734
7735       /* store the newsegment event so it can be sent from the streaming thread. */
7736       src->need_segment = TRUE;
7737     }
7738
7739     if (segment->rate != 1.0) {
7740       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7741
7742       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7743       if (src->skip)
7744         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7745       else
7746         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7747     }
7748
7749     if (async)
7750       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7751
7752     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7753       goto send_error;
7754
7755     /* seek may have silently failed as it is not supported */
7756     if (!(src->methods & GST_RTSP_PLAY)) {
7757       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7758       /* obviously it is supported as we made it here */
7759       src->methods |= GST_RTSP_PLAY;
7760       src->seekable = FALSE;
7761       /* but there is nothing to parse in the response,
7762        * so convey we have no idea and not to expect anything particular */
7763       clear_rtp_base (src, stream);
7764       if (control) {
7765         GList *run;
7766
7767         /* need to do for all streams */
7768         for (run = src->streams; run; run = g_list_next (run))
7769           clear_rtp_base (src, (GstRTSPStream *) run->data);
7770       }
7771       /* NOTE the above also disables npt based eos detection */
7772       /* and below forces position to 0,
7773        * which is visible feedback we lost the plot */
7774       segment->start = segment->position = src->last_pos;
7775     }
7776
7777     gst_rtsp_message_unset (&request);
7778
7779     /* parse RTP npt field. This is the current position in the stream (Normal
7780      * Play Time) and should be put in the NEWSEGMENT position field. */
7781     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7782             0) == GST_RTSP_OK)
7783       gst_rtspsrc_parse_range (src, hval, segment);
7784
7785     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7786     segment->rate = 1.0;
7787
7788     /* parse Speed header. This is the intended playback rate of the stream
7789      * and should be put in the NEWSEGMENT rate field. */
7790     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7791             0) == GST_RTSP_OK) {
7792       segment->rate = gst_rtspsrc_get_float (hval);
7793     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7794             &hval, 0) == GST_RTSP_OK) {
7795       segment->rate = gst_rtspsrc_get_float (hval);
7796     }
7797
7798     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7799      * for the RTP packets. If this is not present, we assume all starts from 0...
7800      * This is info for the RTP session manager that we pass to it in caps. */
7801     hval_idx = 0;
7802     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7803             &hval, hval_idx++) == GST_RTSP_OK)
7804       gst_rtspsrc_parse_rtpinfo (src, hval);
7805
7806     /* some servers indicate RTCP parameters in PLAY response,
7807      * rather than properly in SDP */
7808     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7809             &hval, 0) == GST_RTSP_OK)
7810       gst_rtspsrc_handle_rtcp_interval (src, hval);
7811
7812     gst_rtsp_message_unset (&response);
7813
7814     /* early exit when we did aggregate control */
7815     if (control)
7816       break;
7817   }
7818   /* configure the caps of the streams after we parsed all headers. Only reset
7819    * the manager object when we set a new Range header (we did a seek) */
7820   gst_rtspsrc_configure_caps (src, segment, src->need_range);
7821
7822   /* set to PLAYING after we have configured the caps, otherwise we
7823    * might end up calling request_key (with SRTP) while caps are still
7824    * being configured. */
7825   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7826
7827   /* set again when needed */
7828   src->need_range = FALSE;
7829
7830   src->running = TRUE;
7831   src->base_time = -1;
7832   src->state = GST_RTSP_STATE_PLAYING;
7833
7834   /* mark discont */
7835   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7836   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7837     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7838     stream->discont = TRUE;
7839   }
7840
7841 done:
7842   if (async)
7843     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7844
7845   return res;
7846
7847   /* ERRORS */
7848 open_failed:
7849   {
7850     GST_DEBUG_OBJECT (src, "failed to open stream");
7851     goto done;
7852   }
7853 not_supported:
7854   {
7855     GST_DEBUG_OBJECT (src, "PLAY is not supported");
7856     goto done;
7857   }
7858 was_playing:
7859   {
7860     GST_DEBUG_OBJECT (src, "we were already PLAYING");
7861     goto done;
7862   }
7863 create_request_failed:
7864   {
7865     gchar *str = gst_rtsp_strresult (res);
7866
7867     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7868         ("Could not create request. (%s)", str));
7869     g_free (str);
7870     goto done;
7871   }
7872 send_error:
7873   {
7874     gchar *str = gst_rtsp_strresult (res);
7875
7876     gst_rtsp_message_unset (&request);
7877     if (res != GST_RTSP_EINTR) {
7878       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7879           ("Could not send message. (%s)", str));
7880     } else {
7881       GST_WARNING_OBJECT (src, "PLAY interrupted");
7882     }
7883     g_free (str);
7884     goto done;
7885   }
7886 }
7887
7888 static GstRTSPResult
7889 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7890 {
7891   GstRTSPResult res = GST_RTSP_OK;
7892   GstRTSPMessage request = { 0 };
7893   GstRTSPMessage response = { 0 };
7894   GList *walk;
7895   const gchar *control;
7896
7897   GST_DEBUG_OBJECT (src, "PAUSE...");
7898
7899   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7900     goto open_failed;
7901
7902   if (!(src->methods & GST_RTSP_PAUSE))
7903     goto not_supported;
7904
7905   if (src->state == GST_RTSP_STATE_READY)
7906     goto was_paused;
7907
7908   if (!src->conninfo.connection || !src->conninfo.connected)
7909     goto no_connection;
7910
7911   /* construct a control url */
7912   control = get_aggregate_control (src);
7913
7914   /* loop over the streams. We might exit the loop early when we could do an
7915    * aggregate control */
7916   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7917     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7918     GstRTSPConnection *conn;
7919     const gchar *setup_url;
7920
7921     /* try aggregate control first but do non-aggregate control otherwise */
7922     if (control)
7923       setup_url = control;
7924     else if ((setup_url = stream->conninfo.location) == NULL)
7925       continue;
7926
7927     if (src->conninfo.connection) {
7928       conn = src->conninfo.connection;
7929     } else if (stream->conninfo.connection) {
7930       conn = stream->conninfo.connection;
7931     } else {
7932       continue;
7933     }
7934
7935     if (async)
7936       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7937           ("Sending PAUSE request"));
7938
7939     if ((res =
7940             gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
7941                 setup_url)) < 0)
7942       goto create_request_failed;
7943
7944     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7945       goto send_error;
7946
7947     gst_rtsp_message_unset (&request);
7948     gst_rtsp_message_unset (&response);
7949
7950     /* exit early when we did agregate control */
7951     if (control)
7952       break;
7953   }
7954
7955   /* change element states now */
7956   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7957
7958 no_connection:
7959   src->state = GST_RTSP_STATE_READY;
7960
7961 done:
7962   if (async)
7963     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7964
7965   return res;
7966
7967   /* ERRORS */
7968 open_failed:
7969   {
7970     GST_DEBUG_OBJECT (src, "failed to open stream");
7971     goto done;
7972   }
7973 not_supported:
7974   {
7975     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7976     goto done;
7977   }
7978 was_paused:
7979   {
7980     GST_DEBUG_OBJECT (src, "we were already PAUSED");
7981     goto done;
7982   }
7983 create_request_failed:
7984   {
7985     gchar *str = gst_rtsp_strresult (res);
7986
7987     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7988         ("Could not create request. (%s)", str));
7989     g_free (str);
7990     goto done;
7991   }
7992 send_error:
7993   {
7994     gchar *str = gst_rtsp_strresult (res);
7995
7996     gst_rtsp_message_unset (&request);
7997     if (res != GST_RTSP_EINTR) {
7998       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7999           ("Could not send message. (%s)", str));
8000     } else {
8001       GST_WARNING_OBJECT (src, "PAUSE interrupted");
8002     }
8003     g_free (str);
8004     goto done;
8005   }
8006 }
8007
8008 static void
8009 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
8010 {
8011   GstRTSPSrc *rtspsrc;
8012
8013   rtspsrc = GST_RTSPSRC (bin);
8014
8015   switch (GST_MESSAGE_TYPE (message)) {
8016     case GST_MESSAGE_EOS:
8017       gst_message_unref (message);
8018       break;
8019     case GST_MESSAGE_ELEMENT:
8020     {
8021       const GstStructure *s = gst_message_get_structure (message);
8022
8023       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
8024         gboolean ignore_timeout;
8025
8026         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
8027
8028         GST_OBJECT_LOCK (rtspsrc);
8029         ignore_timeout = rtspsrc->ignore_timeout;
8030         rtspsrc->ignore_timeout = TRUE;
8031         GST_OBJECT_UNLOCK (rtspsrc);
8032
8033         /* we only act on the first udp timeout message, others are irrelevant
8034          * and can be ignored. */
8035         if (!ignore_timeout)
8036           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
8037         /* eat and free */
8038         gst_message_unref (message);
8039         return;
8040       }
8041       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8042       break;
8043     }
8044     case GST_MESSAGE_ERROR:
8045     {
8046       GstObject *udpsrc;
8047       GstRTSPStream *stream;
8048       GstFlowReturn ret;
8049
8050       udpsrc = GST_MESSAGE_SRC (message);
8051
8052       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
8053           GST_ELEMENT_NAME (udpsrc));
8054
8055       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
8056       if (!stream)
8057         goto forward;
8058
8059       /* we ignore the RTCP udpsrc */
8060       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
8061         goto done;
8062
8063       /* if we get error messages from the udp sources, that's not a problem as
8064        * long as not all of them error out. We also don't really know what the
8065        * problem is, the message does not give enough detail... */
8066       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
8067       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
8068       if (ret != GST_FLOW_OK)
8069         goto forward;
8070
8071     done:
8072       gst_message_unref (message);
8073       break;
8074
8075     forward:
8076       /* fatal but not our message, forward */
8077       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8078       break;
8079     }
8080     default:
8081     {
8082       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8083       break;
8084     }
8085   }
8086 }
8087
8088 /* the thread where everything happens */
8089 static void
8090 gst_rtspsrc_thread (GstRTSPSrc * src)
8091 {
8092   gint cmd;
8093
8094   GST_OBJECT_LOCK (src);
8095   cmd = src->pending_cmd;
8096   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
8097       || cmd == CMD_LOOP || cmd == CMD_OPEN)
8098     src->pending_cmd = CMD_LOOP;
8099   else
8100     src->pending_cmd = CMD_WAIT;
8101   GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
8102
8103   /* we got the message command, so ensure communication is possible again */
8104   gst_rtspsrc_connection_flush (src, FALSE);
8105
8106   src->busy_cmd = cmd;
8107   GST_OBJECT_UNLOCK (src);
8108
8109   switch (cmd) {
8110     case CMD_OPEN:
8111       gst_rtspsrc_open (src, TRUE);
8112       break;
8113     case CMD_PLAY:
8114       gst_rtspsrc_play (src, &src->segment, TRUE);
8115       break;
8116     case CMD_PAUSE:
8117       gst_rtspsrc_pause (src, TRUE);
8118       break;
8119     case CMD_CLOSE:
8120       gst_rtspsrc_close (src, TRUE, FALSE);
8121       break;
8122     case CMD_LOOP:
8123       gst_rtspsrc_loop (src);
8124       break;
8125     case CMD_RECONNECT:
8126       gst_rtspsrc_reconnect (src, FALSE);
8127       break;
8128     default:
8129       break;
8130   }
8131
8132   GST_OBJECT_LOCK (src);
8133   /* and go back to sleep */
8134   if (src->pending_cmd == CMD_WAIT) {
8135     if (src->task)
8136       gst_task_pause (src->task);
8137   }
8138   /* reset waiting */
8139   src->busy_cmd = CMD_WAIT;
8140   GST_OBJECT_UNLOCK (src);
8141 }
8142
8143 static gboolean
8144 gst_rtspsrc_start (GstRTSPSrc * src)
8145 {
8146   GST_DEBUG_OBJECT (src, "starting");
8147
8148   GST_OBJECT_LOCK (src);
8149
8150   src->pending_cmd = CMD_WAIT;
8151
8152   if (src->task == NULL) {
8153     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
8154     if (src->task == NULL)
8155       goto task_error;
8156
8157     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
8158   }
8159   GST_OBJECT_UNLOCK (src);
8160
8161   return TRUE;
8162
8163   /* ERRORS */
8164 task_error:
8165   {
8166     GST_OBJECT_UNLOCK (src);
8167     GST_ERROR_OBJECT (src, "failed to create task");
8168     return FALSE;
8169   }
8170 }
8171
8172 static gboolean
8173 gst_rtspsrc_stop (GstRTSPSrc * src)
8174 {
8175   GstTask *task;
8176
8177   GST_DEBUG_OBJECT (src, "stopping");
8178
8179   /* also cancels pending task */
8180   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
8181
8182   GST_OBJECT_LOCK (src);
8183   if ((task = src->task)) {
8184     src->task = NULL;
8185     GST_OBJECT_UNLOCK (src);
8186
8187     gst_task_stop (task);
8188
8189     /* make sure it is not running */
8190     GST_RTSP_STREAM_LOCK (src);
8191     GST_RTSP_STREAM_UNLOCK (src);
8192
8193     /* now wait for the task to finish */
8194     gst_task_join (task);
8195
8196     /* and free the task */
8197     gst_object_unref (GST_OBJECT (task));
8198
8199     GST_OBJECT_LOCK (src);
8200   }
8201   GST_OBJECT_UNLOCK (src);
8202
8203   /* ensure synchronously all is closed and clean */
8204   gst_rtspsrc_close (src, FALSE, TRUE);
8205
8206   return TRUE;
8207 }
8208
8209 static GstStateChangeReturn
8210 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
8211 {
8212   GstRTSPSrc *rtspsrc;
8213   GstStateChangeReturn ret;
8214
8215   rtspsrc = GST_RTSPSRC (element);
8216
8217   switch (transition) {
8218     case GST_STATE_CHANGE_NULL_TO_READY:
8219       if (!gst_rtspsrc_start (rtspsrc))
8220         goto start_failed;
8221       break;
8222     case GST_STATE_CHANGE_READY_TO_PAUSED:
8223       /* init some state */
8224       rtspsrc->cur_protocols = rtspsrc->protocols;
8225       /* first attempt, don't ignore timeouts */
8226       rtspsrc->ignore_timeout = FALSE;
8227       rtspsrc->open_error = FALSE;
8228       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
8229       break;
8230     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8231       set_manager_buffer_mode (rtspsrc);
8232       /* fall-through */
8233     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8234       /* unblock the tcp tasks and make the loop waiting */
8235       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
8236         /* make sure it is waiting before we send PAUSE or PLAY below */
8237         GST_RTSP_STREAM_LOCK (rtspsrc);
8238         GST_RTSP_STREAM_UNLOCK (rtspsrc);
8239       }
8240       break;
8241     case GST_STATE_CHANGE_PAUSED_TO_READY:
8242       break;
8243     default:
8244       break;
8245   }
8246
8247   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
8248   if (ret == GST_STATE_CHANGE_FAILURE)
8249     goto done;
8250
8251   switch (transition) {
8252     case GST_STATE_CHANGE_NULL_TO_READY:
8253       ret = GST_STATE_CHANGE_SUCCESS;
8254       break;
8255     case GST_STATE_CHANGE_READY_TO_PAUSED:
8256       ret = GST_STATE_CHANGE_NO_PREROLL;
8257       break;
8258     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8259       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
8260       ret = GST_STATE_CHANGE_SUCCESS;
8261       break;
8262     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8263       /* send pause request and keep the idle task around */
8264       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
8265       ret = GST_STATE_CHANGE_NO_PREROLL;
8266       break;
8267     case GST_STATE_CHANGE_PAUSED_TO_READY:
8268       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
8269       ret = GST_STATE_CHANGE_SUCCESS;
8270       break;
8271     case GST_STATE_CHANGE_READY_TO_NULL:
8272       gst_rtspsrc_stop (rtspsrc);
8273       ret = GST_STATE_CHANGE_SUCCESS;
8274       break;
8275     default:
8276       break;
8277   }
8278
8279 done:
8280   return ret;
8281
8282 start_failed:
8283   {
8284     GST_DEBUG_OBJECT (rtspsrc, "start failed");
8285     return GST_STATE_CHANGE_FAILURE;
8286   }
8287 }
8288
8289 static gboolean
8290 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
8291 {
8292   gboolean res;
8293   GstRTSPSrc *rtspsrc;
8294
8295   rtspsrc = GST_RTSPSRC (element);
8296
8297   if (GST_EVENT_IS_DOWNSTREAM (event)) {
8298     res = gst_rtspsrc_push_event (rtspsrc, event);
8299   } else {
8300     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
8301   }
8302
8303   return res;
8304 }
8305
8306
8307 /*** GSTURIHANDLER INTERFACE *************************************************/
8308
8309 static GstURIType
8310 gst_rtspsrc_uri_get_type (GType type)
8311 {
8312   return GST_URI_SRC;
8313 }
8314
8315 static const gchar *const *
8316 gst_rtspsrc_uri_get_protocols (GType type)
8317 {
8318   static const gchar *protocols[] =
8319       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
8320     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
8321   };
8322
8323   return protocols;
8324 }
8325
8326 static gchar *
8327 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
8328 {
8329   GstRTSPSrc *src = GST_RTSPSRC (handler);
8330
8331   /* FIXME: make thread-safe */
8332   return g_strdup (src->conninfo.location);
8333 }
8334
8335 static gboolean
8336 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
8337     GError ** error)
8338 {
8339   GstRTSPSrc *src;
8340   GstRTSPResult res;
8341   GstSDPResult sres;
8342   GstRTSPUrl *newurl = NULL;
8343   GstSDPMessage *sdp = NULL;
8344
8345   src = GST_RTSPSRC (handler);
8346
8347   /* same URI, we're fine */
8348   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
8349     goto was_ok;
8350
8351   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
8352     sres = gst_sdp_message_new (&sdp);
8353     if (sres < 0)
8354       goto sdp_failed;
8355
8356     GST_DEBUG_OBJECT (src, "parsing SDP message");
8357     sres = gst_sdp_message_parse_uri (uri, sdp);
8358     if (sres < 0)
8359       goto invalid_sdp;
8360   } else {
8361     /* try to parse */
8362     GST_DEBUG_OBJECT (src, "parsing URI");
8363     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
8364       goto parse_error;
8365   }
8366
8367   /* if worked, free previous and store new url object along with the original
8368    * location. */
8369   GST_DEBUG_OBJECT (src, "configuring URI");
8370   g_free (src->conninfo.location);
8371   src->conninfo.location = g_strdup (uri);
8372   gst_rtsp_url_free (src->conninfo.url);
8373   src->conninfo.url = newurl;
8374   g_free (src->conninfo.url_str);
8375   if (newurl)
8376     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
8377   else
8378     src->conninfo.url_str = NULL;
8379
8380   if (src->sdp)
8381     gst_sdp_message_free (src->sdp);
8382   src->sdp = sdp;
8383   src->from_sdp = sdp != NULL;
8384
8385   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
8386   GST_DEBUG_OBJECT (src, "request uri is: %s",
8387       GST_STR_NULL (src->conninfo.url_str));
8388
8389   return TRUE;
8390
8391   /* Special cases */
8392 was_ok:
8393   {
8394     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
8395     return TRUE;
8396   }
8397 sdp_failed:
8398   {
8399     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
8400     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8401         "Could not create SDP");
8402     return FALSE;
8403   }
8404 invalid_sdp:
8405   {
8406     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
8407         GST_STR_NULL (uri));
8408     gst_sdp_message_free (sdp);
8409     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8410         "Invalid SDP");
8411     return FALSE;
8412   }
8413 parse_error:
8414   {
8415     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
8416         GST_STR_NULL (uri), res);
8417     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8418         "Invalid RTSP URI");
8419     return FALSE;
8420   }
8421 }
8422
8423 static void
8424 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
8425 {
8426   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
8427
8428   iface->get_type = gst_rtspsrc_uri_get_type;
8429   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
8430   iface->get_uri = gst_rtspsrc_uri_get_uri;
8431   iface->set_uri = gst_rtspsrc_uri_set_uri;
8432 }