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