multiudpsink: avoid some unnecessary run-time type checks
[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_get_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     gst_memory_unref (map[i].memory);
619   }
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       gst_memory_unref (map[i].memory);
640     }
641
642     return GST_FLOW_FLUSHING;
643   }
644 }
645
646 static void
647 gst_multiudpsink_set_clients_string (GstMultiUDPSink * sink,
648     const gchar * string)
649 {
650   gchar **clients;
651   gint i;
652
653   clients = g_strsplit (string, ",", 0);
654
655   g_mutex_lock (&sink->client_lock);
656   /* clear all existing clients */
657   gst_multiudpsink_clear_internal (sink, FALSE);
658   for (i = 0; clients[i]; i++) {
659     gchar *host, *p;
660     gint64 port = 0;
661
662     host = clients[i];
663     p = strstr (clients[i], ":");
664     if (p != NULL) {
665       *p = '\0';
666       port = g_ascii_strtoll (p + 1, NULL, 10);
667     }
668     if (port != 0)
669       gst_multiudpsink_add_internal (sink, host, port, FALSE);
670   }
671   g_mutex_unlock (&sink->client_lock);
672
673   g_strfreev (clients);
674 }
675
676 static gchar *
677 gst_multiudpsink_get_clients_string (GstMultiUDPSink * sink)
678 {
679   GString *str;
680   GList *clients;
681
682   str = g_string_new ("");
683
684   g_mutex_lock (&sink->client_lock);
685   clients = sink->clients;
686   while (clients) {
687     GstUDPClient *client;
688     gint count;
689
690     client = (GstUDPClient *) clients->data;
691
692     clients = g_list_next (clients);
693
694     count = client->refcount;
695     while (count--) {
696       g_string_append_printf (str, "%s:%d%s", client->host, client->port,
697           (clients || count > 1 ? "," : ""));
698     }
699   }
700   g_mutex_unlock (&sink->client_lock);
701
702   return g_string_free (str, FALSE);
703 }
704
705 static void
706 gst_multiudpsink_setup_qos_dscp (GstMultiUDPSink * sink, GSocket * socket)
707 {
708   /* don't touch on -1 */
709   if (sink->qos_dscp < 0)
710     return;
711
712   if (socket == NULL)
713     return;
714
715 #ifdef IP_TOS
716   {
717     gint tos;
718     gint fd;
719
720     fd = g_socket_get_fd (socket);
721
722     GST_DEBUG_OBJECT (sink, "setting TOS to %d", sink->qos_dscp);
723
724     /* Extract and shift 6 bits of DSFIELD */
725     tos = (sink->qos_dscp & 0x3f) << 2;
726
727     if (setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0) {
728       GST_ERROR_OBJECT (sink, "could not set TOS: %s", g_strerror (errno));
729     }
730 #ifdef IPV6_TCLASS
731     if (setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0) {
732       GST_ERROR_OBJECT (sink, "could not set TCLASS: %s", g_strerror (errno));
733     }
734 #endif
735   }
736 #endif
737 }
738
739 static void
740 gst_multiudpsink_set_property (GObject * object, guint prop_id,
741     const GValue * value, GParamSpec * pspec)
742 {
743   GstMultiUDPSink *udpsink;
744
745   udpsink = GST_MULTIUDPSINK (object);
746
747   switch (prop_id) {
748     case PROP_SOCKET:
749       if (udpsink->socket != NULL && udpsink->socket != udpsink->used_socket &&
750           udpsink->close_socket) {
751         GError *err = NULL;
752
753         if (!g_socket_close (udpsink->socket, &err)) {
754           GST_ERROR ("failed to close socket %p: %s", udpsink->socket,
755               err->message);
756           g_clear_error (&err);
757         }
758       }
759       if (udpsink->socket)
760         g_object_unref (udpsink->socket);
761       udpsink->socket = g_value_dup_object (value);
762       GST_DEBUG_OBJECT (udpsink, "setting socket to %p", udpsink->socket);
763       break;
764     case PROP_SOCKET_V6:
765       if (udpsink->socket_v6 != NULL
766           && udpsink->socket_v6 != udpsink->used_socket_v6
767           && udpsink->close_socket) {
768         GError *err = NULL;
769
770         if (!g_socket_close (udpsink->socket_v6, &err)) {
771           GST_ERROR ("failed to close socket %p: %s", udpsink->socket_v6,
772               err->message);
773           g_clear_error (&err);
774         }
775       }
776       if (udpsink->socket_v6)
777         g_object_unref (udpsink->socket_v6);
778       udpsink->socket_v6 = g_value_dup_object (value);
779       GST_DEBUG_OBJECT (udpsink, "setting socket to %p", udpsink->socket_v6);
780       break;
781     case PROP_CLOSE_SOCKET:
782       udpsink->close_socket = g_value_get_boolean (value);
783       break;
784     case PROP_CLIENTS:
785       gst_multiudpsink_set_clients_string (udpsink, g_value_get_string (value));
786       break;
787     case PROP_AUTO_MULTICAST:
788       udpsink->auto_multicast = g_value_get_boolean (value);
789       break;
790     case PROP_MULTICAST_IFACE:
791       g_free (udpsink->multi_iface);
792
793       if (g_value_get_string (value) == NULL)
794         udpsink->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
795       else
796         udpsink->multi_iface = g_value_dup_string (value);
797       break;
798     case PROP_TTL:
799       udpsink->ttl = g_value_get_int (value);
800       break;
801     case PROP_TTL_MC:
802       udpsink->ttl_mc = g_value_get_int (value);
803       break;
804     case PROP_LOOP:
805       udpsink->loop = g_value_get_boolean (value);
806       break;
807     case PROP_FORCE_IPV4:
808       udpsink->force_ipv4 = g_value_get_boolean (value);
809       break;
810     case PROP_QOS_DSCP:
811       udpsink->qos_dscp = g_value_get_int (value);
812       gst_multiudpsink_setup_qos_dscp (udpsink, udpsink->used_socket);
813       gst_multiudpsink_setup_qos_dscp (udpsink, udpsink->used_socket_v6);
814       break;
815     case PROP_SEND_DUPLICATES:
816       udpsink->send_duplicates = g_value_get_boolean (value);
817       break;
818     case PROP_BUFFER_SIZE:
819       udpsink->buffer_size = g_value_get_int (value);
820       break;
821     case PROP_BIND_ADDRESS:
822       g_free (udpsink->bind_address);
823       udpsink->bind_address = g_value_dup_string (value);
824       break;
825     case PROP_BIND_PORT:
826       udpsink->bind_port = g_value_get_int (value);
827       break;
828     default:
829       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
830       break;
831   }
832 }
833
834 static void
835 gst_multiudpsink_get_property (GObject * object, guint prop_id, GValue * value,
836     GParamSpec * pspec)
837 {
838   GstMultiUDPSink *udpsink;
839
840   udpsink = GST_MULTIUDPSINK (object);
841
842   switch (prop_id) {
843     case PROP_BYTES_TO_SERVE:
844       g_value_set_uint64 (value, udpsink->bytes_to_serve);
845       break;
846     case PROP_BYTES_SERVED:
847       g_value_set_uint64 (value, udpsink->bytes_served);
848       break;
849     case PROP_SOCKET:
850       g_value_set_object (value, udpsink->socket);
851       break;
852     case PROP_SOCKET_V6:
853       g_value_set_object (value, udpsink->socket_v6);
854       break;
855     case PROP_CLOSE_SOCKET:
856       g_value_set_boolean (value, udpsink->close_socket);
857       break;
858     case PROP_USED_SOCKET:
859       g_value_set_object (value, udpsink->used_socket);
860       break;
861     case PROP_USED_SOCKET_V6:
862       g_value_set_object (value, udpsink->used_socket_v6);
863       break;
864     case PROP_CLIENTS:
865       g_value_take_string (value,
866           gst_multiudpsink_get_clients_string (udpsink));
867       break;
868     case PROP_AUTO_MULTICAST:
869       g_value_set_boolean (value, udpsink->auto_multicast);
870       break;
871     case PROP_MULTICAST_IFACE:
872       g_value_set_string (value, udpsink->multi_iface);
873       break;
874     case PROP_TTL:
875       g_value_set_int (value, udpsink->ttl);
876       break;
877     case PROP_TTL_MC:
878       g_value_set_int (value, udpsink->ttl_mc);
879       break;
880     case PROP_LOOP:
881       g_value_set_boolean (value, udpsink->loop);
882       break;
883     case PROP_FORCE_IPV4:
884       g_value_set_boolean (value, udpsink->force_ipv4);
885       break;
886     case PROP_QOS_DSCP:
887       g_value_set_int (value, udpsink->qos_dscp);
888       break;
889     case PROP_SEND_DUPLICATES:
890       g_value_set_boolean (value, udpsink->send_duplicates);
891       break;
892     case PROP_BUFFER_SIZE:
893       g_value_set_int (value, udpsink->buffer_size);
894       break;
895     case PROP_BIND_ADDRESS:
896       g_value_set_string (value, udpsink->bind_address);
897       break;
898     case PROP_BIND_PORT:
899       g_value_set_int (value, udpsink->bind_port);
900       break;
901     default:
902       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
903       break;
904   }
905 }
906
907 static gboolean
908 gst_multiudpsink_configure_client (GstMultiUDPSink * sink,
909     GstUDPClient * client)
910 {
911   GInetSocketAddress *saddr = G_INET_SOCKET_ADDRESS (client->addr);
912   GInetAddress *addr = g_inet_socket_address_get_address (saddr);
913   GSocketFamily family = g_socket_address_get_family (G_SOCKET_ADDRESS (saddr));
914   GSocket *socket;
915   GError *err = NULL;
916
917   GST_DEBUG_OBJECT (sink, "configuring client %p", client);
918
919   if (family == G_SOCKET_FAMILY_IPV6 && !sink->used_socket_v6)
920     goto invalid_family;
921
922   /* Select socket to send from for this address */
923   if (family == G_SOCKET_FAMILY_IPV6 || !sink->used_socket)
924     socket = sink->used_socket_v6;
925   else
926     socket = sink->used_socket;
927
928   if (g_inet_address_get_is_multicast (addr)) {
929     GST_DEBUG_OBJECT (sink, "we have a multicast client %p", client);
930     if (sink->auto_multicast) {
931       GST_DEBUG_OBJECT (sink, "autojoining group");
932       if (!g_socket_join_multicast_group (socket, addr, FALSE,
933               sink->multi_iface, &err))
934         goto join_group_failed;
935     }
936     GST_DEBUG_OBJECT (sink, "setting loop to %d", sink->loop);
937     g_socket_set_multicast_loopback (socket, sink->loop);
938     GST_DEBUG_OBJECT (sink, "setting ttl to %d", sink->ttl_mc);
939     g_socket_set_multicast_ttl (socket, sink->ttl_mc);
940   } else {
941     GST_DEBUG_OBJECT (sink, "setting unicast ttl to %d", sink->ttl);
942     g_socket_set_ttl (socket, sink->ttl);
943   }
944   return TRUE;
945
946   /* ERRORS */
947 join_group_failed:
948   {
949     gst_multiudpsink_stop (GST_BASE_SINK (sink));
950     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
951         ("Could not join multicast group: %s",
952             err ? err->message : "unknown reason"));
953     g_clear_error (&err);
954     return FALSE;
955   }
956 invalid_family:
957   {
958     gst_multiudpsink_stop (GST_BASE_SINK (sink));
959     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
960         ("Invalid address family (got %d)", family));
961     return FALSE;
962   }
963 }
964
965 /* create a socket for sending to remote machine */
966 static gboolean
967 gst_multiudpsink_start (GstBaseSink * bsink)
968 {
969   GstMultiUDPSink *sink;
970   GList *clients;
971   GstUDPClient *client;
972   GError *err = NULL;
973
974   sink = GST_MULTIUDPSINK (bsink);
975
976   sink->external_socket = FALSE;
977
978   if (sink->socket) {
979     GST_DEBUG_OBJECT (sink, "using configured socket");
980     if (g_socket_get_family (sink->socket) == G_SOCKET_FAMILY_IPV6) {
981       sink->used_socket_v6 = G_SOCKET (g_object_ref (sink->socket));
982       sink->external_socket = TRUE;
983     } else {
984       sink->used_socket = G_SOCKET (g_object_ref (sink->socket));
985       sink->external_socket = TRUE;
986     }
987   }
988
989   if (sink->socket_v6) {
990     GST_DEBUG_OBJECT (sink, "using configured IPv6 socket");
991     g_return_val_if_fail (g_socket_get_family (sink->socket) !=
992         G_SOCKET_FAMILY_IPV6, FALSE);
993
994     if (sink->used_socket_v6 && sink->used_socket_v6 != sink->socket_v6) {
995       GST_ERROR_OBJECT (sink,
996           "Provided different IPv6 sockets in socket and socket-v6 properties");
997       return FALSE;
998     }
999
1000     sink->used_socket_v6 = G_SOCKET (g_object_ref (sink->socket_v6));
1001     sink->external_socket = TRUE;
1002   }
1003
1004   if (!sink->used_socket && !sink->used_socket_v6) {
1005     GSocketAddress *bind_addr;
1006     GInetAddress *bind_iaddr;
1007
1008     if (sink->bind_address) {
1009       GSocketFamily family;
1010
1011       bind_iaddr = g_inet_address_new_from_string (sink->bind_address);
1012       if (!bind_iaddr) {
1013         GList *results;
1014         GResolver *resolver;
1015
1016         resolver = g_resolver_get_default ();
1017         results =
1018             g_resolver_lookup_by_name (resolver, sink->bind_address,
1019             sink->cancellable, &err);
1020         if (!results) {
1021           g_object_unref (resolver);
1022           goto name_resolve;
1023         }
1024         bind_iaddr = G_INET_ADDRESS (g_object_ref (results->data));
1025         g_resolver_free_addresses (results);
1026         g_object_unref (resolver);
1027       }
1028
1029       bind_addr = g_inet_socket_address_new (bind_iaddr, sink->bind_port);
1030       g_object_unref (bind_iaddr);
1031       family = g_socket_address_get_family (G_SOCKET_ADDRESS (bind_addr));
1032
1033       if ((sink->used_socket =
1034               g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
1035                   G_SOCKET_PROTOCOL_UDP, &err)) == NULL) {
1036         g_object_unref (bind_addr);
1037         goto no_socket;
1038       }
1039
1040       g_socket_bind (sink->used_socket, bind_addr, TRUE, &err);
1041       if (err != NULL)
1042         goto bind_error;
1043     } else {
1044       /* create sender sockets if none available */
1045       if ((sink->used_socket = g_socket_new (G_SOCKET_FAMILY_IPV4,
1046                   G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &err)) == NULL)
1047         goto no_socket;
1048
1049       bind_iaddr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1050       bind_addr = g_inet_socket_address_new (bind_iaddr, sink->bind_port);
1051       g_socket_bind (sink->used_socket, bind_addr, TRUE, &err);
1052       g_object_unref (bind_addr);
1053       g_object_unref (bind_iaddr);
1054       if (err != NULL)
1055         goto bind_error;
1056
1057       if ((sink->used_socket_v6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
1058                   G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP,
1059                   &err)) == NULL) {
1060         GST_INFO_OBJECT (sink, "Failed to create IPv6 socket: %s",
1061             err->message);
1062         g_clear_error (&err);
1063       } else {
1064         bind_iaddr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
1065         bind_addr = g_inet_socket_address_new (bind_iaddr, sink->bind_port);
1066         g_socket_bind (sink->used_socket_v6, bind_addr, TRUE, &err);
1067         g_object_unref (bind_addr);
1068         g_object_unref (bind_iaddr);
1069         if (err != NULL)
1070           goto bind_error;
1071       }
1072     }
1073   }
1074 #ifdef SO_SNDBUF
1075   {
1076     socklen_t len;
1077     gint sndsize, ret;
1078
1079     len = sizeof (sndsize);
1080     if (sink->buffer_size != 0) {
1081       sndsize = sink->buffer_size;
1082
1083       GST_DEBUG_OBJECT (sink, "setting udp buffer of %d bytes", sndsize);
1084       /* set buffer size, Note that on Linux this is typically limited to a
1085        * maximum of around 100K. Also a minimum of 128 bytes is required on
1086        * Linux. */
1087
1088       if (sink->used_socket) {
1089         ret =
1090             setsockopt (g_socket_get_fd (sink->used_socket), SOL_SOCKET,
1091             SO_SNDBUF, (void *) &sndsize, len);
1092         if (ret != 0) {
1093           GST_ELEMENT_WARNING (sink, RESOURCE, SETTINGS, (NULL),
1094               ("Could not create a buffer of requested %d bytes, %d: %s",
1095                   sndsize, ret, g_strerror (errno)));
1096         }
1097       }
1098
1099       if (sink->used_socket_v6) {
1100         ret =
1101             setsockopt (g_socket_get_fd (sink->used_socket_v6), SOL_SOCKET,
1102             SO_SNDBUF, (void *) &sndsize, len);
1103         if (ret != 0) {
1104           GST_ELEMENT_WARNING (sink, RESOURCE, SETTINGS, (NULL),
1105               ("Could not create a buffer of requested %d bytes, %d: %s",
1106                   sndsize, ret, g_strerror (errno)));
1107         }
1108       }
1109     }
1110
1111     /* read the value of the receive buffer. Note that on linux this returns 2x the
1112      * value we set because the kernel allocates extra memory for metadata.
1113      * The default on Linux is about 100K (which is about 50K without metadata) */
1114     if (sink->used_socket) {
1115       ret =
1116           getsockopt (g_socket_get_fd (sink->used_socket), SOL_SOCKET,
1117           SO_SNDBUF, (void *) &sndsize, &len);
1118       if (ret == 0)
1119         GST_DEBUG_OBJECT (sink, "have UDP buffer of %d bytes", sndsize);
1120       else
1121         GST_DEBUG_OBJECT (sink, "could not get UDP buffer size");
1122     }
1123
1124     if (sink->used_socket_v6) {
1125       ret =
1126           getsockopt (g_socket_get_fd (sink->used_socket_v6), SOL_SOCKET,
1127           SO_SNDBUF, (void *) &sndsize, &len);
1128       if (ret == 0)
1129         GST_DEBUG_OBJECT (sink, "have UDPv6 buffer of %d bytes", sndsize);
1130       else
1131         GST_DEBUG_OBJECT (sink, "could not get UDPv6 buffer size");
1132     }
1133   }
1134 #endif
1135
1136 #ifdef SO_BINDTODEVICE
1137   if (sink->multi_iface) {
1138     if (sink->used_socket) {
1139       if (setsockopt (g_socket_get_fd (sink->used_socket), SOL_SOCKET,
1140               SO_BINDTODEVICE, sink->multi_iface,
1141               strlen (sink->multi_iface)) < 0)
1142         GST_WARNING_OBJECT (sink, "setsockopt SO_BINDTODEVICE failed: %s",
1143             strerror (errno));
1144     }
1145     if (sink->used_socket_v6) {
1146       if (setsockopt (g_socket_get_fd (sink->used_socket_v6), SOL_SOCKET,
1147               SO_BINDTODEVICE, sink->multi_iface,
1148               strlen (sink->multi_iface)) < 0)
1149         GST_WARNING_OBJECT (sink, "setsockopt SO_BINDTODEVICE failed (v6): %s",
1150             strerror (errno));
1151     }
1152   }
1153 #endif
1154
1155   if (sink->used_socket)
1156     g_socket_set_broadcast (sink->used_socket, TRUE);
1157   if (sink->used_socket_v6)
1158     g_socket_set_broadcast (sink->used_socket_v6, TRUE);
1159
1160   sink->bytes_to_serve = 0;
1161   sink->bytes_served = 0;
1162
1163   gst_multiudpsink_setup_qos_dscp (sink, sink->used_socket);
1164   gst_multiudpsink_setup_qos_dscp (sink, sink->used_socket_v6);
1165
1166   /* look for multicast clients and join multicast groups appropriately
1167      set also ttl and multicast loopback delivery appropriately  */
1168   for (clients = sink->clients; clients; clients = g_list_next (clients)) {
1169     client = (GstUDPClient *) clients->data;
1170
1171     if (!gst_multiudpsink_configure_client (sink, client))
1172       return FALSE;
1173   }
1174   return TRUE;
1175
1176   /* ERRORS */
1177 no_socket:
1178   {
1179     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1180         ("Could not create socket: %s", err->message));
1181     g_clear_error (&err);
1182     return FALSE;
1183   }
1184 bind_error:
1185   {
1186     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1187         ("Failed to bind socket: %s", err->message));
1188     g_clear_error (&err);
1189     return FALSE;
1190   }
1191 name_resolve:
1192   {
1193     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1194         ("Failed to resolve bind address %s: %s", sink->bind_address,
1195             err->message));
1196     g_clear_error (&err);
1197     return FALSE;
1198   }
1199 }
1200
1201 static gboolean
1202 gst_multiudpsink_stop (GstBaseSink * bsink)
1203 {
1204   GstMultiUDPSink *udpsink;
1205
1206   udpsink = GST_MULTIUDPSINK (bsink);
1207
1208   if (udpsink->used_socket) {
1209     if (udpsink->close_socket || !udpsink->external_socket) {
1210       GError *err = NULL;
1211
1212       if (!g_socket_close (udpsink->used_socket, &err)) {
1213         GST_ERROR_OBJECT (udpsink, "Failed to close socket: %s", err->message);
1214         g_clear_error (&err);
1215       }
1216     }
1217
1218     g_object_unref (udpsink->used_socket);
1219     udpsink->used_socket = NULL;
1220   }
1221
1222   if (udpsink->used_socket_v6) {
1223     if (udpsink->close_socket || !udpsink->external_socket) {
1224       GError *err = NULL;
1225
1226       if (!g_socket_close (udpsink->used_socket_v6, &err)) {
1227         GST_ERROR_OBJECT (udpsink, "Failed to close socket: %s", err->message);
1228         g_clear_error (&err);
1229       }
1230     }
1231
1232     g_object_unref (udpsink->used_socket_v6);
1233     udpsink->used_socket_v6 = NULL;
1234   }
1235
1236   return TRUE;
1237 }
1238
1239 static void
1240 gst_multiudpsink_add_internal (GstMultiUDPSink * sink, const gchar * host,
1241     gint port, gboolean lock)
1242 {
1243   GstUDPClient *client;
1244   GstUDPClient udpclient;
1245   GTimeVal now;
1246   GList *find;
1247
1248   udpclient.host = (gchar *) host;
1249   udpclient.port = port;
1250
1251   GST_DEBUG_OBJECT (sink, "adding client on host %s, port %d", host, port);
1252
1253   if (lock)
1254     g_mutex_lock (&sink->client_lock);
1255
1256   find = g_list_find_custom (sink->clients, &udpclient,
1257       (GCompareFunc) client_compare);
1258   if (find) {
1259     client = (GstUDPClient *) find->data;
1260
1261     GST_DEBUG_OBJECT (sink, "found %d existing clients with host %s, port %d",
1262         client->refcount, host, port);
1263     client->refcount++;
1264   } else {
1265     client = create_client (sink, host, port);
1266     if (!client)
1267       goto error;
1268
1269     g_get_current_time (&now);
1270     client->connect_time = GST_TIMEVAL_TO_TIME (now);
1271
1272     if (sink->used_socket)
1273       gst_multiudpsink_configure_client (sink, client);
1274
1275     GST_DEBUG_OBJECT (sink, "add client with host %s, port %d", host, port);
1276     sink->clients = g_list_prepend (sink->clients, client);
1277   }
1278
1279   if (lock)
1280     g_mutex_unlock (&sink->client_lock);
1281
1282   g_signal_emit (G_OBJECT (sink),
1283       gst_multiudpsink_signals[SIGNAL_CLIENT_ADDED], 0, host, port);
1284
1285   GST_DEBUG_OBJECT (sink, "added client on host %s, port %d", host, port);
1286   return;
1287
1288   /* ERRORS */
1289 error:
1290   {
1291     GST_DEBUG_OBJECT (sink, "did not add client on host %s, port %d", host,
1292         port);
1293     if (lock)
1294       g_mutex_unlock (&sink->client_lock);
1295     return;
1296   }
1297 }
1298
1299 void
1300 gst_multiudpsink_add (GstMultiUDPSink * sink, const gchar * host, gint port)
1301 {
1302   gst_multiudpsink_add_internal (sink, host, port, TRUE);
1303 }
1304
1305 void
1306 gst_multiudpsink_remove (GstMultiUDPSink * sink, const gchar * host, gint port)
1307 {
1308   GList *find;
1309   GstUDPClient udpclient;
1310   GstUDPClient *client;
1311   GTimeVal now;
1312
1313   udpclient.host = (gchar *) host;
1314   udpclient.port = port;
1315
1316   g_mutex_lock (&sink->client_lock);
1317   find = g_list_find_custom (sink->clients, &udpclient,
1318       (GCompareFunc) client_compare);
1319   if (!find)
1320     goto not_found;
1321
1322   client = (GstUDPClient *) find->data;
1323
1324   GST_DEBUG_OBJECT (sink, "found %d clients with host %s, port %d",
1325       client->refcount, host, port);
1326
1327   client->refcount--;
1328   if (client->refcount == 0) {
1329     GInetSocketAddress *saddr = G_INET_SOCKET_ADDRESS (client->addr);
1330     GSocketFamily family = g_socket_address_get_family (client->addr);
1331     GInetAddress *addr = g_inet_socket_address_get_address (saddr);
1332     GSocket *socket;
1333
1334     /* Select socket to send from for this address */
1335     if (family == G_SOCKET_FAMILY_IPV6 || !sink->used_socket)
1336       socket = sink->used_socket_v6;
1337     else
1338       socket = sink->used_socket;
1339
1340     GST_DEBUG_OBJECT (sink, "remove client with host %s, port %d", host, port);
1341
1342     g_get_current_time (&now);
1343     client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
1344
1345     if (socket && sink->auto_multicast
1346         && g_inet_address_get_is_multicast (addr)) {
1347       GError *err = NULL;
1348
1349       if (!g_socket_leave_multicast_group (socket, addr, FALSE,
1350               sink->multi_iface, &err)) {
1351         GST_DEBUG_OBJECT (sink, "Failed to leave multicast group: %s",
1352             err->message);
1353         g_clear_error (&err);
1354       }
1355     }
1356
1357     /* Unlock to emit signal before we delete the actual client */
1358     g_mutex_unlock (&sink->client_lock);
1359     g_signal_emit (G_OBJECT (sink),
1360         gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED], 0, host, port);
1361     g_mutex_lock (&sink->client_lock);
1362
1363     sink->clients = g_list_delete_link (sink->clients, find);
1364
1365     free_client (client);
1366   }
1367   g_mutex_unlock (&sink->client_lock);
1368
1369   return;
1370
1371   /* ERRORS */
1372 not_found:
1373   {
1374     g_mutex_unlock (&sink->client_lock);
1375     GST_WARNING_OBJECT (sink, "client at host %s, port %d not found",
1376         host, port);
1377     return;
1378   }
1379 }
1380
1381 static void
1382 gst_multiudpsink_clear_internal (GstMultiUDPSink * sink, gboolean lock)
1383 {
1384   GST_DEBUG_OBJECT (sink, "clearing");
1385   /* we only need to remove the client structure, there is no additional
1386    * socket or anything to free for UDP */
1387   if (lock)
1388     g_mutex_lock (&sink->client_lock);
1389   g_list_foreach (sink->clients, (GFunc) free_client, sink);
1390   g_list_free (sink->clients);
1391   sink->clients = NULL;
1392   if (lock)
1393     g_mutex_unlock (&sink->client_lock);
1394 }
1395
1396 void
1397 gst_multiudpsink_clear (GstMultiUDPSink * sink)
1398 {
1399   gst_multiudpsink_clear_internal (sink, TRUE);
1400 }
1401
1402 GstStructure *
1403 gst_multiudpsink_get_stats (GstMultiUDPSink * sink, const gchar * host,
1404     gint port)
1405 {
1406   GstUDPClient *client;
1407   GstStructure *result = NULL;
1408   GstUDPClient udpclient;
1409   GList *find;
1410
1411   udpclient.host = (gchar *) host;
1412   udpclient.port = port;
1413
1414   g_mutex_lock (&sink->client_lock);
1415
1416   find = g_list_find_custom (sink->clients, &udpclient,
1417       (GCompareFunc) client_compare);
1418   if (!find)
1419     goto not_found;
1420
1421   GST_DEBUG_OBJECT (sink, "stats for client with host %s, port %d", host, port);
1422
1423   client = (GstUDPClient *) find->data;
1424
1425   result = gst_structure_new_empty ("multiudpsink-stats");
1426
1427   gst_structure_set (result,
1428       "bytes-sent", G_TYPE_UINT64, client->bytes_sent,
1429       "packets-sent", G_TYPE_UINT64, client->packets_sent,
1430       "connect-time", G_TYPE_UINT64, client->connect_time,
1431       "disconnect-time", G_TYPE_UINT64, client->disconnect_time, NULL);
1432
1433   g_mutex_unlock (&sink->client_lock);
1434
1435   return result;
1436
1437   /* ERRORS */
1438 not_found:
1439   {
1440     g_mutex_unlock (&sink->client_lock);
1441     GST_WARNING_OBJECT (sink, "client with host %s, port %d not found",
1442         host, port);
1443     /* Apparently (see comment in gstmultifdsink.c) returning NULL from here may
1444      * confuse/break python bindings */
1445     return gst_structure_new_empty ("multiudpsink-stats");
1446   }
1447 }
1448
1449 static gboolean
1450 gst_multiudpsink_unlock (GstBaseSink * bsink)
1451 {
1452   GstMultiUDPSink *sink;
1453
1454   sink = GST_MULTIUDPSINK (bsink);
1455
1456   g_cancellable_cancel (sink->cancellable);
1457
1458   return TRUE;
1459 }
1460
1461 static gboolean
1462 gst_multiudpsink_unlock_stop (GstBaseSink * bsink)
1463 {
1464   GstMultiUDPSink *sink;
1465
1466   sink = GST_MULTIUDPSINK (bsink);
1467
1468   g_cancellable_reset (sink->cancellable);
1469
1470   return TRUE;
1471 }