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