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