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