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