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