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