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