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