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