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