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