rtsp-stream: Set close-socket FALSE on UDP src:es
[platform/upstream/gstreamer.git] / gst / rtsp-sink / gstrtspclientsink.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  *               <2015> Jan Schmidt <jan at centricular dot com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /*
22  * Unless otherwise indicated, Source Code is licensed under MIT license.
23  * See further explanation attached in License Statement (distributed in the file
24  * LICENSE).
25  *
26  * Permission is hereby granted, free of charge, to any person obtaining a copy of
27  * this software and associated documentation files (the "Software"), to deal in
28  * the Software without restriction, including without limitation the rights to
29  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
30  * of the Software, and to permit persons to whom the Software is furnished to do
31  * so, subject to the following conditions:
32  *
33  * The above copyright notice and this permission notice shall be included in all
34  * copies or substantial portions of the Software.
35  *
36  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42  * SOFTWARE.
43  */
44 /**
45  * SECTION:element-rtspclientsink
46  *
47  * Makes a connection to an RTSP server and send data via RTSP RECORD.
48  * rtspclientsink strictly follows RFC 2326
49  *
50  * RTSP supports transport over TCP or UDP in unicast or multicast mode. By
51  * default rtspclientsink 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 #GstRTSPClientSink:protocols property.
54  *
55  * rtspclientsink will internally instantiate an RTP session manager element
56  * that will handle the RTCP messages to and from the server, jitter removal,
57  * and packet reordering.
58  * This feature is implemented using the gstrtpbin element.
59  *
60  * rtspclientsink accepts any stream for which there is an installed payloader,
61  * creates the payloader and manages payload-types, as well as RTX setup.
62  * The new-payloader signal is fired when a payloader is created, in case
63  * an app wants to do custom configuration (such as for MTU).
64  *
65  * <refsect2>
66  * <title>Example launch line</title>
67  * |[
68  * gst-launch-1.0 videotestsrc ! jpegenc ! rtspclientsink location=rtsp://some.server/url
69  * ]| Establish a connection to an RTSP server and send JPEG encoded video packets
70  * </refsect2>
71  */
72
73 /* FIXMEs
74  * - Handle EOS properly and shutdown. The problem with EOS is we don't know
75  *   when the server has received all data, so we don't know when to do teardown.
76  *   At the moment, we forward EOS to the app as soon as we stop sending. Is there
77  *   a way to know from the receiver that it's got all data? Some session timeout?
78  * - Implement extension support for Real / WMS if they support RECORD?
79  * - Add support for network clock synchronised streaming?
80  * - Fix crypto key nego so SAVP/SAVPF profiles work.
81  * - Test (&fix?) HTTP tunnel support
82  * - Add an address pool object for GstRTSPStreams to use for multicast
83  * - Test multicast UDP transport
84  */
85
86 #ifdef HAVE_CONFIG_H
87 #include "config.h"
88 #endif
89
90 #ifdef HAVE_UNISTD_H
91 #include <unistd.h>
92 #endif /* HAVE_UNISTD_H */
93 #include <stdlib.h>
94 #include <string.h>
95 #include <stdio.h>
96 #include <stdarg.h>
97
98 #include <gst/net/gstnet.h>
99 #include <gst/sdp/gstsdpmessage.h>
100 #include <gst/sdp/gstmikey.h>
101 #include <gst/rtp/rtp.h>
102
103 #include "gstrtspclientsink.h"
104
105 GST_DEBUG_CATEGORY_STATIC (rtsp_client_sink_debug);
106 #define GST_CAT_DEFAULT (rtsp_client_sink_debug)
107
108 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream_%u",
109     GST_PAD_SINK,
110     GST_PAD_REQUEST,
111     GST_STATIC_CAPS_ANY);       /* Actual caps come from available set of payloaders */
112
113 enum
114 {
115   SIGNAL_HANDLE_REQUEST,
116   SIGNAL_NEW_MANAGER,
117   SIGNAL_NEW_PAYLOADER,
118   SIGNAL_REQUEST_RTCP_KEY,
119   LAST_SIGNAL
120 };
121
122 enum _GstRTSPClientSinkNtpTimeSource
123 {
124   NTP_TIME_SOURCE_NTP,
125   NTP_TIME_SOURCE_UNIX,
126   NTP_TIME_SOURCE_RUNNING_TIME,
127   NTP_TIME_SOURCE_CLOCK_TIME
128 };
129
130 #define GST_TYPE_RTSP_CLIENT_SINK_NTP_TIME_SOURCE (gst_rtsp_client_sink_ntp_time_source_get_type())
131 static GType
132 gst_rtsp_client_sink_ntp_time_source_get_type (void)
133 {
134   static GType ntp_time_source_type = 0;
135   static const GEnumValue ntp_time_source_values[] = {
136     {NTP_TIME_SOURCE_NTP, "NTP time based on realtime clock", "ntp"},
137     {NTP_TIME_SOURCE_UNIX, "UNIX time based on realtime clock", "unix"},
138     {NTP_TIME_SOURCE_RUNNING_TIME,
139           "Running time based on pipeline clock",
140         "running-time"},
141     {NTP_TIME_SOURCE_CLOCK_TIME, "Pipeline clock time", "clock-time"},
142     {0, NULL, NULL},
143   };
144
145   if (!ntp_time_source_type) {
146     ntp_time_source_type =
147         g_enum_register_static ("GstRTSPClientSinkNtpTimeSource",
148         ntp_time_source_values);
149   }
150   return ntp_time_source_type;
151 }
152
153 #define DEFAULT_LOCATION         NULL
154 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
155 #define DEFAULT_DEBUG            FALSE
156 #define DEFAULT_RETRY            20
157 #define DEFAULT_TIMEOUT          5000000
158 #define DEFAULT_UDP_BUFFER_SIZE  0x80000
159 #define DEFAULT_TCP_TIMEOUT      20000000
160 #define DEFAULT_LATENCY_MS       2000
161 #define DEFAULT_DO_RTSP_KEEP_ALIVE       TRUE
162 #define DEFAULT_PROXY            NULL
163 #define DEFAULT_RTP_BLOCKSIZE    0
164 #define DEFAULT_USER_ID          NULL
165 #define DEFAULT_USER_PW          NULL
166 #define DEFAULT_PORT_RANGE       NULL
167 #define DEFAULT_UDP_RECONNECT    TRUE
168 #define DEFAULT_MULTICAST_IFACE  NULL
169 #define DEFAULT_TLS_VALIDATION_FLAGS     G_TLS_CERTIFICATE_VALIDATE_ALL
170 #define DEFAULT_TLS_DATABASE     NULL
171 #define DEFAULT_TLS_INTERACTION     NULL
172 #define DEFAULT_NTP_TIME_SOURCE  NTP_TIME_SOURCE_NTP
173 #define DEFAULT_USER_AGENT       "GStreamer/" PACKAGE_VERSION
174 #define DEFAULT_PROFILES         GST_RTSP_PROFILE_AVP
175 #define DEFAULT_RTX_TIME_MS      500
176
177 enum
178 {
179   PROP_0,
180   PROP_LOCATION,
181   PROP_PROTOCOLS,
182   PROP_DEBUG,
183   PROP_RETRY,
184   PROP_TIMEOUT,
185   PROP_TCP_TIMEOUT,
186   PROP_LATENCY,
187   PROP_RTX_TIME,
188   PROP_DO_RTSP_KEEP_ALIVE,
189   PROP_PROXY,
190   PROP_PROXY_ID,
191   PROP_PROXY_PW,
192   PROP_RTP_BLOCKSIZE,
193   PROP_USER_ID,
194   PROP_USER_PW,
195   PROP_PORT_RANGE,
196   PROP_UDP_BUFFER_SIZE,
197   PROP_UDP_RECONNECT,
198   PROP_MULTICAST_IFACE,
199   PROP_SDES,
200   PROP_TLS_VALIDATION_FLAGS,
201   PROP_TLS_DATABASE,
202   PROP_TLS_INTERACTION,
203   PROP_NTP_TIME_SOURCE,
204   PROP_USER_AGENT,
205   PROP_PROFILES
206 };
207
208 static void gst_rtsp_client_sink_finalize (GObject * object);
209
210 static void gst_rtsp_client_sink_set_property (GObject * object, guint prop_id,
211     const GValue * value, GParamSpec * pspec);
212 static void gst_rtsp_client_sink_get_property (GObject * object, guint prop_id,
213     GValue * value, GParamSpec * pspec);
214
215 static GstClock *gst_rtsp_client_sink_provide_clock (GstElement * element);
216
217 static void gst_rtsp_client_sink_uri_handler_init (gpointer g_iface,
218     gpointer iface_data);
219
220 static gboolean gst_rtsp_client_sink_set_proxy (GstRTSPClientSink * rtsp,
221     const gchar * proxy);
222 static void gst_rtsp_client_sink_set_tcp_timeout (GstRTSPClientSink *
223     rtsp_client_sink, guint64 timeout);
224
225 static GstStateChangeReturn gst_rtsp_client_sink_change_state (GstElement *
226     element, GstStateChange transition);
227 static void gst_rtsp_client_sink_handle_message (GstBin * bin,
228     GstMessage * message);
229
230 static gboolean gst_rtsp_client_sink_setup_auth (GstRTSPClientSink * sink,
231     GstRTSPMessage * response);
232
233 static gboolean gst_rtsp_client_sink_loop_send_cmd (GstRTSPClientSink * sink,
234     gint cmd, gint mask);
235
236 static GstRTSPResult gst_rtsp_client_sink_open (GstRTSPClientSink * sink,
237     gboolean async);
238 static GstRTSPResult gst_rtsp_client_sink_record (GstRTSPClientSink * sink,
239     gboolean async);
240 static GstRTSPResult gst_rtsp_client_sink_pause (GstRTSPClientSink * sink,
241     gboolean async);
242 static GstRTSPResult gst_rtsp_client_sink_close (GstRTSPClientSink * sink,
243     gboolean async, gboolean only_close);
244 static gboolean gst_rtsp_client_sink_collect_streams (GstRTSPClientSink * sink);
245
246 static gboolean gst_rtsp_client_sink_uri_set_uri (GstURIHandler * handler,
247     const gchar * uri, GError ** error);
248 static gchar *gst_rtsp_client_sink_uri_get_uri (GstURIHandler * handler);
249
250 static gboolean gst_rtsp_client_sink_loop (GstRTSPClientSink * sink);
251 static void gst_rtsp_client_sink_connection_flush (GstRTSPClientSink * sink,
252     gboolean flush);
253
254 static GstPad *gst_rtsp_client_sink_request_new_pad (GstElement * element,
255     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
256 static void gst_rtsp_client_sink_release_pad (GstElement * element,
257     GstPad * pad);
258
259 /* commands we send to out loop to notify it of events */
260 #define CMD_OPEN        (1 << 0)
261 #define CMD_RECORD      (1 << 1)
262 #define CMD_PAUSE       (1 << 2)
263 #define CMD_CLOSE       (1 << 3)
264 #define CMD_WAIT        (1 << 4)
265 #define CMD_RECONNECT   (1 << 5)
266 #define CMD_LOOP        (1 << 6)
267
268 /* mask for all commands */
269 #define CMD_ALL         ((CMD_LOOP << 1) - 1)
270
271 #define GST_ELEMENT_PROGRESS(el, type, code, text)      \
272 G_STMT_START {                                          \
273   gchar *__txt = _gst_element_error_printf text;        \
274   gst_element_post_message (GST_ELEMENT_CAST (el),      \
275       gst_message_new_progress (GST_OBJECT_CAST (el),   \
276           GST_PROGRESS_TYPE_ ##type, code, __txt));     \
277   g_free (__txt);                                       \
278 } G_STMT_END
279
280 static guint gst_rtsp_client_sink_signals[LAST_SIGNAL] = { 0 };
281
282 #define gst_rtsp_client_sink_parent_class parent_class
283 G_DEFINE_TYPE_WITH_CODE (GstRTSPClientSink, gst_rtsp_client_sink, GST_TYPE_BIN,
284     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
285         gst_rtsp_client_sink_uri_handler_init));
286
287 #ifndef GST_DISABLE_GST_DEBUG
288 static inline const gchar *
289 cmd_to_string (guint cmd)
290 {
291   switch (cmd) {
292     case CMD_OPEN:
293       return "OPEN";
294     case CMD_RECORD:
295       return "RECORD";
296     case CMD_PAUSE:
297       return "PAUSE";
298     case CMD_CLOSE:
299       return "CLOSE";
300     case CMD_WAIT:
301       return "WAIT";
302     case CMD_RECONNECT:
303       return "RECONNECT";
304     case CMD_LOOP:
305       return "LOOP";
306   }
307
308   return "unknown";
309 }
310 #endif
311
312 static void
313 gst_rtsp_client_sink_class_init (GstRTSPClientSinkClass * klass)
314 {
315   GObjectClass *gobject_class;
316   GstElementClass *gstelement_class;
317   GstBinClass *gstbin_class;
318
319   gobject_class = (GObjectClass *) klass;
320   gstelement_class = (GstElementClass *) klass;
321   gstbin_class = (GstBinClass *) klass;
322
323   GST_DEBUG_CATEGORY_INIT (rtsp_client_sink_debug, "rtspclientsink", 0,
324       "RTSP sink element");
325
326   gobject_class->set_property = gst_rtsp_client_sink_set_property;
327   gobject_class->get_property = gst_rtsp_client_sink_get_property;
328
329   gobject_class->finalize = gst_rtsp_client_sink_finalize;
330
331   g_object_class_install_property (gobject_class, PROP_LOCATION,
332       g_param_spec_string ("location", "RTSP Location",
333           "Location of the RTSP url to read",
334           DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
335
336   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
337       g_param_spec_flags ("protocols", "Protocols",
338           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
339           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
340
341   g_object_class_install_property (gobject_class, PROP_PROFILES,
342       g_param_spec_flags ("profiles", "Profiles",
343           "Allowed RTSP profiles", GST_TYPE_RTSP_PROFILE,
344           DEFAULT_PROFILES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
345
346   g_object_class_install_property (gobject_class, PROP_DEBUG,
347       g_param_spec_boolean ("debug", "Debug",
348           "Dump request and response messages to stdout",
349           DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
350
351   g_object_class_install_property (gobject_class, PROP_RETRY,
352       g_param_spec_uint ("retry", "Retry",
353           "Max number of retries when allocating RTP ports.",
354           0, G_MAXUINT16, DEFAULT_RETRY,
355           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
356
357   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
358       g_param_spec_uint64 ("timeout", "Timeout",
359           "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
360           0, G_MAXUINT64, DEFAULT_TIMEOUT,
361           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
362
363   g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
364       g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
365           "Fail after timeout microseconds on TCP connections (0 = disabled)",
366           0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
367           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
368
369   g_object_class_install_property (gobject_class, PROP_LATENCY,
370       g_param_spec_uint ("latency", "Buffer latency in ms",
371           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
372           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
373
374   g_object_class_install_property (gobject_class, PROP_RTX_TIME,
375       g_param_spec_uint ("rtx-time", "Retransmission buffer in ms",
376           "Amount of ms to buffer for retransmission. 0 disables retransmission",
377           0, G_MAXUINT, DEFAULT_RTX_TIME_MS,
378           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
379
380   /**
381    * GstRTSPClientSink:do-rtsp-keep-alive:
382    *
383    * Enable RTSP keep alive support. Some old server don't like RTSP
384    * keep alive and then this property needs to be set to FALSE.
385    */
386   g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
387       g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
388           "Send RTSP keep alive packets, disable for old incompatible server.",
389           DEFAULT_DO_RTSP_KEEP_ALIVE,
390           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
391
392   /**
393    * GstRTSPClientSink:proxy:
394    *
395    * Set the proxy parameters. This has to be a string of the format
396    * [http://][user:passwd@]host[:port].
397    */
398   g_object_class_install_property (gobject_class, PROP_PROXY,
399       g_param_spec_string ("proxy", "Proxy",
400           "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
401           DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
402   /**
403    * GstRTSPClientSink:proxy-id:
404    *
405    * Sets the proxy URI user id for authentication. If the URI set via the
406    * "proxy" property contains a user-id already, that will take precedence.
407    *
408    */
409   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
410       g_param_spec_string ("proxy-id", "proxy-id",
411           "HTTP proxy URI user id for authentication", "",
412           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
413   /**
414    * GstRTSPClientSink:proxy-pw:
415    *
416    * Sets the proxy URI password for authentication. If the URI set via the
417    * "proxy" property contains a password already, that will take precedence.
418    *
419    */
420   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
421       g_param_spec_string ("proxy-pw", "proxy-pw",
422           "HTTP proxy URI user password for authentication", "",
423           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
424
425   /**
426    * GstRTSPClientSink:rtp-blocksize:
427    *
428    * RTP package size to suggest to server.
429    */
430   g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
431       g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
432           "RTP package size to suggest to server (0 = disabled)",
433           0, 65536, DEFAULT_RTP_BLOCKSIZE,
434           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
435
436   g_object_class_install_property (gobject_class,
437       PROP_USER_ID,
438       g_param_spec_string ("user-id", "user-id",
439           "RTSP location URI user id for authentication", DEFAULT_USER_ID,
440           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
441   g_object_class_install_property (gobject_class, PROP_USER_PW,
442       g_param_spec_string ("user-pw", "user-pw",
443           "RTSP location URI user password for authentication", DEFAULT_USER_PW,
444           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
445
446   /**
447    * GstRTSPClientSink:port-range:
448    *
449    * Configure the client port numbers that can be used to receive
450    * RTCP.
451    */
452   g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
453       g_param_spec_string ("port-range", "Port range",
454           "Client port range that can be used to receive RTCP data, "
455           "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
456           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
457
458   /**
459    * GstRTSPClientSink:udp-buffer-size:
460    *
461    * Size of the kernel UDP receive buffer in bytes.
462    */
463   g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
464       g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
465           "Size of the kernel UDP receive buffer in bytes, 0=default",
466           0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
467           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
468
469   g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
470       g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
471           "Reconnect to the server if RTSP connection is closed when doing UDP",
472           DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
473
474   g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
475       g_param_spec_string ("multicast-iface", "Multicast Interface",
476           "The network interface on which to join the multicast group",
477           DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
478
479   g_object_class_install_property (gobject_class, PROP_SDES,
480       g_param_spec_boxed ("sdes", "SDES",
481           "The SDES items of this session",
482           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
483
484   /**
485    * GstRTSPClientSink::tls-validation-flags:
486    *
487    * TLS certificate validation flags used to validate server
488    * certificate.
489    *
490    */
491   g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
492       g_param_spec_flags ("tls-validation-flags", "TLS validation flags",
493           "TLS certificate validation flags used to validate the server certificate",
494           G_TYPE_TLS_CERTIFICATE_FLAGS, DEFAULT_TLS_VALIDATION_FLAGS,
495           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
496
497   /**
498    * GstRTSPClientSink::tls-database:
499    *
500    * TLS database with anchor certificate authorities used to validate
501    * the server certificate.
502    *
503    */
504   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
505       g_param_spec_object ("tls-database", "TLS database",
506           "TLS database with anchor certificate authorities used to validate the server certificate",
507           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
508
509   /**
510    * GstRTSPClientSink::tls-interaction:
511    *
512    * A #GTlsInteraction object to be used when the connection or certificate
513    * database need to interact with the user. This will be used to prompt the
514    * user for passwords where necessary.
515    *
516    */
517   g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
518       g_param_spec_object ("tls-interaction", "TLS interaction",
519           "A GTlsInteraction object to prompt the user for password or certificate",
520           G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
521
522   /**
523    * GstRTSPClientSink::ntp-time-source:
524    *
525    * allows to select the time source that should be used
526    * for the NTP time in outgoing packets
527    *
528    */
529   g_object_class_install_property (gobject_class, PROP_NTP_TIME_SOURCE,
530       g_param_spec_enum ("ntp-time-source", "NTP Time Source",
531           "NTP time source for RTCP packets",
532           GST_TYPE_RTSP_CLIENT_SINK_NTP_TIME_SOURCE, DEFAULT_NTP_TIME_SOURCE,
533           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
534
535   /**
536    * GstRTSPClientSink::user-agent:
537    *
538    * The string to set in the User-Agent header.
539    *
540    */
541   g_object_class_install_property (gobject_class, PROP_USER_AGENT,
542       g_param_spec_string ("user-agent", "User Agent",
543           "The User-Agent string to send to the server",
544           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
545
546   /**
547    * GstRTSPClientSink::handle-request:
548    * @rtsp_client_sink: a #GstRTSPClientSink
549    * @request: a #GstRTSPMessage
550    * @response: a #GstRTSPMessage
551    *
552    * Handle a server request in @request and prepare @response.
553    *
554    * This signal is called from the streaming thread, you should therefore not
555    * do any state changes on @rtsp_client_sink because this might deadlock. If you want
556    * to modify the state as a result of this signal, post a
557    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
558    * in some other way.
559    *
560    */
561   gst_rtsp_client_sink_signals[SIGNAL_HANDLE_REQUEST] =
562       g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
563       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
564       G_TYPE_POINTER, G_TYPE_POINTER);
565
566   /**
567    * GstRTSPClientSink::new-manager:
568    * @rtsp_client_sink: a #GstRTSPClientSink
569    * @manager: a #GstElement
570    *
571    * Emitted after a new manager (like rtpbin) was created and the default
572    * properties were configured.
573    *
574    */
575   gst_rtsp_client_sink_signals[SIGNAL_NEW_MANAGER] =
576       g_signal_new_class_handler ("new-manager", G_TYPE_FROM_CLASS (klass),
577       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
578       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
579
580   /**
581    * GstRTSPClientSink::new-payloader:
582    * @rtsp_client_sink: a #GstRTSPClientSink
583    * @payloader: a #GstElement
584    *
585    * Emitted after a new RTP payloader was created and the default
586    * properties were configured.
587    *
588    */
589   gst_rtsp_client_sink_signals[SIGNAL_NEW_PAYLOADER] =
590       g_signal_new_class_handler ("new-payloader", G_TYPE_FROM_CLASS (klass),
591       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
592       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
593
594   /**
595    * GstRTSPClientSink::request-rtcp-key:
596    * @rtsp_client_sink: a #GstRTSPClientSink
597    * @num: the stream number
598    *
599    * Signal emitted to get the crypto parameters relevant to the RTCP
600    * stream. User should provide the key and the RTCP encryption ciphers
601    * and authentication, and return them wrapped in a GstCaps.
602    *
603    */
604   gst_rtsp_client_sink_signals[SIGNAL_REQUEST_RTCP_KEY] =
605       g_signal_new ("request-rtcp-key", G_TYPE_FROM_CLASS (klass),
606       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, GST_TYPE_CAPS, 1, G_TYPE_UINT);
607
608   gstelement_class->provide_clock = gst_rtsp_client_sink_provide_clock;
609   gstelement_class->change_state = gst_rtsp_client_sink_change_state;
610   gstelement_class->request_new_pad =
611       GST_DEBUG_FUNCPTR (gst_rtsp_client_sink_request_new_pad);
612   gstelement_class->release_pad =
613       GST_DEBUG_FUNCPTR (gst_rtsp_client_sink_release_pad);
614
615   gst_element_class_add_static_pad_template (gstelement_class, &rtptemplate);
616
617   gst_element_class_set_static_metadata (gstelement_class,
618       "RTSP RECORD client", "Sink/Network",
619       "Send data over the network via RTSP RECORD(RFC 2326)",
620       "Jan Schmidt <jan@centricular.com>");
621
622   gstbin_class->handle_message = gst_rtsp_client_sink_handle_message;
623 }
624
625 static void
626 gst_rtsp_client_sink_init (GstRTSPClientSink * sink)
627 {
628   sink->conninfo.location = g_strdup (DEFAULT_LOCATION);
629   sink->protocols = DEFAULT_PROTOCOLS;
630   sink->debug = DEFAULT_DEBUG;
631   sink->retry = DEFAULT_RETRY;
632   sink->udp_timeout = DEFAULT_TIMEOUT;
633   gst_rtsp_client_sink_set_tcp_timeout (sink, DEFAULT_TCP_TIMEOUT);
634   sink->latency = DEFAULT_LATENCY_MS;
635   sink->rtx_time = DEFAULT_RTX_TIME_MS;
636   sink->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
637   gst_rtsp_client_sink_set_proxy (sink, DEFAULT_PROXY);
638   sink->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
639   sink->user_id = g_strdup (DEFAULT_USER_ID);
640   sink->user_pw = g_strdup (DEFAULT_USER_PW);
641   sink->client_port_range.min = 0;
642   sink->client_port_range.max = 0;
643   sink->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
644   sink->udp_reconnect = DEFAULT_UDP_RECONNECT;
645   sink->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
646   sink->sdes = NULL;
647   sink->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
648   sink->tls_database = DEFAULT_TLS_DATABASE;
649   sink->tls_interaction = DEFAULT_TLS_INTERACTION;
650   sink->ntp_time_source = DEFAULT_NTP_TIME_SOURCE;
651   sink->user_agent = g_strdup (DEFAULT_USER_AGENT);
652
653   sink->profiles = DEFAULT_PROFILES;
654
655   /* protects the streaming thread in interleaved mode or the polling
656    * thread in UDP mode. */
657   g_rec_mutex_init (&sink->stream_rec_lock);
658
659   /* protects our state changes from multiple invocations */
660   g_rec_mutex_init (&sink->state_rec_lock);
661
662   g_mutex_init (&sink->send_lock);
663
664   g_mutex_init (&sink->preroll_lock);
665   g_cond_init (&sink->preroll_cond);
666
667   sink->state = GST_RTSP_STATE_INVALID;
668
669   sink->internal_bin = (GstBin *) gst_bin_new ("rtspbin");
670   gst_element_set_locked_state (GST_ELEMENT_CAST (sink->internal_bin), TRUE);
671   gst_bin_add (GST_BIN (sink), GST_ELEMENT_CAST (sink->internal_bin));
672
673   sink->next_dyn_pt = 96;
674
675   gst_sdp_message_init (&sink->cursdp);
676
677   GST_OBJECT_FLAG_SET (sink, GST_ELEMENT_FLAG_SINK);
678 }
679
680 static void
681 gst_rtsp_client_sink_finalize (GObject * object)
682 {
683   GstRTSPClientSink *rtsp_client_sink;
684
685   rtsp_client_sink = GST_RTSP_CLIENT_SINK (object);
686
687   gst_sdp_message_uninit (&rtsp_client_sink->cursdp);
688
689   g_free (rtsp_client_sink->conninfo.location);
690   gst_rtsp_url_free (rtsp_client_sink->conninfo.url);
691   g_free (rtsp_client_sink->conninfo.url_str);
692   g_free (rtsp_client_sink->user_id);
693   g_free (rtsp_client_sink->user_pw);
694   g_free (rtsp_client_sink->multi_iface);
695   g_free (rtsp_client_sink->user_agent);
696
697   if (rtsp_client_sink->uri_sdp) {
698     gst_sdp_message_free (rtsp_client_sink->uri_sdp);
699     rtsp_client_sink->uri_sdp = NULL;
700   }
701   if (rtsp_client_sink->provided_clock)
702     gst_object_unref (rtsp_client_sink->provided_clock);
703
704   if (rtsp_client_sink->sdes)
705     gst_structure_free (rtsp_client_sink->sdes);
706
707   if (rtsp_client_sink->tls_database)
708     g_object_unref (rtsp_client_sink->tls_database);
709
710   if (rtsp_client_sink->tls_interaction)
711     g_object_unref (rtsp_client_sink->tls_interaction);
712
713   /* free locks */
714   g_rec_mutex_clear (&rtsp_client_sink->stream_rec_lock);
715   g_rec_mutex_clear (&rtsp_client_sink->state_rec_lock);
716
717   g_mutex_clear (&rtsp_client_sink->send_lock);
718
719   g_mutex_clear (&rtsp_client_sink->preroll_lock);
720   g_cond_clear (&rtsp_client_sink->preroll_cond);
721
722   G_OBJECT_CLASS (parent_class)->finalize (object);
723 }
724
725 static gboolean
726 gst_rtp_payloader_filter_func (GstPluginFeature * feature, gpointer user_data)
727 {
728   GstElementFactory *factory = NULL;
729   const gchar *klass;
730
731   if (!GST_IS_ELEMENT_FACTORY (feature))
732     return FALSE;
733
734   factory = GST_ELEMENT_FACTORY (feature);
735
736   if (gst_plugin_feature_get_rank (feature) == GST_RANK_NONE)
737     return FALSE;
738
739   if (!gst_element_factory_list_is_type (factory,
740           GST_ELEMENT_FACTORY_TYPE_PAYLOADER))
741     return FALSE;
742
743   klass =
744       gst_element_factory_get_metadata (factory, GST_ELEMENT_METADATA_KLASS);
745   if (strstr (klass, "Codec") == NULL)
746     return FALSE;
747   if (strstr (klass, "RTP") == NULL)
748     return FALSE;
749
750   return TRUE;
751 }
752
753 static gint
754 compare_ranks (GstPluginFeature * f1, GstPluginFeature * f2)
755 {
756   gint diff;
757   const gchar *rname1, *rname2;
758   GstRank rank1, rank2;
759
760   rname1 = gst_plugin_feature_get_name (f1);
761   rname2 = gst_plugin_feature_get_name (f2);
762
763   rank1 = gst_plugin_feature_get_rank (f1);
764   rank2 = gst_plugin_feature_get_rank (f2);
765
766   /* HACK: Prefer rtpmp4apay over rtpmp4gpay */
767   if (g_str_equal (rname1, "rtpmp4apay"))
768     rank1 = GST_RANK_SECONDARY + 1;
769   if (g_str_equal (rname2, "rtpmp4apay"))
770     rank2 = GST_RANK_SECONDARY + 1;
771
772   diff = rank2 - rank1;
773   if (diff != 0)
774     return diff;
775
776   diff = strcmp (rname2, rname1);
777
778   return diff;
779 }
780
781 static GList *
782 gst_rtsp_client_sink_get_factories (void)
783 {
784   static GList *payloader_factories = NULL;
785
786   if (g_once_init_enter (&payloader_factories)) {
787     GList *all_factories;
788
789     all_factories =
790         gst_registry_feature_filter (gst_registry_get (),
791         gst_rtp_payloader_filter_func, FALSE, NULL);
792
793     all_factories = g_list_sort (all_factories, (GCompareFunc) compare_ranks);
794
795     g_once_init_leave (&payloader_factories, all_factories);
796   }
797
798   return payloader_factories;
799 }
800
801 static GstCaps *
802 gst_rtsp_client_sink_get_payloader_caps (void)
803 {
804   /* Cached caps result */
805   static GstCaps *ret;
806
807   if (g_once_init_enter (&ret)) {
808     GList *factories, *cur;
809     GstCaps *caps = gst_caps_new_empty ();
810
811     factories = gst_rtsp_client_sink_get_factories ();
812     for (cur = factories; cur != NULL; cur = g_list_next (cur)) {
813       GstElementFactory *factory = GST_ELEMENT_FACTORY (cur->data);
814       const GList *tmp;
815
816       for (tmp = gst_element_factory_get_static_pad_templates (factory);
817           tmp; tmp = g_list_next (tmp)) {
818         GstStaticPadTemplate *template = tmp->data;
819
820         if (template->direction == GST_PAD_SINK) {
821           GstCaps *static_caps = gst_static_pad_template_get_caps (template);
822
823           GST_LOG ("Found pad template %s on factory %s",
824               template->name_template, gst_plugin_feature_get_name (factory));
825
826           if (static_caps)
827             caps = gst_caps_merge (caps, static_caps);
828
829           /* Early out, any is absorbing */
830           if (gst_caps_is_any (caps))
831             goto out;
832         }
833       }
834     }
835   out:
836     g_once_init_leave (&ret, caps);
837   }
838
839   /* Return cached result */
840   return gst_caps_ref (ret);
841 }
842
843 static GstElement *
844 gst_rtsp_client_sink_make_payloader (GstCaps * caps)
845 {
846   GList *factories, *cur;
847
848   factories = gst_rtsp_client_sink_get_factories ();
849   for (cur = factories; cur != NULL; cur = g_list_next (cur)) {
850     GstElementFactory *factory = GST_ELEMENT_FACTORY (cur->data);
851     const GList *tmp;
852
853     for (tmp = gst_element_factory_get_static_pad_templates (factory);
854         tmp; tmp = g_list_next (tmp)) {
855       GstStaticPadTemplate *template = tmp->data;
856
857       if (template->direction == GST_PAD_SINK) {
858         GstCaps *static_caps = gst_static_pad_template_get_caps (template);
859         GstElement *payloader = NULL;
860
861         if (gst_caps_can_intersect (static_caps, caps)) {
862           GST_DEBUG ("caps %" GST_PTR_FORMAT " intersects with template %"
863               GST_PTR_FORMAT " for payloader %s", caps, static_caps,
864               gst_plugin_feature_get_name (factory));
865           payloader = gst_element_factory_create (factory, NULL);
866         }
867
868         gst_caps_unref (static_caps);
869
870         if (payloader)
871           return payloader;
872       }
873     }
874   }
875
876   return NULL;
877 }
878
879 static GstRTSPStream *
880 gst_rtsp_client_sink_create_stream (GstRTSPClientSink * sink,
881     GstRTSPStreamContext * context, GstElement * payloader, GstPad * pad)
882 {
883   GstRTSPStream *stream = NULL;
884   guint pt, aux_pt;
885
886   GST_OBJECT_LOCK (sink);
887
888   g_object_get (G_OBJECT (payloader), "pt", &pt, NULL);
889   if (pt >= 96 && pt <= sink->next_dyn_pt) {
890     /* Payloader has a dynamic PT, but one that's already used */
891     /* FIXME: Create a caps->ptmap instead? */
892     pt = sink->next_dyn_pt;
893
894     if (pt > 127)
895       goto no_free_pt;
896
897     GST_DEBUG_OBJECT (sink, "Assigning pt %u to stream %d", pt, context->index);
898
899     sink->next_dyn_pt++;
900   } else {
901     GST_DEBUG_OBJECT (sink, "Keeping existing pt %u for stream %d",
902         pt, context->index);
903   }
904
905   aux_pt = sink->next_dyn_pt;
906   if (aux_pt > 127)
907     goto no_free_pt;
908   sink->next_dyn_pt++;
909
910   GST_OBJECT_UNLOCK (sink);
911
912
913   g_object_set (G_OBJECT (payloader), "pt", pt, NULL);
914
915   stream = gst_rtsp_stream_new (context->index, payloader, pad);
916
917   gst_rtsp_stream_set_client_side (stream, TRUE);
918   gst_rtsp_stream_set_retransmission_time (stream,
919       (GstClockTime) (sink->rtx_time) * GST_MSECOND);
920   gst_rtsp_stream_set_protocols (stream, sink->protocols);
921   gst_rtsp_stream_set_profiles (stream, sink->profiles);
922   gst_rtsp_stream_set_retransmission_pt (stream, aux_pt);
923   gst_rtsp_stream_set_buffer_size (stream, sink->udp_buffer_size);
924   if (sink->rtp_blocksize > 0)
925     gst_rtsp_stream_set_mtu (stream, sink->rtp_blocksize);
926   gst_rtsp_stream_set_multicast_iface (stream, sink->multi_iface);
927
928 #if 0
929   if (priv->pool)
930     gst_rtsp_stream_set_address_pool (stream, priv->pool);
931 #endif
932
933   return stream;
934 no_free_pt:
935   GST_OBJECT_UNLOCK (sink);
936
937   GST_ELEMENT_ERROR (sink, RESOURCE, NO_SPACE_LEFT, (NULL),
938       ("Ran out of dynamic payload types."));
939
940   return NULL;
941 }
942
943 static GstPadProbeReturn
944 handle_payloader_block (GstPad * pad, GstPadProbeInfo * info,
945     GstRTSPStreamContext * context)
946 {
947   GstRTSPClientSink *sink = context->parent;
948
949   GST_INFO_OBJECT (sink, "Block on pad %" GST_PTR_FORMAT, pad);
950
951   g_mutex_lock (&sink->preroll_lock);
952   context->prerolled = TRUE;
953   g_cond_broadcast (&sink->preroll_cond);
954   g_mutex_unlock (&sink->preroll_lock);
955
956   GST_INFO_OBJECT (sink, "Announced preroll on pad %" GST_PTR_FORMAT, pad);
957
958   return GST_PAD_PROBE_OK;
959 }
960
961 static gboolean
962 gst_rtsp_client_sink_setup_payloader (GstRTSPClientSink * sink, GstPad * pad,
963     GstCaps * caps)
964 {
965   GstRTSPStreamContext *context;
966
967   GstElement *payloader;
968   GstPad *sinkpad, *srcpad, *ghostsink;
969
970   context = gst_pad_get_element_private (pad);
971
972   /* Find the payloader. FIXME: Allow user to provide payloader via pad property */
973   payloader = gst_rtsp_client_sink_make_payloader (caps);
974   if (payloader == NULL)
975     return FALSE;
976
977   GST_DEBUG_OBJECT (sink, "Configuring payloader %" GST_PTR_FORMAT
978       " for pad %" GST_PTR_FORMAT, payloader, pad);
979
980   sinkpad = gst_element_get_static_pad (payloader, "sink");
981   if (sinkpad == NULL)
982     goto no_sinkpad;
983
984   srcpad = gst_element_get_static_pad (payloader, "src");
985   if (srcpad == NULL)
986     goto no_srcpad;
987
988   gst_bin_add (GST_BIN (sink->internal_bin), payloader);
989   ghostsink = gst_ghost_pad_new (NULL, sinkpad);
990   gst_pad_set_active (ghostsink, TRUE);
991   gst_element_add_pad (GST_ELEMENT (sink->internal_bin), ghostsink);
992
993   g_signal_emit (sink, gst_rtsp_client_sink_signals[SIGNAL_NEW_PAYLOADER], 0,
994       payloader);
995
996   GST_RTSP_STATE_LOCK (sink);
997   context->payloader_block_id =
998       gst_pad_add_probe (srcpad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
999       (GstPadProbeCallback) handle_payloader_block, context, NULL);
1000   context->payloader = payloader;
1001
1002   payloader = gst_object_ref (payloader);
1003
1004   gst_ghost_pad_set_target (GST_GHOST_PAD (pad), ghostsink);
1005   gst_object_unref (GST_OBJECT (sinkpad));
1006   GST_RTSP_STATE_UNLOCK (sink);
1007
1008   gst_element_sync_state_with_parent (payloader);
1009
1010   gst_object_unref (payloader);
1011   gst_object_unref (GST_OBJECT (srcpad));
1012
1013   return TRUE;
1014
1015 no_sinkpad:
1016   GST_ERROR_OBJECT (sink,
1017       "Could not find sink pad on payloader %" GST_PTR_FORMAT, payloader);
1018   gst_object_unref (payloader);
1019   return FALSE;
1020
1021 no_srcpad:
1022   GST_ERROR_OBJECT (sink,
1023       "Could not find src pad on payloader %" GST_PTR_FORMAT, payloader);
1024   gst_object_unref (GST_OBJECT (sinkpad));
1025   gst_object_unref (payloader);
1026   return TRUE;
1027 }
1028
1029 static gboolean
1030 gst_rtsp_client_sink_sinkpad_event (GstPad * pad, GstObject * parent,
1031     GstEvent * event)
1032 {
1033   if (GST_EVENT_TYPE (event) == GST_EVENT_CAPS) {
1034     GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
1035     if (target == NULL) {
1036       GstCaps *caps;
1037
1038       /* No target yet - choose a payloader and configure it */
1039       gst_event_parse_caps (event, &caps);
1040
1041       GST_DEBUG_OBJECT (parent,
1042           "Have set caps event on pad %" GST_PTR_FORMAT
1043           " caps %" GST_PTR_FORMAT, pad, caps);
1044
1045       if (!gst_rtsp_client_sink_setup_payloader (GST_RTSP_CLIENT_SINK (parent),
1046               pad, caps)) {
1047         gst_event_unref (event);
1048         return FALSE;
1049       }
1050     } else {
1051       gst_object_unref (target);
1052     }
1053   }
1054
1055   return gst_pad_event_default (pad, parent, event);
1056 }
1057
1058 static gboolean
1059 gst_rtsp_client_sink_sinkpad_query (GstPad * pad, GstObject * parent,
1060     GstQuery * query)
1061 {
1062   if (GST_QUERY_TYPE (query) == GST_QUERY_CAPS) {
1063     GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
1064     if (target == NULL) {
1065       /* No target yet - return the union of all payloader caps */
1066       GstCaps *caps = gst_rtsp_client_sink_get_payloader_caps ();
1067
1068       GST_TRACE_OBJECT (parent, "Returning payloader caps %" GST_PTR_FORMAT,
1069           caps);
1070
1071       gst_query_set_caps_result (query, caps);
1072       gst_caps_unref (caps);
1073
1074       return TRUE;
1075     }
1076     gst_object_unref (target);
1077   }
1078
1079   return gst_pad_query_default (pad, parent, query);
1080 }
1081
1082 static GstPad *
1083 gst_rtsp_client_sink_request_new_pad (GstElement * element,
1084     GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
1085 {
1086   GstRTSPClientSink *sink = GST_RTSP_CLIENT_SINK (element);
1087   GstPad *pad;
1088   GstRTSPStreamContext *context;
1089   guint idx = (guint) - 1;
1090   gchar *tmpname;
1091
1092   g_mutex_lock (&sink->preroll_lock);
1093   if (sink->streams_collected) {
1094     GST_WARNING_OBJECT (element, "Can't add streams to a running session");
1095     g_mutex_unlock (&sink->preroll_lock);
1096     return NULL;
1097   }
1098   g_mutex_unlock (&sink->preroll_lock);
1099
1100   GST_OBJECT_LOCK (sink);
1101   if (name) {
1102     if (!sscanf (name, "sink_%u", &idx)) {
1103       GST_OBJECT_UNLOCK (sink);
1104       GST_ERROR_OBJECT (element, "Invalid sink pad name %s", name);
1105       return NULL;
1106     }
1107
1108     if (idx >= sink->next_pad_id)
1109       sink->next_pad_id = idx + 1;
1110   }
1111   if (idx == (guint) - 1) {
1112     idx = sink->next_pad_id;
1113     sink->next_pad_id++;
1114   }
1115   GST_OBJECT_UNLOCK (sink);
1116
1117   tmpname = g_strdup_printf ("sink_%u", idx);
1118   pad = gst_ghost_pad_new_no_target_from_template (tmpname, templ);
1119   g_free (tmpname);
1120
1121   GST_DEBUG_OBJECT (element, "Creating request pad %" GST_PTR_FORMAT, pad);
1122
1123   gst_pad_set_event_function (pad,
1124       GST_DEBUG_FUNCPTR (gst_rtsp_client_sink_sinkpad_event));
1125   gst_pad_set_query_function (pad,
1126       GST_DEBUG_FUNCPTR (gst_rtsp_client_sink_sinkpad_query));
1127
1128   context = g_new0 (GstRTSPStreamContext, 1);
1129   context->parent = sink;
1130   context->index = idx;
1131
1132   gst_pad_set_element_private (pad, context);
1133
1134   /* The rest of the context is configured on a caps set */
1135   gst_pad_set_active (pad, TRUE);
1136   gst_element_add_pad (element, pad);
1137
1138   (void) gst_rtsp_client_sink_get_factories ();
1139
1140   GST_RTSP_STATE_LOCK (sink);
1141   sink->contexts = g_list_prepend (sink->contexts, context);
1142   GST_RTSP_STATE_UNLOCK (sink);
1143
1144   return pad;
1145 }
1146
1147 static void
1148 gst_rtsp_client_sink_release_pad (GstElement * element, GstPad * pad)
1149 {
1150   GstRTSPClientSink *sink = GST_RTSP_CLIENT_SINK (element);
1151   GstRTSPStreamContext *context;
1152
1153   context = gst_pad_get_element_private (pad);
1154
1155   GST_RTSP_STATE_LOCK (sink);
1156   sink->contexts = g_list_remove (sink->contexts, context);
1157   GST_RTSP_STATE_UNLOCK (sink);
1158
1159   /* FIXME: Shut down and clean up streaming on this pad,
1160    * do teardown if needed */
1161   GST_LOG_OBJECT (sink,
1162       "Cleaning up payloader and stream for released pad %" GST_PTR_FORMAT,
1163       pad);
1164
1165   if (context->stream_transport) {
1166     gst_rtsp_stream_transport_set_active (context->stream_transport, FALSE);
1167     gst_object_unref (context->stream_transport);
1168     context->stream_transport = NULL;
1169   }
1170   if (context->stream) {
1171     if (context->joined) {
1172       gst_rtsp_stream_leave_bin (context->stream,
1173           GST_BIN (sink->internal_bin), sink->rtpbin);
1174       context->joined = FALSE;
1175     }
1176     gst_object_unref (context->stream);
1177     context->stream = NULL;
1178   }
1179   if (context->srtcpparams)
1180     gst_caps_unref (context->srtcpparams);
1181
1182   g_free (context->conninfo.location);
1183   context->conninfo.location = NULL;
1184
1185   g_free (context);
1186
1187   gst_element_remove_pad (element, pad);
1188 }
1189
1190 static GstClock *
1191 gst_rtsp_client_sink_provide_clock (GstElement * element)
1192 {
1193   GstRTSPClientSink *sink = GST_RTSP_CLIENT_SINK (element);
1194   GstClock *clock;
1195
1196   if ((clock = sink->provided_clock) != NULL)
1197     gst_object_ref (clock);
1198
1199   return clock;
1200 }
1201
1202 /* a proxy string of the format [user:passwd@]host[:port] */
1203 static gboolean
1204 gst_rtsp_client_sink_set_proxy (GstRTSPClientSink * rtsp, const gchar * proxy)
1205 {
1206   gchar *p, *at, *col;
1207
1208   g_free (rtsp->proxy_user);
1209   rtsp->proxy_user = NULL;
1210   g_free (rtsp->proxy_passwd);
1211   rtsp->proxy_passwd = NULL;
1212   g_free (rtsp->proxy_host);
1213   rtsp->proxy_host = NULL;
1214   rtsp->proxy_port = 0;
1215
1216   p = (gchar *) proxy;
1217
1218   if (p == NULL)
1219     return TRUE;
1220
1221   /* we allow http:// in front but ignore it */
1222   if (g_str_has_prefix (p, "http://"))
1223     p += 7;
1224
1225   at = strchr (p, '@');
1226   if (at) {
1227     /* look for user:passwd */
1228     col = strchr (proxy, ':');
1229     if (col == NULL || col > at)
1230       return FALSE;
1231
1232     rtsp->proxy_user = g_strndup (p, col - p);
1233     col++;
1234     rtsp->proxy_passwd = g_strndup (col, at - col);
1235
1236     /* move to host */
1237     p = at + 1;
1238   } else {
1239     if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
1240       rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
1241     if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
1242       rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
1243     if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
1244       GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
1245           GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
1246     }
1247   }
1248   col = strchr (p, ':');
1249
1250   if (col) {
1251     /* everything before the colon is the hostname */
1252     rtsp->proxy_host = g_strndup (p, col - p);
1253     p = col + 1;
1254     rtsp->proxy_port = strtoul (p, (char **) &p, 10);
1255   } else {
1256     rtsp->proxy_host = g_strdup (p);
1257     rtsp->proxy_port = 8080;
1258   }
1259   return TRUE;
1260 }
1261
1262 static void
1263 gst_rtsp_client_sink_set_tcp_timeout (GstRTSPClientSink * rtsp_client_sink,
1264     guint64 timeout)
1265 {
1266   rtsp_client_sink->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
1267   rtsp_client_sink->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
1268
1269   if (timeout != 0)
1270     rtsp_client_sink->ptcp_timeout = &rtsp_client_sink->tcp_timeout;
1271   else
1272     rtsp_client_sink->ptcp_timeout = NULL;
1273 }
1274
1275 static void
1276 gst_rtsp_client_sink_set_property (GObject * object, guint prop_id,
1277     const GValue * value, GParamSpec * pspec)
1278 {
1279   GstRTSPClientSink *rtsp_client_sink;
1280
1281   rtsp_client_sink = GST_RTSP_CLIENT_SINK (object);
1282
1283   switch (prop_id) {
1284     case PROP_LOCATION:
1285       gst_rtsp_client_sink_uri_set_uri (GST_URI_HANDLER (rtsp_client_sink),
1286           g_value_get_string (value), NULL);
1287       break;
1288     case PROP_PROTOCOLS:
1289       rtsp_client_sink->protocols = g_value_get_flags (value);
1290       break;
1291     case PROP_PROFILES:
1292       rtsp_client_sink->profiles = g_value_get_flags (value);
1293       break;
1294     case PROP_DEBUG:
1295       rtsp_client_sink->debug = g_value_get_boolean (value);
1296       break;
1297     case PROP_RETRY:
1298       rtsp_client_sink->retry = g_value_get_uint (value);
1299       break;
1300     case PROP_TIMEOUT:
1301       rtsp_client_sink->udp_timeout = g_value_get_uint64 (value);
1302       break;
1303     case PROP_TCP_TIMEOUT:
1304       gst_rtsp_client_sink_set_tcp_timeout (rtsp_client_sink,
1305           g_value_get_uint64 (value));
1306       break;
1307     case PROP_LATENCY:
1308       rtsp_client_sink->latency = g_value_get_uint (value);
1309       break;
1310     case PROP_RTX_TIME:
1311       rtsp_client_sink->rtx_time = g_value_get_uint (value);
1312       break;
1313     case PROP_DO_RTSP_KEEP_ALIVE:
1314       rtsp_client_sink->do_rtsp_keep_alive = g_value_get_boolean (value);
1315       break;
1316     case PROP_PROXY:
1317       gst_rtsp_client_sink_set_proxy (rtsp_client_sink,
1318           g_value_get_string (value));
1319       break;
1320     case PROP_PROXY_ID:
1321       if (rtsp_client_sink->prop_proxy_id)
1322         g_free (rtsp_client_sink->prop_proxy_id);
1323       rtsp_client_sink->prop_proxy_id = g_value_dup_string (value);
1324       break;
1325     case PROP_PROXY_PW:
1326       if (rtsp_client_sink->prop_proxy_pw)
1327         g_free (rtsp_client_sink->prop_proxy_pw);
1328       rtsp_client_sink->prop_proxy_pw = g_value_dup_string (value);
1329       break;
1330     case PROP_RTP_BLOCKSIZE:
1331       rtsp_client_sink->rtp_blocksize = g_value_get_uint (value);
1332       break;
1333     case PROP_USER_ID:
1334       if (rtsp_client_sink->user_id)
1335         g_free (rtsp_client_sink->user_id);
1336       rtsp_client_sink->user_id = g_value_dup_string (value);
1337       break;
1338     case PROP_USER_PW:
1339       if (rtsp_client_sink->user_pw)
1340         g_free (rtsp_client_sink->user_pw);
1341       rtsp_client_sink->user_pw = g_value_dup_string (value);
1342       break;
1343     case PROP_PORT_RANGE:
1344     {
1345       const gchar *str;
1346
1347       str = g_value_get_string (value);
1348       if (!str || !sscanf (str, "%u-%u",
1349               &rtsp_client_sink->client_port_range.min,
1350               &rtsp_client_sink->client_port_range.max)) {
1351         rtsp_client_sink->client_port_range.min = 0;
1352         rtsp_client_sink->client_port_range.max = 0;
1353       }
1354       break;
1355     }
1356     case PROP_UDP_BUFFER_SIZE:
1357       rtsp_client_sink->udp_buffer_size = g_value_get_int (value);
1358       break;
1359     case PROP_UDP_RECONNECT:
1360       rtsp_client_sink->udp_reconnect = g_value_get_boolean (value);
1361       break;
1362     case PROP_MULTICAST_IFACE:
1363       g_free (rtsp_client_sink->multi_iface);
1364
1365       if (g_value_get_string (value) == NULL)
1366         rtsp_client_sink->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
1367       else
1368         rtsp_client_sink->multi_iface = g_value_dup_string (value);
1369       break;
1370     case PROP_SDES:
1371       rtsp_client_sink->sdes = g_value_dup_boxed (value);
1372       break;
1373     case PROP_TLS_VALIDATION_FLAGS:
1374       rtsp_client_sink->tls_validation_flags = g_value_get_flags (value);
1375       break;
1376     case PROP_TLS_DATABASE:
1377       g_clear_object (&rtsp_client_sink->tls_database);
1378       rtsp_client_sink->tls_database = g_value_dup_object (value);
1379       break;
1380     case PROP_TLS_INTERACTION:
1381       g_clear_object (&rtsp_client_sink->tls_interaction);
1382       rtsp_client_sink->tls_interaction = g_value_dup_object (value);
1383       break;
1384     case PROP_NTP_TIME_SOURCE:
1385       rtsp_client_sink->ntp_time_source = g_value_get_enum (value);
1386       break;
1387     case PROP_USER_AGENT:
1388       g_free (rtsp_client_sink->user_agent);
1389       rtsp_client_sink->user_agent = g_value_dup_string (value);
1390       break;
1391     default:
1392       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1393       break;
1394   }
1395 }
1396
1397 static void
1398 gst_rtsp_client_sink_get_property (GObject * object, guint prop_id,
1399     GValue * value, GParamSpec * pspec)
1400 {
1401   GstRTSPClientSink *rtsp_client_sink;
1402
1403   rtsp_client_sink = GST_RTSP_CLIENT_SINK (object);
1404
1405   switch (prop_id) {
1406     case PROP_LOCATION:
1407       g_value_set_string (value, rtsp_client_sink->conninfo.location);
1408       break;
1409     case PROP_PROTOCOLS:
1410       g_value_set_flags (value, rtsp_client_sink->protocols);
1411       break;
1412     case PROP_PROFILES:
1413       g_value_set_flags (value, rtsp_client_sink->profiles);
1414       break;
1415     case PROP_DEBUG:
1416       g_value_set_boolean (value, rtsp_client_sink->debug);
1417       break;
1418     case PROP_RETRY:
1419       g_value_set_uint (value, rtsp_client_sink->retry);
1420       break;
1421     case PROP_TIMEOUT:
1422       g_value_set_uint64 (value, rtsp_client_sink->udp_timeout);
1423       break;
1424     case PROP_TCP_TIMEOUT:
1425     {
1426       guint64 timeout;
1427
1428       timeout = rtsp_client_sink->tcp_timeout.tv_sec * G_USEC_PER_SEC +
1429           rtsp_client_sink->tcp_timeout.tv_usec;
1430       g_value_set_uint64 (value, timeout);
1431       break;
1432     }
1433     case PROP_LATENCY:
1434       g_value_set_uint (value, rtsp_client_sink->latency);
1435       break;
1436     case PROP_RTX_TIME:
1437       g_value_set_uint (value, rtsp_client_sink->rtx_time);
1438       break;
1439     case PROP_DO_RTSP_KEEP_ALIVE:
1440       g_value_set_boolean (value, rtsp_client_sink->do_rtsp_keep_alive);
1441       break;
1442     case PROP_PROXY:
1443     {
1444       gchar *str;
1445
1446       if (rtsp_client_sink->proxy_host) {
1447         str =
1448             g_strdup_printf ("%s:%d", rtsp_client_sink->proxy_host,
1449             rtsp_client_sink->proxy_port);
1450       } else {
1451         str = NULL;
1452       }
1453       g_value_take_string (value, str);
1454       break;
1455     }
1456     case PROP_PROXY_ID:
1457       g_value_set_string (value, rtsp_client_sink->prop_proxy_id);
1458       break;
1459     case PROP_PROXY_PW:
1460       g_value_set_string (value, rtsp_client_sink->prop_proxy_pw);
1461       break;
1462     case PROP_RTP_BLOCKSIZE:
1463       g_value_set_uint (value, rtsp_client_sink->rtp_blocksize);
1464       break;
1465     case PROP_USER_ID:
1466       g_value_set_string (value, rtsp_client_sink->user_id);
1467       break;
1468     case PROP_USER_PW:
1469       g_value_set_string (value, rtsp_client_sink->user_pw);
1470       break;
1471     case PROP_PORT_RANGE:
1472     {
1473       gchar *str;
1474
1475       if (rtsp_client_sink->client_port_range.min != 0) {
1476         str = g_strdup_printf ("%u-%u", rtsp_client_sink->client_port_range.min,
1477             rtsp_client_sink->client_port_range.max);
1478       } else {
1479         str = NULL;
1480       }
1481       g_value_take_string (value, str);
1482       break;
1483     }
1484     case PROP_UDP_BUFFER_SIZE:
1485       g_value_set_int (value, rtsp_client_sink->udp_buffer_size);
1486       break;
1487     case PROP_UDP_RECONNECT:
1488       g_value_set_boolean (value, rtsp_client_sink->udp_reconnect);
1489       break;
1490     case PROP_MULTICAST_IFACE:
1491       g_value_set_string (value, rtsp_client_sink->multi_iface);
1492       break;
1493     case PROP_SDES:
1494       g_value_set_boxed (value, rtsp_client_sink->sdes);
1495       break;
1496     case PROP_TLS_VALIDATION_FLAGS:
1497       g_value_set_flags (value, rtsp_client_sink->tls_validation_flags);
1498       break;
1499     case PROP_TLS_DATABASE:
1500       g_value_set_object (value, rtsp_client_sink->tls_database);
1501       break;
1502     case PROP_TLS_INTERACTION:
1503       g_value_set_object (value, rtsp_client_sink->tls_interaction);
1504       break;
1505     case PROP_NTP_TIME_SOURCE:
1506       g_value_set_enum (value, rtsp_client_sink->ntp_time_source);
1507       break;
1508     case PROP_USER_AGENT:
1509       g_value_set_string (value, rtsp_client_sink->user_agent);
1510       break;
1511     default:
1512       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1513       break;
1514   }
1515 }
1516
1517 static const gchar *
1518 get_aggregate_control (GstRTSPClientSink * sink)
1519 {
1520   const gchar *base;
1521
1522   if (sink->control)
1523     base = sink->control;
1524   else if (sink->content_base)
1525     base = sink->content_base;
1526   else if (sink->conninfo.url_str)
1527     base = sink->conninfo.url_str;
1528   else
1529     base = "/";
1530
1531   return base;
1532 }
1533
1534 static void
1535 gst_rtsp_client_sink_cleanup (GstRTSPClientSink * sink)
1536 {
1537   GList *walk;
1538
1539   GST_DEBUG_OBJECT (sink, "cleanup");
1540
1541   gst_element_set_state (GST_ELEMENT (sink->internal_bin), GST_STATE_NULL);
1542
1543   /* Clean up any left over stream objects */
1544   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
1545     GstRTSPStreamContext *context = (GstRTSPStreamContext *) (walk->data);
1546     if (context->stream_transport) {
1547       gst_rtsp_stream_transport_set_active (context->stream_transport, FALSE);
1548       gst_object_unref (context->stream_transport);
1549       context->stream_transport = NULL;
1550     }
1551
1552     if (context->stream) {
1553       if (context->joined) {
1554         gst_rtsp_stream_leave_bin (context->stream,
1555             GST_BIN (sink->internal_bin), sink->rtpbin);
1556         context->joined = FALSE;
1557       }
1558       gst_object_unref (context->stream);
1559       context->stream = NULL;
1560     }
1561
1562     if (context->srtcpparams)
1563       gst_caps_unref (context->srtcpparams);
1564     g_free (context->conninfo.location);
1565     context->conninfo.location = NULL;
1566   }
1567
1568   if (sink->rtpbin) {
1569     gst_element_set_state (sink->rtpbin, GST_STATE_NULL);
1570     gst_bin_remove (GST_BIN_CAST (sink->internal_bin), sink->rtpbin);
1571     sink->rtpbin = NULL;
1572   }
1573
1574   g_free (sink->content_base);
1575   sink->content_base = NULL;
1576
1577   g_free (sink->control);
1578   sink->control = NULL;
1579
1580   if (sink->range)
1581     gst_rtsp_range_free (sink->range);
1582   sink->range = NULL;
1583
1584   /* don't clear the SDP when it was used in the url */
1585   if (sink->uri_sdp && !sink->from_sdp) {
1586     gst_sdp_message_free (sink->uri_sdp);
1587     sink->uri_sdp = NULL;
1588   }
1589
1590   if (sink->provided_clock) {
1591     gst_object_unref (sink->provided_clock);
1592     sink->provided_clock = NULL;
1593   }
1594
1595   g_free (sink->server_ip);
1596   sink->server_ip = NULL;
1597
1598   sink->next_pad_id = 0;
1599   sink->next_dyn_pt = 96;
1600 }
1601
1602 static GstRTSPResult
1603 gst_rtsp_client_sink_connection_send (GstRTSPClientSink * sink,
1604     GstRTSPConnection * conn, GstRTSPMessage * message, GTimeVal * timeout)
1605 {
1606   GstRTSPResult ret;
1607
1608   if (conn)
1609     ret = gst_rtsp_connection_send (conn, message, timeout);
1610   else
1611     ret = GST_RTSP_ERROR;
1612
1613   return ret;
1614 }
1615
1616 static GstRTSPResult
1617 gst_rtsp_client_sink_connection_receive (GstRTSPClientSink * sink,
1618     GstRTSPConnection * conn, GstRTSPMessage * message, GTimeVal * timeout)
1619 {
1620   GstRTSPResult ret;
1621
1622   if (conn)
1623     ret = gst_rtsp_connection_receive (conn, message, timeout);
1624   else
1625     ret = GST_RTSP_ERROR;
1626
1627   return ret;
1628 }
1629
1630 static GstRTSPResult
1631 gst_rtsp_conninfo_connect (GstRTSPClientSink * sink, GstRTSPConnInfo * info,
1632     gboolean async)
1633 {
1634   GstRTSPResult res;
1635
1636   if (info->connection == NULL) {
1637     if (info->url == NULL) {
1638       GST_DEBUG_OBJECT (sink, "parsing uri (%s)...", info->location);
1639       if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
1640         goto parse_error;
1641     }
1642
1643     /* create connection */
1644     GST_DEBUG_OBJECT (sink, "creating connection (%s)...", info->location);
1645     if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
1646       goto could_not_create;
1647
1648     if (info->url_str)
1649       g_free (info->url_str);
1650     info->url_str = gst_rtsp_url_get_request_uri (info->url);
1651
1652     GST_DEBUG_OBJECT (sink, "sanitized uri %s", info->url_str);
1653
1654     if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
1655       if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
1656               sink->tls_validation_flags))
1657         GST_WARNING_OBJECT (sink, "Unable to set TLS validation flags");
1658
1659       if (sink->tls_database)
1660         gst_rtsp_connection_set_tls_database (info->connection,
1661             sink->tls_database);
1662
1663       if (sink->tls_interaction)
1664         gst_rtsp_connection_set_tls_interaction (info->connection,
1665             sink->tls_interaction);
1666     }
1667
1668     if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
1669       gst_rtsp_connection_set_tunneled (info->connection, TRUE);
1670
1671     if (sink->proxy_host) {
1672       GST_DEBUG_OBJECT (sink, "setting proxy %s:%d", sink->proxy_host,
1673           sink->proxy_port);
1674       gst_rtsp_connection_set_proxy (info->connection, sink->proxy_host,
1675           sink->proxy_port);
1676     }
1677   }
1678
1679   if (!info->connected) {
1680     /* connect */
1681     if (async)
1682       GST_ELEMENT_PROGRESS (sink, CONTINUE, "connect",
1683           ("Connecting to %s", info->location));
1684     GST_DEBUG_OBJECT (sink, "connecting (%s)...", info->location);
1685     if ((res =
1686             gst_rtsp_connection_connect (info->connection,
1687                 sink->ptcp_timeout)) < 0)
1688       goto could_not_connect;
1689
1690     info->connected = TRUE;
1691   }
1692   return GST_RTSP_OK;
1693
1694   /* ERRORS */
1695 parse_error:
1696   {
1697     GST_ERROR_OBJECT (sink, "No valid RTSP URL was provided");
1698     return res;
1699   }
1700 could_not_create:
1701   {
1702     gchar *str = gst_rtsp_strresult (res);
1703     GST_ERROR_OBJECT (sink, "Could not create connection. (%s)", str);
1704     g_free (str);
1705     return res;
1706   }
1707 could_not_connect:
1708   {
1709     gchar *str = gst_rtsp_strresult (res);
1710     GST_ERROR_OBJECT (sink, "Could not connect to server. (%s)", str);
1711     g_free (str);
1712     return res;
1713   }
1714 }
1715
1716 static GstRTSPResult
1717 gst_rtsp_conninfo_close (GstRTSPClientSink * sink, GstRTSPConnInfo * info,
1718     gboolean free)
1719 {
1720   GST_RTSP_STATE_LOCK (sink);
1721   if (info->connected) {
1722     GST_DEBUG_OBJECT (sink, "closing connection...");
1723     gst_rtsp_connection_close (info->connection);
1724     info->connected = FALSE;
1725   }
1726   if (free && info->connection) {
1727     /* free connection */
1728     GST_DEBUG_OBJECT (sink, "freeing connection...");
1729     gst_rtsp_connection_free (info->connection);
1730     info->connection = NULL;
1731   }
1732   GST_RTSP_STATE_UNLOCK (sink);
1733   return GST_RTSP_OK;
1734 }
1735
1736 static GstRTSPResult
1737 gst_rtsp_conninfo_reconnect (GstRTSPClientSink * sink, GstRTSPConnInfo * info,
1738     gboolean async)
1739 {
1740   GstRTSPResult res;
1741
1742   GST_DEBUG_OBJECT (sink, "reconnecting connection...");
1743   gst_rtsp_conninfo_close (sink, info, FALSE);
1744   res = gst_rtsp_conninfo_connect (sink, info, async);
1745
1746   return res;
1747 }
1748
1749 static void
1750 gst_rtsp_client_sink_connection_flush (GstRTSPClientSink * sink, gboolean flush)
1751 {
1752   GList *walk;
1753
1754   GST_DEBUG_OBJECT (sink, "set flushing %d", flush);
1755   g_mutex_lock (&sink->preroll_lock);
1756   if (sink->conninfo.connection && sink->conninfo.flushing != flush) {
1757     GST_DEBUG_OBJECT (sink, "connection flush");
1758     gst_rtsp_connection_flush (sink->conninfo.connection, flush);
1759     sink->conninfo.flushing = flush;
1760   }
1761   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
1762     GstRTSPStreamContext *stream = (GstRTSPStreamContext *) walk->data;
1763     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
1764       GST_DEBUG_OBJECT (sink, "stream %p flush", stream);
1765       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
1766       stream->conninfo.flushing = flush;
1767     }
1768   }
1769   g_cond_broadcast (&sink->preroll_cond);
1770   g_mutex_unlock (&sink->preroll_lock);
1771 }
1772
1773 static GstRTSPResult
1774 gst_rtsp_client_sink_init_request (GstRTSPClientSink * sink,
1775     GstRTSPMessage * msg, GstRTSPMethod method, const gchar * uri)
1776 {
1777   GstRTSPResult res;
1778
1779   res = gst_rtsp_message_init_request (msg, method, uri);
1780   if (res < 0)
1781     return res;
1782
1783   /* set user-agent */
1784   if (sink->user_agent)
1785     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_USER_AGENT,
1786         sink->user_agent);
1787
1788   return res;
1789 }
1790
1791 /* FIXME, handle server request, reply with OK, for now */
1792 static GstRTSPResult
1793 gst_rtsp_client_sink_handle_request (GstRTSPClientSink * sink,
1794     GstRTSPConnection * conn, GstRTSPMessage * request)
1795 {
1796   GstRTSPMessage response = { 0 };
1797   GstRTSPResult res;
1798
1799   GST_DEBUG_OBJECT (sink, "got server request message");
1800
1801   if (sink->debug)
1802     gst_rtsp_message_dump (request);
1803
1804   /* default implementation, send OK */
1805   GST_DEBUG_OBJECT (sink, "prepare OK reply");
1806   res =
1807       gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
1808       request);
1809   if (res < 0)
1810     goto send_error;
1811
1812   /* let app parse and reply */
1813   g_signal_emit (sink, gst_rtsp_client_sink_signals[SIGNAL_HANDLE_REQUEST],
1814       0, request, &response);
1815
1816   if (sink->debug)
1817     gst_rtsp_message_dump (&response);
1818
1819   res = gst_rtsp_client_sink_connection_send (sink, conn, &response, NULL);
1820   if (res < 0)
1821     goto send_error;
1822
1823   gst_rtsp_message_unset (&response);
1824
1825   return GST_RTSP_OK;
1826
1827   /* ERRORS */
1828 send_error:
1829   {
1830     gst_rtsp_message_unset (&response);
1831     return res;
1832   }
1833 }
1834
1835 /* send server keep-alive */
1836 static GstRTSPResult
1837 gst_rtsp_client_sink_send_keep_alive (GstRTSPClientSink * sink)
1838 {
1839   GstRTSPMessage request = { 0 };
1840   GstRTSPResult res;
1841   GstRTSPMethod method;
1842   const gchar *control;
1843
1844   if (sink->do_rtsp_keep_alive == FALSE) {
1845     GST_DEBUG_OBJECT (sink, "do-rtsp-keep-alive is FALSE, not sending.");
1846     gst_rtsp_connection_reset_timeout (sink->conninfo.connection);
1847     return GST_RTSP_OK;
1848   }
1849
1850   GST_DEBUG_OBJECT (sink, "creating server keep-alive");
1851
1852   /* find a method to use for keep-alive */
1853   if (sink->methods & GST_RTSP_GET_PARAMETER)
1854     method = GST_RTSP_GET_PARAMETER;
1855   else
1856     method = GST_RTSP_OPTIONS;
1857
1858   control = get_aggregate_control (sink);
1859   if (control == NULL)
1860     goto no_control;
1861
1862   res = gst_rtsp_client_sink_init_request (sink, &request, method, control);
1863   if (res < 0)
1864     goto send_error;
1865
1866   if (sink->debug)
1867     gst_rtsp_message_dump (&request);
1868
1869   res =
1870       gst_rtsp_client_sink_connection_send (sink, sink->conninfo.connection,
1871       &request, NULL);
1872   if (res < 0)
1873     goto send_error;
1874
1875   gst_rtsp_connection_reset_timeout (sink->conninfo.connection);
1876   gst_rtsp_message_unset (&request);
1877
1878   return GST_RTSP_OK;
1879
1880   /* ERRORS */
1881 no_control:
1882   {
1883     GST_WARNING_OBJECT (sink, "no control url to send keepalive");
1884     return GST_RTSP_OK;
1885   }
1886 send_error:
1887   {
1888     gchar *str = gst_rtsp_strresult (res);
1889
1890     gst_rtsp_message_unset (&request);
1891     GST_ELEMENT_WARNING (sink, RESOURCE, WRITE, (NULL),
1892         ("Could not send keep-alive. (%s)", str));
1893     g_free (str);
1894     return res;
1895   }
1896 }
1897
1898 static GstFlowReturn
1899 gst_rtsp_client_sink_loop_rx (GstRTSPClientSink * sink)
1900 {
1901   GstRTSPResult res;
1902   GstRTSPMessage message = { 0 };
1903   gint retry = 0;
1904
1905   while (TRUE) {
1906     GTimeVal tv_timeout;
1907
1908     /* get the next timeout interval */
1909     gst_rtsp_connection_next_timeout (sink->conninfo.connection, &tv_timeout);
1910
1911     GST_DEBUG_OBJECT (sink, "doing receive with timeout %d seconds",
1912         (gint) tv_timeout.tv_sec);
1913
1914     gst_rtsp_message_unset (&message);
1915
1916     /* we should continue reading the TCP socket because the server might
1917      * send us requests. When the session timeout expires, we need to send a
1918      * keep-alive request to keep the session open. */
1919     res =
1920         gst_rtsp_client_sink_connection_receive (sink,
1921         sink->conninfo.connection, &message, &tv_timeout);
1922
1923     switch (res) {
1924       case GST_RTSP_OK:
1925         GST_DEBUG_OBJECT (sink, "we received a server message");
1926         break;
1927       case GST_RTSP_EINTR:
1928         /* we got interrupted, see what we have to do */
1929         goto interrupt;
1930       case GST_RTSP_ETIMEOUT:
1931         /* send keep-alive, ignore the result, a warning will be posted. */
1932         GST_DEBUG_OBJECT (sink, "timeout, sending keep-alive");
1933         if ((res =
1934                 gst_rtsp_client_sink_send_keep_alive (sink)) == GST_RTSP_EINTR)
1935           goto interrupt;
1936         continue;
1937       case GST_RTSP_EEOF:
1938         /* server closed the connection. not very fatal for UDP, reconnect and
1939          * see what happens. */
1940         GST_ELEMENT_WARNING (sink, RESOURCE, READ, (NULL),
1941             ("The server closed the connection."));
1942         if (sink->udp_reconnect) {
1943           if ((res =
1944                   gst_rtsp_conninfo_reconnect (sink, &sink->conninfo,
1945                       FALSE)) < 0)
1946             goto connect_error;
1947         } else {
1948           goto server_eof;
1949         }
1950         continue;
1951         break;
1952       case GST_RTSP_ENET:
1953         GST_DEBUG_OBJECT (sink, "An ethernet problem occured.");
1954       default:
1955         GST_ELEMENT_WARNING (sink, RESOURCE, READ, (NULL),
1956             ("Unhandled return value %d.", res));
1957         goto receive_error;
1958     }
1959
1960     switch (message.type) {
1961       case GST_RTSP_MESSAGE_REQUEST:
1962         /* server sends us a request message, handle it */
1963         res =
1964             gst_rtsp_client_sink_handle_request (sink,
1965             sink->conninfo.connection, &message);
1966         if (res == GST_RTSP_EEOF)
1967           goto server_eof;
1968         else if (res < 0)
1969           goto handle_request_failed;
1970         break;
1971       case GST_RTSP_MESSAGE_RESPONSE:
1972         /* we ignore response and data messages */
1973         GST_DEBUG_OBJECT (sink, "ignoring response message");
1974         if (sink->debug)
1975           gst_rtsp_message_dump (&message);
1976         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
1977           GST_DEBUG_OBJECT (sink, "but is Unauthorized response ...");
1978           if (gst_rtsp_client_sink_setup_auth (sink, &message) && !(retry++)) {
1979             GST_DEBUG_OBJECT (sink, "so retrying keep-alive");
1980             if ((res =
1981                     gst_rtsp_client_sink_send_keep_alive (sink)) ==
1982                 GST_RTSP_EINTR)
1983               goto interrupt;
1984           }
1985         } else {
1986           retry = 0;
1987         }
1988         break;
1989       case GST_RTSP_MESSAGE_DATA:
1990         /* we ignore response and data messages */
1991         GST_DEBUG_OBJECT (sink, "ignoring data message");
1992         break;
1993       default:
1994         GST_WARNING_OBJECT (sink, "ignoring unknown message type %d",
1995             message.type);
1996         break;
1997     }
1998   }
1999   g_assert_not_reached ();
2000
2001   /* we get here when the connection got interrupted */
2002 interrupt:
2003   {
2004     gst_rtsp_message_unset (&message);
2005     GST_DEBUG_OBJECT (sink, "got interrupted");
2006     return GST_FLOW_FLUSHING;
2007   }
2008 connect_error:
2009   {
2010     gchar *str = gst_rtsp_strresult (res);
2011     GstFlowReturn ret;
2012
2013     sink->conninfo.connected = FALSE;
2014     if (res != GST_RTSP_EINTR) {
2015       GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_READ_WRITE, (NULL),
2016           ("Could not connect to server. (%s)", str));
2017       g_free (str);
2018       ret = GST_FLOW_ERROR;
2019     } else {
2020       ret = GST_FLOW_FLUSHING;
2021     }
2022     return ret;
2023   }
2024 receive_error:
2025   {
2026     gchar *str = gst_rtsp_strresult (res);
2027
2028     GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
2029         ("Could not receive message. (%s)", str));
2030     g_free (str);
2031     return GST_FLOW_ERROR;
2032   }
2033 handle_request_failed:
2034   {
2035     gchar *str = gst_rtsp_strresult (res);
2036     GstFlowReturn ret;
2037
2038     gst_rtsp_message_unset (&message);
2039     if (res != GST_RTSP_EINTR) {
2040       GST_ELEMENT_ERROR (sink, RESOURCE, WRITE, (NULL),
2041           ("Could not handle server message. (%s)", str));
2042       g_free (str);
2043       ret = GST_FLOW_ERROR;
2044     } else {
2045       ret = GST_FLOW_FLUSHING;
2046     }
2047     return ret;
2048   }
2049 server_eof:
2050   {
2051     GST_DEBUG_OBJECT (sink, "we got an eof from the server");
2052     GST_ELEMENT_WARNING (sink, RESOURCE, READ, (NULL),
2053         ("The server closed the connection."));
2054     sink->conninfo.connected = FALSE;
2055     gst_rtsp_message_unset (&message);
2056     return GST_FLOW_EOS;
2057   }
2058 }
2059
2060 static GstRTSPResult
2061 gst_rtsp_client_sink_reconnect (GstRTSPClientSink * sink, gboolean async)
2062 {
2063   GstRTSPResult res = GST_RTSP_OK;
2064   gboolean restart = FALSE;
2065
2066   GST_DEBUG_OBJECT (sink, "doing reconnect");
2067
2068   GST_FIXME_OBJECT (sink, "Reconnection is not yet implemented");
2069
2070   /* no need to restart, we're done */
2071   if (!restart)
2072     goto done;
2073
2074   /* we can try only TCP now */
2075   sink->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
2076
2077   /* close and cleanup our state */
2078   if ((res = gst_rtsp_client_sink_close (sink, async, FALSE)) < 0)
2079     goto done;
2080
2081   /* see if we have TCP left to try. Also don't try TCP when we were configured
2082    * with an SDP. */
2083   if (!(sink->protocols & GST_RTSP_LOWER_TRANS_TCP) || sink->from_sdp)
2084     goto no_protocols;
2085
2086   /* We post a warning message now to inform the user
2087    * that nothing happened. It's most likely a firewall thing. */
2088   GST_ELEMENT_WARNING (sink, RESOURCE, READ, (NULL),
2089       ("Could not receive any UDP packets for %.4f seconds, maybe your "
2090           "firewall is blocking it. Retrying using a TCP connection.",
2091           gst_guint64_to_gdouble (sink->udp_timeout / 1000000.0)));
2092
2093   /* open new connection using tcp */
2094   if (gst_rtsp_client_sink_open (sink, async) < 0)
2095     goto open_failed;
2096
2097   /* start recording */
2098   if (gst_rtsp_client_sink_record (sink, async) < 0)
2099     goto play_failed;
2100
2101 done:
2102   return res;
2103
2104   /* ERRORS */
2105 no_protocols:
2106   {
2107     sink->cur_protocols = 0;
2108     /* no transport possible, post an error and stop */
2109     GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
2110         ("Could not receive any UDP packets for %.4f seconds, maybe your "
2111             "firewall is blocking it. No other protocols to try.",
2112             gst_guint64_to_gdouble (sink->udp_timeout / 1000000.0)));
2113     return GST_RTSP_ERROR;
2114   }
2115 open_failed:
2116   {
2117     GST_DEBUG_OBJECT (sink, "open failed");
2118     return GST_RTSP_OK;
2119   }
2120 play_failed:
2121   {
2122     GST_DEBUG_OBJECT (sink, "play failed");
2123     return GST_RTSP_OK;
2124   }
2125 }
2126
2127 static void
2128 gst_rtsp_client_sink_loop_start_cmd (GstRTSPClientSink * sink, gint cmd)
2129 {
2130   switch (cmd) {
2131     case CMD_OPEN:
2132       GST_ELEMENT_PROGRESS (sink, START, "open", ("Opening Stream"));
2133       break;
2134     case CMD_RECORD:
2135       GST_ELEMENT_PROGRESS (sink, START, "request", ("Sending RECORD request"));
2136       break;
2137     case CMD_PAUSE:
2138       GST_ELEMENT_PROGRESS (sink, START, "request", ("Sending PAUSE request"));
2139       break;
2140     case CMD_CLOSE:
2141       GST_ELEMENT_PROGRESS (sink, START, "close", ("Closing Stream"));
2142       break;
2143     default:
2144       break;
2145   }
2146 }
2147
2148 static void
2149 gst_rtsp_client_sink_loop_complete_cmd (GstRTSPClientSink * sink, gint cmd)
2150 {
2151   switch (cmd) {
2152     case CMD_OPEN:
2153       GST_ELEMENT_PROGRESS (sink, COMPLETE, "open", ("Opened Stream"));
2154       break;
2155     case CMD_RECORD:
2156       GST_ELEMENT_PROGRESS (sink, COMPLETE, "request", ("Sent RECORD request"));
2157       break;
2158     case CMD_PAUSE:
2159       GST_ELEMENT_PROGRESS (sink, COMPLETE, "request", ("Sent PAUSE request"));
2160       break;
2161     case CMD_CLOSE:
2162       GST_ELEMENT_PROGRESS (sink, COMPLETE, "close", ("Closed Stream"));
2163       break;
2164     default:
2165       break;
2166   }
2167 }
2168
2169 static void
2170 gst_rtsp_client_sink_loop_cancel_cmd (GstRTSPClientSink * sink, gint cmd)
2171 {
2172   switch (cmd) {
2173     case CMD_OPEN:
2174       GST_ELEMENT_PROGRESS (sink, CANCELED, "open", ("Open canceled"));
2175       break;
2176     case CMD_RECORD:
2177       GST_ELEMENT_PROGRESS (sink, CANCELED, "request", ("RECORD canceled"));
2178       break;
2179     case CMD_PAUSE:
2180       GST_ELEMENT_PROGRESS (sink, CANCELED, "request", ("PAUSE canceled"));
2181       break;
2182     case CMD_CLOSE:
2183       GST_ELEMENT_PROGRESS (sink, CANCELED, "close", ("Close canceled"));
2184       break;
2185     default:
2186       break;
2187   }
2188 }
2189
2190 static void
2191 gst_rtsp_client_sink_loop_error_cmd (GstRTSPClientSink * sink, gint cmd)
2192 {
2193   switch (cmd) {
2194     case CMD_OPEN:
2195       GST_ELEMENT_PROGRESS (sink, ERROR, "open", ("Open failed"));
2196       break;
2197     case CMD_RECORD:
2198       GST_ELEMENT_PROGRESS (sink, ERROR, "request", ("RECORD failed"));
2199       break;
2200     case CMD_PAUSE:
2201       GST_ELEMENT_PROGRESS (sink, ERROR, "request", ("PAUSE failed"));
2202       break;
2203     case CMD_CLOSE:
2204       GST_ELEMENT_PROGRESS (sink, ERROR, "close", ("Close failed"));
2205       break;
2206     default:
2207       break;
2208   }
2209 }
2210
2211 static void
2212 gst_rtsp_client_sink_loop_end_cmd (GstRTSPClientSink * sink, gint cmd,
2213     GstRTSPResult ret)
2214 {
2215   if (ret == GST_RTSP_OK)
2216     gst_rtsp_client_sink_loop_complete_cmd (sink, cmd);
2217   else if (ret == GST_RTSP_EINTR)
2218     gst_rtsp_client_sink_loop_cancel_cmd (sink, cmd);
2219   else
2220     gst_rtsp_client_sink_loop_error_cmd (sink, cmd);
2221 }
2222
2223 static gboolean
2224 gst_rtsp_client_sink_loop_send_cmd (GstRTSPClientSink * sink, gint cmd,
2225     gint mask)
2226 {
2227   gint old;
2228   gboolean flushed = FALSE;
2229
2230   /* start new request */
2231   gst_rtsp_client_sink_loop_start_cmd (sink, cmd);
2232
2233   GST_DEBUG_OBJECT (sink, "sending cmd %s", cmd_to_string (cmd));
2234
2235   GST_OBJECT_LOCK (sink);
2236   old = sink->pending_cmd;
2237   if (old == CMD_RECONNECT) {
2238     GST_DEBUG_OBJECT (sink, "ignore, we were reconnecting");
2239     cmd = CMD_RECONNECT;
2240   }
2241   if (old != CMD_WAIT) {
2242     sink->pending_cmd = CMD_WAIT;
2243     GST_OBJECT_UNLOCK (sink);
2244     /* cancel previous request */
2245     GST_DEBUG_OBJECT (sink, "cancel previous request %s", cmd_to_string (old));
2246     gst_rtsp_client_sink_loop_cancel_cmd (sink, old);
2247     GST_OBJECT_LOCK (sink);
2248   }
2249   sink->pending_cmd = cmd;
2250   /* interrupt if allowed */
2251   if (sink->busy_cmd & mask) {
2252     GST_DEBUG_OBJECT (sink, "connection flush busy %s",
2253         cmd_to_string (sink->busy_cmd));
2254     gst_rtsp_client_sink_connection_flush (sink, TRUE);
2255     flushed = TRUE;
2256   } else {
2257     GST_DEBUG_OBJECT (sink, "not interrupting busy cmd %s",
2258         cmd_to_string (sink->busy_cmd));
2259   }
2260   if (sink->task)
2261     gst_task_start (sink->task);
2262   GST_OBJECT_UNLOCK (sink);
2263
2264   return flushed;
2265 }
2266
2267 static gboolean
2268 gst_rtsp_client_sink_loop (GstRTSPClientSink * sink)
2269 {
2270   GstFlowReturn ret;
2271
2272   if (!sink->conninfo.connection || !sink->conninfo.connected)
2273     goto no_connection;
2274
2275   ret = gst_rtsp_client_sink_loop_rx (sink);
2276   if (ret != GST_FLOW_OK)
2277     goto pause;
2278
2279   return TRUE;
2280
2281   /* ERRORS */
2282 no_connection:
2283   {
2284     GST_WARNING_OBJECT (sink, "we are not connected");
2285     ret = GST_FLOW_FLUSHING;
2286     goto pause;
2287   }
2288 pause:
2289   {
2290     const gchar *reason = gst_flow_get_name (ret);
2291
2292     GST_DEBUG_OBJECT (sink, "pausing task, reason %s", reason);
2293     gst_rtsp_client_sink_loop_send_cmd (sink, CMD_WAIT, CMD_LOOP);
2294     return FALSE;
2295   }
2296 }
2297
2298 #ifndef GST_DISABLE_GST_DEBUG
2299 static const gchar *
2300 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
2301 {
2302   gint index = 0;
2303
2304   while (method != 0) {
2305     index++;
2306     method >>= 1;
2307   }
2308   switch (index) {
2309     case 0:
2310       return "None";
2311     case 1:
2312       return "Basic";
2313     case 2:
2314       return "Digest";
2315   }
2316
2317   return "Unknown";
2318 }
2319 #endif
2320
2321 /* Parse a WWW-Authenticate Response header and determine the
2322  * available authentication methods
2323  *
2324  * This code should also cope with the fact that each WWW-Authenticate
2325  * header can contain multiple challenge methods + tokens
2326  *
2327  * At the moment, for Basic auth, we just do a minimal check and don't
2328  * even parse out the realm */
2329 static void
2330 gst_rtsp_client_sink_parse_auth_hdr (GstRTSPMessage * response,
2331     GstRTSPAuthMethod * methods, GstRTSPConnection * conn, gboolean * stale)
2332 {
2333   GstRTSPAuthCredential **credentials, **credential;
2334
2335   g_return_if_fail (response != NULL);
2336   g_return_if_fail (methods != NULL);
2337   g_return_if_fail (stale != NULL);
2338
2339   credentials =
2340       gst_rtsp_message_parse_auth_credentials (response,
2341       GST_RTSP_HDR_WWW_AUTHENTICATE);
2342   if (!credentials)
2343     return;
2344
2345   credential = credentials;
2346   while (*credential) {
2347     if ((*credential)->scheme == GST_RTSP_AUTH_BASIC) {
2348       *methods |= GST_RTSP_AUTH_BASIC;
2349     } else if ((*credential)->scheme == GST_RTSP_AUTH_DIGEST) {
2350       GstRTSPAuthParam **param = (*credential)->params;
2351
2352       *methods |= GST_RTSP_AUTH_DIGEST;
2353
2354       gst_rtsp_connection_clear_auth_params (conn);
2355       *stale = FALSE;
2356
2357       while (*param) {
2358         if (strcmp ((*param)->name, "stale") == 0
2359             && g_ascii_strcasecmp ((*param)->value, "TRUE") == 0)
2360           *stale = TRUE;
2361         gst_rtsp_connection_set_auth_param (conn, (*param)->name,
2362             (*param)->value);
2363         param++;
2364       }
2365     }
2366
2367     credential++;
2368   }
2369
2370   gst_rtsp_auth_credentials_free (credentials);
2371 }
2372
2373 /**
2374  * gst_rtsp_client_sink_setup_auth:
2375  * @src: the rtsp source
2376  *
2377  * Configure a username and password and auth method on the
2378  * connection object based on a response we received from the
2379  * peer.
2380  *
2381  * Currently, this requires that a username and password were supplied
2382  * in the uri. In the future, they may be requested on demand by sending
2383  * a message up the bus.
2384  *
2385  * Returns: TRUE if authentication information could be set up correctly.
2386  */
2387 static gboolean
2388 gst_rtsp_client_sink_setup_auth (GstRTSPClientSink * sink,
2389     GstRTSPMessage * response)
2390 {
2391   gchar *user = NULL;
2392   gchar *pass = NULL;
2393   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
2394   GstRTSPAuthMethod method;
2395   GstRTSPResult auth_result;
2396   GstRTSPUrl *url;
2397   GstRTSPConnection *conn;
2398   gboolean stale = FALSE;
2399
2400   conn = sink->conninfo.connection;
2401
2402   /* Identify the available auth methods and see if any are supported */
2403   gst_rtsp_client_sink_parse_auth_hdr (response, &avail_methods, conn, &stale);
2404
2405   if (avail_methods == GST_RTSP_AUTH_NONE)
2406     goto no_auth_available;
2407
2408   /* For digest auth, if the response indicates that the session
2409    * data are stale, we just update them in the connection object and
2410    * return TRUE to retry the request */
2411   if (stale)
2412     sink->tried_url_auth = FALSE;
2413
2414   url = gst_rtsp_connection_get_url (conn);
2415
2416   /* Do we have username and password available? */
2417   if (url != NULL && !sink->tried_url_auth && url->user != NULL
2418       && url->passwd != NULL) {
2419     user = url->user;
2420     pass = url->passwd;
2421     sink->tried_url_auth = TRUE;
2422     GST_DEBUG_OBJECT (sink,
2423         "Attempting authentication using credentials from the URL");
2424   } else {
2425     user = sink->user_id;
2426     pass = sink->user_pw;
2427     GST_DEBUG_OBJECT (sink,
2428         "Attempting authentication using credentials from the properties");
2429   }
2430
2431   /* FIXME: If the url didn't contain username and password or we tried them
2432    * already, request a username and passwd from the application via some kind
2433    * of credentials request message */
2434
2435   /* If we don't have a username and passwd at this point, bail out. */
2436   if (user == NULL || pass == NULL)
2437     goto no_user_pass;
2438
2439   /* Try to configure for each available authentication method, strongest to
2440    * weakest */
2441   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
2442     /* Check if this method is available on the server */
2443     if ((method & avail_methods) == 0)
2444       continue;
2445
2446     /* Pass the credentials to the connection to try on the next request */
2447     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
2448     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
2449      * ignore it and end up retrying later */
2450     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
2451       GST_DEBUG_OBJECT (sink, "Attempting %s authentication",
2452           gst_rtsp_auth_method_to_string (method));
2453       break;
2454     }
2455   }
2456
2457   if (method == GST_RTSP_AUTH_NONE)
2458     goto no_auth_available;
2459
2460   return TRUE;
2461
2462 no_auth_available:
2463   {
2464     /* Output an error indicating that we couldn't connect because there were
2465      * no supported authentication protocols */
2466     GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_READ, (NULL),
2467         ("No supported authentication protocol was found"));
2468     return FALSE;
2469   }
2470 no_user_pass:
2471   {
2472     /* We don't fire an error message, we just return FALSE and let the
2473      * normal NOT_AUTHORIZED error be propagated */
2474     return FALSE;
2475   }
2476 }
2477
2478 static GstRTSPResult
2479 gst_rtsp_client_sink_try_send (GstRTSPClientSink * sink,
2480     GstRTSPConnection * conn, GstRTSPMessage * request,
2481     GstRTSPMessage * response, GstRTSPStatusCode * code)
2482 {
2483   GstRTSPResult res;
2484   GstRTSPStatusCode thecode;
2485   gchar *content_base = NULL;
2486   gint try = 0;
2487
2488 again:
2489   GST_DEBUG_OBJECT (sink, "sending message");
2490
2491   if (sink->debug)
2492     gst_rtsp_message_dump (request);
2493
2494   g_mutex_lock (&sink->send_lock);
2495
2496   res =
2497       gst_rtsp_client_sink_connection_send (sink, conn, request,
2498       sink->ptcp_timeout);
2499   if (res < 0) {
2500     g_mutex_unlock (&sink->send_lock);
2501     goto send_error;
2502   }
2503
2504   gst_rtsp_connection_reset_timeout (conn);
2505
2506   /* See if we should handle the response */
2507   if (response == NULL) {
2508     g_mutex_unlock (&sink->send_lock);
2509     return GST_RTSP_OK;
2510   }
2511 next:
2512   res =
2513       gst_rtsp_client_sink_connection_receive (sink, conn, response,
2514       sink->ptcp_timeout);
2515
2516   g_mutex_unlock (&sink->send_lock);
2517
2518   if (res < 0)
2519     goto receive_error;
2520
2521   if (sink->debug)
2522     gst_rtsp_message_dump (response);
2523
2524
2525   switch (response->type) {
2526     case GST_RTSP_MESSAGE_REQUEST:
2527       res = gst_rtsp_client_sink_handle_request (sink, conn, response);
2528       if (res == GST_RTSP_EEOF)
2529         goto server_eof;
2530       else if (res < 0)
2531         goto handle_request_failed;
2532       g_mutex_lock (&sink->send_lock);
2533       goto next;
2534     case GST_RTSP_MESSAGE_RESPONSE:
2535       /* ok, a response is good */
2536       GST_DEBUG_OBJECT (sink, "received response message");
2537       break;
2538     case GST_RTSP_MESSAGE_DATA:
2539       /* we ignore data messages */
2540       GST_DEBUG_OBJECT (sink, "ignoring data message");
2541       g_mutex_lock (&sink->send_lock);
2542       goto next;
2543     default:
2544       GST_WARNING_OBJECT (sink, "ignoring unknown message type %d",
2545           response->type);
2546       g_mutex_lock (&sink->send_lock);
2547       goto next;
2548   }
2549
2550   thecode = response->type_data.response.code;
2551
2552   GST_DEBUG_OBJECT (sink, "got response message %d", thecode);
2553
2554   /* if the caller wanted the result code, we store it. */
2555   if (code)
2556     *code = thecode;
2557
2558   /* If the request didn't succeed, bail out before doing any more */
2559   if (thecode != GST_RTSP_STS_OK)
2560     return GST_RTSP_OK;
2561
2562   /* store new content base if any */
2563   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
2564       &content_base, 0);
2565   if (content_base) {
2566     g_free (sink->content_base);
2567     sink->content_base = g_strdup (content_base);
2568   }
2569
2570   return GST_RTSP_OK;
2571
2572   /* ERRORS */
2573 send_error:
2574   {
2575     gchar *str = gst_rtsp_strresult (res);
2576
2577     if (res != GST_RTSP_EINTR) {
2578       GST_ELEMENT_ERROR (sink, RESOURCE, WRITE, (NULL),
2579           ("Could not send message. (%s)", str));
2580     } else {
2581       GST_WARNING_OBJECT (sink, "send interrupted");
2582     }
2583     g_free (str);
2584     return res;
2585   }
2586 receive_error:
2587   {
2588     switch (res) {
2589       case GST_RTSP_EEOF:
2590         GST_WARNING_OBJECT (sink, "server closed connection");
2591         if ((try == 0) && !sink->interleaved && sink->udp_reconnect) {
2592           try++;
2593           /* if reconnect succeeds, try again */
2594           if ((res =
2595                   gst_rtsp_conninfo_reconnect (sink, &sink->conninfo,
2596                       FALSE)) == 0)
2597             goto again;
2598         }
2599         /* only try once after reconnect, then fallthrough and error out */
2600       default:
2601       {
2602         gchar *str = gst_rtsp_strresult (res);
2603
2604         if (res != GST_RTSP_EINTR) {
2605           GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
2606               ("Could not receive message. (%s)", str));
2607         } else {
2608           GST_WARNING_OBJECT (sink, "receive interrupted");
2609         }
2610         g_free (str);
2611         break;
2612       }
2613     }
2614     return res;
2615   }
2616 handle_request_failed:
2617   {
2618     /* ERROR was posted */
2619     gst_rtsp_message_unset (response);
2620     return res;
2621   }
2622 server_eof:
2623   {
2624     GST_DEBUG_OBJECT (sink, "we got an eof from the server");
2625     GST_ELEMENT_WARNING (sink, RESOURCE, READ, (NULL),
2626         ("The server closed the connection."));
2627     gst_rtsp_message_unset (response);
2628     return res;
2629   }
2630 }
2631
2632 static void
2633 gst_rtsp_client_sink_set_state (GstRTSPClientSink * sink, GstState state)
2634 {
2635   GST_DEBUG_OBJECT (sink, "Setting internal state to %s",
2636       gst_element_state_get_name (state));
2637   gst_element_set_state (GST_ELEMENT (sink->internal_bin), state);
2638 }
2639
2640 /**
2641  * gst_rtsp_client_sink_send:
2642  * @src: the rtsp source
2643  * @conn: the connection to send on
2644  * @request: must point to a valid request
2645  * @response: must point to an empty #GstRTSPMessage
2646  * @code: an optional code result
2647  *
2648  * send @request and retrieve the response in @response. optionally @code can be
2649  * non-NULL in which case it will contain the status code of the response.
2650  *
2651  * If This function returns #GST_RTSP_OK, @response will contain a valid response
2652  * message that should be cleaned with gst_rtsp_message_unset() after usage.
2653  *
2654  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
2655  * @response message) if the response code was not 200 (OK).
2656  *
2657  * If the attempt results in an authentication failure, then this will attempt
2658  * to retrieve authentication credentials via gst_rtsp_client_sink_setup_auth and retry
2659  * the request.
2660  *
2661  * Returns: #GST_RTSP_OK if the processing was successful.
2662  */
2663 static GstRTSPResult
2664 gst_rtsp_client_sink_send (GstRTSPClientSink * sink, GstRTSPConnection * conn,
2665     GstRTSPMessage * request, GstRTSPMessage * response,
2666     GstRTSPStatusCode * code)
2667 {
2668   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
2669   GstRTSPResult res = GST_RTSP_ERROR;
2670   gint count;
2671   gboolean retry;
2672   GstRTSPMethod method = GST_RTSP_INVALID;
2673
2674   count = 0;
2675   do {
2676     retry = FALSE;
2677
2678     /* make sure we don't loop forever */
2679     if (count++ > 8)
2680       break;
2681
2682     /* save method so we can disable it when the server complains */
2683     method = request->type_data.request.method;
2684
2685     if ((res =
2686             gst_rtsp_client_sink_try_send (sink, conn, request, response,
2687                 &int_code)) < 0)
2688       goto error;
2689
2690     switch (int_code) {
2691       case GST_RTSP_STS_UNAUTHORIZED:
2692         if (gst_rtsp_client_sink_setup_auth (sink, response)) {
2693           /* Try the request/response again after configuring the auth info
2694            * and loop again */
2695           retry = TRUE;
2696         }
2697         break;
2698       default:
2699         break;
2700     }
2701   } while (retry == TRUE);
2702
2703   /* If the user requested the code, let them handle errors, otherwise
2704    * post an error below */
2705   if (code != NULL)
2706     *code = int_code;
2707   else if (int_code != GST_RTSP_STS_OK)
2708     goto error_response;
2709
2710   return res;
2711
2712   /* ERRORS */
2713 error:
2714   {
2715     GST_DEBUG_OBJECT (sink, "got error %d", res);
2716     return res;
2717   }
2718 error_response:
2719   {
2720     res = GST_RTSP_ERROR;
2721
2722     switch (response->type_data.response.code) {
2723       case GST_RTSP_STS_NOT_FOUND:
2724         GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND, (NULL), ("%s",
2725                 response->type_data.response.reason));
2726         break;
2727       case GST_RTSP_STS_UNAUTHORIZED:
2728         GST_ELEMENT_ERROR (sink, RESOURCE, NOT_AUTHORIZED, (NULL), ("%s",
2729                 response->type_data.response.reason));
2730         break;
2731       case GST_RTSP_STS_MOVED_PERMANENTLY:
2732       case GST_RTSP_STS_MOVE_TEMPORARILY:
2733       {
2734         gchar *new_location;
2735         GstRTSPLowerTrans transports;
2736
2737         GST_DEBUG_OBJECT (sink, "got redirection");
2738         /* if we don't have a Location Header, we must error */
2739         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
2740                 &new_location, 0) < 0)
2741           break;
2742
2743         /* When we receive a redirect result, we go back to the INIT state after
2744          * parsing the new URI. The caller should do the needed steps to issue
2745          * a new setup when it detects this state change. */
2746         GST_DEBUG_OBJECT (sink, "redirection to %s", new_location);
2747
2748         /* save current transports */
2749         if (sink->conninfo.url)
2750           transports = sink->conninfo.url->transports;
2751         else
2752           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
2753
2754         gst_rtsp_client_sink_uri_set_uri (GST_URI_HANDLER (sink), new_location,
2755             NULL);
2756
2757         /* set old transports */
2758         if (sink->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
2759           sink->conninfo.url->transports = transports;
2760
2761         sink->need_redirect = TRUE;
2762         sink->state = GST_RTSP_STATE_INIT;
2763         res = GST_RTSP_OK;
2764         break;
2765       }
2766       case GST_RTSP_STS_NOT_ACCEPTABLE:
2767       case GST_RTSP_STS_NOT_IMPLEMENTED:
2768       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
2769         GST_WARNING_OBJECT (sink, "got NOT IMPLEMENTED, disable method %s",
2770             gst_rtsp_method_as_text (method));
2771         sink->methods &= ~method;
2772         res = GST_RTSP_OK;
2773         break;
2774       default:
2775         GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
2776             ("Got error response: %d (%s).", response->type_data.response.code,
2777                 response->type_data.response.reason));
2778         break;
2779     }
2780     /* if we return ERROR we should unset the response ourselves */
2781     if (res == GST_RTSP_ERROR)
2782       gst_rtsp_message_unset (response);
2783
2784     return res;
2785   }
2786 }
2787
2788 /* parse the response and collect all the supported methods. We need this
2789  * information so that we don't try to send an unsupported request to the
2790  * server.
2791  */
2792 static gboolean
2793 gst_rtsp_client_sink_parse_methods (GstRTSPClientSink * sink,
2794     GstRTSPMessage * response)
2795 {
2796   GstRTSPHeaderField field;
2797   gchar *respoptions;
2798   gint indx = 0;
2799
2800   /* reset supported methods */
2801   sink->methods = 0;
2802
2803   /* Try Allow Header first */
2804   field = GST_RTSP_HDR_ALLOW;
2805   while (TRUE) {
2806     respoptions = NULL;
2807     gst_rtsp_message_get_header (response, field, &respoptions, indx);
2808     if (indx == 0 && !respoptions) {
2809       /* if no Allow header was found then try the Public header... */
2810       field = GST_RTSP_HDR_PUBLIC;
2811       gst_rtsp_message_get_header (response, field, &respoptions, indx);
2812     }
2813     if (!respoptions)
2814       break;
2815
2816     sink->methods |= gst_rtsp_options_from_text (respoptions);
2817
2818     indx++;
2819   }
2820
2821   if (sink->methods == 0) {
2822     /* neither Allow nor Public are required, assume the server supports
2823      * at least SETUP. */
2824     GST_DEBUG_OBJECT (sink, "could not get OPTIONS");
2825     sink->methods = GST_RTSP_SETUP;
2826   }
2827
2828   /* Even if the server replied, and didn't say it supports
2829    * RECORD|ANNOUNCE, try anyway by assuming it does */
2830   sink->methods |= GST_RTSP_ANNOUNCE | GST_RTSP_RECORD;
2831
2832   if (!(sink->methods & GST_RTSP_SETUP))
2833     goto no_setup;
2834
2835   return TRUE;
2836
2837   /* ERRORS */
2838 no_setup:
2839   {
2840     GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_READ, (NULL),
2841         ("Server does not support SETUP."));
2842     return FALSE;
2843   }
2844 }
2845
2846 static GstRTSPResult
2847 gst_rtsp_client_sink_connect_to_server (GstRTSPClientSink * sink,
2848     gboolean async)
2849 {
2850   GstRTSPResult res;
2851   GstRTSPMessage request = { 0 };
2852   GstRTSPMessage response = { 0 };
2853   GSocket *conn_socket;
2854   GSocketAddress *sa;
2855   GInetAddress *ia;
2856
2857   sink->need_redirect = FALSE;
2858
2859   /* can't continue without a valid url */
2860   if (G_UNLIKELY (sink->conninfo.url == NULL)) {
2861     res = GST_RTSP_EINVAL;
2862     goto no_url;
2863   }
2864   sink->tried_url_auth = FALSE;
2865
2866   if ((res = gst_rtsp_conninfo_connect (sink, &sink->conninfo, async)) < 0)
2867     goto connect_failed;
2868
2869   conn_socket = gst_rtsp_connection_get_read_socket (sink->conninfo.connection);
2870   sa = g_socket_get_remote_address (conn_socket, NULL);
2871   ia = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (sa));
2872
2873   sink->server_ip = g_inet_address_to_string (ia);
2874
2875   g_object_unref (sa);
2876
2877   /* create OPTIONS */
2878   GST_DEBUG_OBJECT (sink, "create options...");
2879   res =
2880       gst_rtsp_client_sink_init_request (sink, &request, GST_RTSP_OPTIONS,
2881       sink->conninfo.url_str);
2882   if (res < 0)
2883     goto create_request_failed;
2884
2885   /* send OPTIONS */
2886   GST_DEBUG_OBJECT (sink, "send options...");
2887
2888   if (async)
2889     GST_ELEMENT_PROGRESS (sink, CONTINUE, "open",
2890         ("Retrieving server options"));
2891
2892   if ((res =
2893           gst_rtsp_client_sink_send (sink, sink->conninfo.connection, &request,
2894               &response, NULL)) < 0)
2895     goto send_error;
2896
2897   /* parse OPTIONS */
2898   if (!gst_rtsp_client_sink_parse_methods (sink, &response))
2899     goto methods_error;
2900
2901   /* FIXME: Do we need to handle REDIRECT responses for OPTIONS? */
2902
2903   /* clean up any messages */
2904   gst_rtsp_message_unset (&request);
2905   gst_rtsp_message_unset (&response);
2906
2907   return res;
2908
2909   /* ERRORS */
2910 no_url:
2911   {
2912     GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND, (NULL),
2913         ("No valid RTSP URL was provided"));
2914     goto cleanup_error;
2915   }
2916 connect_failed:
2917   {
2918     gchar *str = gst_rtsp_strresult (res);
2919
2920     if (res != GST_RTSP_EINTR) {
2921       GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_READ_WRITE, (NULL),
2922           ("Failed to connect. (%s)", str));
2923     } else {
2924       GST_WARNING_OBJECT (sink, "connect interrupted");
2925     }
2926     g_free (str);
2927     goto cleanup_error;
2928   }
2929 create_request_failed:
2930   {
2931     gchar *str = gst_rtsp_strresult (res);
2932
2933     GST_ELEMENT_ERROR (sink, LIBRARY, INIT, (NULL),
2934         ("Could not create request. (%s)", str));
2935     g_free (str);
2936     goto cleanup_error;
2937   }
2938 send_error:
2939   {
2940     /* Don't post a message - the rtsp_send method will have
2941      * taken care of it because we passed NULL for the response code */
2942     goto cleanup_error;
2943   }
2944 methods_error:
2945   {
2946     /* error was posted */
2947     res = GST_RTSP_ERROR;
2948     goto cleanup_error;
2949   }
2950 cleanup_error:
2951   {
2952     if (sink->conninfo.connection) {
2953       GST_DEBUG_OBJECT (sink, "free connection");
2954       gst_rtsp_conninfo_close (sink, &sink->conninfo, TRUE);
2955     }
2956     gst_rtsp_message_unset (&request);
2957     gst_rtsp_message_unset (&response);
2958     return res;
2959   }
2960 }
2961
2962 static GstRTSPResult
2963 gst_rtsp_client_sink_open (GstRTSPClientSink * sink, gboolean async)
2964 {
2965   GstRTSPResult ret;
2966
2967   sink->methods =
2968       GST_RTSP_SETUP | GST_RTSP_RECORD | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
2969
2970   if ((ret = gst_rtsp_client_sink_connect_to_server (sink, async)) < 0)
2971     goto open_failed;
2972
2973   if (async)
2974     gst_rtsp_client_sink_loop_end_cmd (sink, CMD_OPEN, ret);
2975
2976   /* Collect all our input streams and create
2977    * stream objects before actually returning */
2978   gst_rtsp_client_sink_collect_streams (sink);
2979
2980   return ret;
2981
2982   /* ERRORS */
2983 open_failed:
2984   {
2985     GST_WARNING_OBJECT (sink, "Failed to connect to server");
2986     sink->open_error = TRUE;
2987     if (async)
2988       gst_rtsp_client_sink_loop_end_cmd (sink, CMD_OPEN, ret);
2989     return ret;
2990   }
2991 }
2992
2993 static GstRTSPResult
2994 gst_rtsp_client_sink_close (GstRTSPClientSink * sink, gboolean async,
2995     gboolean only_close)
2996 {
2997   GstRTSPMessage request = { 0 };
2998   GstRTSPMessage response = { 0 };
2999   GstRTSPResult res = GST_RTSP_OK;
3000   GList *walk;
3001   const gchar *control;
3002
3003   GST_DEBUG_OBJECT (sink, "TEARDOWN...");
3004
3005   gst_rtsp_client_sink_set_state (sink, GST_STATE_NULL);
3006
3007   if (sink->state < GST_RTSP_STATE_READY) {
3008     GST_DEBUG_OBJECT (sink, "not ready, doing cleanup");
3009     goto close;
3010   }
3011
3012   if (only_close)
3013     goto close;
3014
3015   /* construct a control url */
3016   control = get_aggregate_control (sink);
3017
3018   if (!(sink->methods & (GST_RTSP_RECORD | GST_RTSP_TEARDOWN)))
3019     goto not_supported;
3020
3021   /* stop streaming */
3022   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3023     GstRTSPStreamContext *context = (GstRTSPStreamContext *) walk->data;
3024
3025     if (context->stream_transport)
3026       gst_rtsp_stream_transport_set_active (context->stream_transport, FALSE);
3027
3028     if (context->joined) {
3029       gst_rtsp_stream_leave_bin (context->stream, GST_BIN (sink->internal_bin),
3030           sink->rtpbin);
3031       context->joined = FALSE;
3032     }
3033   }
3034
3035   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3036     GstRTSPStreamContext *context = (GstRTSPStreamContext *) walk->data;
3037     const gchar *setup_url;
3038     GstRTSPConnInfo *info;
3039
3040     GST_DEBUG_OBJECT (sink, "Looking at stream %p for teardown",
3041         context->stream);
3042
3043     /* try aggregate control first but do non-aggregate control otherwise */
3044     if (control)
3045       setup_url = control;
3046     else if ((setup_url = context->conninfo.location) == NULL) {
3047       GST_DEBUG_OBJECT (sink, "Skipping TEARDOWN stream %p - no setup URL",
3048           context->stream);
3049       continue;
3050     }
3051
3052     if (sink->conninfo.connection) {
3053       info = &sink->conninfo;
3054     } else if (context->conninfo.connection) {
3055       info = &context->conninfo;
3056     } else {
3057       continue;
3058     }
3059     if (!info->connected)
3060       goto next;
3061
3062     /* do TEARDOWN */
3063     GST_DEBUG_OBJECT (sink, "Sending teardown for stream %p at URL %s",
3064         context->stream, setup_url);
3065     res =
3066         gst_rtsp_client_sink_init_request (sink, &request, GST_RTSP_TEARDOWN,
3067         setup_url);
3068     if (res < 0)
3069       goto create_request_failed;
3070
3071     if (async)
3072       GST_ELEMENT_PROGRESS (sink, CONTINUE, "close", ("Closing stream"));
3073
3074     if ((res =
3075             gst_rtsp_client_sink_send (sink, info->connection, &request,
3076                 &response, NULL)) < 0)
3077       goto send_error;
3078
3079     /* FIXME, parse result? */
3080     gst_rtsp_message_unset (&request);
3081     gst_rtsp_message_unset (&response);
3082
3083   next:
3084     /* early exit when we did aggregate control */
3085     if (control)
3086       break;
3087   }
3088
3089 close:
3090   /* close connections */
3091   GST_DEBUG_OBJECT (sink, "closing connection...");
3092   gst_rtsp_conninfo_close (sink, &sink->conninfo, TRUE);
3093   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3094     GstRTSPStreamContext *stream = (GstRTSPStreamContext *) walk->data;
3095     gst_rtsp_conninfo_close (sink, &stream->conninfo, TRUE);
3096   }
3097
3098   /* cleanup */
3099   gst_rtsp_client_sink_cleanup (sink);
3100
3101   sink->state = GST_RTSP_STATE_INVALID;
3102
3103   if (async)
3104     gst_rtsp_client_sink_loop_end_cmd (sink, CMD_CLOSE, res);
3105
3106   return res;
3107
3108   /* ERRORS */
3109 create_request_failed:
3110   {
3111     gchar *str = gst_rtsp_strresult (res);
3112
3113     GST_ELEMENT_ERROR (sink, LIBRARY, INIT, (NULL),
3114         ("Could not create request. (%s)", str));
3115     g_free (str);
3116     goto close;
3117   }
3118 send_error:
3119   {
3120     gchar *str = gst_rtsp_strresult (res);
3121
3122     gst_rtsp_message_unset (&request);
3123     if (res != GST_RTSP_EINTR) {
3124       GST_ELEMENT_ERROR (sink, RESOURCE, WRITE, (NULL),
3125           ("Could not send message. (%s)", str));
3126     } else {
3127       GST_WARNING_OBJECT (sink, "TEARDOWN interrupted");
3128     }
3129     g_free (str);
3130     goto close;
3131   }
3132 not_supported:
3133   {
3134     GST_DEBUG_OBJECT (sink,
3135         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
3136     goto close;
3137   }
3138 }
3139
3140 static gboolean
3141 gst_rtsp_client_sink_configure_manager (GstRTSPClientSink * sink)
3142 {
3143   GstElement *rtpbin;
3144   GstStateChangeReturn ret;
3145
3146   rtpbin = sink->rtpbin;
3147
3148   if (rtpbin == NULL) {
3149     GObjectClass *klass;
3150
3151     rtpbin = gst_element_factory_make ("rtpbin", NULL);
3152     if (rtpbin == NULL)
3153       goto no_rtpbin;
3154
3155     gst_bin_add (GST_BIN_CAST (sink->internal_bin), rtpbin);
3156
3157     sink->rtpbin = rtpbin;
3158
3159     /* Any more settings we should configure on rtpbin here? */
3160     g_object_set (sink->rtpbin, "latency", sink->latency, NULL);
3161
3162     klass = G_OBJECT_GET_CLASS (G_OBJECT (rtpbin));
3163
3164     if (g_object_class_find_property (klass, "ntp-time-source")) {
3165       g_object_set (sink->rtpbin, "ntp-time-source", sink->ntp_time_source,
3166           NULL);
3167     }
3168
3169     if (sink->sdes && g_object_class_find_property (klass, "sdes")) {
3170       g_object_set (sink->rtpbin, "sdes", sink->sdes, NULL);
3171     }
3172
3173     g_signal_emit (sink, gst_rtsp_client_sink_signals[SIGNAL_NEW_MANAGER], 0,
3174         sink->rtpbin);
3175   }
3176
3177   ret = gst_element_set_state (rtpbin, GST_STATE_PAUSED);
3178   if (ret == GST_STATE_CHANGE_FAILURE)
3179     goto start_manager_failure;
3180
3181   return TRUE;
3182
3183 no_rtpbin:
3184   {
3185     GST_WARNING ("no rtpbin element");
3186     g_warning ("failed to create element 'rtpbin', check your installation");
3187     return FALSE;
3188   }
3189 start_manager_failure:
3190   {
3191     GST_DEBUG_OBJECT (sink, "could not start session manager");
3192     gst_bin_remove (GST_BIN_CAST (sink->internal_bin), rtpbin);
3193     return FALSE;
3194   }
3195 }
3196
3197 static GstElement *
3198 request_aux_sender (GstElement * rtpbin, guint sessid, GstRTSPClientSink * sink)
3199 {
3200   GstRTSPStream *stream = NULL;
3201   GstElement *ret = NULL;
3202   GList *walk;
3203
3204   GST_RTSP_STATE_LOCK (sink);
3205   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3206     GstRTSPStreamContext *context = (GstRTSPStreamContext *) walk->data;
3207
3208     if (sessid == gst_rtsp_stream_get_index (context->stream)) {
3209       stream = context->stream;
3210       break;
3211     }
3212   }
3213
3214   if (stream != NULL) {
3215     GST_DEBUG_OBJECT (sink, "Creating aux sender for stream %u", sessid);
3216     ret = gst_rtsp_stream_request_aux_sender (stream, sessid);
3217   }
3218
3219   GST_RTSP_STATE_UNLOCK (sink);
3220
3221   return ret;
3222 }
3223
3224 static gboolean
3225 gst_rtsp_client_sink_collect_streams (GstRTSPClientSink * sink)
3226 {
3227   GstRTSPStreamContext *context;
3228   GList *walk;
3229   const gchar *base;
3230   gboolean has_slash;
3231
3232   GST_DEBUG_OBJECT (sink, "Collecting stream information");
3233
3234   if (!gst_rtsp_client_sink_configure_manager (sink))
3235     return FALSE;
3236
3237   base = get_aggregate_control (sink);
3238   /* check if the base ends with / */
3239   has_slash = g_str_has_suffix (base, "/");
3240
3241   g_mutex_lock (&sink->preroll_lock);
3242   while (sink->contexts == NULL && !sink->conninfo.flushing) {
3243     g_cond_wait (&sink->preroll_cond, &sink->preroll_lock);
3244   }
3245   g_mutex_unlock (&sink->preroll_lock);
3246
3247   /* FIXME: Need different locking - need to protect against pad releases
3248    * and potential state changes ruining things here */
3249   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3250     GstPad *srcpad;
3251
3252     context = (GstRTSPStreamContext *) walk->data;
3253     if (context->stream)
3254       continue;
3255
3256     g_mutex_lock (&sink->preroll_lock);
3257     while (!context->prerolled && !sink->conninfo.flushing) {
3258       GST_DEBUG_OBJECT (sink, "Waiting for caps on stream %d", context->index);
3259       g_cond_wait (&sink->preroll_cond, &sink->preroll_lock);
3260     }
3261     if (sink->conninfo.flushing) {
3262       g_mutex_unlock (&sink->preroll_lock);
3263       break;
3264     }
3265     g_mutex_unlock (&sink->preroll_lock);
3266
3267     if (context->payloader == NULL)
3268       continue;
3269
3270     srcpad = gst_element_get_static_pad (context->payloader, "src");
3271
3272     GST_DEBUG_OBJECT (sink, "Creating stream object for stream %d",
3273         context->index);
3274     context->stream =
3275         gst_rtsp_client_sink_create_stream (sink, context, context->payloader,
3276         srcpad);
3277
3278     /* concatenate the two strings, insert / when not present */
3279     g_free (context->conninfo.location);
3280     context->conninfo.location =
3281         g_strdup_printf ("%s%sstream=%d", base, has_slash ? "" : "/",
3282         context->index);
3283
3284     if (sink->rtx_time > 0) {
3285       /* enable retransmission by setting rtprtxsend as the "aux" element of rtpbin */
3286       g_signal_connect (sink->rtpbin, "request-aux-sender",
3287           (GCallback) request_aux_sender, sink);
3288     }
3289
3290     if (!gst_rtsp_stream_join_bin (context->stream,
3291             GST_BIN (sink->internal_bin), sink->rtpbin, GST_STATE_PAUSED)) {
3292       goto join_bin_failed;
3293     }
3294     context->joined = TRUE;
3295
3296     /* Let the stream object receive data */
3297     gst_pad_remove_probe (srcpad, context->payloader_block_id);
3298
3299     gst_object_unref (srcpad);
3300   }
3301
3302   /* Now wait for the preroll of the rtp bin */
3303   g_mutex_lock (&sink->preroll_lock);
3304   while (!sink->prerolled && !sink->conninfo.flushing) {
3305     GST_LOG_OBJECT (sink, "Waiting for preroll before continuing");
3306     g_cond_wait (&sink->preroll_cond, &sink->preroll_lock);
3307   }
3308   GST_LOG_OBJECT (sink, "Marking streams as collected");
3309   sink->streams_collected = TRUE;
3310   g_mutex_unlock (&sink->preroll_lock);
3311
3312   return TRUE;
3313
3314 join_bin_failed:
3315
3316   GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
3317       ("Could not start stream %d", context->index));
3318   return FALSE;
3319 }
3320
3321 static GstRTSPResult
3322 gst_rtsp_client_sink_create_transports_string (GstRTSPClientSink * sink,
3323     GstRTSPStreamContext * context, GSocketFamily family,
3324     GstRTSPLowerTrans protocols, GstRTSPProfile profiles, gchar ** transports)
3325 {
3326   GString *result;
3327   GstRTSPStream *stream = context->stream;
3328   gboolean first = TRUE;
3329
3330   /* the default RTSP transports */
3331   result = g_string_new ("RTP");
3332
3333   while (profiles != 0) {
3334     if (!first)
3335       g_string_append (result, ",RTP");
3336
3337     if (profiles & GST_RTSP_PROFILE_SAVPF) {
3338       g_string_append (result, "/SAVPF");
3339       profiles &= ~GST_RTSP_PROFILE_SAVPF;
3340     } else if (profiles & GST_RTSP_PROFILE_SAVP) {
3341       g_string_append (result, "/SAVP");
3342       profiles &= ~GST_RTSP_PROFILE_SAVP;
3343     } else if (profiles & GST_RTSP_PROFILE_AVPF) {
3344       g_string_append (result, "/AVPF");
3345       profiles &= ~GST_RTSP_PROFILE_AVPF;
3346     } else if (profiles & GST_RTSP_PROFILE_AVP) {
3347       g_string_append (result, "/AVP");
3348       profiles &= ~GST_RTSP_PROFILE_AVP;
3349     } else {
3350       GST_WARNING_OBJECT (sink, "Unimplemented profile(s) 0x%x", profiles);
3351       break;
3352     }
3353
3354     if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
3355       GstRTSPRange ports;
3356
3357       GST_DEBUG_OBJECT (sink, "adding UDP unicast");
3358       gst_rtsp_stream_get_server_port (stream, &ports, family);
3359
3360       g_string_append_printf (result, "/UDP;unicast;client_port=%d-%d",
3361           ports.min, ports.max);
3362     } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3363       GstRTSPAddress *addr =
3364           gst_rtsp_stream_get_multicast_address (stream, family);
3365       if (addr) {
3366         GST_DEBUG_OBJECT (sink, "adding UDP multicast");
3367         g_string_append_printf (result, "/UDP;multicast;client_port=%d-%d",
3368             addr->port, addr->port + addr->n_ports - 1);
3369         gst_rtsp_address_free (addr);
3370       }
3371     } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
3372       GST_DEBUG_OBJECT (sink, "adding TCP");
3373       g_string_append_printf (result, "/TCP;unicast;interleaved=%d-%d",
3374           sink->free_channel, sink->free_channel + 1);
3375     }
3376
3377     g_string_append (result, ";mode=RECORD");
3378     /* FIXME: Support appending too:
3379        if (sink->append)
3380        g_string_append (result, ";append");
3381      */
3382
3383     first = FALSE;
3384   }
3385
3386   if (first) {
3387     /* No valid transport could be constructed */
3388     GST_ERROR_OBJECT (sink, "No supported profiles configured");
3389     goto fail;
3390   }
3391
3392   *transports = g_string_free (result, FALSE);
3393
3394   GST_DEBUG_OBJECT (sink, "prepared transports %s", GST_STR_NULL (*transports));
3395
3396   return GST_RTSP_OK;
3397 fail:
3398   g_string_free (result, TRUE);
3399   return GST_RTSP_ERROR;
3400 }
3401
3402 static GstCaps *
3403 signal_get_srtcp_params (GstRTSPClientSink * sink,
3404     GstRTSPStreamContext * context)
3405 {
3406   GstCaps *caps = NULL;
3407
3408   g_signal_emit (sink, gst_rtsp_client_sink_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
3409       context->index, &caps);
3410
3411   if (caps != NULL)
3412     GST_DEBUG_OBJECT (sink, "SRTP parameters received");
3413
3414   return caps;
3415 }
3416
3417 static gchar *
3418 gst_rtsp_client_sink_stream_make_keymgmt (GstRTSPClientSink * sink,
3419     GstRTSPStreamContext * context)
3420 {
3421   gchar *base64, *result = NULL;
3422   GstMIKEYMessage *mikey_msg;
3423
3424   context->srtcpparams = signal_get_srtcp_params (sink, context);
3425   if (context->srtcpparams == NULL)
3426     context->srtcpparams = gst_rtsp_stream_get_caps (context->stream);
3427
3428   mikey_msg = gst_mikey_message_new_from_caps (context->srtcpparams);
3429   if (mikey_msg) {
3430     guint send_ssrc;
3431
3432     /* add policy '0' for our SSRC */
3433     gst_rtsp_stream_get_ssrc (context->stream, &send_ssrc);
3434     GST_LOG_OBJECT (sink, "Stream %p ssrc %x", context->stream, send_ssrc);
3435     gst_mikey_message_add_cs_srtp (mikey_msg, 0, send_ssrc, 0);
3436
3437     base64 = gst_mikey_message_base64_encode (mikey_msg);
3438     gst_mikey_message_unref (mikey_msg);
3439
3440     if (base64) {
3441       result = gst_sdp_make_keymgmt (context->conninfo.location, base64);
3442       g_free (base64);
3443     }
3444   }
3445
3446   return result;
3447 }
3448
3449 /* masks to be kept in sync with the hardcoded protocol order of preference
3450  * in code below */
3451 static const guint protocol_masks[] = {
3452   GST_RTSP_LOWER_TRANS_UDP,
3453   GST_RTSP_LOWER_TRANS_UDP_MCAST,
3454   GST_RTSP_LOWER_TRANS_TCP,
3455   0
3456 };
3457
3458 /* Same for profile_masks */
3459 static const guint profile_masks[] = {
3460   GST_RTSP_PROFILE_SAVPF,
3461   GST_RTSP_PROFILE_SAVP,
3462   GST_RTSP_PROFILE_AVPF,
3463   GST_RTSP_PROFILE_AVP,
3464   0
3465 };
3466
3467 static gboolean
3468 do_send_data (GstBuffer * buffer, guint8 channel,
3469     GstRTSPStreamContext * context)
3470 {
3471   GstRTSPClientSink *sink = context->parent;
3472   GstRTSPMessage message = { 0 };
3473   GstRTSPResult res = GST_RTSP_OK;
3474   GstMapInfo map_info;
3475   guint8 *data;
3476   guint usize;
3477
3478   gst_rtsp_message_init_data (&message, channel);
3479
3480   /* FIXME, need some sort of iovec RTSPMessage here */
3481   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
3482     return FALSE;
3483
3484   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
3485
3486   res =
3487       gst_rtsp_client_sink_try_send (sink, sink->conninfo.connection, &message,
3488       NULL, NULL);
3489
3490   gst_rtsp_message_steal_body (&message, &data, &usize);
3491   gst_buffer_unmap (buffer, &map_info);
3492
3493   gst_rtsp_message_unset (&message);
3494
3495   return res == GST_RTSP_OK;
3496 }
3497
3498 static GstRTSPResult
3499 gst_rtsp_client_sink_setup_streams (GstRTSPClientSink * sink, gboolean async)
3500 {
3501   GstRTSPResult res = GST_RTSP_ERROR;
3502   GstRTSPMessage request = { 0 };
3503   GstRTSPMessage response = { 0 };
3504   GstRTSPLowerTrans protocols;
3505   GstRTSPStatusCode code;
3506   GSocketFamily family;
3507   GSocketAddress *sa;
3508   GSocket *conn_socket;
3509   GstRTSPUrl *url;
3510   GList *walk;
3511   gchar *hval;
3512
3513   if (sink->conninfo.connection) {
3514     url = gst_rtsp_connection_get_url (sink->conninfo.connection);
3515     /* we initially allow all configured lower transports. based on the URL
3516      * transports and the replies from the server we narrow them down. */
3517     protocols = url->transports & sink->cur_protocols;
3518   } else {
3519     url = NULL;
3520     protocols = sink->cur_protocols;
3521   }
3522
3523   if (protocols == 0)
3524     goto no_protocols;
3525
3526   GST_RTSP_STATE_LOCK (sink);
3527
3528   if (G_UNLIKELY (sink->contexts == NULL))
3529     goto no_streams;
3530
3531   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3532     GstRTSPStreamContext *context = (GstRTSPStreamContext *) walk->data;
3533     GstRTSPStream *stream;
3534
3535     GstRTSPConnection *conn;
3536     GstRTSPProfile profiles;
3537     GstRTSPProfile cur_profile;
3538     gchar *transports;
3539     gint retry = 0;
3540     guint profile_mask = 0;
3541     guint mask = 0;
3542     GstCaps *caps;
3543     const GstSDPMedia *media;
3544
3545     stream = context->stream;
3546     profiles = gst_rtsp_stream_get_profiles (stream);
3547
3548     caps = gst_rtsp_stream_get_caps (stream);
3549     if (caps == NULL) {
3550       GST_DEBUG_OBJECT (sink, "skipping stream %p, no caps", stream);
3551       continue;
3552     }
3553     gst_caps_unref (caps);
3554     media = gst_sdp_message_get_media (&sink->cursdp, context->sdp_index);
3555     if (media == NULL) {
3556       GST_DEBUG_OBJECT (sink, "skipping stream %p, no SDP info", stream);
3557       continue;
3558     }
3559
3560     /* skip setup if we have no URL for it */
3561     if (context->conninfo.location == NULL) {
3562       GST_DEBUG_OBJECT (sink, "skipping stream %p, no setup", stream);
3563       continue;
3564     }
3565
3566     if (sink->conninfo.connection == NULL) {
3567       if (!gst_rtsp_conninfo_connect (sink, &context->conninfo, async)) {
3568         GST_DEBUG_OBJECT (sink, "skipping stream %p, failed to connect",
3569             stream);
3570         continue;
3571       }
3572       conn = context->conninfo.connection;
3573     } else {
3574       conn = sink->conninfo.connection;
3575     }
3576     GST_DEBUG_OBJECT (sink, "doing setup of stream %p with %s", stream,
3577         context->conninfo.location);
3578
3579     conn_socket = gst_rtsp_connection_get_read_socket (conn);
3580     sa = g_socket_get_local_address (conn_socket, NULL);
3581     family = g_socket_address_get_family (sa);
3582     g_object_unref (sa);
3583
3584   next_protocol:
3585     /* first selectable profile */
3586     while (profile_masks[profile_mask]
3587         && !(profiles & profile_masks[profile_mask]))
3588       profile_mask++;
3589     if (!profile_masks[profile_mask])
3590       goto no_profiles;
3591
3592     /* first selectable protocol */
3593     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
3594       mask++;
3595     if (!protocol_masks[mask])
3596       goto no_protocols;
3597
3598   retry:
3599     GST_DEBUG_OBJECT (sink, "protocols = 0x%x, protocol mask = 0x%x", protocols,
3600         protocol_masks[mask]);
3601     /* create a string with first transport in line */
3602     transports = NULL;
3603     cur_profile = profiles & profile_masks[profile_mask];
3604     res = gst_rtsp_client_sink_create_transports_string (sink, context, family,
3605         protocols & protocol_masks[mask], cur_profile, &transports);
3606     if (res < 0 || transports == NULL)
3607       goto setup_transport_failed;
3608
3609     if (strlen (transports) == 0) {
3610       g_free (transports);
3611       GST_DEBUG_OBJECT (sink, "no transports found");
3612       mask++;
3613       profile_mask = 0;
3614       goto next_protocol;
3615     }
3616
3617     GST_DEBUG_OBJECT (sink, "transport is %s", GST_STR_NULL (transports));
3618
3619     /* create SETUP request */
3620     res =
3621         gst_rtsp_client_sink_init_request (sink, &request, GST_RTSP_SETUP,
3622         context->conninfo.location);
3623     if (res < 0) {
3624       g_free (transports);
3625       goto create_request_failed;
3626     }
3627
3628     /* select transport */
3629     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
3630
3631     /* set up keys */
3632     if (cur_profile == GST_RTSP_PROFILE_SAVP ||
3633         cur_profile == GST_RTSP_PROFILE_SAVPF) {
3634       hval = gst_rtsp_client_sink_stream_make_keymgmt (sink, context);
3635       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
3636     }
3637
3638     /* if the user wants a non default RTP packet size we add the blocksize
3639      * parameter */
3640     if (sink->rtp_blocksize > 0) {
3641       hval = g_strdup_printf ("%d", sink->rtp_blocksize);
3642       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
3643     }
3644
3645     if (async)
3646       GST_ELEMENT_PROGRESS (sink, CONTINUE, "request", ("SETUP stream %d",
3647               context->index));
3648
3649     /* handle the code ourselves */
3650     res = gst_rtsp_client_sink_send (sink, conn, &request, &response, &code);
3651     if (res < 0)
3652       goto send_error;
3653
3654     switch (code) {
3655       case GST_RTSP_STS_OK:
3656         break;
3657       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
3658         gst_rtsp_message_unset (&request);
3659         gst_rtsp_message_unset (&response);
3660
3661         /* Try another profile. If no more, move to the next protocol */
3662         profile_mask++;
3663         while (profile_masks[profile_mask]
3664             && !(profiles & profile_masks[profile_mask]))
3665           profile_mask++;
3666         if (profile_masks[profile_mask])
3667           goto retry;
3668
3669         /* select next available protocol, give up on this stream if none */
3670         /* Reset profiles to try: */
3671         profile_mask = 0;
3672
3673         mask++;
3674         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
3675           mask++;
3676         if (!protocol_masks[mask])
3677           continue;
3678         else
3679           goto retry;
3680       default:
3681         goto response_error;
3682     }
3683
3684     /* parse response transport */
3685     {
3686       gchar *resptrans = NULL;
3687       GstRTSPTransport *transport;
3688
3689       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
3690           &resptrans, 0);
3691       if (!resptrans) {
3692         goto no_transport;
3693       }
3694
3695       gst_rtsp_transport_new (&transport);
3696
3697       /* parse transport, go to next stream on parse error */
3698       if (gst_rtsp_transport_parse (resptrans, transport) != GST_RTSP_OK) {
3699         GST_WARNING_OBJECT (sink, "failed to parse transport %s", resptrans);
3700         goto next;
3701       }
3702
3703       /* update allowed transports for other streams. once the transport of
3704        * one stream has been determined, we make sure that all other streams
3705        * are configured in the same way */
3706       switch (transport->lower_transport) {
3707         case GST_RTSP_LOWER_TRANS_TCP:
3708           GST_DEBUG_OBJECT (sink, "stream %p as TCP interleaved", stream);
3709           protocols = GST_RTSP_LOWER_TRANS_TCP;
3710           sink->interleaved = TRUE;
3711           /* update free channels */
3712           sink->free_channel =
3713               MAX (transport->interleaved.min, sink->free_channel);
3714           sink->free_channel =
3715               MAX (transport->interleaved.max, sink->free_channel);
3716           sink->free_channel++;
3717           break;
3718         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3719           /* only allow multicast for other streams */
3720           GST_DEBUG_OBJECT (sink, "stream %p as UDP multicast", stream);
3721           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
3722           break;
3723         case GST_RTSP_LOWER_TRANS_UDP:
3724           /* only allow unicast for other streams */
3725           GST_DEBUG_OBJECT (sink, "stream %p as UDP unicast", stream);
3726           protocols = GST_RTSP_LOWER_TRANS_UDP;
3727           /* Update transport with server destination if not provided by the server */
3728           if (transport->destination == NULL) {
3729             transport->destination = g_strdup (sink->server_ip);
3730           }
3731           break;
3732         default:
3733           GST_DEBUG_OBJECT (sink, "stream %p unknown transport %d", stream,
3734               transport->lower_transport);
3735           break;
3736       }
3737
3738       if (!retry) {
3739         GST_DEBUG ("Configuring the stream transport for stream %d",
3740             context->index);
3741         if (context->stream_transport == NULL)
3742           context->stream_transport =
3743               gst_rtsp_stream_transport_new (stream, transport);
3744         else
3745           gst_rtsp_stream_transport_set_transport (context->stream_transport,
3746               transport);
3747
3748         if (transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
3749           /* our callbacks to send data on this TCP connection */
3750           gst_rtsp_stream_transport_set_callbacks (context->stream_transport,
3751               (GstRTSPSendFunc) do_send_data,
3752               (GstRTSPSendFunc) do_send_data, context, NULL);
3753         }
3754
3755         /* The stream_transport now owns the transport */
3756         transport = NULL;
3757
3758         gst_rtsp_stream_transport_set_active (context->stream_transport, TRUE);
3759       }
3760     next:
3761       if (transport)
3762         gst_rtsp_transport_free (transport);
3763       /* clean up used RTSP messages */
3764       gst_rtsp_message_unset (&request);
3765       gst_rtsp_message_unset (&response);
3766     }
3767   }
3768   GST_RTSP_STATE_UNLOCK (sink);
3769
3770   /* store the transport protocol that was configured */
3771   sink->cur_protocols = protocols;
3772
3773   return res;
3774
3775 no_streams:
3776   {
3777     GST_RTSP_STATE_UNLOCK (sink);
3778     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
3779         ("SDP contains no streams"));
3780     return GST_RTSP_ERROR;
3781   }
3782 setup_transport_failed:
3783   {
3784     GST_RTSP_STATE_UNLOCK (sink);
3785     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
3786         ("Could not setup transport."));
3787     res = GST_RTSP_ERROR;
3788     goto cleanup_error;
3789   }
3790 no_profiles:
3791   {
3792     GST_RTSP_STATE_UNLOCK (sink);
3793     /* no transport possible, post an error and stop */
3794     GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
3795         ("Could not connect to server, no profiles left"));
3796     return GST_RTSP_ERROR;
3797   }
3798 no_protocols:
3799   {
3800     GST_RTSP_STATE_UNLOCK (sink);
3801     /* no transport possible, post an error and stop */
3802     GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
3803         ("Could not connect to server, no protocols left"));
3804     return GST_RTSP_ERROR;
3805   }
3806 no_transport:
3807   {
3808     GST_RTSP_STATE_UNLOCK (sink);
3809     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
3810         ("Server did not select transport."));
3811     res = GST_RTSP_ERROR;
3812     goto cleanup_error;
3813   }
3814 create_request_failed:
3815   {
3816     gchar *str = gst_rtsp_strresult (res);
3817
3818     GST_RTSP_STATE_UNLOCK (sink);
3819     GST_ELEMENT_ERROR (sink, LIBRARY, INIT, (NULL),
3820         ("Could not create request. (%s)", str));
3821     g_free (str);
3822     goto cleanup_error;
3823   }
3824 send_error:
3825   {
3826     gchar *str = gst_rtsp_strresult (res);
3827
3828     GST_RTSP_STATE_UNLOCK (sink);
3829     if (res != GST_RTSP_EINTR) {
3830       GST_ELEMENT_ERROR (sink, RESOURCE, WRITE, (NULL),
3831           ("Could not send message. (%s)", str));
3832     } else {
3833       GST_WARNING_OBJECT (sink, "send interrupted");
3834     }
3835     g_free (str);
3836     goto cleanup_error;
3837   }
3838 response_error:
3839   {
3840     const gchar *str = gst_rtsp_status_as_text (code);
3841
3842     GST_RTSP_STATE_UNLOCK (sink);
3843     GST_ELEMENT_ERROR (sink, RESOURCE, WRITE, (NULL),
3844         ("Error (%d): %s", code, GST_STR_NULL (str)));
3845     res = GST_RTSP_ERROR;
3846     goto cleanup_error;
3847   }
3848 cleanup_error:
3849   {
3850     gst_rtsp_message_unset (&request);
3851     gst_rtsp_message_unset (&response);
3852     return res;
3853   }
3854 }
3855
3856 static GstRTSPResult
3857 gst_rtsp_client_sink_ensure_open (GstRTSPClientSink * sink, gboolean async)
3858 {
3859   GstRTSPResult res = GST_RTSP_OK;
3860
3861   if (sink->state < GST_RTSP_STATE_READY) {
3862     res = GST_RTSP_ERROR;
3863     if (sink->open_error) {
3864       GST_DEBUG_OBJECT (sink, "the stream was in error");
3865       goto done;
3866     }
3867     if (async)
3868       gst_rtsp_client_sink_loop_start_cmd (sink, CMD_OPEN);
3869
3870     if ((res = gst_rtsp_client_sink_open (sink, async)) < 0) {
3871       GST_DEBUG_OBJECT (sink, "failed to open stream");
3872       goto done;
3873     }
3874   }
3875
3876 done:
3877   return res;
3878 }
3879
3880 static GstRTSPResult
3881 gst_rtsp_client_sink_record (GstRTSPClientSink * sink, gboolean async)
3882 {
3883   GstRTSPMessage request = { 0 };
3884   GstRTSPMessage response = { 0 };
3885   GstRTSPResult res = GST_RTSP_OK;
3886   GstSDPMessage *sdp;
3887   guint sdp_index = 0;
3888   GstSDPInfo info = { 0, };
3889
3890   const gchar *proto;
3891   gchar *sess_id, *client_ip, *str;
3892   GSocketAddress *sa;
3893   GInetAddress *ia;
3894   GSocket *conn_socket;
3895   GList *walk;
3896
3897   /* Wait for streams to preroll */
3898   g_mutex_lock (&sink->preroll_lock);
3899   while (sink->in_async) {
3900     GST_LOG_OBJECT (sink, "Waiting for ASYNC_DONE preroll");
3901     g_cond_wait (&sink->preroll_cond, &sink->preroll_lock);
3902   }
3903   g_mutex_unlock (&sink->preroll_lock);
3904
3905   if (sink->state == GST_RTSP_STATE_PLAYING) {
3906     /* Already recording, don't send another request */
3907     GST_LOG_OBJECT (sink, "Already in RECORD. Skipping duplicate request.");
3908     goto done;
3909   }
3910
3911   /* Send announce, then setup for all streams */
3912   gst_sdp_message_init (&sink->cursdp);
3913   sdp = &sink->cursdp;
3914
3915   /* some standard things first */
3916   gst_sdp_message_set_version (sdp, "0");
3917
3918   /* session ID doesn't have to be super-unique in this case */
3919   sess_id = g_strdup_printf ("%u", g_random_int ());
3920
3921   if (sink->conninfo.connection == NULL)
3922     return GST_RTSP_ERROR;
3923
3924   conn_socket = gst_rtsp_connection_get_read_socket (sink->conninfo.connection);
3925
3926   sa = g_socket_get_local_address (conn_socket, NULL);
3927   ia = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (sa));
3928   client_ip = g_inet_address_to_string (ia);
3929   if (g_socket_address_get_family (sa) == G_SOCKET_FAMILY_IPV6) {
3930     info.is_ipv6 = TRUE;
3931     proto = "IP6";
3932   } else if (g_socket_address_get_family (sa) == G_SOCKET_FAMILY_IPV4)
3933     proto = "IP4";
3934   else
3935     g_assert_not_reached ();
3936   g_object_unref (sa);
3937
3938   /* FIXME: Should this actually be the server's IP or ours? */
3939   info.server_ip = sink->server_ip;
3940
3941   gst_sdp_message_set_origin (sdp, "-", sess_id, "1", "IN", proto, client_ip);
3942
3943   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
3944   gst_sdp_message_set_information (sdp, "rtspclientsink");
3945   gst_sdp_message_add_time (sdp, "0", "0", NULL);
3946   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
3947
3948   /* add stream */
3949   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
3950     GstRTSPStreamContext *context = (GstRTSPStreamContext *) walk->data;
3951
3952     gst_rtsp_sdp_from_stream (sdp, &info, context->stream);
3953     context->sdp_index = sdp_index++;
3954   }
3955
3956   g_free (sess_id);
3957   g_free (client_ip);
3958
3959   /* send ANNOUNCE request */
3960   GST_DEBUG_OBJECT (sink, "create ANNOUNCE request...");
3961   res =
3962       gst_rtsp_client_sink_init_request (sink, &request, GST_RTSP_ANNOUNCE,
3963       sink->conninfo.url_str);
3964   if (res < 0)
3965     goto create_request_failed;
3966
3967   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_CONTENT_TYPE,
3968       "application/sdp");
3969
3970   /* add SDP to the request body */
3971   str = gst_sdp_message_as_text (sdp);
3972   gst_rtsp_message_take_body (&request, (guint8 *) str, strlen (str));
3973
3974   /* send ANNOUNCE */
3975   GST_DEBUG_OBJECT (sink, "sending announce...");
3976
3977   if (async)
3978     GST_ELEMENT_PROGRESS (sink, CONTINUE, "record",
3979         ("Sending server stream info"));
3980
3981   if ((res =
3982           gst_rtsp_client_sink_send (sink, sink->conninfo.connection, &request,
3983               &response, NULL)) < 0)
3984     goto send_error;
3985
3986   /* send setup for all streams */
3987   if ((res = gst_rtsp_client_sink_setup_streams (sink, async)) < 0)
3988     goto setup_failed;
3989
3990   res = gst_rtsp_client_sink_init_request (sink, &request, GST_RTSP_RECORD,
3991       sink->conninfo.url_str);
3992
3993   if (res < 0)
3994     goto create_request_failed;
3995
3996 #if 0                           /* FIXME: Configure a range based on input segments? */
3997   if (src->need_range) {
3998     hval = gen_range_header (src, segment);
3999
4000     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
4001   }
4002
4003   if (segment->rate != 1.0) {
4004     gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
4005
4006     g_ascii_dtostr (hval, sizeof (hval), segment->rate);
4007     if (src->skip)
4008       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
4009     else
4010       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
4011   }
4012 #endif
4013
4014   if (async)
4015     GST_ELEMENT_PROGRESS (sink, CONTINUE, "record", ("Starting recording"));
4016   if ((res =
4017           gst_rtsp_client_sink_send (sink, sink->conninfo.connection, &request,
4018               &response, NULL)) < 0)
4019     goto send_error;
4020
4021 #if 0                           /* FIXME: Check if servers return these for record: */
4022   /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
4023    * for the RTP packets. If this is not present, we assume all starts from 0...
4024    * This is info for the RTP session manager that we pass to it in caps. */
4025   hval_idx = 0;
4026   while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
4027           &hval, hval_idx++) == GST_RTSP_OK)
4028     gst_rtspsrc_parse_rtpinfo (src, hval);
4029
4030   /* some servers indicate RTCP parameters in PLAY response,
4031    * rather than properly in SDP */
4032   if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
4033           &hval, 0) == GST_RTSP_OK)
4034     gst_rtspsrc_handle_rtcp_interval (src, hval);
4035 #endif
4036
4037   gst_rtsp_client_sink_set_state (sink, GST_STATE_PLAYING);
4038   sink->state = GST_RTSP_STATE_PLAYING;
4039
4040   /* clean up any messages */
4041   gst_rtsp_message_unset (&request);
4042   gst_rtsp_message_unset (&response);
4043
4044 done:
4045   return res;
4046
4047 create_request_failed:
4048   {
4049     gchar *str = gst_rtsp_strresult (res);
4050
4051     GST_ELEMENT_ERROR (sink, LIBRARY, INIT, (NULL),
4052         ("Could not create request. (%s)", str));
4053     g_free (str);
4054     goto cleanup_error;
4055   }
4056 send_error:
4057   {
4058     /* Don't post a message - the rtsp_send method will have
4059      * taken care of it because we passed NULL for the response code */
4060     goto cleanup_error;
4061   }
4062 setup_failed:
4063   {
4064     GST_ERROR_OBJECT (sink, "setup failed");
4065     goto cleanup_error;
4066   }
4067 cleanup_error:
4068   {
4069     if (sink->conninfo.connection) {
4070       GST_DEBUG_OBJECT (sink, "free connection");
4071       gst_rtsp_conninfo_close (sink, &sink->conninfo, TRUE);
4072     }
4073     gst_rtsp_message_unset (&request);
4074     gst_rtsp_message_unset (&response);
4075     return res;
4076   }
4077 }
4078
4079 static GstRTSPResult
4080 gst_rtsp_client_sink_pause (GstRTSPClientSink * sink, gboolean async)
4081 {
4082   GstRTSPResult res = GST_RTSP_OK;
4083   GstRTSPMessage request = { 0 };
4084   GstRTSPMessage response = { 0 };
4085   GList *walk;
4086   const gchar *control;
4087
4088   GST_DEBUG_OBJECT (sink, "PAUSE...");
4089
4090   if ((res = gst_rtsp_client_sink_ensure_open (sink, async)) < 0)
4091     goto open_failed;
4092
4093   if (!(sink->methods & GST_RTSP_PAUSE))
4094     goto not_supported;
4095
4096   if (sink->state == GST_RTSP_STATE_READY)
4097     goto was_paused;
4098
4099   if (!sink->conninfo.connection || !sink->conninfo.connected)
4100     goto no_connection;
4101
4102   /* construct a control url */
4103   control = get_aggregate_control (sink);
4104
4105   /* loop over the streams. We might exit the loop early when we could do an
4106    * aggregate control */
4107   for (walk = sink->contexts; walk; walk = g_list_next (walk)) {
4108     GstRTSPStreamContext *stream = (GstRTSPStreamContext *) walk->data;
4109     GstRTSPConnection *conn;
4110     const gchar *setup_url;
4111
4112     /* try aggregate control first but do non-aggregate control otherwise */
4113     if (control)
4114       setup_url = control;
4115     else if ((setup_url = stream->conninfo.location) == NULL)
4116       continue;
4117
4118     if (sink->conninfo.connection) {
4119       conn = sink->conninfo.connection;
4120     } else if (stream->conninfo.connection) {
4121       conn = stream->conninfo.connection;
4122     } else {
4123       continue;
4124     }
4125
4126     if (async)
4127       GST_ELEMENT_PROGRESS (sink, CONTINUE, "request",
4128           ("Sending PAUSE request"));
4129
4130     if ((res =
4131             gst_rtsp_client_sink_init_request (sink, &request, GST_RTSP_PAUSE,
4132                 setup_url)) < 0)
4133       goto create_request_failed;
4134
4135     if ((res =
4136             gst_rtsp_client_sink_send (sink, conn, &request, &response,
4137                 NULL)) < 0)
4138       goto send_error;
4139
4140     gst_rtsp_message_unset (&request);
4141     gst_rtsp_message_unset (&response);
4142
4143     /* exit early when we did agregate control */
4144     if (control)
4145       break;
4146   }
4147
4148   /* change element states now */
4149   gst_rtsp_client_sink_set_state (sink, GST_STATE_PAUSED);
4150
4151 no_connection:
4152   sink->state = GST_RTSP_STATE_READY;
4153
4154 done:
4155   if (async)
4156     gst_rtsp_client_sink_loop_end_cmd (sink, CMD_PAUSE, res);
4157
4158   return res;
4159
4160   /* ERRORS */
4161 open_failed:
4162   {
4163     GST_DEBUG_OBJECT (sink, "failed to open stream");
4164     goto done;
4165   }
4166 not_supported:
4167   {
4168     GST_DEBUG_OBJECT (sink, "PAUSE is not supported");
4169     goto done;
4170   }
4171 was_paused:
4172   {
4173     GST_DEBUG_OBJECT (sink, "we were already PAUSED");
4174     goto done;
4175   }
4176 create_request_failed:
4177   {
4178     gchar *str = gst_rtsp_strresult (res);
4179
4180     GST_ELEMENT_ERROR (sink, LIBRARY, INIT, (NULL),
4181         ("Could not create request. (%s)", str));
4182     g_free (str);
4183     goto done;
4184   }
4185 send_error:
4186   {
4187     gchar *str = gst_rtsp_strresult (res);
4188
4189     gst_rtsp_message_unset (&request);
4190     if (res != GST_RTSP_EINTR) {
4191       GST_ELEMENT_ERROR (sink, RESOURCE, WRITE, (NULL),
4192           ("Could not send message. (%s)", str));
4193     } else {
4194       GST_WARNING_OBJECT (sink, "PAUSE interrupted");
4195     }
4196     g_free (str);
4197     goto done;
4198   }
4199 }
4200
4201 static void
4202 gst_rtsp_client_sink_handle_message (GstBin * bin, GstMessage * message)
4203 {
4204   GstRTSPClientSink *rtsp_client_sink;
4205
4206   rtsp_client_sink = GST_RTSP_CLIENT_SINK (bin);
4207
4208   switch (GST_MESSAGE_TYPE (message)) {
4209     case GST_MESSAGE_ELEMENT:
4210     {
4211       const GstStructure *s = gst_message_get_structure (message);
4212
4213       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
4214         gboolean ignore_timeout;
4215
4216         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
4217
4218         GST_OBJECT_LOCK (rtsp_client_sink);
4219         ignore_timeout = rtsp_client_sink->ignore_timeout;
4220         rtsp_client_sink->ignore_timeout = TRUE;
4221         GST_OBJECT_UNLOCK (rtsp_client_sink);
4222
4223         /* we only act on the first udp timeout message, others are irrelevant
4224          * and can be ignored. */
4225         if (!ignore_timeout)
4226           gst_rtsp_client_sink_loop_send_cmd (rtsp_client_sink, CMD_RECONNECT,
4227               CMD_LOOP);
4228         /* eat and free */
4229         gst_message_unref (message);
4230         return;
4231       } else if (gst_structure_has_name (s, "GstRTSPStreamBlocking")) {
4232         /* An RTSPStream has prerolled */
4233         g_cond_broadcast (&rtsp_client_sink->preroll_cond);
4234       }
4235       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
4236       break;
4237     }
4238     case GST_MESSAGE_ASYNC_START:{
4239       GstObject *sender;
4240
4241       sender = GST_MESSAGE_SRC (message);
4242
4243       GST_LOG_OBJECT (rtsp_client_sink,
4244           "Have async-start from %" GST_PTR_FORMAT, sender);
4245       if (sender == GST_OBJECT (rtsp_client_sink->internal_bin)) {
4246         GST_LOG_OBJECT (rtsp_client_sink, "child bin is now ASYNC");
4247       }
4248       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
4249       break;
4250     }
4251     case GST_MESSAGE_ASYNC_DONE:
4252     {
4253       GstObject *sender;
4254       gboolean need_async_done;
4255
4256       sender = GST_MESSAGE_SRC (message);
4257       GST_LOG_OBJECT (rtsp_client_sink, "Have async-done from %" GST_PTR_FORMAT,
4258           sender);
4259
4260       g_mutex_lock (&rtsp_client_sink->preroll_lock);
4261       if (sender == GST_OBJECT_CAST (rtsp_client_sink->internal_bin)) {
4262         GST_LOG_OBJECT (rtsp_client_sink, "child bin is no longer ASYNC");
4263       }
4264       need_async_done = rtsp_client_sink->in_async;
4265       if (rtsp_client_sink->in_async) {
4266         rtsp_client_sink->in_async = FALSE;
4267         g_cond_broadcast (&rtsp_client_sink->preroll_cond);
4268       }
4269       g_mutex_unlock (&rtsp_client_sink->preroll_lock);
4270
4271       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
4272
4273       if (need_async_done) {
4274         GST_DEBUG_OBJECT (rtsp_client_sink, "Posting ASYNC-DONE");
4275         gst_element_post_message (GST_ELEMENT_CAST (rtsp_client_sink),
4276             gst_message_new_async_done (GST_OBJECT_CAST (rtsp_client_sink),
4277                 GST_CLOCK_TIME_NONE));
4278       }
4279       break;
4280     }
4281     case GST_MESSAGE_ERROR:
4282     {
4283       GstObject *sender;
4284
4285       sender = GST_MESSAGE_SRC (message);
4286
4287       GST_DEBUG_OBJECT (rtsp_client_sink, "got error from %s",
4288           GST_ELEMENT_NAME (sender));
4289
4290       /* FIXME: Ignore errors on RTCP? */
4291       /* fatal but not our message, forward */
4292       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
4293       break;
4294     }
4295     case GST_MESSAGE_STATE_CHANGED:
4296     {
4297       if (GST_MESSAGE_SRC (message) ==
4298           (GstObject *) rtsp_client_sink->internal_bin) {
4299         GstState newstate, pending;
4300         gst_message_parse_state_changed (message, NULL, &newstate, &pending);
4301         g_mutex_lock (&rtsp_client_sink->preroll_lock);
4302         rtsp_client_sink->prerolled = (newstate >= GST_STATE_PAUSED)
4303             && pending == GST_STATE_VOID_PENDING;
4304         g_cond_broadcast (&rtsp_client_sink->preroll_cond);
4305         g_mutex_unlock (&rtsp_client_sink->preroll_lock);
4306         GST_DEBUG_OBJECT (bin,
4307             "Internal bin changed state to %s (pending %s). Prerolled now %d",
4308             gst_element_state_get_name (newstate),
4309             gst_element_state_get_name (pending), rtsp_client_sink->prerolled);
4310       }
4311       /* fallthrough */
4312     }
4313     default:
4314     {
4315       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
4316       break;
4317     }
4318   }
4319 }
4320
4321 /* the thread where everything happens */
4322 static void
4323 gst_rtsp_client_sink_thread (GstRTSPClientSink * sink)
4324 {
4325   gint cmd;
4326
4327   GST_OBJECT_LOCK (sink);
4328   cmd = sink->pending_cmd;
4329   if (cmd == CMD_RECONNECT || cmd == CMD_RECORD || cmd == CMD_PAUSE
4330       || cmd == CMD_LOOP || cmd == CMD_OPEN)
4331     sink->pending_cmd = CMD_LOOP;
4332   else
4333     sink->pending_cmd = CMD_WAIT;
4334   GST_DEBUG_OBJECT (sink, "got command %s", cmd_to_string (cmd));
4335
4336   /* we got the message command, so ensure communication is possible again */
4337   gst_rtsp_client_sink_connection_flush (sink, FALSE);
4338
4339   sink->busy_cmd = cmd;
4340   GST_OBJECT_UNLOCK (sink);
4341
4342   switch (cmd) {
4343     case CMD_OPEN:
4344       gst_rtsp_client_sink_open (sink, TRUE);
4345       break;
4346     case CMD_RECORD:
4347       gst_rtsp_client_sink_record (sink, TRUE);
4348       break;
4349     case CMD_PAUSE:
4350       gst_rtsp_client_sink_pause (sink, TRUE);
4351       break;
4352     case CMD_CLOSE:
4353       gst_rtsp_client_sink_close (sink, TRUE, FALSE);
4354       break;
4355     case CMD_LOOP:
4356       gst_rtsp_client_sink_loop (sink);
4357       break;
4358     case CMD_RECONNECT:
4359       gst_rtsp_client_sink_reconnect (sink, FALSE);
4360       break;
4361     default:
4362       break;
4363   }
4364
4365   GST_OBJECT_LOCK (sink);
4366   /* and go back to sleep */
4367   if (sink->pending_cmd == CMD_WAIT) {
4368     if (sink->task)
4369       gst_task_pause (sink->task);
4370   }
4371   /* reset waiting */
4372   sink->busy_cmd = CMD_WAIT;
4373   GST_OBJECT_UNLOCK (sink);
4374 }
4375
4376 static gboolean
4377 gst_rtsp_client_sink_start (GstRTSPClientSink * sink)
4378 {
4379   GST_DEBUG_OBJECT (sink, "starting");
4380
4381   sink->streams_collected = FALSE;
4382   sink->in_async = TRUE;
4383   gst_element_set_locked_state (GST_ELEMENT (sink->internal_bin), TRUE);
4384
4385   gst_rtsp_client_sink_set_state (sink, GST_STATE_READY);
4386
4387   GST_OBJECT_LOCK (sink);
4388   sink->pending_cmd = CMD_WAIT;
4389
4390   if (sink->task == NULL) {
4391     sink->task =
4392         gst_task_new ((GstTaskFunction) gst_rtsp_client_sink_thread, sink,
4393         NULL);
4394     if (sink->task == NULL)
4395       goto task_error;
4396
4397     gst_task_set_lock (sink->task, GST_RTSP_STREAM_GET_LOCK (sink));
4398   }
4399   GST_OBJECT_UNLOCK (sink);
4400
4401   return TRUE;
4402
4403   /* ERRORS */
4404 task_error:
4405   {
4406     GST_OBJECT_UNLOCK (sink);
4407     GST_ERROR_OBJECT (sink, "failed to create task");
4408     return FALSE;
4409   }
4410 }
4411
4412 static gboolean
4413 gst_rtsp_client_sink_stop (GstRTSPClientSink * sink)
4414 {
4415   GstTask *task;
4416
4417   GST_DEBUG_OBJECT (sink, "stopping");
4418
4419   /* also cancels pending task */
4420   gst_rtsp_client_sink_loop_send_cmd (sink, CMD_WAIT, CMD_ALL & ~CMD_CLOSE);
4421
4422   GST_OBJECT_LOCK (sink);
4423   if ((task = sink->task)) {
4424     sink->task = NULL;
4425     GST_OBJECT_UNLOCK (sink);
4426
4427     gst_task_stop (task);
4428
4429     /* make sure it is not running */
4430     GST_RTSP_STREAM_LOCK (sink);
4431     GST_RTSP_STREAM_UNLOCK (sink);
4432
4433     /* now wait for the task to finish */
4434     gst_task_join (task);
4435
4436     /* and free the task */
4437     gst_object_unref (GST_OBJECT (task));
4438
4439     GST_OBJECT_LOCK (sink);
4440   }
4441   GST_OBJECT_UNLOCK (sink);
4442
4443   /* ensure synchronously all is closed and clean */
4444   gst_rtsp_client_sink_close (sink, FALSE, TRUE);
4445
4446   return TRUE;
4447 }
4448
4449 static GstStateChangeReturn
4450 gst_rtsp_client_sink_change_state (GstElement * element,
4451     GstStateChange transition)
4452 {
4453   GstRTSPClientSink *rtsp_client_sink;
4454   GstStateChangeReturn ret;
4455
4456   rtsp_client_sink = GST_RTSP_CLIENT_SINK (element);
4457
4458   switch (transition) {
4459     case GST_STATE_CHANGE_NULL_TO_READY:
4460       if (!gst_rtsp_client_sink_start (rtsp_client_sink))
4461         goto start_failed;
4462       break;
4463     case GST_STATE_CHANGE_READY_TO_PAUSED:
4464       /* init some state */
4465       rtsp_client_sink->cur_protocols = rtsp_client_sink->protocols;
4466       /* first attempt, don't ignore timeouts */
4467       rtsp_client_sink->ignore_timeout = FALSE;
4468       rtsp_client_sink->open_error = FALSE;
4469
4470       gst_rtsp_client_sink_set_state (rtsp_client_sink, GST_STATE_PAUSED);
4471
4472       g_mutex_lock (&rtsp_client_sink->preroll_lock);
4473       if (rtsp_client_sink->in_async) {
4474         GST_DEBUG_OBJECT (rtsp_client_sink, "Posting ASYNC-START");
4475         gst_element_post_message (GST_ELEMENT_CAST (rtsp_client_sink),
4476             gst_message_new_async_start (GST_OBJECT_CAST (rtsp_client_sink)));
4477       }
4478       g_mutex_unlock (&rtsp_client_sink->preroll_lock);
4479
4480       break;
4481     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4482       /* fall-through */
4483     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4484       /* unblock the tcp tasks and make the loop waiting */
4485       if (gst_rtsp_client_sink_loop_send_cmd (rtsp_client_sink, CMD_WAIT,
4486               CMD_LOOP)) {
4487         /* make sure it is waiting before we send PLAY below */
4488         GST_RTSP_STREAM_LOCK (rtsp_client_sink);
4489         GST_RTSP_STREAM_UNLOCK (rtsp_client_sink);
4490       }
4491       break;
4492     case GST_STATE_CHANGE_PAUSED_TO_READY:
4493       gst_rtsp_client_sink_set_state (rtsp_client_sink, GST_STATE_READY);
4494       break;
4495     default:
4496       break;
4497   }
4498
4499   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4500   if (ret == GST_STATE_CHANGE_FAILURE)
4501     goto done;
4502
4503   switch (transition) {
4504     case GST_STATE_CHANGE_NULL_TO_READY:
4505       ret = GST_STATE_CHANGE_SUCCESS;
4506       break;
4507     case GST_STATE_CHANGE_READY_TO_PAUSED:
4508       /* Return ASYNC and preroll input streams */
4509       g_mutex_lock (&rtsp_client_sink->preroll_lock);
4510       if (rtsp_client_sink->in_async)
4511         ret = GST_STATE_CHANGE_ASYNC;
4512       g_mutex_unlock (&rtsp_client_sink->preroll_lock);
4513       gst_rtsp_client_sink_loop_send_cmd (rtsp_client_sink, CMD_OPEN, 0);
4514       break;
4515     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:{
4516       GST_DEBUG_OBJECT (rtsp_client_sink,
4517           "Switching to playing -sending RECORD");
4518       gst_rtsp_client_sink_loop_send_cmd (rtsp_client_sink, CMD_RECORD, 0);
4519       ret = GST_STATE_CHANGE_SUCCESS;
4520       break;
4521     }
4522     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4523       /* send pause request and keep the idle task around */
4524       gst_rtsp_client_sink_loop_send_cmd (rtsp_client_sink, CMD_PAUSE,
4525           CMD_LOOP);
4526       ret = GST_STATE_CHANGE_NO_PREROLL;
4527       break;
4528     case GST_STATE_CHANGE_PAUSED_TO_READY:
4529       gst_rtsp_client_sink_loop_send_cmd (rtsp_client_sink, CMD_CLOSE,
4530           CMD_PAUSE);
4531       ret = GST_STATE_CHANGE_SUCCESS;
4532       break;
4533     case GST_STATE_CHANGE_READY_TO_NULL:
4534       gst_rtsp_client_sink_stop (rtsp_client_sink);
4535       ret = GST_STATE_CHANGE_SUCCESS;
4536       break;
4537     default:
4538       break;
4539   }
4540
4541 done:
4542   return ret;
4543
4544 start_failed:
4545   {
4546     GST_DEBUG_OBJECT (rtsp_client_sink, "start failed");
4547     return GST_STATE_CHANGE_FAILURE;
4548   }
4549 }
4550
4551 /*** GSTURIHANDLER INTERFACE *************************************************/
4552
4553 static GstURIType
4554 gst_rtsp_client_sink_uri_get_type (GType type)
4555 {
4556   return GST_URI_SINK;
4557 }
4558
4559 static const gchar *const *
4560 gst_rtsp_client_sink_uri_get_protocols (GType type)
4561 {
4562   static const gchar *protocols[] =
4563       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
4564     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
4565   };
4566
4567   return protocols;
4568 }
4569
4570 static gchar *
4571 gst_rtsp_client_sink_uri_get_uri (GstURIHandler * handler)
4572 {
4573   GstRTSPClientSink *sink = GST_RTSP_CLIENT_SINK (handler);
4574
4575   /* FIXME: make thread-safe */
4576   return g_strdup (sink->conninfo.location);
4577 }
4578
4579 static gboolean
4580 gst_rtsp_client_sink_uri_set_uri (GstURIHandler * handler, const gchar * uri,
4581     GError ** error)
4582 {
4583   GstRTSPClientSink *sink;
4584   GstRTSPResult res;
4585   GstSDPResult sres;
4586   GstRTSPUrl *newurl = NULL;
4587   GstSDPMessage *sdp = NULL;
4588
4589   sink = GST_RTSP_CLIENT_SINK (handler);
4590
4591   /* same URI, we're fine */
4592   if (sink->conninfo.location && uri && !strcmp (uri, sink->conninfo.location))
4593     goto was_ok;
4594
4595   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
4596     sres = gst_sdp_message_new (&sdp);
4597     if (sres < 0)
4598       goto sdp_failed;
4599
4600     GST_DEBUG_OBJECT (sink, "parsing SDP message");
4601     sres = gst_sdp_message_parse_uri (uri, sdp);
4602     if (sres < 0)
4603       goto invalid_sdp;
4604   } else {
4605     /* try to parse */
4606     GST_DEBUG_OBJECT (sink, "parsing URI");
4607     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
4608       goto parse_error;
4609   }
4610
4611   /* if worked, free previous and store new url object along with the original
4612    * location. */
4613   GST_DEBUG_OBJECT (sink, "configuring URI");
4614   g_free (sink->conninfo.location);
4615   sink->conninfo.location = g_strdup (uri);
4616   gst_rtsp_url_free (sink->conninfo.url);
4617   sink->conninfo.url = newurl;
4618   g_free (sink->conninfo.url_str);
4619   if (newurl)
4620     sink->conninfo.url_str = gst_rtsp_url_get_request_uri (sink->conninfo.url);
4621   else
4622     sink->conninfo.url_str = NULL;
4623
4624   if (sink->uri_sdp)
4625     gst_sdp_message_free (sink->uri_sdp);
4626   sink->uri_sdp = sdp;
4627   sink->from_sdp = sdp != NULL;
4628
4629   GST_DEBUG_OBJECT (sink, "set uri: %s", GST_STR_NULL (uri));
4630   GST_DEBUG_OBJECT (sink, "request uri is: %s",
4631       GST_STR_NULL (sink->conninfo.url_str));
4632
4633   return TRUE;
4634
4635   /* Special cases */
4636 was_ok:
4637   {
4638     GST_DEBUG_OBJECT (sink, "URI was ok: '%s'", GST_STR_NULL (uri));
4639     return TRUE;
4640   }
4641 sdp_failed:
4642   {
4643     GST_ERROR_OBJECT (sink, "Could not create new SDP (%d)", sres);
4644     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
4645         "Could not create SDP");
4646     return FALSE;
4647   }
4648 invalid_sdp:
4649   {
4650     GST_ERROR_OBJECT (sink, "Not a valid SDP (%d) '%s'", sres,
4651         GST_STR_NULL (uri));
4652     gst_sdp_message_free (sdp);
4653     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
4654         "Invalid SDP");
4655     return FALSE;
4656   }
4657 parse_error:
4658   {
4659     GST_ERROR_OBJECT (sink, "Not a valid RTSP url '%s' (%d)",
4660         GST_STR_NULL (uri), res);
4661     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
4662         "Invalid RTSP URI");
4663     return FALSE;
4664   }
4665 }
4666
4667 static void
4668 gst_rtsp_client_sink_uri_handler_init (gpointer g_iface, gpointer iface_data)
4669 {
4670   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
4671
4672   iface->get_type = gst_rtsp_client_sink_uri_get_type;
4673   iface->get_protocols = gst_rtsp_client_sink_uri_get_protocols;
4674   iface->get_uri = gst_rtsp_client_sink_uri_get_uri;
4675   iface->set_uri = gst_rtsp_client_sink_uri_set_uri;
4676 }