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