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