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