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