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