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