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