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