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