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