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