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