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