gstmultiudpsink.c 38.4 KB
Newer Older
1
/* GStreamer
2
 * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3
 * Copyright (C) <2009> Jarkko Palviainen <jarkko.palviainen@sesca.com>
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

21
/**
22
 * SECTION:element-multiudpsink
23 24 25 26 27 28 29
 * @see_also: udpsink, multifdsink
 *
 * multiudpsink is a network sink that sends UDP packets to multiple
 * clients.
 * It can be combined with rtp payload encoders to implement RTP streaming.
 */

30 31 32 33 34 35
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstudp-marshal.h"
#include "gstmultiudpsink.h"

36 37 38 39 40 41 42 43
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include <string.h>

44 45
#include "gst/glib-compat-private.h"

46
GST_DEBUG_CATEGORY_STATIC (multiudpsink_debug);
47 48
#define GST_CAT_DEFAULT (multiudpsink_debug)

49 50
#define UDP_MAX_SIZE 65507

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

/* MultiUDPSink signals and args */
enum
{
  /* methods */
  SIGNAL_ADD,
  SIGNAL_REMOVE,
  SIGNAL_CLEAR,
  SIGNAL_GET_STATS,

  /* signals */
  SIGNAL_CLIENT_ADDED,
  SIGNAL_CLIENT_REMOVED,

  /* FILL ME */
  LAST_SIGNAL
};

73 74 75
#define DEFAULT_SOCKFD             -1
#define DEFAULT_CLOSEFD            TRUE
#define DEFAULT_SOCK               -1
76
#define DEFAULT_CLIENTS            NULL
77
#define DEFAULT_FAMILY             0
78 79 80
/* FIXME, this should be disabled by default, we don't need to join a multicast
 * group for sending, if this socket is also used for receiving, it should
 * be configured in the element that does the receive. */
81
#define DEFAULT_AUTO_MULTICAST     TRUE
82
#define DEFAULT_TTL                64
83
#define DEFAULT_TTL_MC             1
84
#define DEFAULT_LOOP               TRUE
85
#define DEFAULT_QOS_DSCP           -1
86
#define DEFAULT_SEND_DUPLICATES    TRUE
87
#define DEFAULT_BUFFER_SIZE        0
88

89 90 91
enum
{
  PROP_0,
92 93
  PROP_BYTES_TO_SERVE,
  PROP_BYTES_SERVED,
94 95
  PROP_SOCKFD,
  PROP_CLOSEFD,
96
  PROP_SOCK,
97
  PROP_CLIENTS,
98 99
  PROP_AUTO_MULTICAST,
  PROP_TTL,
100
  PROP_TTL_MC,
101 102
  PROP_LOOP,
  PROP_QOS_DSCP,
103
  PROP_SEND_DUPLICATES,
104
  PROP_BUFFER_SIZE,
105
  PROP_LAST
106 107
};

108
#define CLOSE_IF_REQUESTED(udpctx)                                        \
109 110
G_STMT_START {                                                            \
  if ((!udpctx->externalfd) || (udpctx->externalfd && udpctx->closefd)) { \
111
    CLOSE_SOCKET(udpctx->sock);                                           \
112 113 114 115 116
    if (udpctx->sock == udpctx->sockfd)                                   \
      udpctx->sockfd = DEFAULT_SOCKFD;                                    \
  }                                                                       \
  udpctx->sock = DEFAULT_SOCK;                                            \
} G_STMT_END
117

118
static void gst_multiudpsink_base_init (gpointer g_class);
119
static void gst_multiudpsink_class_init (GstMultiUDPSinkClass * klass);
120 121 122 123 124
static void gst_multiudpsink_init (GstMultiUDPSink * udpsink);
static void gst_multiudpsink_finalize (GObject * object);

static GstFlowReturn gst_multiudpsink_render (GstBaseSink * sink,
    GstBuffer * buffer);
125
#ifndef G_OS_WIN32              /* sendmsg() is not available on Windows */
126 127
static GstFlowReturn gst_multiudpsink_render_list (GstBaseSink * bsink,
    GstBufferList * list);
128
#endif
129 130
static GstStateChangeReturn gst_multiudpsink_change_state (GstElement *
    element, GstStateChange transition);
131 132 133 134 135 136

static void gst_multiudpsink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_multiudpsink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);

137 138 139 140 141
static void gst_multiudpsink_add_internal (GstMultiUDPSink * sink,
    const gchar * host, gint port, gboolean lock);
static void gst_multiudpsink_clear_internal (GstMultiUDPSink * sink,
    gboolean lock);

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
static GstElementClass *parent_class = NULL;

static guint gst_multiudpsink_signals[LAST_SIGNAL] = { 0 };

