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