dynudpsink: return FLUSHING when sendto got canceled, not an error
[platform/upstream/gst-plugins-good.git] / gst / udp / gstmultiudpsink.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  * Copyright (C) <2009> Jarkko Palviainen <jarkko.palviainen@sesca.com>
4  * Copyright (C) <2012> Collabora Ltd.
5  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:element-multiudpsink
25  * @see_also: udpsink, multifdsink
26  *
27  * multiudpsink is a network sink that sends UDP packets to multiple
28  * clients.
29  * It can be combined with rtp payload encoders to implement RTP streaming.
30  */
31
32 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
33  * with newer GLib versions (>= 2.31.0) */
34 #define GLIB_DISABLE_DEPRECATION_WARNINGS
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39 #include "gstmultiudpsink.h"
40
41 #include <string.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45
46 #ifndef G_OS_WIN32
47 #include <netinet/in.h>
48 #endif
49
50 #include "gst/glib-compat-private.h"
51
52 GST_DEBUG_CATEGORY_STATIC (multiudpsink_debug);
53 #define GST_CAT_DEFAULT (multiudpsink_debug)
54
55 #define UDP_MAX_SIZE 65507
56
57 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
58     GST_PAD_SINK,
59     GST_PAD_ALWAYS,
60     GST_STATIC_CAPS_ANY);
61
62 /* MultiUDPSink signals and args */
63 enum
64 {
65   /* methods */
66   SIGNAL_ADD,
67   SIGNAL_REMOVE,
68   SIGNAL_CLEAR,
69   SIGNAL_GET_STATS,
70
71   /* signals */
72   SIGNAL_CLIENT_ADDED,
73   SIGNAL_CLIENT_REMOVED,
74
75   /* FILL ME */
76   LAST_SIGNAL
77 };
78
79 #define DEFAULT_SOCKET             NULL
80 #define DEFAULT_CLOSE_SOCKET       TRUE
81 #define DEFAULT_USED_SOCKET        NULL
82 #define DEFAULT_CLIENTS            NULL
83 /* FIXME, this should be disabled by default, we don't need to join a multicast
84  * group for sending, if this socket is also used for receiving, it should
85  * be configured in the element that does the receive. */
86 #define DEFAULT_AUTO_MULTICAST     TRUE
87 #define DEFAULT_MULTICAST_IFACE    NULL
88 #define DEFAULT_TTL                64
89 #define DEFAULT_TTL_MC             1
90 #define DEFAULT_LOOP               TRUE
91 #define DEFAULT_FORCE_IPV4         FALSE
92 #define DEFAULT_QOS_DSCP           -1
93 #define DEFAULT_SEND_DUPLICATES    TRUE
94 #define DEFAULT_BUFFER_SIZE        0
95 #define DEFAULT_BIND_ADDRESS       NULL
96 #define DEFAULT_BIND_PORT          0
97
98 enum
99 {
100   PROP_0,
101   PROP_BYTES_TO_SERVE,
102   PROP_BYTES_SERVED,
103   PROP_SOCKET,
104   PROP_SOCKET_V6,
105   PROP_CLOSE_SOCKET,
106   PROP_USED_SOCKET,
107   PROP_USED_SOCKET_V6,
108   PROP_CLIENTS,
109   PROP_AUTO_MULTICAST,
110   PROP_MULTICAST_IFACE,
111   PROP_TTL,
112   PROP_TTL_MC,
113   PROP_LOOP,
114   PROP_FORCE_IPV4,
115   PROP_QOS_DSCP,
116   PROP_SEND_DUPLICATES,
117   PROP_BUFFER_SIZE,
118   PROP_BIND_ADDRESS,
119   PROP_BIND_PORT,
120   PROP_LAST
121 };
122
123 static void gst_multiudpsink_finalize (GObject * object);
124
125 static GstFlowReturn gst_multiudpsink_render (GstBaseSink * sink,
126     GstBuffer * buffer);
127
128 static gboolean gst_multiudpsink_start (GstBaseSink * bsink);
129 static gboolean gst_multiudpsink_stop (GstBaseSink * bsink);
130 static gboolean gst_multiudpsink_unlock (GstBaseSink * bsink);
131 static gboolean gst_multiudpsink_unlock_stop (GstBaseSink * bsink);
132
133 static void gst_multiudpsink_set_property (GObject * object, guint prop_id,
134     const GValue * value, GParamSpec * pspec);
135 static void gst_multiudpsink_get_property (GObject * object, guint prop_id,
136     GValue * value, GParamSpec * pspec);
137
138 static void gst_multiudpsink_add_internal (GstMultiUDPSink * sink,
139     const gchar * host, gint port, gboolean lock);
140 static void gst_multiudpsink_clear_internal (GstMultiUDPSink * sink,
141     gboolean lock);
142
143 static guint gst_multiudpsink_signals[LAST_SIGNAL] = { 0 };
144
145 #define gst_multiudpsink_parent_class parent_class
146 G_DEFINE_TYPE (GstMultiUDPSink, gst_multiudpsink, GST_TYPE_BASE_SINK);
147
148 static void
149 gst_multiudpsink_class_init (GstMultiUDPSinkClass * klass)
150 {
151   GObjectClass *gobject_class;
152   GstElementClass *gstelement_class;
153   GstBaseSinkClass *gstbasesink_class;
154
155   gobject_class = (GObjectClass *) klass;
156   gstelement_class = (GstElementClass *) klass;
157   gstbasesink_class = (GstBaseSinkClass *) klass;
158
159   gobject_class->set_property = gst_multiudpsink_set_property;
160   gobject_class->get_property = gst_multiudpsink_get_property;
161   gobject_class->finalize = gst_multiudpsink_finalize;
162
163   /**
164    * GstMultiUDPSink::add:
165    * @gstmultiudpsink: the sink on which the signal is emitted
166    * @host: the hostname/IP address of the client to add
167    * @port: the port of the client to add
168    *
169    * Add a client with destination @host and @port to the list of
170    * clients. When the same host/port pair is added multiple times, the
171    * send-duplicates property defines if the packets are sent multiple times to
172    * the same host/port pair or not.
173    *
174    * When a host/port pair is added multiple times, an equal amount of remove
175    * calls must be performed to actually remove the host/port pair from the list
176    * of destinations.
177    */
178   gst_multiudpsink_signals[SIGNAL_ADD] =
179       g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
180       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
181       G_STRUCT_OFFSET (GstMultiUDPSinkClass, add),
182       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
183       G_TYPE_STRING, G_TYPE_INT);
184   /**
185    * GstMultiUDPSink::remove:
186    * @gstmultiudpsink: the sink on which the signal is emitted
187    * @host: the hostname/IP address of the client to remove
188    * @port: the port of the client to remove
189    *
190    * Remove the client with destination @host and @port from the list of
191    * clients.
192    */
193   gst_multiudpsink_signals[SIGNAL_REMOVE] =
194       g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
195       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
196       G_STRUCT_OFFSET (GstMultiUDPSinkClass, remove),
197       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
198       G_TYPE_STRING, G_TYPE_INT);
199   /**
200    * GstMultiUDPSink::clear:
201    * @gstmultiudpsink: the sink on which the signal is emitted
202    *
203    * Clear the list of clients.
204    */
205   gst_multiudpsink_signals[SIGNAL_CLEAR] =
206       g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
207       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
208       G_STRUCT_OFFSET (GstMultiUDPSinkClass, clear),
209       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 0);
210   /**
211    * GstMultiUDPSink::get-stats:
212    * @gstmultiudpsink: the sink on which the signal is emitted
213    * @host: the hostname/IP address of the client to get stats on
214    * @port: the port of the client to get stats on
215    *
216    * Get the statistics of the client with destination @host and @port.
217    *
218    * Returns: a GstStructure: bytes_sent, packets_sent,
219    *           connect_time (in epoch seconds), disconnect_time (in epoch seconds)
220    */
221   gst_multiudpsink_signals[SIGNAL_GET_STATS] =
222       g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
223       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
224       G_STRUCT_OFFSET (GstMultiUDPSinkClass, get_stats),
225       NULL, NULL, g_cclosure_marshal_generic, GST_TYPE_STRUCTURE, 2,
226       G_TYPE_STRING, G_TYPE_INT);
227   /**
228    * GstMultiUDPSink::client-added:
229    * @gstmultiudpsink: the sink emitting the signal
230    * @host: the hostname/IP address of the added client
231    * @port: the port of the added client
232    *
233    * Signal emited when a new client is added to the list of
234    * clients.
235    */
236   gst_multiudpsink_signals[SIGNAL_CLIENT_ADDED] =
237       g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
238       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiUDPSinkClass, client_added),
239       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
240       G_TYPE_STRING, G_TYPE_INT);
241   /**
242    * GstMultiUDPSink::client-removed:
243    * @gstmultiudpsink: the sink emitting the signal
244    * @host: the hostname/IP address of the removed client
245    * @port: the port of the removed client
246    *
247    * Signal emited when a client is removed from the list of
248    * clients.
249    */
250   gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED] =
251       g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
252       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiUDPSinkClass,
253           client_removed), NULL, NULL, g_cclosure_marshal_generic,
254       G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT);
255
256   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTES_TO_SERVE,
257       g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
258           "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
259           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
260   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTES_SERVED,
261       g_param_spec_uint64 ("bytes-served", "Bytes served",
262           "Total number of bytes sent to all clients", 0, G_MAXUINT64, 0,
263           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
264   g_object_class_install_property (gobject_class, PROP_SOCKET,
265       g_param_spec_object ("socket", "Socket Handle",
266           "Socket to use for UDP sending. (NULL == allocate)",
267           G_TYPE_SOCKET, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
268   g_object_class_install_property (gobject_class, PROP_SOCKET_V6,
269       g_param_spec_object ("socket-v6", "Socket Handle IPv6",
270           "Socket to use for UDPv6 sending. (NULL == allocate)",
271           G_TYPE_SOCKET, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
272   g_object_class_install_property (gobject_class, PROP_CLOSE_SOCKET,
273       g_param_spec_boolean ("close-socket", "Close socket",
274           "Close socket if passed as property on state change",
275           DEFAULT_CLOSE_SOCKET, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
276   g_object_class_install_property (gobject_class, PROP_USED_SOCKET,
277       g_param_spec_object ("used-socket", "Used Socket Handle",
278           "Socket currently in use for UDP sending. (NULL == no socket)",
279           G_TYPE_SOCKET, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
280   g_object_class_install_property (gobject_class, PROP_USED_SOCKET_V6,
281       g_param_spec_object ("used-socket-v6", "Used Socket Handle IPv6",
282           "Socket currently in use for UDPv6 sending. (NULL == no socket)",
283           G_TYPE_SOCKET, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
284   g_object_class_install_property (gobject_class, PROP_CLIENTS,
285       g_param_spec_string ("clients", "Clients",
286           "A comma separated list of host:port pairs with destinations",
287           DEFAULT_CLIENTS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
288   g_object_class_install_property (gobject_class, PROP_AUTO_MULTICAST,
289       g_param_spec_boolean ("auto-multicast",
290           "Automatically join/leave multicast groups",
291           "Automatically join/leave the multicast groups, FALSE means user"
292           " has to do it himself", DEFAULT_AUTO_MULTICAST,
293           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
294   g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
295       g_param_spec_string ("multicast-iface", "Multicast Interface",
296           "The network interface on which to join the multicast group",
297           DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
298   g_object_class_install_property (gobject_class, PROP_TTL,
299       g_param_spec_int ("ttl", "Unicast TTL",
300           "Used for setting the unicast TTL parameter",
301           0, 255, DEFAULT_TTL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
302   g_object_class_install_property (gobject_class, PROP_TTL_MC,
303       g_param_spec_int ("ttl-mc", "Multicast TTL",
304           "Used for setting the multicast TTL parameter",
305           0, 255, DEFAULT_TTL_MC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306   g_object_class_install_property (gobject_class, PROP_LOOP,
307       g_param_spec_boolean ("loop", "Multicast Loopback",
308           "Used for setting the multicast loop parameter. TRUE = enable,"
309           " FALSE = disable", DEFAULT_LOOP,
310           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
311   /**
312    * GstMultiUDPSink::force-ipv4:
313    *
314    * Force the use of an IPv4 socket.
315    *
316    * Since: 1.0.2
317    */
318   g_object_class_install_property (gobject_class, PROP_FORCE_IPV4,
319       g_param_spec_boolean ("force-ipv4", "Force IPv4",
320           "Forcing the use of an IPv4 socket (DEPRECATED, has no effect anymore)",
321           DEFAULT_FORCE_IPV4, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
322
323   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_QOS_DSCP,
324       g_param_spec_int ("qos-dscp", "QoS diff srv code point",
325           "Quality of Service, differentiated services code point (-1 default)",
326           -1, 63, DEFAULT_QOS_DSCP,
327           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
328   /**
329    * GstMultiUDPSink::send-duplicates:
330    *
331    * When a host/port pair is added mutliple times, send the packet to the host
332    * multiple times as well.
333    */
334   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SEND_DUPLICATES,
335       g_param_spec_boolean ("send-duplicates", "Send Duplicates",
336           "When a distination/port pair is added multiple times, send packets "
337           "multiple times as well", DEFAULT_SEND_DUPLICATES,
338           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
339
340   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BUFFER_SIZE,
341       g_param_spec_int ("buffer-size", "Buffer Size",
342           "Size of the kernel send buffer in bytes, 0=default", 0, G_MAXINT,
343           DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344
345   g_object_class_install_property (gobject_class, PROP_BIND_ADDRESS,
346       g_param_spec_string ("bind-address", "Bind Address",
347           "Address to bind the socket to", DEFAULT_BIND_ADDRESS,
348           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
349   g_object_class_install_property (gobject_class, PROP_BIND_PORT,
350       g_param_spec_int ("bind-port", "Bind Port",
351           "Port to bind the socket to", 0, G_MAXUINT16,
352           DEFAULT_BIND_PORT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
353
354   gst_element_class_add_pad_template (gstelement_class,
355       gst_static_pad_template_get (&sink_template));
356
357   gst_element_class_set_static_metadata (gstelement_class, "UDP packet sender",
358       "Sink/Network",
359       "Send data over the network via UDP",
360       "Wim Taymans <wim.taymans@gmail.com>");
361
362   gstbasesink_class->render = gst_multiudpsink_render;
363   gstbasesink_class->start = gst_multiudpsink_start;
364   gstbasesink_class->stop = gst_multiudpsink_stop;
365   gstbasesink_class->unlock = gst_multiudpsink_unlock;
366   gstbasesink_class->unlock_stop = gst_multiudpsink_unlock_stop;
367   klass->add = gst_multiudpsink_add;
368   klass->remove = gst_multiudpsink_remove;
369   klass->clear = gst_multiudpsink_clear;
370   klass->get_stats = gst_multiudpsink_get_stats;
371
372   GST_DEBUG_CATEGORY_INIT (multiudpsink_debug, "multiudpsink", 0, "UDP sink");
373 }
374
375
376 static void
377 gst_multiudpsink_init (GstMultiUDPSink * sink)
378 {
379   guint max_mem;
380
381   g_mutex_init (&sink->client_lock);
382   sink->socket = DEFAULT_SOCKET;
383   sink->socket_v6 = DEFAULT_SOCKET;
384   sink->used_socket = DEFAULT_USED_SOCKET;
385   sink->used_socket_v6 = DEFAULT_USED_SOCKET;
386   sink->close_socket = DEFAULT_CLOSE_SOCKET;
387   sink->external_socket = (sink->socket != NULL);
388   sink->auto_multicast = DEFAULT_AUTO_MULTICAST;
389   sink->ttl = DEFAULT_TTL;
390   sink->ttl_mc = DEFAULT_TTL_MC;
391   sink->loop = DEFAULT_LOOP;
392   sink->force_ipv4 = DEFAULT_FORCE_IPV4;
393   sink->qos_dscp = DEFAULT_QOS_DSCP;
394   sink->send_duplicates = DEFAULT_SEND_DUPLICATES;
395   sink->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
396
397   sink->cancellable = g_cancellable_new ();
398
399   /* allocate OutputVector and MapInfo for use in the render function, buffers can
400    * hold up to a maximum amount of memory so we can create a maximally sized
401    * array for them.  */
402   max_mem = gst_buffer_get_max_memory ();
403
404   sink->vec = g_new (GOutputVector, max_mem);
405   sink->map = g_new (GstMapInfo, max_mem);
406 }
407
408 static GstUDPClient *
409 create_client (GstMultiUDPSink * sink, const gchar * host, gint port)
410 {
411   GstUDPClient *client;
412   GInetAddress *addr;
413   GResolver *resolver;
414   GError *err = NULL;
415
416   addr = g_inet_address_new_from_string (host);
417   if (!addr) {
418     GList *results;
419
420     resolver = g_resolver_get_default ();
421     results =
422         g_resolver_lookup_by_name (resolver, host, sink->cancellable, &err);
423     if (!results)
424       goto name_resolve;
425     addr = G_INET_ADDRESS (g_object_ref (results->data));
426
427     g_resolver_free_addresses (results);
428     g_object_unref (resolver);
429   }
430 #ifndef GST_DISABLE_GST_DEBUG
431   {
432     gchar *ip = g_inet_address_to_string (addr);
433
434     GST_DEBUG_OBJECT (sink, "IP address for host %s is %s", host, ip);
435     g_free (ip);
436   }
437 #endif
438
439   client = g_slice_new0 (GstUDPClient);
440   client->refcount = 1;
441   client->host = g_strdup (host);
442   client->port = port;
443   client->addr = g_inet_socket_address_new (addr, port);
444   g_object_unref (addr);
445
446   return client;
447
448 name_resolve:
449   {
450     g_object_unref (resolver);
451
452     return NULL;
453   }
454 }
455
456 static void
457 free_client (GstUDPClient * client)
458 {
459   g_object_unref (client->addr);
460   g_free (client->host);
461   g_slice_free (GstUDPClient, client);
462 }
463
464 static gint
465 client_compare (GstUDPClient * a, GstUDPClient * b)
466 {
467   if ((a->port == b->port) && (strcmp (a->host, b->host) == 0))
468     return 0;
469
470   return 1;
471 }
472
473 static void
474 gst_multiudpsink_finalize (GObject * object)
475 {
476   GstMultiUDPSink *sink;
477
478   sink = GST_MULTIUDPSINK (object);
479
480   g_list_foreach (sink->clients, (GFunc) free_client, NULL);
481   g_list_free (sink->clients);
482
483   if (sink->socket)
484     g_object_unref (sink->socket);
485   sink->socket = NULL;
486
487   if (sink->socket_v6)
488     g_object_unref (sink->socket_v6);
489   sink->socket_v6 = NULL;
490
491   if (sink->used_socket)
492     g_object_unref (sink->used_socket);
493   sink->used_socket = NULL;
494
495   if (sink->used_socket_v6)
496     g_object_unref (sink->used_socket_v6);
497   sink->used_socket_v6 = NULL;
498
499   if (sink->cancellable)
500     g_object_unref (sink->cancellable);
501   sink->cancellable = NULL;
502
503   g_free (sink->multi_iface);
504   sink->multi_iface = NULL;
505
506   g_free (sink->vec);
507   sink->vec = NULL;
508   g_free (sink->map);
509   sink->map = NULL;
510
511   g_free (sink->bind_address);
512   sink->bind_address = NULL;
513
514   g_mutex_clear (&sink->client_lock);
515
516   G_OBJECT_CLASS (parent_class)->finalize (object);
517 }
518
519 static GstFlowReturn
520 gst_multiudpsink_render (GstBaseSink * bsink, GstBuffer * buffer)
521 {
522   GstMultiUDPSink *sink;
523   GList *clients;
524   GOutputVector *vec;
525   GstMapInfo *map;
526   guint n_mem, i;
527   gsize size;
528   GstMemory *mem;
529   gint num, no_clients;
530   GError *err = NULL;
531
532   sink = GST_MULTIUDPSINK (bsink);
533
534   n_mem = gst_buffer_n_memory (buffer);
535   if (n_mem == 0)
536     goto no_data;
537
538   /* pre-allocated, the max number of memory blocks is limited so this
539    * should not cause overflows */
540   vec = sink->vec;
541   map = sink->map;
542
543   size = 0;
544   for (i = 0; i < n_mem; i++) {
545     mem = gst_buffer_get_memory (buffer, i);
546     gst_memory_map (mem, &map[i], GST_MAP_READ);
547
548     vec[i].buffer = map[i].data;
549     vec[i].size = map[i].size;
550
551     size += map[i].size;
552   }
553
554   sink->bytes_to_serve += size;
555
556   /* grab lock while iterating and sending to clients, this should be
557    * fast as UDP never blocks */
558   g_mutex_lock (&sink->client_lock);
559   GST_LOG_OBJECT (bsink, "about to send %" G_GSIZE_FORMAT " bytes in %u blocks",
560       size, n_mem);
561
562   no_clients = 0;
563   num = 0;
564   for (clients = sink->clients; clients; clients = g_list_next (clients)) {
565     GstUDPClient *client;
566     GSocket *socket;
567     GSocketFamily family;
568     gint count;
569
570     client = (GstUDPClient *) clients->data;
571     no_clients++;
572     GST_LOG_OBJECT (sink, "sending %" G_GSIZE_FORMAT " bytes to client %p",
573         size, client);
574
575     family = g_socket_address_get_family (G_SOCKET_ADDRESS (client->addr));
576     /* Select socket to send from for this address */
577     if (family == G_SOCKET_FAMILY_IPV6 || !sink->used_socket)
578       socket = sink->used_socket_v6;
579     else
580       socket = sink->used_socket;
581
582     count = sink->send_duplicates ? client->refcount : 1;
583
584     while (count--) {
585       gssize ret;
586
587       ret =
588           g_socket_send_message (socket, client->addr, vec, n_mem,
589           NULL, 0, 0, sink->cancellable, &err);
590
591       if (G_UNLIKELY (ret < 0)) {
592         if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED))
593           goto flushing;
594
595         /* we continue after posting a warning, next packets might be ok
596          * again */
597         if (size > UDP_MAX_SIZE) {
598           GST_ELEMENT_WARNING (sink, RESOURCE, WRITE,
599               ("Attempting to send a UDP packet larger than maximum size "
600                   "(%" G_GSIZE_FORMAT " > %d)", size, UDP_MAX_SIZE),
601               ("Reason: %s", err ? err->message : "unknown reason"));
602         } else {
603           GST_ELEMENT_WARNING (sink, RESOURCE, WRITE,
604               ("Error sending UDP packet"), ("Reason: %s",
605                   err ? err->message : "unknown reason"));
606         }
607         g_clear_error (&err);
608       } else {
609         num++;
610         client->bytes_sent += ret;
611         client->packets_sent++;
612         sink->bytes_served += ret;
613       }
614     }
615   }
616   g_mutex_unlock (&sink->client_lock);
617
618   /* unmap all memory again */
619   for (i = 0; i < n_mem; i++) {
620     gst_memory_unmap (map[i].memory, &map[i]);
621     gst_memory_unref (map[i].memory);
622   }
623
624   GST_LOG_OBJECT (sink, "sent %" G_GSIZE_FORMAT " bytes to %d (of %d) clients",
625       size, num, no_clients);
626
627   return GST_FLOW_OK;
628
629 no_data:
630   {
631     return GST_FLOW_OK;
632   }
633 flushing:
634   {
635     GST_DEBUG ("we are flushing");
636     g_mutex_unlock (&sink->client_lock);
637     g_clear_error (&err);
638
639     /* unmap all memory */
640     for (i = 0; i < n_mem; i++) {
641       gst_memory_unmap (map[i].memory, &map[i]);
642       gst_memory_unref (map[i].memory);
643     }
644
645     return GST_FLOW_FLUSHING;
646   }
647 }
648
649 static void
650 gst_multiudpsink_set_clients_string (GstMultiUDPSink * sink,
651     const gchar * string)
652 {
653   gchar **clients;
654   gint i;
655
656   clients = g_strsplit (string, ",", 0);
657
658   g_mutex_lock (&sink->client_lock);
659   /* clear all existing clients */
660   gst_multiudpsink_clear_internal (sink, FALSE);
661   for (i = 0; clients[i]; i++) {
662     gchar *host, *p;
663     gint64 port = 0;
664
665     host = clients[i];
666     p = strstr (clients[i], ":");
667     if (p != NULL) {
668       *p = '\0';
669       port = g_ascii_strtoll (p + 1, NULL, 10);
670     }
671     if (port != 0)
672       gst_multiudpsink_add_internal (sink, host, port, FALSE);
673   }
674   g_mutex_unlock (&sink->client_lock);
675
676   g_strfreev (clients);
677 }
678
679 static gchar *
680 gst_multiudpsink_get_clients_string (GstMultiUDPSink * sink)
681 {
682   GString *str;
683   GList *clients;
684
685   str = g_string_new ("");
686
687   g_mutex_lock (&sink->client_lock);
688   clients = sink->clients;
689   while (clients) {
690     GstUDPClient *client;
691     gint count;
692
693     client = (GstUDPClient *) clients->data;
694
695     clients = g_list_next (clients);
696
697     count = client->refcount;
698     while (count--) {
699       g_string_append_printf (str, "%s:%d%s", client->host, client->port,
700           (clients || count > 1 ? "," : ""));
701     }
702   }
703   g_mutex_unlock (&sink->client_lock);
704
705   return g_string_free (str, FALSE);
706 }
707
708 static void
709 gst_multiudpsink_setup_qos_dscp (GstMultiUDPSink * sink, GSocket * socket)
710 {
711   /* don't touch on -1 */
712   if (sink->qos_dscp < 0)
713     return;
714
715   if (socket == NULL)
716     return;
717
718 #ifdef IP_TOS
719   {
720     gint tos;
721     gint fd;
722
723     fd = g_socket_get_fd (socket);
724
725     GST_DEBUG_OBJECT (sink, "setting TOS to %d", sink->qos_dscp);
726
727     /* Extract and shift 6 bits of DSFIELD */
728     tos = (sink->qos_dscp & 0x3f) << 2;
729
730     if (setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0) {
731       GST_ERROR_OBJECT (sink, "could not set TOS: %s", g_strerror (errno));
732     }
733 #ifdef IPV6_TCLASS
734     if (setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0) {
735       GST_ERROR_OBJECT (sink, "could not set TCLASS: %s", g_strerror (errno));
736     }
737 #endif
738   }
739 #endif
740 }
741
742 static void
743 gst_multiudpsink_set_property (GObject * object, guint prop_id,
744     const GValue * value, GParamSpec * pspec)
745 {
746   GstMultiUDPSink *udpsink;
747
748   udpsink = GST_MULTIUDPSINK (object);
749
750   switch (prop_id) {
751     case PROP_SOCKET:
752       if (udpsink->socket != NULL && udpsink->socket != udpsink->used_socket &&
753           udpsink->close_socket) {
754         GError *err = NULL;
755
756         if (!g_socket_close (udpsink->socket, &err)) {
757           GST_ERROR ("failed to close socket %p: %s", udpsink->socket,
758               err->message);
759           g_clear_error (&err);
760         }
761       }
762       if (udpsink->socket)
763         g_object_unref (udpsink->socket);
764       udpsink->socket = g_value_dup_object (value);
765       GST_DEBUG_OBJECT (udpsink, "setting socket to %p", udpsink->socket);
766       break;
767     case PROP_SOCKET_V6:
768       if (udpsink->socket_v6 != NULL
769           && udpsink->socket_v6 != udpsink->used_socket_v6
770           && udpsink->close_socket) {
771         GError *err = NULL;
772
773         if (!g_socket_close (udpsink->socket_v6, &err)) {
774           GST_ERROR ("failed to close socket %p: %s", udpsink->socket_v6,
775               err->message);
776           g_clear_error (&err);
777         }
778       }
779       if (udpsink->socket_v6)
780         g_object_unref (udpsink->socket_v6);
781       udpsink->socket_v6 = g_value_dup_object (value);
782       GST_DEBUG_OBJECT (udpsink, "setting socket to %p", udpsink->socket_v6);
783       break;
784     case PROP_CLOSE_SOCKET:
785       udpsink->close_socket = g_value_get_boolean (value);
786       break;
787     case PROP_CLIENTS:
788       gst_multiudpsink_set_clients_string (udpsink, g_value_get_string (value));
789       break;
790     case PROP_AUTO_MULTICAST:
791       udpsink->auto_multicast = g_value_get_boolean (value);
792       break;
793     case PROP_MULTICAST_IFACE:
794       g_free (udpsink->multi_iface);
795
796       if (g_value_get_string (value) == NULL)
797         udpsink->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
798       else
799         udpsink->multi_iface = g_value_dup_string (value);
800       break;
801     case PROP_TTL:
802       udpsink->ttl = g_value_get_int (value);
803       break;
804     case PROP_TTL_MC:
805       udpsink->ttl_mc = g_value_get_int (value);
806       break;
807     case PROP_LOOP:
808       udpsink->loop = g_value_get_boolean (value);
809       break;
810     case PROP_FORCE_IPV4:
811       udpsink->force_ipv4 = g_value_get_boolean (value);
812       break;
813     case PROP_QOS_DSCP:
814       udpsink->qos_dscp = g_value_get_int (value);
815       gst_multiudpsink_setup_qos_dscp (udpsink, udpsink->used_socket);
816       gst_multiudpsink_setup_qos_dscp (udpsink, udpsink->used_socket_v6);
817       break;
818     case PROP_SEND_DUPLICATES:
819       udpsink->send_duplicates = g_value_get_boolean (value);
820       break;
821     case PROP_BUFFER_SIZE:
822       udpsink->buffer_size = g_value_get_int (value);
823       break;
824     case PROP_BIND_ADDRESS:
825       g_free (udpsink->bind_address);
826       udpsink->bind_address = g_value_dup_string (value);
827       break;
828     case PROP_BIND_PORT:
829       udpsink->bind_port = g_value_get_int (value);
830       break;
831     default:
832       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
833       break;
834   }
835 }
836
837 static void
838 gst_multiudpsink_get_property (GObject * object, guint prop_id, GValue * value,
839     GParamSpec * pspec)
840 {
841   GstMultiUDPSink *udpsink;
842
843   udpsink = GST_MULTIUDPSINK (object);
844
845   switch (prop_id) {
846     case PROP_BYTES_TO_SERVE:
847       g_value_set_uint64 (value, udpsink->bytes_to_serve);
848       break;
849     case PROP_BYTES_SERVED:
850       g_value_set_uint64 (value, udpsink->bytes_served);
851       break;
852     case PROP_SOCKET:
853       g_value_set_object (value, udpsink->socket);
854       break;
855     case PROP_SOCKET_V6:
856       g_value_set_object (value, udpsink->socket_v6);
857       break;
858     case PROP_CLOSE_SOCKET:
859       g_value_set_boolean (value, udpsink->close_socket);
860       break;
861     case PROP_USED_SOCKET:
862       g_value_set_object (value, udpsink->used_socket);
863       break;
864     case PROP_USED_SOCKET_V6:
865       g_value_set_object (value, udpsink->used_socket_v6);
866       break;
867     case PROP_CLIENTS:
868       g_value_take_string (value,
869           gst_multiudpsink_get_clients_string (udpsink));
870       break;
871     case PROP_AUTO_MULTICAST:
872       g_value_set_boolean (value, udpsink->auto_multicast);
873       break;
874     case PROP_MULTICAST_IFACE:
875       g_value_set_string (value, udpsink->multi_iface);
876       break;
877     case PROP_TTL:
878       g_value_set_int (value, udpsink->ttl);
879       break;
880     case PROP_TTL_MC:
881       g_value_set_int (value, udpsink->ttl_mc);
882       break;
883     case PROP_LOOP:
884       g_value_set_boolean (value, udpsink->loop);
885       break;
886     case PROP_FORCE_IPV4:
887       g_value_set_boolean (value, udpsink->force_ipv4);
888       break;
889     case PROP_QOS_DSCP:
890       g_value_set_int (value, udpsink->qos_dscp);
891       break;
892     case PROP_SEND_DUPLICATES:
893       g_value_set_boolean (value, udpsink->send_duplicates);
894       break;
895     case PROP_BUFFER_SIZE:
896       g_value_set_int (value, udpsink->buffer_size);
897       break;
898     case PROP_BIND_ADDRESS:
899       g_value_set_string (value, udpsink->bind_address);
900       break;
901     case PROP_BIND_PORT:
902       g_value_set_int (value, udpsink->bind_port);
903       break;
904     default:
905       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
906       break;
907   }
908 }
909
910 static gboolean
911 gst_multiudpsink_configure_client (GstMultiUDPSink * sink,
912     GstUDPClient * client)
913 {
914   GInetSocketAddress *saddr = G_INET_SOCKET_ADDRESS (client->addr);
915   GInetAddress *addr = g_inet_socket_address_get_address (saddr);
916   GSocketFamily family = g_socket_address_get_family (G_SOCKET_ADDRESS (saddr));
917   GSocket *socket;
918   GError *err = NULL;
919
920   GST_DEBUG_OBJECT (sink, "configuring client %p", client);
921
922   if (family == G_SOCKET_FAMILY_IPV6 && !sink->used_socket_v6)
923     goto invalid_family;
924
925   /* Select socket to send from for this address */
926   if (family == G_SOCKET_FAMILY_IPV6 || !sink->used_socket)
927     socket = sink->used_socket_v6;
928   else
929     socket = sink->used_socket;
930
931   if (g_inet_address_get_is_multicast (addr)) {
932     GST_DEBUG_OBJECT (sink, "we have a multicast client %p", client);
933     if (sink->auto_multicast) {
934       GST_DEBUG_OBJECT (sink, "autojoining group");
935       if (!g_socket_join_multicast_group (socket, addr, FALSE,
936               sink->multi_iface, &err))
937         goto join_group_failed;
938     }
939     GST_DEBUG_OBJECT (sink, "setting loop to %d", sink->loop);
940     g_socket_set_multicast_loopback (socket, sink->loop);
941     GST_DEBUG_OBJECT (sink, "setting ttl to %d", sink->ttl_mc);
942     g_socket_set_multicast_ttl (socket, sink->ttl_mc);
943   } else {
944     GST_DEBUG_OBJECT (sink, "setting unicast ttl to %d", sink->ttl);
945     g_socket_set_ttl (socket, sink->ttl);
946   }
947   return TRUE;
948
949   /* ERRORS */
950 join_group_failed:
951   {
952     gst_multiudpsink_stop (GST_BASE_SINK (sink));
953     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
954         ("Could not join multicast group: %s",
955             err ? err->message : "unknown reason"));
956     g_clear_error (&err);
957     return FALSE;
958   }
959 invalid_family:
960   {
961     gst_multiudpsink_stop (GST_BASE_SINK (sink));
962     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
963         ("Invalid address family (got %d)", family));
964     return FALSE;
965   }
966 }
967
968 /* create a socket for sending to remote machine */
969 static gboolean
970 gst_multiudpsink_start (GstBaseSink * bsink)
971 {
972   GstMultiUDPSink *sink;
973   GList *clients;
974   GstUDPClient *client;
975   GError *err = NULL;
976
977   sink = GST_MULTIUDPSINK (bsink);
978
979   sink->external_socket = FALSE;
980
981   if (sink->socket) {
982     GST_DEBUG_OBJECT (sink, "using configured socket");
983     if (g_socket_get_family (sink->socket) == G_SOCKET_FAMILY_IPV6) {
984       sink->used_socket_v6 = G_SOCKET (g_object_ref (sink->socket));
985       sink->external_socket = TRUE;
986     } else {
987       sink->used_socket = G_SOCKET (g_object_ref (sink->socket));
988       sink->external_socket = TRUE;
989     }
990   }
991
992   if (sink->socket_v6) {
993     GST_DEBUG_OBJECT (sink, "using configured IPv6 socket");
994     g_return_val_if_fail (g_socket_get_family (sink->socket) !=
995         G_SOCKET_FAMILY_IPV6, FALSE);
996
997     if (sink->used_socket_v6 && sink->used_socket_v6 != sink->socket_v6) {
998       GST_ERROR_OBJECT (sink,
999           "Provided different IPv6 sockets in socket and socket-v6 properties");
1000       return FALSE;
1001     }
1002
1003     sink->used_socket_v6 = G_SOCKET (g_object_ref (sink->socket_v6));
1004     sink->external_socket = TRUE;
1005   }
1006
1007   if (!sink->used_socket && !sink->used_socket_v6) {
1008     GSocketAddress *bind_addr;
1009     GInetAddress *bind_iaddr;
1010
1011     if (sink->bind_address) {
1012       GSocketFamily family;
1013
1014       bind_iaddr = g_inet_address_new_from_string (sink->bind_address);
1015       if (!bind_iaddr) {
1016         GList *results;
1017         GResolver *resolver;
1018
1019         resolver = g_resolver_get_default ();
1020         results =
1021             g_resolver_lookup_by_name (resolver, sink->bind_address,
1022             sink->cancellable, &err);
1023         if (!results) {
1024           g_object_unref (resolver);
1025           goto name_resolve;
1026         }
1027         bind_iaddr = G_INET_ADDRESS (g_object_ref (results->data));
1028         g_resolver_free_addresses (results);
1029         g_object_unref (resolver);
1030       }
1031
1032       bind_addr = g_inet_socket_address_new (bind_iaddr, sink->bind_port);
1033       g_object_unref (bind_iaddr);
1034       family = g_socket_address_get_family (G_SOCKET_ADDRESS (bind_addr));
1035
1036       if ((sink->used_socket =
1037               g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
1038                   G_SOCKET_PROTOCOL_UDP, &err)) == NULL) {
1039         g_object_unref (bind_addr);
1040         goto no_socket;
1041       }
1042
1043       g_socket_bind (sink->used_socket, bind_addr, TRUE, &err);
1044       if (err != NULL)
1045         goto bind_error;
1046     } else {
1047       /* create sender sockets if none available */
1048       if ((sink->used_socket = g_socket_new (G_SOCKET_FAMILY_IPV4,
1049                   G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &err)) == NULL)
1050         goto no_socket;
1051
1052       bind_iaddr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1053       bind_addr = g_inet_socket_address_new (bind_iaddr, sink->bind_port);
1054       g_socket_bind (sink->used_socket, bind_addr, TRUE, &err);
1055       g_object_unref (bind_addr);
1056       g_object_unref (bind_iaddr);
1057       if (err != NULL)
1058         goto bind_error;
1059
1060       if ((sink->used_socket_v6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
1061                   G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP,
1062                   &err)) == NULL) {
1063         GST_INFO_OBJECT (sink, "Failed to create IPv6 socket: %s",
1064             err->message);
1065         g_clear_error (&err);
1066       } else {
1067         bind_iaddr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
1068         bind_addr = g_inet_socket_address_new (bind_iaddr, sink->bind_port);
1069         g_socket_bind (sink->used_socket_v6, bind_addr, TRUE, &err);
1070         g_object_unref (bind_addr);
1071         g_object_unref (bind_iaddr);
1072         if (err != NULL)
1073           goto bind_error;
1074       }
1075     }
1076   }
1077 #ifdef SO_SNDBUF
1078   {
1079     socklen_t len;
1080     gint sndsize, ret;
1081
1082     len = sizeof (sndsize);
1083     if (sink->buffer_size != 0) {
1084       sndsize = sink->buffer_size;
1085
1086       GST_DEBUG_OBJECT (sink, "setting udp buffer of %d bytes", sndsize);
1087       /* set buffer size, Note that on Linux this is typically limited to a
1088        * maximum of around 100K. Also a minimum of 128 bytes is required on
1089        * Linux. */
1090
1091       if (sink->used_socket) {
1092         ret =
1093             setsockopt (g_socket_get_fd (sink->used_socket), SOL_SOCKET,
1094             SO_SNDBUF, (void *) &sndsize, len);
1095         if (ret != 0) {
1096           GST_ELEMENT_WARNING (sink, RESOURCE, SETTINGS, (NULL),
1097               ("Could not create a buffer of requested %d bytes, %d: %s",
1098                   sndsize, ret, g_strerror (errno)));
1099         }
1100       }
1101
1102       if (sink->used_socket_v6) {
1103         ret =
1104             setsockopt (g_socket_get_fd (sink->used_socket_v6), SOL_SOCKET,
1105             SO_SNDBUF, (void *) &sndsize, len);
1106         if (ret != 0) {
1107           GST_ELEMENT_WARNING (sink, RESOURCE, SETTINGS, (NULL),
1108               ("Could not create a buffer of requested %d bytes, %d: %s",
1109                   sndsize, ret, g_strerror (errno)));
1110         }
1111       }
1112     }
1113
1114     /* read the value of the receive buffer. Note that on linux this returns 2x the
1115      * value we set because the kernel allocates extra memory for metadata.
1116      * The default on Linux is about 100K (which is about 50K without metadata) */
1117     if (sink->used_socket) {
1118       ret =
1119           getsockopt (g_socket_get_fd (sink->used_socket), SOL_SOCKET,
1120           SO_SNDBUF, (void *) &sndsize, &len);
1121       if (ret == 0)
1122         GST_DEBUG_OBJECT (sink, "have UDP buffer of %d bytes", sndsize);
1123       else
1124         GST_DEBUG_OBJECT (sink, "could not get UDP buffer size");
1125     }
1126
1127     if (sink->used_socket_v6) {
1128       ret =
1129           getsockopt (g_socket_get_fd (sink->used_socket_v6), SOL_SOCKET,
1130           SO_SNDBUF, (void *) &sndsize, &len);
1131       if (ret == 0)
1132         GST_DEBUG_OBJECT (sink, "have UDPv6 buffer of %d bytes", sndsize);
1133       else
1134         GST_DEBUG_OBJECT (sink, "could not get UDPv6 buffer size");
1135     }
1136   }
1137 #endif
1138
1139 #ifdef SO_BINDTODEVICE
1140   if (sink->multi_iface) {
1141     if (sink->used_socket) {
1142       if (setsockopt (g_socket_get_fd (sink->used_socket), SOL_SOCKET,
1143               SO_BINDTODEVICE, sink->multi_iface,
1144               strlen (sink->multi_iface)) < 0)
1145         GST_WARNING_OBJECT (sink, "setsockopt SO_BINDTODEVICE failed: %s",
1146             strerror (errno));
1147     }
1148     if (sink->used_socket_v6) {
1149       if (setsockopt (g_socket_get_fd (sink->used_socket_v6), SOL_SOCKET,
1150               SO_BINDTODEVICE, sink->multi_iface,
1151               strlen (sink->multi_iface)) < 0)
1152         GST_WARNING_OBJECT (sink, "setsockopt SO_BINDTODEVICE failed (v6): %s",
1153             strerror (errno));
1154     }
1155   }
1156 #endif
1157
1158   if (sink->used_socket)
1159     g_socket_set_broadcast (sink->used_socket, TRUE);
1160   if (sink->used_socket_v6)
1161     g_socket_set_broadcast (sink->used_socket_v6, TRUE);
1162
1163   sink->bytes_to_serve = 0;
1164   sink->bytes_served = 0;
1165
1166   gst_multiudpsink_setup_qos_dscp (sink, sink->used_socket);
1167   gst_multiudpsink_setup_qos_dscp (sink, sink->used_socket_v6);
1168
1169   /* look for multicast clients and join multicast groups appropriately
1170      set also ttl and multicast loopback delivery appropriately  */
1171   for (clients = sink->clients; clients; clients = g_list_next (clients)) {
1172     client = (GstUDPClient *) clients->data;
1173
1174     if (!gst_multiudpsink_configure_client (sink, client))
1175       return FALSE;
1176   }
1177   return TRUE;
1178
1179   /* ERRORS */
1180 no_socket:
1181   {
1182     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1183         ("Could not create socket: %s", err->message));
1184     g_clear_error (&err);
1185     return FALSE;
1186   }
1187 bind_error:
1188   {
1189     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1190         ("Failed to bind socket: %s", err->message));
1191     g_clear_error (&err);
1192     return FALSE;
1193   }
1194 name_resolve:
1195   {
1196     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1197         ("Failed to resolve bind address %s: %s", sink->bind_address,
1198             err->message));
1199     g_clear_error (&err);
1200     return FALSE;
1201   }
1202 }
1203
1204 static gboolean
1205 gst_multiudpsink_stop (GstBaseSink * bsink)
1206 {
1207   GstMultiUDPSink *udpsink;
1208
1209   udpsink = GST_MULTIUDPSINK (bsink);
1210
1211   if (udpsink->used_socket) {
1212     if (udpsink->close_socket || !udpsink->external_socket) {
1213       GError *err = NULL;
1214
1215       if (!g_socket_close (udpsink->used_socket, &err)) {
1216         GST_ERROR_OBJECT (udpsink, "Failed to close socket: %s", err->message);
1217         g_clear_error (&err);
1218       }
1219     }
1220
1221     g_object_unref (udpsink->used_socket);
1222     udpsink->used_socket = NULL;
1223   }
1224
1225   if (udpsink->used_socket_v6) {
1226     if (udpsink->close_socket || !udpsink->external_socket) {
1227       GError *err = NULL;
1228
1229       if (!g_socket_close (udpsink->used_socket_v6, &err)) {
1230         GST_ERROR_OBJECT (udpsink, "Failed to close socket: %s", err->message);
1231         g_clear_error (&err);
1232       }
1233     }
1234
1235     g_object_unref (udpsink->used_socket_v6);
1236     udpsink->used_socket_v6 = NULL;
1237   }
1238
1239   return TRUE;
1240 }
1241
1242 static void
1243 gst_multiudpsink_add_internal (GstMultiUDPSink * sink, const gchar * host,
1244     gint port, gboolean lock)
1245 {
1246   GstUDPClient *client;
1247   GstUDPClient udpclient;
1248   GTimeVal now;
1249   GList *find;
1250
1251   udpclient.host = (gchar *) host;
1252   udpclient.port = port;
1253
1254   GST_DEBUG_OBJECT (sink, "adding client on host %s, port %d", host, port);
1255
1256   if (lock)
1257     g_mutex_lock (&sink->client_lock);
1258
1259   find = g_list_find_custom (sink->clients, &udpclient,
1260       (GCompareFunc) client_compare);
1261   if (find) {
1262     client = (GstUDPClient *) find->data;
1263
1264     GST_DEBUG_OBJECT (sink, "found %d existing clients with host %s, port %d",
1265         client->refcount, host, port);
1266     client->refcount++;
1267   } else {
1268     client = create_client (sink, host, port);
1269     if (!client)
1270       goto error;
1271
1272     g_get_current_time (&now);
1273     client->connect_time = GST_TIMEVAL_TO_TIME (now);
1274
1275     if (sink->used_socket)
1276       gst_multiudpsink_configure_client (sink, client);
1277
1278     GST_DEBUG_OBJECT (sink, "add client with host %s, port %d", host, port);
1279     sink->clients = g_list_prepend (sink->clients, client);
1280   }
1281
1282   if (lock)
1283     g_mutex_unlock (&sink->client_lock);
1284
1285   g_signal_emit (G_OBJECT (sink),
1286       gst_multiudpsink_signals[SIGNAL_CLIENT_ADDED], 0, host, port);
1287
1288   GST_DEBUG_OBJECT (sink, "added client on host %s, port %d", host, port);
1289   return;
1290
1291   /* ERRORS */
1292 error:
1293   {
1294     GST_DEBUG_OBJECT (sink, "did not add client on host %s, port %d", host,
1295         port);
1296     if (lock)
1297       g_mutex_unlock (&sink->client_lock);
1298     return;
1299   }
1300 }
1301
1302 void
1303 gst_multiudpsink_add (GstMultiUDPSink * sink, const gchar * host, gint port)
1304 {
1305   gst_multiudpsink_add_internal (sink, host, port, TRUE);
1306 }
1307
1308 void
1309 gst_multiudpsink_remove (GstMultiUDPSink * sink, const gchar * host, gint port)
1310 {
1311   GList *find;
1312   GstUDPClient udpclient;
1313   GstUDPClient *client;
1314   GTimeVal now;
1315
1316   udpclient.host = (gchar *) host;
1317   udpclient.port = port;
1318
1319   g_mutex_lock (&sink->client_lock);
1320   find = g_list_find_custom (sink->clients, &udpclient,
1321       (GCompareFunc) client_compare);
1322   if (!find)
1323     goto not_found;
1324
1325   client = (GstUDPClient *) find->data;
1326
1327   GST_DEBUG_OBJECT (sink, "found %d clients with host %s, port %d",
1328       client->refcount, host, port);
1329
1330   client->refcount--;
1331   if (client->refcount == 0) {
1332     GInetSocketAddress *saddr = G_INET_SOCKET_ADDRESS (client->addr);
1333     GInetAddress *addr = g_inet_socket_address_get_address (saddr);
1334     GSocketFamily family =
1335         g_socket_address_get_family (G_SOCKET_ADDRESS (saddr));
1336     GSocket *socket;
1337
1338     /* Select socket to send from for this address */
1339     if (family == G_SOCKET_FAMILY_IPV6 || !sink->used_socket)
1340       socket = sink->used_socket_v6;
1341     else
1342       socket = sink->used_socket;
1343
1344     GST_DEBUG_OBJECT (sink, "remove client with host %s, port %d", host, port);
1345
1346     g_get_current_time (&now);
1347     client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
1348
1349     if (socket && sink->auto_multicast
1350         && g_inet_address_get_is_multicast (addr)) {
1351       GError *err = NULL;
1352
1353       if (!g_socket_leave_multicast_group (socket, addr, FALSE,
1354               sink->multi_iface, &err)) {
1355         GST_DEBUG_OBJECT (sink, "Failed to leave multicast group: %s",
1356             err->message);
1357         g_clear_error (&err);
1358       }
1359     }
1360
1361     /* Unlock to emit signal before we delete the actual client */
1362     g_mutex_unlock (&sink->client_lock);
1363     g_signal_emit (G_OBJECT (sink),
1364         gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED], 0, host, port);
1365     g_mutex_lock (&sink->client_lock);
1366
1367     sink->clients = g_list_delete_link (sink->clients, find);
1368
1369     free_client (client);
1370   }
1371   g_mutex_unlock (&sink->client_lock);
1372
1373   return;
1374
1375   /* ERRORS */
1376 not_found:
1377   {
1378     g_mutex_unlock (&sink->client_lock);
1379     GST_WARNING_OBJECT (sink, "client at host %s, port %d not found",
1380         host, port);
1381     return;
1382   }
1383 }
1384
1385 static void
1386 gst_multiudpsink_clear_internal (GstMultiUDPSink * sink, gboolean lock)
1387 {
1388   GST_DEBUG_OBJECT (sink, "clearing");
1389   /* we only need to remove the client structure, there is no additional
1390    * socket or anything to free for UDP */
1391   if (lock)
1392     g_mutex_lock (&sink->client_lock);
1393   g_list_foreach (sink->clients, (GFunc) free_client, sink);
1394   g_list_free (sink->clients);
1395   sink->clients = NULL;
1396   if (lock)
1397     g_mutex_unlock (&sink->client_lock);
1398 }
1399
1400 void
1401 gst_multiudpsink_clear (GstMultiUDPSink * sink)
1402 {
1403   gst_multiudpsink_clear_internal (sink, TRUE);
1404 }
1405
1406 GstStructure *
1407 gst_multiudpsink_get_stats (GstMultiUDPSink * sink, const gchar * host,
1408     gint port)
1409 {
1410   GstUDPClient *client;
1411   GstStructure *result = NULL;
1412   GstUDPClient udpclient;
1413   GList *find;
1414
1415   udpclient.host = (gchar *) host;
1416   udpclient.port = port;
1417
1418   g_mutex_lock (&sink->client_lock);
1419
1420   find = g_list_find_custom (sink->clients, &udpclient,
1421       (GCompareFunc) client_compare);
1422   if (!find)
1423     goto not_found;
1424
1425   GST_DEBUG_OBJECT (sink, "stats for client with host %s, port %d", host, port);
1426
1427   client = (GstUDPClient *) find->data;
1428
1429   result = gst_structure_new_empty ("multiudpsink-stats");
1430
1431   gst_structure_set (result,
1432       "bytes-sent", G_TYPE_UINT64, client->bytes_sent,
1433       "packets-sent", G_TYPE_UINT64, client->packets_sent,
1434       "connect-time", G_TYPE_UINT64, client->connect_time,
1435       "disconnect-time", G_TYPE_UINT64, client->disconnect_time, NULL);
1436
1437   g_mutex_unlock (&sink->client_lock);
1438
1439   return result;
1440
1441   /* ERRORS */
1442 not_found:
1443   {
1444     g_mutex_unlock (&sink->client_lock);
1445     GST_WARNING_OBJECT (sink, "client with host %s, port %d not found",
1446         host, port);
1447     /* Apparently (see comment in gstmultifdsink.c) returning NULL from here may
1448      * confuse/break python bindings */
1449     return gst_structure_new_empty ("multiudpsink-stats");
1450   }
1451 }
1452
1453 static gboolean
1454 gst_multiudpsink_unlock (GstBaseSink * bsink)
1455 {
1456   GstMultiUDPSink *sink;
1457
1458   sink = GST_MULTIUDPSINK (bsink);
1459
1460   g_cancellable_cancel (sink->cancellable);
1461
1462   return TRUE;
1463 }
1464
1465 static gboolean
1466 gst_multiudpsink_unlock_stop (GstBaseSink * bsink)
1467 {
1468   GstMultiUDPSink *sink;
1469
1470   sink = GST_MULTIUDPSINK (bsink);
1471
1472   g_cancellable_reset (sink->cancellable);
1473
1474   return TRUE;
1475 }