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