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