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