2 * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3 * Copyright (C) <2004> Thomas Vander Stichele <thomas at apestaart dot org>
4 * Copyright (C) 2006 Wim Taymans <wim at fluendo dot com>
5 * Copyright (C) <2011> Collabora Ltd.
6 * Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
25 * SECTION:element-multisocketsink
26 * @see_also: tcpserversink
28 * This plugin writes incoming data to a set of file descriptors. The
29 * file descriptors can be added to multisocketsink by emitting the #GstMultiHandleSink::add signal.
30 * For each descriptor added, the #GstMultiHandleSink::client-added signal will be called.
32 * As of version 0.10.8, a client can also be added with the #GstMultiHandleSink::add-full signal
33 * that allows for more control over what and how much data a client
36 * Clients can be removed from multisocketsink by emitting the #GstMultiHandleSink::remove signal. For
37 * each descriptor removed, the #GstMultiHandleSink::client-removed signal will be called. The
38 * #GstMultiHandleSink::client-removed signal can also be fired when multisocketsink decides that a
39 * client is not active anymore or, depending on the value of the
40 * #GstMultiHandleSink:recover-policy property, if the client is reading too slowly.
41 * In all cases, multisocketsink will never close a file descriptor itself.
42 * The user of multisocketsink is responsible for closing all file descriptors.
43 * This can for example be done in response to the #GstMultiHandleSink::client-fd-removed signal.
44 * Note that multisocketsink still has a reference to the file descriptor when the
45 * #GstMultiHandleSink::client-removed signal is emitted, so that "get-stats" can be performed on
46 * the descriptor; it is therefore not safe to close the file descriptor in
47 * the #GstMultiHandleSink::client-removed signal handler, and you should use the
48 * #GstMultiHandleSink::client-fd-removed signal to safely close the fd.
50 * Multisocketsink internally keeps a queue of the incoming buffers and uses a
51 * separate thread to send the buffers to the clients. This ensures that no
52 * client write can block the pipeline and that clients can read with different
55 * When adding a client to multisocketsink, the #GstMultiHandleSink:sync-method property will define
56 * which buffer in the queued buffers will be sent first to the client. Clients
57 * can be sent the most recent buffer (which might not be decodable by the
58 * client if it is not a keyframe), the next keyframe received in
59 * multisocketsink (which can take some time depending on the keyframe rate), or the
60 * last received keyframe (which will cause a simple burst-on-connect).
61 * Multisocketsink will always keep at least one keyframe in its internal buffers
62 * when the sync-mode is set to latest-keyframe.
64 * As of version 0.10.8, there are additional values for the #GstMultiHandleSink:sync-method
65 * property to allow finer control over burst-on-connect behaviour. By selecting
66 * the 'burst' method a minimum burst size can be chosen, 'burst-keyframe'
67 * additionally requires that the burst begin with a keyframe, and
68 * 'burst-with-keyframe' attempts to burst beginning with a keyframe, but will
69 * prefer a minimum burst size even if it requires not starting with a keyframe.
71 * Multisocketsink can be instructed to keep at least a minimum amount of data
72 * expressed in time or byte units in its internal queues with the
73 * #GstMultiHandleSink:time-min and #GstMultiHandleSink:bytes-min properties respectively.
74 * These properties are useful if the application adds clients with the
75 * #GstMultiHandleSink::add-full signal to make sure that a burst connect can
76 * actually be honored.
78 * When streaming data, clients are allowed to read at a different rate than
79 * the rate at which multisocketsink receives data. If the client is reading too
80 * fast, no data will be send to the client until multisocketsink receives more
81 * data. If the client, however, reads too slowly, data for that client will be
82 * queued up in multisocketsink. Two properties control the amount of data
83 * (buffers) that is queued in multisocketsink: #GstMultiHandleSink:buffers-max and
84 * #GstMultiHandleSink:buffers-soft-max. A client that falls behind by
85 * #GstMultiHandleSink:buffers-max is removed from multisocketsink forcibly.
87 * A client with a lag of at least #GstMultiHandleSink:buffers-soft-max enters the recovery
88 * procedure which is controlled with the #GstMultiHandleSink:recover-policy property.
89 * A recover policy of NONE will do nothing, RESYNC_LATEST will send the most recently
90 * received buffer as the next buffer for the client, RESYNC_SOFT_LIMIT
91 * positions the client to the soft limit in the buffer queue and
92 * RESYNC_KEYFRAME positions the client at the most recent keyframe in the
95 * multisocketsink will by default synchronize on the clock before serving the
96 * buffers to the clients. This behaviour can be disabled by setting the sync
97 * property to FALSE. Multisocketsink will by default not do QoS and will never
100 * Last reviewed on 2006-09-12 (0.10.10)
107 #include <gst/gst-i18n-plugin.h>
109 #include "gstmultisocketsink.h"
110 #include "gsttcp-marshal.h"
113 #include <netinet/in.h>
116 #define NOT_IMPLEMENTED 0
118 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
121 GST_STATIC_CAPS_ANY);
123 GST_DEBUG_CATEGORY_STATIC (multisocketsink_debug);
124 #define GST_CAT_DEFAULT (multisocketsink_debug)
126 /* MultiHandleSink signals and args */
139 SIGNAL_CLIENT_REMOVED,
140 SIGNAL_CLIENT_SOCKET_REMOVED,
146 /* this is really arbitrarily chosen */
147 #define DEFAULT_MODE 1
148 #define DEFAULT_BUFFERS_MAX -1
149 #define DEFAULT_BUFFERS_SOFT_MAX -1
150 #define DEFAULT_TIME_MIN -1
151 #define DEFAULT_BYTES_MIN -1
152 #define DEFAULT_BUFFERS_MIN -1
153 #define DEFAULT_UNIT_TYPE GST_FORMAT_BUFFERS
154 #define DEFAULT_UNITS_MAX -1
155 #define DEFAULT_UNITS_SOFT_MAX -1
156 #define DEFAULT_RECOVER_POLICY GST_RECOVER_POLICY_NONE
157 #define DEFAULT_TIMEOUT 0
158 #define DEFAULT_SYNC_METHOD GST_SYNC_METHOD_LATEST
160 #define DEFAULT_BURST_FORMAT GST_FORMAT_UNDEFINED
161 #define DEFAULT_BURST_VALUE 0
163 #define DEFAULT_QOS_DSCP -1
164 #define DEFAULT_HANDLE_READ TRUE
166 #define DEFAULT_RESEND_STREAMHEADER TRUE
181 PROP_BUFFERS_SOFT_MAX,
200 PROP_RESEND_STREAMHEADER,
207 #define GST_TYPE_RECOVER_POLICY (gst_multi_handle_sink_recover_policy_get_type())
209 gst_multi_handle_sink_recover_policy_get_type (void)
211 static GType recover_policy_type = 0;
212 static const GEnumValue recover_policy[] = {
213 {GST_RECOVER_POLICY_NONE,
214 "Do not try to recover", "none"},
215 {GST_RECOVER_POLICY_RESYNC_LATEST,
216 "Resync client to latest buffer", "latest"},
217 {GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT,
218 "Resync client to soft limit", "soft-limit"},
219 {GST_RECOVER_POLICY_RESYNC_KEYFRAME,
220 "Resync client to most recent keyframe", "keyframe"},
224 if (!recover_policy_type) {
225 recover_policy_type =
226 g_enum_register_static ("GstMultiHandleSinkRecoverPolicy",
229 return recover_policy_type;
232 #define GST_TYPE_SYNC_METHOD (gst_multi_handle_sink_sync_method_get_type())
234 gst_multi_handle_sink_sync_method_get_type (void)
236 static GType sync_method_type = 0;
237 static const GEnumValue sync_method[] = {
238 {GST_SYNC_METHOD_LATEST,
239 "Serve starting from the latest buffer", "latest"},
240 {GST_SYNC_METHOD_NEXT_KEYFRAME,
241 "Serve starting from the next keyframe", "next-keyframe"},
242 {GST_SYNC_METHOD_LATEST_KEYFRAME,
243 "Serve everything since the latest keyframe (burst)",
245 {GST_SYNC_METHOD_BURST, "Serve burst-value data to client", "burst"},
246 {GST_SYNC_METHOD_BURST_KEYFRAME,
247 "Serve burst-value data starting on a keyframe",
249 {GST_SYNC_METHOD_BURST_WITH_KEYFRAME,
250 "Serve burst-value data preferably starting on a keyframe",
251 "burst-with-keyframe"},
255 if (!sync_method_type) {
257 g_enum_register_static ("GstMultiHandleSinkSyncMethod", sync_method);
259 return sync_method_type;
262 #define GST_TYPE_CLIENT_STATUS (gst_multi_handle_sink_client_status_get_type())
264 gst_multi_handle_sink_client_status_get_type (void)
266 static GType client_status_type = 0;
267 static const GEnumValue client_status[] = {
268 {GST_CLIENT_STATUS_OK, "ok", "ok"},
269 {GST_CLIENT_STATUS_CLOSED, "Closed", "closed"},
270 {GST_CLIENT_STATUS_REMOVED, "Removed", "removed"},
271 {GST_CLIENT_STATUS_SLOW, "Too slow", "slow"},
272 {GST_CLIENT_STATUS_ERROR, "Error", "error"},
273 {GST_CLIENT_STATUS_DUPLICATE, "Duplicate", "duplicate"},
274 {GST_CLIENT_STATUS_FLUSHING, "Flushing", "flushing"},
278 if (!client_status_type) {
280 g_enum_register_static ("GstMultiHandleSinkClientStatus",
283 return client_status_type;
286 static void gst_multi_handle_sink_finalize (GObject * object);
288 static void gst_multi_handle_sink_remove_client_link (GstMultiHandleSink * sink,
290 static gboolean gst_multi_handle_sink_socket_condition (GSocket * socket,
291 GIOCondition condition, GstMultiHandleSink * sink);
293 static GstFlowReturn gst_multi_handle_sink_render (GstBaseSink * bsink,
295 static gboolean gst_multi_handle_sink_unlock (GstBaseSink * bsink);
296 static gboolean gst_multi_handle_sink_unlock_stop (GstBaseSink * bsink);
297 static GstStateChangeReturn gst_multi_handle_sink_change_state (GstElement *
298 element, GstStateChange transition);
300 static void gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
301 const GValue * value, GParamSpec * pspec);
302 static void gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
303 GValue * value, GParamSpec * pspec);
305 #define gst_multi_handle_sink_parent_class parent_class
306 G_DEFINE_TYPE (GstMultiHandleSink, gst_multi_handle_sink, GST_TYPE_BASE_SINK);
308 static guint gst_multi_handle_sink_signals[LAST_SIGNAL] = { 0 };
311 gst_multi_handle_sink_class_init (GstMultiHandleSinkClass * klass)
313 GObjectClass *gobject_class;
314 GstElementClass *gstelement_class;
315 GstBaseSinkClass *gstbasesink_class;
317 gobject_class = (GObjectClass *) klass;
318 gstelement_class = (GstElementClass *) klass;
319 gstbasesink_class = (GstBaseSinkClass *) klass;
321 gobject_class->set_property = gst_multi_handle_sink_set_property;
322 gobject_class->get_property = gst_multi_handle_sink_get_property;
323 gobject_class->finalize = gst_multi_handle_sink_finalize;
325 g_object_class_install_property (gobject_class, PROP_BUFFERS_MAX,
326 g_param_spec_int ("buffers-max", "Buffers max",
327 "max number of buffers to queue for a client (-1 = no limit)", -1,
328 G_MAXINT, DEFAULT_BUFFERS_MAX,
329 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
330 g_object_class_install_property (gobject_class, PROP_BUFFERS_SOFT_MAX,
331 g_param_spec_int ("buffers-soft-max", "Buffers soft max",
332 "Recover client when going over this limit (-1 = no limit)", -1,
333 G_MAXINT, DEFAULT_BUFFERS_SOFT_MAX,
334 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
336 g_object_class_install_property (gobject_class, PROP_BYTES_MIN,
337 g_param_spec_int ("bytes-min", "Bytes min",
338 "min number of bytes to queue (-1 = as little as possible)", -1,
339 G_MAXINT, DEFAULT_BYTES_MIN,
340 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341 g_object_class_install_property (gobject_class, PROP_TIME_MIN,
342 g_param_spec_int64 ("time-min", "Time min",
343 "min number of time to queue (-1 = as little as possible)", -1,
344 G_MAXINT64, DEFAULT_TIME_MIN,
345 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346 g_object_class_install_property (gobject_class, PROP_BUFFERS_MIN,
347 g_param_spec_int ("buffers-min", "Buffers min",
348 "min number of buffers to queue (-1 = as few as possible)", -1,
349 G_MAXINT, DEFAULT_BUFFERS_MIN,
350 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352 g_object_class_install_property (gobject_class, PROP_UNIT_TYPE,
353 g_param_spec_enum ("unit-type", "Units type",
354 "The unit to measure the max/soft-max/queued properties",
355 GST_TYPE_FORMAT, DEFAULT_UNIT_TYPE,
356 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
357 g_object_class_install_property (gobject_class, PROP_UNITS_MAX,
358 g_param_spec_int64 ("units-max", "Units max",
359 "max number of units to queue (-1 = no limit)", -1, G_MAXINT64,
360 DEFAULT_UNITS_MAX, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
361 g_object_class_install_property (gobject_class, PROP_UNITS_SOFT_MAX,
362 g_param_spec_int64 ("units-soft-max", "Units soft max",
363 "Recover client when going over this limit (-1 = no limit)", -1,
364 G_MAXINT64, DEFAULT_UNITS_SOFT_MAX,
365 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
367 g_object_class_install_property (gobject_class, PROP_BUFFERS_QUEUED,
368 g_param_spec_uint ("buffers-queued", "Buffers queued",
369 "Number of buffers currently queued", 0, G_MAXUINT, 0,
370 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
372 g_object_class_install_property (gobject_class, PROP_BYTES_QUEUED,
373 g_param_spec_uint ("bytes-queued", "Bytes queued",
374 "Number of bytes currently queued", 0, G_MAXUINT, 0,
375 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
376 g_object_class_install_property (gobject_class, PROP_TIME_QUEUED,
377 g_param_spec_uint64 ("time-queued", "Time queued",
378 "Number of time currently queued", 0, G_MAXUINT64, 0,
379 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
382 g_object_class_install_property (gobject_class, PROP_RECOVER_POLICY,
383 g_param_spec_enum ("recover-policy", "Recover Policy",
384 "How to recover when client reaches the soft max",
385 GST_TYPE_RECOVER_POLICY, DEFAULT_RECOVER_POLICY,
386 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
387 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
388 g_param_spec_uint64 ("timeout", "Timeout",
389 "Maximum inactivity timeout in nanoseconds for a client (0 = no limit)",
390 0, G_MAXUINT64, DEFAULT_TIMEOUT,
391 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392 g_object_class_install_property (gobject_class, PROP_SYNC_METHOD,
393 g_param_spec_enum ("sync-method", "Sync Method",
394 "How to sync new clients to the stream", GST_TYPE_SYNC_METHOD,
395 DEFAULT_SYNC_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
396 g_object_class_install_property (gobject_class, PROP_BYTES_TO_SERVE,
397 g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
398 "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
399 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
400 g_object_class_install_property (gobject_class, PROP_BYTES_SERVED,
401 g_param_spec_uint64 ("bytes-served", "Bytes served",
402 "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
403 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
405 g_object_class_install_property (gobject_class, PROP_BURST_FORMAT,
406 g_param_spec_enum ("burst-format", "Burst format",
407 "The format of the burst units (when sync-method is burst[[-with]-keyframe])",
408 GST_TYPE_FORMAT, DEFAULT_BURST_FORMAT,
409 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
410 g_object_class_install_property (gobject_class, PROP_BURST_VALUE,
411 g_param_spec_uint64 ("burst-value", "Burst value",
412 "The amount of burst expressed in burst-unit", 0, G_MAXUINT64,
413 DEFAULT_BURST_VALUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
415 g_object_class_install_property (gobject_class, PROP_QOS_DSCP,
416 g_param_spec_int ("qos-dscp", "QoS diff srv code point",
417 "Quality of Service, differentiated services code point (-1 default)",
418 -1, 63, DEFAULT_QOS_DSCP,
419 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
422 * GstMultiHandleSink::handle-read
424 * Handle read requests from clients and discard the data.
428 g_object_class_install_property (gobject_class, PROP_HANDLE_READ,
429 g_param_spec_boolean ("handle-read", "Handle Read",
430 "Handle client reads and discard the data",
431 DEFAULT_HANDLE_READ, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
433 * GstMultiHandleSink::resend-streamheader
435 * Resend the streamheaders to existing clients when they change.
439 g_object_class_install_property (gobject_class, PROP_RESEND_STREAMHEADER,
440 g_param_spec_boolean ("resend-streamheader", "Resend streamheader",
441 "Resend the streamheader if it changes in the caps",
442 DEFAULT_RESEND_STREAMHEADER,
443 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
445 g_object_class_install_property (gobject_class, PROP_NUM_SOCKETS,
446 g_param_spec_uint ("num-sockets", "Number of sockets",
447 "The current number of client sockets",
448 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
451 * GstMultiHandleSink::add:
452 * @gstmultisocketsink: the multisocketsink element to emit this signal on
453 * @socket: the socket to add to multisocketsink
455 * Hand the given open socket to multisocketsink to write to.
457 gst_multi_handle_sink_signals[SIGNAL_ADD] =
458 g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
459 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
460 G_STRUCT_OFFSET (GstMultiHandleSinkClass, add), NULL, NULL,
461 g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_SOCKET);
463 * GstMultiHandleSink::add-full:
464 * @gstmultisocketsink: the multisocketsink element to emit this signal on
465 * @socket: the socket to add to multisocketsink
466 * @sync: the sync method to use
467 * @format_min: the format of @value_min
468 * @value_min: the minimum amount of data to burst expressed in
470 * @format_max: the format of @value_max
471 * @value_max: the maximum amount of data to burst expressed in
474 * Hand the given open socket to multisocketsink to write to and
475 * specify the burst parameters for the new connection.
477 gst_multi_handle_sink_signals[SIGNAL_ADD_BURST] =
478 g_signal_new ("add-full", G_TYPE_FROM_CLASS (klass),
479 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
480 G_STRUCT_OFFSET (GstMultiHandleSinkClass, add_full), NULL, NULL,
481 gst_tcp_marshal_VOID__OBJECT_ENUM_ENUM_UINT64_ENUM_UINT64, G_TYPE_NONE, 6,
482 G_TYPE_SOCKET, GST_TYPE_SYNC_METHOD, GST_TYPE_FORMAT, G_TYPE_UINT64,
483 GST_TYPE_FORMAT, G_TYPE_UINT64);
485 * GstMultiHandleSink::remove:
486 * @gstmultisocketsink: the multisocketsink element to emit this signal on
487 * @socket: the socket to remove from multisocketsink
489 * Remove the given open socket from multisocketsink.
491 gst_multi_handle_sink_signals[SIGNAL_REMOVE] =
492 g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
493 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
494 G_STRUCT_OFFSET (GstMultiHandleSinkClass, remove), NULL, NULL,
495 g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_SOCKET);
497 * GstMultiHandleSink::remove-flush:
498 * @gstmultisocketsink: the multisocketsink element to emit this signal on
499 * @socket: the socket to remove from multisocketsink
501 * Remove the given open socket from multisocketsink after flushing all
502 * the pending data to the socket.
504 gst_multi_handle_sink_signals[SIGNAL_REMOVE_FLUSH] =
505 g_signal_new ("remove-flush", G_TYPE_FROM_CLASS (klass),
506 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
507 G_STRUCT_OFFSET (GstMultiHandleSinkClass, remove_flush), NULL, NULL,
508 g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_SOCKET);
510 * GstMultiHandleSink::clear:
511 * @gstmultisocketsink: the multisocketsink element to emit this signal on
513 * Remove all sockets from multisocketsink. Since multisocketsink did not
514 * open sockets itself, it does not explicitly close the sockets. The application
515 * should do so by connecting to the client-socket-removed callback.
517 gst_multi_handle_sink_signals[SIGNAL_CLEAR] =
518 g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
519 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
520 G_STRUCT_OFFSET (GstMultiHandleSinkClass, clear), NULL, NULL,
521 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
524 * GstMultiHandleSink::get-stats:
525 * @gstmultisocketsink: the multisocketsink element to emit this signal on
526 * @socket: the socket to get stats of from multisocketsink
528 * Get statistics about @socket. This function returns a GstStructure.
530 * Returns: a GstStructure with the statistics. The structure contains
531 * values that represent: total number of bytes sent, time
532 * when the client was added, time when the client was
533 * disconnected/removed, time the client is/was active, last activity
534 * time (in epoch seconds), number of buffers dropped.
535 * All times are expressed in nanoseconds (GstClockTime).
537 gst_multi_handle_sink_signals[SIGNAL_GET_STATS] =
538 g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
539 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
540 G_STRUCT_OFFSET (GstMultiHandleSinkClass, get_stats), NULL, NULL,
541 gst_tcp_marshal_BOXED__OBJECT, GST_TYPE_STRUCTURE, 1, G_TYPE_SOCKET);
544 * GstMultiHandleSink::client-added:
545 * @gstmultisocketsink: the multisocketsink element that emitted this signal
546 * @socket: the socket that was added to multisocketsink
548 * The given socket was added to multisocketsink. This signal will
549 * be emitted from the streaming thread so application should be prepared
552 gst_multi_handle_sink_signals[SIGNAL_CLIENT_ADDED] =
553 g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
554 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiHandleSinkClass,
555 client_added), NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
556 G_TYPE_NONE, 1, G_TYPE_OBJECT);
558 * GstMultiHandleSink::client-removed:
559 * @gstmultisocketsink: the multisocketsink element that emitted this signal
560 * @socket: the socket that is to be removed from multisocketsink
561 * @status: the reason why the client was removed
563 * The given socket is about to be removed from multisocketsink. This
564 * signal will be emitted from the streaming thread so applications should
565 * be prepared for that.
567 * @gstmultisocketsink still holds a handle to @socket so it is possible to call
568 * the get-stats signal from this callback. For the same reason it is
569 * not safe to close() and reuse @socket in this callback.
571 gst_multi_handle_sink_signals[SIGNAL_CLIENT_REMOVED] =
572 g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
573 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiHandleSinkClass,
574 client_removed), NULL, NULL, gst_tcp_marshal_VOID__OBJECT_ENUM,
575 G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CLIENT_STATUS);
577 * GstMultiHandleSink::client-socket-removed:
578 * @gstmultisocketsink: the multisocketsink element that emitted this signal
579 * @socket: the socket that was removed from multisocketsink
581 * The given socket was removed from multisocketsink. This signal will
582 * be emitted from the streaming thread so applications should be prepared
585 * In this callback, @gstmultisocketsink has removed all the information
586 * associated with @socket and it is therefore not possible to call get-stats
587 * with @socket. It is however safe to close() and reuse @fd in the callback.
591 gst_multi_handle_sink_signals[SIGNAL_CLIENT_SOCKET_REMOVED] =
592 g_signal_new ("client-socket-removed", G_TYPE_FROM_CLASS (klass),
593 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiHandleSinkClass,
594 client_socket_removed), NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
595 G_TYPE_NONE, 1, G_TYPE_SOCKET);
597 gst_element_class_add_pad_template (gstelement_class,
598 gst_static_pad_template_get (&sinktemplate));
600 gst_element_class_set_details_simple (gstelement_class,
601 "Multi socket sink", "Sink/Network",
602 "Send data to multiple sockets",
603 "Thomas Vander Stichele <thomas at apestaart dot org>, "
604 "Wim Taymans <wim@fluendo.com>, "
605 "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
607 gstelement_class->change_state =
608 GST_DEBUG_FUNCPTR (gst_multi_handle_sink_change_state);
610 gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_render);
611 gstbasesink_class->unlock = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_unlock);
612 gstbasesink_class->unlock_stop =
613 GST_DEBUG_FUNCPTR (gst_multi_handle_sink_unlock_stop);
615 klass->add = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_add);
616 klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_add_full);
617 klass->remove = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_remove);
618 klass->remove_flush = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_remove_flush);
619 klass->clear = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_clear);
620 klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_get_stats);
622 GST_DEBUG_CATEGORY_INIT (multisocketsink_debug, "multisocketsink", 0,
623 "Multi socket sink");
627 gst_multi_handle_sink_init (GstMultiHandleSink * this)
629 GST_OBJECT_FLAG_UNSET (this, GST_MULTI_HANDLE_SINK_OPEN);
631 CLIENTS_LOCK_INIT (this);
632 this->clients = NULL;
633 this->socket_hash = g_hash_table_new (g_direct_hash, g_int_equal);
635 this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
636 this->unit_type = DEFAULT_UNIT_TYPE;
637 this->units_max = DEFAULT_UNITS_MAX;
638 this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
639 this->time_min = DEFAULT_TIME_MIN;
640 this->bytes_min = DEFAULT_BYTES_MIN;
641 this->buffers_min = DEFAULT_BUFFERS_MIN;
642 this->recover_policy = DEFAULT_RECOVER_POLICY;
644 this->timeout = DEFAULT_TIMEOUT;
645 this->def_sync_method = DEFAULT_SYNC_METHOD;
646 this->def_burst_format = DEFAULT_BURST_FORMAT;
647 this->def_burst_value = DEFAULT_BURST_VALUE;
649 this->qos_dscp = DEFAULT_QOS_DSCP;
650 this->handle_read = DEFAULT_HANDLE_READ;
652 this->resend_streamheader = DEFAULT_RESEND_STREAMHEADER;
654 this->header_flags = 0;
655 this->cancellable = g_cancellable_new ();
659 gst_multi_handle_sink_finalize (GObject * object)
661 GstMultiHandleSink *this;
663 this = GST_MULTI_HANDLE_SINK (object);
665 CLIENTS_LOCK_CLEAR (this);
666 g_hash_table_destroy (this->socket_hash);
667 g_array_free (this->bufqueue, TRUE);
669 if (this->cancellable) {
670 g_object_unref (this->cancellable);
671 this->cancellable = NULL;
674 G_OBJECT_CLASS (parent_class)->finalize (object);
678 setup_dscp_client (GstMultiHandleSink * sink, GstSocketClient * client)
689 struct sockaddr_in6 sa_in6;
690 struct sockaddr_storage sa_stor;
692 socklen_t slen = sizeof (sa);
696 if (sink->qos_dscp < 0)
699 fd = g_socket_get_fd (client->socket);
701 if ((ret = getsockname (fd, &sa.sa, &slen)) < 0) {
702 GST_DEBUG_OBJECT (sink, "could not get sockname: %s", g_strerror (errno));
706 af = sa.sa.sa_family;
708 /* if this is an IPv4-mapped address then do IPv4 QoS */
709 if (af == AF_INET6) {
711 GST_DEBUG_OBJECT (sink, "check IP6 socket");
712 if (IN6_IS_ADDR_V4MAPPED (&(sa.sa_in6.sin6_addr))) {
713 GST_DEBUG_OBJECT (sink, "mapped to IPV4");
718 /* extract and shift 6 bits of the DSCP */
719 tos = (sink->qos_dscp & 0x3f) << 2;
723 ret = setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos));
727 ret = setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos));
732 GST_ERROR_OBJECT (sink, "unsupported AF");
736 GST_DEBUG_OBJECT (sink, "could not set DSCP: %s", g_strerror (errno));
743 setup_dscp (GstMultiHandleSink * sink)
748 for (clients = sink->clients; clients; clients = clients->next) {
749 GstSocketClient *client;
751 client = clients->data;
753 setup_dscp_client (sink, client);
755 CLIENTS_UNLOCK (sink);
758 /* "add-full" signal implementation */
760 gst_multi_handle_sink_add_full (GstMultiHandleSink * sink, GSocket * socket,
761 GstSyncMethod sync_method, GstFormat min_format, guint64 min_value,
762 GstFormat max_format, guint64 max_value)
764 GstSocketClient *client;
768 GST_DEBUG_OBJECT (sink, "[socket %p] adding client, sync_method %d, "
769 "min_format %d, min_value %" G_GUINT64_FORMAT
770 ", max_format %d, max_value %" G_GUINT64_FORMAT, socket,
771 sync_method, min_format, min_value, max_format, max_value);
773 /* do limits check if we can */
774 if (min_format == max_format) {
775 if (max_value != -1 && min_value != -1 && max_value < min_value)
779 /* create client datastructure */
780 client = g_new0 (GstSocketClient, 1);
781 client->socket = G_SOCKET (g_object_ref (socket));
782 client->status = GST_CLIENT_STATUS_OK;
784 client->flushcount = -1;
785 client->bufoffset = 0;
786 client->sending = NULL;
787 client->bytes_sent = 0;
788 client->dropped_buffers = 0;
789 client->avg_queue_size = 0;
790 client->first_buffer_ts = GST_CLOCK_TIME_NONE;
791 client->last_buffer_ts = GST_CLOCK_TIME_NONE;
792 client->new_connection = TRUE;
793 client->burst_min_format = min_format;
794 client->burst_min_value = min_value;
795 client->burst_max_format = max_format;
796 client->burst_max_value = max_value;
797 client->sync_method = sync_method;
798 client->currently_removing = FALSE;
800 /* update start time */
801 g_get_current_time (&now);
802 client->connect_time = GST_TIMEVAL_TO_TIME (now);
803 client->disconnect_time = 0;
804 /* set last activity time to connect time */
805 client->last_activity_time = client->connect_time;
809 /* check the hash to find a duplicate fd */
810 clink = g_hash_table_lookup (sink->socket_hash, socket);
814 /* we can add the fd now */
815 clink = sink->clients = g_list_prepend (sink->clients, client);
816 g_hash_table_insert (sink->socket_hash, socket, clink);
817 sink->clients_cookie++;
819 /* set the socket to non blocking */
820 g_socket_set_blocking (socket, FALSE);
822 /* we always read from a client */
823 if (sink->main_context) {
825 g_socket_create_source (client->socket,
826 G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP, sink->cancellable);
827 g_source_set_callback (client->source,
828 (GSourceFunc) gst_multi_handle_sink_socket_condition,
829 gst_object_ref (sink), (GDestroyNotify) gst_object_unref);
830 g_source_attach (client->source, sink->main_context);
833 setup_dscp_client (sink, client);
835 CLIENTS_UNLOCK (sink);
837 g_signal_emit (G_OBJECT (sink),
838 gst_multi_handle_sink_signals[SIGNAL_CLIENT_ADDED], 0, socket);
845 GST_WARNING_OBJECT (sink,
846 "[socket %p] wrong values min =%" G_GUINT64_FORMAT ", max=%"
847 G_GUINT64_FORMAT ", format %d specified when adding client", socket,
848 min_value, max_value, min_format);
853 client->status = GST_CLIENT_STATUS_DUPLICATE;
854 CLIENTS_UNLOCK (sink);
855 GST_WARNING_OBJECT (sink, "[socket %p] duplicate client found, refusing",
857 g_signal_emit (G_OBJECT (sink),
858 gst_multi_handle_sink_signals[SIGNAL_CLIENT_REMOVED], 0, socket,
865 /* "add" signal implementation */
867 gst_multi_handle_sink_add (GstMultiHandleSink * sink, GSocket * socket)
869 gst_multi_handle_sink_add_full (sink, socket, sink->def_sync_method,
870 sink->def_burst_format, sink->def_burst_value, sink->def_burst_format,
874 /* "remove" signal implementation */
876 gst_multi_handle_sink_remove (GstMultiHandleSink * sink, GSocket * socket)
880 GST_DEBUG_OBJECT (sink, "[socket %p] removing client", socket);
883 clink = g_hash_table_lookup (sink->socket_hash, socket);
885 GstSocketClient *client = clink->data;
887 if (client->status != GST_CLIENT_STATUS_OK) {
888 GST_INFO_OBJECT (sink,
889 "[socket %p] Client already disconnecting with status %d",
890 socket, client->status);
894 client->status = GST_CLIENT_STATUS_REMOVED;
895 gst_multi_handle_sink_remove_client_link (sink, clink);
897 GST_WARNING_OBJECT (sink, "[socket %p] no client with this socket found!",
902 CLIENTS_UNLOCK (sink);
905 /* "remove-flush" signal implementation */
907 gst_multi_handle_sink_remove_flush (GstMultiHandleSink * sink, GSocket * socket)
911 GST_DEBUG_OBJECT (sink, "[socket %p] flushing client", socket);
914 clink = g_hash_table_lookup (sink->socket_hash, socket);
916 GstSocketClient *client = clink->data;
918 if (client->status != GST_CLIENT_STATUS_OK) {
919 GST_INFO_OBJECT (sink,
920 "[socket %p] Client already disconnecting with status %d",
921 socket, client->status);
925 /* take the position of the client as the number of buffers left to flush.
926 * If the client was at position -1, we flush 0 buffers, 0 == flush 1
928 client->flushcount = client->bufpos + 1;
929 /* mark client as flushing. We can not remove the client right away because
930 * it might have some buffers to flush in the ->sending queue. */
931 client->status = GST_CLIENT_STATUS_FLUSHING;
933 GST_WARNING_OBJECT (sink, "[socket %p] no client with this fd found!",
937 CLIENTS_UNLOCK (sink);
940 /* can be called both through the signal (i.e. from any thread) or when
941 * stopping, after the writing thread has shut down */
943 gst_multi_handle_sink_clear (GstMultiHandleSink * sink)
948 GST_DEBUG_OBJECT (sink, "clearing all clients");
952 cookie = sink->clients_cookie;
953 for (clients = sink->clients; clients; clients = clients->next) {
954 GstSocketClient *client;
956 if (cookie != sink->clients_cookie) {
957 GST_DEBUG_OBJECT (sink, "cookie changed while removing all clients");
961 client = clients->data;
962 client->status = GST_CLIENT_STATUS_REMOVED;
963 gst_multi_handle_sink_remove_client_link (sink, clients);
966 CLIENTS_UNLOCK (sink);
969 /* "get-stats" signal implementation
972 gst_multi_handle_sink_get_stats (GstMultiHandleSink * sink, GSocket * socket)
974 GstSocketClient *client;
975 GstStructure *result = NULL;
979 clink = g_hash_table_lookup (sink->socket_hash, socket);
983 client = clink->data;
984 if (client != NULL) {
987 result = gst_structure_new_empty ("multisocketsink-stats");
989 if (client->disconnect_time == 0) {
992 g_get_current_time (&nowtv);
994 interval = GST_TIMEVAL_TO_TIME (nowtv) - client->connect_time;
996 interval = client->disconnect_time - client->connect_time;
999 gst_structure_set (result,
1000 "bytes-sent", G_TYPE_UINT64, client->bytes_sent,
1001 "connect-time", G_TYPE_UINT64, client->connect_time,
1002 "disconnect-time", G_TYPE_UINT64, client->disconnect_time,
1003 "connected-duration", G_TYPE_UINT64, interval,
1004 "last-activatity-time", G_TYPE_UINT64, client->last_activity_time,
1005 "dropped-buffers", G_TYPE_UINT64, client->dropped_buffers,
1006 "first-buffer-ts", G_TYPE_UINT64, client->first_buffer_ts,
1007 "last-buffer-ts", G_TYPE_UINT64, client->last_buffer_ts, NULL);
1011 CLIENTS_UNLOCK (sink);
1013 /* python doesn't like a NULL pointer yet */
1014 if (result == NULL) {
1015 GST_WARNING_OBJECT (sink, "[socket %p] no client with this found!", socket);
1016 result = gst_structure_new_empty ("multisocketsink-stats");
1022 /* should be called with the clientslock helt.
1023 * Note that we don't close the fd as we didn't open it in the first
1024 * place. An application should connect to the client-fd-removed signal and
1025 * close the fd itself.
1028 gst_multi_handle_sink_remove_client_link (GstMultiHandleSink * sink,
1033 GstSocketClient *client = link->data;
1034 GstMultiHandleSinkClass *fclass;
1036 fclass = GST_MULTI_HANDLE_SINK_GET_CLASS (sink);
1038 socket = client->socket;
1040 if (client->currently_removing) {
1041 GST_WARNING_OBJECT (sink, "[socket %p] client is already being removed",
1045 client->currently_removing = TRUE;
1048 /* FIXME: if we keep track of ip we can log it here and signal */
1049 switch (client->status) {
1050 case GST_CLIENT_STATUS_OK:
1051 GST_WARNING_OBJECT (sink, "[socket %p] removing client %p for no reason",
1054 case GST_CLIENT_STATUS_CLOSED:
1055 GST_DEBUG_OBJECT (sink, "[socket %p] removing client %p because of close",
1058 case GST_CLIENT_STATUS_REMOVED:
1059 GST_DEBUG_OBJECT (sink,
1060 "[socket %p] removing client %p because the app removed it", socket,
1063 case GST_CLIENT_STATUS_SLOW:
1064 GST_INFO_OBJECT (sink,
1065 "[socket %p] removing client %p because it was too slow", socket,
1068 case GST_CLIENT_STATUS_ERROR:
1069 GST_WARNING_OBJECT (sink,
1070 "[socket %p] removing client %p because of error", socket, client);
1072 case GST_CLIENT_STATUS_FLUSHING:
1074 GST_WARNING_OBJECT (sink,
1075 "[socket %p] removing client %p with invalid reason %d", socket,
1076 client, client->status);
1080 if (client->source) {
1081 g_source_destroy (client->source);
1082 g_source_unref (client->source);
1083 client->source = NULL;
1086 g_get_current_time (&now);
1087 client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
1089 /* free client buffers */
1090 g_slist_foreach (client->sending, (GFunc) gst_mini_object_unref, NULL);
1091 g_slist_free (client->sending);
1092 client->sending = NULL;
1095 gst_caps_unref (client->caps);
1096 client->caps = NULL;
1098 /* unlock the mutex before signaling because the signal handler
1099 * might query some properties */
1100 CLIENTS_UNLOCK (sink);
1102 g_signal_emit (G_OBJECT (sink),
1103 gst_multi_handle_sink_signals[SIGNAL_CLIENT_REMOVED], 0, socket,
1106 /* lock again before we remove the client completely */
1107 CLIENTS_LOCK (sink);
1109 /* fd cannot be reused in the above signal callback so we can safely
1110 * remove it from the hashtable here */
1111 if (!g_hash_table_remove (sink->socket_hash, socket)) {
1112 GST_WARNING_OBJECT (sink,
1113 "[socket %p] error removing client %p from hash", socket, client);
1115 /* after releasing the lock above, the link could be invalid, more
1116 * precisely, the next and prev pointers could point to invalid list
1117 * links. One optimisation could be to add a cookie to the linked list
1118 * and take a shortcut when it did not change between unlocking and locking
1119 * our mutex. For now we just walk the list again. */
1120 sink->clients = g_list_remove (sink->clients, client);
1121 sink->clients_cookie++;
1123 if (fclass->removed)
1124 fclass->removed (sink, socket);
1127 CLIENTS_UNLOCK (sink);
1129 /* and the fd is really gone now */
1130 g_signal_emit (G_OBJECT (sink),
1131 gst_multi_handle_sink_signals[SIGNAL_CLIENT_SOCKET_REMOVED], 0, socket);
1132 g_object_unref (socket);
1134 CLIENTS_LOCK (sink);
1137 /* handle a read on a client socket,
1138 * which either indicates a close or should be ignored
1139 * returns FALSE if some error occured or the client closed. */
1141 gst_multi_handle_sink_handle_client_read (GstMultiHandleSink * sink,
1142 GstSocketClient * client)
1148 gboolean first = TRUE;
1150 GST_DEBUG_OBJECT (sink, "[socket %p] select reports client read",
1155 /* just Read 'n' Drop, could also just drop the client as it's not supposed
1156 * to write to us except for closing the socket, I guess it's because we
1157 * like to listen to our customers. */
1161 GST_DEBUG_OBJECT (sink, "[socket %p] client wants us to read",
1164 navail = g_socket_get_available_bytes (client->socket);
1169 g_socket_receive (client->socket, dummy, MIN (navail, sizeof (dummy)),
1170 sink->cancellable, &err);
1171 if (first && nread == 0) {
1172 /* client sent close, so remove it */
1173 GST_DEBUG_OBJECT (sink, "[socket %p] client asked for close, removing",
1175 client->status = GST_CLIENT_STATUS_CLOSED;
1177 } else if (nread < 0) {
1178 GST_WARNING_OBJECT (sink, "[socket %p] could not read: %s",
1179 client->socket, err->message);
1180 client->status = GST_CLIENT_STATUS_ERROR;
1185 } while (nread > 0);
1186 g_clear_error (&err);
1192 is_sync_frame (GstMultiHandleSink * sink, GstBuffer * buffer)
1194 if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1196 } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_IN_CAPS)) {
1203 /* queue the given buffer for the given client */
1205 gst_multi_handle_sink_client_queue_buffer (GstMultiHandleSink * sink,
1206 GstSocketClient * client, GstBuffer * buffer)
1210 /* TRUE: send them if the new caps have them */
1211 gboolean send_streamheader = FALSE;
1214 /* before we queue the buffer, we check if we need to queue streamheader
1215 * buffers (because it's a new client, or because they changed) */
1216 caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (sink));
1218 if (!client->caps) {
1219 GST_DEBUG_OBJECT (sink,
1220 "[socket %p] no previous caps for this client, send streamheader",
1222 send_streamheader = TRUE;
1223 client->caps = gst_caps_ref (caps);
1225 /* there were previous caps recorded, so compare */
1226 if (!gst_caps_is_equal (caps, client->caps)) {
1227 const GValue *sh1, *sh2;
1229 /* caps are not equal, but could still have the same streamheader */
1230 s = gst_caps_get_structure (caps, 0);
1231 if (!gst_structure_has_field (s, "streamheader")) {
1232 /* no new streamheader, so nothing new to send */
1233 GST_DEBUG_OBJECT (sink,
1234 "[socket %p] new caps do not have streamheader, not sending",
1237 /* there is a new streamheader */
1238 s = gst_caps_get_structure (client->caps, 0);
1239 if (!gst_structure_has_field (s, "streamheader")) {
1240 /* no previous streamheader, so send the new one */
1241 GST_DEBUG_OBJECT (sink,
1242 "[socket %p] previous caps did not have streamheader, sending",
1244 send_streamheader = TRUE;
1246 /* both old and new caps have streamheader set */
1247 if (!sink->resend_streamheader) {
1248 GST_DEBUG_OBJECT (sink,
1249 "[socket %p] asked to not resend the streamheader, not sending",
1251 send_streamheader = FALSE;
1253 sh1 = gst_structure_get_value (s, "streamheader");
1254 s = gst_caps_get_structure (caps, 0);
1255 sh2 = gst_structure_get_value (s, "streamheader");
1256 if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1257 GST_DEBUG_OBJECT (sink,
1258 "[socket %p] new streamheader different from old, sending",
1260 send_streamheader = TRUE;
1266 /* Replace the old caps */
1267 gst_caps_unref (client->caps);
1268 client->caps = gst_caps_ref (caps);
1271 if (G_UNLIKELY (send_streamheader)) {
1276 GST_LOG_OBJECT (sink,
1277 "[socket %p] sending streamheader from caps %" GST_PTR_FORMAT,
1278 client->socket, caps);
1279 s = gst_caps_get_structure (caps, 0);
1280 if (!gst_structure_has_field (s, "streamheader")) {
1281 GST_DEBUG_OBJECT (sink,
1282 "[socket %p] no new streamheader, so nothing to send",
1285 GST_LOG_OBJECT (sink,
1286 "[socket %p] sending streamheader from caps %" GST_PTR_FORMAT,
1287 client->socket, caps);
1288 sh = gst_structure_get_value (s, "streamheader");
1289 g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1290 buffers = g_value_peek_pointer (sh);
1291 GST_DEBUG_OBJECT (sink, "%d streamheader buffers", buffers->len);
1292 for (i = 0; i < buffers->len; ++i) {
1296 bufval = &g_array_index (buffers, GValue, i);
1297 g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1298 buffer = g_value_peek_pointer (bufval);
1299 GST_DEBUG_OBJECT (sink,
1300 "[socket %p] queueing streamheader buffer of length %"
1301 G_GSIZE_FORMAT, client->socket, gst_buffer_get_size (buffer));
1302 gst_buffer_ref (buffer);
1304 client->sending = g_slist_append (client->sending, buffer);
1309 gst_caps_unref (caps);
1312 GST_LOG_OBJECT (sink,
1313 "[socket %p] queueing buffer of length %" G_GSIZE_FORMAT, client->socket,
1314 gst_buffer_get_size (buffer));
1316 gst_buffer_ref (buffer);
1317 client->sending = g_slist_append (client->sending, buffer);
1322 /* find the keyframe in the list of buffers starting the
1323 * search from @idx. @direction as -1 will search backwards,
1324 * 1 will search forwards.
1325 * Returns: the index or -1 if there is no keyframe after idx.
1328 find_syncframe (GstMultiHandleSink * sink, gint idx, gint direction)
1330 gint i, len, result;
1332 /* take length of queued buffers */
1333 len = sink->bufqueue->len;
1335 /* assume we don't find a keyframe */
1338 /* then loop over all buffers to find the first keyframe */
1339 for (i = idx; i >= 0 && i < len; i += direction) {
1342 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1343 if (is_sync_frame (sink, buf)) {
1344 GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1353 #define find_next_syncframe(s,i) find_syncframe(s,i,1)
1354 #define find_prev_syncframe(s,i) find_syncframe(s,i,-1)
1356 /* Get the number of buffers from the buffer queue needed to satisfy
1357 * the maximum max in the configured units.
1358 * If units are not BUFFERS, and there are insufficient buffers in the
1359 * queue to satify the limit, return len(queue) + 1 */
1361 get_buffers_max (GstMultiHandleSink * sink, gint64 max)
1363 switch (sink->unit_type) {
1364 case GST_FORMAT_BUFFERS:
1366 case GST_FORMAT_TIME:
1372 GstClockTime first = GST_CLOCK_TIME_NONE;
1374 len = sink->bufqueue->len;
1376 for (i = 0; i < len; i++) {
1377 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1378 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1380 first = GST_BUFFER_TIMESTAMP (buf);
1382 diff = first - GST_BUFFER_TIMESTAMP (buf);
1390 case GST_FORMAT_BYTES:
1397 len = sink->bufqueue->len;
1399 for (i = 0; i < len; i++) {
1400 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1401 acc += gst_buffer_get_size (buf);
1413 /* find the positions in the buffer queue where *_min and *_max
1416 /* count the amount of data in the buffers and return the index
1417 * that satifies the given limits.
1419 * Returns: index @idx in the buffer queue so that the given limits are
1420 * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1421 * enough data was in the queue.
1423 * FIXME, this code might now work if any of the units is in buffers...
1426 find_limits (GstMultiHandleSink * sink,
1427 gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1428 gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1430 GstClockTime first, time;
1432 gboolean result, max_hit;
1434 /* take length of queue */
1435 len = sink->bufqueue->len;
1437 /* this must hold */
1440 GST_LOG_OBJECT (sink,
1441 "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1442 ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1443 buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1444 GST_TIME_ARGS (time_max));
1446 /* do the trivial buffer limit test */
1447 if (buffers_min != -1 && len < buffers_min) {
1454 /* else count bytes and time */
1463 /* loop through the buffers, when a limit is ok, mark it
1464 * as -1, we have at least one buffer in the queue. */
1468 /* if we checked all min limits, update result */
1469 if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1470 /* don't go below 0 */
1471 *min_idx = MAX (i - 1, 0);
1473 /* if we reached one max limit break out */
1475 /* i > 0 when we get here, we subtract one to get the position
1476 * of the previous buffer. */
1478 /* we have valid complete result if we found a min_idx too */
1479 result = *min_idx != -1;
1482 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1484 bytes += gst_buffer_get_size (buf);
1486 /* take timestamp and save for the base first timestamp */
1487 if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1488 GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1489 GST_TIME_ARGS (time));
1493 /* increase max usage if we did not fill enough. Note that
1494 * buffers are sorted from new to old, so the first timestamp is
1495 * bigger than the next one. */
1496 if (time_min != -1 && first - time >= time_min)
1498 if (time_max != -1 && first - time >= time_max)
1501 GST_LOG_OBJECT (sink, "No timestamp on buffer");
1503 /* time is OK or unknown, check and increase if not enough bytes */
1504 if (bytes_min != -1) {
1505 if (bytes >= bytes_min)
1508 if (bytes_max != -1) {
1509 if (bytes >= bytes_max) {
1517 /* if we did not hit the max or min limit, set to buffer size */
1520 /* make sure min does not exceed max */
1522 *min_idx = *max_idx;
1527 /* parse the unit/value pair and assign it to the result value of the
1528 * right type, leave the other values untouched
1530 * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1533 assign_value (GstFormat format, guint64 value, gint * bytes, gint * buffers,
1534 GstClockTime * time)
1536 gboolean res = TRUE;
1538 /* set only the limit of the given format to the given value */
1540 case GST_FORMAT_BUFFERS:
1541 *buffers = (gint) value;
1543 case GST_FORMAT_TIME:
1546 case GST_FORMAT_BYTES:
1547 *bytes = (gint) value;
1549 case GST_FORMAT_UNDEFINED:
1557 /* count the index in the buffer queue to satisfy the given unit
1558 * and value pair starting from buffer at index 0.
1560 * Returns: TRUE if there was enough data in the queue to satisfy the
1561 * burst values. @idx contains the index in the buffer that contains enough
1562 * data to satisfy the limits or the last buffer in the queue when the
1563 * function returns FALSE.
1566 count_burst_unit (GstMultiHandleSink * sink, gint * min_idx,
1567 GstFormat min_format, guint64 min_value, gint * max_idx,
1568 GstFormat max_format, guint64 max_value)
1570 gint bytes_min = -1, buffers_min = -1;
1571 gint bytes_max = -1, buffers_max = -1;
1572 GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1574 assign_value (min_format, min_value, &bytes_min, &buffers_min, &time_min);
1575 assign_value (max_format, max_value, &bytes_max, &buffers_max, &time_max);
1577 return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1578 max_idx, bytes_max, buffers_max, time_max);
1581 /* decide where in the current buffer queue this new client should start
1582 * receiving buffers from.
1583 * This function is called whenever a client is connected and has not yet
1584 * received a buffer.
1585 * If this returns -1, it means that we haven't found a good point to
1586 * start streaming from yet, and this function should be called again later
1587 * when more buffers have arrived.
1590 gst_multi_handle_sink_new_client (GstMultiHandleSink * sink,
1591 GstSocketClient * client)
1595 GST_DEBUG_OBJECT (sink,
1596 "[socket %p] new client, deciding where to start in queue",
1598 GST_DEBUG_OBJECT (sink, "queue is currently %d buffers long",
1599 sink->bufqueue->len);
1600 switch (client->sync_method) {
1601 case GST_SYNC_METHOD_LATEST:
1602 /* no syncing, we are happy with whatever the client is going to get */
1603 result = client->bufpos;
1604 GST_DEBUG_OBJECT (sink,
1605 "[socket %p] SYNC_METHOD_LATEST, position %d", client->socket,
1608 case GST_SYNC_METHOD_NEXT_KEYFRAME:
1610 /* if one of the new buffers (between client->bufpos and 0) in the queue
1611 * is a sync point, we can proceed, otherwise we need to keep waiting */
1612 GST_LOG_OBJECT (sink,
1613 "[socket %p] new client, bufpos %d, waiting for keyframe",
1614 client->socket, client->bufpos);
1616 result = find_prev_syncframe (sink, client->bufpos);
1618 GST_DEBUG_OBJECT (sink,
1619 "[socket %p] SYNC_METHOD_NEXT_KEYFRAME: result %d",
1620 client->socket, result);
1624 /* client is not on a syncbuffer, need to skip these buffers and
1626 GST_LOG_OBJECT (sink,
1627 "[socket %p] new client, skipping buffer(s), no syncpoint found",
1629 client->bufpos = -1;
1632 case GST_SYNC_METHOD_LATEST_KEYFRAME:
1634 GST_DEBUG_OBJECT (sink,
1635 "[socket %p] SYNC_METHOD_LATEST_KEYFRAME", client->socket);
1637 /* for new clients we initially scan the complete buffer queue for
1638 * a sync point when a buffer is added. If we don't find a keyframe,
1639 * we need to wait for the next keyframe and so we change the client's
1640 * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1642 result = find_next_syncframe (sink, 0);
1644 GST_DEBUG_OBJECT (sink,
1645 "[socket %p] SYNC_METHOD_LATEST_KEYFRAME: result %d",
1646 client->socket, result);
1650 GST_DEBUG_OBJECT (sink,
1651 "[socket %p] SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1652 "switching to SYNC_METHOD_NEXT_KEYFRAME", client->socket);
1653 /* throw client to the waiting state */
1654 client->bufpos = -1;
1655 /* and make client sync to next keyframe */
1656 client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1659 case GST_SYNC_METHOD_BURST:
1664 /* move to the position where we satisfy the client's burst
1665 * parameters. If we could not satisfy the parameters because there
1666 * is not enough data, we just send what we have (which is in result).
1667 * We use the max value to limit the search
1669 ok = count_burst_unit (sink, &result, client->burst_min_format,
1670 client->burst_min_value, &max, client->burst_max_format,
1671 client->burst_max_value);
1672 GST_DEBUG_OBJECT (sink,
1673 "[socket %p] SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1674 client->socket, ok, result);
1676 GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1678 /* we hit the max and it is below the min, use that then */
1679 if (max != -1 && max <= result) {
1680 result = MAX (max - 1, 0);
1681 GST_DEBUG_OBJECT (sink,
1682 "[socket %p] SYNC_METHOD_BURST: result above max, taken down to %d",
1683 client->socket, result);
1687 case GST_SYNC_METHOD_BURST_KEYFRAME:
1689 gint min_idx, max_idx;
1690 gint next_syncframe, prev_syncframe;
1694 * _always_ start sending a keyframe to the client. We first search
1695 * a keyframe between min/max limits. If there is none, we send it the
1696 * last keyframe before min. If there is none, the behaviour is like
1699 /* gather burst limits */
1700 count_burst_unit (sink, &min_idx, client->burst_min_format,
1701 client->burst_min_value, &max_idx, client->burst_max_format,
1702 client->burst_max_value);
1704 GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1706 /* first find a keyframe after min_idx */
1707 next_syncframe = find_next_syncframe (sink, min_idx);
1708 if (next_syncframe != -1 && next_syncframe < max_idx) {
1709 /* we have a valid keyframe and it's below the max */
1710 GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1711 result = next_syncframe;
1715 /* no valid keyframe, try to find one below min */
1716 prev_syncframe = find_prev_syncframe (sink, min_idx);
1717 if (prev_syncframe != -1) {
1718 GST_WARNING_OBJECT (sink,
1719 "using keyframe below min in BURST_KEYFRAME sync mode");
1720 result = prev_syncframe;
1724 /* no prev keyframe or not enough data */
1725 GST_WARNING_OBJECT (sink,
1726 "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1728 /* throw client to the waiting state */
1729 client->bufpos = -1;
1730 /* and make client sync to next keyframe */
1731 client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1735 case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1737 gint min_idx, max_idx;
1738 gint next_syncframe;
1740 /* BURST_WITH_KEYFRAME:
1742 * try to start sending a keyframe to the client. We first search
1743 * a keyframe between min/max limits. If there is none, we send it the
1744 * amount of data up 'till min.
1746 /* gather enough data to burst */
1747 count_burst_unit (sink, &min_idx, client->burst_min_format,
1748 client->burst_min_value, &max_idx, client->burst_max_format,
1749 client->burst_max_value);
1751 GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1753 /* first find a keyframe after min_idx */
1754 next_syncframe = find_next_syncframe (sink, min_idx);
1755 if (next_syncframe != -1 && next_syncframe < max_idx) {
1756 /* we have a valid keyframe and it's below the max */
1757 GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1758 result = next_syncframe;
1762 /* no keyframe, send data from min_idx */
1763 GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1765 /* make sure we don't go over the max limit */
1766 if (max_idx != -1 && max_idx <= min_idx) {
1767 result = MAX (max_idx - 1, 0);
1775 g_warning ("unknown sync method %d", client->sync_method);
1776 result = client->bufpos;
1782 /* Handle a write on a client,
1783 * which indicates a read request from a client.
1785 * For each client we maintain a queue of GstBuffers that contain the raw bytes
1786 * we need to send to the client.
1788 * We first check to see if we need to send streamheaders. If so, we queue them.
1790 * Then we run into the main loop that tries to send as many buffers as
1791 * possible. It will first exhaust the client->sending queue and if the queue
1792 * is empty, it will pick a buffer from the global queue.
1794 * Sending the buffers from the client->sending queue is basically writing
1795 * the bytes to the socket and maintaining a count of the bytes that were
1796 * sent. When the buffer is completely sent, it is removed from the
1797 * client->sending queue and we try to pick a new buffer for sending.
1799 * When the sending returns a partial buffer we stop sending more data as
1800 * the next send operation could block.
1802 * This functions returns FALSE if some error occured.
1805 gst_multi_handle_sink_handle_client_write (GstMultiHandleSink * sink,
1806 GstSocketClient * client)
1808 GSocket *socket = client->socket;
1815 g_get_current_time (&nowtv);
1816 now = GST_TIMEVAL_TO_TIME (nowtv);
1818 flushing = client->status == GST_CLIENT_STATUS_FLUSHING;
1824 if (!client->sending) {
1825 /* client is not working on a buffer */
1826 if (client->bufpos == -1) {
1827 /* client is too fast, remove from write queue until new buffer is
1829 if (client->source) {
1830 g_source_destroy (client->source);
1831 g_source_unref (client->source);
1832 client->source = NULL;
1834 /* if we flushed out all of the client buffers, we can stop */
1835 if (client->flushcount == 0)
1840 /* client can pick a buffer from the global queue */
1842 GstClockTime timestamp;
1844 /* for new connections, we need to find a good spot in the
1845 * bufqueue to start streaming from */
1846 if (client->new_connection && !flushing) {
1847 gint position = gst_multi_handle_sink_new_client (sink, client);
1849 if (position >= 0) {
1850 /* we got a valid spot in the queue */
1851 client->new_connection = FALSE;
1852 client->bufpos = position;
1854 /* cannot send data to this client yet */
1855 if (client->source) {
1856 g_source_destroy (client->source);
1857 g_source_unref (client->source);
1858 client->source = NULL;
1864 /* we flushed all remaining buffers, no need to get a new one */
1865 if (client->flushcount == 0)
1869 buf = g_array_index (sink->bufqueue, GstBuffer *, client->bufpos);
1873 timestamp = GST_BUFFER_TIMESTAMP (buf);
1874 if (client->first_buffer_ts == GST_CLOCK_TIME_NONE)
1875 client->first_buffer_ts = timestamp;
1876 if (timestamp != -1)
1877 client->last_buffer_ts = timestamp;
1879 /* decrease flushcount */
1880 if (client->flushcount != -1)
1881 client->flushcount--;
1883 GST_LOG_OBJECT (sink, "[socket %p] client %p at position %d",
1884 socket, client, client->bufpos);
1886 /* queueing a buffer will ref it */
1887 gst_multi_handle_sink_client_queue_buffer (sink, client, buf);
1889 /* need to start from the first byte for this new buffer */
1890 client->bufoffset = 0;
1894 /* see if we need to send something */
1895 if (client->sending) {
1900 /* pick first buffer from list */
1901 head = GST_BUFFER (client->sending->data);
1903 gst_buffer_map (head, &map, GST_MAP_READ);
1904 maxsize = map.size - client->bufoffset;
1906 /* try to write the complete buffer */
1909 g_socket_send (socket, (gchar *) map.data + client->bufoffset,
1910 maxsize, sink->cancellable, &err);
1911 gst_buffer_unmap (head, &map);
1915 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CLOSED)) {
1916 goto connection_reset;
1921 if (wrote < maxsize) {
1922 /* partial write means that the client cannot read more and we should
1923 * stop sending more */
1924 GST_LOG_OBJECT (sink,
1925 "partial write on %p of %" G_GSSIZE_FORMAT " bytes", socket,
1927 client->bufoffset += wrote;
1930 /* complete buffer was written, we can proceed to the next one */
1931 client->sending = g_slist_remove (client->sending, head);
1932 gst_buffer_unref (head);
1933 /* make sure we start from byte 0 for the next buffer */
1934 client->bufoffset = 0;
1937 client->bytes_sent += wrote;
1938 client->last_activity_time = now;
1939 sink->bytes_served += wrote;
1949 GST_DEBUG_OBJECT (sink, "[socket %p] flushed, removing", socket);
1950 client->status = GST_CLIENT_STATUS_REMOVED;
1955 GST_DEBUG_OBJECT (sink, "[socket %p] connection reset by peer, removing",
1957 client->status = GST_CLIENT_STATUS_CLOSED;
1958 g_clear_error (&err);
1963 GST_WARNING_OBJECT (sink,
1964 "[socket %p] could not write, removing client: %s", socket,
1966 g_clear_error (&err);
1967 client->status = GST_CLIENT_STATUS_ERROR;
1972 /* calculate the new position for a client after recovery. This function
1973 * does not update the client position but merely returns the required
1977 gst_multi_handle_sink_recover_client (GstMultiHandleSink * sink,
1978 GstSocketClient * client)
1982 GST_WARNING_OBJECT (sink,
1983 "[socket %p] client %p is lagging at %d, recover using policy %d",
1984 client->socket, client, client->bufpos, sink->recover_policy);
1986 switch (sink->recover_policy) {
1987 case GST_RECOVER_POLICY_NONE:
1988 /* do nothing, client will catch up or get kicked out when it reaches
1990 newbufpos = client->bufpos;
1992 case GST_RECOVER_POLICY_RESYNC_LATEST:
1993 /* move to beginning of queue */
1996 case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
1997 /* move to beginning of soft max */
1998 newbufpos = get_buffers_max (sink, sink->units_soft_max);
2000 case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
2001 /* find keyframe in buffers, we search backwards to find the
2002 * closest keyframe relative to what this client already received. */
2003 newbufpos = MIN (sink->bufqueue->len - 1,
2004 get_buffers_max (sink, sink->units_soft_max) - 1);
2006 while (newbufpos >= 0) {
2009 buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
2010 if (is_sync_frame (sink, buf)) {
2011 /* found a buffer that is not a delta unit */
2018 /* unknown recovery procedure */
2019 newbufpos = get_buffers_max (sink, sink->units_soft_max);
2025 /* Queue a buffer on the global queue.
2027 * This function adds the buffer to the front of a GArray. It removes the
2028 * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
2029 * Note that unreffing the buffer is not a problem as clients who
2030 * started writing out this buffer will still have a reference to it in the
2031 * client->sending queue.
2033 * After adding the buffer, we update all client positions in the queue. If
2034 * a client moves over the soft max, we start the recovery procedure for this
2035 * slow client. If it goes over the hard max, it is put into the slow list
2038 * Special care is taken of clients that were waiting for a new buffer (they
2039 * had a position of -1) because they can proceed after adding this new buffer.
2040 * This is done by adding the client back into the write fd_set and signaling
2041 * the select thread that the fd_set changed.
2044 gst_multi_handle_sink_queue_buffer (GstMultiHandleSink * sink, GstBuffer * buf)
2046 GList *clients, *next;
2048 gint max_buffer_usage;
2052 gint max_buffers, soft_max_buffers;
2055 g_get_current_time (&nowtv);
2056 now = GST_TIMEVAL_TO_TIME (nowtv);
2058 CLIENTS_LOCK (sink);
2059 /* add buffer to queue */
2060 gst_buffer_ref (buf);
2061 g_array_prepend_val (sink->bufqueue, buf);
2062 queuelen = sink->bufqueue->len;
2064 if (sink->units_max > 0)
2065 max_buffers = get_buffers_max (sink, sink->units_max);
2069 if (sink->units_soft_max > 0)
2070 soft_max_buffers = get_buffers_max (sink, sink->units_soft_max);
2072 soft_max_buffers = -1;
2073 GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
2076 /* then loop over the clients and update the positions */
2077 max_buffer_usage = 0;
2080 cookie = sink->clients_cookie;
2081 for (clients = sink->clients; clients; clients = next) {
2082 GstSocketClient *client;
2084 if (cookie != sink->clients_cookie) {
2085 GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
2089 client = clients->data;
2090 next = g_list_next (clients);
2093 GST_LOG_OBJECT (sink, "[socket %p] client %p at position %d",
2094 client->socket, client, client->bufpos);
2095 /* check soft max if needed, recover client */
2096 if (soft_max_buffers > 0 && client->bufpos >= soft_max_buffers) {
2099 newpos = gst_multi_handle_sink_recover_client (sink, client);
2100 if (newpos != client->bufpos) {
2101 client->dropped_buffers += client->bufpos - newpos;
2102 client->bufpos = newpos;
2103 client->discont = TRUE;
2104 GST_INFO_OBJECT (sink, "[socket %p] client %p position reset to %d",
2105 client->socket, client, client->bufpos);
2107 GST_INFO_OBJECT (sink,
2108 "[socket %p] client %p not recovering position",
2109 client->socket, client);
2112 /* check hard max and timeout, remove client */
2113 if ((max_buffers > 0 && client->bufpos >= max_buffers) ||
2115 && now - client->last_activity_time > sink->timeout)) {
2117 GST_WARNING_OBJECT (sink, "[socket %p] client %p is too slow, removing",
2118 client->socket, client);
2119 /* remove the client, the fd set will be cleared and the select thread
2120 * will be signaled */
2121 client->status = GST_CLIENT_STATUS_SLOW;
2122 /* set client to invalid position while being removed */
2123 client->bufpos = -1;
2124 gst_multi_handle_sink_remove_client_link (sink, clients);
2126 } else if (client->bufpos == 0 || client->new_connection) {
2127 /* can send data to this client now. need to signal the select thread that
2128 * the fd_set changed */
2129 if (!client->source) {
2131 g_socket_create_source (client->socket,
2132 G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP,
2134 g_source_set_callback (client->source,
2135 (GSourceFunc) gst_multi_handle_sink_socket_condition,
2136 gst_object_ref (sink), (GDestroyNotify) gst_object_unref);
2137 g_source_attach (client->source, sink->main_context);
2140 /* keep track of maximum buffer usage */
2141 if (client->bufpos > max_buffer_usage) {
2142 max_buffer_usage = client->bufpos;
2146 /* make sure we respect bytes-min, buffers-min and time-min when they are set */
2150 GST_LOG_OBJECT (sink,
2151 "extending queue %d to respect time_min %" GST_TIME_FORMAT
2152 ", bytes_min %d, buffers_min %d", max_buffer_usage,
2153 GST_TIME_ARGS (sink->time_min), sink->bytes_min, sink->buffers_min);
2155 /* get index where the limits are ok, we don't really care if all limits
2156 * are ok, we just queue as much as we need. We also don't compare against
2157 * the max limits. */
2158 find_limits (sink, &usage, sink->bytes_min, sink->buffers_min,
2159 sink->time_min, &max, -1, -1, -1);
2161 max_buffer_usage = MAX (max_buffer_usage, usage + 1);
2162 GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
2165 /* now look for sync points and make sure there is at least one
2166 * sync point in the queue. We only do this if the LATEST_KEYFRAME or
2167 * BURST_KEYFRAME mode is selected */
2168 if (sink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
2169 sink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
2170 /* no point in searching beyond the queue length */
2171 gint limit = queuelen;
2174 /* no point in searching beyond the soft-max if any. */
2175 if (soft_max_buffers > 0) {
2176 limit = MIN (limit, soft_max_buffers);
2178 GST_LOG_OBJECT (sink,
2179 "extending queue to include sync point, now at %d, limit is %d",
2180 max_buffer_usage, limit);
2181 for (i = 0; i < limit; i++) {
2182 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
2183 if (is_sync_frame (sink, buf)) {
2184 /* found a sync frame, now extend the buffer usage to
2185 * include at least this frame. */
2186 max_buffer_usage = MAX (max_buffer_usage, i);
2190 GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
2193 GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
2195 /* nobody is referencing units after max_buffer_usage so we can
2196 * remove them from the queue. We remove them in reverse order as
2197 * this is the most optimal for GArray. */
2198 for (i = queuelen - 1; i > max_buffer_usage; i--) {
2201 /* queue exceeded max size */
2203 old = g_array_index (sink->bufqueue, GstBuffer *, i);
2204 sink->bufqueue = g_array_remove_index (sink->bufqueue, i);
2206 /* unref tail buffer */
2207 gst_buffer_unref (old);
2209 /* save for stats */
2210 sink->buffers_queued = max_buffer_usage;
2211 CLIENTS_UNLOCK (sink);
2214 /* Handle the clients. This is called when a socket becomes ready
2215 * to read or writable. Badly behaving clients are put on a
2216 * garbage list and removed.
2219 gst_multi_handle_sink_socket_condition (GSocket * socket,
2220 GIOCondition condition, GstMultiHandleSink * sink)
2223 GstSocketClient *client;
2224 gboolean ret = TRUE;
2226 CLIENTS_LOCK (sink);
2227 clink = g_hash_table_lookup (sink->socket_hash, socket);
2228 if (clink == NULL) {
2233 client = clink->data;
2235 if (client->status != GST_CLIENT_STATUS_FLUSHING
2236 && client->status != GST_CLIENT_STATUS_OK) {
2237 gst_multi_handle_sink_remove_client_link (sink, clink);
2242 if ((condition & G_IO_ERR)) {
2243 GST_WARNING_OBJECT (sink, "Socket %p has error", client->socket);
2244 client->status = GST_CLIENT_STATUS_ERROR;
2245 gst_multi_handle_sink_remove_client_link (sink, clink);
2248 } else if ((condition & G_IO_HUP)) {
2249 client->status = GST_CLIENT_STATUS_CLOSED;
2250 gst_multi_handle_sink_remove_client_link (sink, clink);
2253 } else if ((condition & G_IO_IN) || (condition & G_IO_PRI)) {
2254 /* handle client read */
2255 if (!gst_multi_handle_sink_handle_client_read (sink, client)) {
2256 gst_multi_handle_sink_remove_client_link (sink, clink);
2260 } else if ((condition & G_IO_OUT)) {
2261 /* handle client write */
2262 if (!gst_multi_handle_sink_handle_client_write (sink, client)) {
2263 gst_multi_handle_sink_remove_client_link (sink, clink);
2270 CLIENTS_UNLOCK (sink);
2276 gst_multi_handle_sink_timeout (GstMultiHandleSink * sink)
2282 g_get_current_time (&nowtv);
2283 now = GST_TIMEVAL_TO_TIME (nowtv);
2285 CLIENTS_LOCK (sink);
2286 for (clients = sink->clients; clients; clients = clients->next) {
2287 GstSocketClient *client;
2289 client = clients->data;
2290 if (sink->timeout > 0 && now - client->last_activity_time > sink->timeout) {
2291 client->status = GST_CLIENT_STATUS_SLOW;
2292 gst_multi_handle_sink_remove_client_link (sink, clients);
2295 CLIENTS_UNLOCK (sink);
2300 /* we handle the client communication in another thread so that we do not block
2301 * the gstreamer thread while we select() on the client fds */
2303 gst_multi_handle_sink_thread (GstMultiHandleSink * sink)
2305 GSource *timeout = NULL;
2307 while (sink->running) {
2308 if (sink->timeout > 0) {
2309 timeout = g_timeout_source_new (sink->timeout / GST_MSECOND);
2311 g_source_set_callback (timeout,
2312 (GSourceFunc) gst_multi_handle_sink_timeout, gst_object_ref (sink),
2313 (GDestroyNotify) gst_object_unref);
2314 g_source_attach (timeout, sink->main_context);
2317 /* Returns after handling all pending events or when
2318 * _wakeup() was called. In any case we have to add
2319 * a new timeout because something happened.
2321 g_main_context_iteration (sink->main_context, TRUE);
2324 g_source_destroy (timeout);
2325 g_source_unref (timeout);
2332 static GstFlowReturn
2333 gst_multi_handle_sink_render (GstBaseSink * bsink, GstBuffer * buf)
2335 GstMultiHandleSink *sink;
2338 GstCaps *bufcaps, *padcaps;
2341 sink = GST_MULTI_HANDLE_SINK (bsink);
2343 g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink,
2344 GST_MULTI_HANDLE_SINK_OPEN), GST_FLOW_WRONG_STATE);
2347 /* since we check every buffer for streamheader caps, we need to make
2348 * sure every buffer has caps set */
2349 bufcaps = gst_buffer_get_caps (buf);
2350 padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
2352 /* make sure we have caps on the pad */
2353 if (!padcaps && !bufcaps)
2357 /* get IN_CAPS first, code below might mess with the flags */
2358 in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
2361 /* stamp the buffer with previous caps if no caps set */
2363 if (!gst_buffer_is_writable (buf)) {
2364 /* metadata is not writable, copy will be made and original buffer
2365 * will be unreffed so we need to ref so that we don't lose the
2366 * buffer in the render method. */
2367 gst_buffer_ref (buf);
2368 /* the new buffer is ours only, we keep it out of the scope of this
2370 buf = gst_buffer_make_writable (buf);
2372 /* else the metadata is writable, we ref because we keep the buffer
2373 * out of the scope of this method */
2374 gst_buffer_ref (buf);
2376 /* buffer metadata is writable now, set the caps */
2377 gst_buffer_set_caps (buf, padcaps);
2379 gst_caps_unref (bufcaps);
2381 /* since we keep this buffer out of the scope of this method */
2382 gst_buffer_ref (buf);
2386 GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %s, offset %"
2387 G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT
2388 ", timestamp %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2389 buf, in_caps ? "yes" : "no", GST_BUFFER_OFFSET (buf),
2390 GST_BUFFER_OFFSET_END (buf),
2391 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2392 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2394 /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
2395 * it means we're getting new streamheader buffers, and we should clear
2397 if (in_caps && sink->previous_buffer_in_caps == FALSE) {
2398 GST_DEBUG_OBJECT (sink,
2399 "receiving new IN_CAPS buffers, clearing old streamheader");
2400 g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2401 g_slist_free (sink->streamheader);
2402 sink->streamheader = NULL;
2405 /* save the current in_caps */
2406 sink->previous_buffer_in_caps = in_caps;
2408 /* if the incoming buffer is marked as IN CAPS, then we assume for now
2409 * it's a streamheader that needs to be sent to each new client, so we
2410 * put it on our internal list of streamheader buffers.
2411 * FIXME: we could check if the buffer's contents are in fact part of the
2412 * current streamheader.
2414 * We don't send the buffer to the client, since streamheaders are sent
2415 * separately when necessary. */
2417 GST_DEBUG_OBJECT (sink, "appending IN_CAPS buffer with length %"
2418 G_GSIZE_FORMAT " to streamheader", gst_buffer_get_size (buf));
2419 sink->streamheader = g_slist_append (sink->streamheader, buf);
2421 /* queue the buffer, this is a regular data buffer. */
2422 gst_multi_handle_sink_queue_buffer (sink, buf);
2424 sink->bytes_to_serve += gst_buffer_get_size (buf);
2432 GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
2433 ("Received first buffer without caps set"));
2434 return GST_FLOW_NOT_NEGOTIATED;
2440 gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
2441 const GValue * value, GParamSpec * pspec)
2443 GstMultiHandleSink *multisocketsink;
2445 multisocketsink = GST_MULTI_HANDLE_SINK (object);
2448 case PROP_BUFFERS_MAX:
2449 multisocketsink->units_max = g_value_get_int (value);
2451 case PROP_BUFFERS_SOFT_MAX:
2452 multisocketsink->units_soft_max = g_value_get_int (value);
2455 multisocketsink->time_min = g_value_get_int64 (value);
2457 case PROP_BYTES_MIN:
2458 multisocketsink->bytes_min = g_value_get_int (value);
2460 case PROP_BUFFERS_MIN:
2461 multisocketsink->buffers_min = g_value_get_int (value);
2463 case PROP_UNIT_TYPE:
2464 multisocketsink->unit_type = g_value_get_enum (value);
2466 case PROP_UNITS_MAX:
2467 multisocketsink->units_max = g_value_get_int64 (value);
2469 case PROP_UNITS_SOFT_MAX:
2470 multisocketsink->units_soft_max = g_value_get_int64 (value);
2472 case PROP_RECOVER_POLICY:
2473 multisocketsink->recover_policy = g_value_get_enum (value);
2476 multisocketsink->timeout = g_value_get_uint64 (value);
2478 case PROP_SYNC_METHOD:
2479 multisocketsink->def_sync_method = g_value_get_enum (value);
2481 case PROP_BURST_FORMAT:
2482 multisocketsink->def_burst_format = g_value_get_enum (value);
2484 case PROP_BURST_VALUE:
2485 multisocketsink->def_burst_value = g_value_get_uint64 (value);
2488 multisocketsink->qos_dscp = g_value_get_int (value);
2489 setup_dscp (multisocketsink);
2491 case PROP_HANDLE_READ:
2492 multisocketsink->handle_read = g_value_get_boolean (value);
2494 case PROP_RESEND_STREAMHEADER:
2495 multisocketsink->resend_streamheader = g_value_get_boolean (value);
2499 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2505 gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
2506 GValue * value, GParamSpec * pspec)
2508 GstMultiHandleSink *multisocketsink;
2510 multisocketsink = GST_MULTI_HANDLE_SINK (object);
2513 case PROP_BUFFERS_MAX:
2514 g_value_set_int (value, multisocketsink->units_max);
2516 case PROP_BUFFERS_SOFT_MAX:
2517 g_value_set_int (value, multisocketsink->units_soft_max);
2520 g_value_set_int64 (value, multisocketsink->time_min);
2522 case PROP_BYTES_MIN:
2523 g_value_set_int (value, multisocketsink->bytes_min);
2525 case PROP_BUFFERS_MIN:
2526 g_value_set_int (value, multisocketsink->buffers_min);
2528 case PROP_BUFFERS_QUEUED:
2529 g_value_set_uint (value, multisocketsink->buffers_queued);
2531 case PROP_BYTES_QUEUED:
2532 g_value_set_uint (value, multisocketsink->bytes_queued);
2534 case PROP_TIME_QUEUED:
2535 g_value_set_uint64 (value, multisocketsink->time_queued);
2537 case PROP_UNIT_TYPE:
2538 g_value_set_enum (value, multisocketsink->unit_type);
2540 case PROP_UNITS_MAX:
2541 g_value_set_int64 (value, multisocketsink->units_max);
2543 case PROP_UNITS_SOFT_MAX:
2544 g_value_set_int64 (value, multisocketsink->units_soft_max);
2546 case PROP_RECOVER_POLICY:
2547 g_value_set_enum (value, multisocketsink->recover_policy);
2550 g_value_set_uint64 (value, multisocketsink->timeout);
2552 case PROP_SYNC_METHOD:
2553 g_value_set_enum (value, multisocketsink->def_sync_method);
2555 case PROP_BYTES_TO_SERVE:
2556 g_value_set_uint64 (value, multisocketsink->bytes_to_serve);
2558 case PROP_BYTES_SERVED:
2559 g_value_set_uint64 (value, multisocketsink->bytes_served);
2561 case PROP_BURST_FORMAT:
2562 g_value_set_enum (value, multisocketsink->def_burst_format);
2564 case PROP_BURST_VALUE:
2565 g_value_set_uint64 (value, multisocketsink->def_burst_value);
2568 g_value_set_int (value, multisocketsink->qos_dscp);
2570 case PROP_HANDLE_READ:
2571 g_value_set_boolean (value, multisocketsink->handle_read);
2573 case PROP_RESEND_STREAMHEADER:
2574 g_value_set_boolean (value, multisocketsink->resend_streamheader);
2576 case PROP_NUM_SOCKETS:
2577 g_value_set_uint (value,
2578 g_hash_table_size (multisocketsink->socket_hash));
2582 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2588 /* create a socket for sending to remote machine */
2590 gst_multi_handle_sink_start (GstBaseSink * bsink)
2592 GstMultiHandleSinkClass *fclass;
2593 GstMultiHandleSink *this;
2596 if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2599 this = GST_MULTI_HANDLE_SINK (bsink);
2600 fclass = GST_MULTI_HANDLE_SINK_GET_CLASS (this);
2602 GST_INFO_OBJECT (this, "starting");
2604 this->main_context = g_main_context_new ();
2606 CLIENTS_LOCK (this);
2607 for (clients = this->clients; clients; clients = clients->next) {
2608 GstSocketClient *client;
2610 client = clients->data;
2614 g_socket_create_source (client->socket,
2615 G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP, this->cancellable);
2616 g_source_set_callback (client->source,
2617 (GSourceFunc) gst_multi_handle_sink_socket_condition,
2618 gst_object_ref (this), (GDestroyNotify) gst_object_unref);
2619 g_source_attach (client->source, this->main_context);
2621 CLIENTS_UNLOCK (this);
2623 this->streamheader = NULL;
2624 this->bytes_to_serve = 0;
2625 this->bytes_served = 0;
2628 fclass->init (this);
2631 this->running = TRUE;
2633 this->thread = g_thread_new ("multisocketsink",
2634 (GThreadFunc) gst_multi_handle_sink_thread, this);
2636 GST_OBJECT_FLAG_SET (this, GST_MULTI_HANDLE_SINK_OPEN);
2642 multisocketsink_hash_remove (gpointer key, gpointer value, gpointer data)
2648 gst_multi_handle_sink_stop (GstBaseSink * bsink)
2650 GstMultiHandleSinkClass *fclass;
2651 GstMultiHandleSink *this;
2655 this = GST_MULTI_HANDLE_SINK (bsink);
2656 fclass = GST_MULTI_HANDLE_SINK_GET_CLASS (this);
2658 if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2661 this->running = FALSE;
2663 if (this->main_context)
2664 g_main_context_wakeup (this->main_context);
2667 GST_DEBUG_OBJECT (this, "joining thread");
2668 g_thread_join (this->thread);
2669 GST_DEBUG_OBJECT (this, "joined thread");
2670 this->thread = NULL;
2673 /* free the clients */
2674 gst_multi_handle_sink_clear (this);
2676 if (this->streamheader) {
2677 g_slist_foreach (this->streamheader, (GFunc) gst_mini_object_unref, NULL);
2678 g_slist_free (this->streamheader);
2679 this->streamheader = NULL;
2683 fclass->close (this);
2685 if (this->main_context) {
2686 g_main_context_unref (this->main_context);
2687 this->main_context = NULL;
2690 g_hash_table_foreach_remove (this->socket_hash, multisocketsink_hash_remove,
2693 /* remove all queued buffers */
2694 if (this->bufqueue) {
2695 GST_DEBUG_OBJECT (this, "Emptying bufqueue with %d buffers",
2696 this->bufqueue->len);
2697 for (i = this->bufqueue->len - 1; i >= 0; --i) {
2698 buf = g_array_index (this->bufqueue, GstBuffer *, i);
2699 GST_LOG_OBJECT (this, "Removing buffer %p (%d) with refcount %d", buf, i,
2700 GST_MINI_OBJECT_REFCOUNT (buf));
2701 gst_buffer_unref (buf);
2702 this->bufqueue = g_array_remove_index (this->bufqueue, i);
2704 /* freeing the array is done in _finalize */
2706 GST_OBJECT_FLAG_UNSET (this, GST_MULTI_HANDLE_SINK_OPEN);
2711 static GstStateChangeReturn
2712 gst_multi_handle_sink_change_state (GstElement * element,
2713 GstStateChange transition)
2715 GstMultiHandleSink *sink;
2716 GstStateChangeReturn ret;
2718 sink = GST_MULTI_HANDLE_SINK (element);
2720 /* we disallow changing the state from the streaming thread */
2721 if (g_thread_self () == sink->thread)
2722 return GST_STATE_CHANGE_FAILURE;
2725 switch (transition) {
2726 case GST_STATE_CHANGE_NULL_TO_READY:
2727 if (!gst_multi_handle_sink_start (GST_BASE_SINK (sink)))
2730 case GST_STATE_CHANGE_READY_TO_PAUSED:
2732 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2738 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2740 switch (transition) {
2741 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2743 case GST_STATE_CHANGE_PAUSED_TO_READY:
2745 case GST_STATE_CHANGE_READY_TO_NULL:
2746 gst_multi_handle_sink_stop (GST_BASE_SINK (sink));
2756 /* error message was posted */
2757 return GST_STATE_CHANGE_FAILURE;
2762 gst_multi_handle_sink_unlock (GstBaseSink * bsink)
2764 GstMultiHandleSink *sink;
2766 sink = GST_MULTI_HANDLE_SINK (bsink);
2768 GST_DEBUG_OBJECT (sink, "set to flushing");
2769 g_cancellable_cancel (sink->cancellable);
2770 if (sink->main_context)
2771 g_main_context_wakeup (sink->main_context);
2776 /* will be called only between calls to start() and stop() */
2778 gst_multi_handle_sink_unlock_stop (GstBaseSink * bsink)
2780 GstMultiHandleSink *sink;
2782 sink = GST_MULTI_HANDLE_SINK (bsink);
2784 GST_DEBUG_OBJECT (sink, "unset flushing");
2785 g_cancellable_reset (sink->cancellable);