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