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