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