GType
gst_multiudpsink_get_type (void)
{
  static GType multiudpsink_type = 0;

  if (!multiudpsink_type) {
    static const GTypeInfo multiudpsink_info = {
      sizeof (GstMultiUDPSinkClass),
      gst_multiudpsink_base_init,
      NULL,
      (GClassInitFunc) gst_multiudpsink_class_init,
      NULL,
      NULL,
      sizeof (GstMultiUDPSink),
      0,
      (GInstanceInitFunc) gst_multiudpsink_init,
      NULL
    };

    multiudpsink_type =
166
        g_type_register_static (GST_TYPE_BASE_SINK, "GstMultiUDPSink",
167 168 169 170 171 172 173 174 175 176
        &multiudpsink_info, 0);
  }
  return multiudpsink_type;
}

static void
gst_multiudpsink_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

177
  gst_element_class_add_static_pad_template (element_class, &sink_template);
178

179 180 181 182
  gst_element_class_set_details_simple (element_class, "UDP packet sender",
      "Sink/Network",
      "Send data over the network via UDP",
      "Wim Taymans <wim.taymans@gmail.com>");
183 184 185
}

static void
186
gst_multiudpsink_class_init (GstMultiUDPSinkClass * klass)
187 188 189 190 191 192 193 194 195
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;
  GstBaseSinkClass *gstbasesink_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;
  gstbasesink_class = (GstBaseSinkClass *) klass;

196
  parent_class = g_type_class_peek_parent (klass);
197 198 199 200 201

  gobject_class->set_property = gst_multiudpsink_set_property;
  gobject_class->get_property = gst_multiudpsink_get_property;
  gobject_class->finalize = gst_multiudpsink_finalize;

202 203 204 205 206
  /**
   * GstMultiUDPSink::add:
   * @gstmultiudpsink: the sink on which the signal is emitted
   * @host: the hostname/IP address of the client to add
   * @port: the port of the client to add
207 208
   *
   * Add a client with destination @host and @port to the list of
209 210 211 212 213 214 215
   * clients. When the same host/port pair is added multiple times, the
   * send-duplicates property defines if the packets are sent multiple times to
   * the same host/port pair or not.
   *
   * When a host/port pair is added multiple times, an equal amount of remove
   * calls must be performed to actually remove the host/port pair from the list
   * of destinations.
216
   */
217
  gst_multiudpsink_signals[SIGNAL_ADD] =
218 219
      g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
220 221 222
      G_STRUCT_OFFSET (GstMultiUDPSinkClass, add),
      NULL, NULL, gst_udp_marshal_VOID__STRING_INT, G_TYPE_NONE, 2,
      G_TYPE_STRING, G_TYPE_INT);
223 224 225 226 227
  /**
   * GstMultiUDPSink::remove:
   * @gstmultiudpsink: the sink on which the signal is emitted
   * @host: the hostname/IP address of the client to remove
   * @port: the port of the client to remove
228 229 230
   *
   * Remove the client with destination @host and @port from the list of
   * clients.
231
   */
232
  gst_multiudpsink_signals[SIGNAL_REMOVE] =
233 234
      g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
235 236 237
      G_STRUCT_OFFSET (GstMultiUDPSinkClass, remove),
      NULL, NULL, gst_udp_marshal_VOID__STRING_INT, G_TYPE_NONE, 2,
      G_TYPE_STRING, G_TYPE_INT);
238 239 240 241 242 243
  /**
   * GstMultiUDPSink::clear:
   * @gstmultiudpsink: the sink on which the signal is emitted
   *
   * Clear the list of clients.
   */
244
  gst_multiudpsink_signals[SIGNAL_CLEAR] =
245 246
      g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
247 248
      G_STRUCT_OFFSET (GstMultiUDPSinkClass, clear),
      NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
249 250 251 252 253 254
  /**
   * GstMultiUDPSink::get-stats:
   * @gstmultiudpsink: the sink on which the signal is emitted
   * @host: the hostname/IP address of the client to get stats on
   * @port: the port of the client to get stats on
   *
255 256 257
   * Get the statistics of the client with destination @host and @port.
   *
   * Returns: a GValueArray of uint64: bytes_sent, packets_sent,
258 259
   *           connect_time (in epoch seconds), disconnect_time (in epoch seconds)
   */
260
  gst_multiudpsink_signals[SIGNAL_GET_STATS] =
261 262
      g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
263 264 265
      G_STRUCT_OFFSET (GstMultiUDPSinkClass, get_stats),
      NULL, NULL, gst_udp_marshal_BOXED__STRING_INT, G_TYPE_VALUE_ARRAY, 2,
      G_TYPE_STRING, G_TYPE_INT);
266 267 268 269 270
  /**
   * GstMultiUDPSink::client-added:
   * @gstmultiudpsink: the sink emitting the signal
   * @host: the hostname/IP address of the added client
   * @port: the port of the added client
271 272 273
   *
   * Signal emited when a new client is added to the list of
   * clients.
274
   */
275 276 277 278 279
  gst_multiudpsink_signals[SIGNAL_CLIENT_ADDED] =
      g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiUDPSinkClass, client_added),
      NULL, NULL, gst_udp_marshal_VOID__STRING_INT, G_TYPE_NONE, 2,
      G_TYPE_STRING, G_TYPE_INT);
