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