rtspsrc: Seek handling is always done with a valid event
[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    * GstRTSPSrc: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    * GstRTSPSrc: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    * Emitted 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    * Emitted 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    * Emitted 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 emitted 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, "sendonly") != NULL &&
1776       /* We want to setup caps for streams configured as backchannel */
1777       !stream->is_backchannel && src->backchannel != BACKCHANNEL_NONE)
1778     goto sendonly_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 sendonly_media:
1850   {
1851     GST_DEBUG_OBJECT (src, "sendonly 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 sendonly and onvif backchannel is requested */
1917   if (gst_sdp_media_get_attribute_val (media, "sendonly") != 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   GST_DEBUG_OBJECT (src, "doing seek with event %" GST_PTR_FORMAT, event);
2404
2405   gst_event_parse_seek (event, &rate, &format, &flags,
2406       &cur_type, &cur, &stop_type, &stop);
2407
2408   /* no negative rates yet */
2409   if (rate < 0.0)
2410     goto negative_rate;
2411
2412   /* we need TIME format */
2413   if (format != src->segment.format)
2414     goto no_format;
2415
2416   /* Check if we are not at all seekable */
2417   if (src->seekable == -1.0)
2418     goto not_seekable;
2419
2420   /* Additional seeking-to-beginning-only check */
2421   if (src->seekable == 0.0 && cur != 0)
2422     goto not_seekable;
2423
2424   if (flags & GST_SEEK_FLAG_SEGMENT)
2425     goto invalid_segment_flag;
2426
2427   /* get flush flag */
2428   flush = flags & GST_SEEK_FLAG_FLUSH;
2429   skip = flags & GST_SEEK_FLAG_SKIP;
2430
2431   /* now we need to make sure the streaming thread is stopped. We do this by
2432    * either sending a FLUSH_START event downstream which will cause the
2433    * streaming thread to stop with a WRONG_STATE.
2434    * For a non-flushing seek we simply pause the task, which will happen as soon
2435    * as it completes one iteration (and thus might block when the sink is
2436    * blocking in preroll). */
2437   if (flush) {
2438     GST_DEBUG_OBJECT (src, "starting flush");
2439     gst_rtspsrc_flush (src, TRUE, FALSE);
2440   } else {
2441     if (src->task) {
2442       gst_task_pause (src->task);
2443     }
2444   }
2445
2446   /* we should now be able to grab the streaming thread because we stopped it
2447    * with the above flush/pause code */
2448   GST_RTSP_STREAM_LOCK (src);
2449
2450   GST_DEBUG_OBJECT (src, "stopped streaming");
2451
2452   /* stop flushing the rtsp connection so we can send PAUSE/PLAY below */
2453   gst_rtspsrc_connection_flush (src, FALSE);
2454
2455   /* copy segment, we need this because we still need the old
2456    * segment when we close the current segment. */
2457   memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2458
2459   /* configure the seek parameters in the seeksegment. We will then have the
2460    * right values in the segment to perform the seek */
2461   GST_DEBUG_OBJECT (src, "configuring seek");
2462   gst_segment_do_seek (&seeksegment, rate, format, flags,
2463       cur_type, cur, stop_type, stop, &update);
2464
2465   /* figure out the last position we need to play. If it's configured (stop !=
2466    * -1), use that, else we play until the total duration of the file */
2467   if ((stop = seeksegment.stop) == -1)
2468     stop = seeksegment.duration;
2469
2470   /* if we were playing, pause first */
2471   playing = (src->state == GST_RTSP_STATE_PLAYING);
2472   if (playing) {
2473     /* obtain current position in case seek fails */
2474     gst_rtspsrc_get_position (src);
2475     gst_rtspsrc_pause (src, FALSE);
2476   }
2477   src->skip = skip;
2478
2479   src->state = GST_RTSP_STATE_SEEKING;
2480
2481   /* PLAY will add the range header now. */
2482   src->need_range = TRUE;
2483
2484   /* prepare for streaming again */
2485   if (flush) {
2486     /* if we started flush, we stop now */
2487     GST_DEBUG_OBJECT (src, "stopping flush");
2488     gst_rtspsrc_flush (src, FALSE, playing);
2489   }
2490
2491   /* now we did the seek and can activate the new segment values */
2492   memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2493
2494   /* if we're doing a segment seek, post a SEGMENT_START message */
2495   if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2496     gst_element_post_message (GST_ELEMENT_CAST (src),
2497         gst_message_new_segment_start (GST_OBJECT_CAST (src),
2498             src->segment.format, src->segment.position));
2499   }
2500
2501   /* now create the newsegment */
2502   GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2503       " to %" G_GINT64_FORMAT, src->segment.position, stop);
2504
2505   /* mark discont */
2506   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2507   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2508     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2509     stream->discont = TRUE;
2510   }
2511
2512   /* and continue playing if needed */
2513   GST_OBJECT_LOCK (src);
2514   playing = (GST_STATE_PENDING (src) == GST_STATE_VOID_PENDING
2515       && GST_STATE (src) == GST_STATE_PLAYING)
2516       || (GST_STATE_PENDING (src) == GST_STATE_PLAYING);
2517   GST_OBJECT_UNLOCK (src);
2518
2519   if (src->version >= GST_RTSP_VERSION_2_0) {
2520     if (flags & GST_SEEK_FLAG_ACCURATE)
2521       seek_style = "RAP";
2522     else if (flags & GST_SEEK_FLAG_KEY_UNIT)
2523       seek_style = "CoRAP";
2524     else if (flags & GST_SEEK_FLAG_KEY_UNIT
2525         && flags & GST_SEEK_FLAG_SNAP_BEFORE)
2526       seek_style = "First-Prior";
2527     else if (flags & GST_SEEK_FLAG_KEY_UNIT && flags & GST_SEEK_FLAG_SNAP_AFTER)
2528       seek_style = "Next";
2529   }
2530
2531   if (playing)
2532     gst_rtspsrc_play (src, &seeksegment, FALSE, seek_style);
2533
2534   GST_RTSP_STREAM_UNLOCK (src);
2535
2536   return TRUE;
2537
2538   /* ERRORS */
2539 negative_rate:
2540   {
2541     GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2542     return FALSE;
2543   }
2544 no_format:
2545   {
2546     GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2547     return FALSE;
2548   }
2549 not_seekable:
2550   {
2551     GST_DEBUG_OBJECT (src, "stream is not seekable");
2552     return FALSE;
2553   }
2554 invalid_segment_flag:
2555   {
2556     GST_WARNING_OBJECT (src, "Segment seeks not supported");
2557     return FALSE;
2558   }
2559 }
2560
2561 static gboolean
2562 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2563     GstEvent * event)
2564 {
2565   GstRTSPSrc *src;
2566   gboolean res = TRUE;
2567   gboolean forward;
2568
2569   src = GST_RTSPSRC_CAST (parent);
2570
2571   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2572       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2573
2574   switch (GST_EVENT_TYPE (event)) {
2575     case GST_EVENT_SEEK:
2576       res = gst_rtspsrc_perform_seek (src, event);
2577       forward = FALSE;
2578       break;
2579     case GST_EVENT_QOS:
2580     case GST_EVENT_NAVIGATION:
2581     case GST_EVENT_LATENCY:
2582     default:
2583       forward = TRUE;
2584       break;
2585   }
2586   if (forward) {
2587     GstPad *target;
2588
2589     if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2590       res = gst_pad_send_event (target, event);
2591       gst_object_unref (target);
2592     } else {
2593       gst_event_unref (event);
2594     }
2595   } else {
2596     gst_event_unref (event);
2597   }
2598
2599   return res;
2600 }
2601
2602 static gboolean
2603 gst_rtspsrc_handle_src_sink_event (GstPad * pad, GstObject * parent,
2604     GstEvent * event)
2605 {
2606   GstRTSPStream *stream;
2607
2608   stream = gst_pad_get_element_private (pad);
2609
2610   switch (GST_EVENT_TYPE (event)) {
2611     case GST_EVENT_STREAM_START:{
2612       const gchar *upstream_id;
2613       gchar *stream_id;
2614
2615       gst_event_parse_stream_start (event, &upstream_id);
2616       stream_id = g_strdup_printf ("%s/%s", upstream_id, stream->stream_id);
2617
2618       gst_event_unref (event);
2619       event = gst_event_new_stream_start (stream_id);
2620       g_free (stream_id);
2621       break;
2622     }
2623     default:
2624       break;
2625   }
2626
2627   return gst_pad_push_event (stream->srcpad, event);
2628 }
2629
2630 /* this is the final event function we receive on the internal source pad when
2631  * we deal with TCP connections */
2632 static gboolean
2633 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2634     GstEvent * event)
2635 {
2636   gboolean res;
2637
2638   GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2639
2640   switch (GST_EVENT_TYPE (event)) {
2641     case GST_EVENT_SEEK:
2642     case GST_EVENT_QOS:
2643     case GST_EVENT_NAVIGATION:
2644     case GST_EVENT_LATENCY:
2645     default:
2646       gst_event_unref (event);
2647       res = TRUE;
2648       break;
2649   }
2650   return res;
2651 }
2652
2653 /* this is the final query function we receive on the internal source pad when
2654  * we deal with TCP connections */
2655 static gboolean
2656 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2657     GstQuery * query)
2658 {
2659   GstRTSPSrc *src;
2660   gboolean res = TRUE;
2661
2662   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2663
2664   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2665       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2666
2667   switch (GST_QUERY_TYPE (query)) {
2668     case GST_QUERY_POSITION:
2669     {
2670       /* no idea */
2671       break;
2672     }
2673     case GST_QUERY_DURATION:
2674     {
2675       GstFormat format;
2676
2677       gst_query_parse_duration (query, &format, NULL);
2678
2679       switch (format) {
2680         case GST_FORMAT_TIME:
2681           gst_query_set_duration (query, format, src->segment.duration);
2682           break;
2683         default:
2684           res = FALSE;
2685           break;
2686       }
2687       break;
2688     }
2689     case GST_QUERY_LATENCY:
2690     {
2691       /* we are live with a min latency of 0 and unlimited max latency, this
2692        * result will be updated by the session manager if there is any. */
2693       gst_query_set_latency (query, TRUE, 0, -1);
2694       break;
2695     }
2696     default:
2697       break;
2698   }
2699
2700   return res;
2701 }
2702
2703 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2704 static gboolean
2705 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2706     GstQuery * query)
2707 {
2708   GstRTSPSrc *src;
2709   gboolean res = FALSE;
2710
2711   src = GST_RTSPSRC_CAST (parent);
2712
2713   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2714       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2715
2716   switch (GST_QUERY_TYPE (query)) {
2717     case GST_QUERY_DURATION:
2718     {
2719       GstFormat format;
2720
2721       gst_query_parse_duration (query, &format, NULL);
2722
2723       switch (format) {
2724         case GST_FORMAT_TIME:
2725           gst_query_set_duration (query, format, src->segment.duration);
2726           res = TRUE;
2727           break;
2728         default:
2729           break;
2730       }
2731       break;
2732     }
2733     case GST_QUERY_SEEKING:
2734     {
2735       GstFormat format;
2736
2737       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2738       if (format == GST_FORMAT_TIME) {
2739         gboolean seekable =
2740             src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2741         GstClockTime start = 0, duration = src->segment.duration;
2742
2743         /* seeking without duration is unlikely */
2744         seekable = seekable && src->seekable >= 0.0 && src->segment.duration &&
2745             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2746
2747         if (seekable) {
2748           if (src->seekable > 0.0) {
2749             start = src->last_pos - src->seekable * GST_SECOND;
2750           } else {
2751             /* src->seekable == 0 means that we can only seek to 0 */
2752             start = 0;
2753             duration = 0;
2754           }
2755         }
2756
2757         GST_LOG_OBJECT (src, "seekable : %d", seekable);
2758
2759         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, start,
2760             duration);
2761         res = TRUE;
2762       }
2763       break;
2764     }
2765     case GST_QUERY_URI:
2766     {
2767       gchar *uri;
2768
2769       uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2770       if (uri != NULL) {
2771         gst_query_set_uri (query, uri);
2772         g_free (uri);
2773         res = TRUE;
2774       }
2775       break;
2776     }
2777     default:
2778     {
2779       GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2780
2781       /* forward the query to the proxy target pad */
2782       if (target) {
2783         res = gst_pad_query (target, query);
2784         gst_object_unref (target);
2785       }
2786       break;
2787     }
2788   }
2789
2790   return res;
2791 }
2792
2793 /* callback for RTCP messages to be sent to the server when operating in TCP
2794  * mode. */
2795 static GstFlowReturn
2796 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2797 {
2798   GstRTSPSrc *src;
2799   GstRTSPStream *stream;
2800   GstFlowReturn res = GST_FLOW_OK;
2801   GstMapInfo map;
2802   guint8 *data;
2803   guint size;
2804   GstRTSPResult ret;
2805   GstRTSPMessage message = { 0 };
2806   GstRTSPConnInfo *conninfo;
2807
2808   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2809   src = stream->parent;
2810
2811   gst_buffer_map (buffer, &map, GST_MAP_READ);
2812   size = map.size;
2813   data = map.data;
2814
2815   gst_rtsp_message_init_data (&message, stream->channel[1]);
2816
2817   /* lend the body data to the message */
2818   gst_rtsp_message_take_body (&message, data, size);
2819
2820   if (stream->conninfo.connection)
2821     conninfo = &stream->conninfo;
2822   else
2823     conninfo = &src->conninfo;
2824
2825   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2826   ret = gst_rtspsrc_connection_send (src, conninfo, &message, NULL);
2827   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2828
2829   /* and steal it away again because we will free it when unreffing the
2830    * buffer */
2831   gst_rtsp_message_steal_body (&message, &data, &size);
2832   gst_rtsp_message_unset (&message);
2833
2834   gst_buffer_unmap (buffer, &map);
2835   gst_buffer_unref (buffer);
2836
2837   return res;
2838 }
2839
2840 static GstFlowReturn
2841 gst_rtspsrc_push_backchannel_buffer (GstRTSPSrc * src, guint id,
2842     GstSample * sample)
2843 {
2844   GstFlowReturn res = GST_FLOW_OK;
2845   GstRTSPStream *stream;
2846
2847   if (!src->conninfo.connected || src->state != GST_RTSP_STATE_PLAYING)
2848     goto out;
2849
2850   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2851   if (stream == NULL) {
2852     GST_ERROR_OBJECT (src, "no stream with id %u", id);
2853     goto out;
2854   }
2855
2856   if (src->interleaved) {
2857     GstBuffer *buffer;
2858     GstMapInfo map;
2859     guint8 *data;
2860     guint size;
2861     GstRTSPResult ret;
2862     GstRTSPMessage message = { 0 };
2863     GstRTSPConnInfo *conninfo;
2864
2865     buffer = gst_sample_get_buffer (sample);
2866
2867     gst_buffer_map (buffer, &map, GST_MAP_READ);
2868     size = map.size;
2869     data = map.data;
2870
2871     gst_rtsp_message_init_data (&message, stream->channel[0]);
2872
2873     /* lend the body data to the message */
2874     gst_rtsp_message_take_body (&message, data, size);
2875
2876     if (stream->conninfo.connection)
2877       conninfo = &stream->conninfo;
2878     else
2879       conninfo = &src->conninfo;
2880
2881     GST_DEBUG_OBJECT (src, "sending %u bytes backchannel RTP", size);
2882     ret = gst_rtspsrc_connection_send (src, conninfo, &message, NULL);
2883     GST_DEBUG_OBJECT (src, "sent backchannel RTP, %d", ret);
2884
2885     /* and steal it away again because we will free it when unreffing the
2886      * buffer */
2887     gst_rtsp_message_steal_body (&message, &data, &size);
2888     gst_rtsp_message_unset (&message);
2889
2890     gst_buffer_unmap (buffer, &map);
2891
2892     res = GST_FLOW_OK;
2893   } else {
2894     g_signal_emit_by_name (stream->rtpsrc, "push-sample", sample, &res);
2895     GST_DEBUG_OBJECT (src, "sent backchannel RTP sample %p: %s", sample,
2896         gst_flow_get_name (res));
2897   }
2898
2899 out:
2900   gst_sample_unref (sample);
2901
2902   return res;
2903 }
2904
2905 static GstPadProbeReturn
2906 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2907 {
2908   GstRTSPSrc *src = user_data;
2909
2910   GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2911       GST_DEBUG_PAD_NAME (pad));
2912
2913   /* activate the streams */
2914   GST_OBJECT_LOCK (src);
2915   if (!src->need_activate)
2916     goto was_ok;
2917
2918   src->need_activate = FALSE;
2919   GST_OBJECT_UNLOCK (src);
2920
2921   gst_rtspsrc_activate_streams (src);
2922
2923   return GST_PAD_PROBE_OK;
2924
2925 was_ok:
2926   {
2927     GST_OBJECT_UNLOCK (src);
2928     return GST_PAD_PROBE_OK;
2929   }
2930 }
2931
2932 static gboolean
2933 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
2934 {
2935   GstPad *gpad = GST_PAD_CAST (user_data);
2936
2937   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
2938   gst_pad_store_sticky_event (gpad, *event);
2939
2940   return TRUE;
2941 }
2942
2943 static gboolean
2944 add_backchannel_fakesink (GstRTSPSrc * src, GstRTSPStream * stream,
2945     GstPad * srcpad)
2946 {
2947   GstPad *sinkpad;
2948   GstElement *fakesink;
2949
2950   fakesink = gst_element_factory_make ("fakesink", NULL);
2951   if (fakesink == NULL) {
2952     GST_ERROR_OBJECT (src, "no fakesink");
2953     return FALSE;
2954   }
2955
2956   sinkpad = gst_element_get_static_pad (fakesink, "sink");
2957
2958   GST_DEBUG_OBJECT (src, "backchannel stream %p, hooking fakesink", stream);
2959
2960   gst_bin_add (GST_BIN_CAST (src), fakesink);
2961   if (gst_pad_link (srcpad, sinkpad) != GST_PAD_LINK_OK) {
2962     GST_WARNING_OBJECT (src, "could not link to fakesink");
2963     return FALSE;
2964   }
2965
2966   gst_object_unref (sinkpad);
2967
2968   gst_element_sync_state_with_parent (fakesink);
2969   return TRUE;
2970 }
2971
2972 /* this callback is called when the session manager generated a new src pad with
2973  * payloaded RTP packets. We simply ghost the pad here. */
2974 static void
2975 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2976 {
2977   gchar *name;
2978   GstPadTemplate *template;
2979   gint id, ssrc, pt;
2980   GList *ostreams;
2981   GstRTSPStream *stream;
2982   gboolean all_added;
2983   GstPad *internal_src;
2984
2985   GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2986
2987   GST_RTSP_STATE_LOCK (src);
2988   /* find stream */
2989   name = gst_object_get_name (GST_OBJECT_CAST (pad));
2990   if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2991     goto unknown_stream;
2992
2993   GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2994
2995   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2996   if (stream == NULL)
2997     goto unknown_stream;
2998
2999   /* save SSRC */
3000   stream->ssrc = ssrc;
3001
3002   /* we'll add it later see below */
3003   stream->added = TRUE;
3004
3005   /* check if we added all streams */
3006   all_added = TRUE;
3007   for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
3008     GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
3009
3010     GST_DEBUG_OBJECT (src, "stream %p, container %d, added %d, setup %d",
3011         ostream, ostream->container, ostream->added, ostream->setup);
3012
3013     /* if we find a stream for which we did a setup that is not added, we
3014      * need to wait some more */
3015     if (ostream->setup && !ostream->added) {
3016       all_added = FALSE;
3017       break;
3018     }
3019   }
3020   GST_RTSP_STATE_UNLOCK (src);
3021
3022   /* create a new pad we will use to stream to */
3023   template = gst_static_pad_template_get (&rtptemplate);
3024   stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
3025   gst_object_unref (template);
3026   g_free (name);
3027
3028   /* We intercept and modify the stream start event */
3029   internal_src =
3030       GST_PAD (gst_proxy_pad_get_internal (GST_PROXY_PAD (stream->srcpad)));
3031   gst_pad_set_element_private (internal_src, stream);
3032   gst_pad_set_event_function (internal_src, gst_rtspsrc_handle_src_sink_event);
3033   gst_object_unref (internal_src);
3034
3035   gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3036   gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3037   gst_pad_set_active (stream->srcpad, TRUE);
3038   gst_pad_sticky_events_foreach (pad, copy_sticky_events, stream->srcpad);
3039
3040   /* don't add the srcpad if this is a sendonly stream */
3041   if (stream->is_backchannel)
3042     add_backchannel_fakesink (src, stream, stream->srcpad);
3043   else
3044     gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3045
3046   if (all_added) {
3047     GST_DEBUG_OBJECT (src, "We added all streams");
3048     /* when we get here, all stream are added and we can fire the no-more-pads
3049      * signal. */
3050     gst_element_no_more_pads (GST_ELEMENT_CAST (src));
3051   }
3052
3053   return;
3054
3055   /* ERRORS */
3056 unknown_stream:
3057   {
3058     GST_DEBUG_OBJECT (src, "ignoring unknown stream");
3059     GST_RTSP_STATE_UNLOCK (src);
3060     g_free (name);
3061     return;
3062   }
3063 }
3064
3065 static GstCaps *
3066 stream_get_caps_for_pt (GstRTSPStream * stream, guint pt)
3067 {
3068   guint i, len;
3069
3070   len = stream->ptmap->len;
3071   for (i = 0; i < len; i++) {
3072     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3073     if (item->pt == pt)
3074       return item->caps;
3075   }
3076   return NULL;
3077 }
3078
3079 static GstCaps *
3080 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
3081 {
3082   GstRTSPStream *stream;
3083   GstCaps *caps;
3084
3085   GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
3086
3087   GST_RTSP_STATE_LOCK (src);
3088   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
3089   if (!stream)
3090     goto unknown_stream;
3091
3092   if ((caps = stream_get_caps_for_pt (stream, pt)))
3093     gst_caps_ref (caps);
3094   GST_RTSP_STATE_UNLOCK (src);
3095
3096   return caps;
3097
3098 unknown_stream:
3099   {
3100     GST_DEBUG_OBJECT (src, "unknown stream %d", session);
3101     GST_RTSP_STATE_UNLOCK (src);
3102     return NULL;
3103   }
3104 }
3105
3106 static void
3107 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
3108 {
3109   GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
3110
3111   if (stream->eos)
3112     goto was_eos;
3113
3114   stream->eos = TRUE;
3115   gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
3116   return;
3117
3118   /* ERRORS */
3119 was_eos:
3120   {
3121     GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
3122     return;
3123   }
3124 }
3125
3126 static void
3127 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
3128 {
3129   GstRTSPSrc *src = stream->parent;
3130   guint ssrc;
3131
3132   g_object_get (source, "ssrc", &ssrc, NULL);
3133
3134   GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
3135       ssrc, stream->ssrc, stream->id);
3136
3137   if (ssrc == stream->ssrc)
3138     gst_rtspsrc_do_stream_eos (src, stream);
3139 }
3140
3141 static void
3142 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
3143 {
3144   GstRTSPSrc *src = stream->parent;
3145   guint ssrc;
3146
3147   g_object_get (source, "ssrc", &ssrc, NULL);
3148
3149   GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
3150       ssrc, stream->ssrc, stream->id);
3151
3152   if (ssrc == stream->ssrc)
3153     gst_rtspsrc_do_stream_eos (src, stream);
3154 }
3155
3156 static void
3157 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
3158 {
3159   GstRTSPStream *stream;
3160
3161   GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
3162
3163   /* get stream for session */
3164   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
3165   if (stream) {
3166     gst_rtspsrc_do_stream_eos (src, stream);
3167   }
3168 }
3169
3170 static void
3171 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
3172 {
3173   GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
3174       stream->id);
3175 }
3176
3177 static void
3178 set_manager_buffer_mode (GstRTSPSrc * src)
3179 {
3180   GObjectClass *klass;
3181
3182   if (src->manager == NULL)
3183     return;
3184
3185   klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3186
3187   if (!g_object_class_find_property (klass, "buffer-mode"))
3188     return;
3189
3190   if (src->buffer_mode != BUFFER_MODE_AUTO) {
3191     g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
3192
3193     return;
3194   }
3195
3196   GST_DEBUG_OBJECT (src,
3197       "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
3198
3199   if (src->provided_clock) {
3200     GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
3201
3202     if (clock == src->provided_clock) {
3203       GST_DEBUG_OBJECT (src, "selected synced");
3204       g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
3205
3206       if (clock)
3207         gst_object_unref (clock);
3208
3209       return;
3210     }
3211
3212     /* Otherwise fall-through and use another buffer mode */
3213     if (clock)
3214       gst_object_unref (clock);
3215   }
3216
3217   GST_DEBUG_OBJECT (src, "auto buffering mode");
3218   if (src->use_buffering) {
3219     GST_DEBUG_OBJECT (src, "selected buffer");
3220     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
3221   } else {
3222     GST_DEBUG_OBJECT (src, "selected slave");
3223     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
3224   }
3225 }
3226
3227 static GstCaps *
3228 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
3229 {
3230   guint i;
3231   GstCaps *caps;
3232   GstMIKEYMessage *msg = stream->mikey;
3233
3234   GST_DEBUG ("request key SSRC %u", ssrc);
3235
3236   caps = gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
3237   caps = gst_caps_make_writable (caps);
3238
3239   /* parse crypto sessions and look for the SSRC rollover counter */
3240   msg = stream->mikey;
3241   for (i = 0; msg && i < gst_mikey_message_get_n_cs (msg); i++) {
3242     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
3243
3244     if (ssrc == map->ssrc) {
3245       gst_caps_set_simple (caps, "roc", G_TYPE_UINT, map->roc, NULL);
3246       break;
3247     }
3248   }
3249
3250   return caps;
3251 }
3252
3253 static GstElement *
3254 request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
3255 {
3256   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3257   if (stream->id != session)
3258     return NULL;
3259
3260   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3261       stream->profile != GST_RTSP_PROFILE_SAVPF)
3262     return NULL;
3263
3264   if (stream->srtpdec == NULL) {
3265     gchar *name;
3266
3267     name = g_strdup_printf ("srtpdec_%u", session);
3268     stream->srtpdec = gst_element_factory_make ("srtpdec", name);
3269     g_free (name);
3270
3271     if (stream->srtpdec == NULL) {
3272       GST_ELEMENT_ERROR (stream->parent, CORE, MISSING_PLUGIN, (NULL),
3273           ("no srtpdec element present!"));
3274       return NULL;
3275     }
3276     g_signal_connect (stream->srtpdec, "request-key",
3277         (GCallback) request_key, stream);
3278   }
3279   return gst_object_ref (stream->srtpdec);
3280 }
3281
3282 static GstElement *
3283 request_rtcp_encoder (GstElement * rtpbin, guint session,
3284     GstRTSPStream * stream)
3285 {
3286   gchar *name;
3287   GstPad *pad;
3288
3289   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
3290   if (stream->id != session)
3291     return NULL;
3292
3293   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
3294       stream->profile != GST_RTSP_PROFILE_SAVPF)
3295     return NULL;
3296
3297   if (stream->srtpenc == NULL) {
3298     GstStructure *s;
3299
3300     name = g_strdup_printf ("srtpenc_%u", session);
3301     stream->srtpenc = gst_element_factory_make ("srtpenc", name);
3302     g_free (name);
3303
3304     if (stream->srtpenc == NULL) {
3305       GST_ELEMENT_ERROR (stream->parent, CORE, MISSING_PLUGIN, (NULL),
3306           ("no srtpenc element present!"));
3307       return NULL;
3308     }
3309
3310     /* get RTCP crypto parameters from caps */
3311     s = gst_caps_get_structure (stream->srtcpparams, 0);
3312     if (s) {
3313       GstBuffer *buf;
3314       const gchar *str;
3315       GType ciphertype, authtype;
3316       GValue rtcp_cipher = G_VALUE_INIT, rtcp_auth = G_VALUE_INIT;
3317
3318       ciphertype = g_type_from_name ("GstSrtpCipherType");
3319       authtype = g_type_from_name ("GstSrtpAuthType");
3320       g_value_init (&rtcp_cipher, ciphertype);
3321       g_value_init (&rtcp_auth, authtype);
3322
3323       str = gst_structure_get_string (s, "srtcp-cipher");
3324       gst_value_deserialize (&rtcp_cipher, str);
3325       str = gst_structure_get_string (s, "srtcp-auth");
3326       gst_value_deserialize (&rtcp_auth, str);
3327       gst_structure_get (s, "srtp-key", GST_TYPE_BUFFER, &buf, NULL);
3328
3329       g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-cipher",
3330           &rtcp_cipher);
3331       g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-auth",
3332           &rtcp_auth);
3333       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-cipher",
3334           &rtcp_cipher);
3335       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-auth",
3336           &rtcp_auth);
3337       g_object_set (stream->srtpenc, "key", buf, NULL);
3338
3339       g_value_unset (&rtcp_cipher);
3340       g_value_unset (&rtcp_auth);
3341       gst_buffer_unref (buf);
3342     }
3343   }
3344   name = g_strdup_printf ("rtcp_sink_%d", session);
3345   pad = gst_element_get_request_pad (stream->srtpenc, name);
3346   g_free (name);
3347   gst_object_unref (pad);
3348
3349   return gst_object_ref (stream->srtpenc);
3350 }
3351
3352 static GstElement *
3353 request_aux_receiver (GstElement * rtpbin, guint sessid, GstRTSPSrc * src)
3354 {
3355   GstElement *rtx, *bin;
3356   GstPad *pad;
3357   gchar *name;
3358   GstRTSPStream *stream;
3359
3360   stream = find_stream (src, &sessid, (gpointer) find_stream_by_id);
3361   if (!stream) {
3362     GST_WARNING_OBJECT (src, "Stream %u not found", sessid);
3363     return NULL;
3364   }
3365
3366   GST_INFO_OBJECT (src, "creating retransmision receiver for session %u "
3367       "with map %" GST_PTR_FORMAT, sessid, stream->rtx_pt_map);
3368   bin = gst_bin_new (NULL);
3369   rtx = gst_element_factory_make ("rtprtxreceive", NULL);
3370   g_object_set (rtx, "payload-type-map", stream->rtx_pt_map, NULL);
3371   gst_bin_add (GST_BIN (bin), rtx);
3372
3373   pad = gst_element_get_static_pad (rtx, "src");
3374   name = g_strdup_printf ("src_%u", sessid);
3375   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3376   g_free (name);
3377   gst_object_unref (pad);
3378
3379   pad = gst_element_get_static_pad (rtx, "sink");
3380   name = g_strdup_printf ("sink_%u", sessid);
3381   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
3382   g_free (name);
3383   gst_object_unref (pad);
3384
3385   return bin;
3386 }
3387
3388 static void
3389 add_retransmission (GstRTSPSrc * src, GstRTSPTransport * transport)
3390 {
3391   GList *walk;
3392   guint signal_id;
3393   gboolean do_retransmission = FALSE;
3394
3395   if (transport->trans != GST_RTSP_TRANS_RTP)
3396     return;
3397   if (transport->profile != GST_RTSP_PROFILE_AVPF &&
3398       transport->profile != GST_RTSP_PROFILE_SAVPF)
3399     return;
3400
3401   signal_id = g_signal_lookup ("request-aux-receiver",
3402       G_OBJECT_TYPE (src->manager));
3403   /* there's already something connected */
3404   if (g_signal_handler_find (src->manager, G_SIGNAL_MATCH_ID, signal_id, 0,
3405           NULL, NULL, NULL) != 0) {
3406     GST_DEBUG_OBJECT (src, "Not adding RTX AUX element as "
3407         "\"request-aux-receiver\" signal is "
3408         "already used by the application");
3409     return;
3410   }
3411
3412   /* build the retransmission payload type map */
3413   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3414     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3415     gboolean do_retransmission_stream = FALSE;
3416     int i;
3417
3418     if (stream->rtx_pt_map)
3419       gst_structure_free (stream->rtx_pt_map);
3420     stream->rtx_pt_map = gst_structure_new_empty ("application/x-rtp-pt-map");
3421
3422     for (i = 0; i < stream->ptmap->len; i++) {
3423       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3424       GstStructure *s = gst_caps_get_structure (item->caps, 0);
3425       const gchar *encoding;
3426
3427       /* we only care about RTX streams */
3428       if ((encoding = gst_structure_get_string (s, "encoding-name"))
3429           && g_strcmp0 (encoding, "RTX") == 0) {
3430         const gchar *stream_pt_s;
3431         gint rtx_pt;
3432
3433         if (gst_structure_get_int (s, "payload", &rtx_pt)
3434             && (stream_pt_s = gst_structure_get_string (s, "apt"))) {
3435
3436           if (rtx_pt != 0) {
3437             gst_structure_set (stream->rtx_pt_map, stream_pt_s, G_TYPE_UINT,
3438                 rtx_pt, NULL);
3439             do_retransmission_stream = TRUE;
3440           }
3441         }
3442       }
3443     }
3444
3445     if (do_retransmission_stream) {
3446       GST_DEBUG_OBJECT (src, "built retransmission payload map for stream "
3447           "id %i: %" GST_PTR_FORMAT, stream->id, stream->rtx_pt_map);
3448       do_retransmission = TRUE;
3449     } else {
3450       GST_DEBUG_OBJECT (src, "no retransmission payload map for stream "
3451           "id %i", stream->id);
3452       gst_structure_free (stream->rtx_pt_map);
3453       stream->rtx_pt_map = NULL;
3454     }
3455   }
3456
3457   if (do_retransmission) {
3458     GST_DEBUG_OBJECT (src, "Enabling retransmissions");
3459
3460     g_object_set (src->manager, "do-retransmission", TRUE, NULL);
3461
3462     /* enable RFC4588 retransmission handling by setting rtprtxreceive
3463      * as the "aux" element of rtpbin */
3464     g_signal_connect (src->manager, "request-aux-receiver",
3465         (GCallback) request_aux_receiver, src);
3466   } else {
3467     GST_DEBUG_OBJECT (src,
3468         "Not enabling retransmissions as no stream had a retransmission payload map");
3469   }
3470 }
3471
3472 /* try to get and configure a manager */
3473 static gboolean
3474 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
3475     GstRTSPTransport * transport)
3476 {
3477   const gchar *manager;
3478   gchar *name;
3479   GstStateChangeReturn ret;
3480
3481   /* find a manager */
3482   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
3483     goto no_manager;
3484
3485   if (manager) {
3486     GST_DEBUG_OBJECT (src, "using manager %s", manager);
3487
3488     /* configure the manager */
3489     if (src->manager == NULL) {
3490       GObjectClass *klass;
3491
3492       if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
3493         /* fallback */
3494         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
3495           goto no_manager;
3496
3497         if (!manager)
3498           goto use_no_manager;
3499
3500         if (!(src->manager = gst_element_factory_make (manager, "manager")))
3501           goto manager_failed;
3502       }
3503
3504       /* we manage this element */
3505       gst_element_set_locked_state (src->manager, TRUE);
3506       gst_bin_add (GST_BIN_CAST (src), src->manager);
3507
3508       ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
3509       if (ret == GST_STATE_CHANGE_FAILURE)
3510         goto start_manager_failure;
3511
3512       g_object_set (src->manager, "latency", src->latency, NULL);
3513
3514       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3515
3516       if (g_object_class_find_property (klass, "ntp-sync")) {
3517         g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
3518       }
3519
3520       if (g_object_class_find_property (klass, "rfc7273-sync")) {
3521         g_object_set (src->manager, "rfc7273-sync", src->rfc7273_sync, NULL);
3522       }
3523
3524       if (src->use_pipeline_clock) {
3525         if (g_object_class_find_property (klass, "use-pipeline-clock")) {
3526           g_object_set (src->manager, "use-pipeline-clock", TRUE, NULL);
3527         }
3528       } else {
3529         if (g_object_class_find_property (klass, "ntp-time-source")) {
3530           g_object_set (src->manager, "ntp-time-source", src->ntp_time_source,
3531               NULL);
3532         }
3533       }
3534
3535       if (src->sdes && g_object_class_find_property (klass, "sdes")) {
3536         g_object_set (src->manager, "sdes", src->sdes, NULL);
3537       }
3538
3539       if (g_object_class_find_property (klass, "drop-on-latency")) {
3540         g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
3541             NULL);
3542       }
3543
3544       if (g_object_class_find_property (klass, "max-rtcp-rtp-time-diff")) {
3545         g_object_set (src->manager, "max-rtcp-rtp-time-diff",
3546             src->max_rtcp_rtp_time_diff, NULL);
3547       }
3548
3549       if (g_object_class_find_property (klass, "max-ts-offset-adjustment")) {
3550         g_object_set (src->manager, "max-ts-offset-adjustment",
3551             src->max_ts_offset_adjustment, NULL);
3552       }
3553
3554       if (g_object_class_find_property (klass, "max-ts-offset")) {
3555         gint64 max_ts_offset;
3556
3557         /* setting max-ts-offset in the manager has side effects so only do it
3558          * if the value differs */
3559         g_object_get (src->manager, "max-ts-offset", &max_ts_offset, NULL);
3560         if (max_ts_offset != src->max_ts_offset) {
3561           g_object_set (src->manager, "max-ts-offset", src->max_ts_offset,
3562               NULL);
3563         }
3564       }
3565
3566       /* buffer mode pauses are handled by adding offsets to buffer times,
3567        * but some depayloaders may have a hard time syncing output times
3568        * with such input times, e.g. container ones, most notably ASF */
3569       /* TODO alternatives are having an event that indicates these shifts,
3570        * or having rtsp extensions provide suggestion on buffer mode */
3571       /* valid duration implies not likely live pipeline,
3572        * so slaving in jitterbuffer does not make much sense
3573        * (and might mess things up due to bursts) */
3574       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
3575           src->segment.duration && stream->container) {
3576         src->use_buffering = TRUE;
3577       } else {
3578         src->use_buffering = FALSE;
3579       }
3580
3581       set_manager_buffer_mode (src);
3582
3583       /* connect to signals */
3584       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
3585           stream);
3586       src->manager_sig_id =
3587           g_signal_connect (src->manager, "pad-added",
3588           (GCallback) new_manager_pad, src);
3589       src->manager_ptmap_id =
3590           g_signal_connect (src->manager, "request-pt-map",
3591           (GCallback) request_pt_map, src);
3592
3593       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
3594           src);
3595
3596       g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
3597           src->manager);
3598
3599       if (src->do_retransmission)
3600         add_retransmission (src, transport);
3601     }
3602     g_signal_connect (src->manager, "request-rtp-decoder",
3603         (GCallback) request_rtp_decoder, stream);
3604     g_signal_connect (src->manager, "request-rtcp-decoder",
3605         (GCallback) request_rtp_decoder, stream);
3606     g_signal_connect (src->manager, "request-rtcp-encoder",
3607         (GCallback) request_rtcp_encoder, stream);
3608
3609     /* we stream directly to the manager, get some pads. Each RTSP stream goes
3610      * into a separate RTP session. */
3611     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
3612     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
3613     g_free (name);
3614     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
3615     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
3616     g_free (name);
3617
3618     /* now configure the bandwidth in the manager */
3619     if (g_signal_lookup ("get-internal-session",
3620             G_OBJECT_TYPE (src->manager)) != 0) {
3621       GObject *rtpsession;
3622
3623       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
3624           &rtpsession);
3625       if (rtpsession) {
3626         GstRTPProfile rtp_profile;
3627
3628         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
3629
3630         stream->session = rtpsession;
3631
3632         if (stream->as_bandwidth != -1) {
3633           GST_INFO_OBJECT (src, "setting AS: %f",
3634               (gdouble) (stream->as_bandwidth * 1000));
3635           g_object_set (rtpsession, "bandwidth",
3636               (gdouble) (stream->as_bandwidth * 1000), NULL);
3637         }
3638         if (stream->rr_bandwidth != -1) {
3639           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
3640           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
3641               NULL);
3642         }
3643         if (stream->rs_bandwidth != -1) {
3644           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
3645           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
3646               NULL);
3647         }
3648
3649         switch (stream->profile) {
3650           case GST_RTSP_PROFILE_AVPF:
3651             rtp_profile = GST_RTP_PROFILE_AVPF;
3652             break;
3653           case GST_RTSP_PROFILE_SAVP:
3654             rtp_profile = GST_RTP_PROFILE_SAVP;
3655             break;
3656           case GST_RTSP_PROFILE_SAVPF:
3657             rtp_profile = GST_RTP_PROFILE_SAVPF;
3658             break;
3659           case GST_RTSP_PROFILE_AVP:
3660           default:
3661             rtp_profile = GST_RTP_PROFILE_AVP;
3662             break;
3663         }
3664
3665         g_object_set (rtpsession, "rtp-profile", rtp_profile, NULL);
3666
3667         g_object_set (rtpsession, "probation", src->probation, NULL);
3668
3669         g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
3670
3671         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
3672             stream);
3673         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
3674             stream);
3675         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
3676             stream);
3677         g_signal_connect (rtpsession, "on-ssrc-active",
3678             (GCallback) on_ssrc_active, stream);
3679       }
3680     }
3681   }
3682
3683 use_no_manager:
3684   return TRUE;
3685
3686   /* ERRORS */
3687 no_manager:
3688   {
3689     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3690     return FALSE;
3691   }
3692 manager_failed:
3693   {
3694     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
3695     return FALSE;
3696   }
3697 start_manager_failure:
3698   {
3699     GST_DEBUG_OBJECT (src, "could not start session manager");
3700     return FALSE;
3701   }
3702 }
3703
3704 /* free the UDP sources allocated when negotiating a transport.
3705  * This function is called when the server negotiated to a transport where the
3706  * UDP sources are not needed anymore, such as TCP or multicast. */
3707 static void
3708 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
3709 {
3710   gint i;
3711
3712   for (i = 0; i < 2; i++) {
3713     if (stream->udpsrc[i]) {
3714       GST_DEBUG ("free UDP source %d for stream %p", i, stream);
3715       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
3716       gst_object_unref (stream->udpsrc[i]);
3717       stream->udpsrc[i] = NULL;
3718     }
3719   }
3720 }
3721
3722 /* for TCP, create pads to send and receive data to and from the manager and to
3723  * intercept various events and queries
3724  */
3725 static gboolean
3726 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
3727     GstRTSPTransport * transport, GstPad ** outpad)
3728 {
3729   gchar *name;
3730   GstPadTemplate *template;
3731   GstPad *pad0, *pad1;
3732
3733   /* configure for interleaved delivery, nothing needs to be done
3734    * here, the loop function will call the chain functions of the
3735    * session manager. */
3736   stream->channel[0] = transport->interleaved.min;
3737   stream->channel[1] = transport->interleaved.max;
3738   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
3739       stream->channel[0], stream->channel[1]);
3740
3741   /* we can remove the allocated UDP ports now */
3742   gst_rtspsrc_stream_free_udp (stream);
3743
3744   /* no session manager, send data to srcpad directly */
3745   if (!stream->channelpad[0]) {
3746     GST_DEBUG_OBJECT (src, "no manager, creating pad");
3747
3748     /* create a new pad we will use to stream to */
3749     name = g_strdup_printf ("stream_%u", stream->id);
3750     template = gst_static_pad_template_get (&rtptemplate);
3751     stream->channelpad[0] = gst_pad_new_from_template (template, name);
3752     gst_object_unref (template);
3753     g_free (name);
3754
3755     /* set caps and activate */
3756     gst_pad_use_fixed_caps (stream->channelpad[0]);
3757     gst_pad_set_active (stream->channelpad[0], TRUE);
3758
3759     *outpad = gst_object_ref (stream->channelpad[0]);
3760   } else {
3761     GST_DEBUG_OBJECT (src, "using manager source pad");
3762
3763     template = gst_static_pad_template_get (&anysrctemplate);
3764
3765     /* allocate pads for sending the channel data into the manager */
3766     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
3767     gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
3768     gst_object_unref (stream->channelpad[0]);
3769     stream->channelpad[0] = pad0;
3770     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
3771     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
3772     gst_pad_set_element_private (pad0, src);
3773     gst_pad_set_active (pad0, TRUE);
3774
3775     if (stream->channelpad[1]) {
3776       /* if we have a sinkpad for the other channel, create a pad and link to the
3777        * manager. */
3778       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
3779       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
3780       gst_pad_link_full (pad1, stream->channelpad[1],
3781           GST_PAD_LINK_CHECK_NOTHING);
3782       gst_object_unref (stream->channelpad[1]);
3783       stream->channelpad[1] = pad1;
3784       gst_pad_set_active (pad1, TRUE);
3785     }
3786     gst_object_unref (template);
3787   }
3788   /* setup RTCP transport back to the server if we have to. */
3789   if (src->manager && src->do_rtcp) {
3790     GstPad *pad;
3791
3792     template = gst_static_pad_template_get (&anysinktemplate);
3793
3794     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
3795     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
3796     gst_pad_set_element_private (stream->rtcppad, stream);
3797     gst_pad_set_active (stream->rtcppad, TRUE);
3798
3799     /* get session RTCP pad */
3800     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3801     pad = gst_element_get_request_pad (src->manager, name);
3802     g_free (name);
3803
3804     /* and link */
3805     if (pad) {
3806       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3807       gst_object_unref (pad);
3808     }
3809
3810     gst_object_unref (template);
3811   }
3812   return TRUE;
3813 }
3814
3815 static void
3816 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3817     GstRTSPTransport * transport, const gchar ** destination, gint * min,
3818     gint * max, guint * ttl)
3819 {
3820   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3821     if (destination) {
3822       if (!(*destination = transport->destination))
3823         *destination = stream->destination;
3824     }
3825     if (min && max) {
3826       /* transport first */
3827       *min = transport->port.min;
3828       *max = transport->port.max;
3829       if (*min == -1 && *max == -1) {
3830         /* then try from SDP */
3831         if (stream->port != 0) {
3832           *min = stream->port;
3833           *max = stream->port + 1;
3834         }
3835       }
3836     }
3837
3838     if (ttl) {
3839       if (!(*ttl = transport->ttl))
3840         *ttl = stream->ttl;
3841     }
3842   } else {
3843     if (destination) {
3844       /* first take the source, then the endpoint to figure out where to send
3845        * the RTCP. */
3846       if (!(*destination = transport->source)) {
3847         if (src->conninfo.connection)
3848           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3849         else if (stream->conninfo.connection)
3850           *destination =
3851               gst_rtsp_connection_get_ip (stream->conninfo.connection);
3852       }
3853     }
3854     if (min && max) {
3855       /* for unicast we only expect the ports here */
3856       *min = transport->server_port.min;
3857       *max = transport->server_port.max;
3858     }
3859   }
3860 }
3861
3862 /* For multicast create UDP sources and join the multicast group. */
3863 static gboolean
3864 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3865     GstRTSPTransport * transport, GstPad ** outpad)
3866 {
3867   gchar *uri;
3868   const gchar *destination;
3869   gint min, max;
3870
3871   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3872
3873   /* we can remove the allocated UDP ports now */
3874   gst_rtspsrc_stream_free_udp (stream);
3875
3876   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3877       &max, NULL);
3878
3879   /* we need a destination now */
3880   if (destination == NULL)
3881     goto no_destination;
3882
3883   /* we really need ports now or we won't be able to receive anything at all */
3884   if (min == -1 && max == -1)
3885     goto no_ports;
3886
3887   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3888       destination, min, max);
3889
3890   /* creating UDP source for RTP */
3891   if (min != -1) {
3892     uri = g_strdup_printf ("udp://%s:%d", destination, min);
3893     stream->udpsrc[0] =
3894         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3895     g_free (uri);
3896     if (stream->udpsrc[0] == NULL)
3897       goto no_element;
3898
3899     /* take ownership */
3900     gst_object_ref_sink (stream->udpsrc[0]);
3901
3902     if (src->udp_buffer_size != 0)
3903       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3904           src->udp_buffer_size, NULL);
3905
3906     if (src->multi_iface != NULL)
3907       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3908           src->multi_iface, NULL);
3909
3910     /* change state */
3911     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3912     gst_element_set_state (stream->udpsrc[0], GST_STATE_READY);
3913   }
3914
3915   /* creating another UDP source for RTCP */
3916   if (max != -1) {
3917     GstCaps *caps;
3918
3919     uri = g_strdup_printf ("udp://%s:%d", destination, max);
3920     stream->udpsrc[1] =
3921         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3922     g_free (uri);
3923     if (stream->udpsrc[1] == NULL)
3924       goto no_element;
3925
3926     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3927         stream->profile == GST_RTSP_PROFILE_SAVPF)
3928       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3929     else
3930       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3931     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3932     gst_caps_unref (caps);
3933
3934     /* take ownership */
3935     gst_object_ref_sink (stream->udpsrc[1]);
3936
3937     if (src->multi_iface != NULL)
3938       g_object_set (G_OBJECT (stream->udpsrc[1]), "multicast-iface",
3939           src->multi_iface, NULL);
3940
3941     gst_element_set_state (stream->udpsrc[1], GST_STATE_READY);
3942   }
3943   return TRUE;
3944
3945   /* ERRORS */
3946 no_element:
3947   {
3948     GST_DEBUG_OBJECT (src, "no UDP source element found");
3949     return FALSE;
3950   }
3951 no_destination:
3952   {
3953     GST_DEBUG_OBJECT (src, "no destination found");
3954     return FALSE;
3955   }
3956 no_ports:
3957   {
3958     GST_DEBUG_OBJECT (src, "no ports found");
3959     return FALSE;
3960   }
3961 }
3962
3963 /* configure the remainder of the UDP ports */
3964 static gboolean
3965 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3966     GstRTSPTransport * transport, GstPad ** outpad)
3967 {
3968   /* we manage the UDP elements now. For unicast, the UDP sources where
3969    * allocated in the stream when we suggested a transport. */
3970   if (stream->udpsrc[0]) {
3971     GstCaps *caps;
3972
3973     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3974     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3975
3976     GST_DEBUG_OBJECT (src, "setting up UDP source");
3977
3978     /* configure a timeout on the UDP port. When the timeout message is
3979      * posted, we assume UDP transport is not possible. We reconnect using TCP
3980      * if we can. */
3981     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3982         src->udp_timeout * 1000, NULL);
3983
3984     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt)))
3985       g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3986
3987     /* get output pad of the UDP source. */
3988     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3989
3990     /* save it so we can unblock */
3991     stream->blockedpad = *outpad;
3992
3993     /* configure pad block on the pad. As soon as there is dataflow on the
3994      * UDP source, we know that UDP is not blocked by a firewall and we can
3995      * configure all the streams to let the application autoplug decoders. */
3996     stream->blockid =
3997         gst_pad_add_probe (stream->blockedpad,
3998         GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
3999         GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
4000
4001     if (stream->channelpad[0]) {
4002       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
4003       /* configure for UDP delivery, we need to connect the UDP pads to
4004        * the session plugin. */
4005       gst_pad_link_full (*outpad, stream->channelpad[0],
4006           GST_PAD_LINK_CHECK_NOTHING);
4007       gst_object_unref (*outpad);
4008       *outpad = NULL;
4009       /* we connected to pad-added signal to get pads from the manager */
4010     } else {
4011       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
4012     }
4013   }
4014
4015   /* RTCP port */
4016   if (stream->udpsrc[1]) {
4017     GstCaps *caps;
4018
4019     gst_element_set_locked_state (stream->udpsrc[1], TRUE);
4020     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
4021
4022     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
4023         stream->profile == GST_RTSP_PROFILE_SAVPF)
4024       caps = gst_caps_new_empty_simple ("application/x-srtcp");
4025     else
4026       caps = gst_caps_new_empty_simple ("application/x-rtcp");
4027     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
4028     gst_caps_unref (caps);
4029
4030     if (stream->channelpad[1]) {
4031       GstPad *pad;
4032
4033       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
4034
4035       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
4036       gst_pad_link_full (pad, stream->channelpad[1],
4037           GST_PAD_LINK_CHECK_NOTHING);
4038       gst_object_unref (pad);
4039     } else {
4040       /* leave unlinked */
4041     }
4042   }
4043   return TRUE;
4044 }
4045
4046 /* configure the UDP sink back to the server for status reports */
4047 static gboolean
4048 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
4049     GstRTSPStream * stream, GstRTSPTransport * transport)
4050 {
4051   GstPad *pad;
4052   gint rtp_port, rtcp_port;
4053   gboolean do_rtp, do_rtcp;
4054   const gchar *destination;
4055   gchar *uri, *name;
4056   guint ttl = 0;
4057   GSocket *socket;
4058
4059   /* get transport info */
4060   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
4061       &rtp_port, &rtcp_port, &ttl);
4062
4063   /* see what we need to do */
4064   do_rtp = (rtp_port != -1);
4065   /* it's possible that the server does not want us to send RTCP in which case
4066    * the port is -1 */
4067   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
4068
4069   /* we need a destination when we have RTP or RTCP ports */
4070   if (destination == NULL && (do_rtp || do_rtcp))
4071     goto no_destination;
4072
4073   /* try to construct the fakesrc to the RTP port of the server to open up any
4074    * NAT firewalls or, if backchannel, construct an appsrc */
4075   if (do_rtp) {
4076     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
4077         rtp_port);
4078
4079     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
4080     stream->udpsink[0] =
4081         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
4082     g_free (uri);
4083     if (stream->udpsink[0] == NULL)
4084       goto no_sink_element;
4085
4086     /* don't join multicast group, we will have the source socket do that */
4087     /* no sync or async state changes needed */
4088     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
4089         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
4090     if (ttl > 0)
4091       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
4092
4093     if (stream->udpsrc[0]) {
4094       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
4095        * so that NAT firewalls will open a hole for us */
4096       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
4097       if (!socket)
4098         goto no_socket;
4099
4100       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
4101       /* configure socket and make sure udpsink does not close it when shutting
4102        * down, it belongs to udpsrc after all. */
4103       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
4104           "close-socket", FALSE, NULL);
4105       g_object_unref (socket);
4106     }
4107
4108     if (stream->is_backchannel) {
4109       /* appsrc is for the app to shovel data using push-backchannel-buffer */
4110       stream->rtpsrc = gst_element_factory_make ("appsrc", NULL);
4111       if (stream->rtpsrc == NULL)
4112         goto no_appsrc_element;
4113
4114       /* interal use only, don't emit signals */
4115       g_object_set (G_OBJECT (stream->rtpsrc), "emit-signals", TRUE,
4116           "is-live", TRUE, NULL);
4117     } else {
4118       /* the source for the dummy packets to open up NAT */
4119       stream->rtpsrc = gst_element_factory_make ("fakesrc", NULL);
4120       if (stream->rtpsrc == NULL)
4121         goto no_fakesrc_element;
4122
4123       /* random data in 5 buffers, a size of 200 bytes should be fine */
4124       g_object_set (G_OBJECT (stream->rtpsrc), "filltype", 3, "num-buffers", 5,
4125           "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
4126     }
4127
4128     /* keep everything locked */
4129     gst_element_set_locked_state (stream->udpsink[0], TRUE);
4130     gst_element_set_locked_state (stream->rtpsrc, TRUE);
4131
4132     gst_object_ref (stream->udpsink[0]);
4133     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
4134     gst_object_ref (stream->rtpsrc);
4135     gst_bin_add (GST_BIN_CAST (src), stream->rtpsrc);
4136
4137     gst_element_link_pads_full (stream->rtpsrc, "src", stream->udpsink[0],
4138         "sink", GST_PAD_LINK_CHECK_NOTHING);
4139   }
4140   if (do_rtcp) {
4141     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
4142         rtcp_port);
4143
4144     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
4145     stream->udpsink[1] =
4146         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
4147     g_free (uri);
4148     if (stream->udpsink[1] == NULL)
4149       goto no_sink_element;
4150
4151     /* don't join multicast group, we will have the source socket do that */
4152     /* no sync or async state changes needed */
4153     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
4154         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
4155     if (ttl > 0)
4156       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
4157
4158     if (stream->udpsrc[1]) {
4159       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
4160        * because some servers check the port number of where it sends RTCP to identify
4161        * the RTCP packets it receives */
4162       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
4163       if (!socket)
4164         goto no_socket;
4165
4166       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
4167       /* configure socket and make sure udpsink does not close it when shutting
4168        * down, it belongs to udpsrc after all. */
4169       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
4170           "close-socket", FALSE, NULL);
4171       g_object_unref (socket);
4172     }
4173
4174     /* we keep this playing always */
4175     gst_element_set_locked_state (stream->udpsink[1], TRUE);
4176     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
4177
4178     gst_object_ref (stream->udpsink[1]);
4179     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
4180
4181     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
4182
4183     /* get session RTCP pad */
4184     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
4185     pad = gst_element_get_request_pad (src->manager, name);
4186     g_free (name);
4187
4188     /* and link */
4189     if (pad) {
4190       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
4191       gst_object_unref (pad);
4192     }
4193   }
4194
4195   return TRUE;
4196
4197   /* ERRORS */
4198 no_destination:
4199   {
4200     GST_ERROR_OBJECT (src, "no destination address specified");
4201     return FALSE;
4202   }
4203 no_sink_element:
4204   {
4205     GST_ERROR_OBJECT (src, "no UDP sink element found");
4206     return FALSE;
4207   }
4208 no_appsrc_element:
4209   {
4210     GST_ERROR_OBJECT (src, "no appsrc element found");
4211     return FALSE;
4212   }
4213 no_fakesrc_element:
4214   {
4215     GST_ERROR_OBJECT (src, "no fakesrc element found");
4216     return FALSE;
4217   }
4218 no_socket:
4219   {
4220     GST_ERROR_OBJECT (src, "failed to create socket");
4221     return FALSE;
4222   }
4223 }
4224
4225 /* sets up all elements needed for streaming over the specified transport.
4226  * Does not yet expose the element pads, this will be done when there is actuall
4227  * dataflow detected, which might never happen when UDP is blocked in a
4228  * firewall, for example.
4229  */
4230 static gboolean
4231 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
4232     GstRTSPTransport * transport)
4233 {
4234   GstRTSPSrc *src;
4235   GstPad *outpad = NULL;
4236   GstPadTemplate *template;
4237   gchar *name;
4238   const gchar *media_type;
4239   guint i, len;
4240
4241   src = stream->parent;
4242
4243   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
4244
4245   /* get the proper media type for this stream now */
4246   if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
4247     goto unknown_transport;
4248   if (!media_type)
4249     goto unknown_transport;
4250
4251   /* configure the final media type */
4252   GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
4253
4254   len = stream->ptmap->len;
4255   for (i = 0; i < len; i++) {
4256     GstStructure *s;
4257     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
4258
4259     if (item->caps == NULL)
4260       continue;
4261
4262     s = gst_caps_get_structure (item->caps, 0);
4263     gst_structure_set_name (s, media_type);
4264     /* set ssrc if known */
4265     if (transport->ssrc)
4266       gst_structure_set (s, "ssrc", G_TYPE_UINT, transport->ssrc, NULL);
4267   }
4268
4269   /* try to get and configure a manager, channelpad[0-1] will be configured with
4270    * the pads for the manager, or NULL when no manager is needed. */
4271   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
4272     goto no_manager;
4273
4274   switch (transport->lower_transport) {
4275     case GST_RTSP_LOWER_TRANS_TCP:
4276       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
4277         goto transport_failed;
4278       break;
4279     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
4280       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
4281         goto transport_failed;
4282       /* fallthrough, the rest is the same for UDP and MCAST */
4283     case GST_RTSP_LOWER_TRANS_UDP:
4284       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
4285         goto transport_failed;
4286       /* configure udpsinks back to the server for RTCP messages, for the
4287        * dummy RTP messages to open NAT, and for the backchannel */
4288       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
4289         goto transport_failed;
4290       break;
4291     default:
4292       goto unknown_transport;
4293   }
4294
4295   /* using backchannel and no manager, hence no srcpad for this stream */
4296   if (outpad && stream->is_backchannel) {
4297     add_backchannel_fakesink (src, stream, outpad);
4298     gst_object_unref (outpad);
4299   } else if (outpad) {
4300     GST_DEBUG_OBJECT (src, "creating ghostpad for stream %p", stream);
4301
4302     gst_pad_use_fixed_caps (outpad);
4303
4304     /* create ghostpad, don't add just yet, this will be done when we activate
4305      * the stream. */
4306     name = g_strdup_printf ("stream_%u", stream->id);
4307     template = gst_static_pad_template_get (&rtptemplate);
4308     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
4309     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
4310     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
4311     gst_object_unref (template);
4312     g_free (name);
4313
4314     gst_object_unref (outpad);
4315   }
4316   /* mark pad as ok */
4317   stream->last_ret = GST_FLOW_OK;
4318
4319   return TRUE;
4320
4321   /* ERRORS */
4322 transport_failed:
4323   {
4324     GST_WARNING_OBJECT (src, "failed to configure transport");
4325     return FALSE;
4326   }
4327 unknown_transport:
4328   {
4329     GST_WARNING_OBJECT (src, "unknown transport");
4330     return FALSE;
4331   }
4332 no_manager:
4333   {
4334     GST_WARNING_OBJECT (src, "cannot get a session manager");
4335     return FALSE;
4336   }
4337 }
4338
4339 /* send a couple of dummy random packets on the receiver RTP port to the server,
4340  * this should make a firewall think we initiated the data transfer and
4341  * hopefully allow packets to go from the sender port to our RTP receiver port */
4342 static gboolean
4343 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
4344 {
4345   GList *walk;
4346
4347   if (src->nat_method != GST_RTSP_NAT_DUMMY)
4348     return TRUE;
4349
4350   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4351     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4352
4353     if (!stream->rtpsrc || !stream->udpsink[0])
4354       continue;
4355
4356     if (stream->is_backchannel)
4357       GST_DEBUG_OBJECT (src, "starting backchannel stream %p", stream);
4358     else
4359       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
4360
4361     gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
4362     gst_element_set_state (stream->rtpsrc, GST_STATE_NULL);
4363     gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
4364     gst_element_set_state (stream->rtpsrc, GST_STATE_PLAYING);
4365   }
4366   return TRUE;
4367 }
4368
4369 /* Adds the source pads of all configured streams to the element.
4370  * This code is performed when we detected dataflow.
4371  *
4372  * We detect dataflow from either the _loop function or with pad probes on the
4373  * udp sources.
4374  */
4375 static gboolean
4376 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
4377 {
4378   GList *walk;
4379
4380   GST_DEBUG_OBJECT (src, "activating streams");
4381
4382   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4383     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4384
4385     if (stream->udpsrc[0]) {
4386       /* remove timeout, we are streaming now and timeouts will be handled by
4387        * the session manager and jitter buffer */
4388       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
4389     }
4390     if (stream->srcpad) {
4391       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
4392       gst_pad_set_active (stream->srcpad, TRUE);
4393
4394       /* if we don't have a session manager, set the caps now. If we have a
4395        * session, we will get a notification of the pad and the caps. */
4396       if (!src->manager) {
4397         GstCaps *caps;
4398
4399         caps = stream_get_caps_for_pt (stream, stream->default_pt);
4400         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
4401         gst_pad_set_caps (stream->srcpad, caps);
4402       }
4403       /* add the pad */
4404       if (!stream->added) {
4405         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
4406         if (stream->is_backchannel)
4407           add_backchannel_fakesink (src, stream, stream->srcpad);
4408         else
4409           gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
4410         stream->added = TRUE;
4411       }
4412     }
4413   }
4414
4415   /* unblock all pads */
4416   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4417     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4418
4419     if (stream->blockid) {
4420       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
4421       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
4422       stream->blockid = 0;
4423     }
4424   }
4425
4426   return TRUE;
4427 }
4428
4429 static void
4430 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
4431     gboolean reset_manager)
4432 {
4433   GList *walk;
4434   guint64 start, stop;
4435   gdouble play_speed, play_scale;
4436
4437   GST_DEBUG_OBJECT (src, "configuring stream caps");
4438
4439   start = segment->position;
4440   stop = segment->duration;
4441   play_speed = segment->rate;
4442   play_scale = segment->applied_rate;
4443
4444   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4445     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4446     guint j, len;
4447
4448     if (!stream->setup)
4449       continue;
4450
4451     len = stream->ptmap->len;
4452     for (j = 0; j < len; j++) {
4453       GstCaps *caps;
4454       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, j);
4455
4456       if (item->caps == NULL)
4457         continue;
4458
4459       caps = gst_caps_make_writable (item->caps);
4460       /* update caps */
4461       if (stream->timebase != -1)
4462         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
4463             (guint) stream->timebase, NULL);
4464       if (stream->seqbase != -1)
4465         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
4466             (guint) stream->seqbase, NULL);
4467       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
4468       if (stop != -1)
4469         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
4470       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
4471       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
4472
4473       item->caps = caps;
4474       GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
4475           item->pt, caps);
4476
4477       if (item->pt == stream->default_pt) {
4478         if (stream->udpsrc[0])
4479           g_object_set (stream->udpsrc[0], "caps", caps, NULL);
4480         stream->need_caps = TRUE;
4481       }
4482     }
4483   }
4484   if (reset_manager && src->manager) {
4485     GST_DEBUG_OBJECT (src, "clear session");
4486     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
4487   }
4488 }
4489
4490 static GstFlowReturn
4491 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
4492     GstFlowReturn ret)
4493 {
4494   GList *streams;
4495
4496   /* store the value */
4497   stream->last_ret = ret;
4498
4499   /* if it's success we can return the value right away */
4500   if (ret == GST_FLOW_OK)
4501     goto done;
4502
4503   /* any other error that is not-linked can be returned right
4504    * away */
4505   if (ret != GST_FLOW_NOT_LINKED)
4506     goto done;
4507
4508   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4509   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4510     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4511
4512     ret = ostream->last_ret;
4513     /* some other return value (must be SUCCESS but we can return
4514      * other values as well) */
4515     if (ret != GST_FLOW_NOT_LINKED)
4516       goto done;
4517   }
4518   /* if we get here, all other pads were unlinked and we return
4519    * NOT_LINKED then */
4520 done:
4521   return ret;
4522 }
4523
4524 static gboolean
4525 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
4526     GstEvent * event)
4527 {
4528   gboolean res = TRUE;
4529
4530   /* only streams that have a connection to the outside world */
4531   if (!stream->setup)
4532     goto done;
4533
4534   if (stream->udpsrc[0]) {
4535     gst_event_ref (event);
4536     res = gst_element_send_event (stream->udpsrc[0], event);
4537   } else if (stream->channelpad[0]) {
4538     gst_event_ref (event);
4539     if (GST_PAD_IS_SRC (stream->channelpad[0]))
4540       res = gst_pad_push_event (stream->channelpad[0], event);
4541     else
4542       res = gst_pad_send_event (stream->channelpad[0], event);
4543   }
4544
4545   if (stream->udpsrc[1]) {
4546     gst_event_ref (event);
4547     res &= gst_element_send_event (stream->udpsrc[1], event);
4548   } else if (stream->channelpad[1]) {
4549     gst_event_ref (event);
4550     if (GST_PAD_IS_SRC (stream->channelpad[1]))
4551       res &= gst_pad_push_event (stream->channelpad[1], event);
4552     else
4553       res &= gst_pad_send_event (stream->channelpad[1], event);
4554   }
4555
4556 done:
4557   gst_event_unref (event);
4558
4559   return res;
4560 }
4561
4562 static gboolean
4563 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
4564 {
4565   GList *streams;
4566   gboolean res = TRUE;
4567
4568   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4569     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4570
4571     gst_event_ref (event);
4572     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
4573   }
4574   gst_event_unref (event);
4575
4576   return res;
4577 }
4578
4579 static gboolean
4580 accept_certificate_cb (GTlsConnection * conn, GTlsCertificate * peer_cert,
4581     GTlsCertificateFlags errors, gpointer user_data)
4582 {
4583   GstRTSPSrc *src = user_data;
4584   gboolean accept = FALSE;
4585
4586   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ACCEPT_CERTIFICATE], 0, conn,
4587       peer_cert, errors, &accept);
4588
4589   return accept;
4590 }
4591
4592 static GstRTSPResult
4593 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4594     gboolean async)
4595 {
4596   GstRTSPResult res;
4597   GstRTSPMessage response;
4598   gboolean retry = FALSE;
4599   memset (&response, 0, sizeof (response));
4600   gst_rtsp_message_init (&response);
4601   do {
4602     if (info->connection == NULL) {
4603       if (info->url == NULL) {
4604         GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
4605         if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
4606           goto parse_error;
4607       }
4608       /* create connection */
4609       GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
4610       if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
4611         goto could_not_create;
4612
4613       if (retry) {
4614         gst_rtspsrc_setup_auth (src, &response);
4615       }
4616
4617       g_free (info->url_str);
4618       info->url_str = gst_rtsp_url_get_request_uri (info->url);
4619
4620       GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
4621
4622       if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
4623         if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
4624                 src->tls_validation_flags))
4625           GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
4626
4627         if (src->tls_database)
4628           gst_rtsp_connection_set_tls_database (info->connection,
4629               src->tls_database);
4630
4631         if (src->tls_interaction)
4632           gst_rtsp_connection_set_tls_interaction (info->connection,
4633               src->tls_interaction);
4634         gst_rtsp_connection_set_accept_certificate_func (info->connection,
4635             accept_certificate_cb, src, NULL);
4636       }
4637
4638       if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
4639         gst_rtsp_connection_set_tunneled (info->connection, TRUE);
4640
4641       if (src->proxy_host) {
4642         GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
4643             src->proxy_port);
4644         gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
4645             src->proxy_port);
4646       }
4647     }
4648
4649     if (!info->connected) {
4650       /* connect */
4651       if (async)
4652         GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
4653             ("Connecting to %s", info->location));
4654       GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
4655       res = gst_rtsp_connection_connect_with_response (info->connection,
4656           src->ptcp_timeout, &response);
4657
4658       if (response.type == GST_RTSP_MESSAGE_HTTP_RESPONSE &&
4659           response.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4660         gst_rtsp_conninfo_close (src, info, TRUE);
4661         if (!retry)
4662           retry = TRUE;
4663         else
4664           retry = FALSE;        // we should not retry more than once
4665       } else {
4666         retry = FALSE;
4667       }
4668
4669       if (res == GST_RTSP_OK)
4670         info->connected = TRUE;
4671       else if (!retry)
4672         goto could_not_connect;
4673     }
4674   } while (!info->connected && retry);
4675
4676   gst_rtsp_message_unset (&response);
4677   return GST_RTSP_OK;
4678
4679   /* ERRORS */
4680 parse_error:
4681   {
4682     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
4683     gst_rtsp_message_unset (&response);
4684     return res;
4685   }
4686 could_not_create:
4687   {
4688     gchar *str = gst_rtsp_strresult (res);
4689     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
4690     g_free (str);
4691     gst_rtsp_message_unset (&response);
4692     return res;
4693   }
4694 could_not_connect:
4695   {
4696     gchar *str = gst_rtsp_strresult (res);
4697     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
4698     g_free (str);
4699     gst_rtsp_message_unset (&response);
4700     return res;
4701   }
4702 }
4703
4704 static GstRTSPResult
4705 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
4706     gboolean free)
4707 {
4708   GST_RTSP_STATE_LOCK (src);
4709   if (info->connected) {
4710     GST_DEBUG_OBJECT (src, "closing connection...");
4711     gst_rtsp_connection_close (info->connection);
4712     info->connected = FALSE;
4713   }
4714   if (free && info->connection) {
4715     /* free connection */
4716     GST_DEBUG_OBJECT (src, "freeing connection...");
4717     gst_rtsp_connection_free (info->connection);
4718     info->connection = NULL;
4719     info->flushing = FALSE;
4720   }
4721   GST_RTSP_STATE_UNLOCK (src);
4722   return GST_RTSP_OK;
4723 }
4724
4725 static GstRTSPResult
4726 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4727     gboolean async)
4728 {
4729   GstRTSPResult res;
4730
4731   GST_DEBUG_OBJECT (src, "reconnecting connection...");
4732   gst_rtsp_conninfo_close (src, info, FALSE);
4733   res = gst_rtsp_conninfo_connect (src, info, async);
4734
4735   return res;
4736 }
4737
4738 static void
4739 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
4740 {
4741   GList *walk;
4742
4743   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
4744   GST_RTSP_STATE_LOCK (src);
4745   if (src->conninfo.connection && src->conninfo.flushing != flush) {
4746     GST_DEBUG_OBJECT (src, "connection flush");
4747     gst_rtsp_connection_flush (src->conninfo.connection, flush);
4748     src->conninfo.flushing = flush;
4749   }
4750   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4751     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4752     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
4753       GST_DEBUG_OBJECT (src, "stream %p flush", stream);
4754       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
4755       stream->conninfo.flushing = flush;
4756     }
4757   }
4758   GST_RTSP_STATE_UNLOCK (src);
4759 }
4760
4761 static GstRTSPResult
4762 gst_rtspsrc_init_request (GstRTSPSrc * src, GstRTSPMessage * msg,
4763     GstRTSPMethod method, const gchar * uri)
4764 {
4765   GstRTSPResult res;
4766
4767   res = gst_rtsp_message_init_request (msg, method, uri);
4768   if (res < 0)
4769     return res;
4770
4771   /* set user-agent */
4772   if (src->user_agent)
4773     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_USER_AGENT, src->user_agent);
4774
4775   return res;
4776 }
4777
4778 /* FIXME, handle server request, reply with OK, for now */
4779 static GstRTSPResult
4780 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
4781     GstRTSPMessage * request)
4782 {
4783   GstRTSPMessage response = { 0 };
4784   GstRTSPResult res;
4785
4786   GST_DEBUG_OBJECT (src, "got server request message");
4787
4788   DEBUG_RTSP (src, request);
4789
4790   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4791
4792   if (res == GST_RTSP_ENOTIMPL) {
4793     /* default implementation, send OK */
4794     GST_DEBUG_OBJECT (src, "prepare OK reply");
4795     res =
4796         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4797         request);
4798     if (res < 0)
4799       goto send_error;
4800
4801     /* let app parse and reply */
4802     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4803         0, request, &response);
4804
4805     DEBUG_RTSP (src, &response);
4806
4807     res = gst_rtspsrc_connection_send (src, conninfo, &response, NULL);
4808     if (res < 0)
4809       goto send_error;
4810
4811     gst_rtsp_message_unset (&response);
4812   } else if (res == GST_RTSP_EEOF)
4813     return res;
4814
4815   return GST_RTSP_OK;
4816
4817   /* ERRORS */
4818 send_error:
4819   {
4820     gst_rtsp_message_unset (&response);
4821     return res;
4822   }
4823 }
4824
4825 /* send server keep-alive */
4826 static GstRTSPResult
4827 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4828 {
4829   GstRTSPMessage request = { 0 };
4830   GstRTSPResult res;
4831   GstRTSPMethod method;
4832   const gchar *control;
4833
4834   if (src->do_rtsp_keep_alive == FALSE) {
4835     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4836     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4837     return GST_RTSP_OK;
4838   }
4839
4840   GST_DEBUG_OBJECT (src, "creating server keep-alive");
4841
4842   /* find a method to use for keep-alive */
4843   if (src->methods & GST_RTSP_GET_PARAMETER)
4844     method = GST_RTSP_GET_PARAMETER;
4845   else
4846     method = GST_RTSP_OPTIONS;
4847
4848   control = get_aggregate_control (src);
4849   if (control == NULL)
4850     goto no_control;
4851
4852   res = gst_rtspsrc_init_request (src, &request, method, control);
4853   if (res < 0)
4854     goto send_error;
4855
4856   request.type_data.request.version = src->version;
4857
4858   res = gst_rtspsrc_connection_send (src, &src->conninfo, &request, NULL);
4859   if (res < 0)
4860     goto send_error;
4861
4862   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4863   gst_rtsp_message_unset (&request);
4864
4865   return GST_RTSP_OK;
4866
4867   /* ERRORS */
4868 no_control:
4869   {
4870     GST_WARNING_OBJECT (src, "no control url to send keepalive");
4871     return GST_RTSP_OK;
4872   }
4873 send_error:
4874   {
4875     gchar *str = gst_rtsp_strresult (res);
4876
4877     gst_rtsp_message_unset (&request);
4878     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4879         ("Could not send keep-alive. (%s)", str));
4880     g_free (str);
4881     return res;
4882   }
4883 }
4884
4885 static GstFlowReturn
4886 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4887 {
4888   GstFlowReturn ret = GST_FLOW_OK;
4889   gint channel;
4890   GstRTSPStream *stream;
4891   GstPad *outpad = NULL;
4892   guint8 *data;
4893   guint size;
4894   GstBuffer *buf;
4895   gboolean is_rtcp;
4896
4897   channel = message->type_data.data.channel;
4898
4899   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4900   if (!stream)
4901     goto unknown_stream;
4902
4903   if (channel == stream->channel[0]) {
4904     outpad = stream->channelpad[0];
4905     is_rtcp = FALSE;
4906   } else if (channel == stream->channel[1]) {
4907     outpad = stream->channelpad[1];
4908     is_rtcp = TRUE;
4909   } else {
4910     is_rtcp = FALSE;
4911   }
4912
4913   /* take a look at the body to figure out what we have */
4914   gst_rtsp_message_get_body (message, &data, &size);
4915   if (size < 2)
4916     goto invalid_length;
4917
4918   /* channels are not correct on some servers, do extra check */
4919   if (data[1] >= 200 && data[1] <= 204) {
4920     /* hmm RTCP message switch to the RTCP pad of the same stream. */
4921     outpad = stream->channelpad[1];
4922     is_rtcp = TRUE;
4923   }
4924
4925   /* we have no clue what this is, just ignore then. */
4926   if (outpad == NULL)
4927     goto unknown_stream;
4928
4929   /* take the message body for further processing */
4930   gst_rtsp_message_steal_body (message, &data, &size);
4931
4932   /* strip the trailing \0 */
4933   size -= 1;
4934
4935   buf = gst_buffer_new ();
4936   gst_buffer_append_memory (buf,
4937       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4938
4939   /* don't need message anymore */
4940   gst_rtsp_message_unset (message);
4941
4942   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4943       channel);
4944
4945   if (src->need_activate) {
4946     gchar *stream_id;
4947     GstEvent *event;
4948     GChecksum *cs;
4949     gchar *uri;
4950     GList *streams;
4951     guint group_id = gst_util_group_id_next ();
4952
4953     /* generate an SHA256 sum of the URI */
4954     cs = g_checksum_new (G_CHECKSUM_SHA256);
4955     uri = src->conninfo.location;
4956     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4957
4958     for (streams = src->streams; streams; streams = g_list_next (streams)) {
4959       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4960       GstCaps *caps;
4961
4962       stream_id =
4963           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4964       event = gst_event_new_stream_start (stream_id);
4965       gst_event_set_group_id (event, group_id);
4966
4967       g_free (stream_id);
4968       gst_rtspsrc_stream_push_event (src, ostream, event);
4969
4970       if ((caps = stream_get_caps_for_pt (ostream, ostream->default_pt))) {
4971         /* only streams that have a connection to the outside world */
4972         if (ostream->setup) {
4973           if (ostream->udpsrc[0]) {
4974             gst_element_send_event (ostream->udpsrc[0],
4975                 gst_event_new_caps (caps));
4976           } else if (ostream->channelpad[0]) {
4977             if (GST_PAD_IS_SRC (ostream->channelpad[0]))
4978               gst_pad_push_event (ostream->channelpad[0],
4979                   gst_event_new_caps (caps));
4980             else
4981               gst_pad_send_event (ostream->channelpad[0],
4982                   gst_event_new_caps (caps));
4983           }
4984           ostream->need_caps = FALSE;
4985
4986           if (ostream->profile == GST_RTSP_PROFILE_SAVP ||
4987               ostream->profile == GST_RTSP_PROFILE_SAVPF)
4988             caps = gst_caps_new_empty_simple ("application/x-srtcp");
4989           else
4990             caps = gst_caps_new_empty_simple ("application/x-rtcp");
4991
4992           if (ostream->udpsrc[1]) {
4993             gst_element_send_event (ostream->udpsrc[1],
4994                 gst_event_new_caps (caps));
4995           } else if (ostream->channelpad[1]) {
4996             if (GST_PAD_IS_SRC (ostream->channelpad[1]))
4997               gst_pad_push_event (ostream->channelpad[1],
4998                   gst_event_new_caps (caps));
4999             else
5000               gst_pad_send_event (ostream->channelpad[1],
5001                   gst_event_new_caps (caps));
5002           }
5003
5004           gst_caps_unref (caps);
5005         }
5006       }
5007     }
5008     g_checksum_free (cs);
5009
5010     gst_rtspsrc_activate_streams (src);
5011     src->need_activate = FALSE;
5012     src->need_segment = TRUE;
5013   }
5014
5015   if (src->base_time == -1) {
5016     /* Take current running_time. This timestamp will be put on
5017      * the first buffer of each stream because we are a live source and so we
5018      * timestamp with the running_time. When we are dealing with TCP, we also
5019      * only timestamp the first buffer (using the DISCONT flag) because a server
5020      * typically bursts data, for which we don't want to compensate by speeding
5021      * up the media. The other timestamps will be interpollated from this one
5022      * using the RTP timestamps. */
5023     GST_OBJECT_LOCK (src);
5024     if (GST_ELEMENT_CLOCK (src)) {
5025       GstClockTime now;
5026       GstClockTime base_time;
5027
5028       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
5029       base_time = GST_ELEMENT_CAST (src)->base_time;
5030
5031       src->base_time = now - base_time;
5032
5033       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
5034           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
5035     }
5036     GST_OBJECT_UNLOCK (src);
5037   }
5038
5039   /* If needed send a new segment, don't forget we are live and buffer are
5040    * timestamped with running time */
5041   if (src->need_segment) {
5042     GstSegment segment;
5043     src->need_segment = FALSE;
5044     gst_segment_init (&segment, GST_FORMAT_TIME);
5045     gst_rtspsrc_push_event (src, gst_event_new_segment (&segment));
5046   }
5047
5048   if (stream->need_caps) {
5049     GstCaps *caps;
5050
5051     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt))) {
5052       /* only streams that have a connection to the outside world */
5053       if (stream->setup) {
5054         /* Only need to update the TCP caps here, UDP is already handled */
5055         if (stream->channelpad[0]) {
5056           if (GST_PAD_IS_SRC (stream->channelpad[0]))
5057             gst_pad_push_event (stream->channelpad[0],
5058                 gst_event_new_caps (caps));
5059           else
5060             gst_pad_send_event (stream->channelpad[0],
5061                 gst_event_new_caps (caps));
5062         }
5063         stream->need_caps = FALSE;
5064       }
5065     }
5066
5067     stream->need_caps = FALSE;
5068   }
5069
5070   if (stream->discont && !is_rtcp) {
5071     /* mark first RTP buffer as discont */
5072     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5073     stream->discont = FALSE;
5074     /* first buffer gets the timestamp, other buffers are not timestamped and
5075      * their presentation time will be interpollated from the rtp timestamps. */
5076     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
5077         GST_TIME_ARGS (src->base_time));
5078
5079     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
5080   }
5081
5082   /* chain to the peer pad */
5083   if (GST_PAD_IS_SINK (outpad))
5084     ret = gst_pad_chain (outpad, buf);
5085   else
5086     ret = gst_pad_push (outpad, buf);
5087
5088   if (!is_rtcp) {
5089     /* combine all stream flows for the data transport */
5090     ret = gst_rtspsrc_combine_flows (src, stream, ret);
5091   }
5092   return ret;
5093
5094   /* ERRORS */
5095 unknown_stream:
5096   {
5097     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
5098     gst_rtsp_message_unset (message);
5099     return GST_FLOW_OK;
5100   }
5101 invalid_length:
5102   {
5103     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5104         ("Short message received, ignoring."));
5105     gst_rtsp_message_unset (message);
5106     return GST_FLOW_OK;
5107   }
5108 }
5109
5110 static GstFlowReturn
5111 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
5112 {
5113   GstRTSPMessage message = { 0 };
5114   GstRTSPResult res;
5115   GstFlowReturn ret = GST_FLOW_OK;
5116   GTimeVal tv_timeout;
5117
5118   while (TRUE) {
5119     /* get the next timeout interval */
5120     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
5121
5122     /* see if the timeout period expired */
5123     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
5124       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
5125       /* send keep-alive, only act on interrupt, a warning will be posted for
5126        * other errors. */
5127       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5128         goto interrupt;
5129       /* get new timeout */
5130       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
5131     }
5132
5133     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
5134         tv_timeout.tv_sec, tv_timeout.tv_usec);
5135
5136     /* protect the connection with the connection lock so that we can see when
5137      * we are finished doing server communication */
5138     res =
5139         gst_rtspsrc_connection_receive (src, &src->conninfo,
5140         &message, src->ptcp_timeout);
5141
5142     switch (res) {
5143       case GST_RTSP_OK:
5144         GST_DEBUG_OBJECT (src, "we received a server message");
5145         break;
5146       case GST_RTSP_EINTR:
5147         /* we got interrupted this means we need to stop */
5148         goto interrupt;
5149       case GST_RTSP_ETIMEOUT:
5150         /* no reply, send keep alive */
5151         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
5152         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5153           goto interrupt;
5154         continue;
5155       case GST_RTSP_EEOF:
5156         /* go EOS when the server closed the connection */
5157         goto server_eof;
5158       default:
5159         goto receive_error;
5160     }
5161
5162     switch (message.type) {
5163       case GST_RTSP_MESSAGE_REQUEST:
5164         /* server sends us a request message, handle it */
5165         res = gst_rtspsrc_handle_request (src, &src->conninfo, &message);
5166         if (res == GST_RTSP_EEOF)
5167           goto server_eof;
5168         else if (res < 0)
5169           goto handle_request_failed;
5170         break;
5171       case GST_RTSP_MESSAGE_RESPONSE:
5172         /* we ignore response messages */
5173         GST_DEBUG_OBJECT (src, "ignoring response message");
5174         DEBUG_RTSP (src, &message);
5175         break;
5176       case GST_RTSP_MESSAGE_DATA:
5177         GST_DEBUG_OBJECT (src, "got data message");
5178         ret = gst_rtspsrc_handle_data (src, &message);
5179         if (ret != GST_FLOW_OK)
5180           goto handle_data_failed;
5181         break;
5182       default:
5183         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5184             message.type);
5185         break;
5186     }
5187   }
5188   g_assert_not_reached ();
5189
5190   /* ERRORS */
5191 server_eof:
5192   {
5193     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5194     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5195         ("The server closed the connection."));
5196     src->conninfo.connected = FALSE;
5197     gst_rtsp_message_unset (&message);
5198     return GST_FLOW_EOS;
5199   }
5200 interrupt:
5201   {
5202     gst_rtsp_message_unset (&message);
5203     GST_DEBUG_OBJECT (src, "got interrupted");
5204     return GST_FLOW_FLUSHING;
5205   }
5206 receive_error:
5207   {
5208     gchar *str = gst_rtsp_strresult (res);
5209
5210     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5211         ("Could not receive message. (%s)", str));
5212     g_free (str);
5213
5214     gst_rtsp_message_unset (&message);
5215     return GST_FLOW_ERROR;
5216   }
5217 handle_request_failed:
5218   {
5219     gchar *str = gst_rtsp_strresult (res);
5220
5221     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5222         ("Could not handle server message. (%s)", str));
5223     g_free (str);
5224     gst_rtsp_message_unset (&message);
5225     return GST_FLOW_ERROR;
5226   }
5227 handle_data_failed:
5228   {
5229     GST_DEBUG_OBJECT (src, "could no handle data message");
5230     return ret;
5231   }
5232 }
5233
5234 static GstFlowReturn
5235 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
5236 {
5237   GstRTSPResult res;
5238   GstRTSPMessage message = { 0 };
5239   gint retry = 0;
5240
5241   while (TRUE) {
5242     GTimeVal tv_timeout;
5243
5244     /* get the next timeout interval */
5245     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
5246
5247     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
5248         (gint) tv_timeout.tv_sec);
5249
5250     gst_rtsp_message_unset (&message);
5251
5252     /* we should continue reading the TCP socket because the server might
5253      * send us requests. When the session timeout expires, we need to send a
5254      * keep-alive request to keep the session open. */
5255     res = gst_rtspsrc_connection_receive (src, &src->conninfo,
5256         &message, &tv_timeout);
5257
5258     switch (res) {
5259       case GST_RTSP_OK:
5260         GST_DEBUG_OBJECT (src, "we received a server message");
5261         break;
5262       case GST_RTSP_EINTR:
5263         /* we got interrupted, see what we have to do */
5264         goto interrupt;
5265       case GST_RTSP_ETIMEOUT:
5266         /* send keep-alive, ignore the result, a warning will be posted. */
5267         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
5268         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5269           goto interrupt;
5270         continue;
5271       case GST_RTSP_EEOF:
5272         /* server closed the connection. not very fatal for UDP, reconnect and
5273          * see what happens. */
5274         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5275             ("The server closed the connection."));
5276         if (src->udp_reconnect) {
5277           if ((res =
5278                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
5279             goto connect_error;
5280         } else {
5281           goto server_eof;
5282         }
5283         continue;
5284       case GST_RTSP_ENET:
5285         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
5286       default:
5287         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5288             ("Unhandled return value %d.", res));
5289         goto receive_error;
5290     }
5291
5292     switch (message.type) {
5293       case GST_RTSP_MESSAGE_REQUEST:
5294         /* server sends us a request message, handle it */
5295         res = gst_rtspsrc_handle_request (src, &src->conninfo, &message);
5296         if (res == GST_RTSP_EEOF)
5297           goto server_eof;
5298         else if (res < 0)
5299           goto handle_request_failed;
5300         break;
5301       case GST_RTSP_MESSAGE_RESPONSE:
5302         /* we ignore response and data messages */
5303         GST_DEBUG_OBJECT (src, "ignoring response message");
5304         DEBUG_RTSP (src, &message);
5305         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
5306           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
5307           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
5308             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
5309             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
5310               goto interrupt;
5311           }
5312         } else {
5313           retry = 0;
5314         }
5315         break;
5316       case GST_RTSP_MESSAGE_DATA:
5317         /* we ignore response and data messages */
5318         GST_DEBUG_OBJECT (src, "ignoring data message");
5319         break;
5320       default:
5321         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5322             message.type);
5323         break;
5324     }
5325   }
5326   g_assert_not_reached ();
5327
5328   /* we get here when the connection got interrupted */
5329 interrupt:
5330   {
5331     gst_rtsp_message_unset (&message);
5332     GST_DEBUG_OBJECT (src, "got interrupted");
5333     return GST_FLOW_FLUSHING;
5334   }
5335 connect_error:
5336   {
5337     gchar *str = gst_rtsp_strresult (res);
5338     GstFlowReturn ret;
5339
5340     src->conninfo.connected = FALSE;
5341     if (res != GST_RTSP_EINTR) {
5342       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5343           ("Could not connect to server. (%s)", str));
5344       g_free (str);
5345       ret = GST_FLOW_ERROR;
5346     } else {
5347       ret = GST_FLOW_FLUSHING;
5348     }
5349     return ret;
5350   }
5351 receive_error:
5352   {
5353     gchar *str = gst_rtsp_strresult (res);
5354
5355     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5356         ("Could not receive message. (%s)", str));
5357     g_free (str);
5358     return GST_FLOW_ERROR;
5359   }
5360 handle_request_failed:
5361   {
5362     gchar *str = gst_rtsp_strresult (res);
5363     GstFlowReturn ret;
5364
5365     gst_rtsp_message_unset (&message);
5366     if (res != GST_RTSP_EINTR) {
5367       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5368           ("Could not handle server message. (%s)", str));
5369       g_free (str);
5370       ret = GST_FLOW_ERROR;
5371     } else {
5372       ret = GST_FLOW_FLUSHING;
5373     }
5374     return ret;
5375   }
5376 server_eof:
5377   {
5378     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5379     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5380         ("The server closed the connection."));
5381     src->conninfo.connected = FALSE;
5382     gst_rtsp_message_unset (&message);
5383     return GST_FLOW_EOS;
5384   }
5385 }
5386
5387 static GstRTSPResult
5388 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
5389 {
5390   GstRTSPResult res = GST_RTSP_OK;
5391   gboolean restart;
5392
5393   GST_DEBUG_OBJECT (src, "doing reconnect");
5394
5395   GST_OBJECT_LOCK (src);
5396   /* only restart when the pads were not yet activated, else we were
5397    * streaming over UDP */
5398   restart = src->need_activate;
5399   GST_OBJECT_UNLOCK (src);
5400
5401   /* no need to restart, we're done */
5402   if (!restart)
5403     goto done;
5404
5405   /* we can try only TCP now */
5406   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
5407
5408   /* close and cleanup our state */
5409   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
5410     goto done;
5411
5412   /* see if we have TCP left to try. Also don't try TCP when we were configured
5413    * with an SDP. */
5414   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
5415     goto no_protocols;
5416
5417   /* We post a warning message now to inform the user
5418    * that nothing happened. It's most likely a firewall thing. */
5419   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5420       ("Could not receive any UDP packets for %.4f seconds, maybe your "
5421           "firewall is blocking it. Retrying using a tcp connection.",
5422           gst_guint64_to_gdouble (src->udp_timeout) / 1000000.0));
5423
5424   /* open new connection using tcp */
5425   if (gst_rtspsrc_open (src, async) < 0)
5426     goto open_failed;
5427
5428   /* start playback */
5429   if (gst_rtspsrc_play (src, &src->segment, async, NULL) < 0)
5430     goto play_failed;
5431
5432 done:
5433   return res;
5434
5435   /* ERRORS */
5436 no_protocols:
5437   {
5438     src->cur_protocols = 0;
5439     /* no transport possible, post an error and stop */
5440     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5441         ("Could not receive any UDP packets for %.4f seconds, maybe your "
5442             "firewall is blocking it. No other protocols to try.",
5443             gst_guint64_to_gdouble (src->udp_timeout) / 1000000.0));
5444     return GST_RTSP_ERROR;
5445   }
5446 open_failed:
5447   {
5448     GST_DEBUG_OBJECT (src, "open failed");
5449     return GST_RTSP_OK;
5450   }
5451 play_failed:
5452   {
5453     GST_DEBUG_OBJECT (src, "play failed");
5454     return GST_RTSP_OK;
5455   }
5456 }
5457
5458 static void
5459 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
5460 {
5461   switch (cmd) {
5462     case CMD_OPEN:
5463       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
5464       break;
5465     case CMD_PLAY:
5466       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
5467       break;
5468     case CMD_PAUSE:
5469       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
5470       break;
5471     case CMD_CLOSE:
5472       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
5473       break;
5474     default:
5475       break;
5476   }
5477 }
5478
5479 static void
5480 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
5481 {
5482   switch (cmd) {
5483     case CMD_OPEN:
5484       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
5485       break;
5486     case CMD_PLAY:
5487       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
5488       break;
5489     case CMD_PAUSE:
5490       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
5491       break;
5492     case CMD_CLOSE:
5493       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
5494       break;
5495     default:
5496       break;
5497   }
5498 }
5499
5500 static void
5501 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
5502 {
5503   switch (cmd) {
5504     case CMD_OPEN:
5505       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
5506       break;
5507     case CMD_PLAY:
5508       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
5509       break;
5510     case CMD_PAUSE:
5511       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
5512       break;
5513     case CMD_CLOSE:
5514       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
5515       break;
5516     default:
5517       break;
5518   }
5519 }
5520
5521 static void
5522 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
5523 {
5524   switch (cmd) {
5525     case CMD_OPEN:
5526       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
5527       break;
5528     case CMD_PLAY:
5529       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
5530       break;
5531     case CMD_PAUSE:
5532       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
5533       break;
5534     case CMD_CLOSE:
5535       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
5536       break;
5537     default:
5538       break;
5539   }
5540 }
5541
5542 static void
5543 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
5544 {
5545   if (ret == GST_RTSP_OK)
5546     gst_rtspsrc_loop_complete_cmd (src, cmd);
5547   else if (ret == GST_RTSP_EINTR)
5548     gst_rtspsrc_loop_cancel_cmd (src, cmd);
5549   else
5550     gst_rtspsrc_loop_error_cmd (src, cmd);
5551 }
5552
5553 static gboolean
5554 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
5555 {
5556   gint old;
5557   gboolean flushed = FALSE;
5558
5559   /* start new request */
5560   gst_rtspsrc_loop_start_cmd (src, cmd);
5561
5562   GST_DEBUG_OBJECT (src, "sending cmd %s", cmd_to_string (cmd));
5563
5564   GST_OBJECT_LOCK (src);
5565   old = src->pending_cmd;
5566   if (old == CMD_RECONNECT) {
5567     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
5568     cmd = CMD_RECONNECT;
5569   } else if (old == CMD_CLOSE) {
5570     /* our CMD_CLOSE might have interrutped CMD_LOOP. gst_rtspsrc_loop
5571      * will send a CMD_WAIT which would cancel our pending CMD_CLOSE (if
5572      * still pending). We just avoid it here by making sure CMD_CLOSE is
5573      * still the pending command. */
5574     GST_DEBUG_OBJECT (src, "ignore, we were closing");
5575     cmd = CMD_CLOSE;
5576   } else if (old != CMD_WAIT) {
5577     src->pending_cmd = CMD_WAIT;
5578     GST_OBJECT_UNLOCK (src);
5579     /* cancel previous request */
5580     GST_DEBUG_OBJECT (src, "cancel previous request %s", cmd_to_string (old));
5581     gst_rtspsrc_loop_cancel_cmd (src, old);
5582     GST_OBJECT_LOCK (src);
5583   }
5584   src->pending_cmd = cmd;
5585   /* interrupt if allowed */
5586   if (src->busy_cmd & mask) {
5587     GST_DEBUG_OBJECT (src, "connection flush busy %s",
5588         cmd_to_string (src->busy_cmd));
5589     gst_rtspsrc_connection_flush (src, TRUE);
5590     flushed = TRUE;
5591   } else {
5592     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
5593         cmd_to_string (src->busy_cmd));
5594   }
5595   if (src->task)
5596     gst_task_start (src->task);
5597   GST_OBJECT_UNLOCK (src);
5598
5599   return flushed;
5600 }
5601
5602 static gboolean
5603 gst_rtspsrc_loop (GstRTSPSrc * src)
5604 {
5605   GstFlowReturn ret;
5606
5607   if (!src->conninfo.connection || !src->conninfo.connected)
5608     goto no_connection;
5609
5610   if (src->interleaved)
5611     ret = gst_rtspsrc_loop_interleaved (src);
5612   else
5613     ret = gst_rtspsrc_loop_udp (src);
5614
5615   if (ret != GST_FLOW_OK)
5616     goto pause;
5617
5618   return TRUE;
5619
5620   /* ERRORS */
5621 no_connection:
5622   {
5623     GST_WARNING_OBJECT (src, "we are not connected");
5624     ret = GST_FLOW_FLUSHING;
5625     goto pause;
5626   }
5627 pause:
5628   {
5629     const gchar *reason = gst_flow_get_name (ret);
5630
5631     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
5632     src->running = FALSE;
5633     if (ret == GST_FLOW_EOS) {
5634       /* perform EOS logic */
5635       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5636         gst_element_post_message (GST_ELEMENT_CAST (src),
5637             gst_message_new_segment_done (GST_OBJECT_CAST (src),
5638                 src->segment.format, src->segment.position));
5639         gst_rtspsrc_push_event (src,
5640             gst_event_new_segment_done (src->segment.format,
5641                 src->segment.position));
5642       } else {
5643         gst_rtspsrc_push_event (src, gst_event_new_eos ());
5644       }
5645     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
5646       /* for fatal errors we post an error message, post the error before the
5647        * EOS so the app knows about the error first. */
5648       GST_ELEMENT_FLOW_ERROR (src, ret);
5649       gst_rtspsrc_push_event (src, gst_event_new_eos ());
5650     }
5651     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
5652     return FALSE;
5653   }
5654 }
5655
5656 #ifndef GST_DISABLE_GST_DEBUG
5657 static const gchar *
5658 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5659 {
5660   gint index = 0;
5661
5662   while (method != 0) {
5663     index++;
5664     method >>= 1;
5665   }
5666   switch (index) {
5667     case 0:
5668       return "None";
5669     case 1:
5670       return "Basic";
5671     case 2:
5672       return "Digest";
5673   }
5674
5675   return "Unknown";
5676 }
5677 #endif
5678
5679 /* Parse a WWW-Authenticate Response header and determine the
5680  * available authentication methods
5681  *
5682  * This code should also cope with the fact that each WWW-Authenticate
5683  * header can contain multiple challenge methods + tokens
5684  *
5685  * At the moment, for Basic auth, we just do a minimal check and don't
5686  * even parse out the realm */
5687 static void
5688 gst_rtspsrc_parse_auth_hdr (GstRTSPMessage * response,
5689     GstRTSPAuthMethod * methods, GstRTSPConnection * conn, gboolean * stale)
5690 {
5691   GstRTSPAuthCredential **credentials, **credential;
5692
5693   g_return_if_fail (response != NULL);
5694   g_return_if_fail (methods != NULL);
5695   g_return_if_fail (stale != NULL);
5696
5697   credentials =
5698       gst_rtsp_message_parse_auth_credentials (response,
5699       GST_RTSP_HDR_WWW_AUTHENTICATE);
5700   if (!credentials)
5701     return;
5702
5703   credential = credentials;
5704   while (*credential) {
5705     if ((*credential)->scheme == GST_RTSP_AUTH_BASIC) {
5706       *methods |= GST_RTSP_AUTH_BASIC;
5707     } else if ((*credential)->scheme == GST_RTSP_AUTH_DIGEST) {
5708       GstRTSPAuthParam **param = (*credential)->params;
5709
5710       *methods |= GST_RTSP_AUTH_DIGEST;
5711
5712       gst_rtsp_connection_clear_auth_params (conn);
5713       *stale = FALSE;
5714
5715       while (*param) {
5716         if (strcmp ((*param)->name, "stale") == 0
5717             && g_ascii_strcasecmp ((*param)->value, "TRUE") == 0)
5718           *stale = TRUE;
5719         gst_rtsp_connection_set_auth_param (conn, (*param)->name,
5720             (*param)->value);
5721         param++;
5722       }
5723     }
5724
5725     credential++;
5726   }
5727
5728   gst_rtsp_auth_credentials_free (credentials);
5729 }
5730
5731 /**
5732  * gst_rtspsrc_setup_auth:
5733  * @src: the rtsp source
5734  *
5735  * Configure a username and password and auth method on the
5736  * connection object based on a response we received from the
5737  * peer.
5738  *
5739  * Currently, this requires that a username and password were supplied
5740  * in the uri. In the future, they may be requested on demand by sending
5741  * a message up the bus.
5742  *
5743  * Returns: TRUE if authentication information could be set up correctly.
5744  */
5745 static gboolean
5746 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5747 {
5748   gchar *user = NULL;
5749   gchar *pass = NULL;
5750   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5751   GstRTSPAuthMethod method;
5752   GstRTSPResult auth_result;
5753   GstRTSPUrl *url;
5754   GstRTSPConnection *conn;
5755   gboolean stale = FALSE;
5756
5757   conn = src->conninfo.connection;
5758
5759   /* Identify the available auth methods and see if any are supported */
5760   gst_rtspsrc_parse_auth_hdr (response, &avail_methods, conn, &stale);
5761
5762   if (avail_methods == GST_RTSP_AUTH_NONE)
5763     goto no_auth_available;
5764
5765   /* For digest auth, if the response indicates that the session
5766    * data are stale, we just update them in the connection object and
5767    * return TRUE to retry the request */
5768   if (stale)
5769     src->tried_url_auth = FALSE;
5770
5771   url = gst_rtsp_connection_get_url (conn);
5772
5773   /* Do we have username and password available? */
5774   if (url != NULL && !src->tried_url_auth && url->user != NULL
5775       && url->passwd != NULL) {
5776     user = url->user;
5777     pass = url->passwd;
5778     src->tried_url_auth = TRUE;
5779     GST_DEBUG_OBJECT (src,
5780         "Attempting authentication using credentials from the URL");
5781   } else {
5782     user = src->user_id;
5783     pass = src->user_pw;
5784     GST_DEBUG_OBJECT (src,
5785         "Attempting authentication using credentials from the properties");
5786   }
5787
5788   /* FIXME: If the url didn't contain username and password or we tried them
5789    * already, request a username and passwd from the application via some kind
5790    * of credentials request message */
5791
5792   /* If we don't have a username and passwd at this point, bail out. */
5793   if (user == NULL || pass == NULL)
5794     goto no_user_pass;
5795
5796   /* Try to configure for each available authentication method, strongest to
5797    * weakest */
5798   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5799     /* Check if this method is available on the server */
5800     if ((method & avail_methods) == 0)
5801       continue;
5802
5803     /* Pass the credentials to the connection to try on the next request */
5804     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5805     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5806      * ignore it and end up retrying later */
5807     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5808       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5809           gst_rtsp_auth_method_to_string (method));
5810       break;
5811     }
5812   }
5813
5814   if (method == GST_RTSP_AUTH_NONE)
5815     goto no_auth_available;
5816
5817   return TRUE;
5818
5819 no_auth_available:
5820   {
5821     /* Output an error indicating that we couldn't connect because there were
5822      * no supported authentication protocols */
5823     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5824         ("No supported authentication protocol was found"));
5825     return FALSE;
5826   }
5827 no_user_pass:
5828   {
5829     /* We don't fire an error message, we just return FALSE and let the
5830      * normal NOT_AUTHORIZED error be propagated */
5831     return FALSE;
5832   }
5833 }
5834
5835 static GstRTSPResult
5836 gst_rtsp_src_receive_response (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
5837     GstRTSPMessage * response, GstRTSPStatusCode * code)
5838 {
5839   GstRTSPStatusCode thecode;
5840   gchar *content_base = NULL;
5841   GstRTSPResult res = gst_rtspsrc_connection_receive (src, conninfo,
5842       response, src->ptcp_timeout);
5843
5844   if (res < 0)
5845     goto receive_error;
5846
5847   DEBUG_RTSP (src, response);
5848
5849   switch (response->type) {
5850     case GST_RTSP_MESSAGE_REQUEST:
5851       res = gst_rtspsrc_handle_request (src, conninfo, response);
5852       if (res == GST_RTSP_EEOF)
5853         goto server_eof;
5854       else if (res < 0)
5855         goto handle_request_failed;
5856
5857       /* Not a response, receive next message */
5858       return gst_rtsp_src_receive_response (src, conninfo, response, code);
5859     case GST_RTSP_MESSAGE_RESPONSE:
5860       /* ok, a response is good */
5861       GST_DEBUG_OBJECT (src, "received response message");
5862       break;
5863     case GST_RTSP_MESSAGE_DATA:
5864       /* get next response */
5865       GST_DEBUG_OBJECT (src, "handle data response message");
5866       gst_rtspsrc_handle_data (src, response);
5867
5868       /* Not a response, receive next message */
5869       return gst_rtsp_src_receive_response (src, conninfo, response, code);
5870     default:
5871       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5872           response->type);
5873
5874       /* Not a response, receive next message */
5875       return gst_rtsp_src_receive_response (src, conninfo, response, code);
5876   }
5877
5878   thecode = response->type_data.response.code;
5879
5880   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5881
5882   /* if the caller wanted the result code, we store it. */
5883   if (code)
5884     *code = thecode;
5885
5886   /* If the request didn't succeed, bail out before doing any more */
5887   if (thecode != GST_RTSP_STS_OK)
5888     return GST_RTSP_OK;
5889
5890   /* store new content base if any */
5891   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5892       &content_base, 0);
5893   if (content_base) {
5894     g_free (src->content_base);
5895     src->content_base = g_strdup (content_base);
5896   }
5897
5898   return GST_RTSP_OK;
5899
5900   /* ERRORS */
5901 receive_error:
5902   {
5903     switch (res) {
5904       case GST_RTSP_EEOF:
5905         return GST_RTSP_EEOF;
5906       default:
5907       {
5908         gchar *str = gst_rtsp_strresult (res);
5909
5910         if (res != GST_RTSP_EINTR) {
5911           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5912               ("Could not receive message. (%s)", str));
5913         } else {
5914           GST_WARNING_OBJECT (src, "receive interrupted");
5915         }
5916         g_free (str);
5917         break;
5918       }
5919     }
5920     return res;
5921   }
5922 handle_request_failed:
5923   {
5924     /* ERROR was posted */
5925     gst_rtsp_message_unset (response);
5926     return res;
5927   }
5928 server_eof:
5929   {
5930     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5931     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5932         ("The server closed the connection."));
5933     gst_rtsp_message_unset (response);
5934     return res;
5935   }
5936 }
5937
5938
5939 static GstRTSPResult
5940 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
5941     GstRTSPMessage * request, GstRTSPMessage * response,
5942     GstRTSPStatusCode * code)
5943 {
5944   GstRTSPResult res;
5945   gint try = 0;
5946   gboolean allow_send = TRUE;
5947
5948 again:
5949   if (!src->short_header)
5950     gst_rtsp_ext_list_before_send (src->extensions, request);
5951
5952   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_BEFORE_SEND], 0,
5953       request, &allow_send);
5954   if (!allow_send) {
5955     GST_DEBUG_OBJECT (src, "skipping message, disabled by signal");
5956     return GST_RTSP_OK;
5957   }
5958
5959   GST_DEBUG_OBJECT (src, "sending message");
5960
5961   DEBUG_RTSP (src, request);
5962
5963   res = gst_rtspsrc_connection_send (src, conninfo, request, src->ptcp_timeout);
5964   if (res < 0)
5965     goto send_error;
5966
5967   gst_rtsp_connection_reset_timeout (conninfo->connection);
5968   if (!response)
5969     return res;
5970
5971   res = gst_rtsp_src_receive_response (src, conninfo, response, code);
5972   if (res == GST_RTSP_EEOF) {
5973     GST_WARNING_OBJECT (src, "server closed connection");
5974     /* only try once after reconnect, then fallthrough and error out */
5975     if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5976       try++;
5977       /* if reconnect succeeds, try again */
5978       if ((res = gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) == 0)
5979         goto again;
5980     }
5981   }
5982   gst_rtsp_ext_list_after_send (src->extensions, request, response);
5983
5984   return res;
5985
5986 send_error:
5987   {
5988     gchar *str = gst_rtsp_strresult (res);
5989
5990     if (res != GST_RTSP_EINTR) {
5991       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5992           ("Could not send message. (%s)", str));
5993     } else {
5994       GST_WARNING_OBJECT (src, "send interrupted");
5995     }
5996     g_free (str);
5997     return res;
5998   }
5999 }
6000
6001 /**
6002  * gst_rtspsrc_send:
6003  * @src: the rtsp source
6004  * @conninfo: the connection information to send on
6005  * @request: must point to a valid request
6006  * @response: must point to an empty #GstRTSPMessage
6007  * @code: an optional code result
6008  * @versions: List of versions to try, setting it back onto the @request message
6009  *            if not set, `src->version` will be used as RTSP version.
6010  *
6011  * send @request and retrieve the response in @response. optionally @code can be
6012  * non-NULL in which case it will contain the status code of the response.
6013  *
6014  * If This function returns #GST_RTSP_OK, @response will contain a valid response
6015  * message that should be cleaned with gst_rtsp_message_unset() after usage.
6016  *
6017  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
6018  * @response message) if the response code was not 200 (OK).
6019  *
6020  * If the attempt results in an authentication failure, then this will attempt
6021  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
6022  * the request.
6023  *
6024  * Returns: #GST_RTSP_OK if the processing was successful.
6025  */
6026 static GstRTSPResult
6027 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
6028     GstRTSPMessage * request, GstRTSPMessage * response,
6029     GstRTSPStatusCode * code, GstRTSPVersion * versions)
6030 {
6031   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
6032   GstRTSPResult res = GST_RTSP_ERROR;
6033   gint count;
6034   gboolean retry;
6035   GstRTSPMethod method = GST_RTSP_INVALID;
6036   gint version_retry = 0;
6037
6038   count = 0;
6039   do {
6040     retry = FALSE;
6041
6042     /* make sure we don't loop forever */
6043     if (count++ > 8)
6044       break;
6045
6046     /* save method so we can disable it when the server complains */
6047     method = request->type_data.request.method;
6048
6049     if (!versions)
6050       request->type_data.request.version = src->version;
6051
6052     if ((res =
6053             gst_rtspsrc_try_send (src, conninfo, request, response,
6054                 &int_code)) < 0)
6055       goto error;
6056
6057     switch (int_code) {
6058       case GST_RTSP_STS_UNAUTHORIZED:
6059       case GST_RTSP_STS_NOT_FOUND:
6060         if (gst_rtspsrc_setup_auth (src, response)) {
6061           /* Try the request/response again after configuring the auth info
6062            * and loop again */
6063           retry = TRUE;
6064         }
6065         break;
6066       case GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED:
6067         GST_INFO_OBJECT (src, "Version %s not supported by the server",
6068             versions ? gst_rtsp_version_as_text (versions[version_retry]) :
6069             "unknown");
6070         if (versions && versions[version_retry] != GST_RTSP_VERSION_INVALID) {
6071           GST_INFO_OBJECT (src, "Unsupported version %s => trying %s",
6072               gst_rtsp_version_as_text (request->type_data.request.version),
6073               gst_rtsp_version_as_text (versions[version_retry]));
6074           request->type_data.request.version = versions[version_retry];
6075           retry = TRUE;
6076           version_retry++;
6077           break;
6078         }
6079         /* falltrough */
6080       default:
6081         break;
6082     }
6083   } while (retry == TRUE);
6084
6085   /* If the user requested the code, let them handle errors, otherwise
6086    * post an error below */
6087   if (code != NULL)
6088     *code = int_code;
6089   else if (int_code != GST_RTSP_STS_OK)
6090     goto error_response;
6091
6092   return res;
6093
6094   /* ERRORS */
6095 error:
6096   {
6097     GST_DEBUG_OBJECT (src, "got error %d", res);
6098     return res;
6099   }
6100 error_response:
6101   {
6102     res = GST_RTSP_ERROR;
6103
6104     switch (response->type_data.response.code) {
6105       case GST_RTSP_STS_NOT_FOUND:
6106         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_FOUND,
6107             "Not found");
6108         break;
6109       case GST_RTSP_STS_UNAUTHORIZED:
6110         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_AUTHORIZED,
6111             "Unauthorized");
6112         break;
6113       case GST_RTSP_STS_MOVED_PERMANENTLY:
6114       case GST_RTSP_STS_MOVE_TEMPORARILY:
6115       {
6116         gchar *new_location;
6117         GstRTSPLowerTrans transports;
6118
6119         GST_DEBUG_OBJECT (src, "got redirection");
6120         /* if we don't have a Location Header, we must error */
6121         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
6122                 &new_location, 0) < 0)
6123           break;
6124
6125         /* When we receive a redirect result, we go back to the INIT state after
6126          * parsing the new URI. The caller should do the needed steps to issue
6127          * a new setup when it detects this state change. */
6128         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
6129
6130         /* save current transports */
6131         if (src->conninfo.url)
6132           transports = src->conninfo.url->transports;
6133         else
6134           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
6135
6136         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
6137
6138         /* set old transports */
6139         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
6140           src->conninfo.url->transports = transports;
6141
6142         src->need_redirect = TRUE;
6143         res = GST_RTSP_OK;
6144         break;
6145       }
6146       case GST_RTSP_STS_NOT_ACCEPTABLE:
6147       case GST_RTSP_STS_NOT_IMPLEMENTED:
6148       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
6149         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
6150             gst_rtsp_method_as_text (method));
6151         src->methods &= ~method;
6152         res = GST_RTSP_OK;
6153         break;
6154       default:
6155         RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, READ,
6156             "Unhandled error");
6157         break;
6158     }
6159     /* if we return ERROR we should unset the response ourselves */
6160     if (res == GST_RTSP_ERROR)
6161       gst_rtsp_message_unset (response);
6162
6163     return res;
6164   }
6165 }
6166
6167 static GstRTSPResult
6168 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
6169     GstRTSPMessage * response, GstRTSPSrc * src)
6170 {
6171   return gst_rtspsrc_send (src, &src->conninfo, request, response, NULL, NULL);
6172 }
6173
6174
6175 /* parse the response and collect all the supported methods. We need this
6176  * information so that we don't try to send an unsupported request to the
6177  * server.
6178  */
6179 static gboolean
6180 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
6181 {
6182   GstRTSPHeaderField field;
6183   gchar *respoptions;
6184   gint indx = 0;
6185
6186   /* reset supported methods */
6187   src->methods = 0;
6188
6189   /* Try Allow Header first */
6190   field = GST_RTSP_HDR_ALLOW;
6191   while (TRUE) {
6192     respoptions = NULL;
6193     gst_rtsp_message_get_header (response, field, &respoptions, indx);
6194     if (!respoptions)
6195       break;
6196
6197     src->methods |= gst_rtsp_options_from_text (respoptions);
6198
6199     indx++;
6200   }
6201
6202   indx = 0;
6203   field = GST_RTSP_HDR_PUBLIC;
6204   while (TRUE) {
6205     respoptions = NULL;
6206     gst_rtsp_message_get_header (response, field, &respoptions, indx);
6207     if (!respoptions)
6208       break;
6209
6210     src->methods |= gst_rtsp_options_from_text (respoptions);
6211
6212     indx++;
6213   }
6214
6215   if (src->methods == 0) {
6216     /* neither Allow nor Public are required, assume the server supports
6217      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
6218      * well. */
6219     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
6220     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
6221   }
6222   /* always assume PLAY, FIXME, extensions should be able to override
6223    * this */
6224   src->methods |= GST_RTSP_PLAY;
6225   /* also assume it will support Range */
6226   src->seekable = G_MAXFLOAT;
6227
6228   /* we need describe and setup */
6229   if (!(src->methods & GST_RTSP_DESCRIBE))
6230     goto no_describe;
6231   if (!(src->methods & GST_RTSP_SETUP))
6232     goto no_setup;
6233
6234   return TRUE;
6235
6236   /* ERRORS */
6237 no_describe:
6238   {
6239     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
6240         ("Server does not support DESCRIBE."));
6241     return FALSE;
6242   }
6243 no_setup:
6244   {
6245     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
6246         ("Server does not support SETUP."));
6247     return FALSE;
6248   }
6249 }
6250
6251 /* masks to be kept in sync with the hardcoded protocol order of preference
6252  * in code below */
6253 static const guint protocol_masks[] = {
6254   GST_RTSP_LOWER_TRANS_UDP,
6255   GST_RTSP_LOWER_TRANS_UDP_MCAST,
6256   GST_RTSP_LOWER_TRANS_TCP,
6257   0
6258 };
6259
6260 static GstRTSPResult
6261 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
6262     GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
6263 {
6264   GstRTSPResult res;
6265   GString *result;
6266   gboolean add_udp_str;
6267
6268   *transports = NULL;
6269
6270   res =
6271       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
6272
6273   if (res < 0)
6274     goto failed;
6275
6276   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
6277
6278   /* extension listed transports, use those */
6279   if (*transports != NULL)
6280     return GST_RTSP_OK;
6281
6282   /* it's the default */
6283   add_udp_str = FALSE;
6284
6285   /* the default RTSP transports */
6286   result = g_string_new ("RTP");
6287
6288   switch (profile) {
6289     case GST_RTSP_PROFILE_AVP:
6290       g_string_append (result, "/AVP");
6291       break;
6292     case GST_RTSP_PROFILE_SAVP:
6293       g_string_append (result, "/SAVP");
6294       break;
6295     case GST_RTSP_PROFILE_AVPF:
6296       g_string_append (result, "/AVPF");
6297       break;
6298     case GST_RTSP_PROFILE_SAVPF:
6299       g_string_append (result, "/SAVPF");
6300       break;
6301     default:
6302       break;
6303   }
6304
6305   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
6306     GST_DEBUG_OBJECT (src, "adding UDP unicast");
6307     if (add_udp_str)
6308       g_string_append (result, "/UDP");
6309     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
6310   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
6311     GST_DEBUG_OBJECT (src, "adding UDP multicast");
6312     /* we don't have to allocate any UDP ports yet, if the selected transport
6313      * turns out to be multicast we can create them and join the multicast
6314      * group indicated in the transport reply */
6315     if (add_udp_str)
6316       g_string_append (result, "/UDP");
6317     g_string_append (result, ";multicast");
6318     if (src->next_port_num != 0) {
6319       if (src->client_port_range.max > 0 &&
6320           src->next_port_num >= src->client_port_range.max)
6321         goto no_ports;
6322
6323       g_string_append_printf (result, ";client_port=%d-%d",
6324           src->next_port_num, src->next_port_num + 1);
6325     }
6326   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
6327     GST_DEBUG_OBJECT (src, "adding TCP");
6328
6329     g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
6330   }
6331   *transports = g_string_free (result, FALSE);
6332
6333   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
6334
6335   return GST_RTSP_OK;
6336
6337   /* ERRORS */
6338 failed:
6339   {
6340     GST_ERROR ("extension gave error %d", res);
6341     return res;
6342   }
6343 no_ports:
6344   {
6345     GST_ERROR ("no more ports available");
6346     return GST_RTSP_ERROR;
6347   }
6348 }
6349
6350 static GstRTSPResult
6351 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
6352     gint orig_rtpport, gint orig_rtcpport)
6353 {
6354   GstRTSPSrc *src;
6355   gint nr_udp, nr_int;
6356   gchar *next, *p;
6357   gint rtpport = 0, rtcpport = 0;
6358   GString *str;
6359
6360   src = stream->parent;
6361
6362   /* find number of placeholders first */
6363   if (strstr (*transports, "%%i2"))
6364     nr_int = 2;
6365   else if (strstr (*transports, "%%i1"))
6366     nr_int = 1;
6367   else
6368     nr_int = 0;
6369
6370   if (strstr (*transports, "%%u2"))
6371     nr_udp = 2;
6372   else if (strstr (*transports, "%%u1"))
6373     nr_udp = 1;
6374   else
6375     nr_udp = 0;
6376
6377   if (nr_udp == 0 && nr_int == 0)
6378     goto done;
6379
6380   if (nr_udp > 0) {
6381     if (!orig_rtpport || !orig_rtcpport) {
6382       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
6383         goto failed;
6384     } else {
6385       rtpport = orig_rtpport;
6386       rtcpport = orig_rtcpport;
6387     }
6388   }
6389
6390   str = g_string_new ("");
6391   p = *transports;
6392   while ((next = strstr (p, "%%"))) {
6393     g_string_append_len (str, p, next - p);
6394     if (next[2] == 'u') {
6395       if (next[3] == '1')
6396         g_string_append_printf (str, "%d", rtpport);
6397       else if (next[3] == '2')
6398         g_string_append_printf (str, "%d", rtcpport);
6399     }
6400     if (next[2] == 'i') {
6401       if (next[3] == '1')
6402         g_string_append_printf (str, "%d", src->free_channel);
6403       else if (next[3] == '2')
6404         g_string_append_printf (str, "%d", src->free_channel + 1);
6405
6406     }
6407
6408     p = next + 4;
6409   }
6410   if (src->version >= GST_RTSP_VERSION_2_0)
6411     src->free_channel += 2;
6412
6413   /* append final part */
6414   g_string_append (str, p);
6415
6416   g_free (*transports);
6417   *transports = g_string_free (str, FALSE);
6418
6419 done:
6420   return GST_RTSP_OK;
6421
6422   /* ERRORS */
6423 failed:
6424   {
6425     GST_ERROR ("failed to allocate udp ports");
6426     return GST_RTSP_ERROR;
6427   }
6428 }
6429
6430 static GstCaps *
6431 signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
6432 {
6433   GstCaps *caps = NULL;
6434
6435   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
6436       stream->id, &caps);
6437
6438   if (caps != NULL)
6439     GST_DEBUG_OBJECT (src, "SRTP parameters received");
6440
6441   return caps;
6442 }
6443
6444 static GstCaps *
6445 default_srtcp_params (void)
6446 {
6447   guint i;
6448   GstCaps *caps;
6449   GstBuffer *buf;
6450   guint8 *key_data;
6451 #define KEY_SIZE 30
6452   guint data_size = GST_ROUND_UP_4 (KEY_SIZE);
6453
6454   /* create a random key */
6455   key_data = g_malloc (data_size);
6456   for (i = 0; i < data_size; i += 4)
6457     GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
6458
6459   buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
6460
6461   caps = gst_caps_new_simple ("application/x-srtcp",
6462       "srtp-key", GST_TYPE_BUFFER, buf,
6463       "srtp-cipher", G_TYPE_STRING, "aes-128-icm",
6464       "srtp-auth", G_TYPE_STRING, "hmac-sha1-80",
6465       "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
6466       "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
6467
6468   gst_buffer_unref (buf);
6469
6470   return caps;
6471 }
6472
6473 static gchar *
6474 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
6475 {
6476   gchar *base64, *result = NULL;
6477   GstMIKEYMessage *mikey_msg;
6478
6479   stream->srtcpparams = signal_get_srtcp_params (src, stream);
6480   if (stream->srtcpparams == NULL)
6481     stream->srtcpparams = default_srtcp_params ();
6482
6483   mikey_msg = gst_mikey_message_new_from_caps (stream->srtcpparams);
6484   if (mikey_msg) {
6485     /* add policy '0' for our SSRC */
6486     gst_mikey_message_add_cs_srtp (mikey_msg, 0, stream->send_ssrc, 0);
6487
6488     base64 = gst_mikey_message_base64_encode (mikey_msg);
6489     gst_mikey_message_unref (mikey_msg);
6490
6491     if (base64) {
6492       result = gst_sdp_make_keymgmt (stream->conninfo.location, base64);
6493       g_free (base64);
6494     }
6495   }
6496
6497   return result;
6498 }
6499
6500 static GstRTSPResult
6501 gst_rtsp_src_setup_stream_from_response (GstRTSPSrc * src,
6502     GstRTSPStream * stream, GstRTSPMessage * response,
6503     GstRTSPLowerTrans * protocols, gint retry, gint * rtpport, gint * rtcpport)
6504 {
6505   gchar *resptrans = NULL;
6506   GstRTSPTransport transport = { 0 };
6507
6508   gst_rtsp_message_get_header (response, GST_RTSP_HDR_TRANSPORT, &resptrans, 0);
6509   if (!resptrans) {
6510     gst_rtspsrc_stream_free_udp (stream);
6511     goto no_transport;
6512   }
6513
6514   /* parse transport, go to next stream on parse error */
6515   if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6516     GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6517     return GST_RTSP_ELAST;
6518   }
6519
6520   /* update allowed transports for other streams. once the transport of
6521    * one stream has been determined, we make sure that all other streams
6522    * are configured in the same way */
6523   switch (transport.lower_transport) {
6524     case GST_RTSP_LOWER_TRANS_TCP:
6525       GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6526       if (protocols)
6527         *protocols = GST_RTSP_LOWER_TRANS_TCP;
6528       src->interleaved = TRUE;
6529       if (src->version < GST_RTSP_VERSION_2_0) {
6530         /* update free channels */
6531         src->free_channel = MAX (transport.interleaved.min, src->free_channel);
6532         src->free_channel = MAX (transport.interleaved.max, src->free_channel);
6533         src->free_channel++;
6534       }
6535       break;
6536     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6537       /* only allow multicast for other streams */
6538       GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6539       if (protocols)
6540         *protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6541       /* if the server selected our ports, increment our counters so that
6542        * we select a new port later */
6543       if (src->next_port_num == transport.port.min &&
6544           src->next_port_num + 1 == transport.port.max) {
6545         src->next_port_num += 2;
6546       }
6547       break;
6548     case GST_RTSP_LOWER_TRANS_UDP:
6549       /* only allow unicast for other streams */
6550       GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6551       if (protocols)
6552         *protocols = GST_RTSP_LOWER_TRANS_UDP;
6553       break;
6554     default:
6555       GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6556           transport.lower_transport);
6557       break;
6558   }
6559
6560   if (!src->interleaved || !retry) {
6561     /* now configure the stream with the selected transport */
6562     if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6563       GST_DEBUG_OBJECT (src,
6564           "could not configure stream %p transport, skipping stream", stream);
6565       goto done;
6566     } else if (stream->udpsrc[0] && stream->udpsrc[1] && rtpport && rtcpport) {
6567       /* retain the first allocated UDP port pair */
6568       g_object_get (G_OBJECT (stream->udpsrc[0]), "port", rtpport, NULL);
6569       g_object_get (G_OBJECT (stream->udpsrc[1]), "port", rtcpport, NULL);
6570     }
6571   }
6572   /* we need to activate at least one stream when we detect activity */
6573   src->need_activate = TRUE;
6574
6575   /* stream is setup now */
6576   stream->setup = TRUE;
6577   stream->waiting_setup_response = FALSE;
6578
6579   if (src->version >= GST_RTSP_VERSION_2_0) {
6580     gchar *prop, *media_properties;
6581     gchar **props;
6582     gint i;
6583
6584     if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_MEDIA_PROPERTIES,
6585             &media_properties, 0) != GST_RTSP_OK) {
6586       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6587           ("Error: No MEDIA_PROPERTY header in a SETUP request in RTSP 2.0"
6588               " - this header is mandatory."));
6589
6590       gst_rtsp_message_unset (response);
6591       return GST_RTSP_ERROR;
6592     }
6593
6594     props = g_strsplit (media_properties, ",", -2);
6595     for (i = 0; props[i]; i++) {
6596       prop = props[i];
6597
6598       while (*prop == ' ')
6599         prop++;
6600
6601       if (strstr (prop, "Random-Access")) {
6602         gchar **random_seekable_val = g_strsplit (prop, "=", 2);
6603
6604         if (!random_seekable_val[1])
6605           src->seekable = G_MAXFLOAT;
6606         else
6607           src->seekable = g_ascii_strtod (random_seekable_val[1], NULL);
6608
6609         g_strfreev (random_seekable_val);
6610       } else if (!g_strcmp0 (prop, "No-Seeking")) {
6611         src->seekable = -1.0;
6612       } else if (!g_strcmp0 (prop, "Beginning-Only")) {
6613         src->seekable = 0.0;
6614       }
6615     }
6616
6617     g_strfreev (props);
6618   }
6619
6620 done:
6621   /* clean up our transport struct */
6622   gst_rtsp_transport_init (&transport);
6623   /* clean up used RTSP messages */
6624   gst_rtsp_message_unset (response);
6625
6626   return GST_RTSP_OK;
6627
6628 no_transport:
6629   {
6630     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6631         ("Server did not select transport."));
6632
6633     gst_rtsp_message_unset (response);
6634     return GST_RTSP_ERROR;
6635   }
6636 }
6637
6638 static GstRTSPResult
6639 gst_rtspsrc_setup_streams_end (GstRTSPSrc * src, gboolean async)
6640 {
6641   GList *tmp;
6642   GstRTSPConnInfo *conninfo;
6643
6644   g_assert (src->version >= GST_RTSP_VERSION_2_0);
6645
6646   conninfo = &src->conninfo;
6647   for (tmp = src->streams; tmp; tmp = tmp->next) {
6648     GstRTSPStream *stream = (GstRTSPStream *) tmp->data;
6649     GstRTSPMessage response = { 0, };
6650
6651     if (!stream->waiting_setup_response)
6652       continue;
6653
6654     if (!src->conninfo.connection)
6655       conninfo = &((GstRTSPStream *) tmp->data)->conninfo;
6656
6657     gst_rtsp_src_receive_response (src, conninfo, &response, NULL);
6658
6659     gst_rtsp_src_setup_stream_from_response (src, stream,
6660         &response, NULL, 0, NULL, NULL);
6661   }
6662
6663   return GST_RTSP_OK;
6664 }
6665
6666 /* Perform the SETUP request for all the streams.
6667  *
6668  * We ask the server for a specific transport, which initially includes all the
6669  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6670  * two local UDP ports that we send to the server.
6671  *
6672  * Once the server replied with a transport, we configure the other streams
6673  * with the same transport.
6674  *
6675  * In case setup request are not pipelined, this function will also configure the
6676  * stream for the selected transport, * which basically means creating the pipeline.
6677  * Otherwise, the first stream is setup right away from the reply and a
6678  * CMD_FINALIZE_SETUP command is set for the stream pipelines to happen on the
6679  * remaining streams from the RTSP thread.
6680  */
6681 static GstRTSPResult
6682 gst_rtspsrc_setup_streams_start (GstRTSPSrc * src, gboolean async)
6683 {
6684   GList *walk;
6685   GstRTSPResult res = GST_RTSP_ERROR;
6686   GstRTSPMessage request = { 0 };
6687   GstRTSPMessage response = { 0 };
6688   GstRTSPStream *stream = NULL;
6689   GstRTSPLowerTrans protocols;
6690   GstRTSPStatusCode code;
6691   gboolean unsupported_real = FALSE;
6692   gint rtpport, rtcpport;
6693   GstRTSPUrl *url;
6694   gchar *hval;
6695   gchar *pipelined_request_id = NULL;
6696
6697   if (src->conninfo.connection) {
6698     url = gst_rtsp_connection_get_url (src->conninfo.connection);
6699     /* we initially allow all configured lower transports. based on the URL
6700      * transports and the replies from the server we narrow them down. */
6701     protocols = url->transports & src->cur_protocols;
6702   } else {
6703     url = NULL;
6704     protocols = src->cur_protocols;
6705   }
6706
6707   if (protocols == 0)
6708     goto no_protocols;
6709
6710   /* reset some state */
6711   src->free_channel = 0;
6712   src->interleaved = FALSE;
6713   src->need_activate = FALSE;
6714   /* keep track of next port number, 0 is random */
6715   src->next_port_num = src->client_port_range.min;
6716   rtpport = rtcpport = 0;
6717
6718   if (G_UNLIKELY (src->streams == NULL))
6719     goto no_streams;
6720
6721   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6722     GstRTSPConnInfo *conninfo;
6723     gchar *transports;
6724     gint retry = 0;
6725     guint mask = 0;
6726     gboolean selected;
6727     GstCaps *caps;
6728
6729     stream = (GstRTSPStream *) walk->data;
6730
6731     caps = stream_get_caps_for_pt (stream, stream->default_pt);
6732     if (caps == NULL) {
6733       GST_WARNING_OBJECT (src, "skipping stream %p, no caps", stream);
6734       continue;
6735     }
6736
6737     if (stream->skipped) {
6738       GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6739       continue;
6740     }
6741
6742     /* see if we need to configure this stream */
6743     if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6744       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6745           stream);
6746       continue;
6747     }
6748
6749     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6750         stream->id, caps, &selected);
6751     if (!selected) {
6752       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6753       continue;
6754     }
6755
6756     /* merge/overwrite global caps */
6757     if (caps) {
6758       guint j, num;
6759       GstStructure *s;
6760
6761       s = gst_caps_get_structure (caps, 0);
6762
6763       num = gst_structure_n_fields (src->props);
6764       for (j = 0; j < num; j++) {
6765         const gchar *name;
6766         const GValue *val;
6767
6768         name = gst_structure_nth_field_name (src->props, j);
6769         val = gst_structure_get_value (src->props, name);
6770         gst_structure_set_value (s, name, val);
6771
6772         GST_DEBUG_OBJECT (src, "copied %s", name);
6773       }
6774     }
6775
6776     /* skip setup if we have no URL for it */
6777     if (stream->conninfo.location == NULL) {
6778       GST_WARNING_OBJECT (src, "skipping stream %p, no setup", stream);
6779       continue;
6780     }
6781
6782     if (src->conninfo.connection == NULL) {
6783       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6784         GST_WARNING_OBJECT (src, "skipping stream %p, failed to connect",
6785             stream);
6786         continue;
6787       }
6788       conninfo = &stream->conninfo;
6789     } else {
6790       conninfo = &src->conninfo;
6791     }
6792     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6793         stream->conninfo.location);
6794
6795     /* if we have a multicast connection, only suggest multicast from now on */
6796     if (stream->is_multicast)
6797       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6798
6799   next_protocol:
6800     /* first selectable protocol */
6801     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6802       mask++;
6803     if (!protocol_masks[mask])
6804       goto no_protocols;
6805
6806   retry:
6807     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6808         protocol_masks[mask]);
6809     /* create a string with first transport in line */
6810     transports = NULL;
6811     res = gst_rtspsrc_create_transports_string (src,
6812         protocols & protocol_masks[mask], stream->profile, &transports);
6813     if (res < 0 || transports == NULL)
6814       goto setup_transport_failed;
6815
6816     if (strlen (transports) == 0) {
6817       g_free (transports);
6818       GST_DEBUG_OBJECT (src, "no transports found");
6819       mask++;
6820       goto next_protocol;
6821     }
6822
6823     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6824
6825     /* replace placeholders with real values, this function will optionally
6826      * allocate UDP ports and other info needed to execute the setup request */
6827     res = gst_rtspsrc_prepare_transports (stream, &transports,
6828         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6829     if (res < 0) {
6830       g_free (transports);
6831       goto setup_transport_failed;
6832     }
6833
6834     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6835     /* create SETUP request */
6836     res =
6837         gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
6838         stream->conninfo.location);
6839     if (res < 0) {
6840       g_free (transports);
6841       goto create_request_failed;
6842     }
6843
6844     if (src->version >= GST_RTSP_VERSION_2_0) {
6845       if (!pipelined_request_id)
6846         pipelined_request_id = g_strdup_printf ("%d",
6847             g_random_int_range (0, G_MAXINT32));
6848
6849       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_PIPELINED_REQUESTS,
6850           pipelined_request_id);
6851       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT_RANGES,
6852           "npt, clock, smpte, clock");
6853     }
6854
6855     /* select transport */
6856     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6857
6858     if (stream->is_backchannel && src->backchannel == BACKCHANNEL_ONVIF)
6859       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_REQUIRE,
6860           BACKCHANNEL_ONVIF_HDR_REQUIRE_VAL);
6861
6862     /* set up keys */
6863     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6864         stream->profile == GST_RTSP_PROFILE_SAVPF) {
6865       hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6866       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6867     }
6868
6869     /* if the user wants a non default RTP packet size we add the blocksize
6870      * parameter */
6871     if (src->rtp_blocksize > 0) {
6872       hval = g_strdup_printf ("%d", src->rtp_blocksize);
6873       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6874     }
6875
6876     if (async)
6877       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6878               stream->id));
6879
6880     /* handle the code ourselves */
6881     res =
6882         gst_rtspsrc_send (src, conninfo, &request,
6883         pipelined_request_id ? NULL : &response, &code, NULL);
6884     if (res < 0)
6885       goto send_error;
6886
6887     switch (code) {
6888       case GST_RTSP_STS_OK:
6889         break;
6890       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6891         gst_rtsp_message_unset (&request);
6892         gst_rtsp_message_unset (&response);
6893         /* cleanup of leftover transport */
6894         gst_rtspsrc_stream_free_udp (stream);
6895         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6896          * we might be in this case */
6897         if (stream->container && rtpport && rtcpport && !retry) {
6898           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6899               rtpport, rtcpport);
6900           retry++;
6901           goto retry;
6902         }
6903         /* this transport did not go down well, but we may have others to try
6904          * that we did not send yet, try those and only give up then
6905          * but not without checking for lost cause/extension so we can
6906          * post a nicer/more useful error message later */
6907         if (!unsupported_real)
6908           unsupported_real = stream->is_real;
6909         /* select next available protocol, give up on this stream if none */
6910         mask++;
6911         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6912           mask++;
6913         if (!protocol_masks[mask] || unsupported_real)
6914           continue;
6915         else
6916           goto retry;
6917       default:
6918         /* cleanup of leftover transport and move to the next stream */
6919         gst_rtspsrc_stream_free_udp (stream);
6920         goto response_error;
6921     }
6922
6923
6924     if (!pipelined_request_id) {
6925       /* parse response transport */
6926       res = gst_rtsp_src_setup_stream_from_response (src, stream,
6927           &response, &protocols, retry, &rtpport, &rtcpport);
6928       switch (res) {
6929         case GST_RTSP_ERROR:
6930           goto cleanup_error;
6931         case GST_RTSP_ELAST:
6932           goto retry;
6933         default:
6934           break;
6935       }
6936     } else {
6937       stream->waiting_setup_response = TRUE;
6938       /* we need to activate at least one stream when we detect activity */
6939       src->need_activate = TRUE;
6940     }
6941
6942     {
6943       GList *skip = walk;
6944
6945       while (TRUE) {
6946         GstRTSPStream *sskip;
6947
6948         skip = g_list_next (skip);
6949         if (skip == NULL)
6950           break;
6951
6952         sskip = (GstRTSPStream *) skip->data;
6953
6954         /* skip all streams with the same control url */
6955         if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6956           GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6957               sskip, sskip->conninfo.location);
6958           sskip->skipped = TRUE;
6959         }
6960       }
6961     }
6962     gst_rtsp_message_unset (&request);
6963   }
6964
6965   if (pipelined_request_id) {
6966     gst_rtspsrc_setup_streams_end (src, TRUE);
6967   }
6968
6969   /* store the transport protocol that was configured */
6970   src->cur_protocols = protocols;
6971
6972   gst_rtsp_ext_list_stream_select (src->extensions, url);
6973
6974   if (pipelined_request_id)
6975     g_free (pipelined_request_id);
6976
6977   /* if there is nothing to activate, error out */
6978   if (!src->need_activate)
6979     goto nothing_to_activate;
6980
6981   return res;
6982
6983   /* ERRORS */
6984 no_protocols:
6985   {
6986     /* no transport possible, post an error and stop */
6987     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6988         ("Could not connect to server, no protocols left"));
6989     return GST_RTSP_ERROR;
6990   }
6991 no_streams:
6992   {
6993     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6994         ("SDP contains no streams"));
6995     return GST_RTSP_ERROR;
6996   }
6997 create_request_failed:
6998   {
6999     gchar *str = gst_rtsp_strresult (res);
7000
7001     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7002         ("Could not create request. (%s)", str));
7003     g_free (str);
7004     goto cleanup_error;
7005   }
7006 setup_transport_failed:
7007   {
7008     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7009         ("Could not setup transport."));
7010     res = GST_RTSP_ERROR;
7011     goto cleanup_error;
7012   }
7013 response_error:
7014   {
7015     const gchar *str = gst_rtsp_status_as_text (code);
7016
7017     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7018         ("Error (%d): %s", code, GST_STR_NULL (str)));
7019     res = GST_RTSP_ERROR;
7020     goto cleanup_error;
7021   }
7022 send_error:
7023   {
7024     gchar *str = gst_rtsp_strresult (res);
7025
7026     if (res != GST_RTSP_EINTR) {
7027       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7028           ("Could not send message. (%s)", str));
7029     } else {
7030       GST_WARNING_OBJECT (src, "send interrupted");
7031     }
7032     g_free (str);
7033     goto cleanup_error;
7034   }
7035 nothing_to_activate:
7036   {
7037     /* none of the available error codes is really right .. */
7038     if (unsupported_real) {
7039       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
7040           (_("No supported stream was found. You might need to install a "
7041                   "GStreamer RTSP extension plugin for Real media streams.")),
7042           (NULL));
7043     } else {
7044       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
7045           (_("No supported stream was found. You might need to allow "
7046                   "more transport protocols or may otherwise be missing "
7047                   "the right GStreamer RTSP extension plugin.")), (NULL));
7048     }
7049     return GST_RTSP_ERROR;
7050   }
7051 cleanup_error:
7052   {
7053     if (pipelined_request_id)
7054       g_free (pipelined_request_id);
7055     gst_rtsp_message_unset (&request);
7056     gst_rtsp_message_unset (&response);
7057     return res;
7058   }
7059 }
7060
7061 static gboolean
7062 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
7063     GstSegment * segment)
7064 {
7065   gint64 seconds;
7066   GstRTSPTimeRange *therange;
7067
7068   if (src->range)
7069     gst_rtsp_range_free (src->range);
7070
7071   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
7072     GST_DEBUG_OBJECT (src, "parsed range %s", range);
7073     src->range = therange;
7074   } else {
7075     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
7076     src->range = NULL;
7077     gst_segment_init (segment, GST_FORMAT_TIME);
7078     return FALSE;
7079   }
7080
7081   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
7082       therange->min.type, therange->min.seconds, therange->max.type,
7083       therange->max.seconds);
7084
7085   if (therange->min.type == GST_RTSP_TIME_NOW)
7086     seconds = 0;
7087   else if (therange->min.type == GST_RTSP_TIME_END)
7088     seconds = 0;
7089   else
7090     seconds = therange->min.seconds * GST_SECOND;
7091
7092   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
7093       GST_TIME_ARGS (seconds));
7094
7095   /* we need to start playback without clipping from the position reported by
7096    * the server */
7097   segment->start = seconds;
7098   segment->position = seconds;
7099
7100   if (therange->max.type == GST_RTSP_TIME_NOW)
7101     seconds = -1;
7102   else if (therange->max.type == GST_RTSP_TIME_END)
7103     seconds = -1;
7104   else
7105     seconds = therange->max.seconds * GST_SECOND;
7106
7107   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
7108       GST_TIME_ARGS (seconds));
7109
7110   /* live (WMS) server might send overflowed large max as its idea of infinity,
7111    * compensate to prevent problems later on */
7112   if (seconds != -1 && seconds < 0) {
7113     seconds = -1;
7114     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
7115   }
7116
7117   /* live (WMS) might send min == max, which is not worth recording */
7118   if (segment->duration == -1 && seconds == segment->start)
7119     seconds = -1;
7120
7121   /* don't change duration with unknown value, we might have a valid value
7122    * there that we want to keep. */
7123   if (seconds != -1)
7124     segment->duration = seconds;
7125
7126   return TRUE;
7127 }
7128
7129 /* Parse clock profived by the server with following syntax:
7130  *
7131  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
7132  */
7133 static gboolean
7134 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
7135 {
7136   gboolean res = FALSE;
7137
7138   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
7139     gchar **fields = NULL, **parts = NULL;
7140     gchar *remote_ip, *str;
7141     gint port;
7142     GstClockTime base_time;
7143     GstClock *netclock;
7144
7145     fields = g_strsplit (gstclock, " ", 0);
7146
7147     /* wrapped clock, not very interesting for now */
7148     if (fields[1] == NULL)
7149       goto cleanup;
7150
7151     /* remote IP address and port */
7152     if ((str = fields[2]) == NULL)
7153       goto cleanup;
7154
7155     parts = g_strsplit (str, ":", 0);
7156
7157     if ((remote_ip = parts[0]) == NULL)
7158       goto cleanup;
7159
7160     if ((str = parts[1]) == NULL)
7161       goto cleanup;
7162
7163     port = atoi (str);
7164     if (port == 0)
7165       goto cleanup;
7166
7167     /* base-time */
7168     if ((str = fields[3]) == NULL)
7169       goto cleanup;
7170
7171     base_time = g_ascii_strtoull (str, NULL, 10);
7172
7173     netclock =
7174         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
7175         base_time);
7176
7177     if (src->provided_clock)
7178       gst_object_unref (src->provided_clock);
7179     src->provided_clock = netclock;
7180
7181     gst_element_post_message (GST_ELEMENT_CAST (src),
7182         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
7183             src->provided_clock, TRUE));
7184
7185     res = TRUE;
7186   cleanup:
7187     g_strfreev (fields);
7188     g_strfreev (parts);
7189   }
7190   return res;
7191 }
7192
7193 /* must be called with the RTSP state lock */
7194 static GstRTSPResult
7195 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
7196     gboolean async)
7197 {
7198   GstRTSPResult res;
7199   gint i, n_streams;
7200
7201   /* prepare global stream caps properties */
7202   if (src->props)
7203     gst_structure_remove_all_fields (src->props);
7204   else
7205     src->props = gst_structure_new_empty ("RTSPProperties");
7206
7207   DEBUG_SDP (src, sdp);
7208
7209   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
7210
7211   /* let the app inspect and change the SDP */
7212   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
7213
7214   gst_segment_init (&src->segment, GST_FORMAT_TIME);
7215
7216   /* parse range for duration reporting. */
7217   {
7218     const gchar *range;
7219
7220     for (i = 0;; i++) {
7221       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
7222       if (range == NULL)
7223         break;
7224
7225       /* keep track of the range and configure it in the segment */
7226       if (gst_rtspsrc_parse_range (src, range, &src->segment))
7227         break;
7228     }
7229   }
7230   /* parse clock information. This is GStreamer specific, a server can tell the
7231    * client what clock it is using and wrap that in a network clock. The
7232    * advantage of that is that we can slave to it. */
7233   {
7234     const gchar *gstclock;
7235
7236     for (i = 0;; i++) {
7237       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
7238       if (gstclock == NULL)
7239         break;
7240
7241       /* parse the clock and expose it in the provide_clock method */
7242       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
7243         break;
7244     }
7245   }
7246   /* try to find a global control attribute. Note that a '*' means that we should
7247    * do aggregate control with the current url (so we don't do anything and
7248    * leave the current connection as is) */
7249   {
7250     const gchar *control;
7251
7252     for (i = 0;; i++) {
7253       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
7254       if (control == NULL)
7255         break;
7256
7257       /* only take fully qualified urls */
7258       if (g_str_has_prefix (control, "rtsp://"))
7259         break;
7260     }
7261     if (control) {
7262       g_free (src->conninfo.location);
7263       src->conninfo.location = g_strdup (control);
7264       /* make a connection for this, if there was a connection already, nothing
7265        * happens. */
7266       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
7267         GST_ERROR_OBJECT (src, "could not connect");
7268       }
7269     }
7270     /* we need to keep the control url separate from the connection url because
7271      * the rules for constructing the media control url need it */
7272     g_free (src->control);
7273     src->control = g_strdup (control);
7274   }
7275
7276   /* create streams */
7277   n_streams = gst_sdp_message_medias_len (sdp);
7278   for (i = 0; i < n_streams; i++) {
7279     gst_rtspsrc_create_stream (src, sdp, i, n_streams);
7280   }
7281
7282   src->state = GST_RTSP_STATE_INIT;
7283
7284   /* setup streams */
7285   if ((res = gst_rtspsrc_setup_streams_start (src, async)) < 0)
7286     goto setup_failed;
7287
7288   /* reset our state */
7289   src->need_range = TRUE;
7290   src->skip = FALSE;
7291
7292   src->state = GST_RTSP_STATE_READY;
7293
7294   return res;
7295
7296   /* ERRORS */
7297 setup_failed:
7298   {
7299     GST_ERROR_OBJECT (src, "setup failed");
7300     gst_rtspsrc_cleanup (src);
7301     return res;
7302   }
7303 }
7304
7305 static GstRTSPResult
7306 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
7307     gboolean async)
7308 {
7309   GstRTSPResult res;
7310   GstRTSPMessage request = { 0 };
7311   GstRTSPMessage response = { 0 };
7312   guint8 *data;
7313   guint size;
7314   gchar *respcont = NULL;
7315   GstRTSPVersion versions[] =
7316       { GST_RTSP_VERSION_2_0, GST_RTSP_VERSION_INVALID };
7317
7318   src->version = src->default_version;
7319   if (src->default_version == GST_RTSP_VERSION_2_0) {
7320     versions[0] = GST_RTSP_VERSION_1_0;
7321   }
7322
7323 restart:
7324   src->need_redirect = FALSE;
7325
7326   /* can't continue without a valid url */
7327   if (G_UNLIKELY (src->conninfo.url == NULL)) {
7328     res = GST_RTSP_EINVAL;
7329     goto no_url;
7330   }
7331   src->tried_url_auth = FALSE;
7332
7333   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
7334     goto connect_failed;
7335
7336   /* create OPTIONS */
7337   GST_DEBUG_OBJECT (src, "create options... (%s)", async ? "async" : "sync");
7338   res =
7339       gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
7340       src->conninfo.url_str);
7341   if (res < 0)
7342     goto create_request_failed;
7343
7344   /* send OPTIONS */
7345   request.type_data.request.version = src->version;
7346   GST_DEBUG_OBJECT (src, "send options...");
7347
7348   if (async)
7349     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
7350
7351   if ((res =
7352           gst_rtspsrc_send (src, &src->conninfo, &request, &response,
7353               NULL, versions)) < 0) {
7354     goto send_error;
7355   }
7356
7357   src->version = request.type_data.request.version;
7358   GST_INFO_OBJECT (src, "Now using version: %s",
7359       gst_rtsp_version_as_text (src->version));
7360
7361   /* parse OPTIONS */
7362   if (!gst_rtspsrc_parse_methods (src, &response))
7363     goto methods_error;
7364
7365   /* create DESCRIBE */
7366   GST_DEBUG_OBJECT (src, "create describe...");
7367   res =
7368       gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
7369       src->conninfo.url_str);
7370   if (res < 0)
7371     goto create_request_failed;
7372
7373   /* we only accept SDP for now */
7374   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
7375       "application/sdp");
7376
7377   if (src->backchannel == BACKCHANNEL_ONVIF)
7378     gst_rtsp_message_add_header (&request, GST_RTSP_HDR_REQUIRE,
7379         BACKCHANNEL_ONVIF_HDR_REQUIRE_VAL);
7380   /* TODO: Handle the case when backchannel is unsupported and goto restart */
7381
7382   /* send DESCRIBE */
7383   GST_DEBUG_OBJECT (src, "send describe...");
7384
7385   if (async)
7386     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
7387
7388   if ((res =
7389           gst_rtspsrc_send (src, &src->conninfo, &request, &response,
7390               NULL, NULL)) < 0)
7391     goto send_error;
7392
7393   /* we only perform redirect for describe and play, currently */
7394   if (src->need_redirect) {
7395     /* close connection, we don't have to send a TEARDOWN yet, ignore the
7396      * result. */
7397     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7398
7399     gst_rtsp_message_unset (&request);
7400     gst_rtsp_message_unset (&response);
7401
7402     /* and now retry */
7403     goto restart;
7404   }
7405
7406   /* it could be that the DESCRIBE method was not implemented */
7407   if (!(src->methods & GST_RTSP_DESCRIBE))
7408     goto no_describe;
7409
7410   /* check if reply is SDP */
7411   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
7412       0);
7413   /* could not be set but since the request returned OK, we assume it
7414    * was SDP, else check it. */
7415   if (respcont) {
7416     const gchar *props = strchr (respcont, ';');
7417
7418     if (props) {
7419       gchar *mimetype = g_strndup (respcont, props - respcont);
7420
7421       mimetype = g_strstrip (mimetype);
7422       if (g_ascii_strcasecmp (mimetype, "application/sdp") != 0) {
7423         g_free (mimetype);
7424         goto wrong_content_type;
7425       }
7426
7427       /* TODO: Check for charset property and do conversions of all messages if
7428        * needed. Some servers actually send that property */
7429
7430       g_free (mimetype);
7431     } else if (g_ascii_strcasecmp (respcont, "application/sdp") != 0) {
7432       goto wrong_content_type;
7433     }
7434   }
7435
7436   /* get message body and parse as SDP */
7437   gst_rtsp_message_get_body (&response, &data, &size);
7438   if (data == NULL || size == 0)
7439     goto no_describe;
7440
7441   GST_DEBUG_OBJECT (src, "parse SDP...");
7442   gst_sdp_message_new (sdp);
7443   gst_sdp_message_parse_buffer (data, size, *sdp);
7444
7445   /* clean up any messages */
7446   gst_rtsp_message_unset (&request);
7447   gst_rtsp_message_unset (&response);
7448
7449   return res;
7450
7451   /* ERRORS */
7452 no_url:
7453   {
7454     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
7455         ("No valid RTSP URL was provided"));
7456     goto cleanup_error;
7457   }
7458 connect_failed:
7459   {
7460     gchar *str = gst_rtsp_strresult (res);
7461
7462     if (res != GST_RTSP_EINTR) {
7463       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
7464           ("Failed to connect. (%s)", str));
7465     } else {
7466       GST_WARNING_OBJECT (src, "connect interrupted");
7467     }
7468     g_free (str);
7469     goto cleanup_error;
7470   }
7471 create_request_failed:
7472   {
7473     gchar *str = gst_rtsp_strresult (res);
7474
7475     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7476         ("Could not create request. (%s)", str));
7477     g_free (str);
7478     goto cleanup_error;
7479   }
7480 send_error:
7481   {
7482     /* Don't post a message - the rtsp_send method will have
7483      * taken care of it because we passed NULL for the response code */
7484     goto cleanup_error;
7485   }
7486 methods_error:
7487   {
7488     /* error was posted */
7489     res = GST_RTSP_ERROR;
7490     goto cleanup_error;
7491   }
7492 wrong_content_type:
7493   {
7494     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7495         ("Server does not support SDP, got %s.", respcont));
7496     res = GST_RTSP_ERROR;
7497     goto cleanup_error;
7498   }
7499 no_describe:
7500   {
7501     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
7502         ("Server can not provide an SDP."));
7503     res = GST_RTSP_ERROR;
7504     goto cleanup_error;
7505   }
7506 cleanup_error:
7507   {
7508     if (src->conninfo.connection) {
7509       GST_DEBUG_OBJECT (src, "free connection");
7510       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7511     }
7512     gst_rtsp_message_unset (&request);
7513     gst_rtsp_message_unset (&response);
7514     return res;
7515   }
7516 }
7517
7518 static GstRTSPResult
7519 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
7520 {
7521   GstRTSPResult ret;
7522
7523   src->methods =
7524       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
7525
7526   if (src->sdp == NULL) {
7527     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
7528       goto no_sdp;
7529   }
7530
7531   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
7532     goto open_failed;
7533
7534 done:
7535   if (async)
7536     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
7537
7538   return ret;
7539
7540   /* ERRORS */
7541 no_sdp:
7542   {
7543     GST_WARNING_OBJECT (src, "can't get sdp");
7544     src->open_error = TRUE;
7545     goto done;
7546   }
7547 open_failed:
7548   {
7549     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
7550     src->open_error = TRUE;
7551     goto done;
7552   }
7553 }
7554
7555 static GstRTSPResult
7556 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
7557 {
7558   GstRTSPMessage request = { 0 };
7559   GstRTSPMessage response = { 0 };
7560   GstRTSPResult res = GST_RTSP_OK;
7561   GList *walk;
7562   const gchar *control;
7563
7564   GST_DEBUG_OBJECT (src, "TEARDOWN...");
7565
7566   gst_rtspsrc_set_state (src, GST_STATE_READY);
7567
7568   if (src->state < GST_RTSP_STATE_READY) {
7569     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
7570     goto close;
7571   }
7572
7573   if (only_close)
7574     goto close;
7575
7576   /* construct a control url */
7577   control = get_aggregate_control (src);
7578
7579   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
7580     goto not_supported;
7581
7582   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7583     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7584     const gchar *setup_url;
7585     GstRTSPConnInfo *info;
7586
7587     /* try aggregate control first but do non-aggregate control otherwise */
7588     if (control)
7589       setup_url = control;
7590     else if ((setup_url = stream->conninfo.location) == NULL)
7591       continue;
7592
7593     if (src->conninfo.connection) {
7594       info = &src->conninfo;
7595     } else if (stream->conninfo.connection) {
7596       info = &stream->conninfo;
7597     } else {
7598       continue;
7599     }
7600     if (!info->connected)
7601       goto next;
7602
7603     /* do TEARDOWN */
7604     res =
7605         gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
7606     if (res < 0)
7607       goto create_request_failed;
7608
7609     if (stream->is_backchannel && src->backchannel == BACKCHANNEL_ONVIF)
7610       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_REQUIRE,
7611           BACKCHANNEL_ONVIF_HDR_REQUIRE_VAL);
7612
7613     if (async)
7614       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
7615
7616     if ((res =
7617             gst_rtspsrc_send (src, info, &request, &response, NULL, NULL)) < 0)
7618       goto send_error;
7619
7620     /* FIXME, parse result? */
7621     gst_rtsp_message_unset (&request);
7622     gst_rtsp_message_unset (&response);
7623
7624   next:
7625     /* early exit when we did aggregate control */
7626     if (control)
7627       break;
7628   }
7629
7630 close:
7631   /* close connections */
7632   GST_DEBUG_OBJECT (src, "closing connection...");
7633   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
7634   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7635     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7636     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
7637   }
7638
7639   /* cleanup */
7640   gst_rtspsrc_cleanup (src);
7641
7642   src->state = GST_RTSP_STATE_INVALID;
7643
7644   if (async)
7645     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
7646
7647   return res;
7648
7649   /* ERRORS */
7650 create_request_failed:
7651   {
7652     gchar *str = gst_rtsp_strresult (res);
7653
7654     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7655         ("Could not create request. (%s)", str));
7656     g_free (str);
7657     goto close;
7658   }
7659 send_error:
7660   {
7661     gchar *str = gst_rtsp_strresult (res);
7662
7663     gst_rtsp_message_unset (&request);
7664     if (res != GST_RTSP_EINTR) {
7665       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7666           ("Could not send message. (%s)", str));
7667     } else {
7668       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7669     }
7670     g_free (str);
7671     goto close;
7672   }
7673 not_supported:
7674   {
7675     GST_DEBUG_OBJECT (src,
7676         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7677     goto close;
7678   }
7679 }
7680
7681 /* RTP-Info is of the format:
7682  *
7683  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7684  *
7685  * rtptime corresponds to the timestamp for the NPT time given in the header
7686  * seqbase corresponds to the next sequence number we received. This number
7687  * indicates the first seqnum after the seek and should be used to discard
7688  * packets that are from before the seek.
7689  */
7690 static gboolean
7691 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7692 {
7693   gchar **infos;
7694   gint i, j;
7695
7696   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7697
7698   infos = g_strsplit (rtpinfo, ",", 0);
7699   for (i = 0; infos[i]; i++) {
7700     gchar **fields;
7701     GstRTSPStream *stream;
7702     gint32 seqbase;
7703     gint64 timebase;
7704
7705     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7706
7707     /* init values, types of seqbase and timebase are bigger than needed so we
7708      * can store -1 as uninitialized values */
7709     stream = NULL;
7710     seqbase = -1;
7711     timebase = -1;
7712
7713     /* parse url, find stream for url.
7714      * parse seq and rtptime. The seq number should be configured in the rtp
7715      * depayloader or session manager to detect gaps. Same for the rtptime, it
7716      * should be used to create an initial time newsegment. */
7717     fields = g_strsplit (infos[i], ";", 0);
7718     for (j = 0; fields[j]; j++) {
7719       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7720       /* remove leading whitespace */
7721       fields[j] = g_strchug (fields[j]);
7722       if (g_str_has_prefix (fields[j], "url=")) {
7723         /* get the url and the stream */
7724         stream =
7725             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7726       } else if (g_str_has_prefix (fields[j], "seq=")) {
7727         seqbase = atoi (fields[j] + 4);
7728       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7729         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7730       }
7731     }
7732     g_strfreev (fields);
7733     /* now we need to store the values for the caps of the stream */
7734     if (stream != NULL) {
7735       GST_DEBUG_OBJECT (src,
7736           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7737           stream, seqbase, timebase);
7738
7739       /* we have a stream, configure detected params */
7740       stream->seqbase = seqbase;
7741       stream->timebase = timebase;
7742     }
7743   }
7744   g_strfreev (infos);
7745
7746   return TRUE;
7747 }
7748
7749 static void
7750 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7751 {
7752   guint64 interval;
7753   GList *walk;
7754
7755   interval = strtoul (rtcp, NULL, 10);
7756   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7757
7758   if (!interval)
7759     return;
7760
7761   interval *= GST_MSECOND;
7762
7763   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7764     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7765
7766     /* already (optionally) retrieved this when configuring manager */
7767     if (stream->session) {
7768       GObject *rtpsession = stream->session;
7769
7770       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7771           rtpsession);
7772       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7773     }
7774   }
7775
7776   /* now it happens that (Xenon) server sending this may also provide bogus
7777    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7778    * and just use RTP-Info to sync */
7779   if (src->manager) {
7780     GObjectClass *klass;
7781
7782     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7783     if (g_object_class_find_property (klass, "rtcp-sync")) {
7784       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7785       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7786     }
7787   }
7788 }
7789
7790 static gdouble
7791 gst_rtspsrc_get_float (const gchar * dstr)
7792 {
7793   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7794
7795   /* canonicalise floating point string so we can handle float strings
7796    * in the form "24.930" or "24,930" irrespective of the current locale */
7797   g_strlcpy (s, dstr, sizeof (s));
7798   g_strdelimit (s, ",", '.');
7799   return g_ascii_strtod (s, NULL);
7800 }
7801
7802 static gchar *
7803 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7804 {
7805   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7806
7807   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7808     g_strlcpy (val_str, "now", sizeof (val_str));
7809   } else {
7810     if (segment->position == 0) {
7811       g_strlcpy (val_str, "0", sizeof (val_str));
7812     } else {
7813       g_ascii_dtostr (val_str, sizeof (val_str),
7814           ((gdouble) segment->position) / GST_SECOND);
7815     }
7816   }
7817   return g_strdup_printf ("npt=%s-", val_str);
7818 }
7819
7820 static void
7821 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7822 {
7823   guint i, len;
7824
7825   stream->timebase = -1;
7826   stream->seqbase = -1;
7827
7828   len = stream->ptmap->len;
7829   for (i = 0; i < len; i++) {
7830     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7831     GstStructure *s;
7832
7833     if (item->caps == NULL)
7834       continue;
7835
7836     item->caps = gst_caps_make_writable (item->caps);
7837     s = gst_caps_get_structure (item->caps, 0);
7838     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7839     if (item->pt == stream->default_pt && stream->udpsrc[0])
7840       g_object_set (stream->udpsrc[0], "caps", item->caps, NULL);
7841   }
7842   stream->need_caps = TRUE;
7843 }
7844
7845 static GstRTSPResult
7846 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7847 {
7848   GstRTSPResult res = GST_RTSP_OK;
7849
7850   if (src->state < GST_RTSP_STATE_READY) {
7851     res = GST_RTSP_ERROR;
7852     if (src->open_error) {
7853       GST_DEBUG_OBJECT (src, "the stream was in error");
7854       goto done;
7855     }
7856     if (async)
7857       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7858
7859     if ((res = gst_rtspsrc_open (src, async)) < 0) {
7860       GST_DEBUG_OBJECT (src, "failed to open stream");
7861       goto done;
7862     }
7863   }
7864
7865 done:
7866   return res;
7867 }
7868
7869 static GstRTSPResult
7870 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async,
7871     const gchar * seek_style)
7872 {
7873   GstRTSPMessage request = { 0 };
7874   GstRTSPMessage response = { 0 };
7875   GstRTSPResult res = GST_RTSP_OK;
7876   GList *walk;
7877   gchar *hval;
7878   gint hval_idx;
7879   const gchar *control;
7880
7881   GST_DEBUG_OBJECT (src, "PLAY...");
7882
7883 restart:
7884   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7885     goto open_failed;
7886
7887   if (!(src->methods & GST_RTSP_PLAY))
7888     goto not_supported;
7889
7890   if (src->state == GST_RTSP_STATE_PLAYING)
7891     goto was_playing;
7892
7893   if (!src->conninfo.connection || !src->conninfo.connected)
7894     goto done;
7895
7896   /* send some dummy packets before we activate the receive in the
7897    * udp sources */
7898   gst_rtspsrc_send_dummy_packets (src);
7899
7900   /* require new SR packets */
7901   if (src->manager)
7902     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7903
7904   /* construct a control url */
7905   control = get_aggregate_control (src);
7906
7907   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7908     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7909     const gchar *setup_url;
7910     GstRTSPConnInfo *conninfo;
7911
7912     /* try aggregate control first but do non-aggregate control otherwise */
7913     if (control)
7914       setup_url = control;
7915     else if ((setup_url = stream->conninfo.location) == NULL)
7916       continue;
7917
7918     if (src->conninfo.connection) {
7919       conninfo = &src->conninfo;
7920     } else if (stream->conninfo.connection) {
7921       conninfo = &stream->conninfo;
7922     } else {
7923       continue;
7924     }
7925
7926     /* do play */
7927     res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
7928     if (res < 0)
7929       goto create_request_failed;
7930
7931     if (src->need_range && src->seekable >= 0.0) {
7932       hval = gen_range_header (src, segment);
7933
7934       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7935
7936       /* store the newsegment event so it can be sent from the streaming thread. */
7937       src->need_segment = TRUE;
7938     }
7939
7940     if (segment->rate != 1.0) {
7941       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7942
7943       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7944       if (src->skip)
7945         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7946       else
7947         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7948     }
7949
7950     if (seek_style)
7951       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SEEK_STYLE,
7952           seek_style);
7953
7954     /* when we have an ONVIF audio backchannel, the PLAY request must have the
7955      * Require: header when doing either aggregate or non-aggregate control */
7956     if (src->backchannel == BACKCHANNEL_ONVIF &&
7957         (control || stream->is_backchannel))
7958       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_REQUIRE,
7959           BACKCHANNEL_ONVIF_HDR_REQUIRE_VAL);
7960
7961     if (async)
7962       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7963
7964     if ((res =
7965             gst_rtspsrc_send (src, conninfo, &request, &response, NULL, NULL))
7966         < 0)
7967       goto send_error;
7968
7969     if (src->need_redirect) {
7970       GST_DEBUG_OBJECT (src,
7971           "redirect: tearing down and restarting with new url");
7972       /* teardown and restart with new url */
7973       gst_rtspsrc_close (src, TRUE, FALSE);
7974       /* reset protocols to force re-negotiation with redirected url */
7975       src->cur_protocols = src->protocols;
7976       gst_rtsp_message_unset (&request);
7977       gst_rtsp_message_unset (&response);
7978       goto restart;
7979     }
7980
7981     /* seek may have silently failed as it is not supported */
7982     if (!(src->methods & GST_RTSP_PLAY)) {
7983       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7984
7985       if (src->version >= GST_RTSP_VERSION_2_0 && src->seekable >= 0.0) {
7986         GST_WARNING_OBJECT (src, "Server declared stream as seekable but"
7987             " playing with range failed... Ignoring information.");
7988       }
7989       /* obviously it is supported as we made it here */
7990       src->methods |= GST_RTSP_PLAY;
7991       src->seekable = -1.0;
7992       /* but there is nothing to parse in the response,
7993        * so convey we have no idea and not to expect anything particular */
7994       clear_rtp_base (src, stream);
7995       if (control) {
7996         GList *run;
7997
7998         /* need to do for all streams */
7999         for (run = src->streams; run; run = g_list_next (run))
8000           clear_rtp_base (src, (GstRTSPStream *) run->data);
8001       }
8002       /* NOTE the above also disables npt based eos detection */
8003       /* and below forces position to 0,
8004        * which is visible feedback we lost the plot */
8005       segment->start = segment->position = src->last_pos;
8006     }
8007
8008     gst_rtsp_message_unset (&request);
8009
8010     /* parse RTP npt field. This is the current position in the stream (Normal
8011      * Play Time) and should be put in the NEWSEGMENT position field. */
8012     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
8013             0) == GST_RTSP_OK)
8014       gst_rtspsrc_parse_range (src, hval, segment);
8015
8016     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
8017     segment->rate = 1.0;
8018
8019     /* parse Speed header. This is the intended playback rate of the stream
8020      * and should be put in the NEWSEGMENT rate field. */
8021     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
8022             0) == GST_RTSP_OK) {
8023       segment->rate = gst_rtspsrc_get_float (hval);
8024     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
8025             &hval, 0) == GST_RTSP_OK) {
8026       segment->rate = gst_rtspsrc_get_float (hval);
8027     }
8028
8029     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
8030      * for the RTP packets. If this is not present, we assume all starts from 0...
8031      * This is info for the RTP session manager that we pass to it in caps. */
8032     hval_idx = 0;
8033     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
8034             &hval, hval_idx++) == GST_RTSP_OK)
8035       gst_rtspsrc_parse_rtpinfo (src, hval);
8036
8037     /* some servers indicate RTCP parameters in PLAY response,
8038      * rather than properly in SDP */
8039     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
8040             &hval, 0) == GST_RTSP_OK)
8041       gst_rtspsrc_handle_rtcp_interval (src, hval);
8042
8043     gst_rtsp_message_unset (&response);
8044
8045     /* early exit when we did aggregate control */
8046     if (control)
8047       break;
8048   }
8049   /* configure the caps of the streams after we parsed all headers. Only reset
8050    * the manager object when we set a new Range header (we did a seek) */
8051   gst_rtspsrc_configure_caps (src, segment, src->need_range);
8052
8053   /* set to PLAYING after we have configured the caps, otherwise we
8054    * might end up calling request_key (with SRTP) while caps are still
8055    * being configured. */
8056   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
8057
8058   /* set again when needed */
8059   src->need_range = FALSE;
8060
8061   src->running = TRUE;
8062   src->base_time = -1;
8063   src->state = GST_RTSP_STATE_PLAYING;
8064
8065   /* mark discont */
8066   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
8067   for (walk = src->streams; walk; walk = g_list_next (walk)) {
8068     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
8069     stream->discont = TRUE;
8070   }
8071
8072 done:
8073   if (async)
8074     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
8075
8076   return res;
8077
8078   /* ERRORS */
8079 open_failed:
8080   {
8081     GST_WARNING_OBJECT (src, "failed to open stream");
8082     goto done;
8083   }
8084 not_supported:
8085   {
8086     GST_WARNING_OBJECT (src, "PLAY is not supported");
8087     goto done;
8088   }
8089 was_playing:
8090   {
8091     GST_WARNING_OBJECT (src, "we were already PLAYING");
8092     goto done;
8093   }
8094 create_request_failed:
8095   {
8096     gchar *str = gst_rtsp_strresult (res);
8097
8098     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
8099         ("Could not create request. (%s)", str));
8100     g_free (str);
8101     goto done;
8102   }
8103 send_error:
8104   {
8105     gchar *str = gst_rtsp_strresult (res);
8106
8107     gst_rtsp_message_unset (&request);
8108     if (res != GST_RTSP_EINTR) {
8109       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
8110           ("Could not send message. (%s)", str));
8111     } else {
8112       GST_WARNING_OBJECT (src, "PLAY interrupted");
8113     }
8114     g_free (str);
8115     goto done;
8116   }
8117 }
8118
8119 static GstRTSPResult
8120 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
8121 {
8122   GstRTSPResult res = GST_RTSP_OK;
8123   GstRTSPMessage request = { 0 };
8124   GstRTSPMessage response = { 0 };
8125   GList *walk;
8126   const gchar *control;
8127
8128   GST_DEBUG_OBJECT (src, "PAUSE...");
8129
8130   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
8131     goto open_failed;
8132
8133   if (!(src->methods & GST_RTSP_PAUSE))
8134     goto not_supported;
8135
8136   if (src->state == GST_RTSP_STATE_READY)
8137     goto was_paused;
8138
8139   if (!src->conninfo.connection || !src->conninfo.connected)
8140     goto no_connection;
8141
8142   /* construct a control url */
8143   control = get_aggregate_control (src);
8144
8145   /* loop over the streams. We might exit the loop early when we could do an
8146    * aggregate control */
8147   for (walk = src->streams; walk; walk = g_list_next (walk)) {
8148     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
8149     GstRTSPConnInfo *conninfo;
8150     const gchar *setup_url;
8151
8152     /* try aggregate control first but do non-aggregate control otherwise */
8153     if (control)
8154       setup_url = control;
8155     else if ((setup_url = stream->conninfo.location) == NULL)
8156       continue;
8157
8158     if (src->conninfo.connection) {
8159       conninfo = &src->conninfo;
8160     } else if (stream->conninfo.connection) {
8161       conninfo = &stream->conninfo;
8162     } else {
8163       continue;
8164     }
8165
8166     if (async)
8167       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
8168           ("Sending PAUSE request"));
8169
8170     if ((res =
8171             gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
8172                 setup_url)) < 0)
8173       goto create_request_failed;
8174
8175     /* when we have an ONVIF audio backchannel, the PAUSE request must have the
8176      * Require: header when doing either aggregate or non-aggregate control */
8177     if (src->backchannel == BACKCHANNEL_ONVIF &&
8178         (control || stream->is_backchannel))
8179       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_REQUIRE,
8180           BACKCHANNEL_ONVIF_HDR_REQUIRE_VAL);
8181
8182     if ((res =
8183             gst_rtspsrc_send (src, conninfo, &request, &response, NULL,
8184                 NULL)) < 0)
8185       goto send_error;
8186
8187     gst_rtsp_message_unset (&request);
8188     gst_rtsp_message_unset (&response);
8189
8190     /* exit early when we did agregate control */
8191     if (control)
8192       break;
8193   }
8194
8195   /* change element states now */
8196   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
8197
8198 no_connection:
8199   src->state = GST_RTSP_STATE_READY;
8200
8201 done:
8202   if (async)
8203     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
8204
8205   return res;
8206
8207   /* ERRORS */
8208 open_failed:
8209   {
8210     GST_DEBUG_OBJECT (src, "failed to open stream");
8211     goto done;
8212   }
8213 not_supported:
8214   {
8215     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
8216     goto done;
8217   }
8218 was_paused:
8219   {
8220     GST_DEBUG_OBJECT (src, "we were already PAUSED");
8221     goto done;
8222   }
8223 create_request_failed:
8224   {
8225     gchar *str = gst_rtsp_strresult (res);
8226
8227     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
8228         ("Could not create request. (%s)", str));
8229     g_free (str);
8230     goto done;
8231   }
8232 send_error:
8233   {
8234     gchar *str = gst_rtsp_strresult (res);
8235
8236     gst_rtsp_message_unset (&request);
8237     if (res != GST_RTSP_EINTR) {
8238       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
8239           ("Could not send message. (%s)", str));
8240     } else {
8241       GST_WARNING_OBJECT (src, "PAUSE interrupted");
8242     }
8243     g_free (str);
8244     goto done;
8245   }
8246 }
8247
8248 static void
8249 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
8250 {
8251   GstRTSPSrc *rtspsrc;
8252
8253   rtspsrc = GST_RTSPSRC (bin);
8254
8255   switch (GST_MESSAGE_TYPE (message)) {
8256     case GST_MESSAGE_EOS:
8257       gst_message_unref (message);
8258       break;
8259     case GST_MESSAGE_ELEMENT:
8260     {
8261       const GstStructure *s = gst_message_get_structure (message);
8262
8263       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
8264         gboolean ignore_timeout;
8265
8266         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
8267
8268         GST_OBJECT_LOCK (rtspsrc);
8269         ignore_timeout = rtspsrc->ignore_timeout;
8270         rtspsrc->ignore_timeout = TRUE;
8271         GST_OBJECT_UNLOCK (rtspsrc);
8272
8273         /* we only act on the first udp timeout message, others are irrelevant
8274          * and can be ignored. */
8275         if (!ignore_timeout)
8276           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
8277         /* eat and free */
8278         gst_message_unref (message);
8279         return;
8280       }
8281       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8282       break;
8283     }
8284     case GST_MESSAGE_ERROR:
8285     {
8286       GstObject *udpsrc;
8287       GstRTSPStream *stream;
8288       GstFlowReturn ret;
8289
8290       udpsrc = GST_MESSAGE_SRC (message);
8291
8292       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
8293           GST_ELEMENT_NAME (udpsrc));
8294
8295       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
8296       if (!stream)
8297         goto forward;
8298
8299       /* we ignore the RTCP udpsrc */
8300       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
8301         goto done;
8302
8303       /* if we get error messages from the udp sources, that's not a problem as
8304        * long as not all of them error out. We also don't really know what the
8305        * problem is, the message does not give enough detail... */
8306       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
8307       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
8308       if (ret != GST_FLOW_OK)
8309         goto forward;
8310
8311     done:
8312       gst_message_unref (message);
8313       break;
8314
8315     forward:
8316       /* fatal but not our message, forward */
8317       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8318       break;
8319     }
8320     default:
8321     {
8322       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
8323       break;
8324     }
8325   }
8326 }
8327
8328 /* the thread where everything happens */
8329 static void
8330 gst_rtspsrc_thread (GstRTSPSrc * src)
8331 {
8332   gint cmd;
8333
8334   GST_OBJECT_LOCK (src);
8335   cmd = src->pending_cmd;
8336   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
8337       || cmd == CMD_LOOP || cmd == CMD_OPEN)
8338     src->pending_cmd = CMD_LOOP;
8339   else
8340     src->pending_cmd = CMD_WAIT;
8341   GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
8342
8343   /* we got the message command, so ensure communication is possible again */
8344   gst_rtspsrc_connection_flush (src, FALSE);
8345
8346   src->busy_cmd = cmd;
8347   GST_OBJECT_UNLOCK (src);
8348
8349   switch (cmd) {
8350     case CMD_OPEN:
8351       gst_rtspsrc_open (src, TRUE);
8352       break;
8353     case CMD_PLAY:
8354       gst_rtspsrc_play (src, &src->segment, TRUE, NULL);
8355       break;
8356     case CMD_PAUSE:
8357       gst_rtspsrc_pause (src, TRUE);
8358       break;
8359     case CMD_CLOSE:
8360       gst_rtspsrc_close (src, TRUE, FALSE);
8361       break;
8362     case CMD_LOOP:
8363       gst_rtspsrc_loop (src);
8364       break;
8365     case CMD_RECONNECT:
8366       gst_rtspsrc_reconnect (src, FALSE);
8367       break;
8368     default:
8369       break;
8370   }
8371
8372   GST_OBJECT_LOCK (src);
8373   /* and go back to sleep */
8374   if (src->pending_cmd == CMD_WAIT) {
8375     if (src->task)
8376       gst_task_pause (src->task);
8377   }
8378   /* reset waiting */
8379   src->busy_cmd = CMD_WAIT;
8380   GST_OBJECT_UNLOCK (src);
8381 }
8382
8383 static gboolean
8384 gst_rtspsrc_start (GstRTSPSrc * src)
8385 {
8386   GST_DEBUG_OBJECT (src, "starting");
8387
8388   GST_OBJECT_LOCK (src);
8389
8390   src->pending_cmd = CMD_WAIT;
8391
8392   if (src->task == NULL) {
8393     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
8394     if (src->task == NULL)
8395       goto task_error;
8396
8397     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
8398   }
8399   GST_OBJECT_UNLOCK (src);
8400
8401   return TRUE;
8402
8403   /* ERRORS */
8404 task_error:
8405   {
8406     GST_OBJECT_UNLOCK (src);
8407     GST_ERROR_OBJECT (src, "failed to create task");
8408     return FALSE;
8409   }
8410 }
8411
8412 static gboolean
8413 gst_rtspsrc_stop (GstRTSPSrc * src)
8414 {
8415   GstTask *task;
8416
8417   GST_DEBUG_OBJECT (src, "stopping");
8418
8419   /* also cancels pending task */
8420   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
8421
8422   GST_OBJECT_LOCK (src);
8423   if ((task = src->task)) {
8424     src->task = NULL;
8425     GST_OBJECT_UNLOCK (src);
8426
8427     gst_task_stop (task);
8428
8429     /* make sure it is not running */
8430     GST_RTSP_STREAM_LOCK (src);
8431     GST_RTSP_STREAM_UNLOCK (src);
8432
8433     /* now wait for the task to finish */
8434     gst_task_join (task);
8435
8436     /* and free the task */
8437     gst_object_unref (GST_OBJECT (task));
8438
8439     GST_OBJECT_LOCK (src);
8440   }
8441   GST_OBJECT_UNLOCK (src);
8442
8443   /* ensure synchronously all is closed and clean */
8444   gst_rtspsrc_close (src, FALSE, TRUE);
8445
8446   return TRUE;
8447 }
8448
8449 static GstStateChangeReturn
8450 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
8451 {
8452   GstRTSPSrc *rtspsrc;
8453   GstStateChangeReturn ret;
8454
8455   rtspsrc = GST_RTSPSRC (element);
8456
8457   switch (transition) {
8458     case GST_STATE_CHANGE_NULL_TO_READY:
8459       if (!gst_rtspsrc_start (rtspsrc))
8460         goto start_failed;
8461       break;
8462     case GST_STATE_CHANGE_READY_TO_PAUSED:
8463       /* init some state */
8464       rtspsrc->cur_protocols = rtspsrc->protocols;
8465       /* first attempt, don't ignore timeouts */
8466       rtspsrc->ignore_timeout = FALSE;
8467       rtspsrc->open_error = FALSE;
8468       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
8469       break;
8470     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8471       set_manager_buffer_mode (rtspsrc);
8472       /* fall-through */
8473     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8474       /* unblock the tcp tasks and make the loop waiting */
8475       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
8476         /* make sure it is waiting before we send PAUSE or PLAY below */
8477         GST_RTSP_STREAM_LOCK (rtspsrc);
8478         GST_RTSP_STREAM_UNLOCK (rtspsrc);
8479       }
8480       break;
8481     case GST_STATE_CHANGE_PAUSED_TO_READY:
8482       break;
8483     default:
8484       break;
8485   }
8486
8487   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
8488   if (ret == GST_STATE_CHANGE_FAILURE)
8489     goto done;
8490
8491   switch (transition) {
8492     case GST_STATE_CHANGE_NULL_TO_READY:
8493       ret = GST_STATE_CHANGE_SUCCESS;
8494       break;
8495     case GST_STATE_CHANGE_READY_TO_PAUSED:
8496       ret = GST_STATE_CHANGE_NO_PREROLL;
8497       break;
8498     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
8499       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
8500       ret = GST_STATE_CHANGE_SUCCESS;
8501       break;
8502     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
8503       /* send pause request and keep the idle task around */
8504       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
8505       ret = GST_STATE_CHANGE_NO_PREROLL;
8506       break;
8507     case GST_STATE_CHANGE_PAUSED_TO_READY:
8508       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_ALL);
8509       ret = GST_STATE_CHANGE_SUCCESS;
8510       break;
8511     case GST_STATE_CHANGE_READY_TO_NULL:
8512       gst_rtspsrc_stop (rtspsrc);
8513       ret = GST_STATE_CHANGE_SUCCESS;
8514       break;
8515     default:
8516       /* Otherwise it's success, we don't want to return spurious
8517        * NO_PREROLL or ASYNC from internal elements as we care for
8518        * state changes ourselves here
8519        *
8520        * This is to catch PAUSED->PAUSED and PLAYING->PLAYING transitions.
8521        */
8522       if (GST_STATE_TRANSITION_NEXT (transition) == GST_STATE_PAUSED)
8523         ret = GST_STATE_CHANGE_NO_PREROLL;
8524       else
8525         ret = GST_STATE_CHANGE_SUCCESS;
8526       break;
8527   }
8528
8529 done:
8530   return ret;
8531
8532 start_failed:
8533   {
8534     GST_DEBUG_OBJECT (rtspsrc, "start failed");
8535     return GST_STATE_CHANGE_FAILURE;
8536   }
8537 }
8538
8539 static gboolean
8540 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
8541 {
8542   gboolean res;
8543   GstRTSPSrc *rtspsrc;
8544
8545   rtspsrc = GST_RTSPSRC (element);
8546
8547   if (GST_EVENT_IS_DOWNSTREAM (event)) {
8548     res = gst_rtspsrc_push_event (rtspsrc, event);
8549   } else {
8550     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
8551   }
8552
8553   return res;
8554 }
8555
8556
8557 /*** GSTURIHANDLER INTERFACE *************************************************/
8558
8559 static GstURIType
8560 gst_rtspsrc_uri_get_type (GType type)
8561 {
8562   return GST_URI_SRC;
8563 }
8564
8565 static const gchar *const *
8566 gst_rtspsrc_uri_get_protocols (GType type)
8567 {
8568   static const gchar *protocols[] =
8569       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
8570     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
8571   };
8572
8573   return protocols;
8574 }
8575
8576 static gchar *
8577 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
8578 {
8579   GstRTSPSrc *src = GST_RTSPSRC (handler);
8580
8581   /* FIXME: make thread-safe */
8582   return g_strdup (src->conninfo.location);
8583 }
8584
8585 static gboolean
8586 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
8587     GError ** error)
8588 {
8589   GstRTSPSrc *src;
8590   GstRTSPResult res;
8591   GstSDPResult sres;
8592   GstRTSPUrl *newurl = NULL;
8593   GstSDPMessage *sdp = NULL;
8594
8595   src = GST_RTSPSRC (handler);
8596
8597   /* same URI, we're fine */
8598   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
8599     goto was_ok;
8600
8601   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
8602     sres = gst_sdp_message_new (&sdp);
8603     if (sres < 0)
8604       goto sdp_failed;
8605
8606     GST_DEBUG_OBJECT (src, "parsing SDP message");
8607     sres = gst_sdp_message_parse_uri (uri, sdp);
8608     if (sres < 0)
8609       goto invalid_sdp;
8610   } else {
8611     /* try to parse */
8612     GST_DEBUG_OBJECT (src, "parsing URI");
8613     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
8614       goto parse_error;
8615   }
8616
8617   /* if worked, free previous and store new url object along with the original
8618    * location. */
8619   GST_DEBUG_OBJECT (src, "configuring URI");
8620   g_free (src->conninfo.location);
8621   src->conninfo.location = g_strdup (uri);
8622   gst_rtsp_url_free (src->conninfo.url);
8623   src->conninfo.url = newurl;
8624   g_free (src->conninfo.url_str);
8625   if (newurl)
8626     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
8627   else
8628     src->conninfo.url_str = NULL;
8629
8630   if (src->sdp)
8631     gst_sdp_message_free (src->sdp);
8632   src->sdp = sdp;
8633   src->from_sdp = sdp != NULL;
8634
8635   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
8636   GST_DEBUG_OBJECT (src, "request uri is: %s",
8637       GST_STR_NULL (src->conninfo.url_str));
8638
8639   return TRUE;
8640
8641   /* Special cases */
8642 was_ok:
8643   {
8644     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
8645     return TRUE;
8646   }
8647 sdp_failed:
8648   {
8649     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
8650     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8651         "Could not create SDP");
8652     return FALSE;
8653   }
8654 invalid_sdp:
8655   {
8656     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
8657         GST_STR_NULL (uri));
8658     gst_sdp_message_free (sdp);
8659     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8660         "Invalid SDP");
8661     return FALSE;
8662   }
8663 parse_error:
8664   {
8665     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
8666         GST_STR_NULL (uri), res);
8667     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
8668         "Invalid RTSP URI");
8669     return FALSE;
8670   }
8671 }
8672
8673 static void
8674 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
8675 {
8676   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
8677
8678   iface->get_type = gst_rtspsrc_uri_get_type;
8679   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
8680   iface->get_uri = gst_rtspsrc_uri_get_uri;
8681   iface->set_uri = gst_rtspsrc_uri_set_uri;
8682 }
8683
8684 typedef struct _RTSPKeyValue
8685 {
8686   GstRTSPHeaderField field;
8687   gchar *value;
8688   gchar *custom_key;            /* custom header string (field is INVALID then) */
8689 } RTSPKeyValue;
8690
8691 static void
8692 key_value_foreach (GArray * array, GFunc func, gpointer user_data)
8693 {
8694   guint i;
8695
8696   g_return_if_fail (array != NULL);
8697
8698   for (i = 0; i < array->len; i++) {
8699     (*func) (&g_array_index (array, RTSPKeyValue, i), user_data);
8700   }
8701 }
8702
8703 static void
8704 dump_key_value (gpointer data, gpointer user_data G_GNUC_UNUSED)
8705 {
8706   RTSPKeyValue *key_value = (RTSPKeyValue *) data;
8707   GstRTSPSrc *src = GST_RTSPSRC (user_data);
8708   const gchar *key_string;
8709
8710   if (key_value->custom_key != NULL)
8711     key_string = key_value->custom_key;
8712   else
8713     key_string = gst_rtsp_header_as_text (key_value->field);
8714
8715   GST_LOG_OBJECT (src, "   key: '%s', value: '%s'", key_string,
8716       key_value->value);
8717 }
8718
8719 static void
8720 gst_rtspsrc_print_rtsp_message (GstRTSPSrc * src, const GstRTSPMessage * msg)
8721 {
8722   guint8 *data;
8723   guint size;
8724   GString *body_string = NULL;
8725
8726   g_return_if_fail (src != NULL);
8727   g_return_if_fail (msg != NULL);
8728
8729   if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) < GST_LEVEL_LOG)
8730     return;
8731
8732   GST_LOG_OBJECT (src, "--------------------------------------------");
8733   switch (msg->type) {
8734     case GST_RTSP_MESSAGE_REQUEST:
8735       GST_LOG_OBJECT (src, "RTSP request message %p", msg);
8736       GST_LOG_OBJECT (src, " request line:");
8737       GST_LOG_OBJECT (src, "   method: '%s'",
8738           gst_rtsp_method_as_text (msg->type_data.request.method));
8739       GST_LOG_OBJECT (src, "   uri:    '%s'", msg->type_data.request.uri);
8740       GST_LOG_OBJECT (src, "   version: '%s'",
8741           gst_rtsp_version_as_text (msg->type_data.request.version));
8742       GST_LOG_OBJECT (src, " headers:");
8743       key_value_foreach (msg->hdr_fields, dump_key_value, src);
8744       GST_LOG_OBJECT (src, " body:");
8745       gst_rtsp_message_get_body (msg, &data, &size);
8746       if (size > 0) {
8747         body_string = g_string_new_len ((const gchar *) data, size);
8748         GST_LOG_OBJECT (src, " %s(%d)", body_string->str, size);
8749         g_string_free (body_string, TRUE);
8750         body_string = NULL;
8751       }
8752       break;
8753     case GST_RTSP_MESSAGE_RESPONSE:
8754       GST_LOG_OBJECT (src, "RTSP response message %p", msg);
8755       GST_LOG_OBJECT (src, " status line:");
8756       GST_LOG_OBJECT (src, "   code:   '%d'", msg->type_data.response.code);
8757       GST_LOG_OBJECT (src, "   reason: '%s'", msg->type_data.response.reason);
8758       GST_LOG_OBJECT (src, "   version: '%s",
8759           gst_rtsp_version_as_text (msg->type_data.response.version));
8760       GST_LOG_OBJECT (src, " headers:");
8761       key_value_foreach (msg->hdr_fields, dump_key_value, src);
8762       gst_rtsp_message_get_body (msg, &data, &size);
8763       GST_LOG_OBJECT (src, " body: length %d", size);
8764       if (size > 0) {
8765         body_string = g_string_new_len ((const gchar *) data, size);
8766         GST_LOG_OBJECT (src, " %s(%d)", body_string->str, size);
8767         g_string_free (body_string, TRUE);
8768         body_string = NULL;
8769       }
8770       break;
8771     case GST_RTSP_MESSAGE_HTTP_REQUEST:
8772       GST_LOG_OBJECT (src, "HTTP request message %p", msg);
8773       GST_LOG_OBJECT (src, " request line:");
8774       GST_LOG_OBJECT (src, "   method:  '%s'",
8775           gst_rtsp_method_as_text (msg->type_data.request.method));
8776       GST_LOG_OBJECT (src, "   uri:     '%s'", msg->type_data.request.uri);
8777       GST_LOG_OBJECT (src, "   version: '%s'",
8778           gst_rtsp_version_as_text (msg->type_data.request.version));
8779       GST_LOG_OBJECT (src, " headers:");
8780       key_value_foreach (msg->hdr_fields, dump_key_value, src);
8781       GST_LOG_OBJECT (src, " body:");
8782       gst_rtsp_message_get_body (msg, &data, &size);
8783       if (size > 0) {
8784         body_string = g_string_new_len ((const gchar *) data, size);
8785         GST_LOG_OBJECT (src, " %s(%d)", body_string->str, size);
8786         g_string_free (body_string, TRUE);
8787         body_string = NULL;
8788       }
8789       break;
8790     case GST_RTSP_MESSAGE_HTTP_RESPONSE:
8791       GST_LOG_OBJECT (src, "HTTP response message %p", msg);
8792       GST_LOG_OBJECT (src, " status line:");
8793       GST_LOG_OBJECT (src, "   code:    '%d'", msg->type_data.response.code);
8794       GST_LOG_OBJECT (src, "   reason:  '%s'", msg->type_data.response.reason);
8795       GST_LOG_OBJECT (src, "   version: '%s'",
8796           gst_rtsp_version_as_text (msg->type_data.response.version));
8797       GST_LOG_OBJECT (src, " headers:");
8798       key_value_foreach (msg->hdr_fields, dump_key_value, src);
8799       gst_rtsp_message_get_body (msg, &data, &size);
8800       GST_LOG_OBJECT (src, " body: length %d", size);
8801       if (size > 0) {
8802         body_string = g_string_new_len ((const gchar *) data, size);
8803         GST_LOG_OBJECT (src, " %s(%d)", body_string->str, size);
8804         g_string_free (body_string, TRUE);
8805         body_string = NULL;
8806       }
8807       break;
8808     case GST_RTSP_MESSAGE_DATA:
8809       GST_LOG_OBJECT (src, "RTSP data message %p", msg);
8810       GST_LOG_OBJECT (src, " channel: '%d'", msg->type_data.data.channel);
8811       GST_LOG_OBJECT (src, " size:    '%d'", msg->body_size);
8812       gst_rtsp_message_get_body (msg, &data, &size);
8813       if (size > 0) {
8814         body_string = g_string_new_len ((const gchar *) data, size);
8815         GST_LOG_OBJECT (src, " %s(%d)", body_string->str, size);
8816         g_string_free (body_string, TRUE);
8817         body_string = NULL;
8818       }
8819       break;
8820     default:
8821       GST_LOG_OBJECT (src, "unsupported message type %d", msg->type);
8822       break;
8823   }
8824   GST_LOG_OBJECT (src, "--------------------------------------------");
8825 }
8826
8827 static void
8828 gst_rtspsrc_print_sdp_media (GstRTSPSrc * src, GstSDPMedia * media)
8829 {
8830   GST_LOG_OBJECT (src, "   media:       '%s'", GST_STR_NULL (media->media));
8831   GST_LOG_OBJECT (src, "   port:        '%u'", media->port);
8832   GST_LOG_OBJECT (src, "   num_ports:   '%u'", media->num_ports);
8833   GST_LOG_OBJECT (src, "   proto:       '%s'", GST_STR_NULL (media->proto));
8834   if (media->fmts && media->fmts->len > 0) {
8835     guint i;
8836
8837     GST_LOG_OBJECT (src, "   formats:");
8838     for (i = 0; i < media->fmts->len; i++) {
8839       GST_LOG_OBJECT (src, "    format  '%s'", g_array_index (media->fmts,
8840               gchar *, i));
8841     }
8842   }
8843   GST_LOG_OBJECT (src, "   information: '%s'",
8844       GST_STR_NULL (media->information));
8845   if (media->connections && media->connections->len > 0) {
8846     guint i;
8847
8848     GST_LOG_OBJECT (src, "   connections:");
8849     for (i = 0; i < media->connections->len; i++) {
8850       GstSDPConnection *conn =
8851           &g_array_index (media->connections, GstSDPConnection, i);
8852
8853       GST_LOG_OBJECT (src, "    nettype:      '%s'",
8854           GST_STR_NULL (conn->nettype));
8855       GST_LOG_OBJECT (src, "    addrtype:     '%s'",
8856           GST_STR_NULL (conn->addrtype));
8857       GST_LOG_OBJECT (src, "    address:      '%s'",
8858           GST_STR_NULL (conn->address));
8859       GST_LOG_OBJECT (src, "    ttl:          '%u'", conn->ttl);
8860       GST_LOG_OBJECT (src, "    addr_number:  '%u'", conn->addr_number);
8861     }
8862   }
8863   if (media->bandwidths && media->bandwidths->len > 0) {
8864     guint i;
8865
8866     GST_LOG_OBJECT (src, "   bandwidths:");
8867     for (i = 0; i < media->bandwidths->len; i++) {
8868       GstSDPBandwidth *bw =
8869           &g_array_index (media->bandwidths, GstSDPBandwidth, i);
8870
8871       GST_LOG_OBJECT (src, "    type:         '%s'", GST_STR_NULL (bw->bwtype));
8872       GST_LOG_OBJECT (src, "    bandwidth:    '%u'", bw->bandwidth);
8873     }
8874   }
8875   GST_LOG_OBJECT (src, "   key:");
8876   GST_LOG_OBJECT (src, "    type:       '%s'", GST_STR_NULL (media->key.type));
8877   GST_LOG_OBJECT (src, "    data:       '%s'", GST_STR_NULL (media->key.data));
8878   if (media->attributes && media->attributes->len > 0) {
8879     guint i;
8880
8881     GST_LOG_OBJECT (src, "   attributes:");
8882     for (i = 0; i < media->attributes->len; i++) {
8883       GstSDPAttribute *attr =
8884           &g_array_index (media->attributes, GstSDPAttribute, i);
8885
8886       GST_LOG_OBJECT (src, "    attribute '%s' : '%s'", attr->key, attr->value);
8887     }
8888   }
8889 }
8890
8891 void
8892 gst_rtspsrc_print_sdp_message (GstRTSPSrc * src, const GstSDPMessage * msg)
8893 {
8894   g_return_if_fail (src != NULL);
8895   g_return_if_fail (msg != NULL);
8896
8897   if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) < GST_LEVEL_LOG)
8898     return;
8899
8900   GST_LOG_OBJECT (src, "--------------------------------------------");
8901   GST_LOG_OBJECT (src, "sdp packet %p:", msg);
8902   GST_LOG_OBJECT (src, " version:       '%s'", GST_STR_NULL (msg->version));
8903   GST_LOG_OBJECT (src, " origin:");
8904   GST_LOG_OBJECT (src, "  username:     '%s'",
8905       GST_STR_NULL (msg->origin.username));
8906   GST_LOG_OBJECT (src, "  sess_id:      '%s'",
8907       GST_STR_NULL (msg->origin.sess_id));
8908   GST_LOG_OBJECT (src, "  sess_version: '%s'",
8909       GST_STR_NULL (msg->origin.sess_version));
8910   GST_LOG_OBJECT (src, "  nettype:      '%s'",
8911       GST_STR_NULL (msg->origin.nettype));
8912   GST_LOG_OBJECT (src, "  addrtype:     '%s'",
8913       GST_STR_NULL (msg->origin.addrtype));
8914   GST_LOG_OBJECT (src, "  addr:         '%s'", GST_STR_NULL (msg->origin.addr));
8915   GST_LOG_OBJECT (src, " session_name:  '%s'",
8916       GST_STR_NULL (msg->session_name));
8917   GST_LOG_OBJECT (src, " information:   '%s'", GST_STR_NULL (msg->information));
8918   GST_LOG_OBJECT (src, " uri:           '%s'", GST_STR_NULL (msg->uri));
8919
8920   if (msg->emails && msg->emails->len > 0) {
8921     guint i;
8922
8923     GST_LOG_OBJECT (src, " emails:");
8924     for (i = 0; i < msg->emails->len; i++) {
8925       GST_LOG_OBJECT (src, "  email '%s'", g_array_index (msg->emails, gchar *,
8926               i));
8927     }
8928   }
8929   if (msg->phones && msg->phones->len > 0) {
8930     guint i;
8931
8932     GST_LOG_OBJECT (src, " phones:");
8933     for (i = 0; i < msg->phones->len; i++) {
8934       GST_LOG_OBJECT (src, "  phone '%s'", g_array_index (msg->phones, gchar *,
8935               i));
8936     }
8937   }
8938   GST_LOG_OBJECT (src, " connection:");
8939   GST_LOG_OBJECT (src, "  nettype:      '%s'",
8940       GST_STR_NULL (msg->connection.nettype));
8941   GST_LOG_OBJECT (src, "  addrtype:     '%s'",
8942       GST_STR_NULL (msg->connection.addrtype));
8943   GST_LOG_OBJECT (src, "  address:      '%s'",
8944       GST_STR_NULL (msg->connection.address));
8945   GST_LOG_OBJECT (src, "  ttl:          '%u'", msg->connection.ttl);
8946   GST_LOG_OBJECT (src, "  addr_number:  '%u'", msg->connection.addr_number);
8947   if (msg->bandwidths && msg->bandwidths->len > 0) {
8948     guint i;
8949
8950     GST_LOG_OBJECT (src, " bandwidths:");
8951     for (i = 0; i < msg->bandwidths->len; i++) {
8952       GstSDPBandwidth *bw =
8953           &g_array_index (msg->bandwidths, GstSDPBandwidth, i);
8954
8955       GST_LOG_OBJECT (src, "  type:         '%s'", GST_STR_NULL (bw->bwtype));
8956       GST_LOG_OBJECT (src, "  bandwidth:    '%u'", bw->bandwidth);
8957     }
8958   }
8959   GST_LOG_OBJECT (src, " key:");
8960   GST_LOG_OBJECT (src, "  type:         '%s'", GST_STR_NULL (msg->key.type));
8961   GST_LOG_OBJECT (src, "  data:         '%s'", GST_STR_NULL (msg->key.data));
8962   if (msg->attributes && msg->attributes->len > 0) {
8963     guint i;
8964
8965     GST_LOG_OBJECT (src, " attributes:");
8966     for (i = 0; i < msg->attributes->len; i++) {
8967       GstSDPAttribute *attr =
8968           &g_array_index (msg->attributes, GstSDPAttribute, i);
8969
8970       GST_LOG_OBJECT (src, "  attribute '%s' : '%s'", attr->key, attr->value);
8971     }
8972   }
8973   if (msg->medias && msg->medias->len > 0) {
8974     guint i;
8975
8976     GST_LOG_OBJECT (src, " medias:");
8977     for (i = 0; i < msg->medias->len; i++) {
8978       GST_LOG_OBJECT (src, "  media %u:", i);
8979       gst_rtspsrc_print_sdp_media (src, &g_array_index (msg->medias,
8980               GstSDPMedia, i));
8981     }
8982   }
8983   GST_LOG_OBJECT (src, "--------------------------------------------");
8984 }