rtspsrc: wrap gst_rtsp_message_init_request in a local function
[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 static GstRTSPResult
4571 gst_rtspsrc_init_request (GstRTSPSrc * src, GstRTSPMessage * msg,
4572     GstRTSPMethod method, const gchar * uri)
4573 {
4574   GstRTSPResult res;
4575
4576   res = gst_rtsp_message_init_request (msg, method, uri);
4577   if (res < 0)
4578     return res;
4579
4580   /* TODO add common initialization here */
4581
4582   return res;
4583 }
4584
4585 /* FIXME, handle server request, reply with OK, for now */
4586 static GstRTSPResult
4587 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
4588     GstRTSPMessage * request)
4589 {
4590   GstRTSPMessage response = { 0 };
4591   GstRTSPResult res;
4592
4593   GST_DEBUG_OBJECT (src, "got server request message");
4594
4595   if (src->debug)
4596     gst_rtsp_message_dump (request);
4597
4598   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4599
4600   if (res == GST_RTSP_ENOTIMPL) {
4601     /* default implementation, send OK */
4602     GST_DEBUG_OBJECT (src, "prepare OK reply");
4603     res =
4604         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4605         request);
4606     if (res < 0)
4607       goto send_error;
4608
4609     /* let app parse and reply */
4610     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4611         0, request, &response);
4612
4613     if (src->debug)
4614       gst_rtsp_message_dump (&response);
4615
4616     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
4617     if (res < 0)
4618       goto send_error;
4619
4620     gst_rtsp_message_unset (&response);
4621   } else if (res == GST_RTSP_EEOF)
4622     return res;
4623
4624   return GST_RTSP_OK;
4625
4626   /* ERRORS */
4627 send_error:
4628   {
4629     gst_rtsp_message_unset (&response);
4630     return res;
4631   }
4632 }
4633
4634 /* send server keep-alive */
4635 static GstRTSPResult
4636 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4637 {
4638   GstRTSPMessage request = { 0 };
4639   GstRTSPResult res;
4640   GstRTSPMethod method;
4641   const gchar *control;
4642
4643   if (src->do_rtsp_keep_alive == FALSE) {
4644     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4645     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4646     return GST_RTSP_OK;
4647   }
4648
4649   GST_DEBUG_OBJECT (src, "creating server keep-alive");
4650
4651   /* find a method to use for keep-alive */
4652   if (src->methods & GST_RTSP_GET_PARAMETER)
4653     method = GST_RTSP_GET_PARAMETER;
4654   else
4655     method = GST_RTSP_OPTIONS;
4656
4657   control = get_aggregate_control (src);
4658   if (control == NULL)
4659     goto no_control;
4660
4661   res = gst_rtspsrc_init_request (src, &request, method, control);
4662   if (res < 0)
4663     goto send_error;
4664
4665   if (src->debug)
4666     gst_rtsp_message_dump (&request);
4667
4668   res =
4669       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
4670       NULL);
4671   if (res < 0)
4672     goto send_error;
4673
4674   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4675   gst_rtsp_message_unset (&request);
4676
4677   return GST_RTSP_OK;
4678
4679   /* ERRORS */
4680 no_control:
4681   {
4682     GST_WARNING_OBJECT (src, "no control url to send keepalive");
4683     return GST_RTSP_OK;
4684   }
4685 send_error:
4686   {
4687     gchar *str = gst_rtsp_strresult (res);
4688
4689     gst_rtsp_message_unset (&request);
4690     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4691         ("Could not send keep-alive. (%s)", str));
4692     g_free (str);
4693     return res;
4694   }
4695 }
4696
4697 static GstFlowReturn
4698 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4699 {
4700   GstFlowReturn ret = GST_FLOW_OK;
4701   gint channel;
4702   GstRTSPStream *stream;
4703   GstPad *outpad = NULL;
4704   guint8 *data;
4705   guint size;
4706   GstBuffer *buf;
4707   gboolean is_rtcp;
4708
4709   channel = message->type_data.data.channel;
4710
4711   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4712   if (!stream)
4713     goto unknown_stream;
4714
4715   if (channel == stream->channel[0]) {
4716     outpad = stream->channelpad[0];
4717     is_rtcp = FALSE;
4718   } else if (channel == stream->channel[1]) {
4719     outpad = stream->channelpad[1];
4720     is_rtcp = TRUE;
4721   } else {
4722     is_rtcp = FALSE;
4723   }
4724
4725   /* take a look at the body to figure out what we have */
4726   gst_rtsp_message_get_body (message, &data, &size);
4727   if (size < 2)
4728     goto invalid_length;
4729
4730   /* channels are not correct on some servers, do extra check */
4731   if (data[1] >= 200 && data[1] <= 204) {
4732     /* hmm RTCP message switch to the RTCP pad of the same stream. */
4733     outpad = stream->channelpad[1];
4734     is_rtcp = TRUE;
4735   }
4736
4737   /* we have no clue what this is, just ignore then. */
4738   if (outpad == NULL)
4739     goto unknown_stream;
4740
4741   /* take the message body for further processing */
4742   gst_rtsp_message_steal_body (message, &data, &size);
4743
4744   /* strip the trailing \0 */
4745   size -= 1;
4746
4747   buf = gst_buffer_new ();
4748   gst_buffer_append_memory (buf,
4749       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4750
4751   /* don't need message anymore */
4752   gst_rtsp_message_unset (message);
4753
4754   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4755       channel);
4756
4757   if (src->need_activate) {
4758     gchar *stream_id;
4759     GstEvent *event;
4760     GChecksum *cs;
4761     gchar *uri;
4762     GList *streams;
4763     guint group_id = gst_util_group_id_next ();
4764
4765     /* generate an SHA256 sum of the URI */
4766     cs = g_checksum_new (G_CHECKSUM_SHA256);
4767     uri = src->conninfo.location;
4768     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4769
4770     for (streams = src->streams; streams; streams = g_list_next (streams)) {
4771       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4772       GstCaps *caps;
4773
4774       stream_id =
4775           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4776       event = gst_event_new_stream_start (stream_id);
4777       gst_event_set_group_id (event, group_id);
4778
4779       g_free (stream_id);
4780       gst_rtspsrc_stream_push_event (src, ostream, event);
4781
4782       if ((caps = stream_get_caps_for_pt (ostream, ostream->default_pt))) {
4783         /* only streams that have a connection to the outside world */
4784         if (ostream->setup) {
4785           if (ostream->udpsrc[0]) {
4786             gst_element_send_event (ostream->udpsrc[0],
4787                 gst_event_new_caps (caps));
4788           } else if (ostream->channelpad[0]) {
4789             if (GST_PAD_IS_SRC (ostream->channelpad[0]))
4790               gst_pad_push_event (ostream->channelpad[0],
4791                   gst_event_new_caps (caps));
4792             else
4793               gst_pad_send_event (ostream->channelpad[0],
4794                   gst_event_new_caps (caps));
4795           }
4796
4797           caps = gst_caps_new_empty_simple ("application/x-rtcp");
4798
4799           if (ostream->udpsrc[1]) {
4800             gst_element_send_event (ostream->udpsrc[1],
4801                 gst_event_new_caps (caps));
4802           } else if (ostream->channelpad[1]) {
4803             if (GST_PAD_IS_SRC (ostream->channelpad[1]))
4804               gst_pad_push_event (ostream->channelpad[1],
4805                   gst_event_new_caps (caps));
4806             else
4807               gst_pad_send_event (ostream->channelpad[1],
4808                   gst_event_new_caps (caps));
4809           }
4810
4811           gst_caps_unref (caps);
4812         }
4813       }
4814     }
4815     g_checksum_free (cs);
4816
4817     gst_rtspsrc_activate_streams (src);
4818     src->need_activate = FALSE;
4819     src->need_segment = TRUE;
4820   }
4821
4822   if (src->base_time == -1) {
4823     /* Take current running_time. This timestamp will be put on
4824      * the first buffer of each stream because we are a live source and so we
4825      * timestamp with the running_time. When we are dealing with TCP, we also
4826      * only timestamp the first buffer (using the DISCONT flag) because a server
4827      * typically bursts data, for which we don't want to compensate by speeding
4828      * up the media. The other timestamps will be interpollated from this one
4829      * using the RTP timestamps. */
4830     GST_OBJECT_LOCK (src);
4831     if (GST_ELEMENT_CLOCK (src)) {
4832       GstClockTime now;
4833       GstClockTime base_time;
4834
4835       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4836       base_time = GST_ELEMENT_CAST (src)->base_time;
4837
4838       src->base_time = now - base_time;
4839
4840       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4841           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4842     }
4843     GST_OBJECT_UNLOCK (src);
4844   }
4845
4846   /* If needed send a new segment, don't forget we are live and buffer are
4847    * timestamped with running time */
4848   if (src->need_segment) {
4849     GstSegment segment;
4850     src->need_segment = FALSE;
4851     gst_segment_init (&segment, GST_FORMAT_TIME);
4852     gst_rtspsrc_push_event (src, gst_event_new_segment (&segment));
4853   }
4854
4855   if (stream->discont && !is_rtcp) {
4856     /* mark first RTP buffer as discont */
4857     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4858     stream->discont = FALSE;
4859     /* first buffer gets the timestamp, other buffers are not timestamped and
4860      * their presentation time will be interpollated from the rtp timestamps. */
4861     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4862         GST_TIME_ARGS (src->base_time));
4863
4864     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4865   }
4866
4867   /* chain to the peer pad */
4868   if (GST_PAD_IS_SINK (outpad))
4869     ret = gst_pad_chain (outpad, buf);
4870   else
4871     ret = gst_pad_push (outpad, buf);
4872
4873   if (!is_rtcp) {
4874     /* combine all stream flows for the data transport */
4875     ret = gst_rtspsrc_combine_flows (src, stream, ret);
4876   }
4877   return ret;
4878
4879   /* ERRORS */
4880 unknown_stream:
4881   {
4882     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4883     gst_rtsp_message_unset (message);
4884     return GST_FLOW_OK;
4885   }
4886 invalid_length:
4887   {
4888     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4889         ("Short message received, ignoring."));
4890     gst_rtsp_message_unset (message);
4891     return GST_FLOW_OK;
4892   }
4893 }
4894
4895 static GstFlowReturn
4896 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4897 {
4898   GstRTSPMessage message = { 0 };
4899   GstRTSPResult res;
4900   GstFlowReturn ret = GST_FLOW_OK;
4901   GTimeVal tv_timeout;
4902
4903   while (TRUE) {
4904     /* get the next timeout interval */
4905     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4906
4907     /* see if the timeout period expired */
4908     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4909       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4910       /* send keep-alive, only act on interrupt, a warning will be posted for
4911        * other errors. */
4912       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4913         goto interrupt;
4914       /* get new timeout */
4915       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4916     }
4917
4918     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4919         tv_timeout.tv_sec, tv_timeout.tv_usec);
4920
4921     /* protect the connection with the connection lock so that we can see when
4922      * we are finished doing server communication */
4923     res =
4924         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4925         &message, src->ptcp_timeout);
4926
4927     switch (res) {
4928       case GST_RTSP_OK:
4929         GST_DEBUG_OBJECT (src, "we received a server message");
4930         break;
4931       case GST_RTSP_EINTR:
4932         /* we got interrupted this means we need to stop */
4933         goto interrupt;
4934       case GST_RTSP_ETIMEOUT:
4935         /* no reply, send keep alive */
4936         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4937         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4938           goto interrupt;
4939         continue;
4940       case GST_RTSP_EEOF:
4941         /* go EOS when the server closed the connection */
4942         goto server_eof;
4943       default:
4944         goto receive_error;
4945     }
4946
4947     switch (message.type) {
4948       case GST_RTSP_MESSAGE_REQUEST:
4949         /* server sends us a request message, handle it */
4950         res =
4951             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4952             &message);
4953         if (res == GST_RTSP_EEOF)
4954           goto server_eof;
4955         else if (res < 0)
4956           goto handle_request_failed;
4957         break;
4958       case GST_RTSP_MESSAGE_RESPONSE:
4959         /* we ignore response messages */
4960         GST_DEBUG_OBJECT (src, "ignoring response message");
4961         if (src->debug)
4962           gst_rtsp_message_dump (&message);
4963         break;
4964       case GST_RTSP_MESSAGE_DATA:
4965         GST_DEBUG_OBJECT (src, "got data message");
4966         ret = gst_rtspsrc_handle_data (src, &message);
4967         if (ret != GST_FLOW_OK)
4968           goto handle_data_failed;
4969         break;
4970       default:
4971         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4972             message.type);
4973         break;
4974     }
4975   }
4976   g_assert_not_reached ();
4977
4978   /* ERRORS */
4979 server_eof:
4980   {
4981     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4982     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4983         ("The server closed the connection."));
4984     src->conninfo.connected = FALSE;
4985     gst_rtsp_message_unset (&message);
4986     return GST_FLOW_EOS;
4987   }
4988 interrupt:
4989   {
4990     gst_rtsp_message_unset (&message);
4991     GST_DEBUG_OBJECT (src, "got interrupted");
4992     return GST_FLOW_FLUSHING;
4993   }
4994 receive_error:
4995   {
4996     gchar *str = gst_rtsp_strresult (res);
4997
4998     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4999         ("Could not receive message. (%s)", str));
5000     g_free (str);
5001
5002     gst_rtsp_message_unset (&message);
5003     return GST_FLOW_ERROR;
5004   }
5005 handle_request_failed:
5006   {
5007     gchar *str = gst_rtsp_strresult (res);
5008
5009     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5010         ("Could not handle server message. (%s)", str));
5011     g_free (str);
5012     gst_rtsp_message_unset (&message);
5013     return GST_FLOW_ERROR;
5014   }
5015 handle_data_failed:
5016   {
5017     GST_DEBUG_OBJECT (src, "could no handle data message");
5018     return ret;
5019   }
5020 }
5021
5022 static GstFlowReturn
5023 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
5024 {
5025   GstRTSPResult res;
5026   GstRTSPMessage message = { 0 };
5027   gint retry = 0;
5028
5029   while (TRUE) {
5030     GTimeVal tv_timeout;
5031
5032     /* get the next timeout interval */
5033     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
5034
5035     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
5036         (gint) tv_timeout.tv_sec);
5037
5038     gst_rtsp_message_unset (&message);
5039
5040     /* we should continue reading the TCP socket because the server might
5041      * send us requests. When the session timeout expires, we need to send a
5042      * keep-alive request to keep the session open. */
5043     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
5044         &message, &tv_timeout);
5045
5046     switch (res) {
5047       case GST_RTSP_OK:
5048         GST_DEBUG_OBJECT (src, "we received a server message");
5049         break;
5050       case GST_RTSP_EINTR:
5051         /* we got interrupted, see what we have to do */
5052         goto interrupt;
5053       case GST_RTSP_ETIMEOUT:
5054         /* send keep-alive, ignore the result, a warning will be posted. */
5055         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
5056         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5057           goto interrupt;
5058         continue;
5059       case GST_RTSP_EEOF:
5060         /* server closed the connection. not very fatal for UDP, reconnect and
5061          * see what happens. */
5062         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5063             ("The server closed the connection."));
5064         if (src->udp_reconnect) {
5065           if ((res =
5066                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
5067             goto connect_error;
5068         } else {
5069           goto server_eof;
5070         }
5071         continue;
5072       case GST_RTSP_ENET:
5073         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
5074       default:
5075         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5076             ("Unhandled return value %d.", res));
5077         goto receive_error;
5078     }
5079
5080     switch (message.type) {
5081       case GST_RTSP_MESSAGE_REQUEST:
5082         /* server sends us a request message, handle it */
5083         res =
5084             gst_rtspsrc_handle_request (src, src->conninfo.connection,
5085             &message);
5086         if (res == GST_RTSP_EEOF)
5087           goto server_eof;
5088         else if (res < 0)
5089           goto handle_request_failed;
5090         break;
5091       case GST_RTSP_MESSAGE_RESPONSE:
5092         /* we ignore response and data messages */
5093         GST_DEBUG_OBJECT (src, "ignoring response message");
5094         if (src->debug)
5095           gst_rtsp_message_dump (&message);
5096         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
5097           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
5098           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
5099             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
5100             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5101               goto interrupt;
5102           }
5103         } else {
5104           retry = 0;
5105         }
5106         break;
5107       case GST_RTSP_MESSAGE_DATA:
5108         /* we ignore response and data messages */
5109         GST_DEBUG_OBJECT (src, "ignoring data message");
5110         break;
5111       default:
5112         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5113             message.type);
5114         break;
5115     }
5116   }
5117   g_assert_not_reached ();
5118
5119   /* we get here when the connection got interrupted */
5120 interrupt:
5121   {
5122     gst_rtsp_message_unset (&message);
5123     GST_DEBUG_OBJECT (src, "got interrupted");
5124     return GST_FLOW_FLUSHING;
5125   }
5126 connect_error:
5127   {
5128     gchar *str = gst_rtsp_strresult (res);
5129     GstFlowReturn ret;
5130
5131     src->conninfo.connected = FALSE;
5132     if (res != GST_RTSP_EINTR) {
5133       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5134           ("Could not connect to server. (%s)", str));
5135       g_free (str);
5136       ret = GST_FLOW_ERROR;
5137     } else {
5138       ret = GST_FLOW_FLUSHING;
5139     }
5140     return ret;
5141   }
5142 receive_error:
5143   {
5144     gchar *str = gst_rtsp_strresult (res);
5145
5146     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5147         ("Could not receive message. (%s)", str));
5148     g_free (str);
5149     return GST_FLOW_ERROR;
5150   }
5151 handle_request_failed:
5152   {
5153     gchar *str = gst_rtsp_strresult (res);
5154     GstFlowReturn ret;
5155
5156     gst_rtsp_message_unset (&message);
5157     if (res != GST_RTSP_EINTR) {
5158       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5159           ("Could not handle server message. (%s)", str));
5160       g_free (str);
5161       ret = GST_FLOW_ERROR;
5162     } else {
5163       ret = GST_FLOW_FLUSHING;
5164     }
5165     return ret;
5166   }
5167 server_eof:
5168   {
5169     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5170     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5171         ("The server closed the connection."));
5172     src->conninfo.connected = FALSE;
5173     gst_rtsp_message_unset (&message);
5174     return GST_FLOW_EOS;
5175   }
5176 }
5177
5178 static GstRTSPResult
5179 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
5180 {
5181   GstRTSPResult res = GST_RTSP_OK;
5182   gboolean restart;
5183
5184   GST_DEBUG_OBJECT (src, "doing reconnect");
5185
5186   GST_OBJECT_LOCK (src);
5187   /* only restart when the pads were not yet activated, else we were
5188    * streaming over UDP */
5189   restart = src->need_activate;
5190   GST_OBJECT_UNLOCK (src);
5191
5192   /* no need to restart, we're done */
5193   if (!restart)
5194     goto done;
5195
5196   /* we can try only TCP now */
5197   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
5198
5199   /* close and cleanup our state */
5200   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
5201     goto done;
5202
5203   /* see if we have TCP left to try. Also don't try TCP when we were configured
5204    * with an SDP. */
5205   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
5206     goto no_protocols;
5207
5208   /* We post a warning message now to inform the user
5209    * that nothing happened. It's most likely a firewall thing. */
5210   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5211       ("Could not receive any UDP packets for %.4f seconds, maybe your "
5212           "firewall is blocking it. Retrying using a TCP connection.",
5213           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
5214
5215   /* open new connection using tcp */
5216   if (gst_rtspsrc_open (src, async) < 0)
5217     goto open_failed;
5218
5219   /* start playback */
5220   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
5221     goto play_failed;
5222
5223 done:
5224   return res;
5225
5226   /* ERRORS */
5227 no_protocols:
5228   {
5229     src->cur_protocols = 0;
5230     /* no transport possible, post an error and stop */
5231     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5232         ("Could not receive any UDP packets for %.4f seconds, maybe your "
5233             "firewall is blocking it. No other protocols to try.",
5234             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
5235     return GST_RTSP_ERROR;
5236   }
5237 open_failed:
5238   {
5239     GST_DEBUG_OBJECT (src, "open failed");
5240     return GST_RTSP_OK;
5241   }
5242 play_failed:
5243   {
5244     GST_DEBUG_OBJECT (src, "play failed");
5245     return GST_RTSP_OK;
5246   }
5247 }
5248
5249 static void
5250 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
5251 {
5252   switch (cmd) {
5253     case CMD_OPEN:
5254       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
5255       break;
5256     case CMD_PLAY:
5257       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
5258       break;
5259     case CMD_PAUSE:
5260       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
5261       break;
5262     case CMD_CLOSE:
5263       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
5264       break;
5265     default:
5266       break;
5267   }
5268 }
5269
5270 static void
5271 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
5272 {
5273   switch (cmd) {
5274     case CMD_OPEN:
5275       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
5276       break;
5277     case CMD_PLAY:
5278       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
5279       break;
5280     case CMD_PAUSE:
5281       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
5282       break;
5283     case CMD_CLOSE:
5284       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
5285       break;
5286     default:
5287       break;
5288   }
5289 }
5290
5291 static void
5292 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
5293 {
5294   switch (cmd) {
5295     case CMD_OPEN:
5296       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
5297       break;
5298     case CMD_PLAY:
5299       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
5300       break;
5301     case CMD_PAUSE:
5302       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
5303       break;
5304     case CMD_CLOSE:
5305       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
5306       break;
5307     default:
5308       break;
5309   }
5310 }
5311
5312 static void
5313 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
5314 {
5315   switch (cmd) {
5316     case CMD_OPEN:
5317       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
5318       break;
5319     case CMD_PLAY:
5320       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
5321       break;
5322     case CMD_PAUSE:
5323       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
5324       break;
5325     case CMD_CLOSE:
5326       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
5327       break;
5328     default:
5329       break;
5330   }
5331 }
5332
5333 static void
5334 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
5335 {
5336   if (ret == GST_RTSP_OK)
5337     gst_rtspsrc_loop_complete_cmd (src, cmd);
5338   else if (ret == GST_RTSP_EINTR)
5339     gst_rtspsrc_loop_cancel_cmd (src, cmd);
5340   else
5341     gst_rtspsrc_loop_error_cmd (src, cmd);
5342 }
5343
5344 static gboolean
5345 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
5346 {
5347   gint old;
5348   gboolean flushed = FALSE;
5349
5350   /* start new request */
5351   gst_rtspsrc_loop_start_cmd (src, cmd);
5352
5353   GST_DEBUG_OBJECT (src, "sending cmd %s", cmd_to_string (cmd));
5354
5355   GST_OBJECT_LOCK (src);
5356   old = src->pending_cmd;
5357   if (old == CMD_RECONNECT) {
5358     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
5359     cmd = CMD_RECONNECT;
5360   }
5361   if (old != CMD_WAIT) {
5362     src->pending_cmd = CMD_WAIT;
5363     GST_OBJECT_UNLOCK (src);
5364     /* cancel previous request */
5365     GST_DEBUG_OBJECT (src, "cancel previous request %s", cmd_to_string (old));
5366     gst_rtspsrc_loop_cancel_cmd (src, old);
5367     GST_OBJECT_LOCK (src);
5368   }
5369   src->pending_cmd = cmd;
5370   /* interrupt if allowed */
5371   if (src->busy_cmd & mask) {
5372     GST_DEBUG_OBJECT (src, "connection flush busy %s",
5373         cmd_to_string (src->busy_cmd));
5374     gst_rtspsrc_connection_flush (src, TRUE);
5375     flushed = TRUE;
5376   } else {
5377     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
5378         cmd_to_string (src->busy_cmd));
5379   }
5380   if (src->task)
5381     gst_task_start (src->task);
5382   GST_OBJECT_UNLOCK (src);
5383
5384   return flushed;
5385 }
5386
5387 static gboolean
5388 gst_rtspsrc_loop (GstRTSPSrc * src)
5389 {
5390   GstFlowReturn ret;
5391
5392   if (!src->conninfo.connection || !src->conninfo.connected)
5393     goto no_connection;
5394
5395   if (src->interleaved)
5396     ret = gst_rtspsrc_loop_interleaved (src);
5397   else
5398     ret = gst_rtspsrc_loop_udp (src);
5399
5400   if (ret != GST_FLOW_OK)
5401     goto pause;
5402
5403   return TRUE;
5404
5405   /* ERRORS */
5406 no_connection:
5407   {
5408     GST_WARNING_OBJECT (src, "we are not connected");
5409     ret = GST_FLOW_FLUSHING;
5410     goto pause;
5411   }
5412 pause:
5413   {
5414     const gchar *reason = gst_flow_get_name (ret);
5415
5416     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
5417     src->running = FALSE;
5418     if (ret == GST_FLOW_EOS) {
5419       /* perform EOS logic */
5420       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5421         gst_element_post_message (GST_ELEMENT_CAST (src),
5422             gst_message_new_segment_done (GST_OBJECT_CAST (src),
5423                 src->segment.format, src->segment.position));
5424         gst_rtspsrc_push_event (src,
5425             gst_event_new_segment_done (src->segment.format,
5426                 src->segment.position));
5427       } else {
5428         gst_rtspsrc_push_event (src, gst_event_new_eos ());
5429       }
5430     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
5431       /* for fatal errors we post an error message, post the error before the
5432        * EOS so the app knows about the error first. */
5433       GST_ELEMENT_ERROR (src, STREAM, FAILED,
5434           ("Internal data flow error."),
5435           ("streaming task paused, reason %s (%d)", reason, ret));
5436       gst_rtspsrc_push_event (src, gst_event_new_eos ());
5437     }
5438     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
5439     return FALSE;
5440   }
5441 }
5442
5443 #ifndef GST_DISABLE_GST_DEBUG
5444 static const gchar *
5445 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5446 {
5447   gint index = 0;
5448
5449   while (method != 0) {
5450     index++;
5451     method >>= 1;
5452   }
5453   switch (index) {
5454     case 0:
5455       return "None";
5456     case 1:
5457       return "Basic";
5458     case 2:
5459       return "Digest";
5460   }
5461
5462   return "Unknown";
5463 }
5464 #endif
5465
5466 static const gchar *
5467 gst_rtspsrc_skip_lws (const gchar * s)
5468 {
5469   while (g_ascii_isspace (*s))
5470     s++;
5471   return s;
5472 }
5473
5474 static const gchar *
5475 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
5476 {
5477   while (s > start && g_ascii_isspace (*(s - 1)))
5478     s--;
5479   return s;
5480 }
5481
5482 static const gchar *
5483 gst_rtspsrc_skip_commas (const gchar * s)
5484 {
5485   /* The grammar allows for multiple commas */
5486   while (g_ascii_isspace (*s) || *s == ',')
5487     s++;
5488   return s;
5489 }
5490
5491 static const gchar *
5492 gst_rtspsrc_skip_item (const gchar * s)
5493 {
5494   gboolean quoted = FALSE;
5495   const gchar *start = s;
5496
5497   /* A list item ends at the last non-whitespace character
5498    * before a comma which is not inside a quoted-string. Or at
5499    * the end of the string.
5500    */
5501   while (*s) {
5502     if (*s == '"')
5503       quoted = !quoted;
5504     else if (quoted) {
5505       if (*s == '\\' && *(s + 1))
5506         s++;
5507     } else {
5508       if (*s == ',')
5509         break;
5510     }
5511     s++;
5512   }
5513
5514   return gst_rtspsrc_unskip_lws (s, start);
5515 }
5516
5517 static void
5518 gst_rtsp_decode_quoted_string (gchar * quoted_string)
5519 {
5520   gchar *src, *dst;
5521
5522   src = quoted_string + 1;
5523   dst = quoted_string;
5524   while (*src && *src != '"') {
5525     if (*src == '\\' && *(src + 1))
5526       src++;
5527     *dst++ = *src++;
5528   }
5529   *dst = '\0';
5530 }
5531
5532 /* Extract the authentication tokens that the server provided for each method
5533  * into an array of structures and give those to the connection object.
5534  */
5535 static void
5536 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
5537     const gchar * header, gboolean * stale)
5538 {
5539   GSList *list = NULL, *iter;
5540   const gchar *end;
5541   gchar *item, *eq, *name_end, *value;
5542
5543   g_return_if_fail (stale != NULL);
5544
5545   gst_rtsp_connection_clear_auth_params (conn);
5546   *stale = FALSE;
5547
5548   /* Parse a header whose content is described by RFC2616 as
5549    * "#something", where "something" does not itself contain commas,
5550    * except as part of quoted-strings, into a list of allocated strings.
5551    */
5552   header = gst_rtspsrc_skip_commas (header);
5553   while (*header) {
5554     end = gst_rtspsrc_skip_item (header);
5555     list = g_slist_prepend (list, g_strndup (header, end - header));
5556     header = gst_rtspsrc_skip_commas (end);
5557   }
5558   if (!list)
5559     return;
5560
5561   list = g_slist_reverse (list);
5562   for (iter = list; iter; iter = iter->next) {
5563     item = iter->data;
5564
5565     eq = strchr (item, '=');
5566     if (eq) {
5567       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
5568       if (name_end == item) {
5569         /* That's no good... */
5570         g_free (item);
5571         continue;
5572       }
5573
5574       *name_end = '\0';
5575
5576       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
5577       if (*value == '"')
5578         gst_rtsp_decode_quoted_string (value);
5579     } else
5580       value = NULL;
5581
5582     if (value && strcmp (item, "stale") == 0 && strcmp (value, "TRUE") == 0)
5583       *stale = TRUE;
5584     gst_rtsp_connection_set_auth_param (conn, item, value);
5585     g_free (item);
5586   }
5587
5588   g_slist_free (list);
5589 }
5590
5591 /* Parse a WWW-Authenticate Response header and determine the
5592  * available authentication methods
5593  *
5594  * This code should also cope with the fact that each WWW-Authenticate
5595  * header can contain multiple challenge methods + tokens
5596  *
5597  * At the moment, for Basic auth, we just do a minimal check and don't
5598  * even parse out the realm */
5599 static void
5600 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
5601     GstRTSPConnection * conn, gboolean * stale)
5602 {
5603   gchar *start;
5604
5605   g_return_if_fail (hdr != NULL);
5606   g_return_if_fail (methods != NULL);
5607   g_return_if_fail (stale != NULL);
5608
5609   /* Skip whitespace at the start of the string */
5610   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
5611
5612   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
5613     *methods |= GST_RTSP_AUTH_BASIC;
5614   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
5615     *methods |= GST_RTSP_AUTH_DIGEST;
5616     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
5617   }
5618 }
5619
5620 /**
5621  * gst_rtspsrc_setup_auth:
5622  * @src: the rtsp source
5623  *
5624  * Configure a username and password and auth method on the
5625  * connection object based on a response we received from the
5626  * peer.
5627  *
5628  * Currently, this requires that a username and password were supplied
5629  * in the uri. In the future, they may be requested on demand by sending
5630  * a message up the bus.
5631  *
5632  * Returns: TRUE if authentication information could be set up correctly.
5633  */
5634 static gboolean
5635 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5636 {
5637   gchar *user = NULL;
5638   gchar *pass = NULL;
5639   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5640   GstRTSPAuthMethod method;
5641   GstRTSPResult auth_result;
5642   GstRTSPUrl *url;
5643   GstRTSPConnection *conn;
5644   gchar *hdr;
5645   gboolean stale = FALSE;
5646
5647   conn = src->conninfo.connection;
5648
5649   /* Identify the available auth methods and see if any are supported */
5650   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
5651           &hdr, 0) == GST_RTSP_OK) {
5652     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
5653   }
5654
5655   if (avail_methods == GST_RTSP_AUTH_NONE)
5656     goto no_auth_available;
5657
5658   /* For digest auth, if the response indicates that the session
5659    * data are stale, we just update them in the connection object and
5660    * return TRUE to retry the request */
5661   if (stale)
5662     src->tried_url_auth = FALSE;
5663
5664   url = gst_rtsp_connection_get_url (conn);
5665
5666   /* Do we have username and password available? */
5667   if (url != NULL && !src->tried_url_auth && url->user != NULL
5668       && url->passwd != NULL) {
5669     user = url->user;
5670     pass = url->passwd;
5671     src->tried_url_auth = TRUE;
5672     GST_DEBUG_OBJECT (src,
5673         "Attempting authentication using credentials from the URL");
5674   } else {
5675     user = src->user_id;
5676     pass = src->user_pw;
5677     GST_DEBUG_OBJECT (src,
5678         "Attempting authentication using credentials from the properties");
5679   }
5680
5681   /* FIXME: If the url didn't contain username and password or we tried them
5682    * already, request a username and passwd from the application via some kind
5683    * of credentials request message */
5684
5685   /* If we don't have a username and passwd at this point, bail out. */
5686   if (user == NULL || pass == NULL)
5687     goto no_user_pass;
5688
5689   /* Try to configure for each available authentication method, strongest to
5690    * weakest */
5691   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5692     /* Check if this method is available on the server */
5693     if ((method & avail_methods) == 0)
5694       continue;
5695
5696     /* Pass the credentials to the connection to try on the next request */
5697     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5698     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5699      * ignore it and end up retrying later */
5700     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5701       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5702           gst_rtsp_auth_method_to_string (method));
5703       break;
5704     }
5705   }
5706
5707   if (method == GST_RTSP_AUTH_NONE)
5708     goto no_auth_available;
5709
5710   return TRUE;
5711
5712 no_auth_available:
5713   {
5714     /* Output an error indicating that we couldn't connect because there were
5715      * no supported authentication protocols */
5716     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5717         ("No supported authentication protocol was found"));
5718     return FALSE;
5719   }
5720 no_user_pass:
5721   {
5722     /* We don't fire an error message, we just return FALSE and let the
5723      * normal NOT_AUTHORIZED error be propagated */
5724     return FALSE;
5725   }
5726 }
5727
5728 static GstRTSPResult
5729 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5730     GstRTSPMessage * request, GstRTSPMessage * response,
5731     GstRTSPStatusCode * code)
5732 {
5733   GstRTSPResult res;
5734   GstRTSPStatusCode thecode;
5735   gchar *content_base = NULL;
5736   gint try = 0;
5737
5738 again:
5739   if (!src->short_header)
5740     gst_rtsp_ext_list_before_send (src->extensions, request);
5741
5742   GST_DEBUG_OBJECT (src, "sending message");
5743
5744   if (src->debug)
5745     gst_rtsp_message_dump (request);
5746
5747   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
5748   if (res < 0)
5749     goto send_error;
5750
5751   gst_rtsp_connection_reset_timeout (conn);
5752
5753 next:
5754   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
5755   if (res < 0)
5756     goto receive_error;
5757
5758   if (src->debug)
5759     gst_rtsp_message_dump (response);
5760
5761   switch (response->type) {
5762     case GST_RTSP_MESSAGE_REQUEST:
5763       res = gst_rtspsrc_handle_request (src, conn, response);
5764       if (res == GST_RTSP_EEOF)
5765         goto server_eof;
5766       else if (res < 0)
5767         goto handle_request_failed;
5768       goto next;
5769     case GST_RTSP_MESSAGE_RESPONSE:
5770       /* ok, a response is good */
5771       GST_DEBUG_OBJECT (src, "received response message");
5772       break;
5773     case GST_RTSP_MESSAGE_DATA:
5774       /* get next response */
5775       GST_DEBUG_OBJECT (src, "handle data response message");
5776       gst_rtspsrc_handle_data (src, response);
5777       goto next;
5778     default:
5779       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5780           response->type);
5781       goto next;
5782   }
5783
5784   thecode = response->type_data.response.code;
5785
5786   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5787
5788   /* if the caller wanted the result code, we store it. */
5789   if (code)
5790     *code = thecode;
5791
5792   /* If the request didn't succeed, bail out before doing any more */
5793   if (thecode != GST_RTSP_STS_OK)
5794     return GST_RTSP_OK;
5795
5796   /* store new content base if any */
5797   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5798       &content_base, 0);
5799   if (content_base) {
5800     g_free (src->content_base);
5801     src->content_base = g_strdup (content_base);
5802   }
5803   gst_rtsp_ext_list_after_send (src->extensions, request, response);
5804
5805   return GST_RTSP_OK;
5806
5807   /* ERRORS */
5808 send_error:
5809   {
5810     gchar *str = gst_rtsp_strresult (res);
5811
5812     if (res != GST_RTSP_EINTR) {
5813       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5814           ("Could not send message. (%s)", str));
5815     } else {
5816       GST_WARNING_OBJECT (src, "send interrupted");
5817     }
5818     g_free (str);
5819     return res;
5820   }
5821 receive_error:
5822   {
5823     switch (res) {
5824       case GST_RTSP_EEOF:
5825         GST_WARNING_OBJECT (src, "server closed connection");
5826         if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5827           try++;
5828           /* if reconnect succeeds, try again */
5829           if ((res =
5830                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5831                       FALSE)) == 0)
5832             goto again;
5833         }
5834         /* only try once after reconnect, then fallthrough and error out */
5835       default:
5836       {
5837         gchar *str = gst_rtsp_strresult (res);
5838
5839         if (res != GST_RTSP_EINTR) {
5840           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5841               ("Could not receive message. (%s)", str));
5842         } else {
5843           GST_WARNING_OBJECT (src, "receive interrupted");
5844         }
5845         g_free (str);
5846         break;
5847       }
5848     }
5849     return res;
5850   }
5851 handle_request_failed:
5852   {
5853     /* ERROR was posted */
5854     gst_rtsp_message_unset (response);
5855     return res;
5856   }
5857 server_eof:
5858   {
5859     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5860     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5861         ("The server closed the connection."));
5862     gst_rtsp_message_unset (response);
5863     return res;
5864   }
5865 }
5866
5867 /**
5868  * gst_rtspsrc_send:
5869  * @src: the rtsp source
5870  * @conn: the connection to send on
5871  * @request: must point to a valid request
5872  * @response: must point to an empty #GstRTSPMessage
5873  * @code: an optional code result
5874  *
5875  * send @request and retrieve the response in @response. optionally @code can be
5876  * non-NULL in which case it will contain the status code of the response.
5877  *
5878  * If This function returns #GST_RTSP_OK, @response will contain a valid response
5879  * message that should be cleaned with gst_rtsp_message_unset() after usage.
5880  *
5881  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5882  * @response message) if the response code was not 200 (OK).
5883  *
5884  * If the attempt results in an authentication failure, then this will attempt
5885  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5886  * the request.
5887  *
5888  * Returns: #GST_RTSP_OK if the processing was successful.
5889  */
5890 static GstRTSPResult
5891 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5892     GstRTSPMessage * request, GstRTSPMessage * response,
5893     GstRTSPStatusCode * code)
5894 {
5895   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5896   GstRTSPResult res = GST_RTSP_ERROR;
5897   gint count;
5898   gboolean retry;
5899   GstRTSPMethod method = GST_RTSP_INVALID;
5900
5901   count = 0;
5902   do {
5903     retry = FALSE;
5904
5905     /* make sure we don't loop forever */
5906     if (count++ > 8)
5907       break;
5908
5909     /* save method so we can disable it when the server complains */
5910     method = request->type_data.request.method;
5911
5912     if ((res =
5913             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5914       goto error;
5915
5916     switch (int_code) {
5917       case GST_RTSP_STS_UNAUTHORIZED:
5918         if (gst_rtspsrc_setup_auth (src, response)) {
5919           /* Try the request/response again after configuring the auth info
5920            * and loop again */
5921           retry = TRUE;
5922         }
5923         break;
5924       default:
5925         break;
5926     }
5927   } while (retry == TRUE);
5928
5929   /* If the user requested the code, let them handle errors, otherwise
5930    * post an error below */
5931   if (code != NULL)
5932     *code = int_code;
5933   else if (int_code != GST_RTSP_STS_OK)
5934     goto error_response;
5935
5936   return res;
5937
5938   /* ERRORS */
5939 error:
5940   {
5941     GST_DEBUG_OBJECT (src, "got error %d", res);
5942     return res;
5943   }
5944 error_response:
5945   {
5946     res = GST_RTSP_ERROR;
5947
5948     switch (response->type_data.response.code) {
5949       case GST_RTSP_STS_NOT_FOUND:
5950         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5951                 response->type_data.response.reason));
5952         break;
5953       case GST_RTSP_STS_UNAUTHORIZED:
5954         GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED, (NULL), ("%s",
5955                 response->type_data.response.reason));
5956         break;
5957       case GST_RTSP_STS_MOVED_PERMANENTLY:
5958       case GST_RTSP_STS_MOVE_TEMPORARILY:
5959       {
5960         gchar *new_location;
5961         GstRTSPLowerTrans transports;
5962
5963         GST_DEBUG_OBJECT (src, "got redirection");
5964         /* if we don't have a Location Header, we must error */
5965         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5966                 &new_location, 0) < 0)
5967           break;
5968
5969         /* When we receive a redirect result, we go back to the INIT state after
5970          * parsing the new URI. The caller should do the needed steps to issue
5971          * a new setup when it detects this state change. */
5972         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5973
5974         /* save current transports */
5975         if (src->conninfo.url)
5976           transports = src->conninfo.url->transports;
5977         else
5978           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5979
5980         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5981
5982         /* set old transports */
5983         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5984           src->conninfo.url->transports = transports;
5985
5986         src->need_redirect = TRUE;
5987         src->state = GST_RTSP_STATE_INIT;
5988         res = GST_RTSP_OK;
5989         break;
5990       }
5991       case GST_RTSP_STS_NOT_ACCEPTABLE:
5992       case GST_RTSP_STS_NOT_IMPLEMENTED:
5993       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5994         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5995             gst_rtsp_method_as_text (method));
5996         src->methods &= ~method;
5997         res = GST_RTSP_OK;
5998         break;
5999       default:
6000         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6001             ("Got error response: %d (%s).", response->type_data.response.code,
6002                 response->type_data.response.reason));
6003         break;
6004     }
6005     /* if we return ERROR we should unset the response ourselves */
6006     if (res == GST_RTSP_ERROR)
6007       gst_rtsp_message_unset (response);
6008
6009     return res;
6010   }
6011 }
6012
6013 static GstRTSPResult
6014 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
6015     GstRTSPMessage * response, GstRTSPSrc * src)
6016 {
6017   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
6018       NULL);
6019 }
6020
6021
6022 /* parse the response and collect all the supported methods. We need this
6023  * information so that we don't try to send an unsupported request to the
6024  * server.
6025  */
6026 static gboolean
6027 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
6028 {
6029   GstRTSPHeaderField field;
6030   gchar *respoptions;
6031   gint indx = 0;
6032
6033   /* reset supported methods */
6034   src->methods = 0;
6035
6036   /* Try Allow Header first */
6037   field = GST_RTSP_HDR_ALLOW;
6038   while (TRUE) {
6039     respoptions = NULL;
6040     gst_rtsp_message_get_header (response, field, &respoptions, indx);
6041     if (indx == 0 && !respoptions) {
6042       /* if no Allow header was found then try the Public header... */
6043       field = GST_RTSP_HDR_PUBLIC;
6044       gst_rtsp_message_get_header (response, field, &respoptions, indx);
6045     }
6046     if (!respoptions)
6047       break;
6048
6049     src->methods |= gst_rtsp_options_from_text (respoptions);
6050
6051     indx++;
6052   }
6053
6054   if (src->methods == 0) {
6055     /* neither Allow nor Public are required, assume the server supports
6056      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
6057      * well. */
6058     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
6059     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
6060   }
6061   /* always assume PLAY, FIXME, extensions should be able to override
6062    * this */
6063   src->methods |= GST_RTSP_PLAY;
6064   /* also assume it will support Range */
6065   src->seekable = TRUE;
6066
6067   /* we need describe and setup */
6068   if (!(src->methods & GST_RTSP_DESCRIBE))
6069     goto no_describe;
6070   if (!(src->methods & GST_RTSP_SETUP))
6071     goto no_setup;
6072
6073   return TRUE;
6074
6075   /* ERRORS */
6076 no_describe:
6077   {
6078     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
6079         ("Server does not support DESCRIBE."));
6080     return FALSE;
6081   }
6082 no_setup:
6083   {
6084     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
6085         ("Server does not support SETUP."));
6086     return FALSE;
6087   }
6088 }
6089
6090 /* masks to be kept in sync with the hardcoded protocol order of preference
6091  * in code below */
6092 static const guint protocol_masks[] = {
6093   GST_RTSP_LOWER_TRANS_UDP,
6094   GST_RTSP_LOWER_TRANS_UDP_MCAST,
6095   GST_RTSP_LOWER_TRANS_TCP,
6096   0
6097 };
6098
6099 static GstRTSPResult
6100 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
6101     GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
6102 {
6103   GstRTSPResult res;
6104   GString *result;
6105   gboolean add_udp_str;
6106
6107   *transports = NULL;
6108
6109   res =
6110       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
6111
6112   if (res < 0)
6113     goto failed;
6114
6115   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
6116
6117   /* extension listed transports, use those */
6118   if (*transports != NULL)
6119     return GST_RTSP_OK;
6120
6121   /* it's the default */
6122   add_udp_str = FALSE;
6123
6124   /* the default RTSP transports */
6125   result = g_string_new ("RTP");
6126
6127   switch (profile) {
6128     case GST_RTSP_PROFILE_AVP:
6129       g_string_append (result, "/AVP");
6130       break;
6131     case GST_RTSP_PROFILE_SAVP:
6132       g_string_append (result, "/SAVP");
6133       break;
6134     case GST_RTSP_PROFILE_AVPF:
6135       g_string_append (result, "/AVPF");
6136       break;
6137     case GST_RTSP_PROFILE_SAVPF:
6138       g_string_append (result, "/SAVPF");
6139       break;
6140     default:
6141       break;
6142   }
6143
6144   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
6145     GST_DEBUG_OBJECT (src, "adding UDP unicast");
6146     if (add_udp_str)
6147       g_string_append (result, "/UDP");
6148     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
6149   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
6150     GST_DEBUG_OBJECT (src, "adding UDP multicast");
6151     /* we don't have to allocate any UDP ports yet, if the selected transport
6152      * turns out to be multicast we can create them and join the multicast
6153      * group indicated in the transport reply */
6154     if (add_udp_str)
6155       g_string_append (result, "/UDP");
6156     g_string_append (result, ";multicast");
6157     if (src->next_port_num != 0) {
6158       if (src->client_port_range.max > 0 &&
6159           src->next_port_num >= src->client_port_range.max)
6160         goto no_ports;
6161
6162       g_string_append_printf (result, ";client_port=%d-%d",
6163           src->next_port_num, src->next_port_num + 1);
6164     }
6165   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
6166     GST_DEBUG_OBJECT (src, "adding TCP");
6167
6168     g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
6169   }
6170   *transports = g_string_free (result, FALSE);
6171
6172   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
6173
6174   return GST_RTSP_OK;
6175
6176   /* ERRORS */
6177 failed:
6178   {
6179     GST_ERROR ("extension gave error %d", res);
6180     return res;
6181   }
6182 no_ports:
6183   {
6184     GST_ERROR ("no more ports available");
6185     return GST_RTSP_ERROR;
6186   }
6187 }
6188
6189 static GstRTSPResult
6190 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
6191     gint orig_rtpport, gint orig_rtcpport)
6192 {
6193   GstRTSPSrc *src;
6194   gint nr_udp, nr_int;
6195   gchar *next, *p;
6196   gint rtpport = 0, rtcpport = 0;
6197   GString *str;
6198
6199   src = stream->parent;
6200
6201   /* find number of placeholders first */
6202   if (strstr (*transports, "%%i2"))
6203     nr_int = 2;
6204   else if (strstr (*transports, "%%i1"))
6205     nr_int = 1;
6206   else
6207     nr_int = 0;
6208
6209   if (strstr (*transports, "%%u2"))
6210     nr_udp = 2;
6211   else if (strstr (*transports, "%%u1"))
6212     nr_udp = 1;
6213   else
6214     nr_udp = 0;
6215
6216   if (nr_udp == 0 && nr_int == 0)
6217     goto done;
6218
6219   if (nr_udp > 0) {
6220     if (!orig_rtpport || !orig_rtcpport) {
6221       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
6222         goto failed;
6223     } else {
6224       rtpport = orig_rtpport;
6225       rtcpport = orig_rtcpport;
6226     }
6227   }
6228
6229   str = g_string_new ("");
6230   p = *transports;
6231   while ((next = strstr (p, "%%"))) {
6232     g_string_append_len (str, p, next - p);
6233     if (next[2] == 'u') {
6234       if (next[3] == '1')
6235         g_string_append_printf (str, "%d", rtpport);
6236       else if (next[3] == '2')
6237         g_string_append_printf (str, "%d", rtcpport);
6238     }
6239     if (next[2] == 'i') {
6240       if (next[3] == '1')
6241         g_string_append_printf (str, "%d", src->free_channel);
6242       else if (next[3] == '2')
6243         g_string_append_printf (str, "%d", src->free_channel + 1);
6244     }
6245
6246     p = next + 4;
6247   }
6248   /* append final part */
6249   g_string_append (str, p);
6250
6251   g_free (*transports);
6252   *transports = g_string_free (str, FALSE);
6253
6254 done:
6255   return GST_RTSP_OK;
6256
6257   /* ERRORS */
6258 failed:
6259   {
6260     GST_ERROR ("failed to allocate udp ports");
6261     return GST_RTSP_ERROR;
6262   }
6263 }
6264
6265 static guint8
6266 enc_key_length_from_cipher_name (const gchar * cipher)
6267 {
6268   if (g_strcmp0 (cipher, "aes-128-icm") == 0)
6269     return AES_128_KEY_LEN;
6270   else if (g_strcmp0 (cipher, "aes-256-icm") == 0)
6271     return AES_256_KEY_LEN;
6272   else {
6273     GST_ERROR ("encryption algorithm '%s' not supported", cipher);
6274     return 0;
6275   }
6276 }
6277
6278 static guint8
6279 auth_key_length_from_auth_name (const gchar * auth)
6280 {
6281   if (g_strcmp0 (auth, "hmac-sha1-32") == 0)
6282     return HMAC_32_KEY_LEN;
6283   else if (g_strcmp0 (auth, "hmac-sha1-80") == 0)
6284     return HMAC_80_KEY_LEN;
6285   else {
6286     GST_ERROR ("authentication algorithm '%s' not supported", auth);
6287     return 0;
6288   }
6289 }
6290
6291 static GstCaps *
6292 signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
6293 {
6294   GstCaps *caps = NULL;
6295
6296   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
6297       stream->id, &caps);
6298
6299   if (caps != NULL)
6300     GST_DEBUG_OBJECT (src, "SRTP parameters received");
6301
6302   return caps;
6303 }
6304
6305 static GstCaps *
6306 default_srtcp_params (void)
6307 {
6308   guint i;
6309   GstCaps *caps;
6310   GstBuffer *buf;
6311   guint8 *key_data;
6312 #define KEY_SIZE 30
6313
6314   /* create a random key */
6315   key_data = g_malloc (KEY_SIZE);
6316   for (i = 0; i < KEY_SIZE; i += 4)
6317     GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
6318
6319   buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
6320
6321   caps = gst_caps_new_simple ("application/x-srtp",
6322       "srtp-key", GST_TYPE_BUFFER, buf,
6323       "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
6324       "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
6325
6326   gst_buffer_unref (buf);
6327
6328   return caps;
6329 }
6330
6331 static gchar *
6332 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
6333 {
6334   GBytes *bytes;
6335   gchar *result, *base64;
6336   const guint8 *data;
6337   gsize size;
6338   GstMIKEYMessage *msg;
6339   GstMIKEYPayload *payload, *pkd;
6340   guint8 byte;
6341   GstStructure *s;
6342   GstMapInfo info;
6343   GstBuffer *srtpkey;
6344   const GValue *val;
6345   const gchar *srtcpcipher, *srtcpauth;
6346
6347   stream->srtcpparams = signal_get_srtcp_params (src, stream);
6348   if (stream->srtcpparams == NULL)
6349     stream->srtcpparams = default_srtcp_params ();
6350
6351   s = gst_caps_get_structure (stream->srtcpparams, 0);
6352
6353   srtcpcipher = gst_structure_get_string (s, "srtcp-cipher");
6354   srtcpauth = gst_structure_get_string (s, "srtcp-auth");
6355   val = gst_structure_get_value (s, "srtp-key");
6356
6357   if (srtcpcipher == NULL || srtcpauth == NULL || val == NULL) {
6358     GST_ERROR_OBJECT (src, "could not find the right SRTP parameters in caps");
6359     return NULL;
6360   }
6361
6362   srtpkey = gst_value_get_buffer (val);
6363
6364   msg = gst_mikey_message_new ();
6365   /* unencrypted MIKEY message, we send this over TLS so this is allowed */
6366   gst_mikey_message_set_info (msg, GST_MIKEY_VERSION, GST_MIKEY_TYPE_PSK_INIT,
6367       FALSE, GST_MIKEY_PRF_MIKEY_1, g_random_int (), GST_MIKEY_MAP_TYPE_SRTP);
6368   /* add policy '0' for our SSRC */
6369   gst_mikey_message_add_cs_srtp (msg, 0, stream->send_ssrc, 0);
6370   /* timestamp is now */
6371   gst_mikey_message_add_t_now_ntp_utc (msg);
6372   /* add some random data */
6373   gst_mikey_message_add_rand_len (msg, 16);
6374
6375   /* the policy '0' is SRTP */
6376   payload = gst_mikey_payload_new (GST_MIKEY_PT_SP);
6377   gst_mikey_payload_sp_set (payload, 0, GST_MIKEY_SEC_PROTO_SRTP);
6378
6379   /* only AES-CM is supported */
6380   byte = 1;
6381   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_ALG, 1, &byte);
6382   /* encryption key length */
6383   byte = enc_key_length_from_cipher_name (srtcpcipher);
6384   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_ENC_KEY_LEN, 1,
6385       &byte);
6386   /* only HMAC-SHA1 */
6387   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_ALG, 1,
6388       &byte);
6389   /* authentication key length */
6390   byte = auth_key_length_from_auth_name (srtcpauth);
6391   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_AUTH_KEY_LEN, 1,
6392       &byte);
6393   /* we enable encryption on RTP and RTCP */
6394   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_ENC, 1,
6395       &byte);
6396   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTCP_ENC, 1,
6397       &byte);
6398   /* we enable authentication on RTP and RTCP */
6399   gst_mikey_payload_sp_add_param (payload, GST_MIKEY_SP_SRTP_SRTP_AUTH, 1,
6400       &byte);
6401   gst_mikey_message_add_payload (msg, payload);
6402
6403   /* make unencrypted KEMAC */
6404   payload = gst_mikey_payload_new (GST_MIKEY_PT_KEMAC);
6405   gst_mikey_payload_kemac_set (payload, GST_MIKEY_ENC_NULL, GST_MIKEY_MAC_NULL);
6406   /* add the key in KEMAC */
6407   pkd = gst_mikey_payload_new (GST_MIKEY_PT_KEY_DATA);
6408   gst_buffer_map (srtpkey, &info, GST_MAP_READ);
6409   gst_mikey_payload_key_data_set_key (pkd, GST_MIKEY_KD_TEK, info.size,
6410       info.data);
6411   gst_buffer_unmap (srtpkey, &info);
6412   gst_mikey_payload_kemac_add_sub (payload, pkd);
6413   gst_mikey_message_add_payload (msg, payload);
6414
6415   /* now serialize this to bytes */
6416   bytes = gst_mikey_message_to_bytes (msg, NULL, NULL);
6417   gst_mikey_message_unref (msg);
6418   /* and make it into base64 */
6419   data = g_bytes_get_data (bytes, &size);
6420   base64 = g_base64_encode (data, size);
6421   g_bytes_unref (bytes);
6422
6423   result = g_strdup_printf ("prot=mikey;uri=\"%s\";data=\"%s\"",
6424       stream->conninfo.location, base64);
6425   g_free (base64);
6426
6427   return result;
6428 }
6429
6430
6431 /* Perform the SETUP request for all the streams.
6432  *
6433  * We ask the server for a specific transport, which initially includes all the
6434  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6435  * two local UDP ports that we send to the server.
6436  *
6437  * Once the server replied with a transport, we configure the other streams
6438  * with the same transport.
6439  *
6440  * This function will also configure the stream for the selected transport,
6441  * which basically means creating the pipeline.
6442  */
6443 static GstRTSPResult
6444 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
6445 {
6446   GList *walk;
6447   GstRTSPResult res = GST_RTSP_ERROR;
6448   GstRTSPMessage request = { 0 };
6449   GstRTSPMessage response = { 0 };
6450   GstRTSPStream *stream = NULL;
6451   GstRTSPLowerTrans protocols;
6452   GstRTSPStatusCode code;
6453   gboolean unsupported_real = FALSE;
6454   gint rtpport, rtcpport;
6455   GstRTSPUrl *url;
6456   gchar *hval;
6457
6458   if (src->conninfo.connection) {
6459     url = gst_rtsp_connection_get_url (src->conninfo.connection);
6460     /* we initially allow all configured lower transports. based on the URL
6461      * transports and the replies from the server we narrow them down. */
6462     protocols = url->transports & src->cur_protocols;
6463   } else {
6464     url = NULL;
6465     protocols = src->cur_protocols;
6466   }
6467
6468   if (protocols == 0)
6469     goto no_protocols;
6470
6471   /* reset some state */
6472   src->free_channel = 0;
6473   src->interleaved = FALSE;
6474   src->need_activate = FALSE;
6475   /* keep track of next port number, 0 is random */
6476   src->next_port_num = src->client_port_range.min;
6477   rtpport = rtcpport = 0;
6478
6479   if (G_UNLIKELY (src->streams == NULL))
6480     goto no_streams;
6481
6482   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6483     GstRTSPConnection *conn;
6484     gchar *transports;
6485     gint retry = 0;
6486     guint mask = 0;
6487     gboolean selected;
6488     GstCaps *caps;
6489
6490     stream = (GstRTSPStream *) walk->data;
6491
6492     caps = stream_get_caps_for_pt (stream, stream->default_pt);
6493     if (caps == NULL) {
6494       GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
6495       continue;
6496     }
6497
6498     if (stream->skipped) {
6499       GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6500       continue;
6501     }
6502
6503     /* see if we need to configure this stream */
6504     if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6505       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6506           stream);
6507       continue;
6508     }
6509
6510     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6511         stream->id, caps, &selected);
6512     if (!selected) {
6513       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6514       continue;
6515     }
6516
6517     /* merge/overwrite global caps */
6518     if (caps) {
6519       guint j, num;
6520       GstStructure *s;
6521
6522       s = gst_caps_get_structure (caps, 0);
6523
6524       num = gst_structure_n_fields (src->props);
6525       for (j = 0; j < num; j++) {
6526         const gchar *name;
6527         const GValue *val;
6528
6529         name = gst_structure_nth_field_name (src->props, j);
6530         val = gst_structure_get_value (src->props, name);
6531         gst_structure_set_value (s, name, val);
6532
6533         GST_DEBUG_OBJECT (src, "copied %s", name);
6534       }
6535     }
6536
6537     /* skip setup if we have no URL for it */
6538     if (stream->conninfo.location == NULL) {
6539       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6540       continue;
6541     }
6542
6543     if (src->conninfo.connection == NULL) {
6544       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6545         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6546         continue;
6547       }
6548       conn = stream->conninfo.connection;
6549     } else {
6550       conn = src->conninfo.connection;
6551     }
6552     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6553         stream->conninfo.location);
6554
6555     /* if we have a multicast connection, only suggest multicast from now on */
6556     if (stream->is_multicast)
6557       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6558
6559   next_protocol:
6560     /* first selectable protocol */
6561     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6562       mask++;
6563     if (!protocol_masks[mask])
6564       goto no_protocols;
6565
6566   retry:
6567     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6568         protocol_masks[mask]);
6569     /* create a string with first transport in line */
6570     transports = NULL;
6571     res = gst_rtspsrc_create_transports_string (src,
6572         protocols & protocol_masks[mask], stream->profile, &transports);
6573     if (res < 0 || transports == NULL)
6574       goto setup_transport_failed;
6575
6576     if (strlen (transports) == 0) {
6577       g_free (transports);
6578       GST_DEBUG_OBJECT (src, "no transports found");
6579       mask++;
6580       goto next_protocol;
6581     }
6582
6583     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6584
6585     /* replace placeholders with real values, this function will optionally
6586      * allocate UDP ports and other info needed to execute the setup request */
6587     res = gst_rtspsrc_prepare_transports (stream, &transports,
6588         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6589     if (res < 0) {
6590       g_free (transports);
6591       goto setup_transport_failed;
6592     }
6593
6594     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6595
6596     /* create SETUP request */
6597     res =
6598         gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
6599         stream->conninfo.location);
6600     if (res < 0) {
6601       g_free (transports);
6602       goto create_request_failed;
6603     }
6604
6605     /* select transport */
6606     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6607
6608     /* set up keys */
6609     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6610         stream->profile == GST_RTSP_PROFILE_SAVPF) {
6611       hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6612       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6613     }
6614
6615     /* if the user wants a non default RTP packet size we add the blocksize
6616      * parameter */
6617     if (src->rtp_blocksize > 0) {
6618       hval = g_strdup_printf ("%d", src->rtp_blocksize);
6619       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6620     }
6621
6622     if (async)
6623       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6624               stream->id));
6625
6626     /* handle the code ourselves */
6627     res = gst_rtspsrc_send (src, conn, &request, &response, &code);
6628     if (res < 0)
6629       goto send_error;
6630
6631     switch (code) {
6632       case GST_RTSP_STS_OK:
6633         break;
6634       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6635         gst_rtsp_message_unset (&request);
6636         gst_rtsp_message_unset (&response);
6637         /* cleanup of leftover transport */
6638         gst_rtspsrc_stream_free_udp (stream);
6639         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6640          * we might be in this case */
6641         if (stream->container && rtpport && rtcpport && !retry) {
6642           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6643               rtpport, rtcpport);
6644           retry++;
6645           goto retry;
6646         }
6647         /* this transport did not go down well, but we may have others to try
6648          * that we did not send yet, try those and only give up then
6649          * but not without checking for lost cause/extension so we can
6650          * post a nicer/more useful error message later */
6651         if (!unsupported_real)
6652           unsupported_real = stream->is_real;
6653         /* select next available protocol, give up on this stream if none */
6654         mask++;
6655         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6656           mask++;
6657         if (!protocol_masks[mask] || unsupported_real)
6658           continue;
6659         else
6660           goto retry;
6661       default:
6662         /* cleanup of leftover transport and move to the next stream */
6663         gst_rtspsrc_stream_free_udp (stream);
6664         goto response_error;
6665     }
6666
6667     /* parse response transport */
6668     {
6669       gchar *resptrans = NULL;
6670       GstRTSPTransport transport = { 0 };
6671
6672       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
6673           &resptrans, 0);
6674       if (!resptrans) {
6675         gst_rtspsrc_stream_free_udp (stream);
6676         goto no_transport;
6677       }
6678
6679       /* parse transport, go to next stream on parse error */
6680       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6681         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6682         goto next;
6683       }
6684
6685       /* update allowed transports for other streams. once the transport of
6686        * one stream has been determined, we make sure that all other streams
6687        * are configured in the same way */
6688       switch (transport.lower_transport) {
6689         case GST_RTSP_LOWER_TRANS_TCP:
6690           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6691           protocols = GST_RTSP_LOWER_TRANS_TCP;
6692           src->interleaved = TRUE;
6693           /* update free channels */
6694           src->free_channel =
6695               MAX (transport.interleaved.min, src->free_channel);
6696           src->free_channel =
6697               MAX (transport.interleaved.max, src->free_channel);
6698           src->free_channel++;
6699           break;
6700         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6701           /* only allow multicast for other streams */
6702           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6703           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6704           /* if the server selected our ports, increment our counters so that
6705            * we select a new port later */
6706           if (src->next_port_num == transport.port.min &&
6707               src->next_port_num + 1 == transport.port.max) {
6708             src->next_port_num += 2;
6709           }
6710           break;
6711         case GST_RTSP_LOWER_TRANS_UDP:
6712           /* only allow unicast for other streams */
6713           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6714           protocols = GST_RTSP_LOWER_TRANS_UDP;
6715           break;
6716         default:
6717           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6718               transport.lower_transport);
6719           break;
6720       }
6721
6722       if (!src->interleaved || !retry) {
6723         /* now configure the stream with the selected transport */
6724         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6725           GST_DEBUG_OBJECT (src,
6726               "could not configure stream %p transport, skipping stream",
6727               stream);
6728           goto next;
6729         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
6730           /* retain the first allocated UDP port pair */
6731           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
6732           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
6733         }
6734       }
6735       /* we need to activate at least one streams when we detect activity */
6736       src->need_activate = TRUE;
6737
6738       /* stream is setup now */
6739       stream->setup = TRUE;
6740       {
6741         GList *skip = walk;
6742
6743         while (TRUE) {
6744           GstRTSPStream *sskip;
6745
6746           skip = g_list_next (skip);
6747           if (skip == NULL)
6748             break;
6749
6750           sskip = (GstRTSPStream *) skip->data;
6751
6752           /* skip all streams with the same control url */
6753           if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6754             GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6755                 sskip, sskip->conninfo.location);
6756             sskip->skipped = TRUE;
6757           }
6758         }
6759       }
6760     next:
6761       /* clean up our transport struct */
6762       gst_rtsp_transport_init (&transport);
6763       /* clean up used RTSP messages */
6764       gst_rtsp_message_unset (&request);
6765       gst_rtsp_message_unset (&response);
6766     }
6767   }
6768
6769   /* store the transport protocol that was configured */
6770   src->cur_protocols = protocols;
6771
6772   gst_rtsp_ext_list_stream_select (src->extensions, url);
6773
6774   /* if there is nothing to activate, error out */
6775   if (!src->need_activate)
6776     goto nothing_to_activate;
6777
6778   return res;
6779
6780   /* ERRORS */
6781 no_protocols:
6782   {
6783     /* no transport possible, post an error and stop */
6784     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6785         ("Could not connect to server, no protocols left"));
6786     return GST_RTSP_ERROR;
6787   }
6788 no_streams:
6789   {
6790     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6791         ("SDP contains no streams"));
6792     return GST_RTSP_ERROR;
6793   }
6794 create_request_failed:
6795   {
6796     gchar *str = gst_rtsp_strresult (res);
6797
6798     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6799         ("Could not create request. (%s)", str));
6800     g_free (str);
6801     goto cleanup_error;
6802   }
6803 setup_transport_failed:
6804   {
6805     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6806         ("Could not setup transport."));
6807     res = GST_RTSP_ERROR;
6808     goto cleanup_error;
6809   }
6810 response_error:
6811   {
6812     const gchar *str = gst_rtsp_status_as_text (code);
6813
6814     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6815         ("Error (%d): %s", code, GST_STR_NULL (str)));
6816     res = GST_RTSP_ERROR;
6817     goto cleanup_error;
6818   }
6819 send_error:
6820   {
6821     gchar *str = gst_rtsp_strresult (res);
6822
6823     if (res != GST_RTSP_EINTR) {
6824       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6825           ("Could not send message. (%s)", str));
6826     } else {
6827       GST_WARNING_OBJECT (src, "send interrupted");
6828     }
6829     g_free (str);
6830     goto cleanup_error;
6831   }
6832 no_transport:
6833   {
6834     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6835         ("Server did not select transport."));
6836     res = GST_RTSP_ERROR;
6837     goto cleanup_error;
6838   }
6839 nothing_to_activate:
6840   {
6841     /* none of the available error codes is really right .. */
6842     if (unsupported_real) {
6843       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6844           (_("No supported stream was found. You might need to install a "
6845                   "GStreamer RTSP extension plugin for Real media streams.")),
6846           (NULL));
6847     } else {
6848       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6849           (_("No supported stream was found. You might need to allow "
6850                   "more transport protocols or may otherwise be missing "
6851                   "the right GStreamer RTSP extension plugin.")), (NULL));
6852     }
6853     return GST_RTSP_ERROR;
6854   }
6855 cleanup_error:
6856   {
6857     gst_rtsp_message_unset (&request);
6858     gst_rtsp_message_unset (&response);
6859     return res;
6860   }
6861 }
6862
6863 static gboolean
6864 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6865     GstSegment * segment)
6866 {
6867   gint64 seconds;
6868   GstRTSPTimeRange *therange;
6869
6870   if (src->range)
6871     gst_rtsp_range_free (src->range);
6872
6873   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6874     GST_DEBUG_OBJECT (src, "parsed range %s", range);
6875     src->range = therange;
6876   } else {
6877     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6878     src->range = NULL;
6879     gst_segment_init (segment, GST_FORMAT_TIME);
6880     return FALSE;
6881   }
6882
6883   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
6884       therange->min.type, therange->min.seconds, therange->max.type,
6885       therange->max.seconds);
6886
6887   if (therange->min.type == GST_RTSP_TIME_NOW)
6888     seconds = 0;
6889   else if (therange->min.type == GST_RTSP_TIME_END)
6890     seconds = 0;
6891   else
6892     seconds = therange->min.seconds * GST_SECOND;
6893
6894   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6895       GST_TIME_ARGS (seconds));
6896
6897   /* we need to start playback without clipping from the position reported by
6898    * the server */
6899   segment->start = seconds;
6900   segment->position = seconds;
6901
6902   if (therange->max.type == GST_RTSP_TIME_NOW)
6903     seconds = -1;
6904   else if (therange->max.type == GST_RTSP_TIME_END)
6905     seconds = -1;
6906   else
6907     seconds = therange->max.seconds * GST_SECOND;
6908
6909   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6910       GST_TIME_ARGS (seconds));
6911
6912   /* live (WMS) server might send overflowed large max as its idea of infinity,
6913    * compensate to prevent problems later on */
6914   if (seconds != -1 && seconds < 0) {
6915     seconds = -1;
6916     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6917   }
6918
6919   /* live (WMS) might send min == max, which is not worth recording */
6920   if (segment->duration == -1 && seconds == segment->start)
6921     seconds = -1;
6922
6923   /* don't change duration with unknown value, we might have a valid value
6924    * there that we want to keep. */
6925   if (seconds != -1)
6926     segment->duration = seconds;
6927
6928   return TRUE;
6929 }
6930
6931 /* Parse clock profived by the server with following syntax:
6932  *
6933  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6934  */
6935 static gboolean
6936 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6937 {
6938   gboolean res = FALSE;
6939
6940   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6941     gchar **fields = NULL, **parts = NULL;
6942     gchar *remote_ip, *str;
6943     gint port;
6944     GstClockTime base_time;
6945     GstClock *netclock;
6946
6947     fields = g_strsplit (gstclock, " ", 0);
6948
6949     /* wrapped clock, not very interesting for now */
6950     if (fields[1] == NULL)
6951       goto cleanup;
6952
6953     /* remote IP address and port */
6954     if ((str = fields[2]) == NULL)
6955       goto cleanup;
6956
6957     parts = g_strsplit (str, ":", 0);
6958
6959     if ((remote_ip = parts[0]) == NULL)
6960       goto cleanup;
6961
6962     if ((str = parts[1]) == NULL)
6963       goto cleanup;
6964
6965     port = atoi (str);
6966     if (port == 0)
6967       goto cleanup;
6968
6969     /* base-time */
6970     if ((str = fields[3]) == NULL)
6971       goto cleanup;
6972
6973     base_time = g_ascii_strtoull (str, NULL, 10);
6974
6975     netclock =
6976         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
6977         base_time);
6978
6979     if (src->provided_clock)
6980       gst_object_unref (src->provided_clock);
6981     src->provided_clock = netclock;
6982
6983     gst_element_post_message (GST_ELEMENT_CAST (src),
6984         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
6985             src->provided_clock, TRUE));
6986
6987     res = TRUE;
6988   cleanup:
6989     g_strfreev (fields);
6990     g_strfreev (parts);
6991   }
6992   return res;
6993 }
6994
6995 /* must be called with the RTSP state lock */
6996 static GstRTSPResult
6997 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
6998     gboolean async)
6999 {
7000   GstRTSPResult res;
7001   gint i, n_streams;
7002
7003   /* prepare global stream caps properties */
7004   if (src->props)
7005     gst_structure_remove_all_fields (src->props);
7006   else
7007     src->props = gst_structure_new_empty ("RTSPProperties");
7008
7009   if (src->debug)
7010     gst_sdp_message_dump (sdp);
7011
7012   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
7013
7014   /* let the app inspect and change the SDP */
7015   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
7016
7017   gst_segment_init (&src->segment, GST_FORMAT_TIME);
7018
7019   /* parse range for duration reporting. */
7020   {
7021     const gchar *range;
7022
7023     for (i = 0;; i++) {
7024       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
7025       if (range == NULL)
7026         break;
7027
7028       /* keep track of the range and configure it in the segment */
7029       if (gst_rtspsrc_parse_range (src, range, &src->segment))
7030         break;
7031     }
7032   }
7033   /* parse clock information. This is GStreamer specific, a server can tell the
7034    * client what clock it is using and wrap that in a network clock. The
7035    * advantage of that is that we can slave to it. */
7036   {
7037     const gchar *gstclock;
7038
7039     for (i = 0;; i++) {
7040       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
7041       if (gstclock == NULL)
7042         break;
7043
7044       /* parse the clock and expose it in the provide_clock method */
7045       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
7046         break;
7047     }
7048   }
7049   /* try to find a global control attribute. Note that a '*' means that we should
7050    * do aggregate control with the current url (so we don't do anything and
7051    * leave the current connection as is) */
7052   {
7053     const gchar *control;
7054
7055     for (i = 0;; i++) {
7056       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
7057       if (control == NULL)
7058         break;
7059
7060       /* only take fully qualified urls */
7061       if (g_str_has_prefix (control, "rtsp://"))
7062         break;
7063     }
7064     if (control) {
7065       g_free (src->conninfo.location);
7066       src->conninfo.location = g_strdup (control);
7067       /* make a connection for this, if there was a connection already, nothing
7068        * happens. */
7069       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
7070         GST_ERROR_OBJECT (src, "could not connect");
7071       }
7072     }
7073     /* we need to keep the control url separate from the connection url because
7074      * the rules for constructing the media control url need it */
7075     g_free (src->control);
7076     src->control = g_strdup (control);
7077   }
7078
7079   /* create streams */
7080   n_streams = gst_sdp_message_medias_len (sdp);
7081   for (i = 0; i < n_streams; i++) {
7082     gst_rtspsrc_create_stream (src, sdp, i);
7083   }
7084
7085   src->state = GST_RTSP_STATE_INIT;
7086
7087   /* setup streams */
7088   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
7089     goto setup_failed;
7090
7091   /* reset our state */
7092   src->need_range = TRUE;
7093   src->skip = FALSE;
7094
7095   src->state = GST_RTSP_STATE_READY;
7096
7097   return res;
7098
7099   /* ERRORS */
7100 setup_failed:
7101   {
7102     GST_ERROR_OBJECT (src, "setup failed");
7103     gst_rtspsrc_cleanup (src);
7104     return res;
7105   }
7106 }
7107
7108 static GstRTSPResult
7109 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
7110     gboolean async)
7111 {
7112   GstRTSPResult res;
7113   GstRTSPMessage request = { 0 };
7114   GstRTSPMessage response = { 0 };
7115   guint8 *data;
7116   guint size;
7117   gchar *respcont = NULL;
7118
7119 restart:
7120   src->need_redirect = FALSE;
7121
7122   /* can't continue without a valid url */
7123   if (G_UNLIKELY (src->conninfo.url == NULL)) {
7124     res = GST_RTSP_EINVAL;
7125     goto no_url;
7126   }
7127   src->tried_url_auth = FALSE;
7128
7129   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
7130     goto connect_failed;
7131
7132   /* create OPTIONS */
7133   GST_DEBUG_OBJECT (src, "create options...");
7134   res =
7135       gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
7136       src->conninfo.url_str);
7137   if (res < 0)
7138     goto create_request_failed;
7139
7140   /* send OPTIONS */
7141   GST_DEBUG_OBJECT (src, "send options...");
7142
7143   if (async)
7144     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
7145
7146   if ((res =
7147           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
7148               NULL)) < 0)
7149     goto send_error;
7150
7151   /* parse OPTIONS */
7152   if (!gst_rtspsrc_parse_methods (src, &response))
7153     goto methods_error;
7154
7155   /* create DESCRIBE */
7156   GST_DEBUG_OBJECT (src, "create describe...");
7157   res =
7158       gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
7159       src->conninfo.url_str);
7160   if (res < 0)
7161     goto create_request_failed;
7162
7163   /* we only accept SDP for now */
7164   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
7165       "application/sdp");
7166
7167   /* send DESCRIBE */
7168   GST_DEBUG_OBJECT (src, "send describe...");
7169
7170   if (async)
7171     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
7172
7173   if ((res =
7174           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
7175               NULL)) < 0)
7176     goto send_error;
7177
7178   /* we only perform redirect for the describe, currently */
7179   if (src->need_redirect) {
7180     /* close connection, we don't have to send a TEARDOWN yet, ignore the
7181      * result. */
7182     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7183
7184     gst_rtsp_message_unset (&request);
7185     gst_rtsp_message_unset (&response);
7186
7187     /* and now retry */
7188     goto restart;
7189   }
7190
7191   /* it could be that the DESCRIBE method was not implemented */
7192   if (!src->methods & GST_RTSP_DESCRIBE)
7193     goto no_describe;
7194
7195   /* check if reply is SDP */
7196   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
7197       0);
7198   /* could not be set but since the request returned OK, we assume it
7199    * was SDP, else check it. */
7200   if (respcont) {
7201     if (g_ascii_strcasecmp (respcont, "application/sdp") != 0)
7202       goto wrong_content_type;
7203   }
7204
7205   /* get message body and parse as SDP */
7206   gst_rtsp_message_get_body (&response, &data, &size);
7207   if (data == NULL || size == 0)
7208     goto no_describe;
7209
7210   GST_DEBUG_OBJECT (src, "parse SDP...");
7211   gst_sdp_message_new (sdp);
7212   gst_sdp_message_parse_buffer (data, size, *sdp);
7213
7214   /* clean up any messages */
7215   gst_rtsp_message_unset (&request);
7216   gst_rtsp_message_unset (&response);
7217
7218   return res;
7219
7220   /* ERRORS */
7221 no_url:
7222   {
7223     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
7224         ("No valid RTSP URL was provided"));
7225     goto cleanup_error;
7226   }
7227 connect_failed:
7228   {
7229     gchar *str = gst_rtsp_strresult (res);
7230
7231     if (res != GST_RTSP_EINTR) {
7232       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
7233           ("Failed to connect. (%s)", str));
7234     } else {
7235       GST_WARNING_OBJECT (src, "connect interrupted");
7236     }
7237     g_free (str);
7238     goto cleanup_error;
7239   }
7240 create_request_failed:
7241   {
7242     gchar *str = gst_rtsp_strresult (res);
7243
7244     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7245         ("Could not create request. (%s)", str));
7246     g_free (str);
7247     goto cleanup_error;
7248   }
7249 send_error:
7250   {
7251     /* Don't post a message - the rtsp_send method will have
7252      * taken care of it because we passed NULL for the response code */
7253     goto cleanup_error;
7254   }
7255 methods_error:
7256   {
7257     /* error was posted */
7258     res = GST_RTSP_ERROR;
7259     goto cleanup_error;
7260   }
7261 wrong_content_type:
7262   {
7263     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7264         ("Server does not support SDP, got %s.", respcont));
7265     res = GST_RTSP_ERROR;
7266     goto cleanup_error;
7267   }
7268 no_describe:
7269   {
7270     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7271         ("Server can not provide an SDP."));
7272     res = GST_RTSP_ERROR;
7273     goto cleanup_error;
7274   }
7275 cleanup_error:
7276   {
7277     if (src->conninfo.connection) {
7278       GST_DEBUG_OBJECT (src, "free connection");
7279       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7280     }
7281     gst_rtsp_message_unset (&request);
7282     gst_rtsp_message_unset (&response);
7283     return res;
7284   }
7285 }
7286
7287 static GstRTSPResult
7288 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
7289 {
7290   GstRTSPResult ret;
7291
7292   src->methods =
7293       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
7294
7295   if (src->sdp == NULL) {
7296     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
7297       goto no_sdp;
7298   }
7299
7300   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
7301     goto open_failed;
7302
7303 done:
7304   if (async)
7305     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
7306
7307   return ret;
7308
7309   /* ERRORS */
7310 no_sdp:
7311   {
7312     GST_WARNING_OBJECT (src, "can't get sdp");
7313     src->open_error = TRUE;
7314     goto done;
7315   }
7316 open_failed:
7317   {
7318     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
7319     src->open_error = TRUE;
7320     goto done;
7321   }
7322 }
7323
7324 static GstRTSPResult
7325 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
7326 {
7327   GstRTSPMessage request = { 0 };
7328   GstRTSPMessage response = { 0 };
7329   GstRTSPResult res = GST_RTSP_OK;
7330   GList *walk;
7331   const gchar *control;
7332
7333   GST_DEBUG_OBJECT (src, "TEARDOWN...");
7334
7335   gst_rtspsrc_set_state (src, GST_STATE_READY);
7336
7337   if (src->state < GST_RTSP_STATE_READY) {
7338     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
7339     goto close;
7340   }
7341
7342   if (only_close)
7343     goto close;
7344
7345   /* construct a control url */
7346   control = get_aggregate_control (src);
7347
7348   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
7349     goto not_supported;
7350
7351   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7352     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7353     const gchar *setup_url;
7354     GstRTSPConnInfo *info;
7355
7356     /* try aggregate control first but do non-aggregate control otherwise */
7357     if (control)
7358       setup_url = control;
7359     else if ((setup_url = stream->conninfo.location) == NULL)
7360       continue;
7361
7362     if (src->conninfo.connection) {
7363       info = &src->conninfo;
7364     } else if (stream->conninfo.connection) {
7365       info = &stream->conninfo;
7366     } else {
7367       continue;
7368     }
7369     if (!info->connected)
7370       goto next;
7371
7372     /* do TEARDOWN */
7373     res =
7374         gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
7375     if (res < 0)
7376       goto create_request_failed;
7377
7378     if (async)
7379       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
7380
7381     if ((res =
7382             gst_rtspsrc_send (src, info->connection, &request, &response,
7383                 NULL)) < 0)
7384       goto send_error;
7385
7386     /* FIXME, parse result? */
7387     gst_rtsp_message_unset (&request);
7388     gst_rtsp_message_unset (&response);
7389
7390   next:
7391     /* early exit when we did aggregate control */
7392     if (control)
7393       break;
7394   }
7395
7396 close:
7397   /* close connections */
7398   GST_DEBUG_OBJECT (src, "closing connection...");
7399   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7400   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7401     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7402     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
7403   }
7404
7405   /* cleanup */
7406   gst_rtspsrc_cleanup (src);
7407
7408   src->state = GST_RTSP_STATE_INVALID;
7409
7410   if (async)
7411     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
7412
7413   return res;
7414
7415   /* ERRORS */
7416 create_request_failed:
7417   {
7418     gchar *str = gst_rtsp_strresult (res);
7419
7420     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7421         ("Could not create request. (%s)", str));
7422     g_free (str);
7423     goto close;
7424   }
7425 send_error:
7426   {
7427     gchar *str = gst_rtsp_strresult (res);
7428
7429     gst_rtsp_message_unset (&request);
7430     if (res != GST_RTSP_EINTR) {
7431       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7432           ("Could not send message. (%s)", str));
7433     } else {
7434       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7435     }
7436     g_free (str);
7437     goto close;
7438   }
7439 not_supported:
7440   {
7441     GST_DEBUG_OBJECT (src,
7442         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7443     goto close;
7444   }
7445 }
7446
7447 /* RTP-Info is of the format:
7448  *
7449  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7450  *
7451  * rtptime corresponds to the timestamp for the NPT time given in the header
7452  * seqbase corresponds to the next sequence number we received. This number
7453  * indicates the first seqnum after the seek and should be used to discard
7454  * packets that are from before the seek.
7455  */
7456 static gboolean
7457 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7458 {
7459   gchar **infos;
7460   gint i, j;
7461
7462   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7463
7464   infos = g_strsplit (rtpinfo, ",", 0);
7465   for (i = 0; infos[i]; i++) {
7466     gchar **fields;
7467     GstRTSPStream *stream;
7468     gint32 seqbase;
7469     gint64 timebase;
7470
7471     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7472
7473     /* init values, types of seqbase and timebase are bigger than needed so we
7474      * can store -1 as uninitialized values */
7475     stream = NULL;
7476     seqbase = -1;
7477     timebase = -1;
7478
7479     /* parse url, find stream for url.
7480      * parse seq and rtptime. The seq number should be configured in the rtp
7481      * depayloader or session manager to detect gaps. Same for the rtptime, it
7482      * should be used to create an initial time newsegment. */
7483     fields = g_strsplit (infos[i], ";", 0);
7484     for (j = 0; fields[j]; j++) {
7485       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7486       /* remove leading whitespace */
7487       fields[j] = g_strchug (fields[j]);
7488       if (g_str_has_prefix (fields[j], "url=")) {
7489         /* get the url and the stream */
7490         stream =
7491             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7492       } else if (g_str_has_prefix (fields[j], "seq=")) {
7493         seqbase = atoi (fields[j] + 4);
7494       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7495         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7496       }
7497     }
7498     g_strfreev (fields);
7499     /* now we need to store the values for the caps of the stream */
7500     if (stream != NULL) {
7501       GST_DEBUG_OBJECT (src,
7502           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7503           stream, seqbase, timebase);
7504
7505       /* we have a stream, configure detected params */
7506       stream->seqbase = seqbase;
7507       stream->timebase = timebase;
7508     }
7509   }
7510   g_strfreev (infos);
7511
7512   return TRUE;
7513 }
7514
7515 static void
7516 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7517 {
7518   guint64 interval;
7519   GList *walk;
7520
7521   interval = strtoul (rtcp, NULL, 10);
7522   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7523
7524   if (!interval)
7525     return;
7526
7527   interval *= GST_MSECOND;
7528
7529   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7530     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7531
7532     /* already (optionally) retrieved this when configuring manager */
7533     if (stream->session) {
7534       GObject *rtpsession = stream->session;
7535
7536       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7537           rtpsession);
7538       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7539     }
7540   }
7541
7542   /* now it happens that (Xenon) server sending this may also provide bogus
7543    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7544    * and just use RTP-Info to sync */
7545   if (src->manager) {
7546     GObjectClass *klass;
7547
7548     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7549     if (g_object_class_find_property (klass, "rtcp-sync")) {
7550       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7551       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7552     }
7553   }
7554 }
7555
7556 static gdouble
7557 gst_rtspsrc_get_float (const gchar * dstr)
7558 {
7559   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7560
7561   /* canonicalise floating point string so we can handle float strings
7562    * in the form "24.930" or "24,930" irrespective of the current locale */
7563   g_strlcpy (s, dstr, sizeof (s));
7564   g_strdelimit (s, ",", '.');
7565   return g_ascii_strtod (s, NULL);
7566 }
7567
7568 static gchar *
7569 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7570 {
7571   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7572
7573   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7574     g_strlcpy (val_str, "now", sizeof (val_str));
7575   } else {
7576     if (segment->position == 0) {
7577       g_strlcpy (val_str, "0", sizeof (val_str));
7578     } else {
7579       g_ascii_dtostr (val_str, sizeof (val_str),
7580           ((gdouble) segment->position) / GST_SECOND);
7581     }
7582   }
7583   return g_strdup_printf ("npt=%s-", val_str);
7584 }
7585
7586 static void
7587 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7588 {
7589   guint i, len;
7590
7591   stream->timebase = -1;
7592   stream->seqbase = -1;
7593
7594   len = stream->ptmap->len;
7595   for (i = 0; i < len; i++) {
7596     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7597     GstStructure *s;
7598
7599     if (item->caps == NULL)
7600       continue;
7601
7602     item->caps = gst_caps_make_writable (item->caps);
7603     s = gst_caps_get_structure (item->caps, 0);
7604     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7605   }
7606 }
7607
7608 static GstRTSPResult
7609 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7610 {
7611   GstRTSPResult res = GST_RTSP_OK;
7612
7613   if (src->state < GST_RTSP_STATE_READY) {
7614     res = GST_RTSP_ERROR;
7615     if (src->open_error) {
7616       GST_DEBUG_OBJECT (src, "the stream was in error");
7617       goto done;
7618     }
7619     if (async)
7620       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7621
7622     if ((res = gst_rtspsrc_open (src, async)) < 0) {
7623       GST_DEBUG_OBJECT (src, "failed to open stream");
7624       goto done;
7625     }
7626   }
7627
7628 done:
7629   return res;
7630 }
7631
7632 static GstRTSPResult
7633 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
7634 {
7635   GstRTSPMessage request = { 0 };
7636   GstRTSPMessage response = { 0 };
7637   GstRTSPResult res = GST_RTSP_OK;
7638   GList *walk;
7639   gchar *hval;
7640   gint hval_idx;
7641   const gchar *control;
7642
7643   GST_DEBUG_OBJECT (src, "PLAY...");
7644
7645   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7646     goto open_failed;
7647
7648   if (!(src->methods & GST_RTSP_PLAY))
7649     goto not_supported;
7650
7651   if (src->state == GST_RTSP_STATE_PLAYING)
7652     goto was_playing;
7653
7654   if (!src->conninfo.connection || !src->conninfo.connected)
7655     goto done;
7656
7657   /* send some dummy packets before we activate the receive in the
7658    * udp sources */
7659   gst_rtspsrc_send_dummy_packets (src);
7660
7661   /* require new SR packets */
7662   if (src->manager)
7663     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7664
7665   /* construct a control url */
7666   control = get_aggregate_control (src);
7667
7668   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7669     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7670     const gchar *setup_url;
7671     GstRTSPConnection *conn;
7672
7673     /* try aggregate control first but do non-aggregate control otherwise */
7674     if (control)
7675       setup_url = control;
7676     else if ((setup_url = stream->conninfo.location) == NULL)
7677       continue;
7678
7679     if (src->conninfo.connection) {
7680       conn = src->conninfo.connection;
7681     } else if (stream->conninfo.connection) {
7682       conn = stream->conninfo.connection;
7683     } else {
7684       continue;
7685     }
7686
7687     /* do play */
7688     res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
7689     if (res < 0)
7690       goto create_request_failed;
7691
7692     if (src->need_range) {
7693       hval = gen_range_header (src, segment);
7694
7695       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7696
7697       /* store the newsegment event so it can be sent from the streaming thread. */
7698       src->need_segment = TRUE;
7699     }
7700
7701     if (segment->rate != 1.0) {
7702       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7703
7704       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7705       if (src->skip)
7706         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7707       else
7708         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7709     }
7710
7711     if (async)
7712       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7713
7714     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7715       goto send_error;
7716
7717     /* seek may have silently failed as it is not supported */
7718     if (!(src->methods & GST_RTSP_PLAY)) {
7719       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7720       /* obviously it is supported as we made it here */
7721       src->methods |= GST_RTSP_PLAY;
7722       src->seekable = FALSE;
7723       /* but there is nothing to parse in the response,
7724        * so convey we have no idea and not to expect anything particular */
7725       clear_rtp_base (src, stream);
7726       if (control) {
7727         GList *run;
7728
7729         /* need to do for all streams */
7730         for (run = src->streams; run; run = g_list_next (run))
7731           clear_rtp_base (src, (GstRTSPStream *) run->data);
7732       }
7733       /* NOTE the above also disables npt based eos detection */
7734       /* and below forces position to 0,
7735        * which is visible feedback we lost the plot */
7736       segment->start = segment->position = src->last_pos;
7737     }
7738
7739     gst_rtsp_message_unset (&request);
7740
7741     /* parse RTP npt field. This is the current position in the stream (Normal
7742      * Play Time) and should be put in the NEWSEGMENT position field. */
7743     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7744             0) == GST_RTSP_OK)
7745       gst_rtspsrc_parse_range (src, hval, segment);
7746
7747     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7748     segment->rate = 1.0;
7749
7750     /* parse Speed header. This is the intended playback rate of the stream
7751      * and should be put in the NEWSEGMENT rate field. */
7752     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7753             0) == GST_RTSP_OK) {
7754       segment->rate = gst_rtspsrc_get_float (hval);
7755     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7756             &hval, 0) == GST_RTSP_OK) {
7757       segment->rate = gst_rtspsrc_get_float (hval);
7758     }
7759
7760     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7761      * for the RTP packets. If this is not present, we assume all starts from 0...
7762      * This is info for the RTP session manager that we pass to it in caps. */
7763     hval_idx = 0;
7764     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7765             &hval, hval_idx++) == GST_RTSP_OK)
7766       gst_rtspsrc_parse_rtpinfo (src, hval);
7767
7768     /* some servers indicate RTCP parameters in PLAY response,
7769      * rather than properly in SDP */
7770     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7771             &hval, 0) == GST_RTSP_OK)
7772       gst_rtspsrc_handle_rtcp_interval (src, hval);
7773
7774     gst_rtsp_message_unset (&response);
7775
7776     /* early exit when we did aggregate control */
7777     if (control)
7778       break;
7779   }
7780   /* configure the caps of the streams after we parsed all headers. Only reset
7781    * the manager object when we set a new Range header (we did a seek) */
7782   gst_rtspsrc_configure_caps (src, segment, src->need_range);
7783
7784   /* set to PLAYING after we have configured the caps, otherwise we
7785    * might end up calling request_key (with SRTP) while caps are still
7786    * being configured. */
7787   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7788
7789   /* set again when needed */
7790   src->need_range = FALSE;
7791
7792   src->running = TRUE;
7793   src->base_time = -1;
7794   src->state = GST_RTSP_STATE_PLAYING;
7795
7796   /* mark discont */
7797   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7798   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7799     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7800     stream->discont = TRUE;
7801   }
7802
7803 done:
7804   if (async)
7805     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7806
7807   return res;
7808
7809   /* ERRORS */
7810 open_failed:
7811   {
7812     GST_DEBUG_OBJECT (src, "failed to open stream");
7813     goto done;
7814   }
7815 not_supported:
7816   {
7817     GST_DEBUG_OBJECT (src, "PLAY is not supported");
7818     goto done;
7819   }
7820 was_playing:
7821   {
7822     GST_DEBUG_OBJECT (src, "we were already PLAYING");
7823     goto done;
7824   }
7825 create_request_failed:
7826   {
7827     gchar *str = gst_rtsp_strresult (res);
7828
7829     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7830         ("Could not create request. (%s)", str));
7831     g_free (str);
7832     goto done;
7833   }
7834 send_error:
7835   {
7836     gchar *str = gst_rtsp_strresult (res);
7837
7838     gst_rtsp_message_unset (&request);
7839     if (res != GST_RTSP_EINTR) {
7840       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7841           ("Could not send message. (%s)", str));
7842     } else {
7843       GST_WARNING_OBJECT (src, "PLAY interrupted");
7844     }
7845     g_free (str);
7846     goto done;
7847   }
7848 }
7849
7850 static GstRTSPResult
7851 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7852 {
7853   GstRTSPResult res = GST_RTSP_OK;
7854   GstRTSPMessage request = { 0 };
7855   GstRTSPMessage response = { 0 };
7856   GList *walk;
7857   const gchar *control;
7858
7859   GST_DEBUG_OBJECT (src, "PAUSE...");
7860
7861   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7862     goto open_failed;
7863
7864   if (!(src->methods & GST_RTSP_PAUSE))
7865     goto not_supported;
7866
7867   if (src->state == GST_RTSP_STATE_READY)
7868     goto was_paused;
7869
7870   if (!src->conninfo.connection || !src->conninfo.connected)
7871     goto no_connection;
7872
7873   /* construct a control url */
7874   control = get_aggregate_control (src);
7875
7876   /* loop over the streams. We might exit the loop early when we could do an
7877    * aggregate control */
7878   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7879     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7880     GstRTSPConnection *conn;
7881     const gchar *setup_url;
7882
7883     /* try aggregate control first but do non-aggregate control otherwise */
7884     if (control)
7885       setup_url = control;
7886     else if ((setup_url = stream->conninfo.location) == NULL)
7887       continue;
7888
7889     if (src->conninfo.connection) {
7890       conn = src->conninfo.connection;
7891     } else if (stream->conninfo.connection) {
7892       conn = stream->conninfo.connection;
7893     } else {
7894       continue;
7895     }
7896
7897     if (async)
7898       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7899           ("Sending PAUSE request"));
7900
7901     if ((res =
7902             gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
7903                 setup_url)) < 0)
7904       goto create_request_failed;
7905
7906     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7907       goto send_error;
7908
7909     gst_rtsp_message_unset (&request);
7910     gst_rtsp_message_unset (&response);
7911
7912     /* exit early when we did agregate control */
7913     if (control)
7914       break;
7915   }
7916
7917   /* change element states now */
7918   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7919
7920 no_connection:
7921   src->state = GST_RTSP_STATE_READY;
7922
7923 done:
7924   if (async)
7925     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7926
7927   return res;
7928
7929   /* ERRORS */
7930 open_failed:
7931   {
7932     GST_DEBUG_OBJECT (src, "failed to open stream");
7933     goto done;
7934   }
7935 not_supported:
7936   {
7937     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7938     goto done;
7939   }
7940 was_paused:
7941   {
7942     GST_DEBUG_OBJECT (src, "we were already PAUSED");
7943     goto done;
7944   }
7945 create_request_failed:
7946   {
7947     gchar *str = gst_rtsp_strresult (res);
7948
7949     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7950         ("Could not create request. (%s)", str));
7951     g_free (str);
7952     goto done;
7953   }
7954 send_error:
7955   {
7956     gchar *str = gst_rtsp_strresult (res);
7957
7958     gst_rtsp_message_unset (&request);
7959     if (res != GST_RTSP_EINTR) {
7960       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7961           ("Could not send message. (%s)", str));
7962     } else {
7963       GST_WARNING_OBJECT (src, "PAUSE interrupted");
7964     }
7965     g_free (str);
7966     goto done;
7967   }
7968 }
7969
7970 static void
7971 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
7972 {
7973   GstRTSPSrc *rtspsrc;
7974
7975   rtspsrc = GST_RTSPSRC (bin);
7976
7977   switch (GST_MESSAGE_TYPE (message)) {
7978     case GST_MESSAGE_EOS:
7979       gst_message_unref (message);
7980       break;
7981     case GST_MESSAGE_ELEMENT:
7982     {
7983       const GstStructure *s = gst_message_get_structure (message);
7984
7985       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
7986         gboolean ignore_timeout;
7987
7988         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
7989
7990         GST_OBJECT_LOCK (rtspsrc);
7991         ignore_timeout = rtspsrc->ignore_timeout;
7992         rtspsrc->ignore_timeout = TRUE;
7993         GST_OBJECT_UNLOCK (rtspsrc);
7994
7995         /* we only act on the first udp timeout message, others are irrelevant
7996          * and can be ignored. */
7997         if (!ignore_timeout)
7998           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
7999         /* eat and free */
8000         gst_message_unref (message);
8001         return;
8002       }
8003       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8004       break;
8005     }
8006     case GST_MESSAGE_ERROR:
8007     {
8008       GstObject *udpsrc;
8009       GstRTSPStream *stream;
8010       GstFlowReturn ret;
8011
8012       udpsrc = GST_MESSAGE_SRC (message);
8013
8014       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
8015           GST_ELEMENT_NAME (udpsrc));
8016
8017       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
8018       if (!stream)
8019         goto forward;
8020
8021       /* we ignore the RTCP udpsrc */
8022       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
8023         goto done;
8024
8025       /* if we get error messages from the udp sources, that's not a problem as
8026        * long as not all of them error out. We also don't really know what the
8027        * problem is, the message does not give enough detail... */
8028       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
8029       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
8030       if (ret != GST_FLOW_OK)
8031         goto forward;
8032
8033     done:
8034       gst_message_unref (message);
8035       break;
8036
8037     forward:
8038       /* fatal but not our message, forward */
8039       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8040       break;
8041     }
8042     default:
8043     {
8044       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8045       break;
8046     }
8047   }
8048 }
8049
8050 /* the thread where everything happens */
8051 static void
8052 gst_rtspsrc_thread (GstRTSPSrc * src)
8053 {
8054   gint cmd;
8055
8056   GST_OBJECT_LOCK (src);
8057   cmd = src->pending_cmd;
8058   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
8059       || cmd == CMD_LOOP || cmd == CMD_OPEN)
8060     src->pending_cmd = CMD_LOOP;
8061   else
8062     src->pending_cmd = CMD_WAIT;
8063   GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
8064
8065   /* we got the message command, so ensure communication is possible again */
8066   gst_rtspsrc_connection_flush (src, FALSE);
8067
8068   src->busy_cmd = cmd;
8069   GST_OBJECT_UNLOCK (src);
8070
8071   switch (cmd) {
8072     case CMD_OPEN:
8073       gst_rtspsrc_open (src, TRUE);
8074       break;
8075     case CMD_PLAY:
8076       gst_rtspsrc_play (src, &src->segment, TRUE);
8077       break;
8078     case CMD_PAUSE:
8079       gst_rtspsrc_pause (src, TRUE);
8080       break;
8081     case CMD_CLOSE:
8082       gst_rtspsrc_close (src, TRUE, FALSE);
8083       break;
8084     case CMD_LOOP:
8085       gst_rtspsrc_loop (src);
8086       break;
8087     case CMD_RECONNECT:
8088       gst_rtspsrc_reconnect (src, FALSE);
8089       break;
8090     default:
8091       break;
8092   }
8093
8094   GST_OBJECT_LOCK (src);
8095   /* and go back to sleep */
8096   if (src->pending_cmd == CMD_WAIT) {
8097     if (src->task)
8098       gst_task_pause (src->task);
8099   }
8100   /* reset waiting */
8101   src->busy_cmd = CMD_WAIT;
8102   GST_OBJECT_UNLOCK (src);
8103 }
8104
8105 static gboolean
8106 gst_rtspsrc_start (GstRTSPSrc * src)
8107 {
8108   GST_DEBUG_OBJECT (src, "starting");
8109
8110   GST_OBJECT_LOCK (src);
8111
8112   src->pending_cmd = CMD_WAIT;
8113
8114   if (src->task == NULL) {
8115     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
8116     if (src->task == NULL)
8117       goto task_error;
8118
8119     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
8120   }
8121   GST_OBJECT_UNLOCK (src);
8122
8123   return TRUE;
8124
8125   /* ERRORS */
8126 task_error:
8127   {
8128     GST_OBJECT_UNLOCK (src);
8129     GST_ERROR_OBJECT (src, "failed to create task");
8130     return FALSE;
8131   }
8132 }
8133
8134 static gboolean
8135 gst_rtspsrc_stop (GstRTSPSrc * src)
8136 {
8137   GstTask *task;
8138
8139   GST_DEBUG_OBJECT (src, "stopping");
8140
8141   /* also cancels pending task */
8142   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
8143
8144   GST_OBJECT_LOCK (src);
8145   if ((task = src->task)) {
8146     src->task = NULL;
8147     GST_OBJECT_UNLOCK (src);
8148
8149     gst_task_stop (task);
8150
8151     /* make sure it is not running */
8152     GST_RTSP_STREAM_LOCK (src);
8153     GST_RTSP_STREAM_UNLOCK (src);
8154
8155     /* now wait for the task to finish */
8156     gst_task_join (task);
8157
8158     /* and free the task */
8159     gst_object_unref (GST_OBJECT (task));
8160
8161     GST_OBJECT_LOCK (src);
8162   }
8163   GST_OBJECT_UNLOCK (src);
8164
8165   /* ensure synchronously all is closed and clean */
8166   gst_rtspsrc_close (src, FALSE, TRUE);
8167
8168   return TRUE;
8169 }
8170
8171 static GstStateChangeReturn
8172 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
8173 {
8174   GstRTSPSrc *rtspsrc;
8175   GstStateChangeReturn ret;
8176
8177   rtspsrc = GST_RTSPSRC (element);
8178
8179   switch (transition) {
8180     case GST_STATE_CHANGE_NULL_TO_READY:
8181       if (!gst_rtspsrc_start (rtspsrc))
8182         goto start_failed;
8183       break;
8184     case GST_STATE_CHANGE_READY_TO_PAUSED:
8185       /* init some state */
8186       rtspsrc->cur_protocols = rtspsrc->protocols;
8187       /* first attempt, don't ignore timeouts */
8188       rtspsrc->ignore_timeout = FALSE;
8189       rtspsrc->open_error = FALSE;
8190       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
8191       break;
8192     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8193       set_manager_buffer_mode (rtspsrc);
8194       /* fall-through */
8195     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8196       /* unblock the tcp tasks and make the loop waiting */
8197       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
8198         /* make sure it is waiting before we send PAUSE or PLAY below */
8199         GST_RTSP_STREAM_LOCK (rtspsrc);
8200         GST_RTSP_STREAM_UNLOCK (rtspsrc);
8201       }
8202       break;
8203     case GST_STATE_CHANGE_PAUSED_TO_READY:
8204       break;
8205     default:
8206       break;
8207   }
8208
8209   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
8210   if (ret == GST_STATE_CHANGE_FAILURE)
8211     goto done;
8212
8213   switch (transition) {
8214     case GST_STATE_CHANGE_NULL_TO_READY:
8215       ret = GST_STATE_CHANGE_SUCCESS;
8216       break;
8217     case GST_STATE_CHANGE_READY_TO_PAUSED:
8218       ret = GST_STATE_CHANGE_NO_PREROLL;
8219       break;
8220     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8221       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
8222       ret = GST_STATE_CHANGE_SUCCESS;
8223       break;
8224     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8225       /* send pause request and keep the idle task around */
8226       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
8227       ret = GST_STATE_CHANGE_NO_PREROLL;
8228       break;
8229     case GST_STATE_CHANGE_PAUSED_TO_READY:
8230       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
8231       ret = GST_STATE_CHANGE_SUCCESS;
8232       break;
8233     case GST_STATE_CHANGE_READY_TO_NULL:
8234       gst_rtspsrc_stop (rtspsrc);
8235       ret = GST_STATE_CHANGE_SUCCESS;
8236       break;
8237     default:
8238       break;
8239   }
8240
8241 done:
8242   return ret;
8243
8244 start_failed:
8245   {
8246     GST_DEBUG_OBJECT (rtspsrc, "start failed");
8247     return GST_STATE_CHANGE_FAILURE;
8248   }
8249 }
8250
8251 static gboolean
8252 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
8253 {
8254   gboolean res;
8255   GstRTSPSrc *rtspsrc;
8256
8257   rtspsrc = GST_RTSPSRC (element);
8258
8259   if (GST_EVENT_IS_DOWNSTREAM (event)) {
8260     res = gst_rtspsrc_push_event (rtspsrc, event);
8261   } else {
8262     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
8263   }
8264
8265   return res;
8266 }
8267
8268
8269 /*** GSTURIHANDLER INTERFACE *************************************************/
8270
8271 static GstURIType
8272 gst_rtspsrc_uri_get_type (GType type)
8273 {
8274   return GST_URI_SRC;
8275 }
8276
8277 static const gchar *const *
8278 gst_rtspsrc_uri_get_protocols (GType type)
8279 {
8280   static const gchar *protocols[] =
8281       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
8282     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
8283   };
8284
8285   return protocols;
8286 }
8287
8288 static gchar *
8289 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
8290 {
8291   GstRTSPSrc *src = GST_RTSPSRC (handler);
8292
8293   /* FIXME: make thread-safe */
8294   return g_strdup (src->conninfo.location);
8295 }
8296
8297 static gboolean
8298 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
8299     GError ** error)
8300 {
8301   GstRTSPSrc *src;
8302   GstRTSPResult res;
8303   GstSDPResult sres;
8304   GstRTSPUrl *newurl = NULL;
8305   GstSDPMessage *sdp = NULL;
8306
8307   src = GST_RTSPSRC (handler);
8308
8309   /* same URI, we're fine */
8310   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
8311     goto was_ok;
8312
8313   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
8314     sres = gst_sdp_message_new (&sdp);
8315     if (sres < 0)
8316       goto sdp_failed;
8317
8318     GST_DEBUG_OBJECT (src, "parsing SDP message");
8319     sres = gst_sdp_message_parse_uri (uri, sdp);
8320     if (sres < 0)
8321       goto invalid_sdp;
8322   } else {
8323     /* try to parse */
8324     GST_DEBUG_OBJECT (src, "parsing URI");
8325     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
8326       goto parse_error;
8327   }
8328
8329   /* if worked, free previous and store new url object along with the original
8330    * location. */
8331   GST_DEBUG_OBJECT (src, "configuring URI");
8332   g_free (src->conninfo.location);
8333   src->conninfo.location = g_strdup (uri);
8334   gst_rtsp_url_free (src->conninfo.url);
8335   src->conninfo.url = newurl;
8336   g_free (src->conninfo.url_str);
8337   if (newurl)
8338     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
8339   else
8340     src->conninfo.url_str = NULL;
8341
8342   if (src->sdp)
8343     gst_sdp_message_free (src->sdp);
8344   src->sdp = sdp;
8345   src->from_sdp = sdp != NULL;
8346
8347   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
8348   GST_DEBUG_OBJECT (src, "request uri is: %s",
8349       GST_STR_NULL (src->conninfo.url_str));
8350
8351   return TRUE;
8352
8353   /* Special cases */
8354 was_ok:
8355   {
8356     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
8357     return TRUE;
8358   }
8359 sdp_failed:
8360   {
8361     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
8362     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8363         "Could not create SDP");
8364     return FALSE;
8365   }
8366 invalid_sdp:
8367   {
8368     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
8369         GST_STR_NULL (uri));
8370     gst_sdp_message_free (sdp);
8371     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8372         "Invalid SDP");
8373     return FALSE;
8374   }
8375 parse_error:
8376   {
8377     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
8378         GST_STR_NULL (uri), res);
8379     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8380         "Invalid RTSP URI");
8381     return FALSE;
8382   }
8383 }
8384
8385 static void
8386 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
8387 {
8388   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
8389
8390   iface->get_type = gst_rtspsrc_uri_get_type;
8391   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
8392   iface->get_uri = gst_rtspsrc_uri_get_uri;
8393   iface->set_uri = gst_rtspsrc_uri_set_uri;
8394 }