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