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