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