udpsrc: fix typo in multicast join error message
[platform/upstream/gstreamer.git] / gst / udp / gstudpsrc.c
1 /* GStreamer
2  * Copyright (C) <2005> Wim Taymans <wim@fluendo.com>
3  * Copyright (C) <2005> Nokia Corporation <kai.vehmanen@nokia.com>
4  * Copyright (C) <2012> Collabora Ltd.
5  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
6  * Copyright (C) 2014 Tim-Philipp Müller <tim@centricular.com>
7  * Copyright (C) 2014 Centricular Ltd
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:element-udpsrc
27  * @see_also: udpsink, multifdsink
28  *
29  * udpsrc is a network source that reads UDP packets from the network.
30  * It can be combined with RTP depayloaders to implement RTP streaming.
31  *
32  * The udpsrc element supports automatic port allocation by setting the
33  * #GstUDPSrc:port property to 0. After setting the udpsrc to PAUSED, the
34  * allocated port can be obtained by reading the port property.
35  *
36  * udpsrc can read from multicast groups by setting the #GstUDPSrc:multicast-group
37  * property to the IP address of the multicast group.
38  *
39  * Alternatively one can provide a custom socket to udpsrc with the #GstUDPSrc:socket
40  * property, udpsrc will then not allocate a socket itself but use the provided
41  * one.
42  *
43  * The #GstUDPSrc:caps property is mainly used to give a type to the UDP packet
44  * so that they can be autoplugged in GStreamer pipelines. This is very useful
45  * for RTP implementations where the contents of the UDP packets is transfered
46  * out-of-bounds using SDP or other means.
47  *
48  * The #GstUDPSrc:buffer-size property is used to change the default kernel
49  * buffersizes used for receiving packets. The buffer size may be increased for
50  * high-volume connections, or may be decreased to limit the possible backlog of
51  * incoming data. The system places an absolute limit on these values, on Linux,
52  * for example, the default buffer size is typically 50K and can be increased to
53  * maximally 100K.
54  *
55  * The #GstUDPSrc:skip-first-bytes property is used to strip off an arbitrary
56  * number of bytes from the start of the raw udp packet and can be used to strip
57  * off proprietary header, for example.
58  *
59  * The udpsrc is always a live source. It does however not provide a #GstClock,
60  * this is left for upstream elements such as an RTP session manager or demuxer
61  * (such as an MPEG demuxer). As with all live sources, the captured buffers
62  * will have their timestamp set to the current running time of the pipeline.
63  *
64  * udpsrc implements a #GstURIHandler interface that handles udp://host:port
65  * type URIs.
66  *
67  * If the #GstUDPSrc:timeout property is set to a value bigger than 0, udpsrc
68  * will generate an element message named
69  * <classname>&quot;GstUDPSrcTimeout&quot;</classname>
70  * if no data was recieved in the given timeout.
71  * The message's structure contains one field:
72  * <itemizedlist>
73  * <listitem>
74  *   <para>
75  *   #guint64
76  *   <classname>&quot;timeout&quot;</classname>: the timeout in microseconds that
77  *   expired when waiting for data.
78  *   </para>
79  * </listitem>
80  * </itemizedlist>
81  * The message is typically used to detect that no UDP arrives in the receiver
82  * because it is blocked by a firewall.
83  *
84  * A custom file descriptor can be configured with the
85  * #GstUDPSrc:socket property. The socket will be closed when setting
86  * the element to READY by default. This behaviour can be overriden
87  * with the #GstUDPSrc:close-socket property, in which case the
88  * application is responsible for closing the file descriptor.
89  *
90  * <refsect2>
91  * <title>Examples</title>
92  * |[
93  * gst-launch-1.0 -v udpsrc ! fakesink dump=1
94  * ]| A pipeline to read from the default port and dump the udp packets.
95  * To actually generate udp packets on the default port one can use the
96  * udpsink element. When running the following pipeline in another terminal, the
97  * above mentioned pipeline should dump data packets to the console.
98  * |[
99  * gst-launch-1.0 -v audiotestsrc ! udpsink
100  * ]|
101  * |[
102  * gst-launch-1.0 -v udpsrc port=0 ! fakesink
103  * ]| read udp packets from a free port.
104  * </refsect2>
105  */
106 #ifdef HAVE_CONFIG_H
107 #include "config.h"
108 #endif
109
110 /* Needed to get struct in6_pktinfo.
111  * Also all these have to be before glib.h is included as
112  * otherwise struct in6_pktinfo is not defined completely
113  * due to broken glibc headers */
114 #define _GNU_SOURCE
115 /* Needed for OSX/iOS to define the IPv6 variants */
116 #define __APPLE_USE_RFC_3542
117 #include <sys/types.h>
118 #ifdef HAVE_SYS_SOCKET_H
119 #include <sys/socket.h>
120 #endif
121
122 #include <string.h>
123 #include "gstudpsrc.h"
124
125 #include <gst/net/gstnetaddressmeta.h>
126
127 #include <gio/gnetworking.h>
128
129 /* Required for other parts of in_pktinfo / in6_pktinfo but only
130  * on non-Windows and can be included after glib.h */
131 #ifndef G_PLATFORM_WIN32
132 #include <netinet/ip.h>
133 #endif
134
135 /* Control messages for getting the destination address */
136 #ifdef IP_PKTINFO
137 GType gst_ip_pktinfo_message_get_type (void);
138
139 #define GST_TYPE_IP_PKTINFO_MESSAGE         (gst_ip_pktinfo_message_get_type ())
140 #define GST_IP_PKTINFO_MESSAGE(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), GST_TYPE_IP_PKTINFO_MESSAGE, GstIPPktinfoMessage))
141 #define GST_IP_PKTINFO_MESSAGE_CLASS(c)     (G_TYPE_CHECK_CLASS_CAST ((c), GST_TYPE_IP_PKTINFO_MESSAGE, GstIPPktinfoMessageClass))
142 #define GST_IS_IP_PKTINFO_MESSAGE(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), GST_TYPE_IP_PKTINFO_MESSAGE))
143 #define GST_IS_IP_PKTINFO_MESSAGE_CLASS(c)  (G_TYPE_CHECK_CLASS_TYPE ((c), GST_TYPE_IP_PKTINFO_MESSAGE))
144 #define GST_IP_PKTINFO_MESSAGE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GST_TYPE_IP_PKTINFO_MESSAGE, GstIPPktinfoMessageClass))
145
146 typedef struct _GstIPPktinfoMessage GstIPPktinfoMessage;
147 typedef struct _GstIPPktinfoMessageClass GstIPPktinfoMessageClass;
148
149 struct _GstIPPktinfoMessageClass
150 {
151   GSocketControlMessageClass parent_class;
152
153 };
154
155 struct _GstIPPktinfoMessage
156 {
157   GSocketControlMessage parent;
158
159   guint ifindex;
160 #ifndef G_PLATFORM_WIN32
161 #ifndef __NetBSD__
162   struct in_addr spec_dst;
163 #endif
164 #endif
165   struct in_addr addr;
166 };
167
168 G_DEFINE_TYPE (GstIPPktinfoMessage, gst_ip_pktinfo_message,
169     G_TYPE_SOCKET_CONTROL_MESSAGE);
170
171 static gsize
172 gst_ip_pktinfo_message_get_size (GSocketControlMessage * message)
173 {
174   return sizeof (struct in_pktinfo);
175 }
176
177 static int
178 gst_ip_pktinfo_message_get_level (GSocketControlMessage * message)
179 {
180   return IPPROTO_IP;
181 }
182
183 static int
184 gst_ip_pktinfo_message_get_msg_type (GSocketControlMessage * message)
185 {
186   return IP_PKTINFO;
187 }
188
189 static GSocketControlMessage *
190 gst_ip_pktinfo_message_deserialize (gint level,
191     gint type, gsize size, gpointer data)
192 {
193   struct in_pktinfo *pktinfo;
194   GstIPPktinfoMessage *message;
195
196   if (level != IPPROTO_IP || type != IP_PKTINFO)
197     return NULL;
198
199   if (size < sizeof (struct in_pktinfo))
200     return NULL;
201
202   pktinfo = data;
203
204   message = g_object_new (GST_TYPE_IP_PKTINFO_MESSAGE, NULL);
205   message->ifindex = pktinfo->ipi_ifindex;
206 #ifndef G_PLATFORM_WIN32
207 #ifndef __NetBSD__
208   message->spec_dst = pktinfo->ipi_spec_dst;
209 #endif
210 #endif
211   message->addr = pktinfo->ipi_addr;
212
213   return G_SOCKET_CONTROL_MESSAGE (message);
214 }
215
216 static void
217 gst_ip_pktinfo_message_init (GstIPPktinfoMessage * message)
218 {
219 }
220
221 static void
222 gst_ip_pktinfo_message_class_init (GstIPPktinfoMessageClass * class)
223 {
224   GSocketControlMessageClass *scm_class;
225
226   scm_class = G_SOCKET_CONTROL_MESSAGE_CLASS (class);
227   scm_class->get_size = gst_ip_pktinfo_message_get_size;
228   scm_class->get_level = gst_ip_pktinfo_message_get_level;
229   scm_class->get_type = gst_ip_pktinfo_message_get_msg_type;
230   scm_class->deserialize = gst_ip_pktinfo_message_deserialize;
231 }
232 #endif
233
234 #ifdef IPV6_PKTINFO
235 GType gst_ipv6_pktinfo_message_get_type (void);
236
237 #define GST_TYPE_IPV6_PKTINFO_MESSAGE         (gst_ipv6_pktinfo_message_get_type ())
238 #define GST_IPV6_PKTINFO_MESSAGE(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), GST_TYPE_IPV6_PKTINFO_MESSAGE, GstIPV6PktinfoMessage))
239 #define GST_IPV6_PKTINFO_MESSAGE_CLASS(c)     (G_TYPE_CHECK_CLASS_CAST ((c), GST_TYPE_IPV6_PKTINFO_MESSAGE, GstIPV6PktinfoMessageClass))
240 #define GST_IS_IPV6_PKTINFO_MESSAGE(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), GST_TYPE_IPV6_PKTINFO_MESSAGE))
241 #define GST_IS_IPV6_PKTINFO_MESSAGE_CLASS(c)  (G_TYPE_CHECK_CLASS_TYPE ((c), GST_TYPE_IPV6_PKTINFO_MESSAGE))
242 #define GST_IPV6_PKTINFO_MESSAGE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GST_TYPE_IPV6_PKTINFO_MESSAGE, GstIPV6PktinfoMessageClass))
243
244 typedef struct _GstIPV6PktinfoMessage GstIPV6PktinfoMessage;
245 typedef struct _GstIPV6PktinfoMessageClass GstIPV6PktinfoMessageClass;
246
247 struct _GstIPV6PktinfoMessageClass
248 {
249   GSocketControlMessageClass parent_class;
250
251 };
252
253 struct _GstIPV6PktinfoMessage
254 {
255   GSocketControlMessage parent;
256
257   guint ifindex;
258   struct in6_addr addr;
259 };
260
261 G_DEFINE_TYPE (GstIPV6PktinfoMessage, gst_ipv6_pktinfo_message,
262     G_TYPE_SOCKET_CONTROL_MESSAGE);
263
264 static gsize
265 gst_ipv6_pktinfo_message_get_size (GSocketControlMessage * message)
266 {
267   return sizeof (struct in6_pktinfo);
268 }
269
270 static int
271 gst_ipv6_pktinfo_message_get_level (GSocketControlMessage * message)
272 {
273   return IPPROTO_IPV6;
274 }
275
276 static int
277 gst_ipv6_pktinfo_message_get_msg_type (GSocketControlMessage * message)
278 {
279   return IPV6_PKTINFO;
280 }
281
282 static GSocketControlMessage *
283 gst_ipv6_pktinfo_message_deserialize (gint level,
284     gint type, gsize size, gpointer data)
285 {
286   struct in6_pktinfo *pktinfo;
287   GstIPV6PktinfoMessage *message;
288
289   if (level != IPPROTO_IPV6 || type != IPV6_PKTINFO)
290     return NULL;
291
292   if (size < sizeof (struct in6_pktinfo))
293     return NULL;
294
295   pktinfo = data;
296
297   message = g_object_new (GST_TYPE_IPV6_PKTINFO_MESSAGE, NULL);
298   message->ifindex = pktinfo->ipi6_ifindex;
299   message->addr = pktinfo->ipi6_addr;
300
301   return G_SOCKET_CONTROL_MESSAGE (message);
302 }
303
304 static void
305 gst_ipv6_pktinfo_message_init (GstIPV6PktinfoMessage * message)
306 {
307 }
308
309 static void
310 gst_ipv6_pktinfo_message_class_init (GstIPV6PktinfoMessageClass * class)
311 {
312   GSocketControlMessageClass *scm_class;
313
314   scm_class = G_SOCKET_CONTROL_MESSAGE_CLASS (class);
315   scm_class->get_size = gst_ipv6_pktinfo_message_get_size;
316   scm_class->get_level = gst_ipv6_pktinfo_message_get_level;
317   scm_class->get_type = gst_ipv6_pktinfo_message_get_msg_type;
318   scm_class->deserialize = gst_ipv6_pktinfo_message_deserialize;
319 }
320
321 #endif
322
323 #ifdef IP_RECVDSTADDR
324 GType gst_ip_recvdstaddr_message_get_type (void);
325
326 #define GST_TYPE_IP_RECVDSTADDR_MESSAGE         (gst_ip_recvdstaddr_message_get_type ())
327 #define GST_IP_RECVDSTADDR_MESSAGE(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), GST_TYPE_IP_RECVDSTADDR_MESSAGE, GstIPRecvdstaddrMessage))
328 #define GST_IP_RECVDSTADDR_MESSAGE_CLASS(c)     (G_TYPE_CHECK_CLASS_CAST ((c), GST_TYPE_IP_RECVDSTADDR_MESSAGE, GstIPRecvdstaddrMessageClass))
329 #define GST_IS_IP_RECVDSTADDR_MESSAGE(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), GST_TYPE_IP_RECVDSTADDR_MESSAGE))
330 #define GST_IS_IP_RECVDSTADDR_MESSAGE_CLASS(c)  (G_TYPE_CHECK_CLASS_TYPE ((c), GST_TYPE_IP_RECVDSTADDR_MESSAGE))
331 #define GST_IP_RECVDSTADDR_MESSAGE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GST_TYPE_IP_RECVDSTADDR_MESSAGE, GstIPRecvdstaddrMessageClass))
332
333 typedef struct _GstIPRecvdstaddrMessage GstIPRecvdstaddrMessage;
334 typedef struct _GstIPRecvdstaddrMessageClass GstIPRecvdstaddrMessageClass;
335
336 struct _GstIPRecvdstaddrMessageClass
337 {
338   GSocketControlMessageClass parent_class;
339
340 };
341
342 struct _GstIPRecvdstaddrMessage
343 {
344   GSocketControlMessage parent;
345
346   guint ifindex;
347   struct in_addr addr;
348 };
349
350 G_DEFINE_TYPE (GstIPRecvdstaddrMessage, gst_ip_recvdstaddr_message,
351     G_TYPE_SOCKET_CONTROL_MESSAGE);
352
353 static gsize
354 gst_ip_recvdstaddr_message_get_size (GSocketControlMessage * message)
355 {
356   return sizeof (struct in_addr);
357 }
358
359 static int
360 gst_ip_recvdstaddr_message_get_level (GSocketControlMessage * message)
361 {
362   return IPPROTO_IP;
363 }
364
365 static int
366 gst_ip_recvdstaddr_message_get_msg_type (GSocketControlMessage * message)
367 {
368   return IP_RECVDSTADDR;
369 }
370
371 static GSocketControlMessage *
372 gst_ip_recvdstaddr_message_deserialize (gint level,
373     gint type, gsize size, gpointer data)
374 {
375   struct in_addr *addr;
376   GstIPRecvdstaddrMessage *message;
377
378   if (level != IPPROTO_IP || type != IP_RECVDSTADDR)
379     return NULL;
380
381   if (size < sizeof (struct in_addr))
382     return NULL;
383
384   addr = data;
385
386   message = g_object_new (GST_TYPE_IP_RECVDSTADDR_MESSAGE, NULL);
387   message->addr = *addr;
388
389   return G_SOCKET_CONTROL_MESSAGE (message);
390 }
391
392 static void
393 gst_ip_recvdstaddr_message_init (GstIPRecvdstaddrMessage * message)
394 {
395 }
396
397 static void
398 gst_ip_recvdstaddr_message_class_init (GstIPRecvdstaddrMessageClass * class)
399 {
400   GSocketControlMessageClass *scm_class;
401
402   scm_class = G_SOCKET_CONTROL_MESSAGE_CLASS (class);
403   scm_class->get_size = gst_ip_recvdstaddr_message_get_size;
404   scm_class->get_level = gst_ip_recvdstaddr_message_get_level;
405   scm_class->get_type = gst_ip_recvdstaddr_message_get_msg_type;
406   scm_class->deserialize = gst_ip_recvdstaddr_message_deserialize;
407 }
408 #endif
409
410 /* not 100% correct, but a good upper bound for memory allocation purposes */
411 #define MAX_IPV4_UDP_PACKET_SIZE (65536 - 8)
412
413 GST_DEBUG_CATEGORY_STATIC (udpsrc_debug);
414 #define GST_CAT_DEFAULT (udpsrc_debug)
415
416 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
417     GST_PAD_SRC,
418     GST_PAD_ALWAYS,
419     GST_STATIC_CAPS_ANY);
420
421 #define UDP_DEFAULT_PORT                5004
422 #define UDP_DEFAULT_MULTICAST_GROUP     "0.0.0.0"
423 #define UDP_DEFAULT_MULTICAST_IFACE     NULL
424 #define UDP_DEFAULT_URI                 "udp://"UDP_DEFAULT_MULTICAST_GROUP":"G_STRINGIFY(UDP_DEFAULT_PORT)
425 #define UDP_DEFAULT_CAPS                NULL
426 #define UDP_DEFAULT_SOCKET              NULL
427 #define UDP_DEFAULT_BUFFER_SIZE         0
428 #define UDP_DEFAULT_TIMEOUT             0
429 #define UDP_DEFAULT_SKIP_FIRST_BYTES    0
430 #define UDP_DEFAULT_CLOSE_SOCKET       TRUE
431 #define UDP_DEFAULT_USED_SOCKET        NULL
432 #define UDP_DEFAULT_AUTO_MULTICAST     TRUE
433 #define UDP_DEFAULT_REUSE              TRUE
434 #define UDP_DEFAULT_LOOP               TRUE
435 #define UDP_DEFAULT_RETRIEVE_SENDER_ADDRESS TRUE
436
437 enum
438 {
439   PROP_0,
440
441   PROP_PORT,
442   PROP_MULTICAST_GROUP,
443   PROP_MULTICAST_IFACE,
444   PROP_URI,
445   PROP_CAPS,
446   PROP_SOCKET,
447   PROP_BUFFER_SIZE,
448   PROP_TIMEOUT,
449   PROP_SKIP_FIRST_BYTES,
450   PROP_CLOSE_SOCKET,
451   PROP_USED_SOCKET,
452   PROP_AUTO_MULTICAST,
453   PROP_REUSE,
454   PROP_ADDRESS,
455   PROP_LOOP,
456   PROP_RETRIEVE_SENDER_ADDRESS
457 };
458
459 static void gst_udpsrc_uri_handler_init (gpointer g_iface, gpointer iface_data);
460
461 static GstCaps *gst_udpsrc_getcaps (GstBaseSrc * src, GstCaps * filter);
462 static GstFlowReturn gst_udpsrc_create (GstPushSrc * psrc, GstBuffer ** buf);
463 static gboolean gst_udpsrc_close (GstUDPSrc * src);
464 static gboolean gst_udpsrc_unlock (GstBaseSrc * bsrc);
465 static gboolean gst_udpsrc_unlock_stop (GstBaseSrc * bsrc);
466 static gboolean gst_udpsrc_negotiate (GstBaseSrc * basesrc);
467
468 static void gst_udpsrc_finalize (GObject * object);
469
470 static void gst_udpsrc_set_property (GObject * object, guint prop_id,
471     const GValue * value, GParamSpec * pspec);
472 static void gst_udpsrc_get_property (GObject * object, guint prop_id,
473     GValue * value, GParamSpec * pspec);
474
475 static GstStateChangeReturn gst_udpsrc_change_state (GstElement * element,
476     GstStateChange transition);
477
478 #define gst_udpsrc_parent_class parent_class
479 G_DEFINE_TYPE_WITH_CODE (GstUDPSrc, gst_udpsrc, GST_TYPE_PUSH_SRC,
480     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_udpsrc_uri_handler_init));
481
482 static void
483 gst_udpsrc_class_init (GstUDPSrcClass * klass)
484 {
485   GObjectClass *gobject_class;
486   GstElementClass *gstelement_class;
487   GstBaseSrcClass *gstbasesrc_class;
488   GstPushSrcClass *gstpushsrc_class;
489
490   gobject_class = (GObjectClass *) klass;
491   gstelement_class = (GstElementClass *) klass;
492   gstbasesrc_class = (GstBaseSrcClass *) klass;
493   gstpushsrc_class = (GstPushSrcClass *) klass;
494
495   GST_DEBUG_CATEGORY_INIT (udpsrc_debug, "udpsrc", 0, "UDP src");
496
497 #ifdef IP_PKTINFO
498   GST_TYPE_IP_PKTINFO_MESSAGE;
499 #endif
500 #ifdef IPV6_PKTINFO
501   GST_TYPE_IPV6_PKTINFO_MESSAGE;
502 #endif
503 #ifdef IP_RECVDSTADDR
504   GST_TYPE_IP_RECVDSTADDR_MESSAGE;
505 #endif
506
507   gobject_class->set_property = gst_udpsrc_set_property;
508   gobject_class->get_property = gst_udpsrc_get_property;
509   gobject_class->finalize = gst_udpsrc_finalize;
510
511   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PORT,
512       g_param_spec_int ("port", "Port",
513           "The port to receive the packets from, 0=allocate", 0, G_MAXUINT16,
514           UDP_DEFAULT_PORT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
515   /* FIXME 2.0: Remove multicast-group property */
516 #ifndef GST_REMOVE_DEPRECATED
517   g_object_class_install_property (gobject_class, PROP_MULTICAST_GROUP,
518       g_param_spec_string ("multicast-group", "Multicast Group",
519           "The Address of multicast group to join. (DEPRECATED: "
520           "Use address property instead)", UDP_DEFAULT_MULTICAST_GROUP,
521           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED));
522 #endif
523   g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
524       g_param_spec_string ("multicast-iface", "Multicast Interface",
525           "The network interface on which to join the multicast group."
526           "This allows multiple interfaces seperated by comma. (\"eth0,eth1\")",
527           UDP_DEFAULT_MULTICAST_IFACE,
528           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
529   g_object_class_install_property (gobject_class, PROP_URI,
530       g_param_spec_string ("uri", "URI",
531           "URI in the form of udp://multicast_group:port", UDP_DEFAULT_URI,
532           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
533   g_object_class_install_property (gobject_class, PROP_CAPS,
534       g_param_spec_boxed ("caps", "Caps",
535           "The caps of the source pad", GST_TYPE_CAPS,
536           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
537   g_object_class_install_property (gobject_class, PROP_SOCKET,
538       g_param_spec_object ("socket", "Socket",
539           "Socket to use for UDP reception. (NULL == allocate)",
540           G_TYPE_SOCKET, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
541   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BUFFER_SIZE,
542       g_param_spec_int ("buffer-size", "Buffer Size",
543           "Size of the kernel receive buffer in bytes, 0=default", 0, G_MAXINT,
544           UDP_DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
545   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_TIMEOUT,
546       g_param_spec_uint64 ("timeout", "Timeout",
547           "Post a message after timeout nanoseconds (0 = disabled)", 0,
548           G_MAXUINT64, UDP_DEFAULT_TIMEOUT,
549           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
550   g_object_class_install_property (G_OBJECT_CLASS (klass),
551       PROP_SKIP_FIRST_BYTES, g_param_spec_int ("skip-first-bytes",
552           "Skip first bytes", "number of bytes to skip for each udp packet", 0,
553           G_MAXINT, UDP_DEFAULT_SKIP_FIRST_BYTES,
554           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
555   g_object_class_install_property (gobject_class, PROP_CLOSE_SOCKET,
556       g_param_spec_boolean ("close-socket", "Close socket",
557           "Close socket if passed as property on state change",
558           UDP_DEFAULT_CLOSE_SOCKET,
559           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
560   g_object_class_install_property (gobject_class, PROP_USED_SOCKET,
561       g_param_spec_object ("used-socket", "Socket Handle",
562           "Socket currently in use for UDP reception. (NULL = no socket)",
563           G_TYPE_SOCKET, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
564   g_object_class_install_property (gobject_class, PROP_AUTO_MULTICAST,
565       g_param_spec_boolean ("auto-multicast", "Auto Multicast",
566           "Automatically join/leave multicast groups",
567           UDP_DEFAULT_AUTO_MULTICAST,
568           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
569   g_object_class_install_property (gobject_class, PROP_REUSE,
570       g_param_spec_boolean ("reuse", "Reuse", "Enable reuse of the port",
571           UDP_DEFAULT_REUSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
572   g_object_class_install_property (gobject_class, PROP_ADDRESS,
573       g_param_spec_string ("address", "Address",
574           "Address to receive packets for. This is equivalent to the "
575           "multicast-group property for now", UDP_DEFAULT_MULTICAST_GROUP,
576           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
577   /**
578    * GstUDPSrc::loop:
579    *
580    * Can be used to disable multicast loopback.
581    *
582    * Since: 1.8
583    */
584   g_object_class_install_property (gobject_class, PROP_LOOP,
585       g_param_spec_boolean ("loop", "Multicast Loopback",
586           "Used for setting the multicast loop parameter. TRUE = enable,"
587           " FALSE = disable", UDP_DEFAULT_LOOP,
588           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
589   /**
590    * GstUDPSrc::retrieve-sender-address:
591    *
592    * Whether to retrieve the sender address and add it to the buffers as
593    * meta. Disabling this might result in minor performance improvements
594    * in certain scenarios.
595    *
596    * Since: 1.10
597    */
598   g_object_class_install_property (gobject_class, PROP_RETRIEVE_SENDER_ADDRESS,
599       g_param_spec_boolean ("retrieve-sender-address",
600           "Retrieve Sender Address",
601           "Whether to retrieve the sender address and add it to buffers as "
602           "meta. Disabling this might result in minor performance improvements "
603           "in certain scenarios", UDP_DEFAULT_RETRIEVE_SENDER_ADDRESS,
604           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
605
606   gst_element_class_add_static_pad_template (gstelement_class, &src_template);
607
608   gst_element_class_set_static_metadata (gstelement_class,
609       "UDP packet receiver", "Source/Network",
610       "Receive data over the network via UDP",
611       "Wim Taymans <wim@fluendo.com>, "
612       "Thijs Vermeir <thijs.vermeir@barco.com>");
613
614   gstelement_class->change_state = gst_udpsrc_change_state;
615
616   gstbasesrc_class->unlock = gst_udpsrc_unlock;
617   gstbasesrc_class->unlock_stop = gst_udpsrc_unlock_stop;
618   gstbasesrc_class->get_caps = gst_udpsrc_getcaps;
619   gstbasesrc_class->negotiate = gst_udpsrc_negotiate;
620
621   gstpushsrc_class->create = gst_udpsrc_create;
622 }
623
624 static void
625 gst_udpsrc_init (GstUDPSrc * udpsrc)
626 {
627   udpsrc->uri =
628       g_strdup_printf ("udp://%s:%u", UDP_DEFAULT_MULTICAST_GROUP,
629       UDP_DEFAULT_PORT);
630
631   udpsrc->address = g_strdup (UDP_DEFAULT_MULTICAST_GROUP);
632   udpsrc->port = UDP_DEFAULT_PORT;
633   udpsrc->socket = UDP_DEFAULT_SOCKET;
634   udpsrc->multi_iface = g_strdup (UDP_DEFAULT_MULTICAST_IFACE);
635   udpsrc->buffer_size = UDP_DEFAULT_BUFFER_SIZE;
636   udpsrc->timeout = UDP_DEFAULT_TIMEOUT;
637   udpsrc->skip_first_bytes = UDP_DEFAULT_SKIP_FIRST_BYTES;
638   udpsrc->close_socket = UDP_DEFAULT_CLOSE_SOCKET;
639   udpsrc->external_socket = (udpsrc->socket != NULL);
640   udpsrc->auto_multicast = UDP_DEFAULT_AUTO_MULTICAST;
641   udpsrc->used_socket = UDP_DEFAULT_USED_SOCKET;
642   udpsrc->reuse = UDP_DEFAULT_REUSE;
643   udpsrc->loop = UDP_DEFAULT_LOOP;
644   udpsrc->retrieve_sender_address = UDP_DEFAULT_RETRIEVE_SENDER_ADDRESS;
645
646   /* configure basesrc to be a live source */
647   gst_base_src_set_live (GST_BASE_SRC (udpsrc), TRUE);
648   /* make basesrc output a segment in time */
649   gst_base_src_set_format (GST_BASE_SRC (udpsrc), GST_FORMAT_TIME);
650   /* make basesrc set timestamps on outgoing buffers based on the running_time
651    * when they were captured */
652   gst_base_src_set_do_timestamp (GST_BASE_SRC (udpsrc), TRUE);
653 }
654
655 static void
656 gst_udpsrc_finalize (GObject * object)
657 {
658   GstUDPSrc *udpsrc;
659
660   udpsrc = GST_UDPSRC (object);
661
662   if (udpsrc->caps)
663     gst_caps_unref (udpsrc->caps);
664   udpsrc->caps = NULL;
665
666   g_free (udpsrc->multi_iface);
667   udpsrc->multi_iface = NULL;
668
669   g_free (udpsrc->uri);
670   udpsrc->uri = NULL;
671
672   g_free (udpsrc->address);
673   udpsrc->address = NULL;
674
675   if (udpsrc->socket)
676     g_object_unref (udpsrc->socket);
677   udpsrc->socket = NULL;
678
679   if (udpsrc->used_socket)
680     g_object_unref (udpsrc->used_socket);
681   udpsrc->used_socket = NULL;
682
683   G_OBJECT_CLASS (parent_class)->finalize (object);
684 }
685
686 static GstCaps *
687 gst_udpsrc_getcaps (GstBaseSrc * src, GstCaps * filter)
688 {
689   GstUDPSrc *udpsrc;
690   GstCaps *caps, *result;
691
692   udpsrc = GST_UDPSRC (src);
693
694   GST_OBJECT_LOCK (src);
695   if ((caps = udpsrc->caps))
696     gst_caps_ref (caps);
697   GST_OBJECT_UNLOCK (src);
698
699   if (caps) {
700     if (filter) {
701       result = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
702       gst_caps_unref (caps);
703     } else {
704       result = caps;
705     }
706   } else {
707     result = (filter) ? gst_caps_ref (filter) : gst_caps_new_any ();
708   }
709   return result;
710 }
711
712 static void
713 gst_udpsrc_reset_memory_allocator (GstUDPSrc * src)
714 {
715   if (src->mem != NULL) {
716     gst_memory_unmap (src->mem, &src->map);
717     gst_memory_unref (src->mem);
718     src->mem = NULL;
719   }
720   if (src->mem_max != NULL) {
721     gst_memory_unmap (src->mem_max, &src->map_max);
722     gst_memory_unref (src->mem_max);
723     src->mem_max = NULL;
724   }
725
726   src->vec[0].buffer = NULL;
727   src->vec[0].size = 0;
728   src->vec[1].buffer = NULL;
729   src->vec[1].size = 0;
730
731   if (src->allocator != NULL) {
732     gst_object_unref (src->allocator);
733     src->allocator = NULL;
734   }
735 }
736
737 static gboolean
738 gst_udpsrc_negotiate (GstBaseSrc * basesrc)
739 {
740   GstUDPSrc *src = GST_UDPSRC_CAST (basesrc);
741   gboolean ret;
742
743   /* just chain up to the default implementation, we just want to
744    * retrieve the allocator at the end of it (if there is one) */
745   ret = GST_BASE_SRC_CLASS (parent_class)->negotiate (basesrc);
746
747   if (ret) {
748     GstAllocationParams new_params;
749     GstAllocator *new_allocator = NULL;
750
751     /* retrieve new allocator */
752     gst_base_src_get_allocator (basesrc, &new_allocator, &new_params);
753
754     if (src->allocator != new_allocator ||
755         memcmp (&src->params, &new_params, sizeof (GstAllocationParams)) != 0) {
756       /* drop old allocator and throw away any memory allocated with it */
757       gst_udpsrc_reset_memory_allocator (src);
758
759       /* and save the new allocator and/or new allocation parameters */
760       src->allocator = new_allocator;
761       src->params = new_params;
762
763       GST_INFO_OBJECT (src, "new allocator: %" GST_PTR_FORMAT, new_allocator);
764     }
765   }
766
767   return ret;
768 }
769
770 static gboolean
771 gst_udpsrc_alloc_mem (GstUDPSrc * src, GstMemory ** p_mem, GstMapInfo * map,
772     gsize size)
773 {
774   GstMemory *mem;
775
776   mem = gst_allocator_alloc (src->allocator, size, &src->params);
777
778   if (!gst_memory_map (mem, map, GST_MAP_WRITE)) {
779     gst_memory_unref (mem);
780     memset (map, 0, sizeof (GstMapInfo));
781     return FALSE;
782   }
783   *p_mem = mem;
784   return TRUE;
785 }
786
787 static gboolean
788 gst_udpsrc_ensure_mem (GstUDPSrc * src)
789 {
790   if (src->mem == NULL) {
791     gsize mem_size = 1500;      /* typical max. MTU */
792
793     /* if packets are likely to be smaller, just use that size, otherwise
794      * default to assuming incoming packets are around MTU size */
795     if (src->max_size > 0 && src->max_size < mem_size)
796       mem_size = src->max_size;
797
798     if (!gst_udpsrc_alloc_mem (src, &src->mem, &src->map, mem_size))
799       return FALSE;
800
801     src->vec[0].buffer = src->map.data;
802     src->vec[0].size = src->map.size;
803   }
804
805   if (src->mem_max == NULL) {
806     gsize max_size = MAX_IPV4_UDP_PACKET_SIZE;
807
808     if (!gst_udpsrc_alloc_mem (src, &src->mem_max, &src->map_max, max_size))
809       return FALSE;
810
811     src->vec[1].buffer = src->map_max.data;
812     src->vec[1].size = src->map_max.size;
813   }
814
815   return TRUE;
816 }
817
818 static void
819 gst_udpsrc_create_cancellable (GstUDPSrc * src)
820 {
821   GPollFD pollfd;
822
823   src->cancellable = g_cancellable_new ();
824   src->made_cancel_fd = g_cancellable_make_pollfd (src->cancellable, &pollfd);
825 }
826
827 static void
828 gst_udpsrc_free_cancellable (GstUDPSrc * src)
829 {
830   if (src->made_cancel_fd) {
831     g_cancellable_release_fd (src->cancellable);
832     src->made_cancel_fd = FALSE;
833   }
834   g_object_unref (src->cancellable);
835   src->cancellable = NULL;
836 }
837
838 static GstFlowReturn
839 gst_udpsrc_create (GstPushSrc * psrc, GstBuffer ** buf)
840 {
841   GstUDPSrc *udpsrc;
842   GstBuffer *outbuf = NULL;
843   GSocketAddress *saddr = NULL;
844   GSocketAddress **p_saddr;
845   gint flags = G_SOCKET_MSG_NONE;
846   gboolean try_again;
847   GError *err = NULL;
848   gssize res;
849   gsize offset;
850   GSocketControlMessage **msgs = NULL;
851   GSocketControlMessage ***p_msgs;
852   gint n_msgs = 0, i;
853
854   udpsrc = GST_UDPSRC_CAST (psrc);
855
856   if (!gst_udpsrc_ensure_mem (udpsrc))
857     goto memory_alloc_error;
858
859   /* optimization: use messages only in multicast mode and
860    * if we can't let the kernel do the filtering for us */
861   p_msgs =
862       (g_inet_address_get_is_multicast (g_inet_socket_address_get_address
863           (udpsrc->addr))) ? &msgs : NULL;
864 #ifdef IP_MULTICAST_ALL
865   if (g_inet_address_get_family (g_inet_socket_address_get_address
866           (udpsrc->addr)) == G_SOCKET_FAMILY_IPV4)
867     p_msgs = NULL;
868 #endif
869
870   /* Retrieve sender address unless we've been configured not to do so */
871   p_saddr = (udpsrc->retrieve_sender_address) ? &saddr : NULL;
872
873 retry:
874   if (saddr != NULL) {
875     g_object_unref (saddr);
876     saddr = NULL;
877   }
878
879   do {
880     gint64 timeout;
881
882     try_again = FALSE;
883
884     if (udpsrc->timeout)
885       timeout = udpsrc->timeout / 1000;
886     else
887       timeout = -1;
888
889     GST_LOG_OBJECT (udpsrc, "doing select, timeout %" G_GINT64_FORMAT, timeout);
890
891     if (!g_socket_condition_timed_wait (udpsrc->used_socket, G_IO_IN | G_IO_PRI,
892             timeout, udpsrc->cancellable, &err)) {
893       if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)
894           || g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
895         goto stopped;
896       } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
897         g_clear_error (&err);
898         /* timeout, post element message */
899         gst_element_post_message (GST_ELEMENT_CAST (udpsrc),
900             gst_message_new_element (GST_OBJECT_CAST (udpsrc),
901                 gst_structure_new ("GstUDPSrcTimeout",
902                     "timeout", G_TYPE_UINT64, udpsrc->timeout, NULL)));
903       } else {
904         goto select_error;
905       }
906
907       try_again = TRUE;
908     }
909   } while (G_UNLIKELY (try_again));
910
911   res =
912       g_socket_receive_message (udpsrc->used_socket, p_saddr, udpsrc->vec, 2,
913       p_msgs, &n_msgs, &flags, udpsrc->cancellable, &err);
914
915   if (G_UNLIKELY (res < 0)) {
916     /* G_IO_ERROR_HOST_UNREACHABLE for a UDP socket means that a packet sent
917      * with udpsink generated a "port unreachable" ICMP response. We ignore
918      * that and try again.
919      * On Windows we get G_IO_ERROR_CONNECTION_CLOSED instead */
920 #if GLIB_CHECK_VERSION(2,44,0)
921     if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_HOST_UNREACHABLE) ||
922         g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CONNECTION_CLOSED)) {
923 #else
924     if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_HOST_UNREACHABLE)) {
925 #endif
926       g_clear_error (&err);
927       goto retry;
928     }
929     goto receive_error;
930   }
931
932   /* remember maximum packet size */
933   if (res > udpsrc->max_size)
934     udpsrc->max_size = res;
935
936   /* Retry if multicast and the destination address is not ours. We don't want
937    * to receive arbitrary packets */
938   if (p_msgs) {
939     GInetAddress *iaddr = g_inet_socket_address_get_address (udpsrc->addr);
940     gboolean skip_packet = FALSE;
941     gsize iaddr_size = g_inet_address_get_native_size (iaddr);
942     const guint8 *iaddr_bytes = g_inet_address_to_bytes (iaddr);
943
944     for (i = 0; i < n_msgs && !skip_packet; i++) {
945 #ifdef IP_PKTINFO
946       if (GST_IS_IP_PKTINFO_MESSAGE (msgs[i])) {
947         GstIPPktinfoMessage *msg = GST_IP_PKTINFO_MESSAGE (msgs[i]);
948
949         if (sizeof (msg->addr) == iaddr_size
950             && memcmp (iaddr_bytes, &msg->addr, sizeof (msg->addr)))
951           skip_packet = TRUE;
952       }
953 #endif
954 #ifdef IPV6_PKTINFO
955       if (GST_IS_IPV6_PKTINFO_MESSAGE (msgs[i])) {
956         GstIPV6PktinfoMessage *msg = GST_IPV6_PKTINFO_MESSAGE (msgs[i]);
957
958         if (sizeof (msg->addr) == iaddr_size
959             && memcmp (iaddr_bytes, &msg->addr, sizeof (msg->addr)))
960           skip_packet = TRUE;
961       }
962 #endif
963 #ifdef IP_RECVDSTADDR
964       if (GST_IS_IP_RECVDSTADDR_MESSAGE (msgs[i])) {
965         GstIPRecvdstaddrMessage *msg = GST_IP_RECVDSTADDR_MESSAGE (msgs[i]);
966
967         if (sizeof (msg->addr) == iaddr_size
968             && memcmp (iaddr_bytes, &msg->addr, sizeof (msg->addr)))
969           skip_packet = TRUE;
970       }
971 #endif
972     }
973
974     for (i = 0; i < n_msgs; i++) {
975       g_object_unref (msgs[i]);
976     }
977     g_free (msgs);
978
979     if (skip_packet) {
980       GST_DEBUG_OBJECT (udpsrc,
981           "Dropping packet for a different multicast address");
982       goto retry;
983     }
984   }
985
986   outbuf = gst_buffer_new ();
987
988   /* append first memory chunk to buffer */
989   gst_buffer_append_memory (outbuf, udpsrc->mem);
990
991   /* if the packet didn't fit into the first chunk, add second one as well */
992   if (res > udpsrc->map.size) {
993     gst_buffer_append_memory (outbuf, udpsrc->mem_max);
994     gst_memory_unmap (udpsrc->mem_max, &udpsrc->map_max);
995     udpsrc->vec[1].buffer = NULL;
996     udpsrc->vec[1].size = 0;
997     udpsrc->mem_max = NULL;
998   }
999
1000   /* make sure we allocate a new chunk next time (we do this only here because
1001    * we look at map.size to see if the second memory chunk is needed above) */
1002   gst_memory_unmap (udpsrc->mem, &udpsrc->map);
1003   udpsrc->vec[0].buffer = NULL;
1004   udpsrc->vec[0].size = 0;
1005   udpsrc->mem = NULL;
1006
1007   offset = udpsrc->skip_first_bytes;
1008
1009   if (G_UNLIKELY (offset > 0 && res < offset))
1010     goto skip_error;
1011
1012   gst_buffer_resize (outbuf, offset, res - offset);
1013
1014   /* use buffer metadata so receivers can also track the address */
1015   if (saddr) {
1016     gst_buffer_add_net_address_meta (outbuf, saddr);
1017     g_object_unref (saddr);
1018     saddr = NULL;
1019   }
1020
1021   GST_LOG_OBJECT (udpsrc, "read packet of %d bytes", (int) res);
1022
1023   *buf = GST_BUFFER_CAST (outbuf);
1024
1025   return GST_FLOW_OK;
1026
1027   /* ERRORS */
1028 memory_alloc_error:
1029   {
1030     GST_ELEMENT_ERROR (udpsrc, RESOURCE, READ, (NULL),
1031         ("Failed to allocate or map memory"));
1032     return GST_FLOW_ERROR;
1033   }
1034 select_error:
1035   {
1036     GST_ELEMENT_ERROR (udpsrc, RESOURCE, READ, (NULL),
1037         ("select error: %s", err->message));
1038     g_clear_error (&err);
1039     return GST_FLOW_ERROR;
1040   }
1041 stopped:
1042   {
1043     GST_DEBUG ("stop called");
1044     g_clear_error (&err);
1045     return GST_FLOW_FLUSHING;
1046   }
1047 receive_error:
1048   {
1049     if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY) ||
1050         g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
1051       g_clear_error (&err);
1052       return GST_FLOW_FLUSHING;
1053     } else {
1054       GST_ELEMENT_ERROR (udpsrc, RESOURCE, READ, (NULL),
1055           ("receive error %" G_GSSIZE_FORMAT ": %s", res, err->message));
1056       g_clear_error (&err);
1057       return GST_FLOW_ERROR;
1058     }
1059   }
1060 skip_error:
1061   {
1062     gst_buffer_unref (outbuf);
1063
1064     GST_ELEMENT_ERROR (udpsrc, STREAM, DECODE, (NULL),
1065         ("UDP buffer to small to skip header"));
1066     return GST_FLOW_ERROR;
1067   }
1068 }
1069
1070 static gboolean
1071 gst_udpsrc_set_uri (GstUDPSrc * src, const gchar * uri, GError ** error)
1072 {
1073   gchar *address;
1074   guint16 port;
1075
1076   if (!gst_udp_parse_uri (uri, &address, &port))
1077     goto wrong_uri;
1078
1079   if (port == (guint16) - 1)
1080     port = UDP_DEFAULT_PORT;
1081
1082   g_free (src->address);
1083   src->address = address;
1084   src->port = port;
1085
1086   g_free (src->uri);
1087   src->uri = g_strdup (uri);
1088
1089   return TRUE;
1090
1091   /* ERRORS */
1092 wrong_uri:
1093   {
1094     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
1095         ("error parsing uri %s", uri));
1096     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
1097         "Could not parse UDP URI");
1098     return FALSE;
1099   }
1100 }
1101
1102 static void
1103 gst_udpsrc_set_property (GObject * object, guint prop_id, const GValue * value,
1104     GParamSpec * pspec)
1105 {
1106   GstUDPSrc *udpsrc = GST_UDPSRC (object);
1107
1108   switch (prop_id) {
1109     case PROP_BUFFER_SIZE:
1110       udpsrc->buffer_size = g_value_get_int (value);
1111       break;
1112     case PROP_PORT:
1113       udpsrc->port = g_value_get_int (value);
1114       g_free (udpsrc->uri);
1115       udpsrc->uri =
1116           g_strdup_printf ("udp://%s:%u", udpsrc->address, udpsrc->port);
1117       break;
1118     case PROP_MULTICAST_GROUP:
1119     case PROP_ADDRESS:
1120     {
1121       const gchar *group;
1122
1123       g_free (udpsrc->address);
1124       if ((group = g_value_get_string (value)))
1125         udpsrc->address = g_strdup (group);
1126       else
1127         udpsrc->address = g_strdup (UDP_DEFAULT_MULTICAST_GROUP);
1128
1129       g_free (udpsrc->uri);
1130       udpsrc->uri =
1131           g_strdup_printf ("udp://%s:%u", udpsrc->address, udpsrc->port);
1132       break;
1133     }
1134     case PROP_MULTICAST_IFACE:
1135       g_free (udpsrc->multi_iface);
1136
1137       if (g_value_get_string (value) == NULL)
1138         udpsrc->multi_iface = g_strdup (UDP_DEFAULT_MULTICAST_IFACE);
1139       else
1140         udpsrc->multi_iface = g_value_dup_string (value);
1141       break;
1142     case PROP_URI:
1143       gst_udpsrc_set_uri (udpsrc, g_value_get_string (value), NULL);
1144       break;
1145     case PROP_CAPS:
1146     {
1147       const GstCaps *new_caps_val = gst_value_get_caps (value);
1148       GstCaps *new_caps;
1149       GstCaps *old_caps;
1150
1151       if (new_caps_val == NULL) {
1152         new_caps = gst_caps_new_any ();
1153       } else {
1154         new_caps = gst_caps_copy (new_caps_val);
1155       }
1156
1157       GST_OBJECT_LOCK (udpsrc);
1158       old_caps = udpsrc->caps;
1159       udpsrc->caps = new_caps;
1160       GST_OBJECT_UNLOCK (udpsrc);
1161       if (old_caps)
1162         gst_caps_unref (old_caps);
1163
1164       gst_pad_mark_reconfigure (GST_BASE_SRC_PAD (udpsrc));
1165       break;
1166     }
1167     case PROP_SOCKET:
1168       if (udpsrc->socket != NULL && udpsrc->socket != udpsrc->used_socket &&
1169           udpsrc->close_socket) {
1170         GError *err = NULL;
1171
1172         if (!g_socket_close (udpsrc->socket, &err)) {
1173           GST_ERROR ("failed to close socket %p: %s", udpsrc->socket,
1174               err->message);
1175           g_clear_error (&err);
1176         }
1177       }
1178       if (udpsrc->socket)
1179         g_object_unref (udpsrc->socket);
1180       udpsrc->socket = g_value_dup_object (value);
1181       GST_DEBUG ("setting socket to %p", udpsrc->socket);
1182       break;
1183     case PROP_TIMEOUT:
1184       udpsrc->timeout = g_value_get_uint64 (value);
1185       break;
1186     case PROP_SKIP_FIRST_BYTES:
1187       udpsrc->skip_first_bytes = g_value_get_int (value);
1188       break;
1189     case PROP_CLOSE_SOCKET:
1190       udpsrc->close_socket = g_value_get_boolean (value);
1191       break;
1192     case PROP_AUTO_MULTICAST:
1193       udpsrc->auto_multicast = g_value_get_boolean (value);
1194       break;
1195     case PROP_REUSE:
1196       udpsrc->reuse = g_value_get_boolean (value);
1197       break;
1198     case PROP_LOOP:
1199       udpsrc->loop = g_value_get_boolean (value);
1200       break;
1201     case PROP_RETRIEVE_SENDER_ADDRESS:
1202       udpsrc->retrieve_sender_address = g_value_get_boolean (value);
1203       break;
1204     default:
1205       break;
1206   }
1207 }
1208
1209 static void
1210 gst_udpsrc_get_property (GObject * object, guint prop_id, GValue * value,
1211     GParamSpec * pspec)
1212 {
1213   GstUDPSrc *udpsrc = GST_UDPSRC (object);
1214
1215   switch (prop_id) {
1216     case PROP_BUFFER_SIZE:
1217       g_value_set_int (value, udpsrc->buffer_size);
1218       break;
1219     case PROP_PORT:
1220       g_value_set_int (value, udpsrc->port);
1221       break;
1222     case PROP_MULTICAST_GROUP:
1223     case PROP_ADDRESS:
1224       g_value_set_string (value, udpsrc->address);
1225       break;
1226     case PROP_MULTICAST_IFACE:
1227       g_value_set_string (value, udpsrc->multi_iface);
1228       break;
1229     case PROP_URI:
1230       g_value_set_string (value, udpsrc->uri);
1231       break;
1232     case PROP_CAPS:
1233       GST_OBJECT_LOCK (udpsrc);
1234       gst_value_set_caps (value, udpsrc->caps);
1235       GST_OBJECT_UNLOCK (udpsrc);
1236       break;
1237     case PROP_SOCKET:
1238       g_value_set_object (value, udpsrc->socket);
1239       break;
1240     case PROP_TIMEOUT:
1241       g_value_set_uint64 (value, udpsrc->timeout);
1242       break;
1243     case PROP_SKIP_FIRST_BYTES:
1244       g_value_set_int (value, udpsrc->skip_first_bytes);
1245       break;
1246     case PROP_CLOSE_SOCKET:
1247       g_value_set_boolean (value, udpsrc->close_socket);
1248       break;
1249     case PROP_USED_SOCKET:
1250       g_value_set_object (value, udpsrc->used_socket);
1251       break;
1252     case PROP_AUTO_MULTICAST:
1253       g_value_set_boolean (value, udpsrc->auto_multicast);
1254       break;
1255     case PROP_REUSE:
1256       g_value_set_boolean (value, udpsrc->reuse);
1257       break;
1258     case PROP_LOOP:
1259       g_value_set_boolean (value, udpsrc->loop);
1260       break;
1261     case PROP_RETRIEVE_SENDER_ADDRESS:
1262       g_value_set_boolean (value, udpsrc->retrieve_sender_address);
1263       break;
1264     default:
1265       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1266       break;
1267   }
1268 }
1269
1270 static GInetAddress *
1271 gst_udpsrc_resolve (GstUDPSrc * src, const gchar * address)
1272 {
1273   GInetAddress *addr;
1274   GError *err = NULL;
1275   GResolver *resolver;
1276
1277   addr = g_inet_address_new_from_string (address);
1278   if (!addr) {
1279     GList *results;
1280
1281     GST_DEBUG_OBJECT (src, "resolving IP address for host %s", address);
1282     resolver = g_resolver_get_default ();
1283     results =
1284         g_resolver_lookup_by_name (resolver, address, src->cancellable, &err);
1285     if (!results)
1286       goto name_resolve;
1287     addr = G_INET_ADDRESS (g_object_ref (results->data));
1288
1289     g_resolver_free_addresses (results);
1290     g_object_unref (resolver);
1291   }
1292 #ifndef GST_DISABLE_GST_DEBUG
1293   {
1294     gchar *ip = g_inet_address_to_string (addr);
1295
1296     GST_DEBUG_OBJECT (src, "IP address for host %s is %s", address, ip);
1297     g_free (ip);
1298   }
1299 #endif
1300
1301   return addr;
1302
1303 name_resolve:
1304   {
1305     GST_WARNING_OBJECT (src, "Failed to resolve %s: %s", address, err->message);
1306     g_clear_error (&err);
1307     g_object_unref (resolver);
1308     return NULL;
1309   }
1310 }
1311
1312 /* create a socket for sending to remote machine */
1313 static gboolean
1314 gst_udpsrc_open (GstUDPSrc * src)
1315 {
1316   GInetAddress *addr, *bind_addr;
1317   GSocketAddress *bind_saddr;
1318   GError *err = NULL;
1319
1320   gst_udpsrc_create_cancellable (src);
1321
1322   if (src->socket == NULL) {
1323     /* need to allocate a socket */
1324     GST_DEBUG_OBJECT (src, "allocating socket for %s:%d", src->address,
1325         src->port);
1326
1327     addr = gst_udpsrc_resolve (src, src->address);
1328     if (!addr)
1329       goto name_resolve;
1330
1331     if ((src->used_socket =
1332             g_socket_new (g_inet_address_get_family (addr),
1333                 G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &err)) == NULL)
1334       goto no_socket;
1335
1336     src->external_socket = FALSE;
1337
1338     GST_DEBUG_OBJECT (src, "got socket %p", src->used_socket);
1339
1340     if (src->addr)
1341       g_object_unref (src->addr);
1342     src->addr =
1343         G_INET_SOCKET_ADDRESS (g_inet_socket_address_new (addr, src->port));
1344
1345     GST_DEBUG_OBJECT (src, "binding on port %d", src->port);
1346
1347     /* For multicast, bind to ANY and join the multicast group later */
1348     if (g_inet_address_get_is_multicast (addr))
1349       bind_addr = g_inet_address_new_any (g_inet_address_get_family (addr));
1350     else
1351       bind_addr = G_INET_ADDRESS (g_object_ref (addr));
1352
1353     g_object_unref (addr);
1354
1355     bind_saddr = g_inet_socket_address_new (bind_addr, src->port);
1356     g_object_unref (bind_addr);
1357     if (!g_socket_bind (src->used_socket, bind_saddr, src->reuse, &err))
1358       goto bind_error;
1359
1360     g_object_unref (bind_saddr);
1361     g_socket_set_multicast_loopback (src->used_socket, src->loop);
1362   } else {
1363     GInetSocketAddress *local_addr;
1364
1365     GST_DEBUG_OBJECT (src, "using provided socket %p", src->socket);
1366     /* we use the configured socket, try to get some info about it */
1367     src->used_socket = G_SOCKET (g_object_ref (src->socket));
1368     src->external_socket = TRUE;
1369
1370     local_addr =
1371         G_INET_SOCKET_ADDRESS (g_socket_get_local_address (src->used_socket,
1372             &err));
1373     if (!local_addr)
1374       goto getsockname_error;
1375
1376     addr = gst_udpsrc_resolve (src, src->address);
1377     if (!addr)
1378       goto name_resolve;
1379
1380     /* If bound to ANY and address points to a multicast address, make
1381      * sure that address is not overridden with ANY but we have the
1382      * opportunity later to join the multicast address. This ensures that we
1383      * have the same behaviour as for sockets created by udpsrc */
1384     if (!src->auto_multicast ||
1385         !g_inet_address_get_is_any (g_inet_socket_address_get_address
1386             (local_addr))
1387         || !g_inet_address_get_is_multicast (addr)) {
1388       g_object_unref (addr);
1389       if (src->addr)
1390         g_object_unref (src->addr);
1391       src->addr = local_addr;
1392     } else {
1393       g_object_unref (local_addr);
1394       if (src->addr)
1395         g_object_unref (src->addr);
1396       src->addr =
1397           G_INET_SOCKET_ADDRESS (g_inet_socket_address_new (addr, src->port));
1398       g_object_unref (addr);
1399     }
1400   }
1401
1402   {
1403     gint val = 0;
1404
1405     if (src->buffer_size != 0) {
1406       GError *opt_err = NULL;
1407
1408       GST_INFO_OBJECT (src, "setting udp buffer of %d bytes", src->buffer_size);
1409       /* set buffer size, Note that on Linux this is typically limited to a
1410        * maximum of around 100K. Also a minimum of 128 bytes is required on
1411        * Linux. */
1412       if (!g_socket_set_option (src->used_socket, SOL_SOCKET, SO_RCVBUF,
1413               src->buffer_size, &opt_err)) {
1414         GST_ELEMENT_WARNING (src, RESOURCE, SETTINGS, (NULL),
1415             ("Could not create a buffer of requested %d bytes: %s",
1416                 src->buffer_size, opt_err->message));
1417         g_error_free (opt_err);
1418         opt_err = NULL;
1419       }
1420     }
1421
1422     /* read the value of the receive buffer. Note that on linux this returns
1423      * 2x the value we set because the kernel allocates extra memory for
1424      * metadata. The default on Linux is about 100K (which is about 50K
1425      * without metadata) */
1426     if (g_socket_get_option (src->used_socket, SOL_SOCKET, SO_RCVBUF, &val,
1427             NULL)) {
1428       GST_INFO_OBJECT (src, "have udp buffer of %d bytes", val);
1429     } else {
1430       GST_DEBUG_OBJECT (src, "could not get udp buffer size");
1431     }
1432   }
1433
1434   g_socket_set_broadcast (src->used_socket, TRUE);
1435
1436   if (src->auto_multicast
1437       &&
1438       g_inet_address_get_is_multicast (g_inet_socket_address_get_address
1439           (src->addr))) {
1440
1441     if (src->multi_iface) {
1442       GStrv multi_ifaces = g_strsplit (src->multi_iface, ",", -1);
1443       gchar **ifaces = multi_ifaces;
1444       while (*ifaces) {
1445         g_strstrip (*ifaces);
1446         GST_DEBUG_OBJECT (src, "joining multicast group %s interface %s",
1447             src->address, *ifaces);
1448         if (!g_socket_join_multicast_group (src->used_socket,
1449                 g_inet_socket_address_get_address (src->addr),
1450                 FALSE, *ifaces, &err)) {
1451           g_strfreev (multi_ifaces);
1452           goto membership;
1453         }
1454
1455         ifaces++;
1456       }
1457       g_strfreev (multi_ifaces);
1458     } else {
1459       GST_DEBUG_OBJECT (src, "joining multicast group %s", src->address);
1460       if (!g_socket_join_multicast_group (src->used_socket,
1461               g_inet_socket_address_get_address (src->addr), FALSE, NULL, &err))
1462         goto membership;
1463     }
1464
1465     if (g_inet_address_get_family (g_inet_socket_address_get_address
1466             (src->addr)) == G_SOCKET_FAMILY_IPV4) {
1467 #if defined(IP_MULTICAST_ALL)
1468       if (!g_socket_set_option (src->used_socket, IPPROTO_IP, IP_MULTICAST_ALL,
1469               0, &err)) {
1470         GST_WARNING_OBJECT (src, "Failed to disable IP_MULTICAST_ALL: %s",
1471             err->message);
1472         g_clear_error (&err);
1473       }
1474 #elif defined(IP_PKTINFO)
1475       if (!g_socket_set_option (src->used_socket, IPPROTO_IP, IP_PKTINFO, TRUE,
1476               &err)) {
1477         GST_WARNING_OBJECT (src, "Failed to enable IP_PKTINFO: %s",
1478             err->message);
1479         g_clear_error (&err);
1480       }
1481 #elif defined(IP_RECVDSTADDR)
1482       if (!g_socket_set_option (src->used_socket, IPPROTO_IP, IP_RECVDSTADDR,
1483               TRUE, &err)) {
1484         GST_WARNING_OBJECT (src, "Failed to enable IP_RECVDSTADDR: %s",
1485             err->message);
1486         g_clear_error (&err);
1487       }
1488 #else
1489 #pragma message("No API available for getting IPv4 destination address")
1490       GST_WARNING_OBJECT (src, "No API available for getting IPv4 destination "
1491           "address, will receive packets for every destination to our port");
1492 #endif
1493     } else
1494         if (g_inet_address_get_family (g_inet_socket_address_get_address
1495             (src->addr)) == G_SOCKET_FAMILY_IPV6) {
1496 #ifdef IPV6_PKTINFO
1497 #ifdef IPV6_RECVPKTINFO
1498       if (!g_socket_set_option (src->used_socket, IPPROTO_IPV6,
1499               IPV6_RECVPKTINFO, TRUE, &err)) {
1500 #else
1501       if (!g_socket_set_option (src->used_socket, IPPROTO_IPV6, IPV6_PKTINFO,
1502               TRUE, &err)) {
1503 #endif
1504         GST_WARNING_OBJECT (src, "Failed to enable IPV6_PKTINFO: %s",
1505             err->message);
1506         g_clear_error (&err);
1507       }
1508 #else
1509 #pragma message("No API available for getting IPv6 destination address")
1510       GST_WARNING_OBJECT (src, "No API available for getting IPv6 destination "
1511           "address, will receive packets for every destination to our port");
1512 #endif
1513     }
1514   }
1515
1516   /* NOTE: sockaddr_in.sin_port works for ipv4 and ipv6 because sin_port
1517    * follows ss_family on both */
1518   {
1519     GInetSocketAddress *addr;
1520     guint16 port;
1521
1522     addr =
1523         G_INET_SOCKET_ADDRESS (g_socket_get_local_address (src->used_socket,
1524             &err));
1525     if (!addr)
1526       goto getsockname_error;
1527
1528     port = g_inet_socket_address_get_port (addr);
1529     GST_DEBUG_OBJECT (src, "bound, on port %d", port);
1530     if (port != src->port) {
1531       src->port = port;
1532       GST_DEBUG_OBJECT (src, "notifying port %d", port);
1533       g_object_notify (G_OBJECT (src), "port");
1534     }
1535     g_object_unref (addr);
1536   }
1537
1538   src->allocator = NULL;
1539   gst_allocation_params_init (&src->params);
1540
1541   src->max_size = 0;
1542
1543   return TRUE;
1544
1545   /* ERRORS */
1546 name_resolve:
1547   {
1548     return FALSE;
1549   }
1550 no_socket:
1551   {
1552     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
1553         ("no socket error: %s", err->message));
1554     g_clear_error (&err);
1555     g_object_unref (addr);
1556     return FALSE;
1557   }
1558 bind_error:
1559   {
1560     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
1561         ("bind failed: %s", err->message));
1562     g_clear_error (&err);
1563     g_object_unref (bind_saddr);
1564     gst_udpsrc_close (src);
1565     return FALSE;
1566   }
1567 membership:
1568   {
1569     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
1570         ("could not add membership: %s", err->message));
1571     g_clear_error (&err);
1572     gst_udpsrc_close (src);
1573     return FALSE;
1574   }
1575 getsockname_error:
1576   {
1577     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
1578         ("getsockname failed: %s", err->message));
1579     g_clear_error (&err);
1580     gst_udpsrc_close (src);
1581     return FALSE;
1582   }
1583 }
1584
1585 static gboolean
1586 gst_udpsrc_unlock (GstBaseSrc * bsrc)
1587 {
1588   GstUDPSrc *src;
1589
1590   src = GST_UDPSRC (bsrc);
1591
1592   GST_LOG_OBJECT (src, "Flushing");
1593   g_cancellable_cancel (src->cancellable);
1594
1595   return TRUE;
1596 }
1597
1598 static gboolean
1599 gst_udpsrc_unlock_stop (GstBaseSrc * bsrc)
1600 {
1601   GstUDPSrc *src;
1602
1603   src = GST_UDPSRC (bsrc);
1604
1605   GST_LOG_OBJECT (src, "No longer flushing");
1606
1607   gst_udpsrc_free_cancellable (src);
1608   gst_udpsrc_create_cancellable (src);
1609
1610   return TRUE;
1611 }
1612
1613 static gboolean
1614 gst_udpsrc_close (GstUDPSrc * src)
1615 {
1616   GST_DEBUG ("closing sockets");
1617
1618   if (src->used_socket) {
1619     if (src->auto_multicast
1620         &&
1621         g_inet_address_get_is_multicast (g_inet_socket_address_get_address
1622             (src->addr))) {
1623       GError *err = NULL;
1624
1625       if (src->multi_iface) {
1626         GStrv multi_ifaces = g_strsplit (src->multi_iface, ",", -1);
1627         gchar **ifaces = multi_ifaces;
1628         while (*ifaces) {
1629           g_strstrip (*ifaces);
1630           GST_DEBUG_OBJECT (src, "leaving multicast group %s interface %s",
1631               src->address, *ifaces);
1632           if (!g_socket_leave_multicast_group (src->used_socket,
1633                   g_inet_socket_address_get_address (src->addr),
1634                   FALSE, *ifaces, &err)) {
1635             GST_ERROR_OBJECT (src, "Failed to leave multicast group: %s",
1636                 err->message);
1637             g_clear_error (&err);
1638           }
1639           ifaces++;
1640         }
1641         g_strfreev (multi_ifaces);
1642
1643       } else {
1644         GST_DEBUG_OBJECT (src, "leaving multicast group %s", src->address);
1645         if (!g_socket_leave_multicast_group (src->used_socket,
1646                 g_inet_socket_address_get_address (src->addr), FALSE,
1647                 NULL, &err)) {
1648           GST_ERROR_OBJECT (src, "Failed to leave multicast group: %s",
1649               err->message);
1650           g_clear_error (&err);
1651         }
1652       }
1653     }
1654
1655     if (src->close_socket || !src->external_socket) {
1656       GError *err = NULL;
1657       if (!g_socket_close (src->used_socket, &err)) {
1658         GST_ERROR_OBJECT (src, "Failed to close socket: %s", err->message);
1659         g_clear_error (&err);
1660       }
1661     }
1662
1663     g_object_unref (src->used_socket);
1664     src->used_socket = NULL;
1665     g_object_unref (src->addr);
1666     src->addr = NULL;
1667   }
1668
1669   gst_udpsrc_reset_memory_allocator (src);
1670
1671   gst_udpsrc_free_cancellable (src);
1672
1673   return TRUE;
1674 }
1675
1676
1677 static GstStateChangeReturn
1678 gst_udpsrc_change_state (GstElement * element, GstStateChange transition)
1679 {
1680   GstUDPSrc *src;
1681   GstStateChangeReturn result;
1682
1683   src = GST_UDPSRC (element);
1684
1685   switch (transition) {
1686     case GST_STATE_CHANGE_NULL_TO_READY:
1687       if (!gst_udpsrc_open (src))
1688         goto open_failed;
1689       break;
1690     default:
1691       break;
1692   }
1693   if ((result =
1694           GST_ELEMENT_CLASS (parent_class)->change_state (element,
1695               transition)) == GST_STATE_CHANGE_FAILURE)
1696     goto failure;
1697
1698   switch (transition) {
1699     case GST_STATE_CHANGE_READY_TO_NULL:
1700       gst_udpsrc_close (src);
1701       break;
1702     default:
1703       break;
1704   }
1705   return result;
1706   /* ERRORS */
1707 open_failed:
1708   {
1709     GST_DEBUG_OBJECT (src, "failed to open socket");
1710     return GST_STATE_CHANGE_FAILURE;
1711   }
1712 failure:
1713   {
1714     GST_DEBUG_OBJECT (src, "parent failed state change");
1715     return result;
1716   }
1717 }
1718
1719
1720
1721
1722 /*** GSTURIHANDLER INTERFACE *************************************************/
1723
1724 static GstURIType
1725 gst_udpsrc_uri_get_type (GType type)
1726 {
1727   return GST_URI_SRC;
1728 }
1729
1730 static const gchar *const *
1731 gst_udpsrc_uri_get_protocols (GType type)
1732 {
1733   static const gchar *protocols[] = { "udp", NULL };
1734
1735   return protocols;
1736 }
1737
1738 static gchar *
1739 gst_udpsrc_uri_get_uri (GstURIHandler * handler)
1740 {
1741   GstUDPSrc *src = GST_UDPSRC (handler);
1742
1743   return g_strdup (src->uri);
1744 }
1745
1746 static gboolean
1747 gst_udpsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1748     GError ** error)
1749 {
1750   return gst_udpsrc_set_uri (GST_UDPSRC (handler), uri, error);
1751 }
1752
1753 static void
1754 gst_udpsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
1755 {
1756   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1757
1758   iface->get_type = gst_udpsrc_uri_get_type;
1759   iface->get_protocols = gst_udpsrc_uri_get_protocols;
1760   iface->get_uri = gst_udpsrc_uri_get_uri;
1761   iface->set_uri = gst_udpsrc_uri_set_uri;
1762 }