12587c8f9375e9407d9496c0d47b9276777d72f8
[platform/upstream/gst-plugins-good.git] / gst / rtsp / gstrtspsrc.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  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 /*
21  * Unless otherwise indicated, Source Code is licensed under MIT license.
22  * See further explanation attached in License Statement (distributed in the file
23  * LICENSE).
24  *
25  * Permission is hereby granted, free of charge, to any person obtaining a copy of
26  * this software and associated documentation files (the "Software"), to deal in
27  * the Software without restriction, including without limitation the rights to
28  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
29  * of the Software, and to permit persons to whom the Software is furnished to do
30  * so, subject to the following conditions:
31  *
32  * The above copyright notice and this permission notice shall be included in all
33  * copies or substantial portions of the Software.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
41  * SOFTWARE.
42  */
43 /**
44  * SECTION:element-rtspsrc
45  *
46  * Makes a connection to an RTSP server and read the data.
47  * rtspsrc strictly follows RFC 2326 and therefore does not (yet) support
48  * RealMedia/Quicktime/Microsoft extensions.
49  *
50  * RTSP supports transport over TCP or UDP in unicast or multicast mode. By
51  * default rtspsrc 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 #GstRTSPSrc:protocols property.
54  *
55  * rtspsrc currently understands SDP as the format of the session description.
56  * For each stream listed in the SDP a new rtp_stream\%d pad will be created
57  * with caps derived from the SDP media description. This is a caps of mime type
58  * "application/x-rtp" that can be connected to any available RTP depayloader
59  * element.
60  *
61  * rtspsrc will internally instantiate an RTP session manager element
62  * that will handle the RTCP messages to and from the server, jitter removal,
63  * packet reordering along with providing a clock for the pipeline.
64  * This feature is implemented using the gstrtpbin element.
65  *
66  * rtspsrc acts like a live source and will therefore only generate data in the
67  * PLAYING state.
68  *
69  * <refsect2>
70  * <title>Example launch line</title>
71  * |[
72  * gst-launch-1.0 rtspsrc location=rtsp://some.server/url ! fakesink
73  * ]| Establish a connection to an RTSP server and send the raw RTP packets to a
74  * fakesink.
75  * </refsect2>
76  */
77
78 #ifdef HAVE_CONFIG_H
79 #include "config.h"
80 #endif
81
82 #ifdef HAVE_UNISTD_H
83 #include <unistd.h>
84 #endif /* HAVE_UNISTD_H */
85 #include <stdlib.h>
86 #include <string.h>
87 #include <stdio.h>
88 #include <stdarg.h>
89
90 #include <gst/net/gstnet.h>
91 #include <gst/sdp/gstsdpmessage.h>
92 #include <gst/sdp/gstmikey.h>
93 #include <gst/rtp/rtp.h>
94
95 #include "gst/gst-i18n-plugin.h"
96
97 #include "gstrtspsrc.h"
98
99 GST_DEBUG_CATEGORY_STATIC (rtspsrc_debug);
100 #define GST_CAT_DEFAULT (rtspsrc_debug)
101
102 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream_%u",
103     GST_PAD_SRC,
104     GST_PAD_SOMETIMES,
105     GST_STATIC_CAPS ("application/x-rtp; application/x-rdt"));
106
107 /* templates used internally */
108 static GstStaticPadTemplate anysrctemplate =
109 GST_STATIC_PAD_TEMPLATE ("internalsrc_%u",
110     GST_PAD_SRC,
111     GST_PAD_SOMETIMES,
112     GST_STATIC_CAPS_ANY);
113
114 static GstStaticPadTemplate anysinktemplate =
115 GST_STATIC_PAD_TEMPLATE ("internalsink_%u",
116     GST_PAD_SINK,
117     GST_PAD_SOMETIMES,
118     GST_STATIC_CAPS_ANY);
119
120 enum
121 {
122   SIGNAL_HANDLE_REQUEST,
123   SIGNAL_ON_SDP,
124   SIGNAL_SELECT_STREAM,
125   SIGNAL_NEW_MANAGER,
126   SIGNAL_REQUEST_RTCP_KEY,
127   LAST_SIGNAL
128 };
129
130 enum _GstRtspSrcRtcpSyncMode
131 {
132   RTCP_SYNC_ALWAYS,
133   RTCP_SYNC_INITIAL,
134   RTCP_SYNC_RTP
135 };
136
137 enum _GstRtspSrcBufferMode
138 {
139   BUFFER_MODE_NONE,
140   BUFFER_MODE_SLAVE,
141   BUFFER_MODE_BUFFER,
142   BUFFER_MODE_AUTO,
143   BUFFER_MODE_SYNCED
144 };
145
146 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
147 static GType
148 gst_rtsp_src_buffer_mode_get_type (void)
149 {
150   static GType buffer_mode_type = 0;
151   static const GEnumValue buffer_modes[] = {
152     {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
153     {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
154     {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
155     {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
156     {BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks", "synced"},
157     {0, NULL, NULL},
158   };
159
160   if (!buffer_mode_type) {
161     buffer_mode_type =
162         g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
163   }
164   return buffer_mode_type;
165 }
166
167 enum _GstRtspSrcNtpTimeSource
168 {
169   NTP_TIME_SOURCE_NTP,
170   NTP_TIME_SOURCE_UNIX,
171   NTP_TIME_SOURCE_RUNNING_TIME,
172   NTP_TIME_SOURCE_CLOCK_TIME
173 };
174
175 #define DEBUG_RTSP(__self,msg) if (__self->debug) gst_rtsp_message_dump (msg)
176 #define DEBUG_SDP(__self,msg) if (__self->debug) gst_sdp_message_dump (msg)
177
178 #define GST_TYPE_RTSP_SRC_NTP_TIME_SOURCE (gst_rtsp_src_ntp_time_source_get_type())
179 static GType
180 gst_rtsp_src_ntp_time_source_get_type (void)
181 {
182   static GType ntp_time_source_type = 0;
183   static const GEnumValue ntp_time_source_values[] = {
184     {NTP_TIME_SOURCE_NTP, "NTP time based on realtime clock", "ntp"},
185     {NTP_TIME_SOURCE_UNIX, "UNIX time based on realtime clock", "unix"},
186     {NTP_TIME_SOURCE_RUNNING_TIME,
187           "Running time based on pipeline clock",
188         "running-time"},
189     {NTP_TIME_SOURCE_CLOCK_TIME, "Pipeline clock time", "clock-time"},
190     {0, NULL, NULL},
191   };
192
193   if (!ntp_time_source_type) {
194     ntp_time_source_type =
195         g_enum_register_static ("GstRTSPSrcNtpTimeSource",
196         ntp_time_source_values);
197   }
198   return ntp_time_source_type;
199 }
200
201 #define DEFAULT_LOCATION         NULL
202 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
203 #define DEFAULT_DEBUG            FALSE
204 #define DEFAULT_RETRY            20
205 #define DEFAULT_TIMEOUT          5000000
206 #define DEFAULT_UDP_BUFFER_SIZE  0x80000
207 #define DEFAULT_TCP_TIMEOUT      20000000
208 #define DEFAULT_LATENCY_MS       2000
209 #define DEFAULT_DROP_ON_LATENCY  FALSE
210 #define DEFAULT_CONNECTION_SPEED 0
211 #define DEFAULT_NAT_METHOD       GST_RTSP_NAT_DUMMY
212 #define DEFAULT_DO_RTCP          TRUE
213 #define DEFAULT_DO_RTSP_KEEP_ALIVE       TRUE
214 #define DEFAULT_PROXY            NULL
215 #define DEFAULT_RTP_BLOCKSIZE    0
216 #define DEFAULT_USER_ID          NULL
217 #define DEFAULT_USER_PW          NULL
218 #define DEFAULT_BUFFER_MODE      BUFFER_MODE_AUTO
219 #define DEFAULT_PORT_RANGE       NULL
220 #define DEFAULT_SHORT_HEADER     FALSE
221 #define DEFAULT_PROBATION        2
222 #define DEFAULT_UDP_RECONNECT    TRUE
223 #define DEFAULT_MULTICAST_IFACE  NULL
224 #define DEFAULT_NTP_SYNC         FALSE
225 #define DEFAULT_USE_PIPELINE_CLOCK       FALSE
226 #define DEFAULT_TLS_VALIDATION_FLAGS     G_TLS_CERTIFICATE_VALIDATE_ALL
227 #define DEFAULT_TLS_DATABASE     NULL
228 #define DEFAULT_TLS_INTERACTION     NULL
229 #define DEFAULT_DO_RETRANSMISSION        TRUE
230 #define DEFAULT_NTP_TIME_SOURCE  NTP_TIME_SOURCE_NTP
231 #define DEFAULT_USER_AGENT       "GStreamer/" PACKAGE_VERSION
232 #define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
233 #define DEFAULT_RFC7273_SYNC         FALSE
234 #define DEFAULT_MAX_TS_OFFSET_ADJUSTMENT   0
235 #define DEFAULT_MAX_TS_OFFSET    3000000000
236 #define DEFAULT_VERSION         GST_RTSP_VERSION_1_0
237
238 enum
239 {
240   PROP_0,
241   PROP_LOCATION,
242   PROP_PROTOCOLS,
243   PROP_DEBUG,
244   PROP_RETRY,
245   PROP_TIMEOUT,
246   PROP_TCP_TIMEOUT,
247   PROP_LATENCY,
248   PROP_DROP_ON_LATENCY,
249   PROP_CONNECTION_SPEED,
250   PROP_NAT_METHOD,
251   PROP_DO_RTCP,
252   PROP_DO_RTSP_KEEP_ALIVE,
253   PROP_PROXY,
254   PROP_PROXY_ID,
255   PROP_PROXY_PW,
256   PROP_RTP_BLOCKSIZE,
257   PROP_USER_ID,
258   PROP_USER_PW,
259   PROP_BUFFER_MODE,
260   PROP_PORT_RANGE,
261   PROP_UDP_BUFFER_SIZE,
262   PROP_SHORT_HEADER,
263   PROP_PROBATION,
264   PROP_UDP_RECONNECT,
265   PROP_MULTICAST_IFACE,
266   PROP_NTP_SYNC,
267   PROP_USE_PIPELINE_CLOCK,
268   PROP_SDES,
269   PROP_TLS_VALIDATION_FLAGS,
270   PROP_TLS_DATABASE,
271   PROP_TLS_INTERACTION,
272   PROP_DO_RETRANSMISSION,
273   PROP_NTP_TIME_SOURCE,
274   PROP_USER_AGENT,
275   PROP_MAX_RTCP_RTP_TIME_DIFF,
276   PROP_RFC7273_SYNC,
277   PROP_MAX_TS_OFFSET_ADJUSTMENT,
278   PROP_MAX_TS_OFFSET,
279   PROP_DEFAULT_VERSION,
280 };
281
282 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
283 static GType
284 gst_rtsp_nat_method_get_type (void)
285 {
286   static GType rtsp_nat_method_type = 0;
287   static const GEnumValue rtsp_nat_method[] = {
288     {GST_RTSP_NAT_NONE, "None", "none"},
289     {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
290     {0, NULL, NULL},
291   };
292
293   if (!rtsp_nat_method_type) {
294     rtsp_nat_method_type =
295         g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
296   }
297   return rtsp_nat_method_type;
298 }
299
300 #define RTSP_SRC_RESPONSE_ERROR(src, response_msg, err_cat, err_code, error_message) \
301   do { \
302     GST_ELEMENT_ERROR_WITH_DETAILS((src), err_cat, err_code, ("%s", error_message), \
303         ("%s (%d)", (response_msg)->type_data.response.reason, (response_msg)->type_data.response.code), \
304         ("rtsp-status-code", G_TYPE_UINT, (response_msg)->type_data.response.code, \
305          "rtsp-status-reason", G_TYPE_STRING, GST_STR_NULL((response_msg)->type_data.response.reason), NULL)); \
306   } while (0)
307
308 static void gst_rtspsrc_finalize (GObject * object);
309
310 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
311     const GValue * value, GParamSpec * pspec);
312 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
313     GValue * value, GParamSpec * pspec);
314
315 static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
316
317 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
318     gpointer iface_data);
319
320 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
321 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
322
323 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
324     GstStateChange transition);
325 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
326 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
327
328 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
329     GstRTSPMessage * response);
330
331 static gboolean gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd,
332     gint mask);
333 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
334     GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
335
336 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
337 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
338     gboolean async, const gchar * seek_style);
339 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
340 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
341     gboolean only_close);
342
343 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
344     const gchar * uri, GError ** error);
345 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
346
347 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
348 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
349 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
350     GstRTSPStream * stream, GstEvent * event);
351 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
352 static void gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush);
353 static GstRTSPResult gst_rtsp_conninfo_close (GstRTSPSrc * src,
354     GstRTSPConnInfo * info, gboolean free);
355
356 typedef struct
357 {
358   guint8 pt;
359   GstCaps *caps;
360 } PtMapItem;
361
362 /* commands we send to out loop to notify it of events */
363 #define CMD_OPEN       (1 << 0)
364 #define CMD_PLAY       (1 << 1)
365 #define CMD_PAUSE      (1 << 2)
366 #define CMD_CLOSE      (1 << 3)
367 #define CMD_WAIT       (1 << 4)
368 #define CMD_RECONNECT  (1 << 5)
369 #define CMD_LOOP       (1 << 6)
370
371 /* mask for all commands */
372 #define CMD_ALL         ((CMD_LOOP << 1) - 1)
373
374 #define GST_ELEMENT_PROGRESS(el, type, code, text)      \
375 G_STMT_START {                                          \
376   gchar *__txt = _gst_element_error_printf text;        \
377   gst_element_post_message (GST_ELEMENT_CAST (el),      \
378       gst_message_new_progress (GST_OBJECT_CAST (el),   \
379           GST_PROGRESS_TYPE_ ##type, code, __txt));     \
380   g_free (__txt);                                       \
381 } G_STMT_END
382
383 static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
384
385 #define gst_rtspsrc_parent_class parent_class
386 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
387     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
388
389 #ifndef GST_DISABLE_GST_DEBUG
390 static inline const char *
391 cmd_to_string (guint cmd)
392 {
393   switch (cmd) {
394     case CMD_OPEN:
395       return "OPEN";
396     case CMD_PLAY:
397       return "PLAY";
398     case CMD_PAUSE:
399       return "PAUSE";
400     case CMD_CLOSE:
401       return "CLOSE";
402     case CMD_WAIT:
403       return "WAIT";
404     case CMD_RECONNECT:
405       return "RECONNECT";
406     case CMD_LOOP:
407       return "LOOP";
408   }
409
410   return "unknown";
411 }
412 #endif
413
414 static gboolean
415 default_select_stream (GstRTSPSrc * src, guint id, GstCaps * caps)
416 {
417   GST_DEBUG_OBJECT (src, "default handler");
418   return TRUE;
419 }
420
421 static gboolean
422 select_stream_accum (GSignalInvocationHint * ihint,
423     GValue * return_accu, const GValue * handler_return, gpointer data)
424 {
425   gboolean myboolean;
426
427   myboolean = g_value_get_boolean (handler_return);
428   GST_DEBUG ("accum %d", myboolean);
429   g_value_set_boolean (return_accu, myboolean);
430
431   /* stop emission if FALSE */
432   return myboolean;
433 }
434
435 static void
436 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
437 {
438   GObjectClass *gobject_class;
439   GstElementClass *gstelement_class;
440   GstBinClass *gstbin_class;
441
442   gobject_class = (GObjectClass *) klass;
443   gstelement_class = (GstElementClass *) klass;
444   gstbin_class = (GstBinClass *) klass;
445
446   GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
447
448   gobject_class->set_property = gst_rtspsrc_set_property;
449   gobject_class->get_property = gst_rtspsrc_get_property;
450
451   gobject_class->finalize = gst_rtspsrc_finalize;
452
453   g_object_class_install_property (gobject_class, PROP_LOCATION,
454       g_param_spec_string ("location", "RTSP Location",
455           "Location of the RTSP url to read",
456           DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
457
458   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
459       g_param_spec_flags ("protocols", "Protocols",
460           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
461           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
462
463   g_object_class_install_property (gobject_class, PROP_DEBUG,
464       g_param_spec_boolean ("debug", "Debug",
465           "Dump request and response messages to stdout",
466           DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
467
468   g_object_class_install_property (gobject_class, PROP_RETRY,
469       g_param_spec_uint ("retry", "Retry",
470           "Max number of retries when allocating RTP ports.",
471           0, G_MAXUINT16, DEFAULT_RETRY,
472           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
473
474   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
475       g_param_spec_uint64 ("timeout", "Timeout",
476           "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
477           0, G_MAXUINT64, DEFAULT_TIMEOUT,
478           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
479
480   g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
481       g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
482           "Fail after timeout microseconds on TCP connections (0 = disabled)",
483           0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
484           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
485
486   g_object_class_install_property (gobject_class, PROP_LATENCY,
487       g_param_spec_uint ("latency", "Buffer latency in ms",
488           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
489           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
490
491   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
492       g_param_spec_boolean ("drop-on-latency",
493           "Drop buffers when maximum latency is reached",
494           "Tells the jitterbuffer to never exceed the given latency in size",
495           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
496
497   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
498       g_param_spec_uint64 ("connection-speed", "Connection Speed",
499           "Network connection speed in kbps (0 = unknown)",
500           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
501           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
502
503   g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
504       g_param_spec_enum ("nat-method", "NAT Method",
505           "Method to use for traversing firewalls and NAT",
506           GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
507           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
508
509   /**
510    * GstRTSPSrc:do-rtcp:
511    *
512    * Enable RTCP support. Some old server don't like RTCP and then this property
513    * needs to be set to FALSE.
514    */
515   g_object_class_install_property (gobject_class, PROP_DO_RTCP,
516       g_param_spec_boolean ("do-rtcp", "Do RTCP",
517           "Send RTCP packets, disable for old incompatible server.",
518           DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
519
520   /**
521    * GstRTSPSrc:do-rtsp-keep-alive:
522    *
523    * Enable RTSP keep alive support. Some old server don't like RTSP
524    * keep alive and then this property needs to be set to FALSE.
525    */
526   g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
527       g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
528           "Send RTSP keep alive packets, disable for old incompatible server.",
529           DEFAULT_DO_RTSP_KEEP_ALIVE,
530           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
531
532   /**
533    * GstRTSPSrc:proxy:
534    *
535    * Set the proxy parameters. This has to be a string of the format
536    * [http://][user:passwd@]host[:port].
537    */
538   g_object_class_install_property (gobject_class, PROP_PROXY,
539       g_param_spec_string ("proxy", "Proxy",
540           "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
541           DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
542   /**
543    * GstRTSPSrc:proxy-id:
544    *
545    * Sets the proxy URI user id for authentication. If the URI set via the
546    * "proxy" property contains a user-id already, that will take precedence.
547    *
548    * Since: 1.2
549    */
550   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
551       g_param_spec_string ("proxy-id", "proxy-id",
552           "HTTP proxy URI user id for authentication", "",
553           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
554   /**
555    * GstRTSPSrc:proxy-pw:
556    *
557    * Sets the proxy URI password for authentication. If the URI set via the
558    * "proxy" property contains a password already, that will take precedence.
559    *
560    * Since: 1.2
561    */
562   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
563       g_param_spec_string ("proxy-pw", "proxy-pw",
564           "HTTP proxy URI user password for authentication", "",
565           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
566
567   /**
568    * GstRTSPSrc:rtp-blocksize:
569    *
570    * RTP package size to suggest to server.
571    */
572   g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
573       g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
574           "RTP package size to suggest to server (0 = disabled)",
575           0, 65536, DEFAULT_RTP_BLOCKSIZE,
576           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
577
578   g_object_class_install_property (gobject_class,
579       PROP_USER_ID,
580       g_param_spec_string ("user-id", "user-id",
581           "RTSP location URI user id for authentication", DEFAULT_USER_ID,
582           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
583   g_object_class_install_property (gobject_class, PROP_USER_PW,
584       g_param_spec_string ("user-pw", "user-pw",
585           "RTSP location URI user password for authentication", DEFAULT_USER_PW,
586           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
587
588   /**
589    * GstRTSPSrc:buffer-mode:
590    *
591    * Control the buffering and timestamping mode used by the jitterbuffer.
592    */
593   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
594       g_param_spec_enum ("buffer-mode", "Buffer Mode",
595           "Control the buffering algorithm in use",
596           GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
597           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
598
599   /**
600    * GstRTSPSrc:port-range:
601    *
602    * Configure the client port numbers that can be used to recieve RTP and
603    * RTCP.
604    */
605   g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
606       g_param_spec_string ("port-range", "Port range",
607           "Client port range that can be used to receive RTP and RTCP data, "
608           "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
609           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
610
611   /**
612    * GstRTSPSrc:udp-buffer-size:
613    *
614    * Size of the kernel UDP receive buffer in bytes.
615    */
616   g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
617       g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
618           "Size of the kernel UDP receive buffer in bytes, 0=default",
619           0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
620           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
621
622   /**
623    * GstRTSPSrc:short-header:
624    *
625    * Only send the basic RTSP headers for broken encoders.
626    */
627   g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
628       g_param_spec_boolean ("short-header", "Short Header",
629           "Only send the basic RTSP headers for broken encoders",
630           DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
631
632   g_object_class_install_property (gobject_class, PROP_PROBATION,
633       g_param_spec_uint ("probation", "Number of probations",
634           "Consecutive packet sequence numbers to accept the source",
635           0, G_MAXUINT, DEFAULT_PROBATION,
636           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
637
638   g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
639       g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
640           "Reconnect to the server if RTSP connection is closed when doing UDP",
641           DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
642
643   g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
644       g_param_spec_string ("multicast-iface", "Multicast Interface",
645           "The network interface on which to join the multicast group",
646           DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
647
648   g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
649       g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
650           "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
651           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
652
653   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
654       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
655           "Use the pipeline running-time to set the NTP time in the RTCP SR messages"
656           "(DEPRECATED: Use ntp-time-source property)",
657           DEFAULT_USE_PIPELINE_CLOCK,
658           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED));
659
660   g_object_class_install_property (gobject_class, PROP_SDES,
661       g_param_spec_boxed ("sdes", "SDES",
662           "The SDES items of this session",
663           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
664
665   /**
666    * GstRTSPSrc::tls-validation-flags:
667    *
668    * TLS certificate validation flags used to validate server
669    * certificate.
670    *
671    * Since: 1.2.1
672    */
673   g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
674       g_param_spec_flags ("tls-validation-flags", "TLS validation flags",
675           "TLS certificate validation flags used to validate the server certificate",
676           G_TYPE_TLS_CERTIFICATE_FLAGS, DEFAULT_TLS_VALIDATION_FLAGS,
677           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
678
679   /**
680    * GstRTSPSrc::tls-database:
681    *
682    * TLS database with anchor certificate authorities used to validate
683    * the server certificate.
684    *
685    * Since: 1.4
686    */
687   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
688       g_param_spec_object ("tls-database", "TLS database",
689           "TLS database with anchor certificate authorities used to validate the server certificate",
690           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
691
692   /**
693    * GstRTSPSrc::tls-interaction:
694    *
695    * A #GTlsInteraction object to be used when the connection or certificate
696    * database need to interact with the user. This will be used to prompt the
697    * user for passwords where necessary.
698    *
699    * Since: 1.6
700    */
701   g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
702       g_param_spec_object ("tls-interaction", "TLS interaction",
703           "A GTlsInteraction object to promt the user for password or certificate",
704           G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
705
706   /**
707    * GstRTSPSrc::do-retransmission:
708    *
709    * Attempt to ask the server to retransmit lost packets according to RFC4588.
710    *
711    * Note: currently only works with SSRC-multiplexed retransmission streams
712    *
713    * Since: 1.6
714    */
715   g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
716       g_param_spec_boolean ("do-retransmission", "Retransmission",
717           "Ask the server to retransmit lost packets",
718           DEFAULT_DO_RETRANSMISSION,
719           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
720
721   /**
722    * GstRTSPSrc::ntp-time-source:
723    *
724    * allows to select the time source that should be used
725    * for the NTP time in RTCP packets
726    *
727    * Since: 1.6
728    */
729   g_object_class_install_property (gobject_class, PROP_NTP_TIME_SOURCE,
730       g_param_spec_enum ("ntp-time-source", "NTP Time Source",
731           "NTP time source for RTCP packets",
732           GST_TYPE_RTSP_SRC_NTP_TIME_SOURCE, DEFAULT_NTP_TIME_SOURCE,
733           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
734
735   /**
736    * GstRTSPSrc::user-agent:
737    *
738    * The string to set in the User-Agent header.
739    *
740    * Since: 1.6
741    */
742   g_object_class_install_property (gobject_class, PROP_USER_AGENT,
743       g_param_spec_string ("user-agent", "User Agent",
744           "The User-Agent string to send to the server",
745           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
746
747   g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
748       g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
749           "Maximum amount of time in ms that the RTP time in RTCP SRs "
750           "is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
751           DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
752           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
753
754   g_object_class_install_property (gobject_class, PROP_RFC7273_SYNC,
755       g_param_spec_boolean ("rfc7273-sync", "Sync on RFC7273 clock",
756           "Synchronize received streams to the RFC7273 clock "
757           "(requires clock and offset to be provided)", DEFAULT_RFC7273_SYNC,
758           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
759
760   g_object_class_install_property (gobject_class, PROP_DEFAULT_VERSION,
761       g_param_spec_enum ("default-rtsp-version",
762           "The RTSP version to try first",
763           "The RTSP version that should be tried first when negotiating version.",
764           GST_TYPE_RTSP_VERSION, DEFAULT_VERSION,
765           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
766
767   /**
768    * GstRTSPSrc:max-ts-offset-adjustment:
769    *
770    * Syncing time stamps to NTP time adds a time offset. This parameter
771    * specifies the maximum number of nanoseconds per frame that this time offset
772    * may be adjusted with. This is used to avoid sudden large changes to time
773    * stamps.
774    */
775   g_object_class_install_property (gobject_class, PROP_MAX_TS_OFFSET_ADJUSTMENT,
776       g_param_spec_uint64 ("max-ts-offset-adjustment",
777           "Max Timestamp Offset Adjustment",
778           "The maximum number of nanoseconds per frame that time stamp offsets "
779           "may be adjusted (0 = no limit).", 0, G_MAXUINT64,
780           DEFAULT_MAX_TS_OFFSET_ADJUSTMENT, G_PARAM_READWRITE |
781           G_PARAM_STATIC_STRINGS));
782
783   /**
784    * GstRtpBin:max-ts-offset:
785    *
786    * Used to set an upper limit of how large a time offset may be. This
787    * is used to protect against unrealistic values as a result of either
788    * client,server or clock issues.
789    */
790   g_object_class_install_property (gobject_class, PROP_MAX_TS_OFFSET,
791       g_param_spec_int64 ("max-ts-offset", "Max TS Offset",
792           "The maximum absolute value of the time offset in (nanoseconds). "
793           "Note, if the ntp-sync parameter is set the default value is "
794           "changed to 0 (no limit)", 0, G_MAXINT64, DEFAULT_MAX_TS_OFFSET,
795           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
796
797   /**
798    * GstRTSPSrc::handle-request:
799    * @rtspsrc: a #GstRTSPSrc
800    * @request: a #GstRTSPMessage
801    * @response: a #GstRTSPMessage
802    *
803    * Handle a server request in @request and prepare @response.
804    *
805    * This signal is called from the streaming thread, you should therefore not
806    * do any state changes on @rtspsrc because this might deadlock. If you want
807    * to modify the state as a result of this signal, post a
808    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
809    * in some other way.
810    *
811    * Since: 1.2
812    */
813   gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST] =
814       g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
815       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
816       G_TYPE_POINTER, G_TYPE_POINTER);
817
818   /**
819    * GstRTSPSrc::on-sdp:
820    * @rtspsrc: a #GstRTSPSrc
821    * @sdp: a #GstSDPMessage
822    *
823    * Emited when the client has retrieved the SDP and before it configures the
824    * streams in the SDP. @sdp can be inspected and modified.
825    *
826    * This signal is called from the streaming thread, you should therefore not
827    * do any state changes on @rtspsrc because this might deadlock. If you want
828    * to modify the state as a result of this signal, post a
829    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
830    * in some other way.
831    *
832    * Since: 1.2
833    */
834   gst_rtspsrc_signals[SIGNAL_ON_SDP] =
835       g_signal_new ("on-sdp", G_TYPE_FROM_CLASS (klass), 0,
836       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
837       GST_TYPE_SDP_MESSAGE | G_SIGNAL_TYPE_STATIC_SCOPE);
838
839   /**
840    * GstRTSPSrc::select-stream:
841    * @rtspsrc: a #GstRTSPSrc
842    * @num: the stream number
843    * @caps: the stream caps
844    *
845    * Emited before the client decides to configure the stream @num with
846    * @caps.
847    *
848    * Returns: %TRUE when the stream should be selected, %FALSE when the stream
849    * is to be ignored.
850    *
851    * Since: 1.2
852    */
853   gst_rtspsrc_signals[SIGNAL_SELECT_STREAM] =
854       g_signal_new_class_handler ("select-stream", G_TYPE_FROM_CLASS (klass),
855       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP,
856       (GCallback) default_select_stream, select_stream_accum, NULL,
857       g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_UINT,
858       GST_TYPE_CAPS);
859   /**
860    * GstRTSPSrc::new-manager:
861    * @rtspsrc: a #GstRTSPSrc
862    * @manager: a #GstElement
863    *
864    * Emited after a new manager (like rtpbin) was created and the default
865    * properties were configured.
866    *
867    * Since: 1.4
868    */
869   gst_rtspsrc_signals[SIGNAL_NEW_MANAGER] =
870       g_signal_new_class_handler ("new-manager", G_TYPE_FROM_CLASS (klass),
871       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
872       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
873
874   /**
875    * GstRTSPSrc::request-rtcp-key:
876    * @rtspsrc: a #GstRTSPSrc
877    * @num: the stream number
878    *
879    * Signal emited to get the crypto parameters relevant to the RTCP
880    * stream. User should provide the key and the RTCP encryption ciphers
881    * and authentication, and return them wrapped in a GstCaps.
882    *
883    * Since: 1.4
884    */
885   gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY] =
886       g_signal_new ("request-rtcp-key", G_TYPE_FROM_CLASS (klass),
887       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, GST_TYPE_CAPS, 1, G_TYPE_UINT);
888
889   gstelement_class->send_event = gst_rtspsrc_send_event;
890   gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
891   gstelement_class->change_state = gst_rtspsrc_change_state;
892
893   gst_element_class_add_static_pad_template (gstelement_class, &rtptemplate);
894
895   gst_element_class_set_static_metadata (gstelement_class,
896       "RTSP packet receiver", "Source/Network",
897       "Receive data over the network via RTSP (RFC 2326)",
898       "Wim Taymans <wim@fluendo.com>, "
899       "Thijs Vermeir <thijs.vermeir@barco.com>, "
900       "Lutz Mueller <lutz@topfrose.de>");
901
902   gstbin_class->handle_message = gst_rtspsrc_handle_message;
903
904   gst_rtsp_ext_list_init ();
905 }
906
907 static void
908 gst_rtspsrc_init (GstRTSPSrc * src)
909 {
910   src->conninfo.location = g_strdup (DEFAULT_LOCATION);
911   src->protocols = DEFAULT_PROTOCOLS;
912   src->debug = DEFAULT_DEBUG;
913   src->retry = DEFAULT_RETRY;
914   src->udp_timeout = DEFAULT_TIMEOUT;
915   gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
916   src->latency = DEFAULT_LATENCY_MS;
917   src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
918   src->connection_speed = DEFAULT_CONNECTION_SPEED;
919   src->nat_method = DEFAULT_NAT_METHOD;
920   src->do_rtcp = DEFAULT_DO_RTCP;
921   src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
922   gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
923   src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
924   src->user_id = g_strdup (DEFAULT_USER_ID);
925   src->user_pw = g_strdup (DEFAULT_USER_PW);
926   src->buffer_mode = DEFAULT_BUFFER_MODE;
927   src->client_port_range.min = 0;
928   src->client_port_range.max = 0;
929   src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
930   src->short_header = DEFAULT_SHORT_HEADER;
931   src->probation = DEFAULT_PROBATION;
932   src->udp_reconnect = DEFAULT_UDP_RECONNECT;
933   src->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
934   src->ntp_sync = DEFAULT_NTP_SYNC;
935   src->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
936   src->sdes = NULL;
937   src->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
938   src->tls_database = DEFAULT_TLS_DATABASE;
939   src->tls_interaction = DEFAULT_TLS_INTERACTION;
940   src->do_retransmission = DEFAULT_DO_RETRANSMISSION;
941   src->ntp_time_source = DEFAULT_NTP_TIME_SOURCE;
942   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
943   src->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
944   src->rfc7273_sync = DEFAULT_RFC7273_SYNC;
945   src->max_ts_offset_adjustment = DEFAULT_MAX_TS_OFFSET_ADJUSTMENT;
946   src->max_ts_offset = DEFAULT_MAX_TS_OFFSET;
947   src->max_ts_offset_is_set = FALSE;
948   src->default_version = DEFAULT_VERSION;
949   src->version = GST_RTSP_VERSION_INVALID;
950
951   /* get a list of all extensions */
952   src->extensions = gst_rtsp_ext_list_get ();
953
954   /* connect to send signal */
955   gst_rtsp_ext_list_connect (src->extensions, "send",
956       (GCallback) gst_rtspsrc_send_cb, src);
957
958   /* protects the streaming thread in interleaved mode or the polling
959    * thread in UDP mode. */
960   g_rec_mutex_init (&src->stream_rec_lock);
961
962   /* protects our state changes from multiple invocations */
963   g_rec_mutex_init (&src->state_rec_lock);
964
965   src->state = GST_RTSP_STATE_INVALID;
966
967   g_mutex_init (&src->conninfo.send_lock);
968   g_mutex_init (&src->conninfo.recv_lock);
969
970   GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
971   gst_bin_set_suppressed_flags (GST_BIN (src),
972       GST_ELEMENT_FLAG_SOURCE | GST_ELEMENT_FLAG_SINK);
973 }
974
975 static void
976 gst_rtspsrc_finalize (GObject * object)
977 {
978   GstRTSPSrc *rtspsrc;
979
980   rtspsrc = GST_RTSPSRC (object);
981
982   gst_rtsp_ext_list_free (rtspsrc->extensions);
983   g_free (rtspsrc->conninfo.location);
984   gst_rtsp_url_free (rtspsrc->conninfo.url);
985   g_free (rtspsrc->conninfo.url_str);
986   g_free (rtspsrc->user_id);
987   g_free (rtspsrc->user_pw);
988   g_free (rtspsrc->multi_iface);
989   g_free (rtspsrc->user_agent);
990
991   if (rtspsrc->sdp) {
992     gst_sdp_message_free (rtspsrc->sdp);
993     rtspsrc->sdp = NULL;
994   }
995   if (rtspsrc->provided_clock)
996     gst_object_unref (rtspsrc->provided_clock);
997
998   if (rtspsrc->sdes)
999     gst_structure_free (rtspsrc->sdes);
1000
1001   if (rtspsrc->tls_database)
1002     g_object_unref (rtspsrc->tls_database);
1003
1004   if (rtspsrc->tls_interaction)
1005     g_object_unref (rtspsrc->tls_interaction);
1006
1007   /* free locks */
1008   g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
1009   g_rec_mutex_clear (&rtspsrc->state_rec_lock);
1010
1011   g_mutex_clear (&rtspsrc->conninfo.send_lock);
1012   g_mutex_clear (&rtspsrc->conninfo.recv_lock);
1013
1014   G_OBJECT_CLASS (parent_class)->finalize (object);
1015 }
1016
1017 static GstClock *
1018 gst_rtspsrc_provide_clock (GstElement * element)
1019 {
1020   GstRTSPSrc *src = GST_RTSPSRC (element);
1021   GstClock *clock;
1022
1023   if ((clock = src->provided_clock) != NULL)
1024     return gst_object_ref (clock);
1025
1026   return GST_ELEMENT_CLASS (parent_class)->provide_clock (element);
1027 }
1028
1029 /* a proxy string of the format [user:passwd@]host[:port] */
1030 static gboolean
1031 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
1032 {
1033   gchar *p, *at, *col;
1034
1035   g_free (rtsp->proxy_user);
1036   rtsp->proxy_user = NULL;
1037   g_free (rtsp->proxy_passwd);
1038   rtsp->proxy_passwd = NULL;
1039   g_free (rtsp->proxy_host);
1040   rtsp->proxy_host = NULL;
1041   rtsp->proxy_port = 0;
1042
1043   p = (gchar *) proxy;
1044
1045   if (p == NULL)
1046     return TRUE;
1047
1048   /* we allow http:// in front but ignore it */
1049   if (g_str_has_prefix (p, "http://"))
1050     p += 7;
1051
1052   at = strchr (p, '@');
1053   if (at) {
1054     /* look for user:passwd */
1055     col = strchr (proxy, ':');
1056     if (col == NULL || col > at)
1057       return FALSE;
1058
1059     rtsp->proxy_user = g_strndup (p, col - p);
1060     col++;
1061     rtsp->proxy_passwd = g_strndup (col, at - col);
1062
1063     /* move to host */
1064     p = at + 1;
1065   } else {
1066     if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
1067       rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
1068     if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
1069       rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
1070     if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
1071       GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
1072           GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
1073     }
1074   }
1075   col = strchr (p, ':');
1076
1077   if (col) {
1078     /* everything before the colon is the hostname */
1079     rtsp->proxy_host = g_strndup (p, col - p);
1080     p = col + 1;
1081     rtsp->proxy_port = strtoul (p, (char **) &p, 10);
1082   } else {
1083     rtsp->proxy_host = g_strdup (p);
1084     rtsp->proxy_port = 8080;
1085   }
1086   return TRUE;
1087 }
1088
1089 static void
1090 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
1091 {
1092   rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
1093   rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
1094
1095   if (timeout != 0)
1096     rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
1097   else
1098     rtspsrc->ptcp_timeout = NULL;
1099 }
1100
1101 static void
1102 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
1103     GParamSpec * pspec)
1104 {
1105   GstRTSPSrc *rtspsrc;
1106
1107   rtspsrc = GST_RTSPSRC (object);
1108
1109   switch (prop_id) {
1110     case PROP_LOCATION:
1111       gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
1112           g_value_get_string (value), NULL);
1113       break;
1114     case PROP_PROTOCOLS:
1115       rtspsrc->protocols = g_value_get_flags (value);
1116       break;
1117     case PROP_DEBUG:
1118       rtspsrc->debug = g_value_get_boolean (value);
1119       break;
1120     case PROP_RETRY:
1121       rtspsrc->retry = g_value_get_uint (value);
1122       break;
1123     case PROP_TIMEOUT:
1124       rtspsrc->udp_timeout = g_value_get_uint64 (value);
1125       break;
1126     case PROP_TCP_TIMEOUT:
1127       gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
1128       break;
1129     case PROP_LATENCY:
1130       rtspsrc->latency = g_value_get_uint (value);
1131       break;
1132     case PROP_DROP_ON_LATENCY:
1133       rtspsrc->drop_on_latency = g_value_get_boolean (value);
1134       break;
1135     case PROP_CONNECTION_SPEED:
1136       rtspsrc->connection_speed = g_value_get_uint64 (value);
1137       break;
1138     case PROP_NAT_METHOD:
1139       rtspsrc->nat_method = g_value_get_enum (value);
1140       break;
1141     case PROP_DO_RTCP:
1142       rtspsrc->do_rtcp = g_value_get_boolean (value);
1143       break;
1144     case PROP_DO_RTSP_KEEP_ALIVE:
1145       rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
1146       break;
1147     case PROP_PROXY:
1148       gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
1149       break;
1150     case PROP_PROXY_ID:
1151       g_free (rtspsrc->prop_proxy_id);
1152       rtspsrc->prop_proxy_id = g_value_dup_string (value);
1153       break;
1154     case PROP_PROXY_PW:
1155       g_free (rtspsrc->prop_proxy_pw);
1156       rtspsrc->prop_proxy_pw = g_value_dup_string (value);
1157       break;
1158     case PROP_RTP_BLOCKSIZE:
1159       rtspsrc->rtp_blocksize = g_value_get_uint (value);
1160       break;
1161     case PROP_USER_ID:
1162       g_free (rtspsrc->user_id);
1163       rtspsrc->user_id = g_value_dup_string (value);
1164       break;
1165     case PROP_USER_PW:
1166       g_free (rtspsrc->user_pw);
1167       rtspsrc->user_pw = g_value_dup_string (value);
1168       break;
1169     case PROP_BUFFER_MODE:
1170       rtspsrc->buffer_mode = g_value_get_enum (value);
1171       break;
1172     case PROP_PORT_RANGE:
1173     {
1174       const gchar *str;
1175
1176       str = g_value_get_string (value);
1177       if (sscanf (str, "%u-%u", &rtspsrc->client_port_range.min,
1178               &rtspsrc->client_port_range.max) != 2) {
1179         rtspsrc->client_port_range.min = 0;
1180         rtspsrc->client_port_range.max = 0;
1181       }
1182       break;
1183     }
1184     case PROP_UDP_BUFFER_SIZE:
1185       rtspsrc->udp_buffer_size = g_value_get_int (value);
1186       break;
1187     case PROP_SHORT_HEADER:
1188       rtspsrc->short_header = g_value_get_boolean (value);
1189       break;
1190     case PROP_PROBATION:
1191       rtspsrc->probation = g_value_get_uint (value);
1192       break;
1193     case PROP_UDP_RECONNECT:
1194       rtspsrc->udp_reconnect = g_value_get_boolean (value);
1195       break;
1196     case PROP_MULTICAST_IFACE:
1197       g_free (rtspsrc->multi_iface);
1198
1199       if (g_value_get_string (value) == NULL)
1200         rtspsrc->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
1201       else
1202         rtspsrc->multi_iface = g_value_dup_string (value);
1203       break;
1204     case PROP_NTP_SYNC:
1205       rtspsrc->ntp_sync = g_value_get_boolean (value);
1206       /* The default value of max_ts_offset depends on ntp_sync. If user
1207        * hasn't set it then change default value */
1208       if (!rtspsrc->max_ts_offset_is_set) {
1209         if (rtspsrc->ntp_sync) {
1210           rtspsrc->max_ts_offset = 0;
1211         } else {
1212           rtspsrc->max_ts_offset = DEFAULT_MAX_TS_OFFSET;
1213         }
1214       }
1215       break;
1216     case PROP_USE_PIPELINE_CLOCK:
1217       rtspsrc->use_pipeline_clock = g_value_get_boolean (value);
1218       break;
1219     case PROP_SDES:
1220       rtspsrc->sdes = g_value_dup_boxed (value);
1221       break;
1222     case PROP_TLS_VALIDATION_FLAGS:
1223       rtspsrc->tls_validation_flags = g_value_get_flags (value);
1224       break;
1225     case PROP_TLS_DATABASE:
1226       g_clear_object (&rtspsrc->tls_database);
1227       rtspsrc->tls_database = g_value_dup_object (value);
1228       break;
1229     case PROP_TLS_INTERACTION:
1230       g_clear_object (&rtspsrc->tls_interaction);
1231       rtspsrc->tls_interaction = g_value_dup_object (value);
1232       break;
1233     case PROP_DO_RETRANSMISSION:
1234       rtspsrc->do_retransmission = g_value_get_boolean (value);
1235       break;
1236     case PROP_NTP_TIME_SOURCE:
1237       rtspsrc->ntp_time_source = g_value_get_enum (value);
1238       break;
1239     case PROP_USER_AGENT:
1240       g_free (rtspsrc->user_agent);
1241       rtspsrc->user_agent = g_value_dup_string (value);
1242       break;
1243     case PROP_MAX_RTCP_RTP_TIME_DIFF:
1244       rtspsrc->max_rtcp_rtp_time_diff = g_value_get_int (value);
1245       break;
1246     case PROP_RFC7273_SYNC:
1247       rtspsrc->rfc7273_sync = g_value_get_boolean (value);
1248       break;
1249     case PROP_MAX_TS_OFFSET_ADJUSTMENT:
1250       rtspsrc->max_ts_offset_adjustment = g_value_get_uint64 (value);
1251       break;
1252     case PROP_MAX_TS_OFFSET:
1253       rtspsrc->max_ts_offset = g_value_get_int64 (value);
1254       rtspsrc->max_ts_offset_is_set = TRUE;
1255       break;
1256     case PROP_DEFAULT_VERSION:
1257       rtspsrc->default_version = g_value_get_enum (value);
1258       break;
1259     default:
1260       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1261       break;
1262   }
1263 }
1264
1265 static void
1266 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
1267     GParamSpec * pspec)
1268 {
1269   GstRTSPSrc *rtspsrc;
1270
1271   rtspsrc = GST_RTSPSRC (object);
1272
1273   switch (prop_id) {
1274     case PROP_LOCATION:
1275       g_value_set_string (value, rtspsrc->conninfo.location);
1276       break;
1277     case PROP_PROTOCOLS:
1278       g_value_set_flags (value, rtspsrc->protocols);
1279       break;
1280     case PROP_DEBUG:
1281       g_value_set_boolean (value, rtspsrc->debug);
1282       break;
1283     case PROP_RETRY:
1284       g_value_set_uint (value, rtspsrc->retry);
1285       break;
1286     case PROP_TIMEOUT:
1287       g_value_set_uint64 (value, rtspsrc->udp_timeout);
1288       break;
1289     case PROP_TCP_TIMEOUT:
1290     {
1291       guint64 timeout;
1292
1293       timeout = ((guint64) rtspsrc->tcp_timeout.tv_sec) * G_USEC_PER_SEC +
1294           rtspsrc->tcp_timeout.tv_usec;
1295       g_value_set_uint64 (value, timeout);
1296       break;
1297     }
1298     case PROP_LATENCY:
1299       g_value_set_uint (value, rtspsrc->latency);
1300       break;
1301     case PROP_DROP_ON_LATENCY:
1302       g_value_set_boolean (value, rtspsrc->drop_on_latency);
1303       break;
1304     case PROP_CONNECTION_SPEED:
1305       g_value_set_uint64 (value, rtspsrc->connection_speed);
1306       break;
1307     case PROP_NAT_METHOD:
1308       g_value_set_enum (value, rtspsrc->nat_method);
1309       break;
1310     case PROP_DO_RTCP:
1311       g_value_set_boolean (value, rtspsrc->do_rtcp);
1312       break;
1313     case PROP_DO_RTSP_KEEP_ALIVE:
1314       g_value_set_boolean (value, rtspsrc->do_rtsp_keep_alive);
1315       break;
1316     case PROP_PROXY:
1317     {
1318       gchar *str;
1319
1320       if (rtspsrc->proxy_host) {
1321         str =
1322             g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
1323       } else {
1324         str = NULL;
1325       }
1326       g_value_take_string (value, str);
1327       break;
1328     }
1329     case PROP_PROXY_ID:
1330       g_value_set_string (value, rtspsrc->prop_proxy_id);
1331       break;
1332     case PROP_PROXY_PW:
1333       g_value_set_string (value, rtspsrc->prop_proxy_pw);
1334       break;
1335     case PROP_RTP_BLOCKSIZE:
1336       g_value_set_uint (value, rtspsrc->rtp_blocksize);
1337       break;
1338     case PROP_USER_ID:
1339       g_value_set_string (value, rtspsrc->user_id);
1340       break;
1341     case PROP_USER_PW:
1342       g_value_set_string (value, rtspsrc->user_pw);
1343       break;
1344     case PROP_BUFFER_MODE:
1345       g_value_set_enum (value, rtspsrc->buffer_mode);
1346       break;
1347     case PROP_PORT_RANGE:
1348     {
1349       gchar *str;
1350
1351       if (rtspsrc->client_port_range.min != 0) {
1352         str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
1353             rtspsrc->client_port_range.max);
1354       } else {
1355         str = NULL;
1356       }
1357       g_value_take_string (value, str);
1358       break;
1359     }
1360     case PROP_UDP_BUFFER_SIZE:
1361       g_value_set_int (value, rtspsrc->udp_buffer_size);
1362       break;
1363     case PROP_SHORT_HEADER:
1364       g_value_set_boolean (value, rtspsrc->short_header);
1365       break;
1366     case PROP_PROBATION:
1367       g_value_set_uint (value, rtspsrc->probation);
1368       break;
1369     case PROP_UDP_RECONNECT:
1370       g_value_set_boolean (value, rtspsrc->udp_reconnect);
1371       break;
1372     case PROP_MULTICAST_IFACE:
1373       g_value_set_string (value, rtspsrc->multi_iface);
1374       break;
1375     case PROP_NTP_SYNC:
1376       g_value_set_boolean (value, rtspsrc->ntp_sync);
1377       break;
1378     case PROP_USE_PIPELINE_CLOCK:
1379       g_value_set_boolean (value, rtspsrc->use_pipeline_clock);
1380       break;
1381     case PROP_SDES:
1382       g_value_set_boxed (value, rtspsrc->sdes);
1383       break;
1384     case PROP_TLS_VALIDATION_FLAGS:
1385       g_value_set_flags (value, rtspsrc->tls_validation_flags);
1386       break;
1387     case PROP_TLS_DATABASE:
1388       g_value_set_object (value, rtspsrc->tls_database);
1389       break;
1390     case PROP_TLS_INTERACTION:
1391       g_value_set_object (value, rtspsrc->tls_interaction);
1392       break;
1393     case PROP_DO_RETRANSMISSION:
1394       g_value_set_boolean (value, rtspsrc->do_retransmission);
1395       break;
1396     case PROP_NTP_TIME_SOURCE:
1397       g_value_set_enum (value, rtspsrc->ntp_time_source);
1398       break;
1399     case PROP_USER_AGENT:
1400       g_value_set_string (value, rtspsrc->user_agent);
1401       break;
1402     case PROP_MAX_RTCP_RTP_TIME_DIFF:
1403       g_value_set_int (value, rtspsrc->max_rtcp_rtp_time_diff);
1404       break;
1405     case PROP_RFC7273_SYNC:
1406       g_value_set_boolean (value, rtspsrc->rfc7273_sync);
1407       break;
1408     case PROP_MAX_TS_OFFSET_ADJUSTMENT:
1409       g_value_set_uint64 (value, rtspsrc->max_ts_offset_adjustment);
1410       break;
1411     case PROP_MAX_TS_OFFSET:
1412       g_value_set_int64 (value, rtspsrc->max_ts_offset);
1413       break;
1414     case PROP_DEFAULT_VERSION:
1415       g_value_set_enum (value, rtspsrc->default_version);
1416       break;
1417     default:
1418       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1419       break;
1420   }
1421 }
1422
1423 static gint
1424 find_stream_by_id (GstRTSPStream * stream, gint * id)
1425 {
1426   if (stream->id == *id)
1427     return 0;
1428
1429   return -1;
1430 }
1431
1432 static gint
1433 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
1434 {
1435   /* ignore unconfigured channels here (e.g., those that
1436    * were explicitly skipped during SETUP) */
1437   if ((stream->channelpad[0] != NULL) &&
1438       (stream->channel[0] == *channel || stream->channel[1] == *channel))
1439     return 0;
1440
1441   return -1;
1442 }
1443
1444 static gint
1445 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
1446 {
1447   GstElement *src = (GstElement *) a;
1448
1449   if (stream->udpsrc[0] == src)
1450     return 0;
1451   if (stream->udpsrc[1] == src)
1452     return 0;
1453
1454   return -1;
1455 }
1456
1457 static gint
1458 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
1459 {
1460   if (stream->conninfo.location) {
1461     /* check qualified setup_url */
1462     if (!strcmp (stream->conninfo.location, (gchar *) a))
1463       return 0;
1464   }
1465   if (stream->control_url) {
1466     /* check original control_url */
1467     if (!strcmp (stream->control_url, (gchar *) a))
1468       return 0;
1469
1470     /* check if qualified setup_url ends with string */
1471     if (g_str_has_suffix (stream->control_url, (gchar *) a))
1472       return 0;
1473   }
1474
1475   return -1;
1476 }
1477
1478 static GstRTSPStream *
1479 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
1480 {
1481   GList *lstream;
1482
1483   /* find and get stream */
1484   if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
1485     return (GstRTSPStream *) lstream->data;
1486
1487   return NULL;
1488 }
1489
1490 static const GstSDPBandwidth *
1491 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1492     const GstSDPMedia * media, const gchar * type)
1493 {
1494   guint i, len;
1495
1496   /* first look in the media specific section */
1497   len = gst_sdp_media_bandwidths_len (media);
1498   for (i = 0; i < len; i++) {
1499     const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
1500
1501     if (strcmp (bw->bwtype, type) == 0)
1502       return bw;
1503   }
1504   /* then look in the message specific section */
1505   len = gst_sdp_message_bandwidths_len (sdp);
1506   for (i = 0; i < len; i++) {
1507     const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
1508
1509     if (strcmp (bw->bwtype, type) == 0)
1510       return bw;
1511   }
1512   return NULL;
1513 }
1514
1515 static void
1516 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1517     const GstSDPMedia * media, GstRTSPStream * stream)
1518 {
1519   const GstSDPBandwidth *bw;
1520
1521   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
1522     stream->as_bandwidth = bw->bandwidth;
1523   else
1524     stream->as_bandwidth = -1;
1525
1526   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
1527     stream->rr_bandwidth = bw->bandwidth;
1528   else
1529     stream->rr_bandwidth = -1;
1530
1531   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
1532     stream->rs_bandwidth = bw->bandwidth;
1533   else
1534     stream->rs_bandwidth = -1;
1535 }
1536
1537 static void
1538 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
1539     const GstSDPConnection * conn)
1540 {
1541   if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
1542     return;
1543
1544   if (conn->addrtype == NULL)
1545     return;
1546
1547   /* check for IPV6 */
1548   if (strcmp (conn->addrtype, "IP4") == 0)
1549     stream->is_ipv6 = FALSE;
1550   else if (strcmp (conn->addrtype, "IP6") == 0)
1551     stream->is_ipv6 = TRUE;
1552   else
1553     return;
1554
1555   /* save address */
1556   g_free (stream->destination);
1557   stream->destination = g_strdup (conn->address);
1558
1559   /* check for multicast */
1560   stream->is_multicast =
1561       gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
1562       conn->address);
1563   stream->ttl = conn->ttl;
1564 }
1565
1566 /* Go over the connections for a stream.
1567  * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
1568  *   receiving.
1569  * - If we are dealing with a localhost address, we disable multicast
1570  */
1571 static void
1572 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
1573     const GstSDPMedia * media, GstRTSPStream * stream)
1574 {
1575   const GstSDPConnection *conn;
1576   guint i, len;
1577
1578   /* first look in the media specific section */
1579   len = gst_sdp_media_connections_len (media);
1580   for (i = 0; i < len; i++) {
1581     conn = gst_sdp_media_get_connection (media, i);
1582
1583     gst_rtspsrc_do_stream_connection (src, stream, conn);
1584   }
1585   /* then look in the message specific section */
1586   if ((conn = gst_sdp_message_get_connection (sdp))) {
1587     gst_rtspsrc_do_stream_connection (src, stream, conn);
1588   }
1589 }
1590
1591 static gchar *
1592 make_stream_id (GstRTSPStream * stream, const GstSDPMedia * media)
1593 {
1594   gchar *stream_id =
1595       g_strdup_printf ("%s:%d:%d:%s:%d", media->media, media->port,
1596       media->num_ports, media->proto, stream->default_pt);
1597
1598   g_strcanon (stream_id, G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS, ':');
1599
1600   return stream_id;
1601 }
1602
1603 /*   m=<media> <UDP port> RTP/AVP <payload>
1604  */
1605 static void
1606 gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
1607     const GstSDPMedia * media, GstRTSPStream * stream)
1608 {
1609   guint i, len;
1610   const gchar *proto;
1611   GstCaps *global_caps;
1612
1613   /* get proto */
1614   proto = gst_sdp_media_get_proto (media);
1615   if (proto == NULL)
1616     goto no_proto;
1617
1618   if (g_str_equal (proto, "RTP/AVP"))
1619     stream->profile = GST_RTSP_PROFILE_AVP;
1620   else if (g_str_equal (proto, "RTP/SAVP"))
1621     stream->profile = GST_RTSP_PROFILE_SAVP;
1622   else if (g_str_equal (proto, "RTP/AVPF"))
1623     stream->profile = GST_RTSP_PROFILE_AVPF;
1624   else if (g_str_equal (proto, "RTP/SAVPF"))
1625     stream->profile = GST_RTSP_PROFILE_SAVPF;
1626   else
1627     goto unknown_proto;
1628
1629   if (gst_sdp_media_get_attribute_val (media, "sendonly") != NULL)
1630     goto sendonly_media;
1631
1632   /* Parse global SDP attributes once */
1633   global_caps = gst_caps_new_empty_simple ("application/x-unknown");
1634   GST_DEBUG ("mapping sdp session level attributes to caps");
1635   gst_sdp_message_attributes_to_caps (sdp, global_caps);
1636   GST_DEBUG ("mapping sdp media level attributes to caps");
1637   gst_sdp_media_attributes_to_caps (media, global_caps);
1638
1639   /* Keep a copy of the SDP key management */
1640   gst_sdp_media_parse_keymgmt (media, &stream->mikey);
1641   if (stream->mikey == NULL)
1642     gst_sdp_message_parse_keymgmt (sdp, &stream->mikey);
1643
1644   len = gst_sdp_media_formats_len (media);
1645   for (i = 0; i < len; i++) {
1646     gint pt;
1647     GstCaps *caps, *outcaps;
1648     GstStructure *s;
1649     const gchar *enc;
1650     PtMapItem item;
1651
1652     pt = atoi (gst_sdp_media_get_format (media, i));
1653
1654     GST_DEBUG_OBJECT (src, " looking at %d pt: %d", i, pt);
1655
1656     /* convert caps */
1657     caps = gst_sdp_media_get_caps_from_media (media, pt);
1658     if (caps == NULL) {
1659       GST_WARNING_OBJECT (src, " skipping pt %d without caps", pt);
1660       continue;
1661     }
1662
1663     /* do some tweaks */
1664     s = gst_caps_get_structure (caps, 0);
1665     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
1666       stream->is_real = (strstr (enc, "-REAL") != NULL);
1667       if (strcmp (enc, "X-ASF-PF") == 0)
1668         stream->container = TRUE;
1669     }
1670
1671     /* Merge in global caps */
1672     /* Intersect will merge in missing fields to the current caps */
1673     outcaps = gst_caps_intersect (caps, global_caps);
1674     gst_caps_unref (caps);
1675
1676     /* the first pt will be the default */
1677     if (stream->ptmap->len == 0)
1678       stream->default_pt = pt;
1679
1680     item.pt = pt;
1681     item.caps = outcaps;
1682
1683     g_array_append_val (stream->ptmap, item);
1684   }
1685
1686   stream->stream_id = make_stream_id (stream, media);
1687
1688   gst_caps_unref (global_caps);
1689   return;
1690
1691 no_proto:
1692   {
1693     GST_ERROR_OBJECT (src, "can't find proto in media");
1694     return;
1695   }
1696 unknown_proto:
1697   {
1698     GST_ERROR_OBJECT (src, "unknown proto in media: '%s'", proto);
1699     return;
1700   }
1701 sendonly_media:
1702   {
1703     GST_DEBUG_OBJECT (src, "sendonly media ignored");
1704     return;
1705   }
1706 }
1707
1708 static const gchar *
1709 get_aggregate_control (GstRTSPSrc * src)
1710 {
1711   const gchar *base;
1712
1713   if (src->control)
1714     base = src->control;
1715   else if (src->content_base)
1716     base = src->content_base;
1717   else if (src->conninfo.url_str)
1718     base = src->conninfo.url_str;
1719   else
1720     base = "/";
1721
1722   return base;
1723 }
1724
1725 static void
1726 clear_ptmap_item (PtMapItem * item)
1727 {
1728   if (item->caps)
1729     gst_caps_unref (item->caps);
1730 }
1731
1732 static GstRTSPStream *
1733 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx,
1734     gint n_streams)
1735 {
1736   GstRTSPStream *stream;
1737   const gchar *control_url;
1738   const GstSDPMedia *media;
1739
1740   /* get media, should not return NULL */
1741   media = gst_sdp_message_get_media (sdp, idx);
1742   if (media == NULL)
1743     return NULL;
1744
1745   stream = g_new0 (GstRTSPStream, 1);
1746   stream->parent = src;
1747   /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1748    * the element. */
1749   stream->last_ret = GST_FLOW_NOT_LINKED;
1750   stream->added = FALSE;
1751   stream->setup = FALSE;
1752   stream->skipped = FALSE;
1753   stream->id = idx;
1754   stream->eos = FALSE;
1755   stream->discont = TRUE;
1756   stream->seqbase = -1;
1757   stream->timebase = -1;
1758   stream->send_ssrc = g_random_int ();
1759   stream->profile = GST_RTSP_PROFILE_AVP;
1760   stream->ptmap = g_array_new (FALSE, FALSE, sizeof (PtMapItem));
1761   stream->mikey = NULL;
1762   stream->stream_id = NULL;
1763   g_mutex_init (&stream->conninfo.send_lock);
1764   g_mutex_init (&stream->conninfo.recv_lock);
1765   g_array_set_clear_func (stream->ptmap, (GDestroyNotify) clear_ptmap_item);
1766
1767   /* collect bandwidth information for this steam. FIXME, configure in the RTP
1768    * session manager to scale RTCP. */
1769   gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1770
1771   /* collect connection info */
1772   gst_rtspsrc_collect_connections (src, sdp, media, stream);
1773
1774   /* make the payload type map */
1775   gst_rtspsrc_collect_payloads (src, sdp, media, stream);
1776
1777   /* collect port number */
1778   stream->port = gst_sdp_media_get_port (media);
1779
1780   /* get control url to construct the setup url. The setup url is used to
1781    * configure the transport of the stream and is used to identity the stream in
1782    * the RTP-Info header field returned from PLAY. */
1783   control_url = gst_sdp_media_get_attribute_val (media, "control");
1784   if (control_url == NULL)
1785     control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1786
1787   GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1788   GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1789   GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1790   GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1791
1792   /* RFC 2326, C.3: missing control_url permitted in case of a single stream */
1793   if (control_url == NULL && n_streams == 1) {
1794     control_url = "";
1795   }
1796
1797   if (control_url != NULL) {
1798     stream->control_url = g_strdup (control_url);
1799     /* Build a fully qualified url using the content_base if any or by prefixing
1800      * the original request.
1801      * If the control_url starts with a '/' or a non rtsp: protocol we will most
1802      * likely build a URL that the server will fail to understand, this is ok,
1803      * we will fail then. */
1804     if (g_str_has_prefix (control_url, "rtsp://"))
1805       stream->conninfo.location = g_strdup (control_url);
1806     else {
1807       const gchar *base;
1808       gboolean has_slash;
1809
1810       if (g_strcmp0 (control_url, "*") == 0)
1811         control_url = "";
1812
1813       base = get_aggregate_control (src);
1814
1815       /* check if the base ends or control starts with / */
1816       has_slash = g_str_has_prefix (control_url, "/");
1817       has_slash = has_slash || g_str_has_suffix (base, "/");
1818
1819       /* concatenate the two strings, insert / when not present */
1820       stream->conninfo.location =
1821           g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1822     }
1823   }
1824   GST_DEBUG_OBJECT (src, " setup: %s",
1825       GST_STR_NULL (stream->conninfo.location));
1826
1827   /* we keep track of all streams */
1828   src->streams = g_list_append (src->streams, stream);
1829
1830   return stream;
1831
1832   /* ERRORS */
1833 }
1834
1835 static void
1836 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1837 {
1838   gint i;
1839
1840   GST_DEBUG_OBJECT (src, "free stream %p", stream);
1841
1842   g_array_free (stream->ptmap, TRUE);
1843
1844   g_free (stream->destination);
1845   g_free (stream->control_url);
1846   g_free (stream->conninfo.location);
1847   g_free (stream->stream_id);
1848
1849   for (i = 0; i < 2; i++) {
1850     if (stream->udpsrc[i]) {
1851       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1852       gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1853       gst_object_unref (stream->udpsrc[i]);
1854     }
1855     if (stream->channelpad[i])
1856       gst_object_unref (stream->channelpad[i]);
1857
1858     if (stream->udpsink[i]) {
1859       gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1860       gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1861       gst_object_unref (stream->udpsink[i]);
1862     }
1863   }
1864   if (stream->fakesrc) {
1865     gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1866     gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1867     gst_object_unref (stream->fakesrc);
1868   }
1869   if (stream->srcpad) {
1870     gst_pad_set_active (stream->srcpad, FALSE);
1871     if (stream->added)
1872       gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1873   }
1874   if (stream->srtpenc)
1875     gst_object_unref (stream->srtpenc);
1876   if (stream->srtpdec)
1877     gst_object_unref (stream->srtpdec);
1878   if (stream->srtcpparams)
1879     gst_caps_unref (stream->srtcpparams);
1880   if (stream->mikey)
1881     gst_mikey_message_unref (stream->mikey);
1882   if (stream->rtcppad)
1883     gst_object_unref (stream->rtcppad);
1884   if (stream->session)
1885     g_object_unref (stream->session);
1886   if (stream->rtx_pt_map)
1887     gst_structure_free (stream->rtx_pt_map);
1888
1889   g_mutex_clear (&stream->conninfo.send_lock);
1890   g_mutex_clear (&stream->conninfo.recv_lock);
1891
1892   g_free (stream);
1893 }
1894
1895 static void
1896 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1897 {
1898   GList *walk;
1899
1900   GST_DEBUG_OBJECT (src, "cleanup");
1901
1902   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1903     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1904
1905     gst_rtspsrc_stream_free (src, stream);
1906   }
1907   g_list_free (src->streams);
1908   src->streams = NULL;
1909   if (src->manager) {
1910     if (src->manager_sig_id) {
1911       g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1912       src->manager_sig_id = 0;
1913     }
1914     gst_element_set_state (src->manager, GST_STATE_NULL);
1915     gst_bin_remove (GST_BIN_CAST (src), src->manager);
1916     src->manager = NULL;
1917   }
1918   if (src->props)
1919     gst_structure_free (src->props);
1920   src->props = NULL;
1921
1922   g_free (src->content_base);
1923   src->content_base = NULL;
1924
1925   g_free (src->control);
1926   src->control = NULL;
1927
1928   if (src->range)
1929     gst_rtsp_range_free (src->range);
1930   src->range = NULL;
1931
1932   /* don't clear the SDP when it was used in the url */
1933   if (src->sdp && !src->from_sdp) {
1934     gst_sdp_message_free (src->sdp);
1935     src->sdp = NULL;
1936   }
1937
1938   src->need_segment = FALSE;
1939
1940   if (src->provided_clock) {
1941     gst_object_unref (src->provided_clock);
1942     src->provided_clock = NULL;
1943   }
1944 }
1945
1946 static gboolean
1947 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
1948     gint * rtpport, gint * rtcpport)
1949 {
1950   GstRTSPSrc *src;
1951   GstStateChangeReturn ret;
1952   GstElement *udpsrc0, *udpsrc1;
1953   gint tmp_rtp, tmp_rtcp;
1954   guint count;
1955   const gchar *host;
1956
1957   src = stream->parent;
1958
1959   udpsrc0 = NULL;
1960   udpsrc1 = NULL;
1961   count = 0;
1962
1963   /* Start at next port */
1964   tmp_rtp = src->next_port_num;
1965
1966   if (stream->is_ipv6)
1967     host = "udp://[::0]";
1968   else
1969     host = "udp://0.0.0.0";
1970
1971   /* try to allocate 2 UDP ports, the RTP port should be an even
1972    * number and the RTCP port should be the next (uneven) port */
1973 again:
1974
1975   if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
1976       tmp_rtp >= src->client_port_range.max)
1977     goto no_ports;
1978
1979   udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1980   if (udpsrc0 == NULL)
1981     goto no_udp_protocol;
1982   g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
1983
1984   if (src->udp_buffer_size != 0)
1985     g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
1986         NULL);
1987
1988   ret = gst_element_set_state (udpsrc0, GST_STATE_READY);
1989   if (ret == GST_STATE_CHANGE_FAILURE) {
1990     if (tmp_rtp != 0) {
1991       GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
1992
1993       tmp_rtp += 2;
1994       if (++count > src->retry)
1995         goto no_ports;
1996
1997       GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1998       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1999       gst_object_unref (udpsrc0);
2000       udpsrc0 = NULL;
2001
2002       GST_DEBUG_OBJECT (src, "retry %d", count);
2003       goto again;
2004     }
2005     goto no_udp_protocol;
2006   }
2007
2008   g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
2009   GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
2010
2011   /* check if port is even */
2012   if ((tmp_rtp & 0x01) != 0) {
2013     /* port not even, close and allocate another */
2014     if (++count > src->retry)
2015       goto no_ports;
2016
2017     GST_DEBUG_OBJECT (src, "RTP port not even");
2018
2019     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2020     gst_element_set_state (udpsrc0, GST_STATE_NULL);
2021     gst_object_unref (udpsrc0);
2022     udpsrc0 = NULL;
2023
2024     GST_DEBUG_OBJECT (src, "retry %d", count);
2025     tmp_rtp++;
2026     goto again;
2027   }
2028
2029   /* allocate port+1 for RTCP now */
2030   udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
2031   if (udpsrc1 == NULL)
2032     goto no_udp_rtcp_protocol;
2033
2034   /* set port */
2035   tmp_rtcp = tmp_rtp + 1;
2036   if (src->client_port_range.max > 0 && tmp_rtcp > src->client_port_range.max)
2037     goto no_ports;
2038
2039   g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
2040
2041   GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
2042   ret = gst_element_set_state (udpsrc1, GST_STATE_READY);
2043   /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
2044   if (ret == GST_STATE_CHANGE_FAILURE) {
2045     GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
2046
2047     if (++count > src->retry)
2048       goto no_ports;
2049
2050     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
2051     gst_element_set_state (udpsrc0, GST_STATE_NULL);
2052     gst_object_unref (udpsrc0);
2053     udpsrc0 = NULL;
2054
2055     GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
2056     gst_element_set_state (udpsrc1, GST_STATE_NULL);
2057     gst_object_unref (udpsrc1);
2058     udpsrc1 = NULL;
2059
2060     tmp_rtp += 2;
2061     GST_DEBUG_OBJECT (src, "retry %d", count);
2062     goto again;
2063   }
2064
2065   /* all fine, do port check */
2066   g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
2067   g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
2068
2069   /* this should not happen... */
2070   if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
2071     goto port_error;
2072
2073   /* we keep these elements, we configure all in configure_transport when the
2074    * server told us to really use the UDP ports. */
2075   stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
2076   stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
2077   gst_element_set_locked_state (stream->udpsrc[0], TRUE);
2078   gst_element_set_locked_state (stream->udpsrc[1], TRUE);
2079
2080   /* keep track of next available port number when we have a range
2081    * configured */
2082   if (src->next_port_num != 0)
2083     src->next_port_num = tmp_rtcp + 1;
2084
2085   return TRUE;
2086
2087   /* ERRORS */
2088 no_udp_protocol:
2089   {
2090     GST_DEBUG_OBJECT (src, "could not get UDP source");
2091     goto cleanup;
2092   }
2093 no_ports:
2094   {
2095     GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
2096         count);
2097     goto cleanup;
2098   }
2099 no_udp_rtcp_protocol:
2100   {
2101     GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
2102     goto cleanup;
2103   }
2104 port_error:
2105   {
2106     GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
2107         tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
2108     goto cleanup;
2109   }
2110 cleanup:
2111   {
2112     if (udpsrc0) {
2113       gst_element_set_state (udpsrc0, GST_STATE_NULL);
2114       gst_object_unref (udpsrc0);
2115     }
2116     if (udpsrc1) {
2117       gst_element_set_state (udpsrc1, GST_STATE_NULL);
2118       gst_object_unref (udpsrc1);
2119     }
2120     return FALSE;
2121   }
2122 }
2123
2124 static void
2125 gst_rtspsrc_set_state (GstRTSPSrc * src, GstState state)
2126 {
2127   GList *walk;
2128
2129   if (src->manager)
2130     gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
2131
2132   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2133     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2134     gint i;
2135
2136     for (i = 0; i < 2; i++) {
2137       if (stream->udpsrc[i])
2138         gst_element_set_state (stream->udpsrc[i], state);
2139     }
2140   }
2141 }
2142
2143 static void
2144 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
2145 {
2146   GstEvent *event;
2147   gint cmd;
2148   GstState state;
2149
2150   if (flush) {
2151     event = gst_event_new_flush_start ();
2152     GST_DEBUG_OBJECT (src, "start flush");
2153     cmd = CMD_WAIT;
2154     state = GST_STATE_PAUSED;
2155   } else {
2156     event = gst_event_new_flush_stop (FALSE);
2157     GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
2158     cmd = CMD_LOOP;
2159     if (playing)
2160       state = GST_STATE_PLAYING;
2161     else
2162       state = GST_STATE_PAUSED;
2163   }
2164   gst_rtspsrc_push_event (src, event);
2165   gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
2166   gst_rtspsrc_set_state (src, state);
2167 }
2168
2169 static GstRTSPResult
2170 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
2171     GstRTSPMessage * message, GTimeVal * timeout)
2172 {
2173   GstRTSPResult ret;
2174
2175   if (conninfo->connection) {
2176     g_mutex_lock (&conninfo->send_lock);
2177     ret = gst_rtsp_connection_send (conninfo->connection, message, timeout);
2178     g_mutex_unlock (&conninfo->send_lock);
2179   } else {
2180     ret = GST_RTSP_ERROR;
2181   }
2182
2183   return ret;
2184 }
2185
2186 static GstRTSPResult
2187 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
2188     GstRTSPMessage * message, GTimeVal * timeout)
2189 {
2190   GstRTSPResult ret;
2191
2192   if (conninfo->connection) {
2193     g_mutex_lock (&conninfo->recv_lock);
2194     ret = gst_rtsp_connection_receive (conninfo->connection, message, timeout);
2195     g_mutex_unlock (&conninfo->recv_lock);
2196   } else {
2197     ret = GST_RTSP_ERROR;
2198   }
2199
2200   return ret;
2201 }
2202
2203 static void
2204 gst_rtspsrc_get_position (GstRTSPSrc * src)
2205 {
2206   GstQuery *query;
2207   GList *walk;
2208
2209   query = gst_query_new_position (GST_FORMAT_TIME);
2210   /*  should be known somewhere down the stream (e.g. jitterbuffer) */
2211   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2212     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2213     GstFormat fmt;
2214     gint64 pos;
2215
2216     if (stream->srcpad) {
2217       if (gst_pad_query (stream->srcpad, query)) {
2218         gst_query_parse_position (query, &fmt, &pos);
2219         GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
2220             GST_TIME_ARGS (pos));
2221         src->last_pos = pos;
2222         goto out;
2223       }
2224     }
2225   }
2226
2227   src->last_pos = 0;
2228
2229 out:
2230
2231   gst_query_unref (query);
2232 }
2233
2234 static gboolean
2235 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
2236 {
2237   gdouble rate;
2238   GstFormat format;
2239   GstSeekFlags flags;
2240   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2241   gint64 cur, stop;
2242   gboolean flush, skip;
2243   gboolean update;
2244   gboolean playing;
2245   GstSegment seeksegment = { 0, };
2246   GList *walk;
2247   const gchar *seek_style = NULL;
2248
2249   if (event) {
2250     GST_DEBUG_OBJECT (src, "doing seek with event");
2251
2252     gst_event_parse_seek (event, &rate, &format, &flags,
2253         &cur_type, &cur, &stop_type, &stop);
2254
2255     /* no negative rates yet */
2256     if (rate < 0.0)
2257       goto negative_rate;
2258
2259     /* we need TIME format */
2260     if (format != src->segment.format)
2261       goto no_format;
2262   } else {
2263     GST_DEBUG_OBJECT (src, "doing seek without event");
2264     flags = 0;
2265     cur_type = GST_SEEK_TYPE_SET;
2266     stop_type = GST_SEEK_TYPE_SET;
2267   }
2268
2269   /* get flush flag */
2270   flush = flags & GST_SEEK_FLAG_FLUSH;
2271   skip = flags & GST_SEEK_FLAG_SKIP;
2272
2273   /* now we need to make sure the streaming thread is stopped. We do this by
2274    * either sending a FLUSH_START event downstream which will cause the
2275    * streaming thread to stop with a WRONG_STATE.
2276    * For a non-flushing seek we simply pause the task, which will happen as soon
2277    * as it completes one iteration (and thus might block when the sink is
2278    * blocking in preroll). */
2279   if (flush) {
2280     GST_DEBUG_OBJECT (src, "starting flush");
2281     gst_rtspsrc_flush (src, TRUE, FALSE);
2282   } else {
2283     if (src->task) {
2284       gst_task_pause (src->task);
2285     }
2286   }
2287
2288   /* we should now be able to grab the streaming thread because we stopped it
2289    * with the above flush/pause code */
2290   GST_RTSP_STREAM_LOCK (src);
2291
2292   GST_DEBUG_OBJECT (src, "stopped streaming");
2293
2294   /* stop flushing the rtsp connection so we can send PAUSE/PLAY below */
2295   gst_rtspsrc_connection_flush (src, FALSE);
2296
2297   /* copy segment, we need this because we still need the old
2298    * segment when we close the current segment. */
2299   memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2300
2301   /* configure the seek parameters in the seeksegment. We will then have the
2302    * right values in the segment to perform the seek */
2303   if (event) {
2304     GST_DEBUG_OBJECT (src, "configuring seek");
2305     gst_segment_do_seek (&seeksegment, rate, format, flags,
2306         cur_type, cur, stop_type, stop, &update);
2307   }
2308
2309   /* figure out the last position we need to play. If it's configured (stop !=
2310    * -1), use that, else we play until the total duration of the file */
2311   if ((stop = seeksegment.stop) == -1)
2312     stop = seeksegment.duration;
2313
2314   /* if we were playing, pause first */
2315   playing = (src->state == GST_RTSP_STATE_PLAYING);
2316   if (playing) {
2317     /* obtain current position in case seek fails */
2318     gst_rtspsrc_get_position (src);
2319     gst_rtspsrc_pause (src, FALSE);
2320   }
2321   src->skip = skip;
2322
2323   src->state = GST_RTSP_STATE_SEEKING;
2324
2325   /* PLAY will add the range header now. */
2326   src->need_range = TRUE;
2327
2328   /* prepare for streaming again */
2329   if (flush) {
2330     /* if we started flush, we stop now */
2331     GST_DEBUG_OBJECT (src, "stopping flush");
2332     gst_rtspsrc_flush (src, FALSE, playing);
2333   }
2334
2335   /* now we did the seek and can activate the new segment values */
2336   memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2337
2338   /* if we're doing a segment seek, post a SEGMENT_START message */
2339   if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2340     gst_element_post_message (GST_ELEMENT_CAST (src),
2341         gst_message_new_segment_start (GST_OBJECT_CAST (src),
2342             src->segment.format, src->segment.position));
2343   }
2344
2345   /* now create the newsegment */
2346   GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2347       " to %" G_GINT64_FORMAT, src->segment.position, stop);
2348
2349   /* mark discont */
2350   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2351   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2352     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2353     stream->discont = TRUE;
2354   }
2355
2356   /* and continue playing if needed */
2357   GST_OBJECT_LOCK (src);
2358   playing = (GST_STATE_PENDING (src) == GST_STATE_VOID_PENDING
2359       && GST_STATE (src) == GST_STATE_PLAYING)
2360       || (GST_STATE_PENDING (src) == GST_STATE_PLAYING);
2361   GST_OBJECT_UNLOCK (src);
2362
2363   if (src->version >= GST_RTSP_VERSION_2_0) {
2364     if (flags & GST_SEEK_FLAG_ACCURATE)
2365       seek_style = "RAP";
2366     else if (flags & GST_SEEK_FLAG_KEY_UNIT)
2367       seek_style = "CoRAP";
2368     else if (flags & GST_SEEK_FLAG_KEY_UNIT
2369         && flags & GST_SEEK_FLAG_SNAP_BEFORE)
2370       seek_style = "First-Prior";
2371     else if (flags & GST_SEEK_FLAG_KEY_UNIT && flags & GST_SEEK_FLAG_SNAP_AFTER)
2372       seek_style = "Next";
2373   }
2374
2375   if (playing)
2376     gst_rtspsrc_play (src, &seeksegment, FALSE, seek_style);
2377
2378   GST_RTSP_STREAM_UNLOCK (src);
2379
2380   return TRUE;
2381
2382   /* ERRORS */
2383 negative_rate:
2384   {
2385     GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2386     return FALSE;
2387   }
2388 no_format:
2389   {
2390     GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2391     return FALSE;
2392   }
2393 }
2394
2395 static gboolean
2396 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2397     GstEvent * event)
2398 {
2399   GstRTSPSrc *src;
2400   gboolean res = TRUE;
2401   gboolean forward;
2402
2403   src = GST_RTSPSRC_CAST (parent);
2404
2405   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2406       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2407
2408   switch (GST_EVENT_TYPE (event)) {
2409     case GST_EVENT_SEEK:
2410       res = gst_rtspsrc_perform_seek (src, event);
2411       forward = FALSE;
2412       break;
2413     case GST_EVENT_QOS:
2414     case GST_EVENT_NAVIGATION:
2415     case GST_EVENT_LATENCY:
2416     default:
2417       forward = TRUE;
2418       break;
2419   }
2420   if (forward) {
2421     GstPad *target;
2422
2423     if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2424       res = gst_pad_send_event (target, event);
2425       gst_object_unref (target);
2426     } else {
2427       gst_event_unref (event);
2428     }
2429   } else {
2430     gst_event_unref (event);
2431   }
2432
2433   return res;
2434 }
2435
2436 static gboolean
2437 gst_rtspsrc_handle_src_sink_event (GstPad * pad, GstObject * parent,
2438     GstEvent * event)
2439 {
2440   GstRTSPStream *stream;
2441
2442   stream = gst_pad_get_element_private (pad);
2443
2444   switch (GST_EVENT_TYPE (event)) {
2445     case GST_EVENT_STREAM_START:{
2446       const gchar *upstream_id;
2447       gchar *stream_id;
2448
2449       gst_event_parse_stream_start (event, &upstream_id);
2450       stream_id = g_strdup_printf ("%s/%s", upstream_id, stream->stream_id);
2451
2452       gst_event_unref (event);
2453       event = gst_event_new_stream_start (stream_id);
2454       break;
2455     }
2456     default:
2457       break;
2458   }
2459
2460   return gst_pad_push_event (stream->srcpad, event);
2461 }
2462
2463 /* this is the final event function we receive on the internal source pad when
2464  * we deal with TCP connections */
2465 static gboolean
2466 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2467     GstEvent * event)
2468 {
2469   gboolean res;
2470
2471   GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2472
2473   switch (GST_EVENT_TYPE (event)) {
2474     case GST_EVENT_SEEK:
2475     case GST_EVENT_QOS:
2476     case GST_EVENT_NAVIGATION:
2477     case GST_EVENT_LATENCY:
2478     default:
2479       gst_event_unref (event);
2480       res = TRUE;
2481       break;
2482   }
2483   return res;
2484 }
2485
2486 /* this is the final query function we receive on the internal source pad when
2487  * we deal with TCP connections */
2488 static gboolean
2489 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2490     GstQuery * query)
2491 {
2492   GstRTSPSrc *src;
2493   gboolean res = TRUE;
2494
2495   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2496
2497   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2498       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2499
2500   switch (GST_QUERY_TYPE (query)) {
2501     case GST_QUERY_POSITION:
2502     {
2503       /* no idea */
2504       break;
2505     }
2506     case GST_QUERY_DURATION:
2507     {
2508       GstFormat format;
2509
2510       gst_query_parse_duration (query, &format, NULL);
2511
2512       switch (format) {
2513         case GST_FORMAT_TIME:
2514           gst_query_set_duration (query, format, src->segment.duration);
2515           break;
2516         default:
2517           res = FALSE;
2518           break;
2519       }
2520       break;
2521     }
2522     case GST_QUERY_LATENCY:
2523     {
2524       /* we are live with a min latency of 0 and unlimited max latency, this
2525        * result will be updated by the session manager if there is any. */
2526       gst_query_set_latency (query, TRUE, 0, -1);
2527       break;
2528     }
2529     default:
2530       break;
2531   }
2532
2533   return res;
2534 }
2535
2536 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2537 static gboolean
2538 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2539     GstQuery * query)
2540 {
2541   GstRTSPSrc *src;
2542   gboolean res = FALSE;
2543
2544   src = GST_RTSPSRC_CAST (parent);
2545
2546   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2547       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2548
2549   switch (GST_QUERY_TYPE (query)) {
2550     case GST_QUERY_DURATION:
2551     {
2552       GstFormat format;
2553
2554       gst_query_parse_duration (query, &format, NULL);
2555
2556       switch (format) {
2557         case GST_FORMAT_TIME:
2558           gst_query_set_duration (query, format, src->segment.duration);
2559           res = TRUE;
2560           break;
2561         default:
2562           break;
2563       }
2564       break;
2565     }
2566     case GST_QUERY_SEEKING:
2567     {
2568       GstFormat format;
2569
2570       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2571       if (format == GST_FORMAT_TIME) {
2572         gboolean seekable =
2573             src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2574         GstClockTime start = 0, duration = src->segment.duration;
2575
2576         /* seeking without duration is unlikely */
2577         seekable = seekable && src->seekable >= 0.0 && src->segment.duration &&
2578             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2579
2580         if (seekable) {
2581           if (src->seekable > 0.0) {
2582             start = src->last_pos - src->seekable * GST_SECOND;
2583           } else {
2584             /* src->seekable == 0 means that we can only seek to 0 */
2585             start = 0;
2586             duration = 0;
2587           }
2588         }
2589
2590         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, start,
2591             duration);
2592         res = TRUE;
2593       }
2594       break;
2595     }
2596     case GST_QUERY_URI:
2597     {
2598       gchar *uri;
2599
2600       uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2601       if (uri != NULL) {
2602         gst_query_set_uri (query, uri);
2603         g_free (uri);
2604         res = TRUE;
2605       }
2606       break;
2607     }
2608     default:
2609     {
2610       GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2611
2612       /* forward the query to the proxy target pad */
2613       if (target) {
2614         res = gst_pad_query (target, query);
2615         gst_object_unref (target);
2616       }
2617       break;
2618     }
2619   }
2620
2621   return res;
2622 }
2623
2624 /* callback for RTCP messages to be sent to the server when operating in TCP
2625  * mode. */
2626 static GstFlowReturn
2627 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2628 {
2629   GstRTSPSrc *src;
2630   GstRTSPStream *stream;
2631   GstFlowReturn res = GST_FLOW_OK;
2632   GstMapInfo map;
2633   guint8 *data;
2634   guint size;
2635   GstRTSPResult ret;
2636   GstRTSPMessage message = { 0 };
2637   GstRTSPConnInfo *conninfo;
2638
2639   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2640   src = stream->parent;
2641
2642   gst_buffer_map (buffer, &map, GST_MAP_READ);
2643   size = map.size;
2644   data = map.data;
2645
2646   gst_rtsp_message_init_data (&message, stream->channel[1]);
2647
2648   /* lend the body data to the message */
2649   gst_rtsp_message_take_body (&message, data, size);
2650
2651   if (stream->conninfo.connection)
2652     conninfo = &stream->conninfo;
2653   else
2654     conninfo = &src->conninfo;
2655
2656   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2657   ret = gst_rtspsrc_connection_send (src, conninfo, &message, NULL);
2658   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2659
2660   /* and steal it away again because we will free it when unreffing the
2661    * buffer */
2662   gst_rtsp_message_steal_body (&message, &data, &size);
2663   gst_rtsp_message_unset (&message);
2664
2665   gst_buffer_unmap (buffer, &map);
2666   gst_buffer_unref (buffer);
2667
2668   return res;
2669 }
2670
2671 static GstPadProbeReturn
2672 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2673 {
2674   GstRTSPSrc *src = user_data;
2675
2676   GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2677       GST_DEBUG_PAD_NAME (pad));
2678
2679   /* activate the streams */
2680   GST_OBJECT_LOCK (src);
2681   if (!src->need_activate)
2682     goto was_ok;
2683
2684   src->need_activate = FALSE;
2685   GST_OBJECT_UNLOCK (src);
2686
2687   gst_rtspsrc_activate_streams (src);
2688
2689   return GST_PAD_PROBE_OK;
2690
2691 was_ok:
2692   {
2693     GST_OBJECT_UNLOCK (src);
2694     return GST_PAD_PROBE_OK;
2695   }
2696 }
2697
2698 static gboolean
2699 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
2700 {
2701   GstPad *gpad = GST_PAD_CAST (user_data);
2702
2703   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
2704   gst_pad_store_sticky_event (gpad, *event);
2705
2706   return TRUE;
2707 }
2708
2709 /* this callback is called when the session manager generated a new src pad with
2710  * payloaded RTP packets. We simply ghost the pad here. */
2711 static void
2712 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2713 {
2714   gchar *name;
2715   GstPadTemplate *template;
2716   gint id, ssrc, pt;
2717   GList *ostreams;
2718   GstRTSPStream *stream;
2719   gboolean all_added;
2720   GstPad *internal_src;
2721
2722   GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2723
2724   GST_RTSP_STATE_LOCK (src);
2725   /* find stream */
2726   name = gst_object_get_name (GST_OBJECT_CAST (pad));
2727   if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2728     goto unknown_stream;
2729
2730   GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2731
2732   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2733   if (stream == NULL)
2734     goto unknown_stream;
2735
2736   /* save SSRC */
2737   stream->ssrc = ssrc;
2738
2739   /* we'll add it later see below */
2740   stream->added = TRUE;
2741
2742   /* check if we added all streams */
2743   all_added = TRUE;
2744   for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
2745     GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
2746
2747     GST_DEBUG_OBJECT (src, "stream %p, container %d, added %d, setup %d",
2748         ostream, ostream->container, ostream->added, ostream->setup);
2749
2750     /* if we find a stream for which we did a setup that is not added, we
2751      * need to wait some more */
2752     if (ostream->setup && !ostream->added) {
2753       all_added = FALSE;
2754       break;
2755     }
2756   }
2757   GST_RTSP_STATE_UNLOCK (src);
2758
2759   /* create a new pad we will use to stream to */
2760   template = gst_static_pad_template_get (&rtptemplate);
2761   stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2762   gst_object_unref (template);
2763   g_free (name);
2764
2765   /* We intercept and modify the stream start event */
2766   internal_src =
2767       GST_PAD (gst_proxy_pad_get_internal (GST_PROXY_PAD (stream->srcpad)));
2768   gst_pad_set_element_private (internal_src, stream);
2769   gst_pad_set_event_function (internal_src, gst_rtspsrc_handle_src_sink_event);
2770   gst_object_unref (internal_src);
2771
2772   gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2773   gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2774   gst_pad_set_active (stream->srcpad, TRUE);
2775   gst_pad_sticky_events_foreach (pad, copy_sticky_events, stream->srcpad);
2776   gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2777
2778   if (all_added) {
2779     GST_DEBUG_OBJECT (src, "We added all streams");
2780     /* when we get here, all stream are added and we can fire the no-more-pads
2781      * signal. */
2782     gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2783   }
2784
2785   return;
2786
2787   /* ERRORS */
2788 unknown_stream:
2789   {
2790     GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2791     GST_RTSP_STATE_UNLOCK (src);
2792     g_free (name);
2793     return;
2794   }
2795 }
2796
2797 static GstCaps *
2798 stream_get_caps_for_pt (GstRTSPStream * stream, guint pt)
2799 {
2800   guint i, len;
2801
2802   len = stream->ptmap->len;
2803   for (i = 0; i < len; i++) {
2804     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
2805     if (item->pt == pt)
2806       return item->caps;
2807   }
2808   return NULL;
2809 }
2810
2811 static GstCaps *
2812 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2813 {
2814   GstRTSPStream *stream;
2815   GstCaps *caps;
2816
2817   GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2818
2819   GST_RTSP_STATE_LOCK (src);
2820   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2821   if (!stream)
2822     goto unknown_stream;
2823
2824   if ((caps = stream_get_caps_for_pt (stream, pt)))
2825     gst_caps_ref (caps);
2826   GST_RTSP_STATE_UNLOCK (src);
2827
2828   return caps;
2829
2830 unknown_stream:
2831   {
2832     GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2833     GST_RTSP_STATE_UNLOCK (src);
2834     return NULL;
2835   }
2836 }
2837
2838 static void
2839 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2840 {
2841   GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2842
2843   if (stream->eos)
2844     goto was_eos;
2845
2846   stream->eos = TRUE;
2847   gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
2848   return;
2849
2850   /* ERRORS */
2851 was_eos:
2852   {
2853     GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2854     return;
2855   }
2856 }
2857
2858 static void
2859 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2860 {
2861   GstRTSPSrc *src = stream->parent;
2862   guint ssrc;
2863
2864   g_object_get (source, "ssrc", &ssrc, NULL);
2865
2866   GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
2867       ssrc, stream->ssrc, stream->id);
2868
2869   if (ssrc == stream->ssrc)
2870     gst_rtspsrc_do_stream_eos (src, stream);
2871 }
2872
2873 static void
2874 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2875 {
2876   GstRTSPSrc *src = stream->parent;
2877   guint ssrc;
2878
2879   g_object_get (source, "ssrc", &ssrc, NULL);
2880
2881   GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
2882       ssrc, stream->ssrc, stream->id);
2883
2884   if (ssrc == stream->ssrc)
2885     gst_rtspsrc_do_stream_eos (src, stream);
2886 }
2887
2888 static void
2889 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2890 {
2891   GstRTSPStream *stream;
2892
2893   GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2894
2895   /* get stream for session */
2896   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2897   if (stream) {
2898     gst_rtspsrc_do_stream_eos (src, stream);
2899   }
2900 }
2901
2902 static void
2903 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2904 {
2905   GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2906       stream->id);
2907 }
2908
2909 static void
2910 set_manager_buffer_mode (GstRTSPSrc * src)
2911 {
2912   GObjectClass *klass;
2913
2914   if (src->manager == NULL)
2915     return;
2916
2917   klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2918
2919   if (!g_object_class_find_property (klass, "buffer-mode"))
2920     return;
2921
2922   if (src->buffer_mode != BUFFER_MODE_AUTO) {
2923     g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2924
2925     return;
2926   }
2927
2928   GST_DEBUG_OBJECT (src,
2929       "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
2930
2931   if (src->provided_clock) {
2932     GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
2933
2934     if (clock == src->provided_clock) {
2935       GST_DEBUG_OBJECT (src, "selected synced");
2936       g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
2937
2938       if (clock)
2939         gst_object_unref (clock);
2940
2941       return;
2942     }
2943
2944     /* Otherwise fall-through and use another buffer mode */
2945     if (clock)
2946       gst_object_unref (clock);
2947   }
2948
2949   GST_DEBUG_OBJECT (src, "auto buffering mode");
2950   if (src->use_buffering) {
2951     GST_DEBUG_OBJECT (src, "selected buffer");
2952     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
2953   } else {
2954     GST_DEBUG_OBJECT (src, "selected slave");
2955     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2956   }
2957 }
2958
2959 static GstCaps *
2960 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
2961 {
2962   guint i;
2963   GstCaps *caps;
2964   GstMIKEYMessage *msg = stream->mikey;
2965
2966   GST_DEBUG ("request key SSRC %u", ssrc);
2967
2968   caps = gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
2969   caps = gst_caps_make_writable (caps);
2970
2971   /* parse crypto sessions and look for the SSRC rollover counter */
2972   msg = stream->mikey;
2973   for (i = 0; msg && i < gst_mikey_message_get_n_cs (msg); i++) {
2974     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
2975
2976     if (ssrc == map->ssrc) {
2977       gst_caps_set_simple (caps, "roc", G_TYPE_UINT, map->roc, NULL);
2978       break;
2979     }
2980   }
2981
2982   return caps;
2983 }
2984
2985 static GstElement *
2986 request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
2987 {
2988   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
2989   if (stream->id != session)
2990     return NULL;
2991
2992   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
2993       stream->profile != GST_RTSP_PROFILE_SAVPF)
2994     return NULL;
2995
2996   if (stream->srtpdec == NULL) {
2997     gchar *name;
2998
2999     name = g_strdup_printf ("srtpdec_%u", session);
3000     stream->srtpdec = gst_element_factory_make ("srtpdec", name);
3001     g_free (name);
3002
3003     if (stream->srtpdec == NULL) {
3004       GST_ELEMENT_ERROR (stream->parent, CORE, MISSING_PLUGIN, (NULL),
3005           ("no srtpdec element present!"));
3006       return NULL;
3007     }
3008     g_signal_connect (stream->srtpdec, "request-key",
3009         (GCallback) request_key, stream);
3010   }
3011   return gst_object_ref (stream->srtpdec);
3012 }
3013
3014 static GstElement *
3015 request_rtcp_encoder (GstElement * rtpbin, guint session,
3016     GstRTSPStream * stream)
3017 {
3018   gchar *name;
3019   GstPad *pad;
3020
3021   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3022   if (stream->id != session)
3023     return NULL;
3024
3025   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3026       stream->profile != GST_RTSP_PROFILE_SAVPF)
3027     return NULL;
3028
3029   if (stream->srtpenc == NULL) {
3030     GstStructure *s;
3031
3032     name = g_strdup_printf ("srtpenc_%u", session);
3033     stream->srtpenc = gst_element_factory_make ("srtpenc", name);
3034     g_free (name);
3035
3036     if (stream->srtpenc == NULL) {
3037       GST_ELEMENT_ERROR (stream->parent, CORE, MISSING_PLUGIN, (NULL),
3038           ("no srtpenc element present!"));
3039       return NULL;
3040     }
3041
3042     /* get RTCP crypto parameters from caps */
3043     s = gst_caps_get_structure (stream->srtcpparams, 0);
3044     if (s) {
3045       GstBuffer *buf;
3046       const gchar *str;
3047       GType ciphertype, authtype;
3048       GValue rtcp_cipher = G_VALUE_INIT, rtcp_auth = G_VALUE_INIT;
3049
3050       ciphertype = g_type_from_name ("GstSrtpCipherType");
3051       authtype = g_type_from_name ("GstSrtpAuthType");
3052       g_value_init (&rtcp_cipher, ciphertype);
3053       g_value_init (&rtcp_auth, authtype);
3054
3055       str = gst_structure_get_string (s, "srtcp-cipher");
3056       gst_value_deserialize (&rtcp_cipher, str);
3057       str = gst_structure_get_string (s, "srtcp-auth");
3058       gst_value_deserialize (&rtcp_auth, str);
3059       gst_structure_get (s, "srtp-key", GST_TYPE_BUFFER, &buf, NULL);
3060
3061       g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-cipher",
3062           &rtcp_cipher);
3063       g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-auth",
3064           &rtcp_auth);
3065       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-cipher",
3066           &rtcp_cipher);
3067       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-auth",
3068           &rtcp_auth);
3069       g_object_set (stream->srtpenc, "key", buf, NULL);
3070
3071       g_value_unset (&rtcp_cipher);
3072       g_value_unset (&rtcp_auth);
3073       gst_buffer_unref (buf);
3074     }
3075   }
3076   name = g_strdup_printf ("rtcp_sink_%d", session);
3077   pad = gst_element_get_request_pad (stream->srtpenc, name);
3078   g_free (name);
3079   gst_object_unref (pad);
3080
3081   return gst_object_ref (stream->srtpenc);
3082 }
3083
3084 static GstElement *
3085 request_aux_receiver (GstElement * rtpbin, guint sessid, GstRTSPSrc * src)
3086 {
3087   GstElement *rtx, *bin;
3088   GstPad *pad;
3089   gchar *name;
3090   GstRTSPStream *stream;
3091
3092   stream = find_stream (src, &sessid, (gpointer) find_stream_by_id);
3093   if (!stream) {
3094     GST_WARNING_OBJECT (src, "Stream %u not found", sessid);
3095     return NULL;
3096   }
3097
3098   GST_INFO_OBJECT (src, "creating retransmision receiver for session %u "
3099       "with map %" GST_PTR_FORMAT, sessid, stream->rtx_pt_map);
3100   bin = gst_bin_new (NULL);
3101   rtx = gst_element_factory_make ("rtprtxreceive", NULL);
3102   g_object_set (rtx, "payload-type-map", stream->rtx_pt_map, NULL);
3103   gst_bin_add (GST_BIN (bin), rtx);
3104
3105   pad = gst_element_get_static_pad (rtx, "src");
3106   name = g_strdup_printf ("src_%u", sessid);
3107   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3108   g_free (name);
3109   gst_object_unref (pad);
3110
3111   pad = gst_element_get_static_pad (rtx, "sink");
3112   name = g_strdup_printf ("sink_%u", sessid);
3113   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3114   g_free (name);
3115   gst_object_unref (pad);
3116
3117   return bin;
3118 }
3119
3120 static void
3121 add_retransmission (GstRTSPSrc * src, GstRTSPTransport * transport)
3122 {
3123   GList *walk;
3124   guint signal_id;
3125   gboolean do_retransmission = FALSE;
3126
3127   if (transport->trans != GST_RTSP_TRANS_RTP)
3128     return;
3129   if (transport->profile != GST_RTSP_PROFILE_AVPF &&
3130       transport->profile != GST_RTSP_PROFILE_SAVPF)
3131     return;
3132
3133   signal_id = g_signal_lookup ("request-aux-receiver",
3134       G_OBJECT_TYPE (src->manager));
3135   /* there's already something connected */
3136   if (g_signal_handler_find (src->manager, G_SIGNAL_MATCH_ID, signal_id, 0,
3137           NULL, NULL, NULL) != 0) {
3138     GST_DEBUG_OBJECT (src, "Not adding RTX AUX element as "
3139         "\"request-aux-receiver\" signal is "
3140         "already used by the application");
3141     return;
3142   }
3143
3144   /* build the retransmission payload type map */
3145   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3146     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3147     gboolean do_retransmission_stream = FALSE;
3148     int i;
3149
3150     if (stream->rtx_pt_map)
3151       gst_structure_free (stream->rtx_pt_map);
3152     stream->rtx_pt_map = gst_structure_new_empty ("application/x-rtp-pt-map");
3153
3154     for (i = 0; i < stream->ptmap->len; i++) {
3155       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3156       GstStructure *s = gst_caps_get_structure (item->caps, 0);
3157       const gchar *encoding;
3158
3159       /* we only care about RTX streams */
3160       if ((encoding = gst_structure_get_string (s, "encoding-name"))
3161           && g_strcmp0 (encoding, "RTX") == 0) {
3162         const gchar *stream_pt_s;
3163         gint rtx_pt;
3164
3165         if (gst_structure_get_int (s, "payload", &rtx_pt)
3166             && (stream_pt_s = gst_structure_get_string (s, "apt"))) {
3167
3168           if (rtx_pt != 0) {
3169             gst_structure_set (stream->rtx_pt_map, stream_pt_s, G_TYPE_UINT,
3170                 rtx_pt, NULL);
3171             do_retransmission_stream = TRUE;
3172           }
3173         }
3174       }
3175     }
3176
3177     if (do_retransmission_stream) {
3178       GST_DEBUG_OBJECT (src, "built retransmission payload map for stream "
3179           "id %i: %" GST_PTR_FORMAT, stream->id, stream->rtx_pt_map);
3180       do_retransmission = TRUE;
3181     } else {
3182       GST_DEBUG_OBJECT (src, "no retransmission payload map for stream "
3183           "id %i", stream->id);
3184       gst_structure_free (stream->rtx_pt_map);
3185       stream->rtx_pt_map = NULL;
3186     }
3187   }
3188
3189   if (do_retransmission) {
3190     GST_DEBUG_OBJECT (src, "Enabling retransmissions");
3191
3192     g_object_set (src->manager, "do-retransmission", TRUE, NULL);
3193
3194     /* enable RFC4588 retransmission handling by setting rtprtxreceive
3195      * as the "aux" element of rtpbin */
3196     g_signal_connect (src->manager, "request-aux-receiver",
3197         (GCallback) request_aux_receiver, src);
3198   } else {
3199     GST_DEBUG_OBJECT (src,
3200         "Not enabling retransmissions as no stream had a retransmission payload map");
3201   }
3202 }
3203
3204 /* try to get and configure a manager */
3205 static gboolean
3206 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
3207     GstRTSPTransport * transport)
3208 {
3209   const gchar *manager;
3210   gchar *name;
3211   GstStateChangeReturn ret;
3212
3213   /* find a manager */
3214   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
3215     goto no_manager;
3216
3217   if (manager) {
3218     GST_DEBUG_OBJECT (src, "using manager %s", manager);
3219
3220     /* configure the manager */
3221     if (src->manager == NULL) {
3222       GObjectClass *klass;
3223
3224       if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
3225         /* fallback */
3226         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
3227           goto no_manager;
3228
3229         if (!manager)
3230           goto use_no_manager;
3231
3232         if (!(src->manager = gst_element_factory_make (manager, "manager")))
3233           goto manager_failed;
3234       }
3235
3236       /* we manage this element */
3237       gst_element_set_locked_state (src->manager, TRUE);
3238       gst_bin_add (GST_BIN_CAST (src), src->manager);
3239
3240       ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
3241       if (ret == GST_STATE_CHANGE_FAILURE)
3242         goto start_manager_failure;
3243
3244       g_object_set (src->manager, "latency", src->latency, NULL);
3245
3246       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3247
3248       if (g_object_class_find_property (klass, "ntp-sync")) {
3249         g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
3250       }
3251
3252       if (g_object_class_find_property (klass, "rfc7273-sync")) {
3253         g_object_set (src->manager, "rfc7273-sync", src->rfc7273_sync, NULL);
3254       }
3255
3256       if (src->use_pipeline_clock) {
3257         if (g_object_class_find_property (klass, "use-pipeline-clock")) {
3258           g_object_set (src->manager, "use-pipeline-clock", TRUE, NULL);
3259         }
3260       } else {
3261         if (g_object_class_find_property (klass, "ntp-time-source")) {
3262           g_object_set (src->manager, "ntp-time-source", src->ntp_time_source,
3263               NULL);
3264         }
3265       }
3266
3267       if (src->sdes && g_object_class_find_property (klass, "sdes")) {
3268         g_object_set (src->manager, "sdes", src->sdes, NULL);
3269       }
3270
3271       if (g_object_class_find_property (klass, "drop-on-latency")) {
3272         g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
3273             NULL);
3274       }
3275
3276       if (g_object_class_find_property (klass, "max-rtcp-rtp-time-diff")) {
3277         g_object_set (src->manager, "max-rtcp-rtp-time-diff",
3278             src->max_rtcp_rtp_time_diff, NULL);
3279       }
3280
3281       if (g_object_class_find_property (klass, "max-ts-offset-adjustment")) {
3282         g_object_set (src->manager, "max-ts-offset-adjustment",
3283             src->max_ts_offset_adjustment, NULL);
3284       }
3285
3286       if (g_object_class_find_property (klass, "max-ts-offset")) {
3287         gint64 max_ts_offset;
3288
3289         /* setting max-ts-offset in the manager has side effects so only do it
3290          * if the value differs */
3291         g_object_get (src->manager, "max-ts-offset", &max_ts_offset, NULL);
3292         if (max_ts_offset != src->max_ts_offset) {
3293           g_object_set (src->manager, "max-ts-offset", src->max_ts_offset,
3294               NULL);
3295         }
3296       }
3297
3298       /* buffer mode pauses are handled by adding offsets to buffer times,
3299        * but some depayloaders may have a hard time syncing output times
3300        * with such input times, e.g. container ones, most notably ASF */
3301       /* TODO alternatives are having an event that indicates these shifts,
3302        * or having rtsp extensions provide suggestion on buffer mode */
3303       /* valid duration implies not likely live pipeline,
3304        * so slaving in jitterbuffer does not make much sense
3305        * (and might mess things up due to bursts) */
3306       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
3307           src->segment.duration && stream->container) {
3308         src->use_buffering = TRUE;
3309       } else {
3310         src->use_buffering = FALSE;
3311       }
3312
3313       set_manager_buffer_mode (src);
3314
3315       /* connect to signals */
3316       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
3317           stream);
3318       src->manager_sig_id =
3319           g_signal_connect (src->manager, "pad-added",
3320           (GCallback) new_manager_pad, src);
3321       src->manager_ptmap_id =
3322           g_signal_connect (src->manager, "request-pt-map",
3323           (GCallback) request_pt_map, src);
3324
3325       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
3326           src);
3327
3328       g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
3329           src->manager);
3330
3331       if (src->do_retransmission)
3332         add_retransmission (src, transport);
3333     }
3334     g_signal_connect (src->manager, "request-rtp-decoder",
3335         (GCallback) request_rtp_decoder, stream);
3336     g_signal_connect (src->manager, "request-rtcp-decoder",
3337         (GCallback) request_rtp_decoder, stream);
3338     g_signal_connect (src->manager, "request-rtcp-encoder",
3339         (GCallback) request_rtcp_encoder, stream);
3340
3341     /* we stream directly to the manager, get some pads. Each RTSP stream goes
3342      * into a separate RTP session. */
3343     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
3344     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
3345     g_free (name);
3346     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
3347     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
3348     g_free (name);
3349
3350     /* now configure the bandwidth in the manager */
3351     if (g_signal_lookup ("get-internal-session",
3352             G_OBJECT_TYPE (src->manager)) != 0) {
3353       GObject *rtpsession;
3354
3355       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
3356           &rtpsession);
3357       if (rtpsession) {
3358         GstRTPProfile rtp_profile;
3359
3360         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
3361
3362         stream->session = rtpsession;
3363
3364         if (stream->as_bandwidth != -1) {
3365           GST_INFO_OBJECT (src, "setting AS: %f",
3366               (gdouble) (stream->as_bandwidth * 1000));
3367           g_object_set (rtpsession, "bandwidth",
3368               (gdouble) (stream->as_bandwidth * 1000), NULL);
3369         }
3370         if (stream->rr_bandwidth != -1) {
3371           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
3372           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
3373               NULL);
3374         }
3375         if (stream->rs_bandwidth != -1) {
3376           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
3377           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
3378               NULL);
3379         }
3380
3381         switch (stream->profile) {
3382           case GST_RTSP_PROFILE_AVPF:
3383             rtp_profile = GST_RTP_PROFILE_AVPF;
3384             break;
3385           case GST_RTSP_PROFILE_SAVP:
3386             rtp_profile = GST_RTP_PROFILE_SAVP;
3387             break;
3388           case GST_RTSP_PROFILE_SAVPF:
3389             rtp_profile = GST_RTP_PROFILE_SAVPF;
3390             break;
3391           case GST_RTSP_PROFILE_AVP:
3392           default:
3393             rtp_profile = GST_RTP_PROFILE_AVP;
3394             break;
3395         }
3396
3397         g_object_set (rtpsession, "rtp-profile", rtp_profile, NULL);
3398
3399         g_object_set (rtpsession, "probation", src->probation, NULL);
3400
3401         g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
3402
3403         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
3404             stream);
3405         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
3406             stream);
3407         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
3408             stream);
3409         g_signal_connect (rtpsession, "on-ssrc-active",
3410             (GCallback) on_ssrc_active, stream);
3411       }
3412     }
3413   }
3414
3415 use_no_manager:
3416   return TRUE;
3417
3418   /* ERRORS */
3419 no_manager:
3420   {
3421     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3422     return FALSE;
3423   }
3424 manager_failed:
3425   {
3426     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
3427     return FALSE;
3428   }
3429 start_manager_failure:
3430   {
3431     GST_DEBUG_OBJECT (src, "could not start session manager");
3432     return FALSE;
3433   }
3434 }
3435
3436 /* free the UDP sources allocated when negotiating a transport.
3437  * This function is called when the server negotiated to a transport where the
3438  * UDP sources are not needed anymore, such as TCP or multicast. */
3439 static void
3440 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
3441 {
3442   gint i;
3443
3444   for (i = 0; i < 2; i++) {
3445     if (stream->udpsrc[i]) {
3446       GST_DEBUG ("free UDP source %d for stream %p", i, stream);
3447       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
3448       gst_object_unref (stream->udpsrc[i]);
3449       stream->udpsrc[i] = NULL;
3450     }
3451   }
3452 }
3453
3454 /* for TCP, create pads to send and receive data to and from the manager and to
3455  * intercept various events and queries
3456  */
3457 static gboolean
3458 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
3459     GstRTSPTransport * transport, GstPad ** outpad)
3460 {
3461   gchar *name;
3462   GstPadTemplate *template;
3463   GstPad *pad0, *pad1;
3464
3465   /* configure for interleaved delivery, nothing needs to be done
3466    * here, the loop function will call the chain functions of the
3467    * session manager. */
3468   stream->channel[0] = transport->interleaved.min;
3469   stream->channel[1] = transport->interleaved.max;
3470   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
3471       stream->channel[0], stream->channel[1]);
3472
3473   /* we can remove the allocated UDP ports now */
3474   gst_rtspsrc_stream_free_udp (stream);
3475
3476   /* no session manager, send data to srcpad directly */
3477   if (!stream->channelpad[0]) {
3478     GST_DEBUG_OBJECT (src, "no manager, creating pad");
3479
3480     /* create a new pad we will use to stream to */
3481     name = g_strdup_printf ("stream_%u", stream->id);
3482     template = gst_static_pad_template_get (&rtptemplate);
3483     stream->channelpad[0] = gst_pad_new_from_template (template, name);
3484     gst_object_unref (template);
3485     g_free (name);
3486
3487     /* set caps and activate */
3488     gst_pad_use_fixed_caps (stream->channelpad[0]);
3489     gst_pad_set_active (stream->channelpad[0], TRUE);
3490
3491     *outpad = gst_object_ref (stream->channelpad[0]);
3492   } else {
3493     GST_DEBUG_OBJECT (src, "using manager source pad");
3494
3495     template = gst_static_pad_template_get (&anysrctemplate);
3496
3497     /* allocate pads for sending the channel data into the manager */
3498     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
3499     gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
3500     gst_object_unref (stream->channelpad[0]);
3501     stream->channelpad[0] = pad0;
3502     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
3503     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
3504     gst_pad_set_element_private (pad0, src);
3505     gst_pad_set_active (pad0, TRUE);
3506
3507     if (stream->channelpad[1]) {
3508       /* if we have a sinkpad for the other channel, create a pad and link to the
3509        * manager. */
3510       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
3511       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
3512       gst_pad_link_full (pad1, stream->channelpad[1],
3513           GST_PAD_LINK_CHECK_NOTHING);
3514       gst_object_unref (stream->channelpad[1]);
3515       stream->channelpad[1] = pad1;
3516       gst_pad_set_active (pad1, TRUE);
3517     }
3518     gst_object_unref (template);
3519   }
3520   /* setup RTCP transport back to the server if we have to. */
3521   if (src->manager && src->do_rtcp) {
3522     GstPad *pad;
3523
3524     template = gst_static_pad_template_get (&anysinktemplate);
3525
3526     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
3527     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
3528     gst_pad_set_element_private (stream->rtcppad, stream);
3529     gst_pad_set_active (stream->rtcppad, TRUE);
3530
3531     /* get session RTCP pad */
3532     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3533     pad = gst_element_get_request_pad (src->manager, name);
3534     g_free (name);
3535
3536     /* and link */
3537     if (pad) {
3538       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3539       gst_object_unref (pad);
3540     }
3541
3542     gst_object_unref (template);
3543   }
3544   return TRUE;
3545 }
3546
3547 static void
3548 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3549     GstRTSPTransport * transport, const gchar ** destination, gint * min,
3550     gint * max, guint * ttl)
3551 {
3552   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3553     if (destination) {
3554       if (!(*destination = transport->destination))
3555         *destination = stream->destination;
3556     }
3557     if (min && max) {
3558       /* transport first */
3559       *min = transport->port.min;
3560       *max = transport->port.max;
3561       if (*min == -1 && *max == -1) {
3562         /* then try from SDP */
3563         if (stream->port != 0) {
3564           *min = stream->port;
3565           *max = stream->port + 1;
3566         }
3567       }
3568     }
3569
3570     if (ttl) {
3571       if (!(*ttl = transport->ttl))
3572         *ttl = stream->ttl;
3573     }
3574   } else {
3575     if (destination) {
3576       /* first take the source, then the endpoint to figure out where to send
3577        * the RTCP. */
3578       if (!(*destination = transport->source)) {
3579         if (src->conninfo.connection)
3580           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3581         else if (stream->conninfo.connection)
3582           *destination =
3583               gst_rtsp_connection_get_ip (stream->conninfo.connection);
3584       }
3585     }
3586     if (min && max) {
3587       /* for unicast we only expect the ports here */
3588       *min = transport->server_port.min;
3589       *max = transport->server_port.max;
3590     }
3591   }
3592 }
3593
3594 /* For multicast create UDP sources and join the multicast group. */
3595 static gboolean
3596 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3597     GstRTSPTransport * transport, GstPad ** outpad)
3598 {
3599   gchar *uri;
3600   const gchar *destination;
3601   gint min, max;
3602
3603   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3604
3605   /* we can remove the allocated UDP ports now */
3606   gst_rtspsrc_stream_free_udp (stream);
3607
3608   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3609       &max, NULL);
3610
3611   /* we need a destination now */
3612   if (destination == NULL)
3613     goto no_destination;
3614
3615   /* we really need ports now or we won't be able to receive anything at all */
3616   if (min == -1 && max == -1)
3617     goto no_ports;
3618
3619   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3620       destination, min, max);
3621
3622   /* creating UDP source for RTP */
3623   if (min != -1) {
3624     uri = g_strdup_printf ("udp://%s:%d", destination, min);
3625     stream->udpsrc[0] =
3626         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3627     g_free (uri);
3628     if (stream->udpsrc[0] == NULL)
3629       goto no_element;
3630
3631     /* take ownership */
3632     gst_object_ref_sink (stream->udpsrc[0]);
3633
3634     if (src->udp_buffer_size != 0)
3635       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3636           src->udp_buffer_size, NULL);
3637
3638     if (src->multi_iface != NULL)
3639       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3640           src->multi_iface, NULL);
3641
3642     /* change state */
3643     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3644     gst_element_set_state (stream->udpsrc[0], GST_STATE_READY);
3645   }
3646
3647   /* creating another UDP source for RTCP */
3648   if (max != -1) {
3649     GstCaps *caps;
3650
3651     uri = g_strdup_printf ("udp://%s:%d", destination, max);
3652     stream->udpsrc[1] =
3653         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3654     g_free (uri);
3655     if (stream->udpsrc[1] == NULL)
3656       goto no_element;
3657
3658     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3659         stream->profile == GST_RTSP_PROFILE_SAVPF)
3660       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3661     else
3662       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3663     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3664     gst_caps_unref (caps);
3665
3666     /* take ownership */
3667     gst_object_ref_sink (stream->udpsrc[1]);
3668
3669     if (src->multi_iface != NULL)
3670       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3671           src->multi_iface, NULL);
3672
3673     gst_element_set_state (stream->udpsrc[1], GST_STATE_READY);
3674   }
3675   return TRUE;
3676
3677   /* ERRORS */
3678 no_element:
3679   {
3680     GST_DEBUG_OBJECT (src, "no UDP source element found");
3681     return FALSE;
3682   }
3683 no_destination:
3684   {
3685     GST_DEBUG_OBJECT (src, "no destination found");
3686     return FALSE;
3687   }
3688 no_ports:
3689   {
3690     GST_DEBUG_OBJECT (src, "no ports found");
3691     return FALSE;
3692   }
3693 }
3694
3695 /* configure the remainder of the UDP ports */
3696 static gboolean
3697 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3698     GstRTSPTransport * transport, GstPad ** outpad)
3699 {
3700   /* we manage the UDP elements now. For unicast, the UDP sources where
3701    * allocated in the stream when we suggested a transport. */
3702   if (stream->udpsrc[0]) {
3703     GstCaps *caps;
3704
3705     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3706     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3707
3708     GST_DEBUG_OBJECT (src, "setting up UDP source");
3709
3710     /* configure a timeout on the UDP port. When the timeout message is
3711      * posted, we assume UDP transport is not possible. We reconnect using TCP
3712      * if we can. */
3713     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3714         src->udp_timeout * 1000, NULL);
3715
3716     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt)))
3717       g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3718
3719     /* get output pad of the UDP source. */
3720     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3721
3722     /* save it so we can unblock */
3723     stream->blockedpad = *outpad;
3724
3725     /* configure pad block on the pad. As soon as there is dataflow on the
3726      * UDP source, we know that UDP is not blocked by a firewall and we can
3727      * configure all the streams to let the application autoplug decoders. */
3728     stream->blockid =
3729         gst_pad_add_probe (stream->blockedpad,
3730         GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
3731         GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
3732
3733     if (stream->channelpad[0]) {
3734       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3735       /* configure for UDP delivery, we need to connect the UDP pads to
3736        * the session plugin. */
3737       gst_pad_link_full (*outpad, stream->channelpad[0],
3738           GST_PAD_LINK_CHECK_NOTHING);
3739       gst_object_unref (*outpad);
3740       *outpad = NULL;
3741       /* we connected to pad-added signal to get pads from the manager */
3742     } else {
3743       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3744     }
3745   }
3746
3747   /* RTCP port */
3748   if (stream->udpsrc[1]) {
3749     GstCaps *caps;
3750
3751     gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3752     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3753
3754     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3755         stream->profile == GST_RTSP_PROFILE_SAVPF)
3756       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3757     else
3758       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3759     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3760     gst_caps_unref (caps);
3761
3762     if (stream->channelpad[1]) {
3763       GstPad *pad;
3764
3765       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3766
3767       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3768       gst_pad_link_full (pad, stream->channelpad[1],
3769           GST_PAD_LINK_CHECK_NOTHING);
3770       gst_object_unref (pad);
3771     } else {
3772       /* leave unlinked */
3773     }
3774   }
3775   return TRUE;
3776 }
3777
3778 /* configure the UDP sink back to the server for status reports */
3779 static gboolean
3780 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3781     GstRTSPStream * stream, GstRTSPTransport * transport)
3782 {
3783   GstPad *pad;
3784   gint rtp_port, rtcp_port;
3785   gboolean do_rtp, do_rtcp;
3786   const gchar *destination;
3787   gchar *uri, *name;
3788   guint ttl = 0;
3789   GSocket *socket;
3790
3791   /* get transport info */
3792   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3793       &rtp_port, &rtcp_port, &ttl);
3794
3795   /* see what we need to do */
3796   do_rtp = (rtp_port != -1);
3797   /* it's possible that the server does not want us to send RTCP in which case
3798    * the port is -1 */
3799   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3800
3801   /* we need a destination when we have RTP or RTCP ports */
3802   if (destination == NULL && (do_rtp || do_rtcp))
3803     goto no_destination;
3804
3805   /* try to construct the fakesrc to the RTP port of the server to open up any
3806    * NAT firewalls */
3807   if (do_rtp) {
3808     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3809         rtp_port);
3810
3811     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3812     stream->udpsink[0] =
3813         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3814     g_free (uri);
3815     if (stream->udpsink[0] == NULL)
3816       goto no_sink_element;
3817
3818     /* don't join multicast group, we will have the source socket do that */
3819     /* no sync or async state changes needed */
3820     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3821         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3822     if (ttl > 0)
3823       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3824
3825     if (stream->udpsrc[0]) {
3826       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3827        * so that NAT firewalls will open a hole for us */
3828       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3829       if (!socket)
3830         goto no_socket;
3831
3832       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3833       /* configure socket and make sure udpsink does not close it when shutting
3834        * down, it belongs to udpsrc after all. */
3835       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3836           "close-socket", FALSE, NULL);
3837       g_object_unref (socket);
3838     }
3839
3840     /* the source for the dummy packets to open up NAT */
3841     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3842     if (stream->fakesrc == NULL)
3843       goto no_fakesrc_element;
3844
3845     /* random data in 5 buffers, a size of 200 bytes should be fine */
3846     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3847         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3848
3849     /* keep everything locked */
3850     gst_element_set_locked_state (stream->udpsink[0], TRUE);
3851     gst_element_set_locked_state (stream->fakesrc, TRUE);
3852
3853     gst_object_ref (stream->udpsink[0]);
3854     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3855     gst_object_ref (stream->fakesrc);
3856     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3857
3858     gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
3859         "sink", GST_PAD_LINK_CHECK_NOTHING);
3860   }
3861   if (do_rtcp) {
3862     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3863         rtcp_port);
3864
3865     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3866     stream->udpsink[1] =
3867         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3868     g_free (uri);
3869     if (stream->udpsink[1] == NULL)
3870       goto no_sink_element;
3871
3872     /* don't join multicast group, we will have the source socket do that */
3873     /* no sync or async state changes needed */
3874     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3875         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3876     if (ttl > 0)
3877       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3878
3879     if (stream->udpsrc[1]) {
3880       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3881        * because some servers check the port number of where it sends RTCP to identify
3882        * the RTCP packets it receives */
3883       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3884       if (!socket)
3885         goto no_socket;
3886
3887       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3888       /* configure socket and make sure udpsink does not close it when shutting
3889        * down, it belongs to udpsrc after all. */
3890       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3891           "close-socket", FALSE, NULL);
3892       g_object_unref (socket);
3893     }
3894
3895     /* we keep this playing always */
3896     gst_element_set_locked_state (stream->udpsink[1], TRUE);
3897     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3898
3899     gst_object_ref (stream->udpsink[1]);
3900     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3901
3902     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3903
3904     /* get session RTCP pad */
3905     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3906     pad = gst_element_get_request_pad (src->manager, name);
3907     g_free (name);
3908
3909     /* and link */
3910     if (pad) {
3911       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3912       gst_object_unref (pad);
3913     }
3914   }
3915
3916   return TRUE;
3917
3918   /* ERRORS */
3919 no_destination:
3920   {
3921     GST_ERROR_OBJECT (src, "no destination address specified");
3922     return FALSE;
3923   }
3924 no_sink_element:
3925   {
3926     GST_ERROR_OBJECT (src, "no UDP sink element found");
3927     return FALSE;
3928   }
3929 no_fakesrc_element:
3930   {
3931     GST_ERROR_OBJECT (src, "no fakesrc element found");
3932     return FALSE;
3933   }
3934 no_socket:
3935   {
3936     GST_ERROR_OBJECT (src, "failed to create socket");
3937     return FALSE;
3938   }
3939 }
3940
3941 /* sets up all elements needed for streaming over the specified transport.
3942  * Does not yet expose the element pads, this will be done when there is actuall
3943  * dataflow detected, which might never happen when UDP is blocked in a
3944  * firewall, for example.
3945  */
3946 static gboolean
3947 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3948     GstRTSPTransport * transport)
3949 {
3950   GstRTSPSrc *src;
3951   GstPad *outpad = NULL;
3952   GstPadTemplate *template;
3953   gchar *name;
3954   const gchar *media_type;
3955   guint i, len;
3956
3957   src = stream->parent;
3958
3959   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3960
3961   /* get the proper media type for this stream now */
3962   if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
3963     goto unknown_transport;
3964   if (!media_type)
3965     goto unknown_transport;
3966
3967   /* configure the final media type */
3968   GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
3969
3970   len = stream->ptmap->len;
3971   for (i = 0; i < len; i++) {
3972     GstStructure *s;
3973     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3974
3975     if (item->caps == NULL)
3976       continue;
3977
3978     s = gst_caps_get_structure (item->caps, 0);
3979     gst_structure_set_name (s, media_type);
3980     /* set ssrc if known */
3981     if (transport->ssrc)
3982       gst_structure_set (s, "ssrc", G_TYPE_UINT, transport->ssrc, NULL);
3983   }
3984
3985   /* try to get and configure a manager, channelpad[0-1] will be configured with
3986    * the pads for the manager, or NULL when no manager is needed. */
3987   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3988     goto no_manager;
3989
3990   switch (transport->lower_transport) {
3991     case GST_RTSP_LOWER_TRANS_TCP:
3992       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3993         goto transport_failed;
3994       break;
3995     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3996       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3997         goto transport_failed;
3998       /* fallthrough, the rest is the same for UDP and MCAST */
3999     case GST_RTSP_LOWER_TRANS_UDP:
4000       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
4001         goto transport_failed;
4002       /* configure udpsinks back to the server for RTCP messages and for the
4003        * dummy RTP messages to open NAT. */
4004       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
4005         goto transport_failed;
4006       break;
4007     default:
4008       goto unknown_transport;
4009   }
4010
4011   if (outpad) {
4012     GST_DEBUG_OBJECT (src, "creating ghostpad");
4013
4014     gst_pad_use_fixed_caps (outpad);
4015
4016     /* create ghostpad, don't add just yet, this will be done when we activate
4017      * the stream. */
4018     name = g_strdup_printf ("stream_%u", stream->id);
4019     template = gst_static_pad_template_get (&rtptemplate);
4020     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
4021     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
4022     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
4023     gst_object_unref (template);
4024     g_free (name);
4025
4026     gst_object_unref (outpad);
4027   }
4028   /* mark pad as ok */
4029   stream->last_ret = GST_FLOW_OK;
4030
4031   return TRUE;
4032
4033   /* ERRORS */
4034 transport_failed:
4035   {
4036     GST_DEBUG_OBJECT (src, "failed to configure transport");
4037     return FALSE;
4038   }
4039 unknown_transport:
4040   {
4041     GST_DEBUG_OBJECT (src, "unknown transport");
4042     return FALSE;
4043   }
4044 no_manager:
4045   {
4046     GST_DEBUG_OBJECT (src, "cannot get a session manager");
4047     return FALSE;
4048   }
4049 }
4050
4051 /* send a couple of dummy random packets on the receiver RTP port to the server,
4052  * this should make a firewall think we initiated the data transfer and
4053  * hopefully allow packets to go from the sender port to our RTP receiver port */
4054 static gboolean
4055 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
4056 {
4057   GList *walk;
4058
4059   if (src->nat_method != GST_RTSP_NAT_DUMMY)
4060     return TRUE;
4061
4062   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4063     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4064
4065     if (stream->fakesrc && stream->udpsink[0]) {
4066       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
4067       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
4068       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
4069       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
4070       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
4071     }
4072   }
4073   return TRUE;
4074 }
4075
4076 /* Adds the source pads of all configured streams to the element.
4077  * This code is performed when we detected dataflow.
4078  *
4079  * We detect dataflow from either the _loop function or with pad probes on the
4080  * udp sources.
4081  */
4082 static gboolean
4083 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
4084 {
4085   GList *walk;
4086
4087   GST_DEBUG_OBJECT (src, "activating streams");
4088
4089   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4090     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4091
4092     if (stream->udpsrc[0]) {
4093       /* remove timeout, we are streaming now and timeouts will be handled by
4094        * the session manager and jitter buffer */
4095       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
4096     }
4097     if (stream->srcpad) {
4098       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
4099       gst_pad_set_active (stream->srcpad, TRUE);
4100
4101       /* if we don't have a session manager, set the caps now. If we have a
4102        * session, we will get a notification of the pad and the caps. */
4103       if (!src->manager) {
4104         GstCaps *caps;
4105
4106         caps = stream_get_caps_for_pt (stream, stream->default_pt);
4107         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
4108         gst_pad_set_caps (stream->srcpad, caps);
4109       }
4110       /* add the pad */
4111       if (!stream->added) {
4112         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
4113         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
4114         stream->added = TRUE;
4115       }
4116     }
4117   }
4118
4119   /* unblock all pads */
4120   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4121     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4122
4123     if (stream->blockid) {
4124       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
4125       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
4126       stream->blockid = 0;
4127     }
4128   }
4129
4130   return TRUE;
4131 }
4132
4133 static void
4134 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
4135     gboolean reset_manager)
4136 {
4137   GList *walk;
4138   guint64 start, stop;
4139   gdouble play_speed, play_scale;
4140
4141   GST_DEBUG_OBJECT (src, "configuring stream caps");
4142
4143   start = segment->position;
4144   stop = segment->duration;
4145   play_speed = segment->rate;
4146   play_scale = segment->applied_rate;
4147
4148   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4149     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4150     guint j, len;
4151
4152     if (!stream->setup)
4153       continue;
4154
4155     len = stream->ptmap->len;
4156     for (j = 0; j < len; j++) {
4157       GstCaps *caps;
4158       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, j);
4159
4160       if (item->caps == NULL)
4161         continue;
4162
4163       caps = gst_caps_make_writable (item->caps);
4164       /* update caps */
4165       if (stream->timebase != -1)
4166         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
4167             (guint) stream->timebase, NULL);
4168       if (stream->seqbase != -1)
4169         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
4170             (guint) stream->seqbase, NULL);
4171       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
4172       if (stop != -1)
4173         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
4174       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
4175       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
4176
4177       item->caps = caps;
4178       GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
4179           item->pt, caps);
4180
4181       if (item->pt == stream->default_pt) {
4182         if (stream->udpsrc[0])
4183           g_object_set (stream->udpsrc[0], "caps", caps, NULL);
4184         stream->need_caps = TRUE;
4185       }
4186     }
4187   }
4188   if (reset_manager && src->manager) {
4189     GST_DEBUG_OBJECT (src, "clear session");
4190     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
4191   }
4192 }
4193
4194 static GstFlowReturn
4195 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
4196     GstFlowReturn ret)
4197 {
4198   GList *streams;
4199
4200   /* store the value */
4201   stream->last_ret = ret;
4202
4203   /* if it's success we can return the value right away */
4204   if (ret == GST_FLOW_OK)
4205     goto done;
4206
4207   /* any other error that is not-linked can be returned right
4208    * away */
4209   if (ret != GST_FLOW_NOT_LINKED)
4210     goto done;
4211
4212   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4213   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4214     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4215
4216     ret = ostream->last_ret;
4217     /* some other return value (must be SUCCESS but we can return
4218      * other values as well) */
4219     if (ret != GST_FLOW_NOT_LINKED)
4220       goto done;
4221   }
4222   /* if we get here, all other pads were unlinked and we return
4223    * NOT_LINKED then */
4224 done:
4225   return ret;
4226 }
4227
4228 static gboolean
4229 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
4230     GstEvent * event)
4231 {
4232   gboolean res = TRUE;
4233
4234   /* only streams that have a connection to the outside world */
4235   if (!stream->setup)
4236     goto done;
4237
4238   if (stream->udpsrc[0]) {
4239     gst_event_ref (event);
4240     res = gst_element_send_event (stream->udpsrc[0], event);
4241   } else if (stream->channelpad[0]) {
4242     gst_event_ref (event);
4243     if (GST_PAD_IS_SRC (stream->channelpad[0]))
4244       res = gst_pad_push_event (stream->channelpad[0], event);
4245     else
4246       res = gst_pad_send_event (stream->channelpad[0], event);
4247   }
4248
4249   if (stream->udpsrc[1]) {
4250     gst_event_ref (event);
4251     res &= gst_element_send_event (stream->udpsrc[1], event);
4252   } else if (stream->channelpad[1]) {
4253     gst_event_ref (event);
4254     if (GST_PAD_IS_SRC (stream->channelpad[1]))
4255       res &= gst_pad_push_event (stream->channelpad[1], event);
4256     else
4257       res &= gst_pad_send_event (stream->channelpad[1], event);
4258   }
4259
4260 done:
4261   gst_event_unref (event);
4262
4263   return res;
4264 }
4265
4266 static gboolean
4267 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
4268 {
4269   GList *streams;
4270   gboolean res = TRUE;
4271
4272   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4273     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4274
4275     gst_event_ref (event);
4276     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
4277   }
4278   gst_event_unref (event);
4279
4280   return res;
4281 }
4282
4283 static GstRTSPResult
4284 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4285     gboolean async)
4286 {
4287   GstRTSPResult res;
4288   GstRTSPMessage response;
4289   gboolean retry = FALSE;
4290   memset (&response, 0, sizeof (response));
4291   gst_rtsp_message_init (&response);
4292   do {
4293     if (info->connection == NULL) {
4294       if (info->url == NULL) {
4295         GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
4296         if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
4297           goto parse_error;
4298       }
4299       /* create connection */
4300       GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
4301       if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
4302         goto could_not_create;
4303
4304       if (retry) {
4305         gst_rtspsrc_setup_auth (src, &response);
4306       }
4307
4308       g_free (info->url_str);
4309       info->url_str = gst_rtsp_url_get_request_uri (info->url);
4310
4311       GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
4312
4313       if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
4314         if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
4315                 src->tls_validation_flags))
4316           GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
4317
4318         if (src->tls_database)
4319           gst_rtsp_connection_set_tls_database (info->connection,
4320               src->tls_database);
4321
4322         if (src->tls_interaction)
4323           gst_rtsp_connection_set_tls_interaction (info->connection,
4324               src->tls_interaction);
4325       }
4326
4327       if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
4328         gst_rtsp_connection_set_tunneled (info->connection, TRUE);
4329
4330       if (src->proxy_host) {
4331         GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
4332             src->proxy_port);
4333         gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
4334             src->proxy_port);
4335       }
4336     }
4337
4338     if (!info->connected) {
4339       /* connect */
4340       if (async)
4341         GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
4342             ("Connecting to %s", info->location));
4343       GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
4344       res = gst_rtsp_connection_connect_with_response (info->connection,
4345           src->ptcp_timeout, &response);
4346
4347       if (response.type == GST_RTSP_MESSAGE_HTTP_RESPONSE &&
4348           response.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4349         gst_rtsp_conninfo_close (src, info, TRUE);
4350         if (!retry)
4351           retry = TRUE;
4352         else
4353           retry = FALSE;        // we should not retry more than once
4354       } else {
4355         retry = FALSE;
4356       }
4357
4358       if (res == GST_RTSP_OK)
4359         info->connected = TRUE;
4360       else if (!retry)
4361         goto could_not_connect;
4362     }
4363   } while (!info->connected && retry);
4364
4365   gst_rtsp_message_unset (&response);
4366   return GST_RTSP_OK;
4367
4368   /* ERRORS */
4369 parse_error:
4370   {
4371     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
4372     gst_rtsp_message_unset (&response);
4373     return res;
4374   }
4375 could_not_create:
4376   {
4377     gchar *str = gst_rtsp_strresult (res);
4378     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
4379     g_free (str);
4380     gst_rtsp_message_unset (&response);
4381     return res;
4382   }
4383 could_not_connect:
4384   {
4385     gchar *str = gst_rtsp_strresult (res);
4386     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
4387     g_free (str);
4388     gst_rtsp_message_unset (&response);
4389     return res;
4390   }
4391 }
4392
4393 static GstRTSPResult
4394 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
4395     gboolean free)
4396 {
4397   GST_RTSP_STATE_LOCK (src);
4398   if (info->connected) {
4399     GST_DEBUG_OBJECT (src, "closing connection...");
4400     gst_rtsp_connection_close (info->connection);
4401     info->connected = FALSE;
4402   }
4403   if (free && info->connection) {
4404     /* free connection */
4405     GST_DEBUG_OBJECT (src, "freeing connection...");
4406     gst_rtsp_connection_free (info->connection);
4407     info->connection = NULL;
4408     info->flushing = FALSE;
4409   }
4410   GST_RTSP_STATE_UNLOCK (src);
4411   return GST_RTSP_OK;
4412 }
4413
4414 static GstRTSPResult
4415 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4416     gboolean async)
4417 {
4418   GstRTSPResult res;
4419
4420   GST_DEBUG_OBJECT (src, "reconnecting connection...");
4421   gst_rtsp_conninfo_close (src, info, FALSE);
4422   res = gst_rtsp_conninfo_connect (src, info, async);
4423
4424   return res;
4425 }
4426
4427 static void
4428 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
4429 {
4430   GList *walk;
4431
4432   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
4433   GST_RTSP_STATE_LOCK (src);
4434   if (src->conninfo.connection && src->conninfo.flushing != flush) {
4435     GST_DEBUG_OBJECT (src, "connection flush");
4436     gst_rtsp_connection_flush (src->conninfo.connection, flush);
4437     src->conninfo.flushing = flush;
4438   }
4439   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4440     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4441     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
4442       GST_DEBUG_OBJECT (src, "stream %p flush", stream);
4443       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
4444       stream->conninfo.flushing = flush;
4445     }
4446   }
4447   GST_RTSP_STATE_UNLOCK (src);
4448 }
4449
4450 static GstRTSPResult
4451 gst_rtspsrc_init_request (GstRTSPSrc * src, GstRTSPMessage * msg,
4452     GstRTSPMethod method, const gchar * uri)
4453 {
4454   GstRTSPResult res;
4455
4456   res = gst_rtsp_message_init_request (msg, method, uri);
4457   if (res < 0)
4458     return res;
4459
4460   /* set user-agent */
4461   if (src->user_agent)
4462     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_USER_AGENT, src->user_agent);
4463
4464   return res;
4465 }
4466
4467 /* FIXME, handle server request, reply with OK, for now */
4468 static GstRTSPResult
4469 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
4470     GstRTSPMessage * request)
4471 {
4472   GstRTSPMessage response = { 0 };
4473   GstRTSPResult res;
4474
4475   GST_DEBUG_OBJECT (src, "got server request message");
4476
4477   DEBUG_RTSP (src, request);
4478
4479   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4480
4481   if (res == GST_RTSP_ENOTIMPL) {
4482     /* default implementation, send OK */
4483     GST_DEBUG_OBJECT (src, "prepare OK reply");
4484     res =
4485         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4486         request);
4487     if (res < 0)
4488       goto send_error;
4489
4490     /* let app parse and reply */
4491     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4492         0, request, &response);
4493
4494     DEBUG_RTSP (src, &response);
4495
4496     res = gst_rtspsrc_connection_send (src, conninfo, &response, NULL);
4497     if (res < 0)
4498       goto send_error;
4499
4500     gst_rtsp_message_unset (&response);
4501   } else if (res == GST_RTSP_EEOF)
4502     return res;
4503
4504   return GST_RTSP_OK;
4505
4506   /* ERRORS */
4507 send_error:
4508   {
4509     gst_rtsp_message_unset (&response);
4510     return res;
4511   }
4512 }
4513
4514 /* send server keep-alive */
4515 static GstRTSPResult
4516 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4517 {
4518   GstRTSPMessage request = { 0 };
4519   GstRTSPResult res;
4520   GstRTSPMethod method;
4521   const gchar *control;
4522
4523   if (src->do_rtsp_keep_alive == FALSE) {
4524     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4525     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4526     return GST_RTSP_OK;
4527   }
4528
4529   GST_DEBUG_OBJECT (src, "creating server keep-alive");
4530
4531   /* find a method to use for keep-alive */
4532   if (src->methods & GST_RTSP_GET_PARAMETER)
4533     method = GST_RTSP_GET_PARAMETER;
4534   else
4535     method = GST_RTSP_OPTIONS;
4536
4537   control = get_aggregate_control (src);
4538   if (control == NULL)
4539     goto no_control;
4540
4541   res = gst_rtspsrc_init_request (src, &request, method, control);
4542   if (res < 0)
4543     goto send_error;
4544
4545   request.type_data.request.version = src->version;
4546
4547   res = gst_rtspsrc_connection_send (src, &src->conninfo, &request, NULL);
4548   if (res < 0)
4549     goto send_error;
4550
4551   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4552   gst_rtsp_message_unset (&request);
4553
4554   return GST_RTSP_OK;
4555
4556   /* ERRORS */
4557 no_control:
4558   {
4559     GST_WARNING_OBJECT (src, "no control url to send keepalive");
4560     return GST_RTSP_OK;
4561   }
4562 send_error:
4563   {
4564     gchar *str = gst_rtsp_strresult (res);
4565
4566     gst_rtsp_message_unset (&request);
4567     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4568         ("Could not send keep-alive. (%s)", str));
4569     g_free (str);
4570     return res;
4571   }
4572 }
4573
4574 static GstFlowReturn
4575 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4576 {
4577   GstFlowReturn ret = GST_FLOW_OK;
4578   gint channel;
4579   GstRTSPStream *stream;
4580   GstPad *outpad = NULL;
4581   guint8 *data;
4582   guint size;
4583   GstBuffer *buf;
4584   gboolean is_rtcp;
4585
4586   channel = message->type_data.data.channel;
4587
4588   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4589   if (!stream)
4590     goto unknown_stream;
4591
4592   if (channel == stream->channel[0]) {
4593     outpad = stream->channelpad[0];
4594     is_rtcp = FALSE;
4595   } else if (channel == stream->channel[1]) {
4596     outpad = stream->channelpad[1];
4597     is_rtcp = TRUE;
4598   } else {
4599     is_rtcp = FALSE;
4600   }
4601
4602   /* take a look at the body to figure out what we have */
4603   gst_rtsp_message_get_body (message, &data, &size);
4604   if (size < 2)
4605     goto invalid_length;
4606
4607   /* channels are not correct on some servers, do extra check */
4608   if (data[1] >= 200 && data[1] <= 204) {
4609     /* hmm RTCP message switch to the RTCP pad of the same stream. */
4610     outpad = stream->channelpad[1];
4611     is_rtcp = TRUE;
4612   }
4613
4614   /* we have no clue what this is, just ignore then. */
4615   if (outpad == NULL)
4616     goto unknown_stream;
4617
4618   /* take the message body for further processing */
4619   gst_rtsp_message_steal_body (message, &data, &size);
4620
4621   /* strip the trailing \0 */
4622   size -= 1;
4623
4624   buf = gst_buffer_new ();
4625   gst_buffer_append_memory (buf,
4626       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4627
4628   /* don't need message anymore */
4629   gst_rtsp_message_unset (message);
4630
4631   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4632       channel);
4633
4634   if (src->need_activate) {
4635     gchar *stream_id;
4636     GstEvent *event;
4637     GChecksum *cs;
4638     gchar *uri;
4639     GList *streams;
4640     guint group_id = gst_util_group_id_next ();
4641
4642     /* generate an SHA256 sum of the URI */
4643     cs = g_checksum_new (G_CHECKSUM_SHA256);
4644     uri = src->conninfo.location;
4645     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4646
4647     for (streams = src->streams; streams; streams = g_list_next (streams)) {
4648       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4649       GstCaps *caps;
4650
4651       stream_id =
4652           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4653       event = gst_event_new_stream_start (stream_id);
4654       gst_event_set_group_id (event, group_id);
4655
4656       g_free (stream_id);
4657       gst_rtspsrc_stream_push_event (src, ostream, event);
4658
4659       if ((caps = stream_get_caps_for_pt (ostream, ostream->default_pt))) {
4660         /* only streams that have a connection to the outside world */
4661         if (ostream->setup) {
4662           if (ostream->udpsrc[0]) {
4663             gst_element_send_event (ostream->udpsrc[0],
4664                 gst_event_new_caps (caps));
4665           } else if (ostream->channelpad[0]) {
4666             if (GST_PAD_IS_SRC (ostream->channelpad[0]))
4667               gst_pad_push_event (ostream->channelpad[0],
4668                   gst_event_new_caps (caps));
4669             else
4670               gst_pad_send_event (ostream->channelpad[0],
4671                   gst_event_new_caps (caps));
4672           }
4673           ostream->need_caps = FALSE;
4674
4675           if (ostream->profile == GST_RTSP_PROFILE_SAVP ||
4676               ostream->profile == GST_RTSP_PROFILE_SAVPF)
4677             caps = gst_caps_new_empty_simple ("application/x-srtcp");
4678           else
4679             caps = gst_caps_new_empty_simple ("application/x-rtcp");
4680
4681           if (ostream->udpsrc[1]) {
4682             gst_element_send_event (ostream->udpsrc[1],
4683                 gst_event_new_caps (caps));
4684           } else if (ostream->channelpad[1]) {
4685             if (GST_PAD_IS_SRC (ostream->channelpad[1]))
4686               gst_pad_push_event (ostream->channelpad[1],
4687                   gst_event_new_caps (caps));
4688             else
4689               gst_pad_send_event (ostream->channelpad[1],
4690                   gst_event_new_caps (caps));
4691           }
4692
4693           gst_caps_unref (caps);
4694         }
4695       }
4696     }
4697     g_checksum_free (cs);
4698
4699     gst_rtspsrc_activate_streams (src);
4700     src->need_activate = FALSE;
4701     src->need_segment = TRUE;
4702   }
4703
4704   if (src->base_time == -1) {
4705     /* Take current running_time. This timestamp will be put on
4706      * the first buffer of each stream because we are a live source and so we
4707      * timestamp with the running_time. When we are dealing with TCP, we also
4708      * only timestamp the first buffer (using the DISCONT flag) because a server
4709      * typically bursts data, for which we don't want to compensate by speeding
4710      * up the media. The other timestamps will be interpollated from this one
4711      * using the RTP timestamps. */
4712     GST_OBJECT_LOCK (src);
4713     if (GST_ELEMENT_CLOCK (src)) {
4714       GstClockTime now;
4715       GstClockTime base_time;
4716
4717       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4718       base_time = GST_ELEMENT_CAST (src)->base_time;
4719
4720       src->base_time = now - base_time;
4721
4722       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4723           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4724     }
4725     GST_OBJECT_UNLOCK (src);
4726   }
4727
4728   /* If needed send a new segment, don't forget we are live and buffer are
4729    * timestamped with running time */
4730   if (src->need_segment) {
4731     GstSegment segment;
4732     src->need_segment = FALSE;
4733     gst_segment_init (&segment, GST_FORMAT_TIME);
4734     gst_rtspsrc_push_event (src, gst_event_new_segment (&segment));
4735   }
4736
4737   if (stream->need_caps) {
4738     GstCaps *caps;
4739
4740     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt))) {
4741       /* only streams that have a connection to the outside world */
4742       if (stream->setup) {
4743         /* Only need to update the TCP caps here, UDP is already handled */
4744         if (stream->channelpad[0]) {
4745           if (GST_PAD_IS_SRC (stream->channelpad[0]))
4746             gst_pad_push_event (stream->channelpad[0],
4747                 gst_event_new_caps (caps));
4748           else
4749             gst_pad_send_event (stream->channelpad[0],
4750                 gst_event_new_caps (caps));
4751         }
4752         stream->need_caps = FALSE;
4753       }
4754     }
4755
4756     stream->need_caps = FALSE;
4757   }
4758
4759   if (stream->discont && !is_rtcp) {
4760     /* mark first RTP buffer as discont */
4761     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4762     stream->discont = FALSE;
4763     /* first buffer gets the timestamp, other buffers are not timestamped and
4764      * their presentation time will be interpollated from the rtp timestamps. */
4765     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4766         GST_TIME_ARGS (src->base_time));
4767
4768     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4769   }
4770
4771   /* chain to the peer pad */
4772   if (GST_PAD_IS_SINK (outpad))
4773     ret = gst_pad_chain (outpad, buf);
4774   else
4775     ret = gst_pad_push (outpad, buf);
4776
4777   if (!is_rtcp) {
4778     /* combine all stream flows for the data transport */
4779     ret = gst_rtspsrc_combine_flows (src, stream, ret);
4780   }
4781   return ret;
4782
4783   /* ERRORS */
4784 unknown_stream:
4785   {
4786     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4787     gst_rtsp_message_unset (message);
4788     return GST_FLOW_OK;
4789   }
4790 invalid_length:
4791   {
4792     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4793         ("Short message received, ignoring."));
4794     gst_rtsp_message_unset (message);
4795     return GST_FLOW_OK;
4796   }
4797 }
4798
4799 static GstFlowReturn
4800 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4801 {
4802   GstRTSPMessage message = { 0 };
4803   GstRTSPResult res;
4804   GstFlowReturn ret = GST_FLOW_OK;
4805   GTimeVal tv_timeout;
4806
4807   while (TRUE) {
4808     /* get the next timeout interval */
4809     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4810
4811     /* see if the timeout period expired */
4812     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4813       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4814       /* send keep-alive, only act on interrupt, a warning will be posted for
4815        * other errors. */
4816       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4817         goto interrupt;
4818       /* get new timeout */
4819       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4820     }
4821
4822     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4823         tv_timeout.tv_sec, tv_timeout.tv_usec);
4824
4825     /* protect the connection with the connection lock so that we can see when
4826      * we are finished doing server communication */
4827     res =
4828         gst_rtspsrc_connection_receive (src, &src->conninfo,
4829         &message, src->ptcp_timeout);
4830
4831     switch (res) {
4832       case GST_RTSP_OK:
4833         GST_DEBUG_OBJECT (src, "we received a server message");
4834         break;
4835       case GST_RTSP_EINTR:
4836         /* we got interrupted this means we need to stop */
4837         goto interrupt;
4838       case GST_RTSP_ETIMEOUT:
4839         /* no reply, send keep alive */
4840         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4841         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4842           goto interrupt;
4843         continue;
4844       case GST_RTSP_EEOF:
4845         /* go EOS when the server closed the connection */
4846         goto server_eof;
4847       default:
4848         goto receive_error;
4849     }
4850
4851     switch (message.type) {
4852       case GST_RTSP_MESSAGE_REQUEST:
4853         /* server sends us a request message, handle it */
4854         res = gst_rtspsrc_handle_request (src, &src->conninfo, &message);
4855         if (res == GST_RTSP_EEOF)
4856           goto server_eof;
4857         else if (res < 0)
4858           goto handle_request_failed;
4859         break;
4860       case GST_RTSP_MESSAGE_RESPONSE:
4861         /* we ignore response messages */
4862         GST_DEBUG_OBJECT (src, "ignoring response message");
4863         DEBUG_RTSP (src, &message);
4864         break;
4865       case GST_RTSP_MESSAGE_DATA:
4866         GST_DEBUG_OBJECT (src, "got data message");
4867         ret = gst_rtspsrc_handle_data (src, &message);
4868         if (ret != GST_FLOW_OK)
4869           goto handle_data_failed;
4870         break;
4871       default:
4872         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4873             message.type);
4874         break;
4875     }
4876   }
4877   g_assert_not_reached ();
4878
4879   /* ERRORS */
4880 server_eof:
4881   {
4882     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4883     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4884         ("The server closed the connection."));
4885     src->conninfo.connected = FALSE;
4886     gst_rtsp_message_unset (&message);
4887     return GST_FLOW_EOS;
4888   }
4889 interrupt:
4890   {
4891     gst_rtsp_message_unset (&message);
4892     GST_DEBUG_OBJECT (src, "got interrupted");
4893     return GST_FLOW_FLUSHING;
4894   }
4895 receive_error:
4896   {
4897     gchar *str = gst_rtsp_strresult (res);
4898
4899     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4900         ("Could not receive message. (%s)", str));
4901     g_free (str);
4902
4903     gst_rtsp_message_unset (&message);
4904     return GST_FLOW_ERROR;
4905   }
4906 handle_request_failed:
4907   {
4908     gchar *str = gst_rtsp_strresult (res);
4909
4910     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4911         ("Could not handle server message. (%s)", str));
4912     g_free (str);
4913     gst_rtsp_message_unset (&message);
4914     return GST_FLOW_ERROR;
4915   }
4916 handle_data_failed:
4917   {
4918     GST_DEBUG_OBJECT (src, "could no handle data message");
4919     return ret;
4920   }
4921 }
4922
4923 static GstFlowReturn
4924 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4925 {
4926   GstRTSPResult res;
4927   GstRTSPMessage message = { 0 };
4928   gint retry = 0;
4929
4930   while (TRUE) {
4931     GTimeVal tv_timeout;
4932
4933     /* get the next timeout interval */
4934     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4935
4936     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4937         (gint) tv_timeout.tv_sec);
4938
4939     gst_rtsp_message_unset (&message);
4940
4941     /* we should continue reading the TCP socket because the server might
4942      * send us requests. When the session timeout expires, we need to send a
4943      * keep-alive request to keep the session open. */
4944     res = gst_rtspsrc_connection_receive (src, &src->conninfo,
4945         &message, &tv_timeout);
4946
4947     switch (res) {
4948       case GST_RTSP_OK:
4949         GST_DEBUG_OBJECT (src, "we received a server message");
4950         break;
4951       case GST_RTSP_EINTR:
4952         /* we got interrupted, see what we have to do */
4953         goto interrupt;
4954       case GST_RTSP_ETIMEOUT:
4955         /* send keep-alive, ignore the result, a warning will be posted. */
4956         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4957         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4958           goto interrupt;
4959         continue;
4960       case GST_RTSP_EEOF:
4961         /* server closed the connection. not very fatal for UDP, reconnect and
4962          * see what happens. */
4963         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4964             ("The server closed the connection."));
4965         if (src->udp_reconnect) {
4966           if ((res =
4967                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4968             goto connect_error;
4969         } else {
4970           goto server_eof;
4971         }
4972         continue;
4973       case GST_RTSP_ENET:
4974         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4975       default:
4976         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4977             ("Unhandled return value %d.", res));
4978         goto receive_error;
4979     }
4980
4981     switch (message.type) {
4982       case GST_RTSP_MESSAGE_REQUEST:
4983         /* server sends us a request message, handle it */
4984         res = gst_rtspsrc_handle_request (src, &src->conninfo, &message);
4985         if (res == GST_RTSP_EEOF)
4986           goto server_eof;
4987         else if (res < 0)
4988           goto handle_request_failed;
4989         break;
4990       case GST_RTSP_MESSAGE_RESPONSE:
4991         /* we ignore response and data messages */
4992         GST_DEBUG_OBJECT (src, "ignoring response message");
4993         DEBUG_RTSP (src, &message);
4994         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4995           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4996           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4997             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4998             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4999               goto interrupt;
5000           }
5001         } else {
5002           retry = 0;
5003         }
5004         break;
5005       case GST_RTSP_MESSAGE_DATA:
5006         /* we ignore response and data messages */
5007         GST_DEBUG_OBJECT (src, "ignoring data message");
5008         break;
5009       default:
5010         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5011             message.type);
5012         break;
5013     }
5014   }
5015   g_assert_not_reached ();
5016
5017   /* we get here when the connection got interrupted */
5018 interrupt:
5019   {
5020     gst_rtsp_message_unset (&message);
5021     GST_DEBUG_OBJECT (src, "got interrupted");
5022     return GST_FLOW_FLUSHING;
5023   }
5024 connect_error:
5025   {
5026     gchar *str = gst_rtsp_strresult (res);
5027     GstFlowReturn ret;
5028
5029     src->conninfo.connected = FALSE;
5030     if (res != GST_RTSP_EINTR) {
5031       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5032           ("Could not connect to server. (%s)", str));
5033       g_free (str);
5034       ret = GST_FLOW_ERROR;
5035     } else {
5036       ret = GST_FLOW_FLUSHING;
5037     }
5038     return ret;
5039   }
5040 receive_error:
5041   {
5042     gchar *str = gst_rtsp_strresult (res);
5043
5044     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5045         ("Could not receive message. (%s)", str));
5046     g_free (str);
5047     return GST_FLOW_ERROR;
5048   }
5049 handle_request_failed:
5050   {
5051     gchar *str = gst_rtsp_strresult (res);
5052     GstFlowReturn ret;
5053
5054     gst_rtsp_message_unset (&message);
5055     if (res != GST_RTSP_EINTR) {
5056       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5057           ("Could not handle server message. (%s)", str));
5058       g_free (str);
5059       ret = GST_FLOW_ERROR;
5060     } else {
5061       ret = GST_FLOW_FLUSHING;
5062     }
5063     return ret;
5064   }
5065 server_eof:
5066   {
5067     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5068     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5069         ("The server closed the connection."));
5070     src->conninfo.connected = FALSE;
5071     gst_rtsp_message_unset (&message);
5072     return GST_FLOW_EOS;
5073   }
5074 }
5075
5076 static GstRTSPResult
5077 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
5078 {
5079   GstRTSPResult res = GST_RTSP_OK;
5080   gboolean restart;
5081
5082   GST_DEBUG_OBJECT (src, "doing reconnect");
5083
5084   GST_OBJECT_LOCK (src);
5085   /* only restart when the pads were not yet activated, else we were
5086    * streaming over UDP */
5087   restart = src->need_activate;
5088   GST_OBJECT_UNLOCK (src);
5089
5090   /* no need to restart, we're done */
5091   if (!restart)
5092     goto done;
5093
5094   /* we can try only TCP now */
5095   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
5096
5097   /* close and cleanup our state */
5098   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
5099     goto done;
5100
5101   /* see if we have TCP left to try. Also don't try TCP when we were configured
5102    * with an SDP. */
5103   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
5104     goto no_protocols;
5105
5106   /* We post a warning message now to inform the user
5107    * that nothing happened. It's most likely a firewall thing. */
5108   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5109       ("Could not receive any UDP packets for %.4f seconds, maybe your "
5110           "firewall is blocking it. Retrying using a tcp connection.",
5111           gst_guint64_to_gdouble (src->udp_timeout) / 1000000.0));
5112
5113   /* open new connection using tcp */
5114   if (gst_rtspsrc_open (src, async) < 0)
5115     goto open_failed;
5116
5117   /* start playback */
5118   if (gst_rtspsrc_play (src, &src->segment, async, NULL) < 0)
5119     goto play_failed;
5120
5121 done:
5122   return res;
5123
5124   /* ERRORS */
5125 no_protocols:
5126   {
5127     src->cur_protocols = 0;
5128     /* no transport possible, post an error and stop */
5129     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5130         ("Could not receive any UDP packets for %.4f seconds, maybe your "
5131             "firewall is blocking it. No other protocols to try.",
5132             gst_guint64_to_gdouble (src->udp_timeout) / 1000000.0));
5133     return GST_RTSP_ERROR;
5134   }
5135 open_failed:
5136   {
5137     GST_DEBUG_OBJECT (src, "open failed");
5138     return GST_RTSP_OK;
5139   }
5140 play_failed:
5141   {
5142     GST_DEBUG_OBJECT (src, "play failed");
5143     return GST_RTSP_OK;
5144   }
5145 }
5146
5147 static void
5148 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
5149 {
5150   switch (cmd) {
5151     case CMD_OPEN:
5152       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
5153       break;
5154     case CMD_PLAY:
5155       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
5156       break;
5157     case CMD_PAUSE:
5158       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
5159       break;
5160     case CMD_CLOSE:
5161       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
5162       break;
5163     default:
5164       break;
5165   }
5166 }
5167
5168 static void
5169 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
5170 {
5171   switch (cmd) {
5172     case CMD_OPEN:
5173       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
5174       break;
5175     case CMD_PLAY:
5176       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
5177       break;
5178     case CMD_PAUSE:
5179       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
5180       break;
5181     case CMD_CLOSE:
5182       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
5183       break;
5184     default:
5185       break;
5186   }
5187 }
5188
5189 static void
5190 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
5191 {
5192   switch (cmd) {
5193     case CMD_OPEN:
5194       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
5195       break;
5196     case CMD_PLAY:
5197       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
5198       break;
5199     case CMD_PAUSE:
5200       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
5201       break;
5202     case CMD_CLOSE:
5203       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
5204       break;
5205     default:
5206       break;
5207   }
5208 }
5209
5210 static void
5211 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
5212 {
5213   switch (cmd) {
5214     case CMD_OPEN:
5215       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
5216       break;
5217     case CMD_PLAY:
5218       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
5219       break;
5220     case CMD_PAUSE:
5221       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
5222       break;
5223     case CMD_CLOSE:
5224       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
5225       break;
5226     default:
5227       break;
5228   }
5229 }
5230
5231 static void
5232 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
5233 {
5234   if (ret == GST_RTSP_OK)
5235     gst_rtspsrc_loop_complete_cmd (src, cmd);
5236   else if (ret == GST_RTSP_EINTR)
5237     gst_rtspsrc_loop_cancel_cmd (src, cmd);
5238   else
5239     gst_rtspsrc_loop_error_cmd (src, cmd);
5240 }
5241
5242 static gboolean
5243 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
5244 {
5245   gint old;
5246   gboolean flushed = FALSE;
5247
5248   /* start new request */
5249   gst_rtspsrc_loop_start_cmd (src, cmd);
5250
5251   GST_DEBUG_OBJECT (src, "sending cmd %s", cmd_to_string (cmd));
5252
5253   GST_OBJECT_LOCK (src);
5254   old = src->pending_cmd;
5255   if (old == CMD_RECONNECT) {
5256     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
5257     cmd = CMD_RECONNECT;
5258   } else if (old == CMD_CLOSE) {
5259     /* our CMD_CLOSE might have interrutped CMD_LOOP. gst_rtspsrc_loop
5260      * will send a CMD_WAIT which would cancel our pending CMD_CLOSE (if
5261      * still pending). We just avoid it here by making sure CMD_CLOSE is
5262      * still the pending command. */
5263     GST_DEBUG_OBJECT (src, "ignore, we were closing");
5264     cmd = CMD_CLOSE;
5265   } else if (old != CMD_WAIT) {
5266     src->pending_cmd = CMD_WAIT;
5267     GST_OBJECT_UNLOCK (src);
5268     /* cancel previous request */
5269     GST_DEBUG_OBJECT (src, "cancel previous request %s", cmd_to_string (old));
5270     gst_rtspsrc_loop_cancel_cmd (src, old);
5271     GST_OBJECT_LOCK (src);
5272   }
5273   src->pending_cmd = cmd;
5274   /* interrupt if allowed */
5275   if (src->busy_cmd & mask) {
5276     GST_DEBUG_OBJECT (src, "connection flush busy %s",
5277         cmd_to_string (src->busy_cmd));
5278     gst_rtspsrc_connection_flush (src, TRUE);
5279     flushed = TRUE;
5280   } else {
5281     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
5282         cmd_to_string (src->busy_cmd));
5283   }
5284   if (src->task)
5285     gst_task_start (src->task);
5286   GST_OBJECT_UNLOCK (src);
5287
5288   return flushed;
5289 }
5290
5291 static gboolean
5292 gst_rtspsrc_loop (GstRTSPSrc * src)
5293 {
5294   GstFlowReturn ret;
5295
5296   if (!src->conninfo.connection || !src->conninfo.connected)
5297     goto no_connection;
5298
5299   if (src->interleaved)
5300     ret = gst_rtspsrc_loop_interleaved (src);
5301   else
5302     ret = gst_rtspsrc_loop_udp (src);
5303
5304   if (ret != GST_FLOW_OK)
5305     goto pause;
5306
5307   return TRUE;
5308
5309   /* ERRORS */
5310 no_connection:
5311   {
5312     GST_WARNING_OBJECT (src, "we are not connected");
5313     ret = GST_FLOW_FLUSHING;
5314     goto pause;
5315   }
5316 pause:
5317   {
5318     const gchar *reason = gst_flow_get_name (ret);
5319
5320     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
5321     src->running = FALSE;
5322     if (ret == GST_FLOW_EOS) {
5323       /* perform EOS logic */
5324       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5325         gst_element_post_message (GST_ELEMENT_CAST (src),
5326             gst_message_new_segment_done (GST_OBJECT_CAST (src),
5327                 src->segment.format, src->segment.position));
5328         gst_rtspsrc_push_event (src,
5329             gst_event_new_segment_done (src->segment.format,
5330                 src->segment.position));
5331       } else {
5332         gst_rtspsrc_push_event (src, gst_event_new_eos ());
5333       }
5334     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
5335       /* for fatal errors we post an error message, post the error before the
5336        * EOS so the app knows about the error first. */
5337       GST_ELEMENT_FLOW_ERROR (src, ret);
5338       gst_rtspsrc_push_event (src, gst_event_new_eos ());
5339     }
5340     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
5341     return FALSE;
5342   }
5343 }
5344
5345 #ifndef GST_DISABLE_GST_DEBUG
5346 static const gchar *
5347 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5348 {
5349   gint index = 0;
5350
5351   while (method != 0) {
5352     index++;
5353     method >>= 1;
5354   }
5355   switch (index) {
5356     case 0:
5357       return "None";
5358     case 1:
5359       return "Basic";
5360     case 2:
5361       return "Digest";
5362   }
5363
5364   return "Unknown";
5365 }
5366 #endif
5367
5368 /* Parse a WWW-Authenticate Response header and determine the
5369  * available authentication methods
5370  *
5371  * This code should also cope with the fact that each WWW-Authenticate
5372  * header can contain multiple challenge methods + tokens
5373  *
5374  * At the moment, for Basic auth, we just do a minimal check and don't
5375  * even parse out the realm */
5376 static void
5377 gst_rtspsrc_parse_auth_hdr (GstRTSPMessage * response,
5378     GstRTSPAuthMethod * methods, GstRTSPConnection * conn, gboolean * stale)
5379 {
5380   GstRTSPAuthCredential **credentials, **credential;
5381
5382   g_return_if_fail (response != NULL);
5383   g_return_if_fail (methods != NULL);
5384   g_return_if_fail (stale != NULL);
5385
5386   credentials =
5387       gst_rtsp_message_parse_auth_credentials (response,
5388       GST_RTSP_HDR_WWW_AUTHENTICATE);
5389   if (!credentials)
5390     return;
5391
5392   credential = credentials;
5393   while (*credential) {
5394     if ((*credential)->scheme == GST_RTSP_AUTH_BASIC) {
5395       *methods |= GST_RTSP_AUTH_BASIC;
5396     } else if ((*credential)->scheme == GST_RTSP_AUTH_DIGEST) {
5397       GstRTSPAuthParam **param = (*credential)->params;
5398
5399       *methods |= GST_RTSP_AUTH_DIGEST;
5400
5401       gst_rtsp_connection_clear_auth_params (conn);
5402       *stale = FALSE;
5403
5404       while (*param) {
5405         if (strcmp ((*param)->name, "stale") == 0
5406             && g_ascii_strcasecmp ((*param)->value, "TRUE") == 0)
5407           *stale = TRUE;
5408         gst_rtsp_connection_set_auth_param (conn, (*param)->name,
5409             (*param)->value);
5410         param++;
5411       }
5412     }
5413
5414     credential++;
5415   }
5416
5417   gst_rtsp_auth_credentials_free (credentials);
5418 }
5419
5420 /**
5421  * gst_rtspsrc_setup_auth:
5422  * @src: the rtsp source
5423  *
5424  * Configure a username and password and auth method on the
5425  * connection object based on a response we received from the
5426  * peer.
5427  *
5428  * Currently, this requires that a username and password were supplied
5429  * in the uri. In the future, they may be requested on demand by sending
5430  * a message up the bus.
5431  *
5432  * Returns: TRUE if authentication information could be set up correctly.
5433  */
5434 static gboolean
5435 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5436 {
5437   gchar *user = NULL;
5438   gchar *pass = NULL;
5439   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5440   GstRTSPAuthMethod method;
5441   GstRTSPResult auth_result;
5442   GstRTSPUrl *url;
5443   GstRTSPConnection *conn;
5444   gboolean stale = FALSE;
5445
5446   conn = src->conninfo.connection;
5447
5448   /* Identify the available auth methods and see if any are supported */
5449   gst_rtspsrc_parse_auth_hdr (response, &avail_methods, conn, &stale);
5450
5451   if (avail_methods == GST_RTSP_AUTH_NONE)
5452     goto no_auth_available;
5453
5454   /* For digest auth, if the response indicates that the session
5455    * data are stale, we just update them in the connection object and
5456    * return TRUE to retry the request */
5457   if (stale)
5458     src->tried_url_auth = FALSE;
5459
5460   url = gst_rtsp_connection_get_url (conn);
5461
5462   /* Do we have username and password available? */
5463   if (url != NULL && !src->tried_url_auth && url->user != NULL
5464       && url->passwd != NULL) {
5465     user = url->user;
5466     pass = url->passwd;
5467     src->tried_url_auth = TRUE;
5468     GST_DEBUG_OBJECT (src,
5469         "Attempting authentication using credentials from the URL");
5470   } else {
5471     user = src->user_id;
5472     pass = src->user_pw;
5473     GST_DEBUG_OBJECT (src,
5474         "Attempting authentication using credentials from the properties");
5475   }
5476
5477   /* FIXME: If the url didn't contain username and password or we tried them
5478    * already, request a username and passwd from the application via some kind
5479    * of credentials request message */
5480
5481   /* If we don't have a username and passwd at this point, bail out. */
5482   if (user == NULL || pass == NULL)
5483     goto no_user_pass;
5484
5485   /* Try to configure for each available authentication method, strongest to
5486    * weakest */
5487   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5488     /* Check if this method is available on the server */
5489     if ((method & avail_methods) == 0)
5490       continue;
5491
5492     /* Pass the credentials to the connection to try on the next request */
5493     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5494     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5495      * ignore it and end up retrying later */
5496     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5497       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5498           gst_rtsp_auth_method_to_string (method));
5499       break;
5500     }
5501   }
5502
5503   if (method == GST_RTSP_AUTH_NONE)
5504     goto no_auth_available;
5505
5506   return TRUE;
5507
5508 no_auth_available:
5509   {
5510     /* Output an error indicating that we couldn't connect because there were
5511      * no supported authentication protocols */
5512     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5513         ("No supported authentication protocol was found"));
5514     return FALSE;
5515   }
5516 no_user_pass:
5517   {
5518     /* We don't fire an error message, we just return FALSE and let the
5519      * normal NOT_AUTHORIZED error be propagated */
5520     return FALSE;
5521   }
5522 }
5523
5524 static GstRTSPResult
5525 gst_rtsp_src_receive_response (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
5526     GstRTSPMessage * response, GstRTSPStatusCode * code)
5527 {
5528   GstRTSPStatusCode thecode;
5529   gchar *content_base = NULL;
5530   GstRTSPResult res = gst_rtspsrc_connection_receive (src, conninfo,
5531       response, src->ptcp_timeout);
5532
5533   if (res < 0)
5534     goto receive_error;
5535
5536   DEBUG_RTSP (src, response);
5537
5538   switch (response->type) {
5539     case GST_RTSP_MESSAGE_REQUEST:
5540       res = gst_rtspsrc_handle_request (src, conninfo, response);
5541       if (res == GST_RTSP_EEOF)
5542         goto server_eof;
5543       else if (res < 0)
5544         goto handle_request_failed;
5545
5546       /* Not a response, receive next message */
5547       return gst_rtsp_src_receive_response (src, conninfo, response, code);
5548     case GST_RTSP_MESSAGE_RESPONSE:
5549       /* ok, a response is good */
5550       GST_DEBUG_OBJECT (src, "received response message");
5551       break;
5552     case GST_RTSP_MESSAGE_DATA:
5553       /* get next response */
5554       GST_DEBUG_OBJECT (src, "handle data response message");
5555       gst_rtspsrc_handle_data (src, response);
5556
5557       /* Not a response, receive next message */
5558       return gst_rtsp_src_receive_response (src, conninfo, response, code);
5559     default:
5560       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5561           response->type);
5562
5563       /* Not a response, receive next message */
5564       return gst_rtsp_src_receive_response (src, conninfo, response, code);
5565   }
5566
5567   thecode = response->type_data.response.code;
5568
5569   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5570
5571   /* if the caller wanted the result code, we store it. */
5572   if (code)
5573     *code = thecode;
5574
5575   /* If the request didn't succeed, bail out before doing any more */
5576   if (thecode != GST_RTSP_STS_OK)
5577     return GST_RTSP_OK;
5578
5579   /* store new content base if any */
5580   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5581       &content_base, 0);
5582   if (content_base) {
5583     g_free (src->content_base);
5584     src->content_base = g_strdup (content_base);
5585   }
5586
5587   return GST_RTSP_OK;
5588
5589   /* ERRORS */
5590 receive_error:
5591   {
5592     switch (res) {
5593       case GST_RTSP_EEOF:
5594         return GST_RTSP_EEOF;
5595       default:
5596       {
5597         gchar *str = gst_rtsp_strresult (res);
5598
5599         if (res != GST_RTSP_EINTR) {
5600           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5601               ("Could not receive message. (%s)", str));
5602         } else {
5603           GST_WARNING_OBJECT (src, "receive interrupted");
5604         }
5605         g_free (str);
5606         break;
5607       }
5608     }
5609     return res;
5610   }
5611 handle_request_failed:
5612   {
5613     /* ERROR was posted */
5614     gst_rtsp_message_unset (response);
5615     return res;
5616   }
5617 server_eof:
5618   {
5619     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5620     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5621         ("The server closed the connection."));
5622     gst_rtsp_message_unset (response);
5623     return res;
5624   }
5625 }
5626
5627
5628 static GstRTSPResult
5629 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
5630     GstRTSPMessage * request, GstRTSPMessage * response,
5631     GstRTSPStatusCode * code)
5632 {
5633   GstRTSPResult res;
5634   gint try = 0;
5635
5636 again:
5637   if (!src->short_header)
5638     gst_rtsp_ext_list_before_send (src->extensions, request);
5639
5640   GST_DEBUG_OBJECT (src, "sending message");
5641
5642   DEBUG_RTSP (src, request);
5643
5644   res = gst_rtspsrc_connection_send (src, conninfo, request, src->ptcp_timeout);
5645   if (res < 0)
5646     goto send_error;
5647
5648   gst_rtsp_connection_reset_timeout (conninfo->connection);
5649   if (!response)
5650     return res;
5651
5652   res = gst_rtsp_src_receive_response (src, conninfo, response, code);
5653   if (res == GST_RTSP_EEOF) {
5654     GST_WARNING_OBJECT (src, "server closed connection");
5655     /* only try once after reconnect, then fallthrough and error out */
5656     if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5657       try++;
5658       /* if reconnect succeeds, try again */
5659       if ((res = gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) == 0)
5660         goto again;
5661     }
5662   }
5663   gst_rtsp_ext_list_after_send (src->extensions, request, response);
5664
5665   return res;
5666
5667 send_error:
5668   {
5669     gchar *str = gst_rtsp_strresult (res);
5670
5671     if (res != GST_RTSP_EINTR) {
5672       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5673           ("Could not send message. (%s)", str));
5674     } else {
5675       GST_WARNING_OBJECT (src, "send interrupted");
5676     }
5677     g_free (str);
5678     return res;
5679   }
5680 }
5681
5682 /**
5683  * gst_rtspsrc_send:
5684  * @src: the rtsp source
5685  * @conninfo: the connection information to send on
5686  * @request: must point to a valid request
5687  * @response: must point to an empty #GstRTSPMessage
5688  * @code: an optional code result
5689  * @versions: List of versions to try, setting it back onto the @request message
5690  *            if not set, `src->version` will be used as RTSP version.
5691  *
5692  * send @request and retrieve the response in @response. optionally @code can be
5693  * non-NULL in which case it will contain the status code of the response.
5694  *
5695  * If This function returns #GST_RTSP_OK, @response will contain a valid response
5696  * message that should be cleaned with gst_rtsp_message_unset() after usage.
5697  *
5698  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5699  * @response message) if the response code was not 200 (OK).
5700  *
5701  * If the attempt results in an authentication failure, then this will attempt
5702  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5703  * the request.
5704  *
5705  * Returns: #GST_RTSP_OK if the processing was successful.
5706  */
5707 static GstRTSPResult
5708 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
5709     GstRTSPMessage * request, GstRTSPMessage * response,
5710     GstRTSPStatusCode * code, GstRTSPVersion * versions)
5711 {
5712   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5713   GstRTSPResult res = GST_RTSP_ERROR;
5714   gint count;
5715   gboolean retry;
5716   GstRTSPMethod method = GST_RTSP_INVALID;
5717   gint version_retry = 0;
5718
5719   count = 0;
5720   do {
5721     retry = FALSE;
5722
5723     /* make sure we don't loop forever */
5724     if (count++ > 8)
5725       break;
5726
5727     /* save method so we can disable it when the server complains */
5728     method = request->type_data.request.method;
5729
5730     if (!versions)
5731       request->type_data.request.version = src->version;
5732
5733     if ((res =
5734             gst_rtspsrc_try_send (src, conninfo, request, response,
5735                 &int_code)) < 0)
5736       goto error;
5737
5738     switch (int_code) {
5739       case GST_RTSP_STS_UNAUTHORIZED:
5740       case GST_RTSP_STS_NOT_FOUND:
5741         if (gst_rtspsrc_setup_auth (src, response)) {
5742           /* Try the request/response again after configuring the auth info
5743            * and loop again */
5744           retry = TRUE;
5745         }
5746         break;
5747       case GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED:
5748         GST_INFO_OBJECT (src, "Version %s not supported by the server",
5749             gst_rtsp_version_as_text (versions[version_retry]));
5750         if (versions && versions[version_retry] != GST_RTSP_VERSION_INVALID) {
5751           GST_INFO_OBJECT (src, "Unsupported version %s => trying %s",
5752               gst_rtsp_version_as_text (request->type_data.request.version),
5753               gst_rtsp_version_as_text (versions[version_retry]));
5754           request->type_data.request.version = versions[version_retry];
5755           retry = TRUE;
5756           version_retry++;
5757           break;
5758         }
5759         /* falltrough */
5760       default:
5761         break;
5762     }
5763   } while (retry == TRUE);
5764
5765   /* If the user requested the code, let them handle errors, otherwise
5766    * post an error below */
5767   if (code != NULL)
5768     *code = int_code;
5769   else if (int_code != GST_RTSP_STS_OK)
5770     goto error_response;
5771
5772   return res;
5773
5774   /* ERRORS */
5775 error:
5776   {
5777     GST_DEBUG_OBJECT (src, "got error %d", res);
5778     return res;
5779   }
5780 error_response:
5781   {
5782     res = GST_RTSP_ERROR;
5783
5784     switch (response->type_data.response.code) {
5785       case GST_RTSP_STS_NOT_FOUND:
5786         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_FOUND,
5787             "Not found");
5788         break;
5789       case GST_RTSP_STS_UNAUTHORIZED:
5790         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_AUTHORIZED,
5791             "Unauthorized");
5792         break;
5793       case GST_RTSP_STS_MOVED_PERMANENTLY:
5794       case GST_RTSP_STS_MOVE_TEMPORARILY:
5795       {
5796         gchar *new_location;
5797         GstRTSPLowerTrans transports;
5798
5799         GST_DEBUG_OBJECT (src, "got redirection");
5800         /* if we don't have a Location Header, we must error */
5801         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5802                 &new_location, 0) < 0)
5803           break;
5804
5805         /* When we receive a redirect result, we go back to the INIT state after
5806          * parsing the new URI. The caller should do the needed steps to issue
5807          * a new setup when it detects this state change. */
5808         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5809
5810         /* save current transports */
5811         if (src->conninfo.url)
5812           transports = src->conninfo.url->transports;
5813         else
5814           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5815
5816         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5817
5818         /* set old transports */
5819         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5820           src->conninfo.url->transports = transports;
5821
5822         src->need_redirect = TRUE;
5823         res = GST_RTSP_OK;
5824         break;
5825       }
5826       case GST_RTSP_STS_NOT_ACCEPTABLE:
5827       case GST_RTSP_STS_NOT_IMPLEMENTED:
5828       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5829         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5830             gst_rtsp_method_as_text (method));
5831         src->methods &= ~method;
5832         res = GST_RTSP_OK;
5833         break;
5834       default:
5835         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, READ,
5836             "Unhandled error");
5837         break;
5838     }
5839     /* if we return ERROR we should unset the response ourselves */
5840     if (res == GST_RTSP_ERROR)
5841       gst_rtsp_message_unset (response);
5842
5843     return res;
5844   }
5845 }
5846
5847 static GstRTSPResult
5848 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5849     GstRTSPMessage * response, GstRTSPSrc * src)
5850 {
5851   return gst_rtspsrc_send (src, &src->conninfo, request, response, NULL, NULL);
5852 }
5853
5854
5855 /* parse the response and collect all the supported methods. We need this
5856  * information so that we don't try to send an unsupported request to the
5857  * server.
5858  */
5859 static gboolean
5860 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5861 {
5862   GstRTSPHeaderField field;
5863   gchar *respoptions;
5864   gint indx = 0;
5865
5866   /* reset supported methods */
5867   src->methods = 0;
5868
5869   /* Try Allow Header first */
5870   field = GST_RTSP_HDR_ALLOW;
5871   while (TRUE) {
5872     respoptions = NULL;
5873     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5874     if (!respoptions)
5875       break;
5876
5877     src->methods |= gst_rtsp_options_from_text (respoptions);
5878
5879     indx++;
5880   }
5881
5882   indx = 0;
5883   field = GST_RTSP_HDR_PUBLIC;
5884   while (TRUE) {
5885     respoptions = NULL;
5886     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5887     if (!respoptions)
5888       break;
5889
5890     src->methods |= gst_rtsp_options_from_text (respoptions);
5891
5892     indx++;
5893   }
5894
5895   if (src->methods == 0) {
5896     /* neither Allow nor Public are required, assume the server supports
5897      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5898      * well. */
5899     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5900     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5901   }
5902   /* always assume PLAY, FIXME, extensions should be able to override
5903    * this */
5904   src->methods |= GST_RTSP_PLAY;
5905   /* also assume it will support Range */
5906   src->seekable = G_MAXDOUBLE;
5907
5908   /* we need describe and setup */
5909   if (!(src->methods & GST_RTSP_DESCRIBE))
5910     goto no_describe;
5911   if (!(src->methods & GST_RTSP_SETUP))
5912     goto no_setup;
5913
5914   return TRUE;
5915
5916   /* ERRORS */
5917 no_describe:
5918   {
5919     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5920         ("Server does not support DESCRIBE."));
5921     return FALSE;
5922   }
5923 no_setup:
5924   {
5925     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5926         ("Server does not support SETUP."));
5927     return FALSE;
5928   }
5929 }
5930
5931 /* masks to be kept in sync with the hardcoded protocol order of preference
5932  * in code below */
5933 static const guint protocol_masks[] = {
5934   GST_RTSP_LOWER_TRANS_UDP,
5935   GST_RTSP_LOWER_TRANS_UDP_MCAST,
5936   GST_RTSP_LOWER_TRANS_TCP,
5937   0
5938 };
5939
5940 static GstRTSPResult
5941 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5942     GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
5943 {
5944   GstRTSPResult res;
5945   GString *result;
5946   gboolean add_udp_str;
5947
5948   *transports = NULL;
5949
5950   res =
5951       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5952
5953   if (res < 0)
5954     goto failed;
5955
5956   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5957
5958   /* extension listed transports, use those */
5959   if (*transports != NULL)
5960     return GST_RTSP_OK;
5961
5962   /* it's the default */
5963   add_udp_str = FALSE;
5964
5965   /* the default RTSP transports */
5966   result = g_string_new ("RTP");
5967
5968   switch (profile) {
5969     case GST_RTSP_PROFILE_AVP:
5970       g_string_append (result, "/AVP");
5971       break;
5972     case GST_RTSP_PROFILE_SAVP:
5973       g_string_append (result, "/SAVP");
5974       break;
5975     case GST_RTSP_PROFILE_AVPF:
5976       g_string_append (result, "/AVPF");
5977       break;
5978     case GST_RTSP_PROFILE_SAVPF:
5979       g_string_append (result, "/SAVPF");
5980       break;
5981     default:
5982       break;
5983   }
5984
5985   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5986     GST_DEBUG_OBJECT (src, "adding UDP unicast");
5987     if (add_udp_str)
5988       g_string_append (result, "/UDP");
5989     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5990   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5991     GST_DEBUG_OBJECT (src, "adding UDP multicast");
5992     /* we don't have to allocate any UDP ports yet, if the selected transport
5993      * turns out to be multicast we can create them and join the multicast
5994      * group indicated in the transport reply */
5995     if (add_udp_str)
5996       g_string_append (result, "/UDP");
5997     g_string_append (result, ";multicast");
5998     if (src->next_port_num != 0) {
5999       if (src->client_port_range.max > 0 &&
6000           src->next_port_num >= src->client_port_range.max)
6001         goto no_ports;
6002
6003       g_string_append_printf (result, ";client_port=%d-%d",
6004           src->next_port_num, src->next_port_num + 1);
6005     }
6006   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
6007     GST_DEBUG_OBJECT (src, "adding TCP");
6008
6009     g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
6010   }
6011   *transports = g_string_free (result, FALSE);
6012
6013   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
6014
6015   return GST_RTSP_OK;
6016
6017   /* ERRORS */
6018 failed:
6019   {
6020     GST_ERROR ("extension gave error %d", res);
6021     return res;
6022   }
6023 no_ports:
6024   {
6025     GST_ERROR ("no more ports available");
6026     return GST_RTSP_ERROR;
6027   }
6028 }
6029
6030 static GstRTSPResult
6031 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
6032     gint orig_rtpport, gint orig_rtcpport)
6033 {
6034   GstRTSPSrc *src;
6035   gint nr_udp, nr_int;
6036   gchar *next, *p;
6037   gint rtpport = 0, rtcpport = 0;
6038   GString *str;
6039
6040   src = stream->parent;
6041
6042   /* find number of placeholders first */
6043   if (strstr (*transports, "%%i2"))
6044     nr_int = 2;
6045   else if (strstr (*transports, "%%i1"))
6046     nr_int = 1;
6047   else
6048     nr_int = 0;
6049
6050   if (strstr (*transports, "%%u2"))
6051     nr_udp = 2;
6052   else if (strstr (*transports, "%%u1"))
6053     nr_udp = 1;
6054   else
6055     nr_udp = 0;
6056
6057   if (nr_udp == 0 && nr_int == 0)
6058     goto done;
6059
6060   if (nr_udp > 0) {
6061     if (!orig_rtpport || !orig_rtcpport) {
6062       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
6063         goto failed;
6064     } else {
6065       rtpport = orig_rtpport;
6066       rtcpport = orig_rtcpport;
6067     }
6068   }
6069
6070   str = g_string_new ("");
6071   p = *transports;
6072   while ((next = strstr (p, "%%"))) {
6073     g_string_append_len (str, p, next - p);
6074     if (next[2] == 'u') {
6075       if (next[3] == '1')
6076         g_string_append_printf (str, "%d", rtpport);
6077       else if (next[3] == '2')
6078         g_string_append_printf (str, "%d", rtcpport);
6079     }
6080     if (next[2] == 'i') {
6081       if (next[3] == '1')
6082         g_string_append_printf (str, "%d", src->free_channel);
6083       else if (next[3] == '2')
6084         g_string_append_printf (str, "%d", src->free_channel + 1);
6085
6086     }
6087
6088     p = next + 4;
6089   }
6090   if (src->version >= GST_RTSP_VERSION_2_0)
6091     src->free_channel += 2;
6092
6093   /* append final part */
6094   g_string_append (str, p);
6095
6096   g_free (*transports);
6097   *transports = g_string_free (str, FALSE);
6098
6099 done:
6100   return GST_RTSP_OK;
6101
6102   /* ERRORS */
6103 failed:
6104   {
6105     GST_ERROR ("failed to allocate udp ports");
6106     return GST_RTSP_ERROR;
6107   }
6108 }
6109
6110 static GstCaps *
6111 signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
6112 {
6113   GstCaps *caps = NULL;
6114
6115   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
6116       stream->id, &caps);
6117
6118   if (caps != NULL)
6119     GST_DEBUG_OBJECT (src, "SRTP parameters received");
6120
6121   return caps;
6122 }
6123
6124 static GstCaps *
6125 default_srtcp_params (void)
6126 {
6127   guint i;
6128   GstCaps *caps;
6129   GstBuffer *buf;
6130   guint8 *key_data;
6131 #define KEY_SIZE 30
6132   guint data_size = GST_ROUND_UP_4 (KEY_SIZE);
6133
6134   /* create a random key */
6135   key_data = g_malloc (data_size);
6136   for (i = 0; i < data_size; i += 4)
6137     GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
6138
6139   buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
6140
6141   caps = gst_caps_new_simple ("application/x-srtcp",
6142       "srtp-key", GST_TYPE_BUFFER, buf,
6143       "srtp-cipher", G_TYPE_STRING, "aes-128-icm",
6144       "srtp-auth", G_TYPE_STRING, "hmac-sha1-80",
6145       "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
6146       "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
6147
6148   gst_buffer_unref (buf);
6149
6150   return caps;
6151 }
6152
6153 static gchar *
6154 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
6155 {
6156   gchar *base64, *result = NULL;
6157   GstMIKEYMessage *mikey_msg;
6158
6159   stream->srtcpparams = signal_get_srtcp_params (src, stream);
6160   if (stream->srtcpparams == NULL)
6161     stream->srtcpparams = default_srtcp_params ();
6162
6163   mikey_msg = gst_mikey_message_new_from_caps (stream->srtcpparams);
6164   if (mikey_msg) {
6165     /* add policy '0' for our SSRC */
6166     gst_mikey_message_add_cs_srtp (mikey_msg, 0, stream->send_ssrc, 0);
6167
6168     base64 = gst_mikey_message_base64_encode (mikey_msg);
6169     gst_mikey_message_unref (mikey_msg);
6170
6171     if (base64) {
6172       result = gst_sdp_make_keymgmt (stream->conninfo.location, base64);
6173       g_free (base64);
6174     }
6175   }
6176
6177   return result;
6178 }
6179
6180 static GstRTSPResult
6181 gst_rtsp_src_setup_stream_from_response (GstRTSPSrc * src,
6182     GstRTSPStream * stream, GstRTSPMessage * response,
6183     GstRTSPLowerTrans * protocols, gint retry, gint * rtpport, gint * rtcpport)
6184 {
6185   gchar *resptrans = NULL;
6186   GstRTSPTransport transport = { 0 };
6187
6188   gst_rtsp_message_get_header (response, GST_RTSP_HDR_TRANSPORT, &resptrans, 0);
6189   if (!resptrans) {
6190     gst_rtspsrc_stream_free_udp (stream);
6191     goto no_transport;
6192   }
6193
6194   /* parse transport, go to next stream on parse error */
6195   if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6196     GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6197     return GST_RTSP_ELAST;
6198   }
6199
6200   /* update allowed transports for other streams. once the transport of
6201    * one stream has been determined, we make sure that all other streams
6202    * are configured in the same way */
6203   switch (transport.lower_transport) {
6204     case GST_RTSP_LOWER_TRANS_TCP:
6205       GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6206       if (protocols)
6207         *protocols = GST_RTSP_LOWER_TRANS_TCP;
6208       src->interleaved = TRUE;
6209       if (src->version < GST_RTSP_VERSION_2_0) {
6210         /* update free channels */
6211         src->free_channel = MAX (transport.interleaved.min, src->free_channel);
6212         src->free_channel = MAX (transport.interleaved.max, src->free_channel);
6213         src->free_channel++;
6214       }
6215       break;
6216     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6217       /* only allow multicast for other streams */
6218       GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6219       if (protocols)
6220         *protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6221       /* if the server selected our ports, increment our counters so that
6222        * we select a new port later */
6223       if (src->next_port_num == transport.port.min &&
6224           src->next_port_num + 1 == transport.port.max) {
6225         src->next_port_num += 2;
6226       }
6227       break;
6228     case GST_RTSP_LOWER_TRANS_UDP:
6229       /* only allow unicast for other streams */
6230       GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6231       if (protocols)
6232         *protocols = GST_RTSP_LOWER_TRANS_UDP;
6233       break;
6234     default:
6235       GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6236           transport.lower_transport);
6237       break;
6238   }
6239
6240   if (!src->interleaved || !retry) {
6241     /* now configure the stream with the selected transport */
6242     if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6243       GST_DEBUG_OBJECT (src,
6244           "could not configure stream %p transport, skipping stream", stream);
6245       goto done;
6246     } else if (stream->udpsrc[0] && stream->udpsrc[1] && rtpport && rtcpport) {
6247       /* retain the first allocated UDP port pair */
6248       g_object_get (G_OBJECT (stream->udpsrc[0]), "port", rtpport, NULL);
6249       g_object_get (G_OBJECT (stream->udpsrc[1]), "port", rtcpport, NULL);
6250     }
6251   }
6252   /* we need to activate at least one stream when we detect activity */
6253   src->need_activate = TRUE;
6254
6255   /* stream is setup now */
6256   stream->setup = TRUE;
6257   stream->waiting_setup_response = FALSE;
6258
6259   if (src->version >= GST_RTSP_VERSION_2_0) {
6260     gchar *prop, *media_properties;
6261     gchar **props;
6262     gint i;
6263
6264     if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_MEDIA_PROPERTIES,
6265             &media_properties, 0) != GST_RTSP_OK) {
6266       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6267           ("Error: No MEDIA_PROPERTY header in a SETUP request in RTSP 2.0"
6268               " - this header is mandatory."));
6269
6270       gst_rtsp_message_unset (response);
6271       return GST_RTSP_ERROR;
6272     }
6273
6274     props = g_strsplit (media_properties, ",", -2);
6275     for (i = 0; props[i]; i++) {
6276       prop = props[i];
6277
6278       while (*prop == ' ')
6279         prop++;
6280
6281       if (strstr (prop, "Random-Access")) {
6282         gchar **random_seekable_val = g_strsplit (prop, "=", 2);
6283
6284         if (!random_seekable_val[1])
6285           src->seekable = G_MAXDOUBLE;
6286         else
6287           src->seekable = g_ascii_strtod (random_seekable_val[1], NULL);
6288
6289         g_strfreev (random_seekable_val);
6290       } else if (!g_strcmp0 (prop, "No-Seeking")) {
6291         src->seekable = -1.0;
6292       } else if (!g_strcmp0 (prop, "Beginning-Only")) {
6293         src->seekable = 0.0;
6294       }
6295     }
6296
6297     g_strfreev (props);
6298   }
6299
6300 done:
6301   /* clean up our transport struct */
6302   gst_rtsp_transport_init (&transport);
6303   /* clean up used RTSP messages */
6304   gst_rtsp_message_unset (response);
6305
6306   return GST_RTSP_OK;
6307
6308 no_transport:
6309   {
6310     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6311         ("Server did not select transport."));
6312
6313     gst_rtsp_message_unset (response);
6314     return GST_RTSP_ERROR;
6315   }
6316 }
6317
6318 static GstRTSPResult
6319 gst_rtspsrc_setup_streams_end (GstRTSPSrc * src, gboolean async)
6320 {
6321   GList *tmp;
6322   GstRTSPConnInfo *conninfo;
6323
6324   g_assert (src->version >= GST_RTSP_VERSION_2_0);
6325
6326   conninfo = &src->conninfo;
6327   for (tmp = src->streams; tmp; tmp = tmp->next) {
6328     GstRTSPStream *stream = (GstRTSPStream *) tmp->data;
6329     GstRTSPMessage response = { 0, };
6330
6331     if (!stream->waiting_setup_response)
6332       continue;
6333
6334     if (!src->conninfo.connection)
6335       conninfo = &((GstRTSPStream *) tmp->data)->conninfo;
6336
6337     gst_rtsp_src_receive_response (src, conninfo, &response, NULL);
6338
6339     gst_rtsp_src_setup_stream_from_response (src, stream,
6340         &response, NULL, 0, NULL, NULL);
6341   }
6342
6343   return GST_RTSP_OK;
6344 }
6345
6346 /* Perform the SETUP request for all the streams.
6347  *
6348  * We ask the server for a specific transport, which initially includes all the
6349  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6350  * two local UDP ports that we send to the server.
6351  *
6352  * Once the server replied with a transport, we configure the other streams
6353  * with the same transport.
6354  *
6355  * In case setup request are not pipelined, this function will also configure the
6356  * stream for the selected transport, * which basically means creating the pipeline.
6357  * Otherwise, the first stream is setup right away from the reply and a
6358  * CMD_FINALIZE_SETUP command is set for the stream pipelines to happen on the
6359  * remaining streams from the RTSP thread.
6360  */
6361 static GstRTSPResult
6362 gst_rtspsrc_setup_streams_start (GstRTSPSrc * src, gboolean async)
6363 {
6364   GList *walk;
6365   GstRTSPResult res = GST_RTSP_ERROR;
6366   GstRTSPMessage request = { 0 };
6367   GstRTSPMessage response = { 0 };
6368   GstRTSPStream *stream = NULL;
6369   GstRTSPLowerTrans protocols;
6370   GstRTSPStatusCode code;
6371   gboolean unsupported_real = FALSE;
6372   gint rtpport, rtcpport;
6373   GstRTSPUrl *url;
6374   gchar *hval;
6375   gchar *pipelined_request_id = NULL;
6376
6377   if (src->conninfo.connection) {
6378     url = gst_rtsp_connection_get_url (src->conninfo.connection);
6379     /* we initially allow all configured lower transports. based on the URL
6380      * transports and the replies from the server we narrow them down. */
6381     protocols = url->transports & src->cur_protocols;
6382   } else {
6383     url = NULL;
6384     protocols = src->cur_protocols;
6385   }
6386
6387   if (protocols == 0)
6388     goto no_protocols;
6389
6390   /* reset some state */
6391   src->free_channel = 0;
6392   src->interleaved = FALSE;
6393   src->need_activate = FALSE;
6394   /* keep track of next port number, 0 is random */
6395   src->next_port_num = src->client_port_range.min;
6396   rtpport = rtcpport = 0;
6397
6398   if (G_UNLIKELY (src->streams == NULL))
6399     goto no_streams;
6400
6401   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6402     GstRTSPConnInfo *conninfo;
6403     gchar *transports;
6404     gint retry = 0;
6405     guint mask = 0;
6406     gboolean selected;
6407     GstCaps *caps;
6408
6409     stream = (GstRTSPStream *) walk->data;
6410
6411     caps = stream_get_caps_for_pt (stream, stream->default_pt);
6412     if (caps == NULL) {
6413       GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
6414       continue;
6415     }
6416
6417     if (stream->skipped) {
6418       GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6419       continue;
6420     }
6421
6422     /* see if we need to configure this stream */
6423     if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6424       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6425           stream);
6426       continue;
6427     }
6428
6429     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6430         stream->id, caps, &selected);
6431     if (!selected) {
6432       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6433       continue;
6434     }
6435
6436     /* merge/overwrite global caps */
6437     if (caps) {
6438       guint j, num;
6439       GstStructure *s;
6440
6441       s = gst_caps_get_structure (caps, 0);
6442
6443       num = gst_structure_n_fields (src->props);
6444       for (j = 0; j < num; j++) {
6445         const gchar *name;
6446         const GValue *val;
6447
6448         name = gst_structure_nth_field_name (src->props, j);
6449         val = gst_structure_get_value (src->props, name);
6450         gst_structure_set_value (s, name, val);
6451
6452         GST_DEBUG_OBJECT (src, "copied %s", name);
6453       }
6454     }
6455
6456     /* skip setup if we have no URL for it */
6457     if (stream->conninfo.location == NULL) {
6458       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6459       continue;
6460     }
6461
6462     if (src->conninfo.connection == NULL) {
6463       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6464         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6465         continue;
6466       }
6467       conninfo = &stream->conninfo;
6468     } else {
6469       conninfo = &src->conninfo;
6470     }
6471     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6472         stream->conninfo.location);
6473
6474     /* if we have a multicast connection, only suggest multicast from now on */
6475     if (stream->is_multicast)
6476       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6477
6478   next_protocol:
6479     /* first selectable protocol */
6480     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6481       mask++;
6482     if (!protocol_masks[mask])
6483       goto no_protocols;
6484
6485   retry:
6486     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6487         protocol_masks[mask]);
6488     /* create a string with first transport in line */
6489     transports = NULL;
6490     res = gst_rtspsrc_create_transports_string (src,
6491         protocols & protocol_masks[mask], stream->profile, &transports);
6492     if (res < 0 || transports == NULL)
6493       goto setup_transport_failed;
6494
6495     if (strlen (transports) == 0) {
6496       g_free (transports);
6497       GST_DEBUG_OBJECT (src, "no transports found");
6498       mask++;
6499       goto next_protocol;
6500     }
6501
6502     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6503
6504     /* replace placeholders with real values, this function will optionally
6505      * allocate UDP ports and other info needed to execute the setup request */
6506     res = gst_rtspsrc_prepare_transports (stream, &transports,
6507         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6508     if (res < 0) {
6509       g_free (transports);
6510       goto setup_transport_failed;
6511     }
6512
6513     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6514     /* create SETUP request */
6515     res =
6516         gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
6517         stream->conninfo.location);
6518     if (res < 0) {
6519       g_free (transports);
6520       goto create_request_failed;
6521     }
6522
6523     if (src->version >= GST_RTSP_VERSION_2_0) {
6524       if (!pipelined_request_id)
6525         pipelined_request_id = g_strdup_printf ("%d",
6526             g_random_int_range (0, G_MAXINT32));
6527
6528       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_PIPELINED_REQUESTS,
6529           pipelined_request_id);
6530       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT_RANGES,
6531           "npt, clock, smpte, clock");
6532     }
6533
6534     /* select transport */
6535     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6536
6537     /* set up keys */
6538     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6539         stream->profile == GST_RTSP_PROFILE_SAVPF) {
6540       hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6541       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6542     }
6543
6544     /* if the user wants a non default RTP packet size we add the blocksize
6545      * parameter */
6546     if (src->rtp_blocksize > 0) {
6547       hval = g_strdup_printf ("%d", src->rtp_blocksize);
6548       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6549     }
6550
6551     if (async)
6552       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6553               stream->id));
6554
6555     /* handle the code ourselves */
6556     res =
6557         gst_rtspsrc_send (src, conninfo, &request,
6558         pipelined_request_id ? NULL : &response, &code, NULL);
6559     if (res < 0)
6560       goto send_error;
6561
6562     switch (code) {
6563       case GST_RTSP_STS_OK:
6564         break;
6565       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6566         gst_rtsp_message_unset (&request);
6567         gst_rtsp_message_unset (&response);
6568         /* cleanup of leftover transport */
6569         gst_rtspsrc_stream_free_udp (stream);
6570         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6571          * we might be in this case */
6572         if (stream->container && rtpport && rtcpport && !retry) {
6573           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6574               rtpport, rtcpport);
6575           retry++;
6576           goto retry;
6577         }
6578         /* this transport did not go down well, but we may have others to try
6579          * that we did not send yet, try those and only give up then
6580          * but not without checking for lost cause/extension so we can
6581          * post a nicer/more useful error message later */
6582         if (!unsupported_real)
6583           unsupported_real = stream->is_real;
6584         /* select next available protocol, give up on this stream if none */
6585         mask++;
6586         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6587           mask++;
6588         if (!protocol_masks[mask] || unsupported_real)
6589           continue;
6590         else
6591           goto retry;
6592       default:
6593         /* cleanup of leftover transport and move to the next stream */
6594         gst_rtspsrc_stream_free_udp (stream);
6595         goto response_error;
6596     }
6597
6598
6599     if (!pipelined_request_id) {
6600       /* parse response transport */
6601       res = gst_rtsp_src_setup_stream_from_response (src, stream,
6602           &response, &protocols, retry, &rtpport, &rtcpport);
6603       switch (res) {
6604         case GST_RTSP_ERROR:
6605           goto cleanup_error;
6606         case GST_RTSP_ELAST:
6607           goto retry;
6608         default:
6609           break;
6610       }
6611     } else {
6612       stream->waiting_setup_response = TRUE;
6613       /* we need to activate at least one stream when we detect activity */
6614       src->need_activate = TRUE;
6615     }
6616
6617     {
6618       GList *skip = walk;
6619
6620       while (TRUE) {
6621         GstRTSPStream *sskip;
6622
6623         skip = g_list_next (skip);
6624         if (skip == NULL)
6625           break;
6626
6627         sskip = (GstRTSPStream *) skip->data;
6628
6629         /* skip all streams with the same control url */
6630         if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6631           GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6632               sskip, sskip->conninfo.location);
6633           sskip->skipped = TRUE;
6634         }
6635       }
6636     }
6637     gst_rtsp_message_unset (&request);
6638   }
6639
6640   if (pipelined_request_id) {
6641     gst_rtspsrc_setup_streams_end (src, TRUE);
6642   }
6643
6644   /* store the transport protocol that was configured */
6645   src->cur_protocols = protocols;
6646
6647   gst_rtsp_ext_list_stream_select (src->extensions, url);
6648
6649   /* if there is nothing to activate, error out */
6650   if (!src->need_activate)
6651     goto nothing_to_activate;
6652
6653   return res;
6654
6655   /* ERRORS */
6656 no_protocols:
6657   {
6658     /* no transport possible, post an error and stop */
6659     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6660         ("Could not connect to server, no protocols left"));
6661     return GST_RTSP_ERROR;
6662   }
6663 no_streams:
6664   {
6665     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6666         ("SDP contains no streams"));
6667     return GST_RTSP_ERROR;
6668   }
6669 create_request_failed:
6670   {
6671     gchar *str = gst_rtsp_strresult (res);
6672
6673     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6674         ("Could not create request. (%s)", str));
6675     g_free (str);
6676     goto cleanup_error;
6677   }
6678 setup_transport_failed:
6679   {
6680     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6681         ("Could not setup transport."));
6682     res = GST_RTSP_ERROR;
6683     goto cleanup_error;
6684   }
6685 response_error:
6686   {
6687     const gchar *str = gst_rtsp_status_as_text (code);
6688
6689     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6690         ("Error (%d): %s", code, GST_STR_NULL (str)));
6691     res = GST_RTSP_ERROR;
6692     goto cleanup_error;
6693   }
6694 send_error:
6695   {
6696     gchar *str = gst_rtsp_strresult (res);
6697
6698     if (res != GST_RTSP_EINTR) {
6699       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6700           ("Could not send message. (%s)", str));
6701     } else {
6702       GST_WARNING_OBJECT (src, "send interrupted");
6703     }
6704     g_free (str);
6705     goto cleanup_error;
6706   }
6707 nothing_to_activate:
6708   {
6709     /* none of the available error codes is really right .. */
6710     if (unsupported_real) {
6711       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6712           (_("No supported stream was found. You might need to install a "
6713                   "GStreamer RTSP extension plugin for Real media streams.")),
6714           (NULL));
6715     } else {
6716       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6717           (_("No supported stream was found. You might need to allow "
6718                   "more transport protocols or may otherwise be missing "
6719                   "the right GStreamer RTSP extension plugin.")), (NULL));
6720     }
6721     return GST_RTSP_ERROR;
6722   }
6723 cleanup_error:
6724   {
6725     gst_rtsp_message_unset (&request);
6726     gst_rtsp_message_unset (&response);
6727     return res;
6728   }
6729 }
6730
6731 static gboolean
6732 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6733     GstSegment * segment)
6734 {
6735   gint64 seconds;
6736   GstRTSPTimeRange *therange;
6737
6738   if (src->range)
6739     gst_rtsp_range_free (src->range);
6740
6741   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6742     GST_DEBUG_OBJECT (src, "parsed range %s", range);
6743     src->range = therange;
6744   } else {
6745     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6746     src->range = NULL;
6747     gst_segment_init (segment, GST_FORMAT_TIME);
6748     return FALSE;
6749   }
6750
6751   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
6752       therange->min.type, therange->min.seconds, therange->max.type,
6753       therange->max.seconds);
6754
6755   if (therange->min.type == GST_RTSP_TIME_NOW)
6756     seconds = 0;
6757   else if (therange->min.type == GST_RTSP_TIME_END)
6758     seconds = 0;
6759   else
6760     seconds = therange->min.seconds * GST_SECOND;
6761
6762   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6763       GST_TIME_ARGS (seconds));
6764
6765   /* we need to start playback without clipping from the position reported by
6766    * the server */
6767   segment->start = seconds;
6768   segment->position = seconds;
6769
6770   if (therange->max.type == GST_RTSP_TIME_NOW)
6771     seconds = -1;
6772   else if (therange->max.type == GST_RTSP_TIME_END)
6773     seconds = -1;
6774   else
6775     seconds = therange->max.seconds * GST_SECOND;
6776
6777   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6778       GST_TIME_ARGS (seconds));
6779
6780   /* live (WMS) server might send overflowed large max as its idea of infinity,
6781    * compensate to prevent problems later on */
6782   if (seconds != -1 && seconds < 0) {
6783     seconds = -1;
6784     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6785   }
6786
6787   /* live (WMS) might send min == max, which is not worth recording */
6788   if (segment->duration == -1 && seconds == segment->start)
6789     seconds = -1;
6790
6791   /* don't change duration with unknown value, we might have a valid value
6792    * there that we want to keep. */
6793   if (seconds != -1)
6794     segment->duration = seconds;
6795
6796   return TRUE;
6797 }
6798
6799 /* Parse clock profived by the server with following syntax:
6800  *
6801  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6802  */
6803 static gboolean
6804 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6805 {
6806   gboolean res = FALSE;
6807
6808   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6809     gchar **fields = NULL, **parts = NULL;
6810     gchar *remote_ip, *str;
6811     gint port;
6812     GstClockTime base_time;
6813     GstClock *netclock;
6814
6815     fields = g_strsplit (gstclock, " ", 0);
6816
6817     /* wrapped clock, not very interesting for now */
6818     if (fields[1] == NULL)
6819       goto cleanup;
6820
6821     /* remote IP address and port */
6822     if ((str = fields[2]) == NULL)
6823       goto cleanup;
6824
6825     parts = g_strsplit (str, ":", 0);
6826
6827     if ((remote_ip = parts[0]) == NULL)
6828       goto cleanup;
6829
6830     if ((str = parts[1]) == NULL)
6831       goto cleanup;
6832
6833     port = atoi (str);
6834     if (port == 0)
6835       goto cleanup;
6836
6837     /* base-time */
6838     if ((str = fields[3]) == NULL)
6839       goto cleanup;
6840
6841     base_time = g_ascii_strtoull (str, NULL, 10);
6842
6843     netclock =
6844         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
6845         base_time);
6846
6847     if (src->provided_clock)
6848       gst_object_unref (src->provided_clock);
6849     src->provided_clock = netclock;
6850
6851     gst_element_post_message (GST_ELEMENT_CAST (src),
6852         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
6853             src->provided_clock, TRUE));
6854
6855     res = TRUE;
6856   cleanup:
6857     g_strfreev (fields);
6858     g_strfreev (parts);
6859   }
6860   return res;
6861 }
6862
6863 /* must be called with the RTSP state lock */
6864 static GstRTSPResult
6865 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
6866     gboolean async)
6867 {
6868   GstRTSPResult res;
6869   gint i, n_streams;
6870
6871   /* prepare global stream caps properties */
6872   if (src->props)
6873     gst_structure_remove_all_fields (src->props);
6874   else
6875     src->props = gst_structure_new_empty ("RTSPProperties");
6876
6877   DEBUG_SDP (src, sdp);
6878
6879   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
6880
6881   /* let the app inspect and change the SDP */
6882   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
6883
6884   gst_segment_init (&src->segment, GST_FORMAT_TIME);
6885
6886   /* parse range for duration reporting. */
6887   {
6888     const gchar *range;
6889
6890     for (i = 0;; i++) {
6891       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
6892       if (range == NULL)
6893         break;
6894
6895       /* keep track of the range and configure it in the segment */
6896       if (gst_rtspsrc_parse_range (src, range, &src->segment))
6897         break;
6898     }
6899   }
6900   /* parse clock information. This is GStreamer specific, a server can tell the
6901    * client what clock it is using and wrap that in a network clock. The
6902    * advantage of that is that we can slave to it. */
6903   {
6904     const gchar *gstclock;
6905
6906     for (i = 0;; i++) {
6907       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6908       if (gstclock == NULL)
6909         break;
6910
6911       /* parse the clock and expose it in the provide_clock method */
6912       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6913         break;
6914     }
6915   }
6916   /* try to find a global control attribute. Note that a '*' means that we should
6917    * do aggregate control with the current url (so we don't do anything and
6918    * leave the current connection as is) */
6919   {
6920     const gchar *control;
6921
6922     for (i = 0;; i++) {
6923       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6924       if (control == NULL)
6925         break;
6926
6927       /* only take fully qualified urls */
6928       if (g_str_has_prefix (control, "rtsp://"))
6929         break;
6930     }
6931     if (control) {
6932       g_free (src->conninfo.location);
6933       src->conninfo.location = g_strdup (control);
6934       /* make a connection for this, if there was a connection already, nothing
6935        * happens. */
6936       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6937         GST_ERROR_OBJECT (src, "could not connect");
6938       }
6939     }
6940     /* we need to keep the control url separate from the connection url because
6941      * the rules for constructing the media control url need it */
6942     g_free (src->control);
6943     src->control = g_strdup (control);
6944   }
6945
6946   /* create streams */
6947   n_streams = gst_sdp_message_medias_len (sdp);
6948   for (i = 0; i < n_streams; i++) {
6949     gst_rtspsrc_create_stream (src, sdp, i, n_streams);
6950   }
6951
6952   src->state = GST_RTSP_STATE_INIT;
6953
6954   /* setup streams */
6955   if ((res = gst_rtspsrc_setup_streams_start (src, async)) < 0)
6956     goto setup_failed;
6957
6958   /* reset our state */
6959   src->need_range = TRUE;
6960   src->skip = FALSE;
6961
6962   src->state = GST_RTSP_STATE_READY;
6963
6964   return res;
6965
6966   /* ERRORS */
6967 setup_failed:
6968   {
6969     GST_ERROR_OBJECT (src, "setup failed");
6970     gst_rtspsrc_cleanup (src);
6971     return res;
6972   }
6973 }
6974
6975 static GstRTSPResult
6976 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6977     gboolean async)
6978 {
6979   GstRTSPResult res;
6980   GstRTSPMessage request = { 0 };
6981   GstRTSPMessage response = { 0 };
6982   guint8 *data;
6983   guint size;
6984   gchar *respcont = NULL;
6985   GstRTSPVersion versions[] =
6986       { GST_RTSP_VERSION_2_0, GST_RTSP_VERSION_INVALID };
6987
6988   src->version = src->default_version;
6989   if (src->default_version == GST_RTSP_VERSION_2_0) {
6990     versions[0] = GST_RTSP_VERSION_1_0;
6991   }
6992
6993 restart:
6994   src->need_redirect = FALSE;
6995
6996   /* can't continue without a valid url */
6997   if (G_UNLIKELY (src->conninfo.url == NULL)) {
6998     res = GST_RTSP_EINVAL;
6999     goto no_url;
7000   }
7001   src->tried_url_auth = FALSE;
7002
7003   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
7004     goto connect_failed;
7005
7006   /* create OPTIONS */
7007   GST_DEBUG_OBJECT (src, "create options... (%s)", async ? "async" : "sync");
7008   res =
7009       gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
7010       src->conninfo.url_str);
7011   if (res < 0)
7012     goto create_request_failed;
7013
7014   /* send OPTIONS */
7015   request.type_data.request.version = src->version;
7016   GST_DEBUG_OBJECT (src, "send options...");
7017
7018   if (async)
7019     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
7020
7021   if ((res =
7022           gst_rtspsrc_send (src, &src->conninfo, &request, &response,
7023               NULL, versions)) < 0) {
7024     goto send_error;
7025   }
7026
7027   src->version = request.type_data.request.version;
7028   GST_INFO_OBJECT (src, "Now using version: %s",
7029       gst_rtsp_version_as_text (src->version));
7030
7031   /* parse OPTIONS */
7032   if (!gst_rtspsrc_parse_methods (src, &response))
7033     goto methods_error;
7034
7035   /* create DESCRIBE */
7036   GST_DEBUG_OBJECT (src, "create describe...");
7037   res =
7038       gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
7039       src->conninfo.url_str);
7040   if (res < 0)
7041     goto create_request_failed;
7042
7043   /* we only accept SDP for now */
7044   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
7045       "application/sdp");
7046
7047   /* send DESCRIBE */
7048   GST_DEBUG_OBJECT (src, "send describe...");
7049
7050   if (async)
7051     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
7052
7053   if ((res =
7054           gst_rtspsrc_send (src, &src->conninfo, &request, &response,
7055               NULL, NULL)) < 0)
7056     goto send_error;
7057
7058   /* we only perform redirect for describe and play, currently */
7059   if (src->need_redirect) {
7060     /* close connection, we don't have to send a TEARDOWN yet, ignore the
7061      * result. */
7062     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7063
7064     gst_rtsp_message_unset (&request);
7065     gst_rtsp_message_unset (&response);
7066
7067     /* and now retry */
7068     goto restart;
7069   }
7070
7071   /* it could be that the DESCRIBE method was not implemented */
7072   if (!(src->methods & GST_RTSP_DESCRIBE))
7073     goto no_describe;
7074
7075   /* check if reply is SDP */
7076   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
7077       0);
7078   /* could not be set but since the request returned OK, we assume it
7079    * was SDP, else check it. */
7080   if (respcont) {
7081     const gchar *props = strchr (respcont, ';');
7082
7083     if (props) {
7084       gchar *mimetype = g_strndup (respcont, props - respcont);
7085
7086       mimetype = g_strstrip (mimetype);
7087       if (g_ascii_strcasecmp (mimetype, "application/sdp") != 0) {
7088         g_free (mimetype);
7089         goto wrong_content_type;
7090       }
7091
7092       /* TODO: Check for charset property and do conversions of all messages if
7093        * needed. Some servers actually send that property */
7094
7095       g_free (mimetype);
7096     } else if (g_ascii_strcasecmp (respcont, "application/sdp") != 0) {
7097       goto wrong_content_type;
7098     }
7099   }
7100
7101   /* get message body and parse as SDP */
7102   gst_rtsp_message_get_body (&response, &data, &size);
7103   if (data == NULL || size == 0)
7104     goto no_describe;
7105
7106   GST_DEBUG_OBJECT (src, "parse SDP...");
7107   gst_sdp_message_new (sdp);
7108   gst_sdp_message_parse_buffer (data, size, *sdp);
7109
7110   /* clean up any messages */
7111   gst_rtsp_message_unset (&request);
7112   gst_rtsp_message_unset (&response);
7113
7114   return res;
7115
7116   /* ERRORS */
7117 no_url:
7118   {
7119     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
7120         ("No valid RTSP URL was provided"));
7121     goto cleanup_error;
7122   }
7123 connect_failed:
7124   {
7125     gchar *str = gst_rtsp_strresult (res);
7126
7127     if (res != GST_RTSP_EINTR) {
7128       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
7129           ("Failed to connect. (%s)", str));
7130     } else {
7131       GST_WARNING_OBJECT (src, "connect interrupted");
7132     }
7133     g_free (str);
7134     goto cleanup_error;
7135   }
7136 create_request_failed:
7137   {
7138     gchar *str = gst_rtsp_strresult (res);
7139
7140     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7141         ("Could not create request. (%s)", str));
7142     g_free (str);
7143     goto cleanup_error;
7144   }
7145 send_error:
7146   {
7147     /* Don't post a message - the rtsp_send method will have
7148      * taken care of it because we passed NULL for the response code */
7149     goto cleanup_error;
7150   }
7151 methods_error:
7152   {
7153     /* error was posted */
7154     res = GST_RTSP_ERROR;
7155     goto cleanup_error;
7156   }
7157 wrong_content_type:
7158   {
7159     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7160         ("Server does not support SDP, got %s.", respcont));
7161     res = GST_RTSP_ERROR;
7162     goto cleanup_error;
7163   }
7164 no_describe:
7165   {
7166     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7167         ("Server can not provide an SDP."));
7168     res = GST_RTSP_ERROR;
7169     goto cleanup_error;
7170   }
7171 cleanup_error:
7172   {
7173     if (src->conninfo.connection) {
7174       GST_DEBUG_OBJECT (src, "free connection");
7175       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7176     }
7177     gst_rtsp_message_unset (&request);
7178     gst_rtsp_message_unset (&response);
7179     return res;
7180   }
7181 }
7182
7183 static GstRTSPResult
7184 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
7185 {
7186   GstRTSPResult ret;
7187
7188   src->methods =
7189       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
7190
7191   if (src->sdp == NULL) {
7192     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
7193       goto no_sdp;
7194   }
7195
7196   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
7197     goto open_failed;
7198
7199 done:
7200   if (async)
7201     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
7202
7203   return ret;
7204
7205   /* ERRORS */
7206 no_sdp:
7207   {
7208     GST_WARNING_OBJECT (src, "can't get sdp");
7209     src->open_error = TRUE;
7210     goto done;
7211   }
7212 open_failed:
7213   {
7214     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
7215     src->open_error = TRUE;
7216     goto done;
7217   }
7218 }
7219
7220 static GstRTSPResult
7221 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
7222 {
7223   GstRTSPMessage request = { 0 };
7224   GstRTSPMessage response = { 0 };
7225   GstRTSPResult res = GST_RTSP_OK;
7226   GList *walk;
7227   const gchar *control;
7228
7229   GST_DEBUG_OBJECT (src, "TEARDOWN...");
7230
7231   gst_rtspsrc_set_state (src, GST_STATE_READY);
7232
7233   if (src->state < GST_RTSP_STATE_READY) {
7234     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
7235     goto close;
7236   }
7237
7238   if (only_close)
7239     goto close;
7240
7241   /* construct a control url */
7242   control = get_aggregate_control (src);
7243
7244   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
7245     goto not_supported;
7246
7247   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7248     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7249     const gchar *setup_url;
7250     GstRTSPConnInfo *info;
7251
7252     /* try aggregate control first but do non-aggregate control otherwise */
7253     if (control)
7254       setup_url = control;
7255     else if ((setup_url = stream->conninfo.location) == NULL)
7256       continue;
7257
7258     if (src->conninfo.connection) {
7259       info = &src->conninfo;
7260     } else if (stream->conninfo.connection) {
7261       info = &stream->conninfo;
7262     } else {
7263       continue;
7264     }
7265     if (!info->connected)
7266       goto next;
7267
7268     /* do TEARDOWN */
7269     res =
7270         gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
7271     if (res < 0)
7272       goto create_request_failed;
7273
7274     if (async)
7275       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
7276
7277     if ((res =
7278             gst_rtspsrc_send (src, info, &request, &response, NULL, NULL)) < 0)
7279       goto send_error;
7280
7281     /* FIXME, parse result? */
7282     gst_rtsp_message_unset (&request);
7283     gst_rtsp_message_unset (&response);
7284
7285   next:
7286     /* early exit when we did aggregate control */
7287     if (control)
7288       break;
7289   }
7290
7291 close:
7292   /* close connections */
7293   GST_DEBUG_OBJECT (src, "closing connection...");
7294   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7295   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7296     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7297     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
7298   }
7299
7300   /* cleanup */
7301   gst_rtspsrc_cleanup (src);
7302
7303   src->state = GST_RTSP_STATE_INVALID;
7304
7305   if (async)
7306     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
7307
7308   return res;
7309
7310   /* ERRORS */
7311 create_request_failed:
7312   {
7313     gchar *str = gst_rtsp_strresult (res);
7314
7315     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7316         ("Could not create request. (%s)", str));
7317     g_free (str);
7318     goto close;
7319   }
7320 send_error:
7321   {
7322     gchar *str = gst_rtsp_strresult (res);
7323
7324     gst_rtsp_message_unset (&request);
7325     if (res != GST_RTSP_EINTR) {
7326       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7327           ("Could not send message. (%s)", str));
7328     } else {
7329       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7330     }
7331     g_free (str);
7332     goto close;
7333   }
7334 not_supported:
7335   {
7336     GST_DEBUG_OBJECT (src,
7337         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7338     goto close;
7339   }
7340 }
7341
7342 /* RTP-Info is of the format:
7343  *
7344  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7345  *
7346  * rtptime corresponds to the timestamp for the NPT time given in the header
7347  * seqbase corresponds to the next sequence number we received. This number
7348  * indicates the first seqnum after the seek and should be used to discard
7349  * packets that are from before the seek.
7350  */
7351 static gboolean
7352 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7353 {
7354   gchar **infos;
7355   gint i, j;
7356
7357   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7358
7359   infos = g_strsplit (rtpinfo, ",", 0);
7360   for (i = 0; infos[i]; i++) {
7361     gchar **fields;
7362     GstRTSPStream *stream;
7363     gint32 seqbase;
7364     gint64 timebase;
7365
7366     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7367
7368     /* init values, types of seqbase and timebase are bigger than needed so we
7369      * can store -1 as uninitialized values */
7370     stream = NULL;
7371     seqbase = -1;
7372     timebase = -1;
7373
7374     /* parse url, find stream for url.
7375      * parse seq and rtptime. The seq number should be configured in the rtp
7376      * depayloader or session manager to detect gaps. Same for the rtptime, it
7377      * should be used to create an initial time newsegment. */
7378     fields = g_strsplit (infos[i], ";", 0);
7379     for (j = 0; fields[j]; j++) {
7380       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7381       /* remove leading whitespace */
7382       fields[j] = g_strchug (fields[j]);
7383       if (g_str_has_prefix (fields[j], "url=")) {
7384         /* get the url and the stream */
7385         stream =
7386             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7387       } else if (g_str_has_prefix (fields[j], "seq=")) {
7388         seqbase = atoi (fields[j] + 4);
7389       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7390         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7391       }
7392     }
7393     g_strfreev (fields);
7394     /* now we need to store the values for the caps of the stream */
7395     if (stream != NULL) {
7396       GST_DEBUG_OBJECT (src,
7397           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7398           stream, seqbase, timebase);
7399
7400       /* we have a stream, configure detected params */
7401       stream->seqbase = seqbase;
7402       stream->timebase = timebase;
7403     }
7404   }
7405   g_strfreev (infos);
7406
7407   return TRUE;
7408 }
7409
7410 static void
7411 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7412 {
7413   guint64 interval;
7414   GList *walk;
7415
7416   interval = strtoul (rtcp, NULL, 10);
7417   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7418
7419   if (!interval)
7420     return;
7421
7422   interval *= GST_MSECOND;
7423
7424   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7425     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7426
7427     /* already (optionally) retrieved this when configuring manager */
7428     if (stream->session) {
7429       GObject *rtpsession = stream->session;
7430
7431       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7432           rtpsession);
7433       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7434     }
7435   }
7436
7437   /* now it happens that (Xenon) server sending this may also provide bogus
7438    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7439    * and just use RTP-Info to sync */
7440   if (src->manager) {
7441     GObjectClass *klass;
7442
7443     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7444     if (g_object_class_find_property (klass, "rtcp-sync")) {
7445       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7446       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7447     }
7448   }
7449 }
7450
7451 static gdouble
7452 gst_rtspsrc_get_float (const gchar * dstr)
7453 {
7454   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7455
7456   /* canonicalise floating point string so we can handle float strings
7457    * in the form "24.930" or "24,930" irrespective of the current locale */
7458   g_strlcpy (s, dstr, sizeof (s));
7459   g_strdelimit (s, ",", '.');
7460   return g_ascii_strtod (s, NULL);
7461 }
7462
7463 static gchar *
7464 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7465 {
7466   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7467
7468   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7469     g_strlcpy (val_str, "now", sizeof (val_str));
7470   } else {
7471     if (segment->position == 0) {
7472       g_strlcpy (val_str, "0", sizeof (val_str));
7473     } else {
7474       g_ascii_dtostr (val_str, sizeof (val_str),
7475           ((gdouble) segment->position) / GST_SECOND);
7476     }
7477   }
7478   return g_strdup_printf ("npt=%s-", val_str);
7479 }
7480
7481 static void
7482 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7483 {
7484   guint i, len;
7485
7486   stream->timebase = -1;
7487   stream->seqbase = -1;
7488
7489   len = stream->ptmap->len;
7490   for (i = 0; i < len; i++) {
7491     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7492     GstStructure *s;
7493
7494     if (item->caps == NULL)
7495       continue;
7496
7497     item->caps = gst_caps_make_writable (item->caps);
7498     s = gst_caps_get_structure (item->caps, 0);
7499     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7500     if (item->pt == stream->default_pt && stream->udpsrc[0])
7501       g_object_set (stream->udpsrc[0], "caps", item->caps, NULL);
7502   }
7503   stream->need_caps = TRUE;
7504 }
7505
7506 static GstRTSPResult
7507 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7508 {
7509   GstRTSPResult res = GST_RTSP_OK;
7510
7511   if (src->state < GST_RTSP_STATE_READY) {
7512     res = GST_RTSP_ERROR;
7513     if (src->open_error) {
7514       GST_DEBUG_OBJECT (src, "the stream was in error");
7515       goto done;
7516     }
7517     if (async)
7518       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7519
7520     if ((res = gst_rtspsrc_open (src, async)) < 0) {
7521       GST_DEBUG_OBJECT (src, "failed to open stream");
7522       goto done;
7523     }
7524   }
7525
7526 done:
7527   return res;
7528 }
7529
7530 static GstRTSPResult
7531 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async,
7532     const gchar * seek_style)
7533 {
7534   GstRTSPMessage request = { 0 };
7535   GstRTSPMessage response = { 0 };
7536   GstRTSPResult res = GST_RTSP_OK;
7537   GList *walk;
7538   gchar *hval;
7539   gint hval_idx;
7540   const gchar *control;
7541
7542   GST_DEBUG_OBJECT (src, "PLAY...");
7543
7544 restart:
7545   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7546     goto open_failed;
7547
7548   if (!(src->methods & GST_RTSP_PLAY))
7549     goto not_supported;
7550
7551   if (src->state == GST_RTSP_STATE_PLAYING)
7552     goto was_playing;
7553
7554   if (!src->conninfo.connection || !src->conninfo.connected)
7555     goto done;
7556
7557   /* send some dummy packets before we activate the receive in the
7558    * udp sources */
7559   gst_rtspsrc_send_dummy_packets (src);
7560
7561   /* require new SR packets */
7562   if (src->manager)
7563     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7564
7565   /* construct a control url */
7566   control = get_aggregate_control (src);
7567
7568   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7569     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7570     const gchar *setup_url;
7571     GstRTSPConnInfo *conninfo;
7572
7573     /* try aggregate control first but do non-aggregate control otherwise */
7574     if (control)
7575       setup_url = control;
7576     else if ((setup_url = stream->conninfo.location) == NULL)
7577       continue;
7578
7579     if (src->conninfo.connection) {
7580       conninfo = &src->conninfo;
7581     } else if (stream->conninfo.connection) {
7582       conninfo = &stream->conninfo;
7583     } else {
7584       continue;
7585     }
7586
7587     /* do play */
7588     res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
7589     if (res < 0)
7590       goto create_request_failed;
7591
7592     if (src->need_range && src->seekable >= 0.0) {
7593       hval = gen_range_header (src, segment);
7594
7595       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7596
7597       /* store the newsegment event so it can be sent from the streaming thread. */
7598       src->need_segment = TRUE;
7599     }
7600
7601     if (segment->rate != 1.0) {
7602       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7603
7604       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7605       if (src->skip)
7606         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7607       else
7608         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7609     }
7610
7611     if (seek_style)
7612       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SEEK_STYLE,
7613           seek_style);
7614
7615     if (async)
7616       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7617
7618     if ((res =
7619             gst_rtspsrc_send (src, conninfo, &request, &response, NULL, NULL))
7620         < 0)
7621       goto send_error;
7622
7623     if (src->need_redirect) {
7624       GST_DEBUG_OBJECT (src,
7625           "redirect: tearing down and restarting with new url");
7626       /* teardown and restart with new url */
7627       gst_rtspsrc_close (src, TRUE, FALSE);
7628       /* reset protocols to force re-negotiation with redirected url */
7629       src->cur_protocols = src->protocols;
7630       gst_rtsp_message_unset (&request);
7631       gst_rtsp_message_unset (&response);
7632       goto restart;
7633     }
7634
7635     /* seek may have silently failed as it is not supported */
7636     if (!(src->methods & GST_RTSP_PLAY)) {
7637       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7638
7639       if (src->version >= GST_RTSP_VERSION_2_0 && src->seekable >= 0.0) {
7640         GST_WARNING_OBJECT (src, "Server declared stream as seekable but"
7641             " playing with range failed... Ignoring information.");
7642       }
7643       /* obviously it is supported as we made it here */
7644       src->methods |= GST_RTSP_PLAY;
7645       src->seekable = -1.0;
7646       /* but there is nothing to parse in the response,
7647        * so convey we have no idea and not to expect anything particular */
7648       clear_rtp_base (src, stream);
7649       if (control) {
7650         GList *run;
7651
7652         /* need to do for all streams */
7653         for (run = src->streams; run; run = g_list_next (run))
7654           clear_rtp_base (src, (GstRTSPStream *) run->data);
7655       }
7656       /* NOTE the above also disables npt based eos detection */
7657       /* and below forces position to 0,
7658        * which is visible feedback we lost the plot */
7659       segment->start = segment->position = src->last_pos;
7660     }
7661
7662     gst_rtsp_message_unset (&request);
7663
7664     /* parse RTP npt field. This is the current position in the stream (Normal
7665      * Play Time) and should be put in the NEWSEGMENT position field. */
7666     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7667             0) == GST_RTSP_OK)
7668       gst_rtspsrc_parse_range (src, hval, segment);
7669
7670     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7671     segment->rate = 1.0;
7672
7673     /* parse Speed header. This is the intended playback rate of the stream
7674      * and should be put in the NEWSEGMENT rate field. */
7675     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7676             0) == GST_RTSP_OK) {
7677       segment->rate = gst_rtspsrc_get_float (hval);
7678     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7679             &hval, 0) == GST_RTSP_OK) {
7680       segment->rate = gst_rtspsrc_get_float (hval);
7681     }
7682
7683     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7684      * for the RTP packets. If this is not present, we assume all starts from 0...
7685      * This is info for the RTP session manager that we pass to it in caps. */
7686     hval_idx = 0;
7687     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7688             &hval, hval_idx++) == GST_RTSP_OK)
7689       gst_rtspsrc_parse_rtpinfo (src, hval);
7690
7691     /* some servers indicate RTCP parameters in PLAY response,
7692      * rather than properly in SDP */
7693     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7694             &hval, 0) == GST_RTSP_OK)
7695       gst_rtspsrc_handle_rtcp_interval (src, hval);
7696
7697     gst_rtsp_message_unset (&response);
7698
7699     /* early exit when we did aggregate control */
7700     if (control)
7701       break;
7702   }
7703   /* configure the caps of the streams after we parsed all headers. Only reset
7704    * the manager object when we set a new Range header (we did a seek) */
7705   gst_rtspsrc_configure_caps (src, segment, src->need_range);
7706
7707   /* set to PLAYING after we have configured the caps, otherwise we
7708    * might end up calling request_key (with SRTP) while caps are still
7709    * being configured. */
7710   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7711
7712   /* set again when needed */
7713   src->need_range = FALSE;
7714
7715   src->running = TRUE;
7716   src->base_time = -1;
7717   src->state = GST_RTSP_STATE_PLAYING;
7718
7719   /* mark discont */
7720   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7721   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7722     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7723     stream->discont = TRUE;
7724   }
7725
7726 done:
7727   if (async)
7728     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7729
7730   return res;
7731
7732   /* ERRORS */
7733 open_failed:
7734   {
7735     GST_DEBUG_OBJECT (src, "failed to open stream");
7736     goto done;
7737   }
7738 not_supported:
7739   {
7740     GST_DEBUG_OBJECT (src, "PLAY is not supported");
7741     goto done;
7742   }
7743 was_playing:
7744   {
7745     GST_DEBUG_OBJECT (src, "we were already PLAYING");
7746     goto done;
7747   }
7748 create_request_failed:
7749   {
7750     gchar *str = gst_rtsp_strresult (res);
7751
7752     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7753         ("Could not create request. (%s)", str));
7754     g_free (str);
7755     goto done;
7756   }
7757 send_error:
7758   {
7759     gchar *str = gst_rtsp_strresult (res);
7760
7761     gst_rtsp_message_unset (&request);
7762     if (res != GST_RTSP_EINTR) {
7763       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7764           ("Could not send message. (%s)", str));
7765     } else {
7766       GST_WARNING_OBJECT (src, "PLAY interrupted");
7767     }
7768     g_free (str);
7769     goto done;
7770   }
7771 }
7772
7773 static GstRTSPResult
7774 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7775 {
7776   GstRTSPResult res = GST_RTSP_OK;
7777   GstRTSPMessage request = { 0 };
7778   GstRTSPMessage response = { 0 };
7779   GList *walk;
7780   const gchar *control;
7781
7782   GST_DEBUG_OBJECT (src, "PAUSE...");
7783
7784   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7785     goto open_failed;
7786
7787   if (!(src->methods & GST_RTSP_PAUSE))
7788     goto not_supported;
7789
7790   if (src->state == GST_RTSP_STATE_READY)
7791     goto was_paused;
7792
7793   if (!src->conninfo.connection || !src->conninfo.connected)
7794     goto no_connection;
7795
7796   /* construct a control url */
7797   control = get_aggregate_control (src);
7798
7799   /* loop over the streams. We might exit the loop early when we could do an
7800    * aggregate control */
7801   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7802     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7803     GstRTSPConnInfo *conninfo;
7804     const gchar *setup_url;
7805
7806     /* try aggregate control first but do non-aggregate control otherwise */
7807     if (control)
7808       setup_url = control;
7809     else if ((setup_url = stream->conninfo.location) == NULL)
7810       continue;
7811
7812     if (src->conninfo.connection) {
7813       conninfo = &src->conninfo;
7814     } else if (stream->conninfo.connection) {
7815       conninfo = &stream->conninfo;
7816     } else {
7817       continue;
7818     }
7819
7820     if (async)
7821       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7822           ("Sending PAUSE request"));
7823
7824     if ((res =
7825             gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
7826                 setup_url)) < 0)
7827       goto create_request_failed;
7828
7829     if ((res =
7830             gst_rtspsrc_send (src, conninfo, &request, &response, NULL,
7831                 NULL)) < 0)
7832       goto send_error;
7833
7834     gst_rtsp_message_unset (&request);
7835     gst_rtsp_message_unset (&response);
7836
7837     /* exit early when we did agregate control */
7838     if (control)
7839       break;
7840   }
7841
7842   /* change element states now */
7843   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7844
7845 no_connection:
7846   src->state = GST_RTSP_STATE_READY;
7847
7848 done:
7849   if (async)
7850     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7851
7852   return res;
7853
7854   /* ERRORS */
7855 open_failed:
7856   {
7857     GST_DEBUG_OBJECT (src, "failed to open stream");
7858     goto done;
7859   }
7860 not_supported:
7861   {
7862     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7863     goto done;
7864   }
7865 was_paused:
7866   {
7867     GST_DEBUG_OBJECT (src, "we were already PAUSED");
7868     goto done;
7869   }
7870 create_request_failed:
7871   {
7872     gchar *str = gst_rtsp_strresult (res);
7873
7874     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7875         ("Could not create request. (%s)", str));
7876     g_free (str);
7877     goto done;
7878   }
7879 send_error:
7880   {
7881     gchar *str = gst_rtsp_strresult (res);
7882
7883     gst_rtsp_message_unset (&request);
7884     if (res != GST_RTSP_EINTR) {
7885       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7886           ("Could not send message. (%s)", str));
7887     } else {
7888       GST_WARNING_OBJECT (src, "PAUSE interrupted");
7889     }
7890     g_free (str);
7891     goto done;
7892   }
7893 }
7894
7895 static void
7896 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
7897 {
7898   GstRTSPSrc *rtspsrc;
7899
7900   rtspsrc = GST_RTSPSRC (bin);
7901
7902   switch (GST_MESSAGE_TYPE (message)) {
7903     case GST_MESSAGE_EOS:
7904       gst_message_unref (message);
7905       break;
7906     case GST_MESSAGE_ELEMENT:
7907     {
7908       const GstStructure *s = gst_message_get_structure (message);
7909
7910       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
7911         gboolean ignore_timeout;
7912
7913         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
7914
7915         GST_OBJECT_LOCK (rtspsrc);
7916         ignore_timeout = rtspsrc->ignore_timeout;
7917         rtspsrc->ignore_timeout = TRUE;
7918         GST_OBJECT_UNLOCK (rtspsrc);
7919
7920         /* we only act on the first udp timeout message, others are irrelevant
7921          * and can be ignored. */
7922         if (!ignore_timeout)
7923           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
7924         /* eat and free */
7925         gst_message_unref (message);
7926         return;
7927       }
7928       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7929       break;
7930     }
7931     case GST_MESSAGE_ERROR:
7932     {
7933       GstObject *udpsrc;
7934       GstRTSPStream *stream;
7935       GstFlowReturn ret;
7936
7937       udpsrc = GST_MESSAGE_SRC (message);
7938
7939       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
7940           GST_ELEMENT_NAME (udpsrc));
7941
7942       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
7943       if (!stream)
7944         goto forward;
7945
7946       /* we ignore the RTCP udpsrc */
7947       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
7948         goto done;
7949
7950       /* if we get error messages from the udp sources, that's not a problem as
7951        * long as not all of them error out. We also don't really know what the
7952        * problem is, the message does not give enough detail... */
7953       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
7954       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7955       if (ret != GST_FLOW_OK)
7956         goto forward;
7957
7958     done:
7959       gst_message_unref (message);
7960       break;
7961
7962     forward:
7963       /* fatal but not our message, forward */
7964       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7965       break;
7966     }
7967     default:
7968     {
7969       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7970       break;
7971     }
7972   }
7973 }
7974
7975 /* the thread where everything happens */
7976 static void
7977 gst_rtspsrc_thread (GstRTSPSrc * src)
7978 {
7979   gint cmd;
7980
7981   GST_OBJECT_LOCK (src);
7982   cmd = src->pending_cmd;
7983   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7984       || cmd == CMD_LOOP || cmd == CMD_OPEN)
7985     src->pending_cmd = CMD_LOOP;
7986   else
7987     src->pending_cmd = CMD_WAIT;
7988   GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
7989
7990   /* we got the message command, so ensure communication is possible again */
7991   gst_rtspsrc_connection_flush (src, FALSE);
7992
7993   src->busy_cmd = cmd;
7994   GST_OBJECT_UNLOCK (src);
7995
7996   switch (cmd) {
7997     case CMD_OPEN:
7998       gst_rtspsrc_open (src, TRUE);
7999       break;
8000     case CMD_PLAY:
8001       gst_rtspsrc_play (src, &src->segment, TRUE, NULL);
8002       break;
8003     case CMD_PAUSE:
8004       gst_rtspsrc_pause (src, TRUE);
8005       break;
8006     case CMD_CLOSE:
8007       gst_rtspsrc_close (src, TRUE, FALSE);
8008       break;
8009     case CMD_LOOP:
8010       gst_rtspsrc_loop (src);
8011       break;
8012     case CMD_RECONNECT:
8013       gst_rtspsrc_reconnect (src, FALSE);
8014       break;
8015     default:
8016       break;
8017   }
8018
8019   GST_OBJECT_LOCK (src);
8020   /* and go back to sleep */
8021   if (src->pending_cmd == CMD_WAIT) {
8022     if (src->task)
8023       gst_task_pause (src->task);
8024   }
8025   /* reset waiting */
8026   src->busy_cmd = CMD_WAIT;
8027   GST_OBJECT_UNLOCK (src);
8028 }
8029
8030 static gboolean
8031 gst_rtspsrc_start (GstRTSPSrc * src)
8032 {
8033   GST_DEBUG_OBJECT (src, "starting");
8034
8035   GST_OBJECT_LOCK (src);
8036
8037   src->pending_cmd = CMD_WAIT;
8038
8039   if (src->task == NULL) {
8040     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
8041     if (src->task == NULL)
8042       goto task_error;
8043
8044     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
8045   }
8046   GST_OBJECT_UNLOCK (src);
8047
8048   return TRUE;
8049
8050   /* ERRORS */
8051 task_error:
8052   {
8053     GST_OBJECT_UNLOCK (src);
8054     GST_ERROR_OBJECT (src, "failed to create task");
8055     return FALSE;
8056   }
8057 }
8058
8059 static gboolean
8060 gst_rtspsrc_stop (GstRTSPSrc * src)
8061 {
8062   GstTask *task;
8063
8064   GST_DEBUG_OBJECT (src, "stopping");
8065
8066   /* also cancels pending task */
8067   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
8068
8069   GST_OBJECT_LOCK (src);
8070   if ((task = src->task)) {
8071     src->task = NULL;
8072     GST_OBJECT_UNLOCK (src);
8073
8074     gst_task_stop (task);
8075
8076     /* make sure it is not running */
8077     GST_RTSP_STREAM_LOCK (src);
8078     GST_RTSP_STREAM_UNLOCK (src);
8079
8080     /* now wait for the task to finish */
8081     gst_task_join (task);
8082
8083     /* and free the task */
8084     gst_object_unref (GST_OBJECT (task));
8085
8086     GST_OBJECT_LOCK (src);
8087   }
8088   GST_OBJECT_UNLOCK (src);
8089
8090   /* ensure synchronously all is closed and clean */
8091   gst_rtspsrc_close (src, FALSE, TRUE);
8092
8093   return TRUE;
8094 }
8095
8096 static GstStateChangeReturn
8097 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
8098 {
8099   GstRTSPSrc *rtspsrc;
8100   GstStateChangeReturn ret;
8101
8102   rtspsrc = GST_RTSPSRC (element);
8103
8104   switch (transition) {
8105     case GST_STATE_CHANGE_NULL_TO_READY:
8106       if (!gst_rtspsrc_start (rtspsrc))
8107         goto start_failed;
8108       break;
8109     case GST_STATE_CHANGE_READY_TO_PAUSED:
8110       /* init some state */
8111       rtspsrc->cur_protocols = rtspsrc->protocols;
8112       /* first attempt, don't ignore timeouts */
8113       rtspsrc->ignore_timeout = FALSE;
8114       rtspsrc->open_error = FALSE;
8115       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
8116       break;
8117     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8118       set_manager_buffer_mode (rtspsrc);
8119       /* fall-through */
8120     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8121       /* unblock the tcp tasks and make the loop waiting */
8122       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
8123         /* make sure it is waiting before we send PAUSE or PLAY below */
8124         GST_RTSP_STREAM_LOCK (rtspsrc);
8125         GST_RTSP_STREAM_UNLOCK (rtspsrc);
8126       }
8127       break;
8128     case GST_STATE_CHANGE_PAUSED_TO_READY:
8129       break;
8130     default:
8131       break;
8132   }
8133
8134   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
8135   if (ret == GST_STATE_CHANGE_FAILURE)
8136     goto done;
8137
8138   switch (transition) {
8139     case GST_STATE_CHANGE_NULL_TO_READY:
8140       ret = GST_STATE_CHANGE_SUCCESS;
8141       break;
8142     case GST_STATE_CHANGE_READY_TO_PAUSED:
8143       ret = GST_STATE_CHANGE_NO_PREROLL;
8144       break;
8145     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8146       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
8147       ret = GST_STATE_CHANGE_SUCCESS;
8148       break;
8149     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8150       /* send pause request and keep the idle task around */
8151       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
8152       ret = GST_STATE_CHANGE_NO_PREROLL;
8153       break;
8154     case GST_STATE_CHANGE_PAUSED_TO_READY:
8155       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_ALL);
8156       ret = GST_STATE_CHANGE_SUCCESS;
8157       break;
8158     case GST_STATE_CHANGE_READY_TO_NULL:
8159       gst_rtspsrc_stop (rtspsrc);
8160       ret = GST_STATE_CHANGE_SUCCESS;
8161       break;
8162     default:
8163       /* Otherwise it's success, we don't want to return spurious
8164        * NO_PREROLL or ASYNC from internal elements as we care for
8165        * state changes ourselves here
8166        *
8167        * This is to catch PAUSED->PAUSED and PLAYING->PLAYING transitions.
8168        */
8169       if (GST_STATE_TRANSITION_NEXT (transition) == GST_STATE_PAUSED)
8170         ret = GST_STATE_CHANGE_NO_PREROLL;
8171       else
8172         ret = GST_STATE_CHANGE_SUCCESS;
8173       break;
8174   }
8175
8176 done:
8177   return ret;
8178
8179 start_failed:
8180   {
8181     GST_DEBUG_OBJECT (rtspsrc, "start failed");
8182     return GST_STATE_CHANGE_FAILURE;
8183   }
8184 }
8185
8186 static gboolean
8187 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
8188 {
8189   gboolean res;
8190   GstRTSPSrc *rtspsrc;
8191
8192   rtspsrc = GST_RTSPSRC (element);
8193
8194   if (GST_EVENT_IS_DOWNSTREAM (event)) {
8195     res = gst_rtspsrc_push_event (rtspsrc, event);
8196   } else {
8197     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
8198   }
8199
8200   return res;
8201 }
8202
8203
8204 /*** GSTURIHANDLER INTERFACE *************************************************/
8205
8206 static GstURIType
8207 gst_rtspsrc_uri_get_type (GType type)
8208 {
8209   return GST_URI_SRC;
8210 }
8211
8212 static const gchar *const *
8213 gst_rtspsrc_uri_get_protocols (GType type)
8214 {
8215   static const gchar *protocols[] =
8216       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
8217     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
8218   };
8219
8220   return protocols;
8221 }
8222
8223 static gchar *
8224 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
8225 {
8226   GstRTSPSrc *src = GST_RTSPSRC (handler);
8227
8228   /* FIXME: make thread-safe */
8229   return g_strdup (src->conninfo.location);
8230 }
8231
8232 static gboolean
8233 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
8234     GError ** error)
8235 {
8236   GstRTSPSrc *src;
8237   GstRTSPResult res;
8238   GstSDPResult sres;
8239   GstRTSPUrl *newurl = NULL;
8240   GstSDPMessage *sdp = NULL;
8241
8242   src = GST_RTSPSRC (handler);
8243
8244   /* same URI, we're fine */
8245   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
8246     goto was_ok;
8247
8248   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
8249     sres = gst_sdp_message_new (&sdp);
8250     if (sres < 0)
8251       goto sdp_failed;
8252
8253     GST_DEBUG_OBJECT (src, "parsing SDP message");
8254     sres = gst_sdp_message_parse_uri (uri, sdp);
8255     if (sres < 0)
8256       goto invalid_sdp;
8257   } else {
8258     /* try to parse */
8259     GST_DEBUG_OBJECT (src, "parsing URI");
8260     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
8261       goto parse_error;
8262   }
8263
8264   /* if worked, free previous and store new url object along with the original
8265    * location. */
8266   GST_DEBUG_OBJECT (src, "configuring URI");
8267   g_free (src->conninfo.location);
8268   src->conninfo.location = g_strdup (uri);
8269   gst_rtsp_url_free (src->conninfo.url);
8270   src->conninfo.url = newurl;
8271   g_free (src->conninfo.url_str);
8272   if (newurl)
8273     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
8274   else
8275     src->conninfo.url_str = NULL;
8276
8277   if (src->sdp)
8278     gst_sdp_message_free (src->sdp);
8279   src->sdp = sdp;
8280   src->from_sdp = sdp != NULL;
8281
8282   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
8283   GST_DEBUG_OBJECT (src, "request uri is: %s",
8284       GST_STR_NULL (src->conninfo.url_str));
8285
8286   return TRUE;
8287
8288   /* Special cases */
8289 was_ok:
8290   {
8291     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
8292     return TRUE;
8293   }
8294 sdp_failed:
8295   {
8296     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
8297     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8298         "Could not create SDP");
8299     return FALSE;
8300   }
8301 invalid_sdp:
8302   {
8303     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
8304         GST_STR_NULL (uri));
8305     gst_sdp_message_free (sdp);
8306     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8307         "Invalid SDP");
8308     return FALSE;
8309   }
8310 parse_error:
8311   {
8312     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
8313         GST_STR_NULL (uri), res);
8314     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8315         "Invalid RTSP URI");
8316     return FALSE;
8317   }
8318 }
8319
8320 static void
8321 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
8322 {
8323   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
8324
8325   iface->get_type = gst_rtspsrc_uri_get_type;
8326   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
8327   iface->get_uri = gst_rtspsrc_uri_get_uri;
8328   iface->set_uri = gst_rtspsrc_uri_set_uri;
8329 }