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