multiudpsink: Reset windows error code after getting corresponding error message.
[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  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-multiupdsink
23  * @see_also: udpsink, multifdsink
24  *
25  * multiudpsink is a network sink that sends UDP packets to multiple
26  * clients.
27  * It can be combined with rtp payload encoders to implement RTP streaming.
28  */
29
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33 #include "gstudp-marshal.h"
34 #include "gstmultiudpsink.h"
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41 #include <errno.h>
42 #include <string.h>
43
44 GST_DEBUG_CATEGORY_STATIC (multiudpsink_debug);
45 #define GST_CAT_DEFAULT (multiudpsink_debug)
46
47 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
48     GST_PAD_SINK,
49     GST_PAD_ALWAYS,
50     GST_STATIC_CAPS_ANY);
51
52 /* elementfactory information */
53 static const GstElementDetails gst_multiudpsink_details =
54 GST_ELEMENT_DETAILS ("UDP packet sender",
55     "Sink/Network",
56     "Send data over the network via UDP",
57     "Wim Taymans <wim.taymans@gmail.com>");
58
59 /* MultiUDPSink signals and args */
60 enum
61 {
62   /* methods */
63   SIGNAL_ADD,
64   SIGNAL_REMOVE,
65   SIGNAL_CLEAR,
66   SIGNAL_GET_STATS,
67
68   /* signals */
69   SIGNAL_CLIENT_ADDED,
70   SIGNAL_CLIENT_REMOVED,
71
72   /* FILL ME */
73   LAST_SIGNAL
74 };
75
76 #define DEFAULT_SOCKFD             -1
77 #define DEFAULT_CLOSEFD            TRUE
78 #define DEFAULT_SOCK               -1
79 #define DEFAULT_CLIENTS            NULL
80 /* FIXME, this should be disabled by default, we don't need to join a multicast
81  * group for sending, if this socket is also used for receiving, it should
82  * be configured in the element that does the receive. */
83 #define DEFAULT_AUTO_MULTICAST     TRUE
84 #define DEFAULT_TTL                64
85 #define DEFAULT_TTL_MC             1
86 #define DEFAULT_LOOP               TRUE
87 #define DEFAULT_QOS_DSCP           -1
88
89 enum
90 {
91   PROP_0,
92   PROP_BYTES_TO_SERVE,
93   PROP_BYTES_SERVED,
94   PROP_SOCKFD,
95   PROP_CLOSEFD,
96   PROP_SOCK,
97   PROP_CLIENTS,
98   PROP_AUTO_MULTICAST,
99   PROP_TTL,
100   PROP_TTL_MC,
101   PROP_LOOP,
102   PROP_QOS_DSCP,
103   PROP_LAST
104 };
105
106 #define CLOSE_IF_REQUESTED(udpctx)                                        \
107 G_STMT_START {                                                            \
108   if ((!udpctx->externalfd) || (udpctx->externalfd && udpctx->closefd)) { \
109     CLOSE_SOCKET(udpctx->sock);                                           \
110     if (udpctx->sock == udpctx->sockfd)                                   \
111       udpctx->sockfd = DEFAULT_SOCKFD;                                    \
112   }                                                                       \
113   udpctx->sock = DEFAULT_SOCK;                                            \
114 } G_STMT_END
115
116 static void gst_multiudpsink_base_init (gpointer g_class);
117 static void gst_multiudpsink_class_init (GstMultiUDPSinkClass * klass);
118 static void gst_multiudpsink_init (GstMultiUDPSink * udpsink);
119 static void gst_multiudpsink_finalize (GObject * object);
120
121 static GstFlowReturn gst_multiudpsink_render (GstBaseSink * sink,
122     GstBuffer * buffer);
123 #ifndef G_OS_WIN32              /* sendmsg() is not available on Windows */
124 static GstFlowReturn gst_multiudpsink_render_list (GstBaseSink * bsink,
125     GstBufferList * list);
126 #endif
127 static GstStateChangeReturn gst_multiudpsink_change_state (GstElement *
128     element, GstStateChange transition);
129
130 static void gst_multiudpsink_set_property (GObject * object, guint prop_id,
131     const GValue * value, GParamSpec * pspec);
132 static void gst_multiudpsink_get_property (GObject * object, guint prop_id,
133     GValue * value, GParamSpec * pspec);
134
135 static void gst_multiudpsink_add_internal (GstMultiUDPSink * sink,
136     const gchar * host, gint port, gboolean lock);
137 static void gst_multiudpsink_clear_internal (GstMultiUDPSink * sink,
138     gboolean lock);
139
140 static void free_client (GstUDPClient * client);
141
142 static GstElementClass *parent_class = NULL;
143
144 static guint gst_multiudpsink_signals[LAST_SIGNAL] = { 0 };
145
146 GType
147 gst_multiudpsink_get_type (void)
148 {
149   static GType multiudpsink_type = 0;
150
151   if (!multiudpsink_type) {
152     static const GTypeInfo multiudpsink_info = {
153       sizeof (GstMultiUDPSinkClass),
154       gst_multiudpsink_base_init,
155       NULL,
156       (GClassInitFunc) gst_multiudpsink_class_init,
157       NULL,
158       NULL,
159       sizeof (GstMultiUDPSink),
160       0,
161       (GInstanceInitFunc) gst_multiudpsink_init,
162       NULL
163     };
164
165     multiudpsink_type =
166         g_type_register_static (GST_TYPE_BASE_SINK, "GstMultiUDPSink",
167         &multiudpsink_info, 0);
168   }
169   return multiudpsink_type;
170 }
171
172 static void
173 gst_multiudpsink_base_init (gpointer g_class)
174 {
175   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
176
177   gst_element_class_add_pad_template (element_class,
178       gst_static_pad_template_get (&sink_template));
179
180   gst_element_class_set_details (element_class, &gst_multiudpsink_details);
181 }
182
183 static void
184 gst_multiudpsink_class_init (GstMultiUDPSinkClass * klass)
185 {
186   GObjectClass *gobject_class;
187   GstElementClass *gstelement_class;
188   GstBaseSinkClass *gstbasesink_class;
189
190   gobject_class = (GObjectClass *) klass;
191   gstelement_class = (GstElementClass *) klass;
192   gstbasesink_class = (GstBaseSinkClass *) klass;
193
194   parent_class = g_type_class_peek_parent (klass);
195
196   gobject_class->set_property = gst_multiudpsink_set_property;
197   gobject_class->get_property = gst_multiudpsink_get_property;
198   gobject_class->finalize = gst_multiudpsink_finalize;
199
200   /**
201    * GstMultiUDPSink::add:
202    * @gstmultiudpsink: the sink on which the signal is emitted
203    * @host: the hostname/IP address of the client to add
204    * @port: the port of the client to add
205    *
206    * Add a client with destination @host and @port to the list of
207    * clients.
208    */
209   gst_multiudpsink_signals[SIGNAL_ADD] =
210       g_signal_new ("add", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
211       G_STRUCT_OFFSET (GstMultiUDPSinkClass, add),
212       NULL, NULL, gst_udp_marshal_VOID__STRING_INT, G_TYPE_NONE, 2,
213       G_TYPE_STRING, G_TYPE_INT);
214   /**
215    * GstMultiUDPSink::remove:
216    * @gstmultiudpsink: the sink on which the signal is emitted
217    * @host: the hostname/IP address of the client to remove
218    * @port: the port of the client to remove
219    *
220    * Remove the client with destination @host and @port from the list of
221    * clients.
222    */
223   gst_multiudpsink_signals[SIGNAL_REMOVE] =
224       g_signal_new ("remove", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
225       G_STRUCT_OFFSET (GstMultiUDPSinkClass, remove),
226       NULL, NULL, gst_udp_marshal_VOID__STRING_INT, G_TYPE_NONE, 2,
227       G_TYPE_STRING, G_TYPE_INT);
228   /**
229    * GstMultiUDPSink::clear:
230    * @gstmultiudpsink: the sink on which the signal is emitted
231    *
232    * Clear the list of clients.
233    */
234   gst_multiudpsink_signals[SIGNAL_CLEAR] =
235       g_signal_new ("clear", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
236       G_STRUCT_OFFSET (GstMultiUDPSinkClass, clear),
237       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
238   /**
239    * GstMultiUDPSink::get-stats:
240    * @gstmultiudpsink: the sink on which the signal is emitted
241    * @host: the hostname/IP address of the client to get stats on
242    * @port: the port of the client to get stats on
243    *
244    * Get the statistics of the client with destination @host and @port.
245    *
246    * Returns: a GValueArray of uint64: bytes_sent, packets_sent,
247    *           connect_time (in epoch seconds), disconnect_time (in epoch seconds)
248    */
249   gst_multiudpsink_signals[SIGNAL_GET_STATS] =
250       g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
251       G_STRUCT_OFFSET (GstMultiUDPSinkClass, get_stats),
252       NULL, NULL, gst_udp_marshal_BOXED__STRING_INT, G_TYPE_VALUE_ARRAY, 2,
253       G_TYPE_STRING, G_TYPE_INT);
254   /**
255    * GstMultiUDPSink::client-added:
256    * @gstmultiudpsink: the sink emitting the signal
257    * @host: the hostname/IP address of the added client
258    * @port: the port of the added client
259    *
260    * Signal emited when a new client is added to the list of
261    * clients.
262    */
263   gst_multiudpsink_signals[SIGNAL_CLIENT_ADDED] =
264       g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
265       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiUDPSinkClass, client_added),
266       NULL, NULL, gst_udp_marshal_VOID__STRING_INT, G_TYPE_NONE, 2,
267       G_TYPE_STRING, G_TYPE_INT);
268   /**
269    * GstMultiUDPSink::client-removed:
270    * @gstmultiudpsink: the sink emitting the signal
271    * @host: the hostname/IP address of the removed client
272    * @port: the port of the removed client
273    *
274    * Signal emited when a client is removed from the list of
275    * clients.
276    */
277   gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED] =
278       g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
279       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiUDPSinkClass,
280           client_removed), NULL, NULL, gst_udp_marshal_VOID__STRING_INT,
281       G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT);
282
283   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTES_TO_SERVE,
284       g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
285           "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
286           G_PARAM_READABLE));
287   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTES_SERVED,
288       g_param_spec_uint64 ("bytes-served", "Bytes served",
289           "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
290           G_PARAM_READABLE));
291   g_object_class_install_property (gobject_class, PROP_SOCKFD,
292       g_param_spec_int ("sockfd", "Socket Handle",
293           "Socket to use for UDP sending. (-1 == allocate)",
294           -1, G_MAXINT, DEFAULT_SOCKFD, G_PARAM_READWRITE));
295   g_object_class_install_property (gobject_class, PROP_CLOSEFD,
296       g_param_spec_boolean ("closefd", "Close sockfd",
297           "Close sockfd if passed as property on state change",
298           DEFAULT_CLOSEFD, G_PARAM_READWRITE));
299   g_object_class_install_property (gobject_class, PROP_SOCK,
300       g_param_spec_int ("sock", "Socket Handle",
301           "Socket currently in use for UDP sending. (-1 == no socket)",
302           -1, G_MAXINT, DEFAULT_SOCK, G_PARAM_READABLE));
303   g_object_class_install_property (gobject_class, PROP_CLIENTS,
304       g_param_spec_string ("clients", "Clients",
305           "A comma separated list of host:port pairs with destinations",
306           DEFAULT_CLIENTS, G_PARAM_READWRITE));
307   g_object_class_install_property (gobject_class, PROP_AUTO_MULTICAST,
308       g_param_spec_boolean ("auto-multicast",
309           "Automatically join/leave multicast groups",
310           "Automatically join/leave the multicast groups, FALSE means user"
311           " has to do it himself", DEFAULT_AUTO_MULTICAST, G_PARAM_READWRITE));
312   g_object_class_install_property (gobject_class, PROP_TTL,
313       g_param_spec_int ("ttl", "Unicast TTL",
314           "Used for setting the unicast TTL parameter",
315           0, 255, DEFAULT_TTL, G_PARAM_READWRITE));
316   g_object_class_install_property (gobject_class, PROP_TTL_MC,
317       g_param_spec_int ("ttl-mc", "Multicast TTL",
318           "Used for setting the multicast TTL parameter",
319           0, 255, DEFAULT_TTL_MC, G_PARAM_READWRITE));
320   g_object_class_install_property (gobject_class, PROP_LOOP,
321       g_param_spec_boolean ("loop", "Multicast Loopback",
322           "Used for setting the multicast loop parameter. TRUE = enable,"
323           " FALSE = disable", DEFAULT_LOOP, G_PARAM_READWRITE));
324   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_QOS_DSCP,
325       g_param_spec_int ("qos-dscp", "QoS diff srv code point",
326           "Quality of Service, differentiated services code point (-1 default)",
327           -1, 63, DEFAULT_QOS_DSCP, G_PARAM_READWRITE));
328
329   gstelement_class->change_state = gst_multiudpsink_change_state;
330
331   gstbasesink_class->render = gst_multiudpsink_render;
332 #ifndef G_OS_WIN32
333   gstbasesink_class->render_list = gst_multiudpsink_render_list;
334 #endif
335   klass->add = gst_multiudpsink_add;
336   klass->remove = gst_multiudpsink_remove;
337   klass->clear = gst_multiudpsink_clear;
338   klass->get_stats = gst_multiudpsink_get_stats;
339
340   GST_DEBUG_CATEGORY_INIT (multiudpsink_debug, "multiudpsink", 0, "UDP sink");
341 }
342
343
344 static void
345 gst_multiudpsink_init (GstMultiUDPSink * sink)
346 {
347   WSA_STARTUP (sink);
348
349   sink->client_lock = g_mutex_new ();
350   sink->sock = DEFAULT_SOCK;
351   sink->sockfd = DEFAULT_SOCKFD;
352   sink->closefd = DEFAULT_CLOSEFD;
353   sink->externalfd = (sink->sockfd != -1);
354   sink->auto_multicast = DEFAULT_AUTO_MULTICAST;
355   sink->ttl = DEFAULT_TTL;
356   sink->ttl_mc = DEFAULT_TTL_MC;
357   sink->loop = DEFAULT_LOOP;
358   sink->qos_dscp = DEFAULT_QOS_DSCP;
359 }
360
361 static void
362 gst_multiudpsink_finalize (GObject * object)
363 {
364   GstMultiUDPSink *sink;
365
366   sink = GST_MULTIUDPSINK (object);
367
368   g_list_foreach (sink->clients, (GFunc) free_client, NULL);
369   g_list_free (sink->clients);
370
371   if (sink->sockfd >= 0 && sink->closefd)
372     CLOSE_SOCKET (sink->sockfd);
373
374   g_mutex_free (sink->client_lock);
375
376   WSA_CLEANUP (object);
377
378   G_OBJECT_CLASS (parent_class)->finalize (object);
379 }
380
381 static gboolean
382 socket_error_is_ignorable ()
383 {
384 #ifdef G_OS_WIN32
385   /* Windows doesn't seem to have an EAGAIN for sockets */
386   return WSAGetLastError () == WSAEINTR;
387 #else
388   return errno == EINTR || errno == EAGAIN;
389 #endif
390 }
391
392 static int
393 socket_last_error_code ()
394 {
395 #ifdef G_OS_WIN32
396   return WSAGetLastError ();
397 #else
398   return errno;
399 #endif
400 }
401
402 static gchar *
403 socket_last_error_message ()
404 {
405 #ifdef G_OS_WIN32
406   int errorcode = WSAGetLastError ();
407   wchar_t buf[1024];
408   DWORD result =
409       FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
410       NULL, errorcode, 0, (LPSTR) buf, sizeof (buf) / sizeof (wchar_t), NULL);
411   if (FAILED (result)) {
412     return g_strdup ("failed to get error message from system");
413   } else {
414     gchar *res =
415         g_convert ((gchar *) buf, -1, "UTF-16", "UTF-8", NULL, NULL, NULL);
416     /* g_convert() internally calls windows functions which reset the
417        windows error code, so fix it up again like this */
418     WSASetLastError (errorcode);
419     return res;
420   }
421 #else
422   return g_strdup (g_strerror (errno));
423 #endif
424 }
425
426 static GstFlowReturn
427 gst_multiudpsink_render (GstBaseSink * bsink, GstBuffer * buffer)
428 {
429   GstMultiUDPSink *sink;
430   gint ret, size, num = 0, no_clients = 0;
431   guint8 *data;
432   GList *clients;
433   gint len;
434
435   sink = GST_MULTIUDPSINK (bsink);
436
437   size = GST_BUFFER_SIZE (buffer);
438   data = GST_BUFFER_DATA (buffer);
439
440   sink->bytes_to_serve += size;
441
442   /* grab lock while iterating and sending to clients, this should be
443    * fast as UDP never blocks */
444   g_mutex_lock (sink->client_lock);
445   GST_LOG_OBJECT (bsink, "about to send %d bytes", size);
446
447   for (clients = sink->clients; clients; clients = g_list_next (clients)) {
448     GstUDPClient *client;
449
450     client = (GstUDPClient *) clients->data;
451     no_clients++;
452     GST_LOG_OBJECT (sink, "sending %d bytes to client %p", size, client);
453
454     while (TRUE) {
455       len = gst_udp_get_sockaddr_length (&client->theiraddr);
456
457       ret = sendto (*client->sock,
458 #ifdef G_OS_WIN32
459           (char *) data,
460 #else
461           data,
462 #endif
463           size, 0, (struct sockaddr *) &client->theiraddr, len);
464
465       if (ret < 0) {
466         /* some error, just warn, it's likely recoverable and we don't want to
467          * break streaming. We break so that we stop retrying for this client. */
468         if (!socket_error_is_ignorable ()) {
469           gchar *errormessage = socket_last_error_message ();
470           GST_WARNING_OBJECT (sink, "client %p gave error %d (%s)", client,
471               socket_last_error_code (), errormessage);
472           g_free (errormessage);
473           break;
474         }
475       } else {
476         num++;
477         client->bytes_sent += ret;
478         client->packets_sent++;
479         sink->bytes_served += ret;
480         break;
481       }
482     }
483   }
484   g_mutex_unlock (sink->client_lock);
485
486   GST_LOG_OBJECT (sink, "sent %d bytes to %d (of %d) clients", size, num,
487       no_clients);
488
489   return GST_FLOW_OK;
490 }
491
492 #ifndef G_OS_WIN32
493 static GstFlowReturn
494 gst_multiudpsink_render_list (GstBaseSink * bsink, GstBufferList * list)
495 {
496   GstMultiUDPSink *sink;
497   GList *clients;
498   gint ret, size = 0, num = 0, no_clients = 0;
499   struct iovec *iov;
500   struct msghdr msg = { 0 };
501
502   GstBufferListIterator *it;
503   guint gsize;
504   GstBuffer *buf;
505
506   sink = GST_MULTIUDPSINK (bsink);
507
508   g_return_val_if_fail (list != NULL, GST_FLOW_ERROR);
509
510   it = gst_buffer_list_iterate (list);
511   g_return_val_if_fail (it != NULL, GST_FLOW_ERROR);
512
513   while (gst_buffer_list_iterator_next_group (it)) {
514     msg.msg_iovlen = 0;
515     size = 0;
516
517     if ((gsize = gst_buffer_list_iterator_n_buffers (it)) == 0) {
518       goto invalid_list;
519     }
520
521     iov = (struct iovec *) g_malloc (gsize * sizeof (struct iovec));
522     msg.msg_iov = iov;
523
524     while ((buf = gst_buffer_list_iterator_next (it))) {
525       msg.msg_iov[msg.msg_iovlen].iov_len = GST_BUFFER_SIZE (buf);
526       msg.msg_iov[msg.msg_iovlen].iov_base = GST_BUFFER_DATA (buf);
527       msg.msg_iovlen++;
528       size += GST_BUFFER_SIZE (buf);
529     }
530
531     sink->bytes_to_serve += size;
532
533     /* grab lock while iterating and sending to clients, this should be
534      * fast as UDP never blocks */
535     g_mutex_lock (sink->client_lock);
536     GST_LOG_OBJECT (bsink, "about to send %d bytes", size);
537
538     for (clients = sink->clients; clients; clients = g_list_next (clients)) {
539       GstUDPClient *client;
540
541       client = (GstUDPClient *) clients->data;
542       no_clients++;
543       GST_LOG_OBJECT (sink, "sending %d bytes to client %p", size, client);
544
545       while (TRUE) {
546         msg.msg_name = (void *) &client->theiraddr;
547         msg.msg_namelen = sizeof (client->theiraddr);
548         ret = sendmsg (*client->sock, &msg, 0);
549
550         if (ret < 0) {
551           if (!socket_error_is_ignorable ()) {
552             break;
553           }
554         } else {
555           num++;
556           client->bytes_sent += ret;
557           client->packets_sent++;
558           sink->bytes_served += ret;
559           break;
560         }
561       }
562     }
563     g_mutex_unlock (sink->client_lock);
564
565     g_free (iov);
566     msg.msg_iov = NULL;
567
568     GST_LOG_OBJECT (sink, "sent %d bytes to %d (of %d) clients", size, num,
569         no_clients);
570   }
571
572   gst_buffer_list_iterator_free (it);
573
574   return GST_FLOW_OK;
575
576 invalid_list:
577   gst_buffer_list_iterator_free (it);
578   return GST_FLOW_ERROR;
579 }
580 #endif
581
582 static void
583 gst_multiudpsink_set_clients_string (GstMultiUDPSink * sink,
584     const gchar * string)
585 {
586   gchar **clients;
587   gint i;
588
589   clients = g_strsplit (string, ",", 0);
590
591   g_mutex_lock (sink->client_lock);
592   /* clear all existing clients */
593   gst_multiudpsink_clear_internal (sink, FALSE);
594   for (i = 0; clients[i]; i++) {
595     gchar *host, *p;
596     gint port = 0;
597
598     host = clients[i];
599     p = strstr (clients[i], ":");
600     if (p != NULL) {
601       *p = '\0';
602       port = atoi (p + 1);
603     }
604     if (port != 0)
605       gst_multiudpsink_add_internal (sink, host, port, FALSE);
606   }
607   g_mutex_unlock (sink->client_lock);
608
609   g_strfreev (clients);
610 }
611
612 static gchar *
613 gst_multiudpsink_get_clients_string (GstMultiUDPSink * sink)
614 {
615   GString *str;
616   GList *clients;
617
618   str = g_string_new ("");
619
620   g_mutex_lock (sink->client_lock);
621   clients = sink->clients;
622   while (clients) {
623     GstUDPClient *client;
624
625     client = (GstUDPClient *) clients->data;
626
627     clients = g_list_next (clients);
628
629     g_string_append_printf (str, "%s:%d%s", client->host, client->port,
630         (clients ? "," : ""));
631   }
632   g_mutex_unlock (sink->client_lock);
633
634   return g_string_free (str, FALSE);
635 }
636
637 static void
638 gst_multiudpsink_setup_qos_dscp (GstMultiUDPSink * sink)
639 {
640   gint tos;
641
642   /* don't touch on -1 */
643   if (sink->qos_dscp < 0)
644     return;
645
646   if (sink->sock < 0)
647     return;
648
649   GST_DEBUG_OBJECT (sink, "setting TOS to %d", sink->qos_dscp);
650
651   /* Extract and shift 6 bits of DSFIELD */
652   tos = (sink->qos_dscp & 0x3f) << 2;
653
654   if (setsockopt (sink->sock, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0) {
655     gchar *errormessage = socket_last_error_message ();
656     GST_ERROR_OBJECT (sink, "could not set TOS: %s", errormessage);
657     g_free (errormessage);
658   }
659 #ifdef IPV6_TCLASS
660   if (setsockopt (sink->sock, IPPROTO_IPV6, IPV6_TCLASS, &tos,
661           sizeof (tos)) < 0) {
662     gchar *errormessage = socket_last_error_message ();
663     GST_ERROR_OBJECT (sink, "could not set TCLASS: %s", errormessage);
664     g_free (errormessage);
665   }
666 #endif
667 }
668
669 static void
670 gst_multiudpsink_set_property (GObject * object, guint prop_id,
671     const GValue * value, GParamSpec * pspec)
672 {
673   GstMultiUDPSink *udpsink;
674
675   udpsink = GST_MULTIUDPSINK (object);
676
677   switch (prop_id) {
678     case PROP_SOCKFD:
679       if (udpsink->sockfd >= 0 && udpsink->sockfd != udpsink->sock &&
680           udpsink->closefd)
681         CLOSE_SOCKET (udpsink->sockfd);
682       udpsink->sockfd = g_value_get_int (value);
683       GST_DEBUG_OBJECT (udpsink, "setting SOCKFD to %d", udpsink->sockfd);
684       break;
685     case PROP_CLOSEFD:
686       udpsink->closefd = g_value_get_boolean (value);
687       break;
688     case PROP_CLIENTS:
689       gst_multiudpsink_set_clients_string (udpsink, g_value_get_string (value));
690       break;
691     case PROP_AUTO_MULTICAST:
692       udpsink->auto_multicast = g_value_get_boolean (value);
693       break;
694     case PROP_TTL:
695       udpsink->ttl = g_value_get_int (value);
696       break;
697     case PROP_TTL_MC:
698       udpsink->ttl_mc = g_value_get_int (value);
699       break;
700     case PROP_LOOP:
701       udpsink->loop = g_value_get_boolean (value);
702       break;
703     case PROP_QOS_DSCP:
704       udpsink->qos_dscp = g_value_get_int (value);
705       gst_multiudpsink_setup_qos_dscp (udpsink);
706       break;
707     default:
708       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
709       break;
710   }
711 }
712
713 static void
714 gst_multiudpsink_get_property (GObject * object, guint prop_id, GValue * value,
715     GParamSpec * pspec)
716 {
717   GstMultiUDPSink *udpsink;
718
719   udpsink = GST_MULTIUDPSINK (object);
720
721   switch (prop_id) {
722     case PROP_BYTES_TO_SERVE:
723       g_value_set_uint64 (value, udpsink->bytes_to_serve);
724       break;
725     case PROP_BYTES_SERVED:
726       g_value_set_uint64 (value, udpsink->bytes_served);
727       break;
728     case PROP_SOCKFD:
729       g_value_set_int (value, udpsink->sockfd);
730       break;
731     case PROP_CLOSEFD:
732       g_value_set_boolean (value, udpsink->closefd);
733       break;
734     case PROP_SOCK:
735       g_value_set_int (value, udpsink->sock);
736       break;
737     case PROP_CLIENTS:
738       g_value_take_string (value,
739           gst_multiudpsink_get_clients_string (udpsink));
740       break;
741     case PROP_AUTO_MULTICAST:
742       g_value_set_boolean (value, udpsink->auto_multicast);
743       break;
744     case PROP_TTL:
745       g_value_set_int (value, udpsink->ttl);
746       break;
747     case PROP_TTL_MC:
748       g_value_set_int (value, udpsink->ttl_mc);
749       break;
750     case PROP_LOOP:
751       g_value_set_boolean (value, udpsink->loop);
752       break;
753     case PROP_QOS_DSCP:
754       g_value_set_int (value, udpsink->qos_dscp);
755       break;
756     default:
757       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
758       break;
759   }
760 }
761
762 static gboolean
763 gst_multiudpsink_configure_client (GstMultiUDPSink * sink,
764     GstUDPClient * client)
765 {
766   GST_DEBUG_OBJECT (sink, "configuring client %p", client);
767
768   if (gst_udp_is_multicast (&client->theiraddr)) {
769     GST_DEBUG_OBJECT (sink, "we have a multicast client %p", client);
770     if (sink->auto_multicast) {
771       GST_DEBUG_OBJECT (sink, "autojoining group");
772       if (gst_udp_join_group (*(client->sock), &client->theiraddr, NULL)
773           != 0)
774         goto join_group_failed;
775     }
776     GST_DEBUG_OBJECT (sink, "setting loop to %d", sink->loop);
777     if (gst_udp_set_loop (sink->sock, sink->loop) != 0)
778       goto loop_failed;
779     GST_DEBUG_OBJECT (sink, "setting ttl to %d", sink->ttl_mc);
780     if (gst_udp_set_ttl (sink->sock, sink->ttl_mc, TRUE) != 0)
781       goto ttl_failed;
782   } else {
783     GST_DEBUG_OBJECT (sink, "setting unicast ttl to %d", sink->ttl);
784     if (gst_udp_set_ttl (sink->sock, sink->ttl, FALSE) != 0)
785       goto ttl_failed;
786   }
787   return TRUE;
788
789   /* ERRORS */
790 join_group_failed:
791   {
792     gchar *errormessage = socket_last_error_message ();
793     int errorcode = socket_last_error_code ();
794     CLOSE_IF_REQUESTED (sink);
795     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
796         ("Could not join multicast group (%d): %s", errorcode, errormessage));
797     g_free (errormessage);
798     return FALSE;
799   }
800 ttl_failed:
801   {
802     gchar *errormessage = socket_last_error_message ();
803     int errorcode = socket_last_error_code ();
804     CLOSE_IF_REQUESTED (sink);
805     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
806         ("Could not set TTL socket option (%d): %s", errorcode, errormessage));
807     g_free (errormessage);
808     return FALSE;
809   }
810 loop_failed:
811   {
812     gchar *errormessage = socket_last_error_message ();
813     int errorcode = socket_last_error_code ();
814     CLOSE_IF_REQUESTED (sink);
815     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
816         ("Could not set loopback socket option (%d): %s",
817             errorcode, errormessage));
818     g_free (errormessage);
819     return FALSE;
820   }
821 }
822
823 /* create a socket for sending to remote machine */
824 static gboolean
825 gst_multiudpsink_init_send (GstMultiUDPSink * sink)
826 {
827   guint bc_val;
828   GList *clients;
829   GstUDPClient *client;
830
831   if (sink->sockfd == -1) {
832     GST_DEBUG_OBJECT (sink, "creating sockets");
833     /* create sender socket try IP6, fall back to IP4 */
834     if ((sink->sock = socket (AF_INET6, SOCK_DGRAM, 0)) == -1)
835       if ((sink->sock = socket (AF_INET, SOCK_DGRAM, 0)) == -1)
836         goto no_socket;
837
838     GST_DEBUG_OBJECT (sink, "have socket");
839     sink->externalfd = FALSE;
840   } else {
841     GST_DEBUG_OBJECT (sink, "using configured socket");
842     /* we use the configured socket */
843     sink->sock = sink->sockfd;
844     sink->externalfd = TRUE;
845   }
846
847   bc_val = 1;
848   if (setsockopt (sink->sock, SOL_SOCKET, SO_BROADCAST, &bc_val,
849           sizeof (bc_val)) < 0)
850     goto no_broadcast;
851
852   sink->bytes_to_serve = 0;
853   sink->bytes_served = 0;
854
855   gst_multiudpsink_setup_qos_dscp (sink);
856
857   /* look for multicast clients and join multicast groups appropriately
858      set also ttl and multicast loopback delivery appropriately  */
859   for (clients = sink->clients; clients; clients = g_list_next (clients)) {
860     client = (GstUDPClient *) clients->data;
861
862     if (!gst_multiudpsink_configure_client (sink, client))
863       return FALSE;
864   }
865   return TRUE;
866
867   /* ERRORS */
868 no_socket:
869   {
870     gchar *errormessage = socket_last_error_message ();
871     int errorcode = socket_last_error_code ();
872     GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
873         ("Could not create socket (%d): %s", errorcode, errormessage));
874     g_free (errormessage);
875     return FALSE;
876   }
877 no_broadcast:
878   {
879     gchar *errormessage = socket_last_error_message ();
880     int errorcode = socket_last_error_code ();
881     CLOSE_IF_REQUESTED (sink);
882     GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
883         ("Could not set broadcast socket option (%d): %s",
884             errorcode, errormessage));
885     g_free (errormessage);
886     return FALSE;
887   }
888 }
889
890 static void
891 gst_multiudpsink_close (GstMultiUDPSink * sink)
892 {
893   CLOSE_IF_REQUESTED (sink);
894 }
895
896 static void
897 gst_multiudpsink_add_internal (GstMultiUDPSink * sink, const gchar * host,
898     gint port, gboolean lock)
899 {
900   GstUDPClient *client;
901   GTimeVal now;
902
903   GST_DEBUG_OBJECT (sink, "adding client on host %s, port %d", host, port);
904   client = g_new0 (GstUDPClient, 1);
905   client->host = g_strdup (host);
906   client->port = port;
907   client->sock = &sink->sock;
908
909   if (gst_udp_get_addr (host, port, &client->theiraddr) < 0)
910     goto getaddrinfo_error;
911
912   g_get_current_time (&now);
913   client->connect_time = GST_TIMEVAL_TO_TIME (now);
914
915   if (*client->sock > 0) {
916     gst_multiudpsink_configure_client (sink, client);
917   }
918
919   if (lock)
920     g_mutex_lock (sink->client_lock);
921   sink->clients = g_list_prepend (sink->clients, client);
922   if (lock)
923     g_mutex_unlock (sink->client_lock);
924
925   g_signal_emit (G_OBJECT (sink),
926       gst_multiudpsink_signals[SIGNAL_CLIENT_ADDED], 0, host, port);
927
928   GST_DEBUG_OBJECT (sink, "added client on host %s, port %d", host, port);
929   return;
930
931   /* ERRORS */
932 getaddrinfo_error:
933   {
934     GST_DEBUG_OBJECT (sink, "did not add client on host %s, port %d", host,
935         port);
936     GST_WARNING_OBJECT (sink, "getaddrinfo lookup error?");
937     g_free (client->host);
938     g_free (client);
939     return;
940   }
941 }
942
943 void
944 gst_multiudpsink_add (GstMultiUDPSink * sink, const gchar * host, gint port)
945 {
946   gst_multiudpsink_add_internal (sink, host, port, TRUE);
947 }
948
949 static gint
950 client_compare (GstUDPClient * a, GstUDPClient * b)
951 {
952   if ((a->port == b->port) && (strcmp (a->host, b->host) == 0))
953     return 0;
954
955   return 1;
956 }
957
958 static void
959 free_client (GstUDPClient * client)
960 {
961   g_free (client->host);
962   g_free (client);
963 }
964
965 void
966 gst_multiudpsink_remove (GstMultiUDPSink * sink, const gchar * host, gint port)
967 {
968   GList *find;
969   GstUDPClient udpclient;
970   GstUDPClient *client;
971   GTimeVal now;
972
973   udpclient.host = (gchar *) host;
974   udpclient.port = port;
975
976   g_mutex_lock (sink->client_lock);
977   find = g_list_find_custom (sink->clients, &udpclient,
978       (GCompareFunc) client_compare);
979   if (!find)
980     goto not_found;
981
982   GST_DEBUG_OBJECT (sink, "remove client with host %s, port %d", host, port);
983
984   client = (GstUDPClient *) find->data;
985
986   g_get_current_time (&now);
987   client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
988
989   if (*(client->sock) != -1 && sink->auto_multicast
990       && gst_udp_is_multicast (&client->theiraddr))
991     gst_udp_leave_group (*(client->sock), &client->theiraddr);
992
993   /* Unlock to emit signal before we delete the actual client */
994   g_mutex_unlock (sink->client_lock);
995   g_signal_emit (G_OBJECT (sink),
996       gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED], 0, host, port);
997   g_mutex_lock (sink->client_lock);
998
999   sink->clients = g_list_delete_link (sink->clients, find);
1000
1001   free_client (client);
1002   g_mutex_unlock (sink->client_lock);
1003
1004   return;
1005
1006   /* ERRORS */
1007 not_found:
1008   {
1009     g_mutex_unlock (sink->client_lock);
1010     GST_WARNING_OBJECT (sink, "client at host %s, port %d not found",
1011         host, port);
1012     return;
1013   }
1014 }
1015
1016 static void
1017 gst_multiudpsink_clear_internal (GstMultiUDPSink * sink, gboolean lock)
1018 {
1019   GST_DEBUG_OBJECT (sink, "clearing");
1020   /* we only need to remove the client structure, there is no additional
1021    * socket or anything to free for UDP */
1022   if (lock)
1023     g_mutex_lock (sink->client_lock);
1024   g_list_foreach (sink->clients, (GFunc) free_client, sink);
1025   g_list_free (sink->clients);
1026   sink->clients = NULL;
1027   if (lock)
1028     g_mutex_unlock (sink->client_lock);
1029 }
1030
1031 void
1032 gst_multiudpsink_clear (GstMultiUDPSink * sink)
1033 {
1034   gst_multiudpsink_clear_internal (sink, TRUE);
1035 }
1036
1037 GValueArray *
1038 gst_multiudpsink_get_stats (GstMultiUDPSink * sink, const gchar * host,
1039     gint port)
1040 {
1041   GstUDPClient *client;
1042   GValueArray *result = NULL;
1043   GstUDPClient udpclient;
1044   GList *find;
1045   GValue value = { 0 };
1046
1047   udpclient.host = (gchar *) host;
1048   udpclient.port = port;
1049
1050   g_mutex_lock (sink->client_lock);
1051
1052   find = g_list_find_custom (sink->clients, &udpclient,
1053       (GCompareFunc) client_compare);
1054   if (!find)
1055     goto not_found;
1056
1057   GST_DEBUG_OBJECT (sink, "stats for client with host %s, port %d", host, port);
1058
1059   client = (GstUDPClient *) find->data;
1060
1061   /* Result is a value array of (bytes_sent, packets_sent,
1062    * connect_time, disconnect_time), all as uint64 */
1063   result = g_value_array_new (4);
1064
1065   g_value_init (&value, G_TYPE_UINT64);
1066   g_value_set_uint64 (&value, client->bytes_sent);
1067   result = g_value_array_append (result, &value);
1068   g_value_unset (&value);
1069
1070   g_value_init (&value, G_TYPE_UINT64);
1071   g_value_set_uint64 (&value, client->packets_sent);
1072   result = g_value_array_append (result, &value);
1073   g_value_unset (&value);
1074
1075   g_value_init (&value, G_TYPE_UINT64);
1076   g_value_set_uint64 (&value, client->connect_time);
1077   result = g_value_array_append (result, &value);
1078   g_value_unset (&value);
1079
1080   g_value_init (&value, G_TYPE_UINT64);
1081   g_value_set_uint64 (&value, client->disconnect_time);
1082   result = g_value_array_append (result, &value);
1083   g_value_unset (&value);
1084
1085   g_mutex_unlock (sink->client_lock);
1086
1087   return result;
1088
1089   /* ERRORS */
1090 not_found:
1091   {
1092     g_mutex_unlock (sink->client_lock);
1093     GST_WARNING_OBJECT (sink, "client with host %s, port %d not found",
1094         host, port);
1095     /* Apparently (see comment in gstmultifdsink.c) returning NULL from here may
1096      * confuse/break python bindings */
1097     return g_value_array_new (0);
1098   }
1099 }
1100
1101 static GstStateChangeReturn
1102 gst_multiudpsink_change_state (GstElement * element, GstStateChange transition)
1103 {
1104   GstStateChangeReturn ret;
1105   GstMultiUDPSink *sink;
1106
1107   sink = GST_MULTIUDPSINK (element);
1108
1109   switch (transition) {
1110     case GST_STATE_CHANGE_READY_TO_PAUSED:
1111       if (!gst_multiudpsink_init_send (sink))
1112         goto no_init;
1113       break;
1114     default:
1115       break;
1116   }
1117
1118   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1119
1120   switch (transition) {
1121     case GST_STATE_CHANGE_PAUSED_TO_READY:
1122       gst_multiudpsink_close (sink);
1123       break;
1124     default:
1125       break;
1126   }
1127   return ret;
1128
1129   /* ERRORS */
1130 no_init:
1131   {
1132     /* _init_send() posted specific error already */
1133     return GST_STATE_CHANGE_FAILURE;
1134   }
1135 }