280 281 282 283 284
  /**
   * GstMultiUDPSink::client-removed:
   * @gstmultiudpsink: the sink emitting the signal
   * @host: the hostname/IP address of the removed client
   * @port: the port of the removed client
285 286 287
   *
   * Signal emited when a client is removed from the list of
   * clients.
288
   */
289 290 291 292 293 294
  gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED] =
      g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiUDPSinkClass,
          client_removed), NULL, NULL, gst_udp_marshal_VOID__STRING_INT,
      G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT);

295 296 297
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTES_TO_SERVE,
      g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
          "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
298
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
299 300
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTES_SERVED,
      g_param_spec_uint64 ("bytes-served", "Bytes served",
301
          "Total number of bytes sent to all clients", 0, G_MAXUINT64, 0,
302
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
303 304 305
  g_object_class_install_property (gobject_class, PROP_SOCKFD,
      g_param_spec_int ("sockfd", "Socket Handle",
          "Socket to use for UDP sending. (-1 == allocate)",
306 307
          -1, G_MAXINT, DEFAULT_SOCKFD,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
308 309 310
  g_object_class_install_property (gobject_class, PROP_CLOSEFD,
      g_param_spec_boolean ("closefd", "Close sockfd",
          "Close sockfd if passed as property on state change",
311
          DEFAULT_CLOSEFD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
312 313 314
  g_object_class_install_property (gobject_class, PROP_SOCK,
      g_param_spec_int ("sock", "Socket Handle",
          "Socket currently in use for UDP sending. (-1 == no socket)",
315 316
          -1, G_MAXINT, DEFAULT_SOCK,
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
317 318 319
  g_object_class_install_property (gobject_class, PROP_CLIENTS,
      g_param_spec_string ("clients", "Clients",
          "A comma separated list of host:port pairs with destinations",
320
          DEFAULT_CLIENTS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
321 322 323 324
  g_object_class_install_property (gobject_class, PROP_AUTO_MULTICAST,
      g_param_spec_boolean ("auto-multicast",
          "Automatically join/leave multicast groups",
          "Automatically join/leave the multicast groups, FALSE means user"
325 326
          " has to do it himself", DEFAULT_AUTO_MULTICAST,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
327
  g_object_class_install_property (gobject_class, PROP_TTL,
328 329
      g_param_spec_int ("ttl", "Unicast TTL",
          "Used for setting the unicast TTL parameter",
330
          0, 255, DEFAULT_TTL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331 332 333
  g_object_class_install_property (gobject_class, PROP_TTL_MC,
      g_param_spec_int ("ttl-mc", "Multicast TTL",
          "Used for setting the multicast TTL parameter",
334
          0, 255, DEFAULT_TTL_MC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
335 336 337
  g_object_class_install_property (gobject_class, PROP_LOOP,
      g_param_spec_boolean ("loop", "Multicast Loopback",
          "Used for setting the multicast loop parameter. TRUE = enable,"
338 339
          " FALSE = disable", DEFAULT_LOOP,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
340
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_QOS_DSCP,
341 342
      g_param_spec_int ("qos-dscp", "QoS diff srv code point",
          "Quality of Service, differentiated services code point (-1 default)",
343 344
          -1, 63, DEFAULT_QOS_DSCP,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
345 346 347 348 349 350 351 352 353 354 355 356
  /**
   * GstMultiUDPSink::send-duplicates
   *
   * When a host/port pair is added mutliple times, send the packet to the host
   * multiple times as well.
   *
   * Since: 0.10.26
   */
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SEND_DUPLICATES,
      g_param_spec_boolean ("send-duplicates", "Send Duplicates",
          "When a distination/port pair is added multiple times, send packets "
          "multiple times as well", DEFAULT_SEND_DUPLICATES,
357
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
358

359 360 361 362 363
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BUFFER_SIZE,
      g_param_spec_int ("buffer-size", "Buffer Size",
          "Size of the kernel send buffer in bytes, 0=default", 0, G_MAXINT,
          DEFAULT_BUFFER_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

364 365 366
  gstelement_class->change_state = gst_multiudpsink_change_state;

  gstbasesink_class->render = gst_multiudpsink_render;
367
#ifndef G_OS_WIN32
368
  gstbasesink_class->render_list = gst_multiudpsink_render_list;
369
#endif
370 371 372 373
  klass->add = gst_multiudpsink_add;
  klass->remove = gst_multiudpsink_remove;
  klass->clear = gst_multiudpsink_clear;
  klass->get_stats = gst_multiudpsink_get_stats;
374 375 376 377 378 379 380 381

  GST_DEBUG_CATEGORY_INIT (multiudpsink_debug, "multiudpsink", 0, "UDP sink");
}


static void
gst_multiudpsink_init (GstMultiUDPSink * sink)
{
382 383
  WSA_STARTUP (sink);

384
  sink->client_lock = g_mutex_new ();
385
  sink->sock = DEFAULT_SOCK;
386 387 388
  sink->sockfd = DEFAULT_SOCKFD;
  sink->closefd = DEFAULT_CLOSEFD;
  sink->externalfd = (sink->sockfd != -1);
389
  sink->auto_multicast = DEFAULT_AUTO_MULTICAST;
390
  sink->ttl = DEFAULT_TTL;
391
  sink->ttl_mc = DEFAULT_TTL_MC;
392
  sink->loop = DEFAULT_LOOP;
393
  sink->qos_dscp = DEFAULT_QOS_DSCP;
394
  sink->ss_family = DEFAULT_FAMILY;
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
  sink->send_duplicates = DEFAULT_SEND_DUPLICATES;
}

static GstUDPClient *
create_client (GstMultiUDPSink * sink, const gchar * host, gint port)
{
  GstUDPClient *client;

  client = g_slice_new0 (GstUDPClient);
  client->refcount = 1;
  client->host = g_strdup (host);
  client->port = port;

  return client;
}

static void
free_client (GstUDPClient * client)
{
  g_free (client->host);
  g_slice_free (GstUDPClient, client);
}

static gint
client_compare (GstUDPClient * a, GstUDPClient * b)
{
  if ((a->port == b->port) && (strcmp (a->host, b->host) == 0))
    return 0;

  return 1;
425 426 427 428 429 430 431 432 433
}

static void
gst_multiudpsink_finalize (GObject * object)
{
  GstMultiUDPSink *sink;

  sink = GST_MULTIUDPSINK (object);

434 435 436
  g_list_foreach (sink->clients, (GFunc) free_client, NULL);
  g_list_free (sink->clients);

437 438 439
  if (sink->sockfd >= 0 && sink->closefd)
    CLOSE_SOCKET (sink->sockfd);

440 441
  g_mutex_free (sink->client_lock);

442 443
  WSA_CLEANUP (object);

444 445 446
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

447
static gboolean
448
socket_error_is_ignorable (void)
449 450 451 452 453 454 455 456 457 458
{
#ifdef G_OS_WIN32
  /* Windows doesn't seem to have an EAGAIN for sockets */
  return WSAGetLastError () == WSAEINTR;
#else
  return errno == EINTR || errno == EAGAIN;
#endif
}

static int
459
socket_last_error_code (void)
460 461 462 463 464 465 466 467 468
{
#ifdef G_OS_WIN32
  return WSAGetLastError ();
#else
  return errno;
#endif
}

static gchar *
469
socket_last_error_message (void)
470
{
471 472 473 474 475
#ifdef G_OS_WIN32
  int errorcode = WSAGetLastError ();
  wchar_t buf[1024];
  DWORD result =
      FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
476
      NULL, errorcode, 0, (LPSTR) buf, sizeof (buf) / sizeof (wchar_t), NULL);
477 478 479
  if (FAILED (result)) {
    return g_strdup ("failed to get error message from system");
  } else {
480 481 482 483 484 485
    gchar *res =
        g_convert ((gchar *) buf, -1, "UTF-16", "UTF-8", NULL, NULL, NULL);
    /* g_convert() internally calls windows functions which reset the
       windows error code, so fix it up again like this */
    WSASetLastError (errorcode);
    return res;
486 487
  }
#else
488
  return g_strdup (g_strerror (errno));
489
#endif
490 491
}

492 493 494 495
static GstFlowReturn
gst_multiudpsink_render (GstBaseSink * bsink, GstBuffer * buffer)
{
  GstMultiUDPSink *sink;
496
  gint ret, size, num = 0, no_clients = 0;
497 498
  guint8 *data;
  GList *clients;
499
  gint len;
500 501 502 503 504 505

  sink = GST_MULTIUDPSINK (bsink);

  size = GST_BUFFER_SIZE (buffer);
  data = GST_BUFFER_DATA (buffer);

506 507 508 509 510
  if (size > UDP_MAX_SIZE) {
    GST_WARNING ("Attempting to send a UDP packet larger than maximum "
        "size (%d > %d)", size, UDP_MAX_SIZE);
  }

511 512
  sink->bytes_to_serve += size;

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
513
  /* grab lock while iterating and sending to clients, this should be
514
   * fast as UDP never blocks */
515
  g_mutex_lock (sink->client_lock);
516 517
  GST_LOG_OBJECT (bsink, "about to send %d bytes", size);

518 519
  for (clients = sink->clients; clients; clients = g_list_next (clients)) {
    GstUDPClient *client;
520
    gint count;
521 522

    client = (GstUDPClient *) clients->data;
523
    no_clients++;
524
    GST_LOG_OBJECT (sink, "sending %d bytes to client %p", size, client);
525

526 527 528 529 530
    count = sink->send_duplicates ? client->refcount : 1;

    while (count--) {
      while (TRUE) {
        len = gst_udp_get_sockaddr_length (&client->theiraddr);
531

532
        ret = sendto (*client->sock,
533
#ifdef G_OS_WIN32
534
            (char *) data,
535
#else
536
            data,
537
#endif
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
            size, 0, (struct sockaddr *) &client->theiraddr, len);

        if (ret < 0) {
          /* some error, just warn, it's likely recoverable and we don't want to
           * break streaming. We break so that we stop retrying for this client. */
          if (!socket_error_is_ignorable ()) {
            gchar *errormessage = socket_last_error_message ();
            GST_WARNING_OBJECT (sink, "client %p gave error %d (%s)", client,
                socket_last_error_code (), errormessage);
            g_free (errormessage);
            break;
          }
        } else {
          num++;
          client->bytes_sent += ret;
          client->packets_sent++;
          sink->bytes_served += ret;
555
          break;
556
        }
557
      }
558 559 560 561
    }
  }
  g_mutex_unlock (sink->client_lock);

562 563
  GST_LOG_OBJECT (sink, "sent %d bytes to %d (of %d) clients", size, num,
      no_clients);
564 565 566 567

  return GST_FLOW_OK;
}

568
#ifndef G_OS_WIN32
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
static GstFlowReturn
gst_multiudpsink_render_list (GstBaseSink * bsink, GstBufferList * list)
{
  GstMultiUDPSink *sink;
  GList *clients;
  gint ret, size = 0, num = 0, no_clients = 0;
  struct iovec *iov;
  struct msghdr msg = { 0 };

  GstBufferListIterator *it;
  guint gsize;
  GstBuffer *buf;

  sink = GST_MULTIUDPSINK (bsink);

  g_return_val_if_fail (list != NULL, GST_FLOW_ERROR);
585 586 587

  it = gst_buffer_list_iterate (list);
  g_return_val_if_fail (it != NULL, GST_FLOW_ERROR);
588 589 590 591 592 593 594 595 596 597 598 599 600

  while (gst_buffer_list_iterator_next_group (it)) {
    msg.msg_iovlen = 0;
    size = 0;

    if ((gsize = gst_buffer_list_iterator_n_buffers (it)) == 0) {
      goto invalid_list;
    }

    iov = (struct iovec *) g_malloc (gsize * sizeof (struct iovec));
    msg.msg_iov = iov;

    while ((buf = gst_buffer_list_iterator_next (it))) {
601 602 603 604 605
      if (GST_BUFFER_SIZE (buf) > UDP_MAX_SIZE) {
        GST_WARNING ("Attempting to send a UDP packet larger than maximum "
            "size (%d > %d)", GST_BUFFER_SIZE (buf), UDP_MAX_SIZE);
      }

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
      msg.msg_iov[msg.msg_iovlen].iov_len = GST_BUFFER_SIZE (buf);
      msg.msg_iov[msg.msg_iovlen].iov_base = GST_BUFFER_DATA (buf);
      msg.msg_iovlen++;
      size += GST_BUFFER_SIZE (buf);
    }

    sink->bytes_to_serve += size;

    /* grab lock while iterating and sending to clients, this should be
     * fast as UDP never blocks */
    g_mutex_lock (sink->client_lock);
    GST_LOG_OBJECT (bsink, "about to send %d bytes", size);

    for (clients = sink->clients; clients; clients = g_list_next (clients)) {
      GstUDPClient *client;
621
      gint count;
622 623 624 625 626

      client = (GstUDPClient *) clients->data;
      no_clients++;
      GST_LOG_OBJECT (sink, "sending %d bytes to client %p", size, client);

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
      count = sink->send_duplicates ? client->refcount : 1;

      while (count--) {
        while (TRUE) {
          msg.msg_name = (void *) &client->theiraddr;
          msg.msg_namelen = sizeof (client->theiraddr);
          ret = sendmsg (*client->sock, &msg, 0);

          if (ret < 0) {
            if (!socket_error_is_ignorable ()) {
              break;
            }
          } else {
            num++;
            client->bytes_sent += ret;
            client->packets_sent++;
            sink->bytes_served += ret;
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
            break;
          }
        }
      }
    }
    g_mutex_unlock (sink->client_lock);

    g_free (iov);
    msg.msg_iov = NULL;

    GST_LOG_OBJECT (sink, "sent %d bytes to %d (of %d) clients", size, num,
        no_clients);
  }

  gst_buffer_list_iterator_free (it);

  return GST_FLOW_OK;

invalid_list:
  gst_buffer_list_iterator_free (it);
  return GST_FLOW_ERROR;
}
666
#endif
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
static void
gst_multiudpsink_set_clients_string (GstMultiUDPSink * sink,
    const gchar * string)
{
  gchar **clients;
  gint i;

  clients = g_strsplit (string, ",", 0);

  g_mutex_lock (sink->client_lock);
  /* clear all existing clients */
  gst_multiudpsink_clear_internal (sink, FALSE);
  for (i = 0; clients[i]; i++) {
    gchar *host, *p;
    gint port = 0;

    host = clients[i];
    p = strstr (clients[i], ":");
    if (p != NULL) {
      *p = '\0';
      port = atoi (p + 1);
    }
    if (port != 0)
      gst_multiudpsink_add_internal (sink, host, port, FALSE);
  }
  g_mutex_unlock (sink->client_lock);

  g_strfreev (clients);
}

static gchar *
gst_multiudpsink_get_clients_string (GstMultiUDPSink * sink)
{
  GString *str;
  GList *clients;

  str = g_string_new ("");

  g_mutex_lock (sink->client_lock);
  clients = sink->clients;
  while (clients) {
    GstUDPClient *client;
710
    gint count;
711 712 713 714 715

    client = (GstUDPClient *) clients->data;

    clients = g_list_next (clients);

716 717 718 719 720
    count = client->refcount;
    while (count--) {
      g_string_append_printf (str, "%s:%d%s", client->host, client->port,
          (clients || count > 1 ? "," : ""));
    }
721 722 723 724 725 726
  }
  g_mutex_unlock (sink->client_lock);

  return g_string_free (str, FALSE);
}

727 728 729 730 731
static void
gst_multiudpsink_setup_qos_dscp (GstMultiUDPSink * sink)
{
  gint tos;

732 733 734 735
  /* don't touch on -1 */
  if (sink->qos_dscp < 0)
    return;

736 737 738 739 740 741 742 743
  if (sink->sock < 0)
    return;

  GST_DEBUG_OBJECT (sink, "setting TOS to %d", sink->qos_dscp);

  /* Extract and shift 6 bits of DSFIELD */
  tos = (sink->qos_dscp & 0x3f) << 2;

744
  if (setsockopt (sink->sock, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0) {
745 746 747
    gchar *errormessage = socket_last_error_message ();
    GST_ERROR_OBJECT (sink, "could not set TOS: %s", errormessage);
    g_free (errormessage);
748 749
  }
#ifdef IPV6_TCLASS
750 751
  if (setsockopt (sink->sock, IPPROTO_IPV6, IPV6_TCLASS, &tos,
          sizeof (tos)) < 0) {
752 753 754
    gchar *errormessage = socket_last_error_message ();
    GST_ERROR_OBJECT (sink, "could not set TCLASS: %s", errormessage);
    g_free (errormessage);
755 756 757 758
  }
#endif
}

759 760 761 762 763 764 765 766 767
static void
gst_multiudpsink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstMultiUDPSink *udpsink;

  udpsink = GST_MULTIUDPSINK (object);

  switch (prop_id) {
768
    case PROP_SOCKFD:
769 770 771
      if (udpsink->sockfd >= 0 && udpsink->sockfd != udpsink->sock &&
          udpsink->closefd)
        CLOSE_SOCKET (udpsink->sockfd);
772 773 774 775 776 777
      udpsink->sockfd = g_value_get_int (value);
      GST_DEBUG_OBJECT (udpsink, "setting SOCKFD to %d", udpsink->sockfd);
      break;
    case PROP_CLOSEFD:
      udpsink->closefd = g_value_get_boolean (value);
      break;
778 779 780
    case PROP_CLIENTS:
      gst_multiudpsink_set_clients_string (udpsink, g_value_get_string (value));
      break;
781 782 783
    case PROP_AUTO_MULTICAST:
      udpsink->auto_multicast = g_value_get_boolean (value);
      break;
784 785 786
    case PROP_TTL:
      udpsink->ttl = g_value_get_int (value);
      break;
787 788 789
    case PROP_TTL_MC:
      udpsink->ttl_mc = g_value_get_int (value);
      break;
790 791 792
    case PROP_LOOP:
      udpsink->loop = g_value_get_boolean (value);
      break;
793
    case PROP_QOS_DSCP:
794
      udpsink->qos_dscp = g_value_get_int (value);
795 796
      gst_multiudpsink_setup_qos_dscp (udpsink);
      break;
797 798 799
    case PROP_SEND_DUPLICATES:
      udpsink->send_duplicates = g_value_get_boolean (value);
      break;
800 801 802
    case PROP_BUFFER_SIZE:
      udpsink->buffer_size = g_value_get_int (value);
      break;
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_multiudpsink_get_property (GObject * object, guint prop_id, GValue * value,
    GParamSpec * pspec)
{
  GstMultiUDPSink *udpsink;

  udpsink = GST_MULTIUDPSINK (object);

  switch (prop_id) {
818 819 820 821 822 823
    case PROP_BYTES_TO_SERVE:
      g_value_set_uint64 (value, udpsink->bytes_to_serve);
      break;
    case PROP_BYTES_SERVED:
      g_value_set_uint64 (value, udpsink->bytes_served);
      break;
824 825 826 827 828 829 830 831 832
    case PROP_SOCKFD:
      g_value_set_int (value, udpsink->sockfd);
      break;
    case PROP_CLOSEFD:
      g_value_set_boolean (value, udpsink->closefd);
      break;
    case PROP_SOCK:
      g_value_set_int (value, udpsink->sock);
      break;
833 834 835 836
    case PROP_CLIENTS:
      g_value_take_string (value,
          gst_multiudpsink_get_clients_string (udpsink));
      break;
837 838 839
    case PROP_AUTO_MULTICAST:
      g_value_set_boolean (value, udpsink->auto_multicast);
      break;
840 841 842
    case PROP_TTL:
      g_value_set_int (value, udpsink->ttl);
      break;
843 844 845
    case PROP_TTL_MC:
      g_value_set_int (value, udpsink->ttl_mc);
      break;
846 847 848
    case PROP_LOOP:
      g_value_set_boolean (value, udpsink->loop);
      break;
849 850 851
    case PROP_QOS_DSCP:
      g_value_set_int (value, udpsink->qos_dscp);
      break;
852 853 854
    case PROP_SEND_DUPLICATES:
      g_value_set_boolean (value, udpsink->send_duplicates);
      break;
855 856 857
    case PROP_BUFFER_SIZE:
      g_value_set_int (value, udpsink->buffer_size);
      break;
858 859 860 861 862 863
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
static gboolean
gst_multiudpsink_configure_client (GstMultiUDPSink * sink,
    GstUDPClient * client)
{
  GST_DEBUG_OBJECT (sink, "configuring client %p", client);

  if (gst_udp_is_multicast (&client->theiraddr)) {
    GST_DEBUG_OBJECT (sink, "we have a multicast client %p", client);
    if (sink->auto_multicast) {
      GST_DEBUG_OBJECT (sink, "autojoining group");
      if (gst_udp_join_group (*(client->sock), &client->theiraddr, NULL)
          != 0)
        goto join_group_failed;
    }
    GST_DEBUG_OBJECT (sink, "setting loop to %d", sink->loop);
879
    if (gst_udp_set_loop (sink->sock, sink->ss_family, sink->loop) != 0)
880 881
      goto loop_failed;
    GST_DEBUG_OBJECT (sink, "setting ttl to %d", sink->ttl_mc);
882
    if (gst_udp_set_ttl (sink->sock, sink->ss_family, sink->ttl_mc, TRUE) != 0)
883 884 885
      goto ttl_failed;
  } else {
    GST_DEBUG_OBJECT (sink, "setting unicast ttl to %d", sink->ttl);
886
    if (gst_udp_set_ttl (sink->sock, sink->ss_family, sink->ttl, FALSE) != 0)
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
      goto ttl_failed;
  }
  return TRUE;

  /* ERRORS */
join_group_failed:
  {
    gchar *errormessage = socket_last_error_message ();
    int errorcode = socket_last_error_code ();
    CLOSE_IF_REQUESTED (sink);
    GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
        ("Could not join multicast group (%d): %s", errorcode, errormessage));
    g_free (errormessage);
    return FALSE;
  }
ttl_failed:
  {
    gchar *errormessage = socket_last_error_message ();
    int errorcode = socket_last_error_code ();
    CLOSE_IF_REQUESTED (sink);
    GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
        ("Could not set TTL socket option (%d): %s", errorcode, errormessage));
    g_free (errormessage);
    return FALSE;
  }
loop_failed:
  {
    gchar *errormessage = socket_last_error_message ();
    int errorcode = socket_last_error_code ();
    CLOSE_IF_REQUESTED (sink);
    GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
        ("Could not set loopback socket option (%d): %s",
            errorcode, errormessage));
    g_free (errormessage);
    return FALSE;
  }
}

925 926 927 928 929
/* create a socket for sending to remote machine */
static gboolean
gst_multiudpsink_init_send (GstMultiUDPSink * sink)
{
  guint bc_val;
930 931
  GList *clients;
  GstUDPClient *client;
932
  int sndsize, ret;
933
  socklen_t len;
934

935
  if (sink->sockfd == -1) {
936
    GST_DEBUG_OBJECT (sink, "creating sockets");
937
    /* create sender socket try IP6, fall back to IP4 */
938
    sink->ss_family = AF_INET6;
939
    if ((sink->sock = socket (AF_INET6, SOCK_DGRAM, 0)) == -1) {
940
      sink->ss_family = AF_INET;
941 942
      if ((sink->sock = socket (AF_INET, SOCK_DGRAM, 0)) == -1)
        goto no_socket;
943
    }
944

945
    GST_DEBUG_OBJECT (sink, "have socket");
946 947
    sink->externalfd = FALSE;
  } else {
948 949
    struct sockaddr_storage myaddr;

950
    GST_DEBUG_OBJECT (sink, "using configured socket");
951 952 953 954 955 956
    /* we use the configured socket, try to get some info about it */
    len = sizeof (myaddr);
    if (getsockname (sink->sockfd, (struct sockaddr *) &myaddr, &len) < 0)
      goto getsockname_error;

    sink->ss_family = myaddr.ss_family;
957 958 959 960
    /* we use the configured socket */
    sink->sock = sink->sockfd;
    sink->externalfd = TRUE;
  }
961

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
  len = sizeof (sndsize);
  if (sink->buffer_size != 0) {
    sndsize = sink->buffer_size;

    GST_DEBUG_OBJECT (sink, "setting udp buffer of %d bytes", sndsize);
    /* set buffer size, Note that on Linux this is typically limited to a
     * maximum of around 100K. Also a minimum of 128 bytes is required on
     * Linux. */
    ret =
        setsockopt (sink->sockfd, SOL_SOCKET, SO_SNDBUF, (void *) &sndsize,
        len);
    if (ret != 0) {
      GST_ELEMENT_WARNING (sink, RESOURCE, SETTINGS, (NULL),
          ("Could not create a buffer of requested %d bytes, %d: %s (%d)",
              sndsize, ret, g_strerror (errno), errno));
    }
  }

  /* read the value of the receive buffer. Note that on linux this returns 2x the
   * value we set because the kernel allocates extra memory for metadata.
   * The default on Linux is about 100K (which is about 50K without metadata) */
  ret =
      getsockopt (sink->sockfd, SOL_SOCKET, SO_SNDBUF, (void *) &sndsize, &len);
  if (ret == 0)
    GST_DEBUG_OBJECT (sink, "have udp buffer of %d bytes", sndsize);
  else
    GST_DEBUG_OBJECT (sink, "could not get udp buffer size");


991
  bc_val = 1;
992 993
  if (setsockopt (sink->sock, SOL_SOCKET, SO_BROADCAST, &bc_val,
          sizeof (bc_val)) < 0)
994 995
    goto no_broadcast;

996 997 998
  sink->bytes_to_serve = 0;
  sink->bytes_served = 0;

999
  gst_multiudpsink_setup_qos_dscp (sink);
1000

1001 1002
  /* look for multicast clients and join multicast groups appropriately
     set also ttl and multicast loopback delivery appropriately  */
1003 1004
  for (clients = sink->clients; clients; clients = g_list_next (clients)) {
    client = (GstUDPClient *) clients->data;
1005 1006 1007

    if (!gst_multiudpsink_configure_client (sink, client))
      return FALSE;
1008 1009
  }
  return TRUE;
1010

1011 1012 1013
  /* ERRORS */
no_socket:
  {
1014 1015
    gchar *errormessage = socket_last_error_message ();
    int errorcode = socket_last_error_code ();
1016
    GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
1017 1018
        ("Could not create socket (%d): %s", errorcode, errormessage));
    g_free (errormessage);
1019 1020
    return FALSE;
  }
1021 1022 1023 1024 1025 1026 1027 1028 1029
getsockname_error:
  {
    gchar *errormessage = socket_last_error_message ();
    int errorcode = socket_last_error_code ();
    GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, (NULL),
        ("Could not getsockname (%d): %s", errorcode, errormessage));
    g_free (errormessage);
    return FALSE;
  }
1030 1031
no_broadcast:
  {
1032 1033
    gchar *errormessage = socket_last_error_message ();
    int errorcode = socket_last_error_code ();
1034
    CLOSE_IF_REQUESTED (sink);
1035
    GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL),
1036 1037 1038
        ("Could not set broadcast socket option (%d): %s",
            errorcode, errormessage));
    g_free (errormessage);
1039 1040 1041 1042 1043 1044 1045
    return FALSE;
  }
}

static void
gst_multiudpsink_close (GstMultiUDPSink * sink)
{
1046
  CLOSE_IF_REQUESTED (sink);
1047 1048
}

1049 1050 1051
static void
gst_multiudpsink_add_internal (GstMultiUDPSink * sink, const gchar * host,
    gint port, gboolean lock)
1052 1053
{
  GstUDPClient *client;
1054
  GstUDPClient udpclient;
1055
  GTimeVal now;
1056 1057 1058 1059
  GList *find;

  udpclient.host = (gchar *) host;
  udpclient.port = port;
1060

1061
  GST_DEBUG_OBJECT (sink, "adding client on host %s, port %d", host, port);
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  if (lock)
    g_mutex_lock (sink->client_lock);

  find = g_list_find_custom (sink->clients, &udpclient,
      (GCompareFunc) client_compare);
  if (find) {
    client = (GstUDPClient *) find->data;

    GST_DEBUG_OBJECT (sink, "found %d existing clients with host %s, port %d",
        client->refcount, host, port);
    client->refcount++;
  } else {
    client = create_client (sink, host, port);
1076

1077
    client->sock = &sink->sock;
1078

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    if (gst_udp_get_addr (host, port, &client->theiraddr) < 0)
      goto getaddrinfo_error;

    g_get_current_time (&now);
    client->connect_time = GST_TIMEVAL_TO_TIME (now);

    if (*client->sock > 0) {
      gst_multiudpsink_configure_client (sink, client);
    }

    GST_DEBUG_OBJECT (sink, "add client with host %s, port %d", host, port);
    sink->clients = g_list_prepend (sink->clients, client);
1091 1092
  }

1093 1094
  if (lock)
    g_mutex_unlock (sink->client_lock);
1095

1096 1097 1098
  g_signal_emit (G_OBJECT (sink),<