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