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