rtspsrc: Avoid potentially dereferencing NULL pointer
[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   G_GUINT64_CONSTANT(0)
235 #define DEFAULT_MAX_TS_OFFSET   G_GINT64_CONSTANT(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             versions ? gst_rtsp_version_as_text (versions[version_retry]) :
5750             "unknown");
5751         if (versions && versions[version_retry] != GST_RTSP_VERSION_INVALID) {
5752           GST_INFO_OBJECT (src, "Unsupported version %s => trying %s",
5753               gst_rtsp_version_as_text (request->type_data.request.version),
5754               gst_rtsp_version_as_text (versions[version_retry]));
5755           request->type_data.request.version = versions[version_retry];
5756           retry = TRUE;
5757           version_retry++;
5758           break;
5759         }
5760         /* falltrough */
5761       default:
5762         break;
5763     }
5764   } while (retry == TRUE);
5765
5766   /* If the user requested the code, let them handle errors, otherwise
5767    * post an error below */
5768   if (code != NULL)
5769     *code = int_code;
5770   else if (int_code != GST_RTSP_STS_OK)
5771     goto error_response;
5772
5773   return res;
5774
5775   /* ERRORS */
5776 error:
5777   {
5778     GST_DEBUG_OBJECT (src, "got error %d", res);
5779     return res;
5780   }
5781 error_response:
5782   {
5783     res = GST_RTSP_ERROR;
5784
5785     switch (response->type_data.response.code) {
5786       case GST_RTSP_STS_NOT_FOUND:
5787         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_FOUND,
5788             "Not found");
5789         break;
5790       case GST_RTSP_STS_UNAUTHORIZED:
5791         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_AUTHORIZED,
5792             "Unauthorized");
5793         break;
5794       case GST_RTSP_STS_MOVED_PERMANENTLY:
5795       case GST_RTSP_STS_MOVE_TEMPORARILY:
5796       {
5797         gchar *new_location;
5798         GstRTSPLowerTrans transports;
5799
5800         GST_DEBUG_OBJECT (src, "got redirection");
5801         /* if we don't have a Location Header, we must error */
5802         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5803                 &new_location, 0) < 0)
5804           break;
5805
5806         /* When we receive a redirect result, we go back to the INIT state after
5807          * parsing the new URI. The caller should do the needed steps to issue
5808          * a new setup when it detects this state change. */
5809         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5810
5811         /* save current transports */
5812         if (src->conninfo.url)
5813           transports = src->conninfo.url->transports;
5814         else
5815           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5816
5817         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5818
5819         /* set old transports */
5820         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5821           src->conninfo.url->transports = transports;
5822
5823         src->need_redirect = TRUE;
5824         res = GST_RTSP_OK;
5825         break;
5826       }
5827       case GST_RTSP_STS_NOT_ACCEPTABLE:
5828       case GST_RTSP_STS_NOT_IMPLEMENTED:
5829       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5830         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5831             gst_rtsp_method_as_text (method));
5832         src->methods &= ~method;
5833         res = GST_RTSP_OK;
5834         break;
5835       default:
5836         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, READ,
5837             "Unhandled error");
5838         break;
5839     }
5840     /* if we return ERROR we should unset the response ourselves */
5841     if (res == GST_RTSP_ERROR)
5842       gst_rtsp_message_unset (response);
5843
5844     return res;
5845   }
5846 }
5847
5848 static GstRTSPResult
5849 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5850     GstRTSPMessage * response, GstRTSPSrc * src)
5851 {
5852   return gst_rtspsrc_send (src, &src->conninfo, request, response, NULL, NULL);
5853 }
5854
5855
5856 /* parse the response and collect all the supported methods. We need this
5857  * information so that we don't try to send an unsupported request to the
5858  * server.
5859  */
5860 static gboolean
5861 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5862 {
5863   GstRTSPHeaderField field;
5864   gchar *respoptions;
5865   gint indx = 0;
5866
5867   /* reset supported methods */
5868   src->methods = 0;
5869
5870   /* Try Allow Header first */
5871   field = GST_RTSP_HDR_ALLOW;
5872   while (TRUE) {
5873     respoptions = NULL;
5874     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5875     if (!respoptions)
5876       break;
5877
5878     src->methods |= gst_rtsp_options_from_text (respoptions);
5879
5880     indx++;
5881   }
5882
5883   indx = 0;
5884   field = GST_RTSP_HDR_PUBLIC;
5885   while (TRUE) {
5886     respoptions = NULL;
5887     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5888     if (!respoptions)
5889       break;
5890
5891     src->methods |= gst_rtsp_options_from_text (respoptions);
5892
5893     indx++;
5894   }
5895
5896   if (src->methods == 0) {
5897     /* neither Allow nor Public are required, assume the server supports
5898      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5899      * well. */
5900     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5901     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5902   }
5903   /* always assume PLAY, FIXME, extensions should be able to override
5904    * this */
5905   src->methods |= GST_RTSP_PLAY;
5906   /* also assume it will support Range */
5907   src->seekable = G_MAXDOUBLE;
5908
5909   /* we need describe and setup */
5910   if (!(src->methods & GST_RTSP_DESCRIBE))
5911     goto no_describe;
5912   if (!(src->methods & GST_RTSP_SETUP))
5913     goto no_setup;
5914
5915   return TRUE;
5916
5917   /* ERRORS */
5918 no_describe:
5919   {
5920     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5921         ("Server does not support DESCRIBE."));
5922     return FALSE;
5923   }
5924 no_setup:
5925   {
5926     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5927         ("Server does not support SETUP."));
5928     return FALSE;
5929   }
5930 }
5931
5932 /* masks to be kept in sync with the hardcoded protocol order of preference
5933  * in code below */
5934 static const guint protocol_masks[] = {
5935   GST_RTSP_LOWER_TRANS_UDP,
5936   GST_RTSP_LOWER_TRANS_UDP_MCAST,
5937   GST_RTSP_LOWER_TRANS_TCP,
5938   0
5939 };
5940
5941 static GstRTSPResult
5942 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5943     GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
5944 {
5945   GstRTSPResult res;
5946   GString *result;
5947   gboolean add_udp_str;
5948
5949   *transports = NULL;
5950
5951   res =
5952       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5953
5954   if (res < 0)
5955     goto failed;
5956
5957   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5958
5959   /* extension listed transports, use those */
5960   if (*transports != NULL)
5961     return GST_RTSP_OK;
5962
5963   /* it's the default */
5964   add_udp_str = FALSE;
5965
5966   /* the default RTSP transports */
5967   result = g_string_new ("RTP");
5968
5969   switch (profile) {
5970     case GST_RTSP_PROFILE_AVP:
5971       g_string_append (result, "/AVP");
5972       break;
5973     case GST_RTSP_PROFILE_SAVP:
5974       g_string_append (result, "/SAVP");
5975       break;
5976     case GST_RTSP_PROFILE_AVPF:
5977       g_string_append (result, "/AVPF");
5978       break;
5979     case GST_RTSP_PROFILE_SAVPF:
5980       g_string_append (result, "/SAVPF");
5981       break;
5982     default:
5983       break;
5984   }
5985
5986   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5987     GST_DEBUG_OBJECT (src, "adding UDP unicast");
5988     if (add_udp_str)
5989       g_string_append (result, "/UDP");
5990     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5991   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5992     GST_DEBUG_OBJECT (src, "adding UDP multicast");
5993     /* we don't have to allocate any UDP ports yet, if the selected transport
5994      * turns out to be multicast we can create them and join the multicast
5995      * group indicated in the transport reply */
5996     if (add_udp_str)
5997       g_string_append (result, "/UDP");
5998     g_string_append (result, ";multicast");
5999     if (src->next_port_num != 0) {
6000       if (src->client_port_range.max > 0 &&
6001           src->next_port_num >= src->client_port_range.max)
6002         goto no_ports;
6003
6004       g_string_append_printf (result, ";client_port=%d-%d",
6005           src->next_port_num, src->next_port_num + 1);
6006     }
6007   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
6008     GST_DEBUG_OBJECT (src, "adding TCP");
6009
6010     g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
6011   }
6012   *transports = g_string_free (result, FALSE);
6013
6014   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
6015
6016   return GST_RTSP_OK;
6017
6018   /* ERRORS */
6019 failed:
6020   {
6021     GST_ERROR ("extension gave error %d", res);
6022     return res;
6023   }
6024 no_ports:
6025   {
6026     GST_ERROR ("no more ports available");
6027     return GST_RTSP_ERROR;
6028   }
6029 }
6030
6031 static GstRTSPResult
6032 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
6033     gint orig_rtpport, gint orig_rtcpport)
6034 {
6035   GstRTSPSrc *src;
6036   gint nr_udp, nr_int;
6037   gchar *next, *p;
6038   gint rtpport = 0, rtcpport = 0;
6039   GString *str;
6040
6041   src = stream->parent;
6042
6043   /* find number of placeholders first */
6044   if (strstr (*transports, "%%i2"))
6045     nr_int = 2;
6046   else if (strstr (*transports, "%%i1"))
6047     nr_int = 1;
6048   else
6049     nr_int = 0;
6050
6051   if (strstr (*transports, "%%u2"))
6052     nr_udp = 2;
6053   else if (strstr (*transports, "%%u1"))
6054     nr_udp = 1;
6055   else
6056     nr_udp = 0;
6057
6058   if (nr_udp == 0 && nr_int == 0)
6059     goto done;
6060
6061   if (nr_udp > 0) {
6062     if (!orig_rtpport || !orig_rtcpport) {
6063       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
6064         goto failed;
6065     } else {
6066       rtpport = orig_rtpport;
6067       rtcpport = orig_rtcpport;
6068     }
6069   }
6070
6071   str = g_string_new ("");
6072   p = *transports;
6073   while ((next = strstr (p, "%%"))) {
6074     g_string_append_len (str, p, next - p);
6075     if (next[2] == 'u') {
6076       if (next[3] == '1')
6077         g_string_append_printf (str, "%d", rtpport);
6078       else if (next[3] == '2')
6079         g_string_append_printf (str, "%d", rtcpport);
6080     }
6081     if (next[2] == 'i') {
6082       if (next[3] == '1')
6083         g_string_append_printf (str, "%d", src->free_channel);
6084       else if (next[3] == '2')
6085         g_string_append_printf (str, "%d", src->free_channel + 1);
6086
6087     }
6088
6089     p = next + 4;
6090   }
6091   if (src->version >= GST_RTSP_VERSION_2_0)
6092     src->free_channel += 2;
6093
6094   /* append final part */
6095   g_string_append (str, p);
6096
6097   g_free (*transports);
6098   *transports = g_string_free (str, FALSE);
6099
6100 done:
6101   return GST_RTSP_OK;
6102
6103   /* ERRORS */
6104 failed:
6105   {
6106     GST_ERROR ("failed to allocate udp ports");
6107     return GST_RTSP_ERROR;
6108   }
6109 }
6110
6111 static GstCaps *
6112 signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
6113 {
6114   GstCaps *caps = NULL;
6115
6116   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
6117       stream->id, &caps);
6118
6119   if (caps != NULL)
6120     GST_DEBUG_OBJECT (src, "SRTP parameters received");
6121
6122   return caps;
6123 }
6124
6125 static GstCaps *
6126 default_srtcp_params (void)
6127 {
6128   guint i;
6129   GstCaps *caps;
6130   GstBuffer *buf;
6131   guint8 *key_data;
6132 #define KEY_SIZE 30
6133   guint data_size = GST_ROUND_UP_4 (KEY_SIZE);
6134
6135   /* create a random key */
6136   key_data = g_malloc (data_size);
6137   for (i = 0; i < data_size; i += 4)
6138     GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
6139
6140   buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
6141
6142   caps = gst_caps_new_simple ("application/x-srtcp",
6143       "srtp-key", GST_TYPE_BUFFER, buf,
6144       "srtp-cipher", G_TYPE_STRING, "aes-128-icm",
6145       "srtp-auth", G_TYPE_STRING, "hmac-sha1-80",
6146       "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
6147       "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
6148
6149   gst_buffer_unref (buf);
6150
6151   return caps;
6152 }
6153
6154 static gchar *
6155 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
6156 {
6157   gchar *base64, *result = NULL;
6158   GstMIKEYMessage *mikey_msg;
6159
6160   stream->srtcpparams = signal_get_srtcp_params (src, stream);
6161   if (stream->srtcpparams == NULL)
6162     stream->srtcpparams = default_srtcp_params ();
6163
6164   mikey_msg = gst_mikey_message_new_from_caps (stream->srtcpparams);
6165   if (mikey_msg) {
6166     /* add policy '0' for our SSRC */
6167     gst_mikey_message_add_cs_srtp (mikey_msg, 0, stream->send_ssrc, 0);
6168
6169     base64 = gst_mikey_message_base64_encode (mikey_msg);
6170     gst_mikey_message_unref (mikey_msg);
6171
6172     if (base64) {
6173       result = gst_sdp_make_keymgmt (stream->conninfo.location, base64);
6174       g_free (base64);
6175     }
6176   }
6177
6178   return result;
6179 }
6180
6181 static GstRTSPResult
6182 gst_rtsp_src_setup_stream_from_response (GstRTSPSrc * src,
6183     GstRTSPStream * stream, GstRTSPMessage * response,
6184     GstRTSPLowerTrans * protocols, gint retry, gint * rtpport, gint * rtcpport)
6185 {
6186   gchar *resptrans = NULL;
6187   GstRTSPTransport transport = { 0 };
6188
6189   gst_rtsp_message_get_header (response, GST_RTSP_HDR_TRANSPORT, &resptrans, 0);
6190   if (!resptrans) {
6191     gst_rtspsrc_stream_free_udp (stream);
6192     goto no_transport;
6193   }
6194
6195   /* parse transport, go to next stream on parse error */
6196   if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6197     GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6198     return GST_RTSP_ELAST;
6199   }
6200
6201   /* update allowed transports for other streams. once the transport of
6202    * one stream has been determined, we make sure that all other streams
6203    * are configured in the same way */
6204   switch (transport.lower_transport) {
6205     case GST_RTSP_LOWER_TRANS_TCP:
6206       GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6207       if (protocols)
6208         *protocols = GST_RTSP_LOWER_TRANS_TCP;
6209       src->interleaved = TRUE;
6210       if (src->version < GST_RTSP_VERSION_2_0) {
6211         /* update free channels */
6212         src->free_channel = MAX (transport.interleaved.min, src->free_channel);
6213         src->free_channel = MAX (transport.interleaved.max, src->free_channel);
6214         src->free_channel++;
6215       }
6216       break;
6217     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6218       /* only allow multicast for other streams */
6219       GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6220       if (protocols)
6221         *protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6222       /* if the server selected our ports, increment our counters so that
6223        * we select a new port later */
6224       if (src->next_port_num == transport.port.min &&
6225           src->next_port_num + 1 == transport.port.max) {
6226         src->next_port_num += 2;
6227       }
6228       break;
6229     case GST_RTSP_LOWER_TRANS_UDP:
6230       /* only allow unicast for other streams */
6231       GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6232       if (protocols)
6233         *protocols = GST_RTSP_LOWER_TRANS_UDP;
6234       break;
6235     default:
6236       GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6237           transport.lower_transport);
6238       break;
6239   }
6240
6241   if (!src->interleaved || !retry) {
6242     /* now configure the stream with the selected transport */
6243     if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6244       GST_DEBUG_OBJECT (src,
6245           "could not configure stream %p transport, skipping stream", stream);
6246       goto done;
6247     } else if (stream->udpsrc[0] && stream->udpsrc[1] && rtpport && rtcpport) {
6248       /* retain the first allocated UDP port pair */
6249       g_object_get (G_OBJECT (stream->udpsrc[0]), "port", rtpport, NULL);
6250       g_object_get (G_OBJECT (stream->udpsrc[1]), "port", rtcpport, NULL);
6251     }
6252   }
6253   /* we need to activate at least one stream when we detect activity */
6254   src->need_activate = TRUE;
6255
6256   /* stream is setup now */
6257   stream->setup = TRUE;
6258   stream->waiting_setup_response = FALSE;
6259
6260   if (src->version >= GST_RTSP_VERSION_2_0) {
6261     gchar *prop, *media_properties;
6262     gchar **props;
6263     gint i;
6264
6265     if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_MEDIA_PROPERTIES,
6266             &media_properties, 0) != GST_RTSP_OK) {
6267       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6268           ("Error: No MEDIA_PROPERTY header in a SETUP request in RTSP 2.0"
6269               " - this header is mandatory."));
6270
6271       gst_rtsp_message_unset (response);
6272       return GST_RTSP_ERROR;
6273     }
6274
6275     props = g_strsplit (media_properties, ",", -2);
6276     for (i = 0; props[i]; i++) {
6277       prop = props[i];
6278
6279       while (*prop == ' ')
6280         prop++;
6281
6282       if (strstr (prop, "Random-Access")) {
6283         gchar **random_seekable_val = g_strsplit (prop, "=", 2);
6284
6285         if (!random_seekable_val[1])
6286           src->seekable = G_MAXDOUBLE;
6287         else
6288           src->seekable = g_ascii_strtod (random_seekable_val[1], NULL);
6289
6290         g_strfreev (random_seekable_val);
6291       } else if (!g_strcmp0 (prop, "No-Seeking")) {
6292         src->seekable = -1.0;
6293       } else if (!g_strcmp0 (prop, "Beginning-Only")) {
6294         src->seekable = 0.0;
6295       }
6296     }
6297
6298     g_strfreev (props);
6299   }
6300
6301 done:
6302   /* clean up our transport struct */
6303   gst_rtsp_transport_init (&transport);
6304   /* clean up used RTSP messages */
6305   gst_rtsp_message_unset (response);
6306
6307   return GST_RTSP_OK;
6308
6309 no_transport:
6310   {
6311     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6312         ("Server did not select transport."));
6313
6314     gst_rtsp_message_unset (response);
6315     return GST_RTSP_ERROR;
6316   }
6317 }
6318
6319 static GstRTSPResult
6320 gst_rtspsrc_setup_streams_end (GstRTSPSrc * src, gboolean async)
6321 {
6322   GList *tmp;
6323   GstRTSPConnInfo *conninfo;
6324
6325   g_assert (src->version >= GST_RTSP_VERSION_2_0);
6326
6327   conninfo = &src->conninfo;
6328   for (tmp = src->streams; tmp; tmp = tmp->next) {
6329     GstRTSPStream *stream = (GstRTSPStream *) tmp->data;
6330     GstRTSPMessage response = { 0, };
6331
6332     if (!stream->waiting_setup_response)
6333       continue;
6334
6335     if (!src->conninfo.connection)
6336       conninfo = &((GstRTSPStream *) tmp->data)->conninfo;
6337
6338     gst_rtsp_src_receive_response (src, conninfo, &response, NULL);
6339
6340     gst_rtsp_src_setup_stream_from_response (src, stream,
6341         &response, NULL, 0, NULL, NULL);
6342   }
6343
6344   return GST_RTSP_OK;
6345 }
6346
6347 /* Perform the SETUP request for all the streams.
6348  *
6349  * We ask the server for a specific transport, which initially includes all the
6350  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6351  * two local UDP ports that we send to the server.
6352  *
6353  * Once the server replied with a transport, we configure the other streams
6354  * with the same transport.
6355  *
6356  * In case setup request are not pipelined, this function will also configure the
6357  * stream for the selected transport, * which basically means creating the pipeline.
6358  * Otherwise, the first stream is setup right away from the reply and a
6359  * CMD_FINALIZE_SETUP command is set for the stream pipelines to happen on the
6360  * remaining streams from the RTSP thread.
6361  */
6362 static GstRTSPResult
6363 gst_rtspsrc_setup_streams_start (GstRTSPSrc * src, gboolean async)
6364 {
6365   GList *walk;
6366   GstRTSPResult res = GST_RTSP_ERROR;
6367   GstRTSPMessage request = { 0 };
6368   GstRTSPMessage response = { 0 };
6369   GstRTSPStream *stream = NULL;
6370   GstRTSPLowerTrans protocols;
6371   GstRTSPStatusCode code;
6372   gboolean unsupported_real = FALSE;
6373   gint rtpport, rtcpport;
6374   GstRTSPUrl *url;
6375   gchar *hval;
6376   gchar *pipelined_request_id = NULL;
6377
6378   if (src->conninfo.connection) {
6379     url = gst_rtsp_connection_get_url (src->conninfo.connection);
6380     /* we initially allow all configured lower transports. based on the URL
6381      * transports and the replies from the server we narrow them down. */
6382     protocols = url->transports & src->cur_protocols;
6383   } else {
6384     url = NULL;
6385     protocols = src->cur_protocols;
6386   }
6387
6388   if (protocols == 0)
6389     goto no_protocols;
6390
6391   /* reset some state */
6392   src->free_channel = 0;
6393   src->interleaved = FALSE;
6394   src->need_activate = FALSE;
6395   /* keep track of next port number, 0 is random */
6396   src->next_port_num = src->client_port_range.min;
6397   rtpport = rtcpport = 0;
6398
6399   if (G_UNLIKELY (src->streams == NULL))
6400     goto no_streams;
6401
6402   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6403     GstRTSPConnInfo *conninfo;
6404     gchar *transports;
6405     gint retry = 0;
6406     guint mask = 0;
6407     gboolean selected;
6408     GstCaps *caps;
6409
6410     stream = (GstRTSPStream *) walk->data;
6411
6412     caps = stream_get_caps_for_pt (stream, stream->default_pt);
6413     if (caps == NULL) {
6414       GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
6415       continue;
6416     }
6417
6418     if (stream->skipped) {
6419       GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6420       continue;
6421     }
6422
6423     /* see if we need to configure this stream */
6424     if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6425       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6426           stream);
6427       continue;
6428     }
6429
6430     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6431         stream->id, caps, &selected);
6432     if (!selected) {
6433       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6434       continue;
6435     }
6436
6437     /* merge/overwrite global caps */
6438     if (caps) {
6439       guint j, num;
6440       GstStructure *s;
6441
6442       s = gst_caps_get_structure (caps, 0);
6443
6444       num = gst_structure_n_fields (src->props);
6445       for (j = 0; j < num; j++) {
6446         const gchar *name;
6447         const GValue *val;
6448
6449         name = gst_structure_nth_field_name (src->props, j);
6450         val = gst_structure_get_value (src->props, name);
6451         gst_structure_set_value (s, name, val);
6452
6453         GST_DEBUG_OBJECT (src, "copied %s", name);
6454       }
6455     }
6456
6457     /* skip setup if we have no URL for it */
6458     if (stream->conninfo.location == NULL) {
6459       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6460       continue;
6461     }
6462
6463     if (src->conninfo.connection == NULL) {
6464       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6465         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6466         continue;
6467       }
6468       conninfo = &stream->conninfo;
6469     } else {
6470       conninfo = &src->conninfo;
6471     }
6472     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6473         stream->conninfo.location);
6474
6475     /* if we have a multicast connection, only suggest multicast from now on */
6476     if (stream->is_multicast)
6477       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6478
6479   next_protocol:
6480     /* first selectable protocol */
6481     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6482       mask++;
6483     if (!protocol_masks[mask])
6484       goto no_protocols;
6485
6486   retry:
6487     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6488         protocol_masks[mask]);
6489     /* create a string with first transport in line */
6490     transports = NULL;
6491     res = gst_rtspsrc_create_transports_string (src,
6492         protocols & protocol_masks[mask], stream->profile, &transports);
6493     if (res < 0 || transports == NULL)
6494       goto setup_transport_failed;
6495
6496     if (strlen (transports) == 0) {
6497       g_free (transports);
6498       GST_DEBUG_OBJECT (src, "no transports found");
6499       mask++;
6500       goto next_protocol;
6501     }
6502
6503     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6504
6505     /* replace placeholders with real values, this function will optionally
6506      * allocate UDP ports and other info needed to execute the setup request */
6507     res = gst_rtspsrc_prepare_transports (stream, &transports,
6508         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6509     if (res < 0) {
6510       g_free (transports);
6511       goto setup_transport_failed;
6512     }
6513
6514     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6515     /* create SETUP request */
6516     res =
6517         gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
6518         stream->conninfo.location);
6519     if (res < 0) {
6520       g_free (transports);
6521       goto create_request_failed;
6522     }
6523
6524     if (src->version >= GST_RTSP_VERSION_2_0) {
6525       if (!pipelined_request_id)
6526         pipelined_request_id = g_strdup_printf ("%d",
6527             g_random_int_range (0, G_MAXINT32));
6528
6529       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_PIPELINED_REQUESTS,
6530           pipelined_request_id);
6531       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT_RANGES,
6532           "npt, clock, smpte, clock");
6533     }
6534
6535     /* select transport */
6536     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6537
6538     /* set up keys */
6539     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6540         stream->profile == GST_RTSP_PROFILE_SAVPF) {
6541       hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6542       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6543     }
6544
6545     /* if the user wants a non default RTP packet size we add the blocksize
6546      * parameter */
6547     if (src->rtp_blocksize > 0) {
6548       hval = g_strdup_printf ("%d", src->rtp_blocksize);
6549       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6550     }
6551
6552     if (async)
6553       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6554               stream->id));
6555
6556     /* handle the code ourselves */
6557     res =
6558         gst_rtspsrc_send (src, conninfo, &request,
6559         pipelined_request_id ? NULL : &response, &code, NULL);
6560     if (res < 0)
6561       goto send_error;
6562
6563     switch (code) {
6564       case GST_RTSP_STS_OK:
6565         break;
6566       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6567         gst_rtsp_message_unset (&request);
6568         gst_rtsp_message_unset (&response);
6569         /* cleanup of leftover transport */
6570         gst_rtspsrc_stream_free_udp (stream);
6571         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6572          * we might be in this case */
6573         if (stream->container && rtpport && rtcpport && !retry) {
6574           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6575               rtpport, rtcpport);
6576           retry++;
6577           goto retry;
6578         }
6579         /* this transport did not go down well, but we may have others to try
6580          * that we did not send yet, try those and only give up then
6581          * but not without checking for lost cause/extension so we can
6582          * post a nicer/more useful error message later */
6583         if (!unsupported_real)
6584           unsupported_real = stream->is_real;
6585         /* select next available protocol, give up on this stream if none */
6586         mask++;
6587         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6588           mask++;
6589         if (!protocol_masks[mask] || unsupported_real)
6590           continue;
6591         else
6592           goto retry;
6593       default:
6594         /* cleanup of leftover transport and move to the next stream */
6595         gst_rtspsrc_stream_free_udp (stream);
6596         goto response_error;
6597     }
6598
6599
6600     if (!pipelined_request_id) {
6601       /* parse response transport */
6602       res = gst_rtsp_src_setup_stream_from_response (src, stream,
6603           &response, &protocols, retry, &rtpport, &rtcpport);
6604       switch (res) {
6605         case GST_RTSP_ERROR:
6606           goto cleanup_error;
6607         case GST_RTSP_ELAST:
6608           goto retry;
6609         default:
6610           break;
6611       }
6612     } else {
6613       stream->waiting_setup_response = TRUE;
6614       /* we need to activate at least one stream when we detect activity */
6615       src->need_activate = TRUE;
6616     }
6617
6618     {
6619       GList *skip = walk;
6620
6621       while (TRUE) {
6622         GstRTSPStream *sskip;
6623
6624         skip = g_list_next (skip);
6625         if (skip == NULL)
6626           break;
6627
6628         sskip = (GstRTSPStream *) skip->data;
6629
6630         /* skip all streams with the same control url */
6631         if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6632           GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6633               sskip, sskip->conninfo.location);
6634           sskip->skipped = TRUE;
6635         }
6636       }
6637     }
6638     gst_rtsp_message_unset (&request);
6639   }
6640
6641   if (pipelined_request_id) {
6642     gst_rtspsrc_setup_streams_end (src, TRUE);
6643   }
6644
6645   /* store the transport protocol that was configured */
6646   src->cur_protocols = protocols;
6647
6648   gst_rtsp_ext_list_stream_select (src->extensions, url);
6649
6650   /* if there is nothing to activate, error out */
6651   if (!src->need_activate)
6652     goto nothing_to_activate;
6653
6654   return res;
6655
6656   /* ERRORS */
6657 no_protocols:
6658   {
6659     /* no transport possible, post an error and stop */
6660     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6661         ("Could not connect to server, no protocols left"));
6662     return GST_RTSP_ERROR;
6663   }
6664 no_streams:
6665   {
6666     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6667         ("SDP contains no streams"));
6668     return GST_RTSP_ERROR;
6669   }
6670 create_request_failed:
6671   {
6672     gchar *str = gst_rtsp_strresult (res);
6673
6674     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6675         ("Could not create request. (%s)", str));
6676     g_free (str);
6677     goto cleanup_error;
6678   }
6679 setup_transport_failed:
6680   {
6681     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6682         ("Could not setup transport."));
6683     res = GST_RTSP_ERROR;
6684     goto cleanup_error;
6685   }
6686 response_error:
6687   {
6688     const gchar *str = gst_rtsp_status_as_text (code);
6689
6690     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6691         ("Error (%d): %s", code, GST_STR_NULL (str)));
6692     res = GST_RTSP_ERROR;
6693     goto cleanup_error;
6694   }
6695 send_error:
6696   {
6697     gchar *str = gst_rtsp_strresult (res);
6698
6699     if (res != GST_RTSP_EINTR) {
6700       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6701           ("Could not send message. (%s)", str));
6702     } else {
6703       GST_WARNING_OBJECT (src, "send interrupted");
6704     }
6705     g_free (str);
6706     goto cleanup_error;
6707   }
6708 nothing_to_activate:
6709   {
6710     /* none of the available error codes is really right .. */
6711     if (unsupported_real) {
6712       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6713           (_("No supported stream was found. You might need to install a "
6714                   "GStreamer RTSP extension plugin for Real media streams.")),
6715           (NULL));
6716     } else {
6717       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6718           (_("No supported stream was found. You might need to allow "
6719                   "more transport protocols or may otherwise be missing "
6720                   "the right GStreamer RTSP extension plugin.")), (NULL));
6721     }
6722     return GST_RTSP_ERROR;
6723   }
6724 cleanup_error:
6725   {
6726     gst_rtsp_message_unset (&request);
6727     gst_rtsp_message_unset (&response);
6728     return res;
6729   }
6730 }
6731
6732 static gboolean
6733 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6734     GstSegment * segment)
6735 {
6736   gint64 seconds;
6737   GstRTSPTimeRange *therange;
6738
6739   if (src->range)
6740     gst_rtsp_range_free (src->range);
6741
6742   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6743     GST_DEBUG_OBJECT (src, "parsed range %s", range);
6744     src->range = therange;
6745   } else {
6746     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6747     src->range = NULL;
6748     gst_segment_init (segment, GST_FORMAT_TIME);
6749     return FALSE;
6750   }
6751
6752   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
6753       therange->min.type, therange->min.seconds, therange->max.type,
6754       therange->max.seconds);
6755
6756   if (therange->min.type == GST_RTSP_TIME_NOW)
6757     seconds = 0;
6758   else if (therange->min.type == GST_RTSP_TIME_END)
6759     seconds = 0;
6760   else
6761     seconds = therange->min.seconds * GST_SECOND;
6762
6763   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6764       GST_TIME_ARGS (seconds));
6765
6766   /* we need to start playback without clipping from the position reported by
6767    * the server */
6768   segment->start = seconds;
6769   segment->position = seconds;
6770
6771   if (therange->max.type == GST_RTSP_TIME_NOW)
6772     seconds = -1;
6773   else if (therange->max.type == GST_RTSP_TIME_END)
6774     seconds = -1;
6775   else
6776     seconds = therange->max.seconds * GST_SECOND;
6777
6778   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6779       GST_TIME_ARGS (seconds));
6780
6781   /* live (WMS) server might send overflowed large max as its idea of infinity,
6782    * compensate to prevent problems later on */
6783   if (seconds != -1 && seconds < 0) {
6784     seconds = -1;
6785     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6786   }
6787
6788   /* live (WMS) might send min == max, which is not worth recording */
6789   if (segment->duration == -1 && seconds == segment->start)
6790     seconds = -1;
6791
6792   /* don't change duration with unknown value, we might have a valid value
6793    * there that we want to keep. */
6794   if (seconds != -1)
6795     segment->duration = seconds;
6796
6797   return TRUE;
6798 }
6799
6800 /* Parse clock profived by the server with following syntax:
6801  *
6802  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6803  */
6804 static gboolean
6805 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6806 {
6807   gboolean res = FALSE;
6808
6809   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6810     gchar **fields = NULL, **parts = NULL;
6811     gchar *remote_ip, *str;
6812     gint port;
6813     GstClockTime base_time;
6814     GstClock *netclock;
6815
6816     fields = g_strsplit (gstclock, " ", 0);
6817
6818     /* wrapped clock, not very interesting for now */
6819     if (fields[1] == NULL)
6820       goto cleanup;
6821
6822     /* remote IP address and port */
6823     if ((str = fields[2]) == NULL)
6824       goto cleanup;
6825
6826     parts = g_strsplit (str, ":", 0);
6827
6828     if ((remote_ip = parts[0]) == NULL)
6829       goto cleanup;
6830
6831     if ((str = parts[1]) == NULL)
6832       goto cleanup;
6833
6834     port = atoi (str);
6835     if (port == 0)
6836       goto cleanup;
6837
6838     /* base-time */
6839     if ((str = fields[3]) == NULL)
6840       goto cleanup;
6841
6842     base_time = g_ascii_strtoull (str, NULL, 10);
6843
6844     netclock =
6845         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
6846         base_time);
6847
6848     if (src->provided_clock)
6849       gst_object_unref (src->provided_clock);
6850     src->provided_clock = netclock;
6851
6852     gst_element_post_message (GST_ELEMENT_CAST (src),
6853         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
6854             src->provided_clock, TRUE));
6855
6856     res = TRUE;
6857   cleanup:
6858     g_strfreev (fields);
6859     g_strfreev (parts);
6860   }
6861   return res;
6862 }
6863
6864 /* must be called with the RTSP state lock */
6865 static GstRTSPResult
6866 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
6867     gboolean async)
6868 {
6869   GstRTSPResult res;
6870   gint i, n_streams;
6871
6872   /* prepare global stream caps properties */
6873   if (src->props)
6874     gst_structure_remove_all_fields (src->props);
6875   else
6876     src->props = gst_structure_new_empty ("RTSPProperties");
6877
6878   DEBUG_SDP (src, sdp);
6879
6880   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
6881
6882   /* let the app inspect and change the SDP */
6883   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
6884
6885   gst_segment_init (&src->segment, GST_FORMAT_TIME);
6886
6887   /* parse range for duration reporting. */
6888   {
6889     const gchar *range;
6890
6891     for (i = 0;; i++) {
6892       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
6893       if (range == NULL)
6894         break;
6895
6896       /* keep track of the range and configure it in the segment */
6897       if (gst_rtspsrc_parse_range (src, range, &src->segment))
6898         break;
6899     }
6900   }
6901   /* parse clock information. This is GStreamer specific, a server can tell the
6902    * client what clock it is using and wrap that in a network clock. The
6903    * advantage of that is that we can slave to it. */
6904   {
6905     const gchar *gstclock;
6906
6907     for (i = 0;; i++) {
6908       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6909       if (gstclock == NULL)
6910         break;
6911
6912       /* parse the clock and expose it in the provide_clock method */
6913       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6914         break;
6915     }
6916   }
6917   /* try to find a global control attribute. Note that a '*' means that we should
6918    * do aggregate control with the current url (so we don't do anything and
6919    * leave the current connection as is) */
6920   {
6921     const gchar *control;
6922
6923     for (i = 0;; i++) {
6924       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6925       if (control == NULL)
6926         break;
6927
6928       /* only take fully qualified urls */
6929       if (g_str_has_prefix (control, "rtsp://"))
6930         break;
6931     }
6932     if (control) {
6933       g_free (src->conninfo.location);
6934       src->conninfo.location = g_strdup (control);
6935       /* make a connection for this, if there was a connection already, nothing
6936        * happens. */
6937       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6938         GST_ERROR_OBJECT (src, "could not connect");
6939       }
6940     }
6941     /* we need to keep the control url separate from the connection url because
6942      * the rules for constructing the media control url need it */
6943     g_free (src->control);
6944     src->control = g_strdup (control);
6945   }
6946
6947   /* create streams */
6948   n_streams = gst_sdp_message_medias_len (sdp);
6949   for (i = 0; i < n_streams; i++) {
6950     gst_rtspsrc_create_stream (src, sdp, i, n_streams);
6951   }
6952
6953   src->state = GST_RTSP_STATE_INIT;
6954
6955   /* setup streams */
6956   if ((res = gst_rtspsrc_setup_streams_start (src, async)) < 0)
6957     goto setup_failed;
6958
6959   /* reset our state */
6960   src->need_range = TRUE;
6961   src->skip = FALSE;
6962
6963   src->state = GST_RTSP_STATE_READY;
6964
6965   return res;
6966
6967   /* ERRORS */
6968 setup_failed:
6969   {
6970     GST_ERROR_OBJECT (src, "setup failed");
6971     gst_rtspsrc_cleanup (src);
6972     return res;
6973   }
6974 }
6975
6976 static GstRTSPResult
6977 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6978     gboolean async)
6979 {
6980   GstRTSPResult res;
6981   GstRTSPMessage request = { 0 };
6982   GstRTSPMessage response = { 0 };
6983   guint8 *data;
6984   guint size;
6985   gchar *respcont = NULL;
6986   GstRTSPVersion versions[] =
6987       { GST_RTSP_VERSION_2_0, GST_RTSP_VERSION_INVALID };
6988
6989   src->version = src->default_version;
6990   if (src->default_version == GST_RTSP_VERSION_2_0) {
6991     versions[0] = GST_RTSP_VERSION_1_0;
6992   }
6993
6994 restart:
6995   src->need_redirect = FALSE;
6996
6997   /* can't continue without a valid url */
6998   if (G_UNLIKELY (src->conninfo.url == NULL)) {
6999     res = GST_RTSP_EINVAL;
7000     goto no_url;
7001   }
7002   src->tried_url_auth = FALSE;
7003
7004   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
7005     goto connect_failed;
7006
7007   /* create OPTIONS */
7008   GST_DEBUG_OBJECT (src, "create options... (%s)", async ? "async" : "sync");
7009   res =
7010       gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
7011       src->conninfo.url_str);
7012   if (res < 0)
7013     goto create_request_failed;
7014
7015   /* send OPTIONS */
7016   request.type_data.request.version = src->version;
7017   GST_DEBUG_OBJECT (src, "send options...");
7018
7019   if (async)
7020     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
7021
7022   if ((res =
7023           gst_rtspsrc_send (src, &src->conninfo, &request, &response,
7024               NULL, versions)) < 0) {
7025     goto send_error;
7026   }
7027
7028   src->version = request.type_data.request.version;
7029   GST_INFO_OBJECT (src, "Now using version: %s",
7030       gst_rtsp_version_as_text (src->version));
7031
7032   /* parse OPTIONS */
7033   if (!gst_rtspsrc_parse_methods (src, &response))
7034     goto methods_error;
7035
7036   /* create DESCRIBE */
7037   GST_DEBUG_OBJECT (src, "create describe...");
7038   res =
7039       gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
7040       src->conninfo.url_str);
7041   if (res < 0)
7042     goto create_request_failed;
7043
7044   /* we only accept SDP for now */
7045   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
7046       "application/sdp");
7047
7048   /* send DESCRIBE */
7049   GST_DEBUG_OBJECT (src, "send describe...");
7050
7051   if (async)
7052     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
7053
7054   if ((res =
7055           gst_rtspsrc_send (src, &src->conninfo, &request, &response,
7056               NULL, NULL)) < 0)
7057     goto send_error;
7058
7059   /* we only perform redirect for describe and play, currently */
7060   if (src->need_redirect) {
7061     /* close connection, we don't have to send a TEARDOWN yet, ignore the
7062      * result. */
7063     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7064
7065     gst_rtsp_message_unset (&request);
7066     gst_rtsp_message_unset (&response);
7067
7068     /* and now retry */
7069     goto restart;
7070   }
7071
7072   /* it could be that the DESCRIBE method was not implemented */
7073   if (!(src->methods & GST_RTSP_DESCRIBE))
7074     goto no_describe;
7075
7076   /* check if reply is SDP */
7077   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
7078       0);
7079   /* could not be set but since the request returned OK, we assume it
7080    * was SDP, else check it. */
7081   if (respcont) {
7082     const gchar *props = strchr (respcont, ';');
7083
7084     if (props) {
7085       gchar *mimetype = g_strndup (respcont, props - respcont);
7086
7087       mimetype = g_strstrip (mimetype);
7088       if (g_ascii_strcasecmp (mimetype, "application/sdp") != 0) {
7089         g_free (mimetype);
7090         goto wrong_content_type;
7091       }
7092
7093       /* TODO: Check for charset property and do conversions of all messages if
7094        * needed. Some servers actually send that property */
7095
7096       g_free (mimetype);
7097     } else if (g_ascii_strcasecmp (respcont, "application/sdp") != 0) {
7098       goto wrong_content_type;
7099     }
7100   }
7101
7102   /* get message body and parse as SDP */
7103   gst_rtsp_message_get_body (&response, &data, &size);
7104   if (data == NULL || size == 0)
7105     goto no_describe;
7106
7107   GST_DEBUG_OBJECT (src, "parse SDP...");
7108   gst_sdp_message_new (sdp);
7109   gst_sdp_message_parse_buffer (data, size, *sdp);
7110
7111   /* clean up any messages */
7112   gst_rtsp_message_unset (&request);
7113   gst_rtsp_message_unset (&response);
7114
7115   return res;
7116
7117   /* ERRORS */
7118 no_url:
7119   {
7120     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
7121         ("No valid RTSP URL was provided"));
7122     goto cleanup_error;
7123   }
7124 connect_failed:
7125   {
7126     gchar *str = gst_rtsp_strresult (res);
7127
7128     if (res != GST_RTSP_EINTR) {
7129       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
7130           ("Failed to connect. (%s)", str));
7131     } else {
7132       GST_WARNING_OBJECT (src, "connect interrupted");
7133     }
7134     g_free (str);
7135     goto cleanup_error;
7136   }
7137 create_request_failed:
7138   {
7139     gchar *str = gst_rtsp_strresult (res);
7140
7141     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7142         ("Could not create request. (%s)", str));
7143     g_free (str);
7144     goto cleanup_error;
7145   }
7146 send_error:
7147   {
7148     /* Don't post a message - the rtsp_send method will have
7149      * taken care of it because we passed NULL for the response code */
7150     goto cleanup_error;
7151   }
7152 methods_error:
7153   {
7154     /* error was posted */
7155     res = GST_RTSP_ERROR;
7156     goto cleanup_error;
7157   }
7158 wrong_content_type:
7159   {
7160     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7161         ("Server does not support SDP, got %s.", respcont));
7162     res = GST_RTSP_ERROR;
7163     goto cleanup_error;
7164   }
7165 no_describe:
7166   {
7167     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7168         ("Server can not provide an SDP."));
7169     res = GST_RTSP_ERROR;
7170     goto cleanup_error;
7171   }
7172 cleanup_error:
7173   {
7174     if (src->conninfo.connection) {
7175       GST_DEBUG_OBJECT (src, "free connection");
7176       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7177     }
7178     gst_rtsp_message_unset (&request);
7179     gst_rtsp_message_unset (&response);
7180     return res;
7181   }
7182 }
7183
7184 static GstRTSPResult
7185 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
7186 {
7187   GstRTSPResult ret;
7188
7189   src->methods =
7190       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
7191
7192   if (src->sdp == NULL) {
7193     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
7194       goto no_sdp;
7195   }
7196
7197   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
7198     goto open_failed;
7199
7200 done:
7201   if (async)
7202     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
7203
7204   return ret;
7205
7206   /* ERRORS */
7207 no_sdp:
7208   {
7209     GST_WARNING_OBJECT (src, "can't get sdp");
7210     src->open_error = TRUE;
7211     goto done;
7212   }
7213 open_failed:
7214   {
7215     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
7216     src->open_error = TRUE;
7217     goto done;
7218   }
7219 }
7220
7221 static GstRTSPResult
7222 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
7223 {
7224   GstRTSPMessage request = { 0 };
7225   GstRTSPMessage response = { 0 };
7226   GstRTSPResult res = GST_RTSP_OK;
7227   GList *walk;
7228   const gchar *control;
7229
7230   GST_DEBUG_OBJECT (src, "TEARDOWN...");
7231
7232   gst_rtspsrc_set_state (src, GST_STATE_READY);
7233
7234   if (src->state < GST_RTSP_STATE_READY) {
7235     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
7236     goto close;
7237   }
7238
7239   if (only_close)
7240     goto close;
7241
7242   /* construct a control url */
7243   control = get_aggregate_control (src);
7244
7245   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
7246     goto not_supported;
7247
7248   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7249     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7250     const gchar *setup_url;
7251     GstRTSPConnInfo *info;
7252
7253     /* try aggregate control first but do non-aggregate control otherwise */
7254     if (control)
7255       setup_url = control;
7256     else if ((setup_url = stream->conninfo.location) == NULL)
7257       continue;
7258
7259     if (src->conninfo.connection) {
7260       info = &src->conninfo;
7261     } else if (stream->conninfo.connection) {
7262       info = &stream->conninfo;
7263     } else {
7264       continue;
7265     }
7266     if (!info->connected)
7267       goto next;
7268
7269     /* do TEARDOWN */
7270     res =
7271         gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
7272     if (res < 0)
7273       goto create_request_failed;
7274
7275     if (async)
7276       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
7277
7278     if ((res =
7279             gst_rtspsrc_send (src, info, &request, &response, NULL, NULL)) < 0)
7280       goto send_error;
7281
7282     /* FIXME, parse result? */
7283     gst_rtsp_message_unset (&request);
7284     gst_rtsp_message_unset (&response);
7285
7286   next:
7287     /* early exit when we did aggregate control */
7288     if (control)
7289       break;
7290   }
7291
7292 close:
7293   /* close connections */
7294   GST_DEBUG_OBJECT (src, "closing connection...");
7295   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7296   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7297     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7298     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
7299   }
7300
7301   /* cleanup */
7302   gst_rtspsrc_cleanup (src);
7303
7304   src->state = GST_RTSP_STATE_INVALID;
7305
7306   if (async)
7307     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
7308
7309   return res;
7310
7311   /* ERRORS */
7312 create_request_failed:
7313   {
7314     gchar *str = gst_rtsp_strresult (res);
7315
7316     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7317         ("Could not create request. (%s)", str));
7318     g_free (str);
7319     goto close;
7320   }
7321 send_error:
7322   {
7323     gchar *str = gst_rtsp_strresult (res);
7324
7325     gst_rtsp_message_unset (&request);
7326     if (res != GST_RTSP_EINTR) {
7327       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7328           ("Could not send message. (%s)", str));
7329     } else {
7330       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7331     }
7332     g_free (str);
7333     goto close;
7334   }
7335 not_supported:
7336   {
7337     GST_DEBUG_OBJECT (src,
7338         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7339     goto close;
7340   }
7341 }
7342
7343 /* RTP-Info is of the format:
7344  *
7345  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7346  *
7347  * rtptime corresponds to the timestamp for the NPT time given in the header
7348  * seqbase corresponds to the next sequence number we received. This number
7349  * indicates the first seqnum after the seek and should be used to discard
7350  * packets that are from before the seek.
7351  */
7352 static gboolean
7353 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7354 {
7355   gchar **infos;
7356   gint i, j;
7357
7358   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7359
7360   infos = g_strsplit (rtpinfo, ",", 0);
7361   for (i = 0; infos[i]; i++) {
7362     gchar **fields;
7363     GstRTSPStream *stream;
7364     gint32 seqbase;
7365     gint64 timebase;
7366
7367     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7368
7369     /* init values, types of seqbase and timebase are bigger than needed so we
7370      * can store -1 as uninitialized values */
7371     stream = NULL;
7372     seqbase = -1;
7373     timebase = -1;
7374
7375     /* parse url, find stream for url.
7376      * parse seq and rtptime. The seq number should be configured in the rtp
7377      * depayloader or session manager to detect gaps. Same for the rtptime, it
7378      * should be used to create an initial time newsegment. */
7379     fields = g_strsplit (infos[i], ";", 0);
7380     for (j = 0; fields[j]; j++) {
7381       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7382       /* remove leading whitespace */
7383       fields[j] = g_strchug (fields[j]);
7384       if (g_str_has_prefix (fields[j], "url=")) {
7385         /* get the url and the stream */
7386         stream =
7387             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7388       } else if (g_str_has_prefix (fields[j], "seq=")) {
7389         seqbase = atoi (fields[j] + 4);
7390       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7391         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7392       }
7393     }
7394     g_strfreev (fields);
7395     /* now we need to store the values for the caps of the stream */
7396     if (stream != NULL) {
7397       GST_DEBUG_OBJECT (src,
7398           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7399           stream, seqbase, timebase);
7400
7401       /* we have a stream, configure detected params */
7402       stream->seqbase = seqbase;
7403       stream->timebase = timebase;
7404     }
7405   }
7406   g_strfreev (infos);
7407
7408   return TRUE;
7409 }
7410
7411 static void
7412 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7413 {
7414   guint64 interval;
7415   GList *walk;
7416
7417   interval = strtoul (rtcp, NULL, 10);
7418   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7419
7420   if (!interval)
7421     return;
7422
7423   interval *= GST_MSECOND;
7424
7425   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7426     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7427
7428     /* already (optionally) retrieved this when configuring manager */
7429     if (stream->session) {
7430       GObject *rtpsession = stream->session;
7431
7432       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7433           rtpsession);
7434       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7435     }
7436   }
7437
7438   /* now it happens that (Xenon) server sending this may also provide bogus
7439    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7440    * and just use RTP-Info to sync */
7441   if (src->manager) {
7442     GObjectClass *klass;
7443
7444     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7445     if (g_object_class_find_property (klass, "rtcp-sync")) {
7446       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7447       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7448     }
7449   }
7450 }
7451
7452 static gdouble
7453 gst_rtspsrc_get_float (const gchar * dstr)
7454 {
7455   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7456
7457   /* canonicalise floating point string so we can handle float strings
7458    * in the form "24.930" or "24,930" irrespective of the current locale */
7459   g_strlcpy (s, dstr, sizeof (s));
7460   g_strdelimit (s, ",", '.');
7461   return g_ascii_strtod (s, NULL);
7462 }
7463
7464 static gchar *
7465 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7466 {
7467   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7468
7469   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7470     g_strlcpy (val_str, "now", sizeof (val_str));
7471   } else {
7472     if (segment->position == 0) {
7473       g_strlcpy (val_str, "0", sizeof (val_str));
7474     } else {
7475       g_ascii_dtostr (val_str, sizeof (val_str),
7476           ((gdouble) segment->position) / GST_SECOND);
7477     }
7478   }
7479   return g_strdup_printf ("npt=%s-", val_str);
7480 }
7481
7482 static void
7483 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7484 {
7485   guint i, len;
7486
7487   stream->timebase = -1;
7488   stream->seqbase = -1;
7489
7490   len = stream->ptmap->len;
7491   for (i = 0; i < len; i++) {
7492     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7493     GstStructure *s;
7494
7495     if (item->caps == NULL)
7496       continue;
7497
7498     item->caps = gst_caps_make_writable (item->caps);
7499     s = gst_caps_get_structure (item->caps, 0);
7500     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7501     if (item->pt == stream->default_pt && stream->udpsrc[0])
7502       g_object_set (stream->udpsrc[0], "caps", item->caps, NULL);
7503   }
7504   stream->need_caps = TRUE;
7505 }
7506
7507 static GstRTSPResult
7508 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7509 {
7510   GstRTSPResult res = GST_RTSP_OK;
7511
7512   if (src->state < GST_RTSP_STATE_READY) {
7513     res = GST_RTSP_ERROR;
7514     if (src->open_error) {
7515       GST_DEBUG_OBJECT (src, "the stream was in error");
7516       goto done;
7517     }
7518     if (async)
7519       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7520
7521     if ((res = gst_rtspsrc_open (src, async)) < 0) {
7522       GST_DEBUG_OBJECT (src, "failed to open stream");
7523       goto done;
7524     }
7525   }
7526
7527 done:
7528   return res;
7529 }
7530
7531 static GstRTSPResult
7532 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async,
7533     const gchar * seek_style)
7534 {
7535   GstRTSPMessage request = { 0 };
7536   GstRTSPMessage response = { 0 };
7537   GstRTSPResult res = GST_RTSP_OK;
7538   GList *walk;
7539   gchar *hval;
7540   gint hval_idx;
7541   const gchar *control;
7542
7543   GST_DEBUG_OBJECT (src, "PLAY...");
7544
7545 restart:
7546   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7547     goto open_failed;
7548
7549   if (!(src->methods & GST_RTSP_PLAY))
7550     goto not_supported;
7551
7552   if (src->state == GST_RTSP_STATE_PLAYING)
7553     goto was_playing;
7554
7555   if (!src->conninfo.connection || !src->conninfo.connected)
7556     goto done;
7557
7558   /* send some dummy packets before we activate the receive in the
7559    * udp sources */
7560   gst_rtspsrc_send_dummy_packets (src);
7561
7562   /* require new SR packets */
7563   if (src->manager)
7564     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7565
7566   /* construct a control url */
7567   control = get_aggregate_control (src);
7568
7569   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7570     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7571     const gchar *setup_url;
7572     GstRTSPConnInfo *conninfo;
7573
7574     /* try aggregate control first but do non-aggregate control otherwise */
7575     if (control)
7576       setup_url = control;
7577     else if ((setup_url = stream->conninfo.location) == NULL)
7578       continue;
7579
7580     if (src->conninfo.connection) {
7581       conninfo = &src->conninfo;
7582     } else if (stream->conninfo.connection) {
7583       conninfo = &stream->conninfo;
7584     } else {
7585       continue;
7586     }
7587
7588     /* do play */
7589     res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
7590     if (res < 0)
7591       goto create_request_failed;
7592
7593     if (src->need_range && src->seekable >= 0.0) {
7594       hval = gen_range_header (src, segment);
7595
7596       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7597
7598       /* store the newsegment event so it can be sent from the streaming thread. */
7599       src->need_segment = TRUE;
7600     }
7601
7602     if (segment->rate != 1.0) {
7603       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7604
7605       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7606       if (src->skip)
7607         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7608       else
7609         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7610     }
7611
7612     if (seek_style)
7613       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SEEK_STYLE,
7614           seek_style);
7615
7616     if (async)
7617       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7618
7619     if ((res =
7620             gst_rtspsrc_send (src, conninfo, &request, &response, NULL, NULL))
7621         < 0)
7622       goto send_error;
7623
7624     if (src->need_redirect) {
7625       GST_DEBUG_OBJECT (src,
7626           "redirect: tearing down and restarting with new url");
7627       /* teardown and restart with new url */
7628       gst_rtspsrc_close (src, TRUE, FALSE);
7629       /* reset protocols to force re-negotiation with redirected url */
7630       src->cur_protocols = src->protocols;
7631       gst_rtsp_message_unset (&request);
7632       gst_rtsp_message_unset (&response);
7633       goto restart;
7634     }
7635
7636     /* seek may have silently failed as it is not supported */
7637     if (!(src->methods & GST_RTSP_PLAY)) {
7638       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7639
7640       if (src->version >= GST_RTSP_VERSION_2_0 && src->seekable >= 0.0) {
7641         GST_WARNING_OBJECT (src, "Server declared stream as seekable but"
7642             " playing with range failed... Ignoring information.");
7643       }
7644       /* obviously it is supported as we made it here */
7645       src->methods |= GST_RTSP_PLAY;
7646       src->seekable = -1.0;
7647       /* but there is nothing to parse in the response,
7648        * so convey we have no idea and not to expect anything particular */
7649       clear_rtp_base (src, stream);
7650       if (control) {
7651         GList *run;
7652
7653         /* need to do for all streams */
7654         for (run = src->streams; run; run = g_list_next (run))
7655           clear_rtp_base (src, (GstRTSPStream *) run->data);
7656       }
7657       /* NOTE the above also disables npt based eos detection */
7658       /* and below forces position to 0,
7659        * which is visible feedback we lost the plot */
7660       segment->start = segment->position = src->last_pos;
7661     }
7662
7663     gst_rtsp_message_unset (&request);
7664
7665     /* parse RTP npt field. This is the current position in the stream (Normal
7666      * Play Time) and should be put in the NEWSEGMENT position field. */
7667     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7668             0) == GST_RTSP_OK)
7669       gst_rtspsrc_parse_range (src, hval, segment);
7670
7671     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7672     segment->rate = 1.0;
7673
7674     /* parse Speed header. This is the intended playback rate of the stream
7675      * and should be put in the NEWSEGMENT rate field. */
7676     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7677             0) == GST_RTSP_OK) {
7678       segment->rate = gst_rtspsrc_get_float (hval);
7679     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7680             &hval, 0) == GST_RTSP_OK) {
7681       segment->rate = gst_rtspsrc_get_float (hval);
7682     }
7683
7684     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7685      * for the RTP packets. If this is not present, we assume all starts from 0...
7686      * This is info for the RTP session manager that we pass to it in caps. */
7687     hval_idx = 0;
7688     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7689             &hval, hval_idx++) == GST_RTSP_OK)
7690       gst_rtspsrc_parse_rtpinfo (src, hval);
7691
7692     /* some servers indicate RTCP parameters in PLAY response,
7693      * rather than properly in SDP */
7694     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7695             &hval, 0) == GST_RTSP_OK)
7696       gst_rtspsrc_handle_rtcp_interval (src, hval);
7697
7698     gst_rtsp_message_unset (&response);
7699
7700     /* early exit when we did aggregate control */
7701     if (control)
7702       break;
7703   }
7704   /* configure the caps of the streams after we parsed all headers. Only reset
7705    * the manager object when we set a new Range header (we did a seek) */
7706   gst_rtspsrc_configure_caps (src, segment, src->need_range);
7707
7708   /* set to PLAYING after we have configured the caps, otherwise we
7709    * might end up calling request_key (with SRTP) while caps are still
7710    * being configured. */
7711   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7712
7713   /* set again when needed */
7714   src->need_range = FALSE;
7715
7716   src->running = TRUE;
7717   src->base_time = -1;
7718   src->state = GST_RTSP_STATE_PLAYING;
7719
7720   /* mark discont */
7721   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7722   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7723     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7724     stream->discont = TRUE;
7725   }
7726
7727 done:
7728   if (async)
7729     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7730
7731   return res;
7732
7733   /* ERRORS */
7734 open_failed:
7735   {
7736     GST_DEBUG_OBJECT (src, "failed to open stream");
7737     goto done;
7738   }
7739 not_supported:
7740   {
7741     GST_DEBUG_OBJECT (src, "PLAY is not supported");
7742     goto done;
7743   }
7744 was_playing:
7745   {
7746     GST_DEBUG_OBJECT (src, "we were already PLAYING");
7747     goto done;
7748   }
7749 create_request_failed:
7750   {
7751     gchar *str = gst_rtsp_strresult (res);
7752
7753     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7754         ("Could not create request. (%s)", str));
7755     g_free (str);
7756     goto done;
7757   }
7758 send_error:
7759   {
7760     gchar *str = gst_rtsp_strresult (res);
7761
7762     gst_rtsp_message_unset (&request);
7763     if (res != GST_RTSP_EINTR) {
7764       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7765           ("Could not send message. (%s)", str));
7766     } else {
7767       GST_WARNING_OBJECT (src, "PLAY interrupted");
7768     }
7769     g_free (str);
7770     goto done;
7771   }
7772 }
7773
7774 static GstRTSPResult
7775 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7776 {
7777   GstRTSPResult res = GST_RTSP_OK;
7778   GstRTSPMessage request = { 0 };
7779   GstRTSPMessage response = { 0 };
7780   GList *walk;
7781   const gchar *control;
7782
7783   GST_DEBUG_OBJECT (src, "PAUSE...");
7784
7785   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7786     goto open_failed;
7787
7788   if (!(src->methods & GST_RTSP_PAUSE))
7789     goto not_supported;
7790
7791   if (src->state == GST_RTSP_STATE_READY)
7792     goto was_paused;
7793
7794   if (!src->conninfo.connection || !src->conninfo.connected)
7795     goto no_connection;
7796
7797   /* construct a control url */
7798   control = get_aggregate_control (src);
7799
7800   /* loop over the streams. We might exit the loop early when we could do an
7801    * aggregate control */
7802   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7803     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7804     GstRTSPConnInfo *conninfo;
7805     const gchar *setup_url;
7806
7807     /* try aggregate control first but do non-aggregate control otherwise */
7808     if (control)
7809       setup_url = control;
7810     else if ((setup_url = stream->conninfo.location) == NULL)
7811       continue;
7812
7813     if (src->conninfo.connection) {
7814       conninfo = &src->conninfo;
7815     } else if (stream->conninfo.connection) {
7816       conninfo = &stream->conninfo;
7817     } else {
7818       continue;
7819     }
7820
7821     if (async)
7822       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7823           ("Sending PAUSE request"));
7824
7825     if ((res =
7826             gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
7827                 setup_url)) < 0)
7828       goto create_request_failed;
7829
7830     if ((res =
7831             gst_rtspsrc_send (src, conninfo, &request, &response, NULL,
7832                 NULL)) < 0)
7833       goto send_error;
7834
7835     gst_rtsp_message_unset (&request);
7836     gst_rtsp_message_unset (&response);
7837
7838     /* exit early when we did agregate control */
7839     if (control)
7840       break;
7841   }
7842
7843   /* change element states now */
7844   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7845
7846 no_connection:
7847   src->state = GST_RTSP_STATE_READY;
7848
7849 done:
7850   if (async)
7851     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7852
7853   return res;
7854
7855   /* ERRORS */
7856 open_failed:
7857   {
7858     GST_DEBUG_OBJECT (src, "failed to open stream");
7859     goto done;
7860   }
7861 not_supported:
7862   {
7863     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7864     goto done;
7865   }
7866 was_paused:
7867   {
7868     GST_DEBUG_OBJECT (src, "we were already PAUSED");
7869     goto done;
7870   }
7871 create_request_failed:
7872   {
7873     gchar *str = gst_rtsp_strresult (res);
7874
7875     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7876         ("Could not create request. (%s)", str));
7877     g_free (str);
7878     goto done;
7879   }
7880 send_error:
7881   {
7882     gchar *str = gst_rtsp_strresult (res);
7883
7884     gst_rtsp_message_unset (&request);
7885     if (res != GST_RTSP_EINTR) {
7886       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7887           ("Could not send message. (%s)", str));
7888     } else {
7889       GST_WARNING_OBJECT (src, "PAUSE interrupted");
7890     }
7891     g_free (str);
7892     goto done;
7893   }
7894 }
7895
7896 static void
7897 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
7898 {
7899   GstRTSPSrc *rtspsrc;
7900
7901   rtspsrc = GST_RTSPSRC (bin);
7902
7903   switch (GST_MESSAGE_TYPE (message)) {
7904     case GST_MESSAGE_EOS:
7905       gst_message_unref (message);
7906       break;
7907     case GST_MESSAGE_ELEMENT:
7908     {
7909       const GstStructure *s = gst_message_get_structure (message);
7910
7911       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
7912         gboolean ignore_timeout;
7913
7914         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
7915
7916         GST_OBJECT_LOCK (rtspsrc);
7917         ignore_timeout = rtspsrc->ignore_timeout;
7918         rtspsrc->ignore_timeout = TRUE;
7919         GST_OBJECT_UNLOCK (rtspsrc);
7920
7921         /* we only act on the first udp timeout message, others are irrelevant
7922          * and can be ignored. */
7923         if (!ignore_timeout)
7924           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
7925         /* eat and free */
7926         gst_message_unref (message);
7927         return;
7928       }
7929       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7930       break;
7931     }
7932     case GST_MESSAGE_ERROR:
7933     {
7934       GstObject *udpsrc;
7935       GstRTSPStream *stream;
7936       GstFlowReturn ret;
7937
7938       udpsrc = GST_MESSAGE_SRC (message);
7939
7940       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
7941           GST_ELEMENT_NAME (udpsrc));
7942
7943       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
7944       if (!stream)
7945         goto forward;
7946
7947       /* we ignore the RTCP udpsrc */
7948       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
7949         goto done;
7950
7951       /* if we get error messages from the udp sources, that's not a problem as
7952        * long as not all of them error out. We also don't really know what the
7953        * problem is, the message does not give enough detail... */
7954       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
7955       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7956       if (ret != GST_FLOW_OK)
7957         goto forward;
7958
7959     done:
7960       gst_message_unref (message);
7961       break;
7962
7963     forward:
7964       /* fatal but not our message, forward */
7965       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7966       break;
7967     }
7968     default:
7969     {
7970       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7971       break;
7972     }
7973   }
7974 }
7975
7976 /* the thread where everything happens */
7977 static void
7978 gst_rtspsrc_thread (GstRTSPSrc * src)
7979 {
7980   gint cmd;
7981
7982   GST_OBJECT_LOCK (src);
7983   cmd = src->pending_cmd;
7984   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7985       || cmd == CMD_LOOP || cmd == CMD_OPEN)
7986     src->pending_cmd = CMD_LOOP;
7987   else
7988     src->pending_cmd = CMD_WAIT;
7989   GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
7990
7991   /* we got the message command, so ensure communication is possible again */
7992   gst_rtspsrc_connection_flush (src, FALSE);
7993
7994   src->busy_cmd = cmd;
7995   GST_OBJECT_UNLOCK (src);
7996
7997   switch (cmd) {
7998     case CMD_OPEN:
7999       gst_rtspsrc_open (src, TRUE);
8000       break;
8001     case CMD_PLAY:
8002       gst_rtspsrc_play (src, &src->segment, TRUE, NULL);
8003       break;
8004     case CMD_PAUSE:
8005       gst_rtspsrc_pause (src, TRUE);
8006       break;
8007     case CMD_CLOSE:
8008       gst_rtspsrc_close (src, TRUE, FALSE);
8009       break;
8010     case CMD_LOOP:
8011       gst_rtspsrc_loop (src);
8012       break;
8013     case CMD_RECONNECT:
8014       gst_rtspsrc_reconnect (src, FALSE);
8015       break;
8016     default:
8017       break;
8018   }
8019
8020   GST_OBJECT_LOCK (src);
8021   /* and go back to sleep */
8022   if (src->pending_cmd == CMD_WAIT) {
8023     if (src->task)
8024       gst_task_pause (src->task);
8025   }
8026   /* reset waiting */
8027   src->busy_cmd = CMD_WAIT;
8028   GST_OBJECT_UNLOCK (src);
8029 }
8030
8031 static gboolean
8032 gst_rtspsrc_start (GstRTSPSrc * src)
8033 {
8034   GST_DEBUG_OBJECT (src, "starting");
8035
8036   GST_OBJECT_LOCK (src);
8037
8038   src->pending_cmd = CMD_WAIT;
8039
8040   if (src->task == NULL) {
8041     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
8042     if (src->task == NULL)
8043       goto task_error;
8044
8045     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
8046   }
8047   GST_OBJECT_UNLOCK (src);
8048
8049   return TRUE;
8050
8051   /* ERRORS */
8052 task_error:
8053   {
8054     GST_OBJECT_UNLOCK (src);
8055     GST_ERROR_OBJECT (src, "failed to create task");
8056     return FALSE;
8057   }
8058 }
8059
8060 static gboolean
8061 gst_rtspsrc_stop (GstRTSPSrc * src)
8062 {
8063   GstTask *task;
8064
8065   GST_DEBUG_OBJECT (src, "stopping");
8066
8067   /* also cancels pending task */
8068   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
8069
8070   GST_OBJECT_LOCK (src);
8071   if ((task = src->task)) {
8072     src->task = NULL;
8073     GST_OBJECT_UNLOCK (src);
8074
8075     gst_task_stop (task);
8076
8077     /* make sure it is not running */
8078     GST_RTSP_STREAM_LOCK (src);
8079     GST_RTSP_STREAM_UNLOCK (src);
8080
8081     /* now wait for the task to finish */
8082     gst_task_join (task);
8083
8084     /* and free the task */
8085     gst_object_unref (GST_OBJECT (task));
8086
8087     GST_OBJECT_LOCK (src);
8088   }
8089   GST_OBJECT_UNLOCK (src);
8090
8091   /* ensure synchronously all is closed and clean */
8092   gst_rtspsrc_close (src, FALSE, TRUE);
8093
8094   return TRUE;
8095 }
8096
8097 static GstStateChangeReturn
8098 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
8099 {
8100   GstRTSPSrc *rtspsrc;
8101   GstStateChangeReturn ret;
8102
8103   rtspsrc = GST_RTSPSRC (element);
8104
8105   switch (transition) {
8106     case GST_STATE_CHANGE_NULL_TO_READY:
8107       if (!gst_rtspsrc_start (rtspsrc))
8108         goto start_failed;
8109       break;
8110     case GST_STATE_CHANGE_READY_TO_PAUSED:
8111       /* init some state */
8112       rtspsrc->cur_protocols = rtspsrc->protocols;
8113       /* first attempt, don't ignore timeouts */
8114       rtspsrc->ignore_timeout = FALSE;
8115       rtspsrc->open_error = FALSE;
8116       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
8117       break;
8118     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8119       set_manager_buffer_mode (rtspsrc);
8120       /* fall-through */
8121     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8122       /* unblock the tcp tasks and make the loop waiting */
8123       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
8124         /* make sure it is waiting before we send PAUSE or PLAY below */
8125         GST_RTSP_STREAM_LOCK (rtspsrc);
8126         GST_RTSP_STREAM_UNLOCK (rtspsrc);
8127       }
8128       break;
8129     case GST_STATE_CHANGE_PAUSED_TO_READY:
8130       break;
8131     default:
8132       break;
8133   }
8134
8135   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
8136   if (ret == GST_STATE_CHANGE_FAILURE)
8137     goto done;
8138
8139   switch (transition) {
8140     case GST_STATE_CHANGE_NULL_TO_READY:
8141       ret = GST_STATE_CHANGE_SUCCESS;
8142       break;
8143     case GST_STATE_CHANGE_READY_TO_PAUSED:
8144       ret = GST_STATE_CHANGE_NO_PREROLL;
8145       break;
8146     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8147       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
8148       ret = GST_STATE_CHANGE_SUCCESS;
8149       break;
8150     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8151       /* send pause request and keep the idle task around */
8152       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
8153       ret = GST_STATE_CHANGE_NO_PREROLL;
8154       break;
8155     case GST_STATE_CHANGE_PAUSED_TO_READY:
8156       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_ALL);
8157       ret = GST_STATE_CHANGE_SUCCESS;
8158       break;
8159     case GST_STATE_CHANGE_READY_TO_NULL:
8160       gst_rtspsrc_stop (rtspsrc);
8161       ret = GST_STATE_CHANGE_SUCCESS;
8162       break;
8163     default:
8164       /* Otherwise it's success, we don't want to return spurious
8165        * NO_PREROLL or ASYNC from internal elements as we care for
8166        * state changes ourselves here
8167        *
8168        * This is to catch PAUSED->PAUSED and PLAYING->PLAYING transitions.
8169        */
8170       if (GST_STATE_TRANSITION_NEXT (transition) == GST_STATE_PAUSED)
8171         ret = GST_STATE_CHANGE_NO_PREROLL;
8172       else
8173         ret = GST_STATE_CHANGE_SUCCESS;
8174       break;
8175   }
8176
8177 done:
8178   return ret;
8179
8180 start_failed:
8181   {
8182     GST_DEBUG_OBJECT (rtspsrc, "start failed");
8183     return GST_STATE_CHANGE_FAILURE;
8184   }
8185 }
8186
8187 static gboolean
8188 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
8189 {
8190   gboolean res;
8191   GstRTSPSrc *rtspsrc;
8192
8193   rtspsrc = GST_RTSPSRC (element);
8194
8195   if (GST_EVENT_IS_DOWNSTREAM (event)) {
8196     res = gst_rtspsrc_push_event (rtspsrc, event);
8197   } else {
8198     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
8199   }
8200
8201   return res;
8202 }
8203
8204
8205 /*** GSTURIHANDLER INTERFACE *************************************************/
8206
8207 static GstURIType
8208 gst_rtspsrc_uri_get_type (GType type)
8209 {
8210   return GST_URI_SRC;
8211 }
8212
8213 static const gchar *const *
8214 gst_rtspsrc_uri_get_protocols (GType type)
8215 {
8216   static const gchar *protocols[] =
8217       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
8218     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
8219   };
8220
8221   return protocols;
8222 }
8223
8224 static gchar *
8225 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
8226 {
8227   GstRTSPSrc *src = GST_RTSPSRC (handler);
8228
8229   /* FIXME: make thread-safe */
8230   return g_strdup (src->conninfo.location);
8231 }
8232
8233 static gboolean
8234 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
8235     GError ** error)
8236 {
8237   GstRTSPSrc *src;
8238   GstRTSPResult res;
8239   GstSDPResult sres;
8240   GstRTSPUrl *newurl = NULL;
8241   GstSDPMessage *sdp = NULL;
8242
8243   src = GST_RTSPSRC (handler);
8244
8245   /* same URI, we're fine */
8246   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
8247     goto was_ok;
8248
8249   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
8250     sres = gst_sdp_message_new (&sdp);
8251     if (sres < 0)
8252       goto sdp_failed;
8253
8254     GST_DEBUG_OBJECT (src, "parsing SDP message");
8255     sres = gst_sdp_message_parse_uri (uri, sdp);
8256     if (sres < 0)
8257       goto invalid_sdp;
8258   } else {
8259     /* try to parse */
8260     GST_DEBUG_OBJECT (src, "parsing URI");
8261     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
8262       goto parse_error;
8263   }
8264
8265   /* if worked, free previous and store new url object along with the original
8266    * location. */
8267   GST_DEBUG_OBJECT (src, "configuring URI");
8268   g_free (src->conninfo.location);
8269   src->conninfo.location = g_strdup (uri);
8270   gst_rtsp_url_free (src->conninfo.url);
8271   src->conninfo.url = newurl;
8272   g_free (src->conninfo.url_str);
8273   if (newurl)
8274     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
8275   else
8276     src->conninfo.url_str = NULL;
8277
8278   if (src->sdp)
8279     gst_sdp_message_free (src->sdp);
8280   src->sdp = sdp;
8281   src->from_sdp = sdp != NULL;
8282
8283   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
8284   GST_DEBUG_OBJECT (src, "request uri is: %s",
8285       GST_STR_NULL (src->conninfo.url_str));
8286
8287   return TRUE;
8288
8289   /* Special cases */
8290 was_ok:
8291   {
8292     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
8293     return TRUE;
8294   }
8295 sdp_failed:
8296   {
8297     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
8298     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8299         "Could not create SDP");
8300     return FALSE;
8301   }
8302 invalid_sdp:
8303   {
8304     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
8305         GST_STR_NULL (uri));
8306     gst_sdp_message_free (sdp);
8307     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8308         "Invalid SDP");
8309     return FALSE;
8310   }
8311 parse_error:
8312   {
8313     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
8314         GST_STR_NULL (uri), res);
8315     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8316         "Invalid RTSP URI");
8317     return FALSE;
8318   }
8319 }
8320
8321 static void
8322 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
8323 {
8324   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
8325
8326   iface->get_type = gst_rtspsrc_uri_get_type;
8327   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
8328   iface->get_uri = gst_rtspsrc_uri_get_uri;
8329   iface->set_uri = gst_rtspsrc_uri_set_uri;
8330 }