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