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