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-multihandlesink
26 * @see_also: tcpserversink
28 * This plugin writes incoming data to a set of file descriptors. The
29 * file descriptors can be added to multihandlesink 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 multihandlesink 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 multihandlesink 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, multihandlesink will never close a file descriptor itself.
42 * The user of multihandlesink 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 multihandlesink 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 multihandlesink, 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 * multihandlesink (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 multihandlesink receives data. If the client is reading too
80 * fast, no data will be send to the client until multihandlesink receives more
81 * data. If the client, however, reads too slowly, data for that client will be
82 * queued up in multihandlesink. Two properties control the amount of data
83 * (buffers) that is queued in multihandlesink: #GstMultiHandleSink:buffers-max and
84 * #GstMultiHandleSink:buffers-soft-max. A client that falls behind by
85 * #GstMultiHandleSink:buffers-max is removed from multihandlesink 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 * multihandlesink 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 "gstmultihandlesink.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 (multihandlesink_debug);
124 #define GST_CAT_DEFAULT (multihandlesink_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
182 PROP_BUFFERS_SOFT_MAX,
203 PROP_RESEND_STREAMHEADER,
211 // FIXME: make static again when refactored
212 //#define GST_TYPE_RECOVER_POLICY (gst_multi_handle_sink_recover_policy_get_type())
215 gst_multi_handle_sink_recover_policy_get_type (void)
217 static GType recover_policy_type = 0;
218 static const GEnumValue recover_policy[] = {
219 {GST_RECOVER_POLICY_NONE,
220 "Do not try to recover", "none"},
221 {GST_RECOVER_POLICY_RESYNC_LATEST,
222 "Resync client to latest buffer", "latest"},
223 {GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT,
224 "Resync client to soft limit", "soft-limit"},
225 {GST_RECOVER_POLICY_RESYNC_KEYFRAME,
226 "Resync client to most recent keyframe", "keyframe"},
230 if (!recover_policy_type) {
231 recover_policy_type =
232 g_enum_register_static ("GstMultiHandleSinkRecoverPolicy",
235 return recover_policy_type;
238 // FIXME: make static again after refactoring
239 //#define GST_TYPE_SYNC_METHOD (gst_multi_handle_sink_sync_method_get_type())
242 gst_multi_handle_sink_sync_method_get_type (void)
244 static GType sync_method_type = 0;
245 static const GEnumValue sync_method[] = {
246 {GST_SYNC_METHOD_LATEST,
247 "Serve starting from the latest buffer", "latest"},
248 {GST_SYNC_METHOD_NEXT_KEYFRAME,
249 "Serve starting from the next keyframe", "next-keyframe"},
250 {GST_SYNC_METHOD_LATEST_KEYFRAME,
251 "Serve everything since the latest keyframe (burst)",
253 {GST_SYNC_METHOD_BURST, "Serve burst-value data to client", "burst"},
254 {GST_SYNC_METHOD_BURST_KEYFRAME,
255 "Serve burst-value data starting on a keyframe",
257 {GST_SYNC_METHOD_BURST_WITH_KEYFRAME,
258 "Serve burst-value data preferably starting on a keyframe",
259 "burst-with-keyframe"},
263 if (!sync_method_type) {
265 g_enum_register_static ("GstMultiHandleSinkSyncMethod", sync_method);
267 return sync_method_type;
270 // FIXME: make static again after refactoring
271 //#define GST_TYPE_CLIENT_STATUS (gst_multi_handle_sink_client_status_get_type())
274 gst_multi_handle_sink_client_status_get_type (void)
276 static GType client_status_type = 0;
277 static const GEnumValue client_status[] = {
278 {GST_CLIENT_STATUS_OK, "ok", "ok"},
279 {GST_CLIENT_STATUS_CLOSED, "Closed", "closed"},
280 {GST_CLIENT_STATUS_REMOVED, "Removed", "removed"},
281 {GST_CLIENT_STATUS_SLOW, "Too slow", "slow"},
282 {GST_CLIENT_STATUS_ERROR, "Error", "error"},
283 {GST_CLIENT_STATUS_DUPLICATE, "Duplicate", "duplicate"},
284 {GST_CLIENT_STATUS_FLUSHING, "Flushing", "flushing"},
288 if (!client_status_type) {
290 g_enum_register_static ("GstMultiHandleSinkClientStatus",
293 return client_status_type;
297 static void gst_multi_handle_sink_finalize (GObject * object);
301 static void gst_multi_handle_sink_remove_client_link (GstMultiHandleSink * sink,
303 static gboolean gst_multi_handle_sink_socket_condition (GSocket * socket,
304 GIOCondition condition, GstMultiHandleSink * sink);
308 static GstFlowReturn gst_multi_handle_sink_render (GstBaseSink * bsink,
310 static gboolean gst_multi_handle_sink_unlock (GstBaseSink * bsink);
311 static gboolean gst_multi_handle_sink_unlock_stop (GstBaseSink * bsink);
312 static GstStateChangeReturn gst_multi_handle_sink_change_state (GstElement *
313 element, GstStateChange transition);
316 static void gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
317 const GValue * value, GParamSpec * pspec);
318 static void gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
319 GValue * value, GParamSpec * pspec);
321 #define gst_multi_handle_sink_parent_class parent_class
322 G_DEFINE_TYPE (GstMultiHandleSink, gst_multi_handle_sink, GST_TYPE_BASE_SINK);
324 static guint gst_multi_handle_sink_signals[LAST_SIGNAL] = { 0 };
327 gst_multi_handle_sink_class_init (GstMultiHandleSinkClass * klass)
329 GObjectClass *gobject_class;
330 GstElementClass *gstelement_class;
332 GstBaseSinkClass *gstbasesink_class;
335 gobject_class = (GObjectClass *) klass;
336 gstelement_class = (GstElementClass *) klass;
338 gstbasesink_class = (GstBaseSinkClass *) klass;
341 gobject_class->set_property = gst_multi_handle_sink_set_property;
342 gobject_class->get_property = gst_multi_handle_sink_get_property;
344 gobject_class->finalize = gst_multi_handle_sink_finalize;
348 g_object_class_install_property (gobject_class, PROP_BUFFERS_MAX,
349 g_param_spec_int ("buffers-max", "Buffers max",
350 "max number of buffers to queue for a client (-1 = no limit)", -1,
351 G_MAXINT, DEFAULT_BUFFERS_MAX,
352 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
355 g_object_class_install_property (gobject_class, PROP_BUFFERS_SOFT_MAX,
356 g_param_spec_int ("buffers-soft-max", "Buffers soft max",
357 "Recover client when going over this limit (-1 = no limit)", -1,
358 G_MAXINT, DEFAULT_BUFFERS_SOFT_MAX,
359 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
362 g_object_class_install_property (gobject_class, PROP_BYTES_MIN,
363 g_param_spec_int ("bytes-min", "Bytes min",
364 "min number of bytes to queue (-1 = as little as possible)", -1,
365 G_MAXINT, DEFAULT_BYTES_MIN,
366 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
367 g_object_class_install_property (gobject_class, PROP_TIME_MIN,
368 g_param_spec_int64 ("time-min", "Time min",
369 "min number of time to queue (-1 = as little as possible)", -1,
370 G_MAXINT64, DEFAULT_TIME_MIN,
371 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
372 g_object_class_install_property (gobject_class, PROP_BUFFERS_MIN,
373 g_param_spec_int ("buffers-min", "Buffers min",
374 "min number of buffers to queue (-1 = as few as possible)", -1,
375 G_MAXINT, DEFAULT_BUFFERS_MIN,
376 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
379 g_object_class_install_property (gobject_class, PROP_UNIT_TYPE,
380 g_param_spec_enum ("unit-type", "Units type",
381 "The unit to measure the max/soft-max/queued properties",
382 GST_TYPE_FORMAT, DEFAULT_UNIT_TYPE,
383 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
384 g_object_class_install_property (gobject_class, PROP_UNITS_MAX,
385 g_param_spec_int64 ("units-max", "Units max",
386 "max number of units to queue (-1 = no limit)", -1, G_MAXINT64,
387 DEFAULT_UNITS_MAX, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388 g_object_class_install_property (gobject_class, PROP_UNITS_SOFT_MAX,
389 g_param_spec_int64 ("units-soft-max", "Units soft max",
390 "Recover client when going over this limit (-1 = no limit)", -1,
391 G_MAXINT64, DEFAULT_UNITS_SOFT_MAX,
392 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
394 g_object_class_install_property (gobject_class, PROP_BUFFERS_QUEUED,
395 g_param_spec_uint ("buffers-queued", "Buffers queued",
396 "Number of buffers currently queued", 0, G_MAXUINT, 0,
397 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
399 g_object_class_install_property (gobject_class, PROP_BYTES_QUEUED,
400 g_param_spec_uint ("bytes-queued", "Bytes queued",
401 "Number of bytes currently queued", 0, G_MAXUINT, 0,
402 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
403 g_object_class_install_property (gobject_class, PROP_TIME_QUEUED,
404 g_param_spec_uint64 ("time-queued", "Time queued",
405 "Number of time currently queued", 0, G_MAXUINT64, 0,
406 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
410 g_object_class_install_property (gobject_class, PROP_RECOVER_POLICY,
411 g_param_spec_enum ("recover-policy", "Recover Policy",
412 "How to recover when client reaches the soft max",
413 GST_TYPE_RECOVER_POLICY, DEFAULT_RECOVER_POLICY,
414 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
415 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
416 g_param_spec_uint64 ("timeout", "Timeout",
417 "Maximum inactivity timeout in nanoseconds for a client (0 = no limit)",
418 0, G_MAXUINT64, DEFAULT_TIMEOUT,
419 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
420 g_object_class_install_property (gobject_class, PROP_SYNC_METHOD,
421 g_param_spec_enum ("sync-method", "Sync Method",
422 "How to sync new clients to the stream", GST_TYPE_SYNC_METHOD,
423 DEFAULT_SYNC_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
424 g_object_class_install_property (gobject_class, PROP_BYTES_TO_SERVE,
425 g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
426 "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
427 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
428 g_object_class_install_property (gobject_class, PROP_BYTES_SERVED,
429 g_param_spec_uint64 ("bytes-served", "Bytes served",
430 "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
431 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
434 g_object_class_install_property (gobject_class, PROP_BURST_FORMAT,
435 g_param_spec_enum ("burst-format", "Burst format",
436 "The format of the burst units (when sync-method is burst[[-with]-keyframe])",
437 GST_TYPE_FORMAT, DEFAULT_BURST_FORMAT,
438 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
439 g_object_class_install_property (gobject_class, PROP_BURST_VALUE,
440 g_param_spec_uint64 ("burst-value", "Burst value",
441 "The amount of burst expressed in burst-unit", 0, G_MAXUINT64,
442 DEFAULT_BURST_VALUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
444 g_object_class_install_property (gobject_class, PROP_QOS_DSCP,
445 g_param_spec_int ("qos-dscp", "QoS diff srv code point",
446 "Quality of Service, differentiated services code point (-1 default)",
447 -1, 63, DEFAULT_QOS_DSCP,
448 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
451 * GstMultiHandleSink::handle-read
453 * Handle read requests from clients and discard the data.
457 g_object_class_install_property (gobject_class, PROP_HANDLE_READ,
458 g_param_spec_boolean ("handle-read", "Handle Read",
459 "Handle client reads and discard the data",
460 DEFAULT_HANDLE_READ, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
462 * GstMultiHandleSink::resend-streamheader
464 * Resend the streamheaders to existing clients when they change.
468 g_object_class_install_property (gobject_class, PROP_RESEND_STREAMHEADER,
469 g_param_spec_boolean ("resend-streamheader", "Resend streamheader",
470 "Resend the streamheader if it changes in the caps",
471 DEFAULT_RESEND_STREAMHEADER,
472 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
474 g_object_class_install_property (gobject_class, PROP_NUM_SOCKETS,
475 g_param_spec_uint ("num-sockets", "Number of sockets",
476 "The current number of client sockets",
477 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
482 * GstMultiHandleSink::add:
483 * @gstmultihandlesink: the multihandlesink element to emit this signal on
484 * @socket: the socket to add to multihandlesink
486 * Hand the given open socket to multihandlesink to write to.
488 gst_multi_handle_sink_signals[SIGNAL_ADD] =
489 g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
490 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
491 G_STRUCT_OFFSET (GstMultiHandleSinkClass, add), NULL, NULL,
492 g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_SOCKET);
494 * GstMultiHandleSink::add-full:
495 * @gstmultihandlesink: the multihandlesink element to emit this signal on
496 * @socket: the socket to add to multihandlesink
497 * @sync: the sync method to use
498 * @format_min: the format of @value_min
499 * @value_min: the minimum amount of data to burst expressed in
501 * @format_max: the format of @value_max
502 * @value_max: the maximum amount of data to burst expressed in
505 * Hand the given open socket to multihandlesink to write to and
506 * specify the burst parameters for the new connection.
508 gst_multi_handle_sink_signals[SIGNAL_ADD_BURST] =
509 g_signal_new ("add-full", G_TYPE_FROM_CLASS (klass),
510 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
511 G_STRUCT_OFFSET (GstMultiHandleSinkClass, add_full), NULL, NULL,
512 gst_tcp_marshal_VOID__OBJECT_ENUM_ENUM_UINT64_ENUM_UINT64, G_TYPE_NONE, 6,
513 G_TYPE_SOCKET, GST_TYPE_SYNC_METHOD, GST_TYPE_FORMAT, G_TYPE_UINT64,
514 GST_TYPE_FORMAT, G_TYPE_UINT64);
516 * GstMultiHandleSink::remove:
517 * @gstmultihandlesink: the multihandlesink element to emit this signal on
518 * @socket: the socket to remove from multihandlesink
520 * Remove the given open socket from multihandlesink.
522 gst_multi_handle_sink_signals[SIGNAL_REMOVE] =
523 g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
524 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
525 G_STRUCT_OFFSET (GstMultiHandleSinkClass, remove), NULL, NULL,
526 g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_SOCKET);
528 * GstMultiHandleSink::remove-flush:
529 * @gstmultihandlesink: the multihandlesink element to emit this signal on
530 * @socket: the socket to remove from multihandlesink
532 * Remove the given open socket from multihandlesink after flushing all
533 * the pending data to the socket.
535 gst_multi_handle_sink_signals[SIGNAL_REMOVE_FLUSH] =
536 g_signal_new ("remove-flush", G_TYPE_FROM_CLASS (klass),
537 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
538 G_STRUCT_OFFSET (GstMultiHandleSinkClass, remove_flush), NULL, NULL,
539 g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_SOCKET);
542 * GstMultiHandleSink::clear:
543 * @gstmultihandlesink: the multihandlesink element to emit this signal on
545 * Remove all sockets from multihandlesink. Since multihandlesink did not
546 * open sockets itself, it does not explicitly close the sockets. The application
547 * should do so by connecting to the client-socket-removed callback.
549 gst_multi_handle_sink_signals[SIGNAL_CLEAR] =
550 g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
551 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
552 G_STRUCT_OFFSET (GstMultiHandleSinkClass, clear), NULL, NULL,
553 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
557 * GstMultiHandleSink::get-stats:
558 * @gstmultihandlesink: the multihandlesink element to emit this signal on
559 * @socket: the socket to get stats of from multihandlesink
561 * Get statistics about @socket. This function returns a GstStructure.
563 * Returns: a GstStructure with the statistics. The structure contains
564 * values that represent: total number of bytes sent, time
565 * when the client was added, time when the client was
566 * disconnected/removed, time the client is/was active, last activity
567 * time (in epoch seconds), number of buffers dropped.
568 * All times are expressed in nanoseconds (GstClockTime).
570 gst_multi_handle_sink_signals[SIGNAL_GET_STATS] =
571 g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
572 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
573 G_STRUCT_OFFSET (GstMultiHandleSinkClass, get_stats), NULL, NULL,
574 gst_tcp_marshal_BOXED__OBJECT, GST_TYPE_STRUCTURE, 1, G_TYPE_SOCKET);
577 * GstMultiHandleSink::client-added:
578 * @gstmultihandlesink: the multihandlesink element that emitted this signal
579 * @socket: the socket that was added to multihandlesink
581 * The given socket was added to multihandlesink. This signal will
582 * be emitted from the streaming thread so application should be prepared
585 gst_multi_handle_sink_signals[SIGNAL_CLIENT_ADDED] =
586 g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
587 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiHandleSinkClass,
588 client_added), NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
589 G_TYPE_NONE, 1, G_TYPE_OBJECT);
591 * GstMultiHandleSink::client-removed:
592 * @gstmultihandlesink: the multihandlesink element that emitted this signal
593 * @socket: the socket that is to be removed from multihandlesink
594 * @status: the reason why the client was removed
596 * The given socket is about to be removed from multihandlesink. This
597 * signal will be emitted from the streaming thread so applications should
598 * be prepared for that.
600 * @gstmultihandlesink still holds a handle to @socket so it is possible to call
601 * the get-stats signal from this callback. For the same reason it is
602 * not safe to close() and reuse @socket in this callback.
604 gst_multi_handle_sink_signals[SIGNAL_CLIENT_REMOVED] =
605 g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
606 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiHandleSinkClass,
607 client_removed), NULL, NULL, gst_tcp_marshal_VOID__OBJECT_ENUM,
608 G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CLIENT_STATUS);
610 * GstMultiHandleSink::client-socket-removed:
611 * @gstmultihandlesink: the multihandlesink element that emitted this signal
612 * @socket: the socket that was removed from multihandlesink
614 * The given socket was removed from multihandlesink. This signal will
615 * be emitted from the streaming thread so applications should be prepared
618 * In this callback, @gstmultihandlesink has removed all the information
619 * associated with @socket and it is therefore not possible to call get-stats
620 * with @socket. It is however safe to close() and reuse @fd in the callback.
624 gst_multi_handle_sink_signals[SIGNAL_CLIENT_SOCKET_REMOVED] =
625 g_signal_new ("client-socket-removed", G_TYPE_FROM_CLASS (klass),
626 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiHandleSinkClass,
627 client_socket_removed), NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
628 G_TYPE_NONE, 1, G_TYPE_SOCKET);
631 gst_element_class_add_pad_template (gstelement_class,
632 gst_static_pad_template_get (&sinktemplate));
634 gst_element_class_set_details_simple (gstelement_class,
635 "Multi socket sink", "Sink/Network",
636 "Send data to multiple sockets",
637 "Thomas Vander Stichele <thomas at apestaart dot org>, "
638 "Wim Taymans <wim@fluendo.com>, "
639 "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
642 gstelement_class->change_state =
643 GST_DEBUG_FUNCPTR (gst_multi_handle_sink_change_state);
645 gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_render);
646 gstbasesink_class->unlock = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_unlock);
647 gstbasesink_class->unlock_stop =
648 GST_DEBUG_FUNCPTR (gst_multi_handle_sink_unlock_stop);
652 klass->add = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_add);
653 klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_add_full);
654 klass->remove = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_remove);
655 klass->remove_flush = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_remove_flush);
656 klass->clear = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_clear);
657 klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_get_stats);
660 GST_DEBUG_CATEGORY_INIT (multihandlesink_debug, "multihandlesink", 0,
661 "Multi socket sink");
665 gst_multi_handle_sink_init (GstMultiHandleSink * this)
667 GST_OBJECT_FLAG_UNSET (this, GST_MULTI_HANDLE_SINK_OPEN);
669 CLIENTS_LOCK_INIT (this);
670 this->clients = NULL;
671 this->socket_hash = g_hash_table_new (g_direct_hash, g_int_equal);
673 this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
674 this->unit_type = DEFAULT_UNIT_TYPE;
675 this->units_max = DEFAULT_UNITS_MAX;
676 this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
677 this->time_min = DEFAULT_TIME_MIN;
678 this->bytes_min = DEFAULT_BYTES_MIN;
679 this->buffers_min = DEFAULT_BUFFERS_MIN;
680 this->recover_policy = DEFAULT_RECOVER_POLICY;
682 this->timeout = DEFAULT_TIMEOUT;
683 this->def_sync_method = DEFAULT_SYNC_METHOD;
684 this->def_burst_format = DEFAULT_BURST_FORMAT;
685 this->def_burst_value = DEFAULT_BURST_VALUE;
687 this->qos_dscp = DEFAULT_QOS_DSCP;
688 this->handle_read = DEFAULT_HANDLE_READ;
690 this->resend_streamheader = DEFAULT_RESEND_STREAMHEADER;
692 this->header_flags = 0;
693 this->cancellable = g_cancellable_new ();
698 gst_multi_handle_sink_finalize (GObject * object)
700 GstMultiHandleSink *this;
702 this = GST_MULTI_HANDLE_SINK (object);
704 CLIENTS_LOCK_CLEAR (this);
705 g_hash_table_destroy (this->socket_hash);
706 g_array_free (this->bufqueue, TRUE);
708 if (this->cancellable) {
709 g_object_unref (this->cancellable);
710 this->cancellable = NULL;
713 G_OBJECT_CLASS (parent_class)->finalize (object);
717 setup_dscp_client (GstMultiHandleSink * sink, GstSocketClient * client)
728 struct sockaddr_in6 sa_in6;
729 struct sockaddr_storage sa_stor;
731 socklen_t slen = sizeof (sa);
735 if (sink->qos_dscp < 0)
738 fd = g_socket_get_fd (client->socket);
740 if ((ret = getsockname (fd, &sa.sa, &slen)) < 0) {
741 GST_DEBUG_OBJECT (sink, "could not get sockname: %s", g_strerror (errno));
745 af = sa.sa.sa_family;
747 /* if this is an IPv4-mapped address then do IPv4 QoS */
748 if (af == AF_INET6) {
750 GST_DEBUG_OBJECT (sink, "check IP6 socket");
751 if (IN6_IS_ADDR_V4MAPPED (&(sa.sa_in6.sin6_addr))) {
752 GST_DEBUG_OBJECT (sink, "mapped to IPV4");
757 /* extract and shift 6 bits of the DSCP */
758 tos = (sink->qos_dscp & 0x3f) << 2;
762 ret = setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos));
766 ret = setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos));
771 GST_ERROR_OBJECT (sink, "unsupported AF");
775 GST_DEBUG_OBJECT (sink, "could not set DSCP: %s", g_strerror (errno));
782 setup_dscp (GstMultiHandleSink * sink)
787 for (clients = sink->clients; clients; clients = clients->next) {
788 GstSocketClient *client;
790 client = clients->data;
792 setup_dscp_client (sink, client);
794 CLIENTS_UNLOCK (sink);
799 gst_multi_handle_sink_client_init (GstMultiHandleClient * client,
800 GstSyncMethod sync_method)
804 client->status = GST_CLIENT_STATUS_OK;
806 client->flushcount = -1;
807 client->bufoffset = 0;
808 client->sending = NULL;
809 client->bytes_sent = 0;
810 client->dropped_buffers = 0;
811 client->avg_queue_size = 0;
812 client->first_buffer_ts = GST_CLOCK_TIME_NONE;
813 client->last_buffer_ts = GST_CLOCK_TIME_NONE;
814 client->new_connection = TRUE;
815 client->sync_method = sync_method;
816 client->currently_removing = FALSE;
818 /* update start time */
819 g_get_current_time (&now);
820 client->connect_time = GST_TIMEVAL_TO_TIME (now);
821 client->disconnect_time = 0;
822 /* set last activity time to connect time */
823 client->last_activity_time = client->connect_time;
827 /* "add-full" signal implementation */
829 gst_multi_handle_sink_add_full (GstMultiHandleSink * sink, GSocket * socket,
830 GstSyncMethod sync_method, GstFormat min_format, guint64 min_value,
831 GstFormat max_format, guint64 max_value)
833 GstSocketClient *client;
837 GST_DEBUG_OBJECT (sink, "[socket %p] adding client, sync_method %d, "
838 "min_format %d, min_value %" G_GUINT64_FORMAT
839 ", max_format %d, max_value %" G_GUINT64_FORMAT, socket,
840 sync_method, min_format, min_value, max_format, max_value);
842 /* do limits check if we can */
843 if (min_format == max_format) {
844 if (max_value != -1 && min_value != -1 && max_value < min_value)
848 /* create client datastructure */
849 client = g_new0 (GstSocketClient, 1);
850 client->socket = G_SOCKET (g_object_ref (socket));
851 client->burst_min_format = min_format;
852 client->burst_min_value = min_value;
853 client->burst_max_format = max_format;
854 client->burst_max_value = max_value;
858 /* check the hash to find a duplicate fd */
859 clink = g_hash_table_lookup (sink->socket_hash, socket);
863 /* we can add the fd now */
864 clink = sink->clients = g_list_prepend (sink->clients, client);
865 g_hash_table_insert (sink->socket_hash, socket, clink);
866 sink->clients_cookie++;
868 /* set the socket to non blocking */
869 g_socket_set_blocking (socket, FALSE);
871 /* we always read from a client */
872 if (sink->main_context) {
874 g_socket_create_source (client->socket,
875 G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP, sink->cancellable);
876 g_source_set_callback (client->source,
877 (GSourceFunc) gst_multi_handle_sink_socket_condition,
878 gst_object_ref (sink), (GDestroyNotify) gst_object_unref);
879 g_source_attach (client->source, sink->main_context);
882 setup_dscp_client (sink, client);
884 CLIENTS_UNLOCK (sink);
886 g_signal_emit (G_OBJECT (sink),
887 gst_multi_handle_sink_signals[SIGNAL_CLIENT_ADDED], 0, socket);
894 GST_WARNING_OBJECT (sink,
895 "[socket %p] wrong values min =%" G_GUINT64_FORMAT ", max=%"
896 G_GUINT64_FORMAT ", format %d specified when adding client", socket,
897 min_value, max_value, min_format);
902 client->status = GST_CLIENT_STATUS_DUPLICATE;
903 CLIENTS_UNLOCK (sink);
904 GST_WARNING_OBJECT (sink, "[socket %p] duplicate client found, refusing",
906 g_signal_emit (G_OBJECT (sink),
907 gst_multi_handle_sink_signals[SIGNAL_CLIENT_REMOVED], 0, socket,
914 /* "add" signal implementation */
916 gst_multi_handle_sink_add (GstMultiHandleSink * sink, GSocket * socket)
918 gst_multi_handle_sink_add_full (sink, socket, sink->def_sync_method,
919 sink->def_burst_format, sink->def_burst_value, sink->def_burst_format,
923 /* "remove" signal implementation */
925 gst_multi_handle_sink_remove (GstMultiHandleSink * sink, GSocket * socket)
929 GST_DEBUG_OBJECT (sink, "[socket %p] removing client", socket);
932 clink = g_hash_table_lookup (sink->socket_hash, socket);
934 GstSocketClient *client = clink->data;
936 if (client->status != GST_CLIENT_STATUS_OK) {
937 GST_INFO_OBJECT (sink,
938 "[socket %p] Client already disconnecting with status %d",
939 socket, client->status);
943 client->status = GST_CLIENT_STATUS_REMOVED;
944 gst_multi_handle_sink_remove_client_link (sink, clink);
946 GST_WARNING_OBJECT (sink, "[socket %p] no client with this socket found!",
951 CLIENTS_UNLOCK (sink);
954 /* "remove-flush" signal implementation */
956 gst_multi_handle_sink_remove_flush (GstMultiHandleSink * sink, GSocket * socket)
960 GST_DEBUG_OBJECT (sink, "[socket %p] flushing client", socket);
963 clink = g_hash_table_lookup (sink->socket_hash, socket);
965 GstSocketClient *client = clink->data;
967 if (client->status != GST_CLIENT_STATUS_OK) {
968 GST_INFO_OBJECT (sink,
969 "[socket %p] Client already disconnecting with status %d",
970 socket, client->status);
974 /* take the position of the client as the number of buffers left to flush.
975 * If the client was at position -1, we flush 0 buffers, 0 == flush 1
977 client->flushcount = client->bufpos + 1;
978 /* mark client as flushing. We can not remove the client right away because
979 * it might have some buffers to flush in the ->sending queue. */
980 client->status = GST_CLIENT_STATUS_FLUSHING;
982 GST_WARNING_OBJECT (sink, "[socket %p] no client with this fd found!",
986 CLIENTS_UNLOCK (sink);
989 /* can be called both through the signal (i.e. from any thread) or when
990 * stopping, after the writing thread has shut down */
992 gst_multi_handle_sink_clear (GstMultiHandleSink * sink)
997 GST_DEBUG_OBJECT (sink, "clearing all clients");
1001 cookie = sink->clients_cookie;
1002 for (clients = sink->clients; clients; clients = clients->next) {
1003 GstSocketClient *client;
1005 if (cookie != sink->clients_cookie) {
1006 GST_DEBUG_OBJECT (sink, "cookie changed while removing all clients");
1010 client = clients->data;
1011 client->status = GST_CLIENT_STATUS_REMOVED;
1012 gst_multi_handle_sink_remove_client_link (sink, clients);
1015 CLIENTS_UNLOCK (sink);
1018 /* "get-stats" signal implementation
1021 gst_multi_handle_sink_get_stats (GstMultiHandleSink * sink, GSocket * socket)
1023 GstSocketClient *client;
1024 GstStructure *result = NULL;
1027 CLIENTS_LOCK (sink);
1028 clink = g_hash_table_lookup (sink->socket_hash, socket);
1032 client = clink->data;
1033 if (client != NULL) {
1036 result = gst_structure_new_empty ("multihandlesink-stats");
1038 if (client->disconnect_time == 0) {
1041 g_get_current_time (&nowtv);
1043 interval = GST_TIMEVAL_TO_TIME (nowtv) - client->connect_time;
1045 interval = client->disconnect_time - client->connect_time;
1048 gst_structure_set (result,
1049 "bytes-sent", G_TYPE_UINT64, client->bytes_sent,
1050 "connect-time", G_TYPE_UINT64, client->connect_time,
1051 "disconnect-time", G_TYPE_UINT64, client->disconnect_time,
1052 "connected-duration", G_TYPE_UINT64, interval,
1053 "last-activatity-time", G_TYPE_UINT64, client->last_activity_time,
1054 "dropped-buffers", G_TYPE_UINT64, client->dropped_buffers,
1055 "first-buffer-ts", G_TYPE_UINT64, client->first_buffer_ts,
1056 "last-buffer-ts", G_TYPE_UINT64, client->last_buffer_ts, NULL);
1060 CLIENTS_UNLOCK (sink);
1062 /* python doesn't like a NULL pointer yet */
1063 if (result == NULL) {
1064 GST_WARNING_OBJECT (sink, "[socket %p] no client with this found!", socket);
1065 result = gst_structure_new_empty ("multihandlesink-stats");
1073 /* should be called with the clientslock held.
1074 * Note that we don't close the fd as we didn't open it in the first
1075 * place. An application should connect to the client-fd-removed signal and
1076 * close the fd itself.
1079 gst_multi_handle_sink_remove_client_link (GstMultiHandleSink * sink,
1084 GstSocketClient *client = link->data;
1085 GstMultiHandleSinkClass *fclass;
1087 fclass = GST_MULTI_HANDLE_SINK_GET_CLASS (sink);
1089 socket = client->socket;
1091 if (client->currently_removing) {
1092 GST_WARNING_OBJECT (sink, "[socket %p] client is already being removed",
1096 client->currently_removing = TRUE;
1099 /* FIXME: if we keep track of ip we can log it here and signal */
1100 switch (client->status) {
1101 case GST_CLIENT_STATUS_OK:
1102 GST_WARNING_OBJECT (sink, "[socket %p] removing client %p for no reason",
1105 case GST_CLIENT_STATUS_CLOSED:
1106 GST_DEBUG_OBJECT (sink, "[socket %p] removing client %p because of close",
1109 case GST_CLIENT_STATUS_REMOVED:
1110 GST_DEBUG_OBJECT (sink,
1111 "[socket %p] removing client %p because the app removed it", socket,
1114 case GST_CLIENT_STATUS_SLOW:
1115 GST_INFO_OBJECT (sink,
1116 "[socket %p] removing client %p because it was too slow", socket,
1119 case GST_CLIENT_STATUS_ERROR:
1120 GST_WARNING_OBJECT (sink,
1121 "[socket %p] removing client %p because of error", socket, client);
1123 case GST_CLIENT_STATUS_FLUSHING:
1125 GST_WARNING_OBJECT (sink,
1126 "[socket %p] removing client %p with invalid reason %d", socket,
1127 client, client->status);
1131 if (client->source) {
1132 g_source_destroy (client->source);
1133 g_source_unref (client->source);
1134 client->source = NULL;
1137 g_get_current_time (&now);
1138 client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
1140 /* free client buffers */
1141 g_slist_foreach (client->sending, (GFunc) gst_mini_object_unref, NULL);
1142 g_slist_free (client->sending);
1143 client->sending = NULL;
1146 gst_caps_unref (client->caps);
1147 client->caps = NULL;
1149 /* unlock the mutex before signaling because the signal handler
1150 * might query some properties */
1151 CLIENTS_UNLOCK (sink);
1153 g_signal_emit (G_OBJECT (sink),
1154 gst_multi_handle_sink_signals[SIGNAL_CLIENT_REMOVED], 0, socket,
1157 /* lock again before we remove the client completely */
1158 CLIENTS_LOCK (sink);
1160 /* fd cannot be reused in the above signal callback so we can safely
1161 * remove it from the hashtable here */
1162 if (!g_hash_table_remove (sink->socket_hash, socket)) {
1163 GST_WARNING_OBJECT (sink,
1164 "[socket %p] error removing client %p from hash", socket, client);
1166 /* after releasing the lock above, the link could be invalid, more
1167 * precisely, the next and prev pointers could point to invalid list
1168 * links. One optimisation could be to add a cookie to the linked list
1169 * and take a shortcut when it did not change between unlocking and locking
1170 * our mutex. For now we just walk the list again. */
1171 sink->clients = g_list_remove (sink->clients, client);
1172 sink->clients_cookie++;
1174 if (fclass->removed)
1175 fclass->removed (sink, socket);
1178 CLIENTS_UNLOCK (sink);
1180 /* and the fd is really gone now */
1181 g_signal_emit (G_OBJECT (sink),
1182 gst_multi_handle_sink_signals[SIGNAL_CLIENT_SOCKET_REMOVED], 0, socket);
1183 g_object_unref (socket);
1185 CLIENTS_LOCK (sink);
1190 /* handle a read on a client socket,
1191 * which either indicates a close or should be ignored
1192 * returns FALSE if some error occured or the client closed. */
1194 gst_multi_handle_sink_handle_client_read (GstMultiHandleSink * sink,
1195 GstSocketClient * client)
1201 gboolean first = TRUE;
1203 GST_DEBUG_OBJECT (sink, "[socket %p] select reports client read",
1208 /* just Read 'n' Drop, could also just drop the client as it's not supposed
1209 * to write to us except for closing the socket, I guess it's because we
1210 * like to listen to our customers. */
1214 GST_DEBUG_OBJECT (sink, "[socket %p] client wants us to read",
1217 navail = g_socket_get_available_bytes (client->socket);
1222 g_socket_receive (client->socket, dummy, MIN (navail, sizeof (dummy)),
1223 sink->cancellable, &err);
1224 if (first && nread == 0) {
1225 /* client sent close, so remove it */
1226 GST_DEBUG_OBJECT (sink, "[socket %p] client asked for close, removing",
1228 client->status = GST_CLIENT_STATUS_CLOSED;
1230 } else if (nread < 0) {
1231 GST_WARNING_OBJECT (sink, "[socket %p] could not read: %s",
1232 client->socket, err->message);
1233 client->status = GST_CLIENT_STATUS_ERROR;
1238 } while (nread > 0);
1239 g_clear_error (&err);
1246 /* queue the given buffer for the given client */
1248 gst_multi_handle_sink_client_queue_buffer (GstMultiHandleSink * sink,
1249 GstSocketClient * client, GstBuffer * buffer)
1253 /* TRUE: send them if the new caps have them */
1254 gboolean send_streamheader = FALSE;
1257 /* before we queue the buffer, we check if we need to queue streamheader
1258 * buffers (because it's a new client, or because they changed) */
1259 caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (sink));
1261 if (!client->caps) {
1262 GST_DEBUG_OBJECT (sink,
1263 "[socket %p] no previous caps for this client, send streamheader",
1265 send_streamheader = TRUE;
1266 client->caps = gst_caps_ref (caps);
1268 /* there were previous caps recorded, so compare */
1269 if (!gst_caps_is_equal (caps, client->caps)) {
1270 const GValue *sh1, *sh2;
1272 /* caps are not equal, but could still have the same streamheader */
1273 s = gst_caps_get_structure (caps, 0);
1274 if (!gst_structure_has_field (s, "streamheader")) {
1275 /* no new streamheader, so nothing new to send */
1276 GST_DEBUG_OBJECT (sink,
1277 "[socket %p] new caps do not have streamheader, not sending",
1280 /* there is a new streamheader */
1281 s = gst_caps_get_structure (client->caps, 0);
1282 if (!gst_structure_has_field (s, "streamheader")) {
1283 /* no previous streamheader, so send the new one */
1284 GST_DEBUG_OBJECT (sink,
1285 "[socket %p] previous caps did not have streamheader, sending",
1287 send_streamheader = TRUE;
1289 /* both old and new caps have streamheader set */
1290 if (!sink->resend_streamheader) {
1291 GST_DEBUG_OBJECT (sink,
1292 "[socket %p] asked to not resend the streamheader, not sending",
1294 send_streamheader = FALSE;
1296 sh1 = gst_structure_get_value (s, "streamheader");
1297 s = gst_caps_get_structure (caps, 0);
1298 sh2 = gst_structure_get_value (s, "streamheader");
1299 if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1300 GST_DEBUG_OBJECT (sink,
1301 "[socket %p] new streamheader different from old, sending",
1303 send_streamheader = TRUE;
1309 /* Replace the old caps */
1310 gst_caps_unref (client->caps);
1311 client->caps = gst_caps_ref (caps);
1314 if (G_UNLIKELY (send_streamheader)) {
1319 GST_LOG_OBJECT (sink,
1320 "[socket %p] sending streamheader from caps %" GST_PTR_FORMAT,
1321 client->socket, caps);
1322 s = gst_caps_get_structure (caps, 0);
1323 if (!gst_structure_has_field (s, "streamheader")) {
1324 GST_DEBUG_OBJECT (sink,
1325 "[socket %p] no new streamheader, so nothing to send",
1328 GST_LOG_OBJECT (sink,
1329 "[socket %p] sending streamheader from caps %" GST_PTR_FORMAT,
1330 client->socket, caps);
1331 sh = gst_structure_get_value (s, "streamheader");
1332 g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1333 buffers = g_value_peek_pointer (sh);
1334 GST_DEBUG_OBJECT (sink, "%d streamheader buffers", buffers->len);
1335 for (i = 0; i < buffers->len; ++i) {
1339 bufval = &g_array_index (buffers, GValue, i);
1340 g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1341 buffer = g_value_peek_pointer (bufval);
1342 GST_DEBUG_OBJECT (sink,
1343 "[socket %p] queueing streamheader buffer of length %"
1344 G_GSIZE_FORMAT, client->socket, gst_buffer_get_size (buffer));
1345 gst_buffer_ref (buffer);
1347 client->sending = g_slist_append (client->sending, buffer);
1352 gst_caps_unref (caps);
1355 GST_LOG_OBJECT (sink,
1356 "[socket %p] queueing buffer of length %" G_GSIZE_FORMAT, client->socket,
1357 gst_buffer_get_size (buffer));
1359 gst_buffer_ref (buffer);
1360 client->sending = g_slist_append (client->sending, buffer);
1368 is_sync_frame (GstMultiHandleSink * sink, GstBuffer * buffer)
1370 if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1372 } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_IN_CAPS)) {
1379 /* find the keyframe in the list of buffers starting the
1380 * search from @idx. @direction as -1 will search backwards,
1381 * 1 will search forwards.
1382 * Returns: the index or -1 if there is no keyframe after idx.
1385 find_syncframe (GstMultiHandleSink * sink, gint idx, gint direction)
1387 gint i, len, result;
1389 /* take length of queued buffers */
1390 len = sink->bufqueue->len;
1392 /* assume we don't find a keyframe */
1395 /* then loop over all buffers to find the first keyframe */
1396 for (i = idx; i >= 0 && i < len; i += direction) {
1399 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1400 if (is_sync_frame (sink, buf)) {
1401 GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1411 #define find_next_syncframe(s,i) find_syncframe(s,i,1)
1412 #define find_prev_syncframe(s,i) find_syncframe(s,i,-1)
1415 /* Get the number of buffers from the buffer queue needed to satisfy
1416 * the maximum max in the configured units.
1417 * If units are not BUFFERS, and there are insufficient buffers in the
1418 * queue to satify the limit, return len(queue) + 1 */
1420 get_buffers_max (GstMultiHandleSink * sink, gint64 max)
1422 switch (sink->unit_type) {
1423 case GST_FORMAT_BUFFERS:
1425 case GST_FORMAT_TIME:
1431 GstClockTime first = GST_CLOCK_TIME_NONE;
1433 len = sink->bufqueue->len;
1435 for (i = 0; i < len; i++) {
1436 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1437 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1439 first = GST_BUFFER_TIMESTAMP (buf);
1441 diff = first - GST_BUFFER_TIMESTAMP (buf);
1449 case GST_FORMAT_BYTES:
1456 len = sink->bufqueue->len;
1458 for (i = 0; i < len; i++) {
1459 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1460 acc += gst_buffer_get_size (buf);
1474 /* find the positions in the buffer queue where *_min and *_max
1477 /* count the amount of data in the buffers and return the index
1478 * that satifies the given limits.
1480 * Returns: index @idx in the buffer queue so that the given limits are
1481 * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1482 * enough data was in the queue.
1484 * FIXME, this code might now work if any of the units is in buffers...
1487 find_limits (GstMultiHandleSink * sink,
1488 gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1489 gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1491 GstClockTime first, time;
1493 gboolean result, max_hit;
1495 /* take length of queue */
1496 len = sink->bufqueue->len;
1498 /* this must hold */
1501 GST_LOG_OBJECT (sink,
1502 "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1503 ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1504 buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1505 GST_TIME_ARGS (time_max));
1507 /* do the trivial buffer limit test */
1508 if (buffers_min != -1 && len < buffers_min) {
1515 /* else count bytes and time */
1524 /* loop through the buffers, when a limit is ok, mark it
1525 * as -1, we have at least one buffer in the queue. */
1529 /* if we checked all min limits, update result */
1530 if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1531 /* don't go below 0 */
1532 *min_idx = MAX (i - 1, 0);
1534 /* if we reached one max limit break out */
1536 /* i > 0 when we get here, we subtract one to get the position
1537 * of the previous buffer. */
1539 /* we have valid complete result if we found a min_idx too */
1540 result = *min_idx != -1;
1543 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1545 bytes += gst_buffer_get_size (buf);
1547 /* take timestamp and save for the base first timestamp */
1548 if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1549 GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1550 GST_TIME_ARGS (time));
1554 /* increase max usage if we did not fill enough. Note that
1555 * buffers are sorted from new to old, so the first timestamp is
1556 * bigger than the next one. */
1557 if (time_min != -1 && first - time >= time_min)
1559 if (time_max != -1 && first - time >= time_max)
1562 GST_LOG_OBJECT (sink, "No timestamp on buffer");
1564 /* time is OK or unknown, check and increase if not enough bytes */
1565 if (bytes_min != -1) {
1566 if (bytes >= bytes_min)
1569 if (bytes_max != -1) {
1570 if (bytes >= bytes_max) {
1578 /* if we did not hit the max or min limit, set to buffer size */
1581 /* make sure min does not exceed max */
1583 *min_idx = *max_idx;
1588 /* parse the unit/value pair and assign it to the result value of the
1589 * right type, leave the other values untouched
1591 * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1594 assign_value (GstFormat format, guint64 value, gint * bytes, gint * buffers,
1595 GstClockTime * time)
1597 gboolean res = TRUE;
1599 /* set only the limit of the given format to the given value */
1601 case GST_FORMAT_BUFFERS:
1602 *buffers = (gint) value;
1604 case GST_FORMAT_TIME:
1607 case GST_FORMAT_BYTES:
1608 *bytes = (gint) value;
1610 case GST_FORMAT_UNDEFINED:
1620 /* count the index in the buffer queue to satisfy the given unit
1621 * and value pair starting from buffer at index 0.
1623 * Returns: TRUE if there was enough data in the queue to satisfy the
1624 * burst values. @idx contains the index in the buffer that contains enough
1625 * data to satisfy the limits or the last buffer in the queue when the
1626 * function returns FALSE.
1629 count_burst_unit (GstMultiHandleSink * sink, gint * min_idx,
1630 GstFormat min_format, guint64 min_value, gint * max_idx,
1631 GstFormat max_format, guint64 max_value)
1633 gint bytes_min = -1, buffers_min = -1;
1634 gint bytes_max = -1, buffers_max = -1;
1635 GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1637 assign_value (min_format, min_value, &bytes_min, &buffers_min, &time_min);
1638 assign_value (max_format, max_value, &bytes_max, &buffers_max, &time_max);
1640 return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1641 max_idx, bytes_max, buffers_max, time_max);
1646 /* decide where in the current buffer queue this new client should start
1647 * receiving buffers from.
1648 * This function is called whenever a client is connected and has not yet
1649 * received a buffer.
1650 * If this returns -1, it means that we haven't found a good point to
1651 * start streaming from yet, and this function should be called again later
1652 * when more buffers have arrived.
1655 gst_multi_handle_sink_new_client (GstMultiHandleSink * sink,
1656 GstSocketClient * client)
1660 GST_DEBUG_OBJECT (sink,
1661 "[socket %p] new client, deciding where to start in queue",
1663 GST_DEBUG_OBJECT (sink, "queue is currently %d buffers long",
1664 sink->bufqueue->len);
1665 switch (client->sync_method) {
1666 case GST_SYNC_METHOD_LATEST:
1667 /* no syncing, we are happy with whatever the client is going to get */
1668 result = client->bufpos;
1669 GST_DEBUG_OBJECT (sink,
1670 "[socket %p] SYNC_METHOD_LATEST, position %d", client->socket,
1673 case GST_SYNC_METHOD_NEXT_KEYFRAME:
1675 /* if one of the new buffers (between client->bufpos and 0) in the queue
1676 * is a sync point, we can proceed, otherwise we need to keep waiting */
1677 GST_LOG_OBJECT (sink,
1678 "[socket %p] new client, bufpos %d, waiting for keyframe",
1679 client->socket, client->bufpos);
1681 result = find_prev_syncframe (sink, client->bufpos);
1683 GST_DEBUG_OBJECT (sink,
1684 "[socket %p] SYNC_METHOD_NEXT_KEYFRAME: result %d",
1685 client->socket, result);
1689 /* client is not on a syncbuffer, need to skip these buffers and
1691 GST_LOG_OBJECT (sink,
1692 "[socket %p] new client, skipping buffer(s), no syncpoint found",
1694 client->bufpos = -1;
1697 case GST_SYNC_METHOD_LATEST_KEYFRAME:
1699 GST_DEBUG_OBJECT (sink,
1700 "[socket %p] SYNC_METHOD_LATEST_KEYFRAME", client->socket);
1702 /* for new clients we initially scan the complete buffer queue for
1703 * a sync point when a buffer is added. If we don't find a keyframe,
1704 * we need to wait for the next keyframe and so we change the client's
1705 * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1707 result = find_next_syncframe (sink, 0);
1709 GST_DEBUG_OBJECT (sink,
1710 "[socket %p] SYNC_METHOD_LATEST_KEYFRAME: result %d",
1711 client->socket, result);
1715 GST_DEBUG_OBJECT (sink,
1716 "[socket %p] SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1717 "switching to SYNC_METHOD_NEXT_KEYFRAME", client->socket);
1718 /* throw client to the waiting state */
1719 client->bufpos = -1;
1720 /* and make client sync to next keyframe */
1721 client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1724 case GST_SYNC_METHOD_BURST:
1729 /* move to the position where we satisfy the client's burst
1730 * parameters. If we could not satisfy the parameters because there
1731 * is not enough data, we just send what we have (which is in result).
1732 * We use the max value to limit the search
1734 ok = count_burst_unit (sink, &result, client->burst_min_format,
1735 client->burst_min_value, &max, client->burst_max_format,
1736 client->burst_max_value);
1737 GST_DEBUG_OBJECT (sink,
1738 "[socket %p] SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1739 client->socket, ok, result);
1741 GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1743 /* we hit the max and it is below the min, use that then */
1744 if (max != -1 && max <= result) {
1745 result = MAX (max - 1, 0);
1746 GST_DEBUG_OBJECT (sink,
1747 "[socket %p] SYNC_METHOD_BURST: result above max, taken down to %d",
1748 client->socket, result);
1752 case GST_SYNC_METHOD_BURST_KEYFRAME:
1754 gint min_idx, max_idx;
1755 gint next_syncframe, prev_syncframe;
1759 * _always_ start sending a keyframe to the client. We first search
1760 * a keyframe between min/max limits. If there is none, we send it the
1761 * last keyframe before min. If there is none, the behaviour is like
1764 /* gather burst limits */
1765 count_burst_unit (sink, &min_idx, client->burst_min_format,
1766 client->burst_min_value, &max_idx, client->burst_max_format,
1767 client->burst_max_value);
1769 GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1771 /* first find a keyframe after min_idx */
1772 next_syncframe = find_next_syncframe (sink, min_idx);
1773 if (next_syncframe != -1 && next_syncframe < max_idx) {
1774 /* we have a valid keyframe and it's below the max */
1775 GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1776 result = next_syncframe;
1780 /* no valid keyframe, try to find one below min */
1781 prev_syncframe = find_prev_syncframe (sink, min_idx);
1782 if (prev_syncframe != -1) {
1783 GST_WARNING_OBJECT (sink,
1784 "using keyframe below min in BURST_KEYFRAME sync mode");
1785 result = prev_syncframe;
1789 /* no prev keyframe or not enough data */
1790 GST_WARNING_OBJECT (sink,
1791 "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1793 /* throw client to the waiting state */
1794 client->bufpos = -1;
1795 /* and make client sync to next keyframe */
1796 client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1800 case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1802 gint min_idx, max_idx;
1803 gint next_syncframe;
1805 /* BURST_WITH_KEYFRAME:
1807 * try to start sending a keyframe to the client. We first search
1808 * a keyframe between min/max limits. If there is none, we send it the
1809 * amount of data up 'till min.
1811 /* gather enough data to burst */
1812 count_burst_unit (sink, &min_idx, client->burst_min_format,
1813 client->burst_min_value, &max_idx, client->burst_max_format,
1814 client->burst_max_value);
1816 GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1818 /* first find a keyframe after min_idx */
1819 next_syncframe = find_next_syncframe (sink, min_idx);
1820 if (next_syncframe != -1 && next_syncframe < max_idx) {
1821 /* we have a valid keyframe and it's below the max */
1822 GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1823 result = next_syncframe;
1827 /* no keyframe, send data from min_idx */
1828 GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1830 /* make sure we don't go over the max limit */
1831 if (max_idx != -1 && max_idx <= min_idx) {
1832 result = MAX (max_idx - 1, 0);
1840 g_warning ("unknown sync method %d", client->sync_method);
1841 result = client->bufpos;
1849 /* Handle a write on a client,
1850 * which indicates a read request from a client.
1852 * For each client we maintain a queue of GstBuffers that contain the raw bytes
1853 * we need to send to the client.
1855 * We first check to see if we need to send streamheaders. If so, we queue them.
1857 * Then we run into the main loop that tries to send as many buffers as
1858 * possible. It will first exhaust the client->sending queue and if the queue
1859 * is empty, it will pick a buffer from the global queue.
1861 * Sending the buffers from the client->sending queue is basically writing
1862 * the bytes to the socket and maintaining a count of the bytes that were
1863 * sent. When the buffer is completely sent, it is removed from the
1864 * client->sending queue and we try to pick a new buffer for sending.
1866 * When the sending returns a partial buffer we stop sending more data as
1867 * the next send operation could block.
1869 * This functions returns FALSE if some error occured.
1872 gst_multi_handle_sink_handle_client_write (GstMultiHandleSink * sink,
1873 GstSocketClient * client)
1875 GSocket *socket = client->socket;
1882 g_get_current_time (&nowtv);
1883 now = GST_TIMEVAL_TO_TIME (nowtv);
1885 flushing = client->status == GST_CLIENT_STATUS_FLUSHING;
1891 if (!client->sending) {
1892 /* client is not working on a buffer */
1893 if (client->bufpos == -1) {
1894 /* client is too fast, remove from write queue until new buffer is
1896 if (client->source) {
1897 g_source_destroy (client->source);
1898 g_source_unref (client->source);
1899 client->source = NULL;
1901 /* if we flushed out all of the client buffers, we can stop */
1902 if (client->flushcount == 0)
1907 /* client can pick a buffer from the global queue */
1909 GstClockTime timestamp;
1911 /* for new connections, we need to find a good spot in the
1912 * bufqueue to start streaming from */
1913 if (client->new_connection && !flushing) {
1914 gint position = gst_multi_handle_sink_new_client (sink, client);
1916 if (position >= 0) {
1917 /* we got a valid spot in the queue */
1918 client->new_connection = FALSE;
1919 client->bufpos = position;
1921 /* cannot send data to this client yet */
1922 if (client->source) {
1923 g_source_destroy (client->source);
1924 g_source_unref (client->source);
1925 client->source = NULL;
1931 /* we flushed all remaining buffers, no need to get a new one */
1932 if (client->flushcount == 0)
1936 buf = g_array_index (sink->bufqueue, GstBuffer *, client->bufpos);
1940 timestamp = GST_BUFFER_TIMESTAMP (buf);
1941 if (client->first_buffer_ts == GST_CLOCK_TIME_NONE)
1942 client->first_buffer_ts = timestamp;
1943 if (timestamp != -1)
1944 client->last_buffer_ts = timestamp;
1946 /* decrease flushcount */
1947 if (client->flushcount != -1)
1948 client->flushcount--;
1950 GST_LOG_OBJECT (sink, "[socket %p] client %p at position %d",
1951 socket, client, client->bufpos);
1953 /* queueing a buffer will ref it */
1954 gst_multi_handle_sink_client_queue_buffer (sink, client, buf);
1956 /* need to start from the first byte for this new buffer */
1957 client->bufoffset = 0;
1961 /* see if we need to send something */
1962 if (client->sending) {
1967 /* pick first buffer from list */
1968 head = GST_BUFFER (client->sending->data);
1970 gst_buffer_map (head, &map, GST_MAP_READ);
1971 maxsize = map.size - client->bufoffset;
1973 /* try to write the complete buffer */
1976 g_socket_send (socket, (gchar *) map.data + client->bufoffset,
1977 maxsize, sink->cancellable, &err);
1978 gst_buffer_unmap (head, &map);
1982 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CLOSED)) {
1983 goto connection_reset;
1988 if (wrote < maxsize) {
1989 /* partial write means that the client cannot read more and we should
1990 * stop sending more */
1991 GST_LOG_OBJECT (sink,
1992 "partial write on %p of %" G_GSSIZE_FORMAT " bytes", socket,
1994 client->bufoffset += wrote;
1997 /* complete buffer was written, we can proceed to the next one */
1998 client->sending = g_slist_remove (client->sending, head);
1999 gst_buffer_unref (head);
2000 /* make sure we start from byte 0 for the next buffer */
2001 client->bufoffset = 0;
2004 client->bytes_sent += wrote;
2005 client->last_activity_time = now;
2006 sink->bytes_served += wrote;
2016 GST_DEBUG_OBJECT (sink, "[socket %p] flushed, removing", socket);
2017 client->status = GST_CLIENT_STATUS_REMOVED;
2022 GST_DEBUG_OBJECT (sink, "[socket %p] connection reset by peer, removing",
2024 client->status = GST_CLIENT_STATUS_CLOSED;
2025 g_clear_error (&err);
2030 GST_WARNING_OBJECT (sink,
2031 "[socket %p] could not write, removing client: %s", socket,
2033 g_clear_error (&err);
2034 client->status = GST_CLIENT_STATUS_ERROR;
2041 /* calculate the new position for a client after recovery. This function
2042 * does not update the client position but merely returns the required
2046 gst_multi_handle_sink_recover_client (GstMultiHandleSink * sink,
2047 GstSocketClient * client)
2051 GST_WARNING_OBJECT (sink,
2052 "[socket %p] client %p is lagging at %d, recover using policy %d",
2053 client->socket, client, client->bufpos, sink->recover_policy);
2055 switch (sink->recover_policy) {
2056 case GST_RECOVER_POLICY_NONE:
2057 /* do nothing, client will catch up or get kicked out when it reaches
2059 newbufpos = client->bufpos;
2061 case GST_RECOVER_POLICY_RESYNC_LATEST:
2062 /* move to beginning of queue */
2065 case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
2066 /* move to beginning of soft max */
2067 newbufpos = get_buffers_max (sink, sink->units_soft_max);
2069 case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
2070 /* find keyframe in buffers, we search backwards to find the
2071 * closest keyframe relative to what this client already received. */
2072 newbufpos = MIN (sink->bufqueue->len - 1,
2073 get_buffers_max (sink, sink->units_soft_max) - 1);
2075 while (newbufpos >= 0) {
2078 buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
2079 if (is_sync_frame (sink, buf)) {
2080 /* found a buffer that is not a delta unit */
2087 /* unknown recovery procedure */
2088 newbufpos = get_buffers_max (sink, sink->units_soft_max);
2096 /* Queue a buffer on the global queue.
2098 * This function adds the buffer to the front of a GArray. It removes the
2099 * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
2100 * Note that unreffing the buffer is not a problem as clients who
2101 * started writing out this buffer will still have a reference to it in the
2102 * client->sending queue.
2104 * After adding the buffer, we update all client positions in the queue. If
2105 * a client moves over the soft max, we start the recovery procedure for this
2106 * slow client. If it goes over the hard max, it is put into the slow list
2109 * Special care is taken of clients that were waiting for a new buffer (they
2110 * had a position of -1) because they can proceed after adding this new buffer.
2111 * This is done by adding the client back into the write fd_set and signaling
2112 * the select thread that the fd_set changed.
2115 gst_multi_handle_sink_queue_buffer (GstMultiHandleSink * sink, GstBuffer * buf)
2117 GList *clients, *next;
2119 gint max_buffer_usage;
2123 gint max_buffers, soft_max_buffers;
2126 g_get_current_time (&nowtv);
2127 now = GST_TIMEVAL_TO_TIME (nowtv);
2129 CLIENTS_LOCK (sink);
2130 /* add buffer to queue */
2131 gst_buffer_ref (buf);
2132 g_array_prepend_val (sink->bufqueue, buf);
2133 queuelen = sink->bufqueue->len;
2135 if (sink->units_max > 0)
2136 max_buffers = get_buffers_max (sink, sink->units_max);
2140 if (sink->units_soft_max > 0)
2141 soft_max_buffers = get_buffers_max (sink, sink->units_soft_max);
2143 soft_max_buffers = -1;
2144 GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
2147 /* then loop over the clients and update the positions */
2148 max_buffer_usage = 0;
2151 cookie = sink->clients_cookie;
2152 for (clients = sink->clients; clients; clients = next) {
2153 GstSocketClient *client;
2155 if (cookie != sink->clients_cookie) {
2156 GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
2160 client = clients->data;
2161 next = g_list_next (clients);
2164 GST_LOG_OBJECT (sink, "[socket %p] client %p at position %d",
2165 client->socket, client, client->bufpos);
2166 /* check soft max if needed, recover client */
2167 if (soft_max_buffers > 0 && client->bufpos >= soft_max_buffers) {
2170 newpos = gst_multi_handle_sink_recover_client (sink, client);
2171 if (newpos != client->bufpos) {
2172 client->dropped_buffers += client->bufpos - newpos;
2173 client->bufpos = newpos;
2174 client->discont = TRUE;
2175 GST_INFO_OBJECT (sink, "[socket %p] client %p position reset to %d",
2176 client->socket, client, client->bufpos);
2178 GST_INFO_OBJECT (sink,
2179 "[socket %p] client %p not recovering position",
2180 client->socket, client);
2183 /* check hard max and timeout, remove client */
2184 if ((max_buffers > 0 && client->bufpos >= max_buffers) ||
2186 && now - client->last_activity_time > sink->timeout)) {
2188 GST_WARNING_OBJECT (sink, "[socket %p] client %p is too slow, removing",
2189 client->socket, client);
2190 /* remove the client, the fd set will be cleared and the select thread
2191 * will be signaled */
2192 client->status = GST_CLIENT_STATUS_SLOW;
2193 /* set client to invalid position while being removed */
2194 client->bufpos = -1;
2195 gst_multi_handle_sink_remove_client_link (sink, clients);
2197 } else if (client->bufpos == 0 || client->new_connection) {
2198 /* can send data to this client now. need to signal the select thread that
2199 * the fd_set changed */
2200 if (!client->source) {
2202 g_socket_create_source (client->socket,
2203 G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP,
2205 g_source_set_callback (client->source,
2206 (GSourceFunc) gst_multi_handle_sink_socket_condition,
2207 gst_object_ref (sink), (GDestroyNotify) gst_object_unref);
2208 g_source_attach (client->source, sink->main_context);
2211 /* keep track of maximum buffer usage */
2212 if (client->bufpos > max_buffer_usage) {
2213 max_buffer_usage = client->bufpos;
2217 /* make sure we respect bytes-min, buffers-min and time-min when they are set */
2221 GST_LOG_OBJECT (sink,
2222 "extending queue %d to respect time_min %" GST_TIME_FORMAT
2223 ", bytes_min %d, buffers_min %d", max_buffer_usage,
2224 GST_TIME_ARGS (sink->time_min), sink->bytes_min, sink->buffers_min);
2226 /* get index where the limits are ok, we don't really care if all limits
2227 * are ok, we just queue as much as we need. We also don't compare against
2228 * the max limits. */
2229 find_limits (sink, &usage, sink->bytes_min, sink->buffers_min,
2230 sink->time_min, &max, -1, -1, -1);
2232 max_buffer_usage = MAX (max_buffer_usage, usage + 1);
2233 GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
2236 /* now look for sync points and make sure there is at least one
2237 * sync point in the queue. We only do this if the LATEST_KEYFRAME or
2238 * BURST_KEYFRAME mode is selected */
2239 if (sink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
2240 sink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
2241 /* no point in searching beyond the queue length */
2242 gint limit = queuelen;
2245 /* no point in searching beyond the soft-max if any. */
2246 if (soft_max_buffers > 0) {
2247 limit = MIN (limit, soft_max_buffers);
2249 GST_LOG_OBJECT (sink,
2250 "extending queue to include sync point, now at %d, limit is %d",
2251 max_buffer_usage, limit);
2252 for (i = 0; i < limit; i++) {
2253 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
2254 if (is_sync_frame (sink, buf)) {
2255 /* found a sync frame, now extend the buffer usage to
2256 * include at least this frame. */
2257 max_buffer_usage = MAX (max_buffer_usage, i);
2261 GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
2264 GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
2266 /* nobody is referencing units after max_buffer_usage so we can
2267 * remove them from the queue. We remove them in reverse order as
2268 * this is the most optimal for GArray. */
2269 for (i = queuelen - 1; i > max_buffer_usage; i--) {
2272 /* queue exceeded max size */
2274 old = g_array_index (sink->bufqueue, GstBuffer *, i);
2275 sink->bufqueue = g_array_remove_index (sink->bufqueue, i);
2277 /* unref tail buffer */
2278 gst_buffer_unref (old);
2280 /* save for stats */
2281 sink->buffers_queued = max_buffer_usage;
2282 CLIENTS_UNLOCK (sink);
2287 /* Handle the clients. This is called when a socket becomes ready
2288 * to read or writable. Badly behaving clients are put on a
2289 * garbage list and removed.
2292 gst_multi_handle_sink_socket_condition (GSocket * socket,
2293 GIOCondition condition, GstMultiHandleSink * sink)
2296 GstSocketClient *client;
2297 gboolean ret = TRUE;
2299 CLIENTS_LOCK (sink);
2300 clink = g_hash_table_lookup (sink->socket_hash, socket);
2301 if (clink == NULL) {
2306 client = clink->data;
2308 if (client->status != GST_CLIENT_STATUS_FLUSHING
2309 && client->status != GST_CLIENT_STATUS_OK) {
2310 gst_multi_handle_sink_remove_client_link (sink, clink);
2315 if ((condition & G_IO_ERR)) {
2316 GST_WARNING_OBJECT (sink, "Socket %p has error", client->socket);
2317 client->status = GST_CLIENT_STATUS_ERROR;
2318 gst_multi_handle_sink_remove_client_link (sink, clink);
2321 } else if ((condition & G_IO_HUP)) {
2322 client->status = GST_CLIENT_STATUS_CLOSED;
2323 gst_multi_handle_sink_remove_client_link (sink, clink);
2326 } else if ((condition & G_IO_IN) || (condition & G_IO_PRI)) {
2327 /* handle client read */
2328 if (!gst_multi_handle_sink_handle_client_read (sink, client)) {
2329 gst_multi_handle_sink_remove_client_link (sink, clink);
2333 } else if ((condition & G_IO_OUT)) {
2334 /* handle client write */
2335 if (!gst_multi_handle_sink_handle_client_write (sink, client)) {
2336 gst_multi_handle_sink_remove_client_link (sink, clink);
2343 CLIENTS_UNLOCK (sink);
2351 gst_multi_handle_sink_timeout (GstMultiHandleSink * sink)
2357 g_get_current_time (&nowtv);
2358 now = GST_TIMEVAL_TO_TIME (nowtv);
2360 CLIENTS_LOCK (sink);
2361 for (clients = sink->clients; clients; clients = clients->next) {
2362 GstSocketClient *client;
2364 client = clients->data;
2365 if (sink->timeout > 0 && now - client->last_activity_time > sink->timeout) {
2366 client->status = GST_CLIENT_STATUS_SLOW;
2367 gst_multi_handle_sink_remove_client_link (sink, clients);
2370 CLIENTS_UNLOCK (sink);
2377 /* we handle the client communication in another thread so that we do not block
2378 * the gstreamer thread while we select() on the client fds */
2380 gst_multi_handle_sink_thread (GstMultiHandleSink * sink)
2382 GSource *timeout = NULL;
2384 while (sink->running) {
2385 if (sink->timeout > 0) {
2386 timeout = g_timeout_source_new (sink->timeout / GST_MSECOND);
2388 g_source_set_callback (timeout,
2389 (GSourceFunc) gst_multi_handle_sink_timeout, gst_object_ref (sink),
2390 (GDestroyNotify) gst_object_unref);
2391 g_source_attach (timeout, sink->main_context);
2394 /* Returns after handling all pending events or when
2395 * _wakeup() was called. In any case we have to add
2396 * a new timeout because something happened.
2398 g_main_context_iteration (sink->main_context, TRUE);
2401 g_source_destroy (timeout);
2402 g_source_unref (timeout);
2411 static GstFlowReturn
2412 gst_multi_handle_sink_render (GstBaseSink * bsink, GstBuffer * buf)
2414 GstMultiHandleSink *sink;
2417 GstCaps *bufcaps, *padcaps;
2420 sink = GST_MULTI_HANDLE_SINK (bsink);
2422 g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink,
2423 GST_MULTI_HANDLE_SINK_OPEN), GST_FLOW_WRONG_STATE);
2426 /* since we check every buffer for streamheader caps, we need to make
2427 * sure every buffer has caps set */
2428 bufcaps = gst_buffer_get_caps (buf);
2429 padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
2431 /* make sure we have caps on the pad */
2432 if (!padcaps && !bufcaps)
2436 /* get IN_CAPS first, code below might mess with the flags */
2437 in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
2440 /* stamp the buffer with previous caps if no caps set */
2442 if (!gst_buffer_is_writable (buf)) {
2443 /* metadata is not writable, copy will be made and original buffer
2444 * will be unreffed so we need to ref so that we don't lose the
2445 * buffer in the render method. */
2446 gst_buffer_ref (buf);
2447 /* the new buffer is ours only, we keep it out of the scope of this
2449 buf = gst_buffer_make_writable (buf);
2451 /* else the metadata is writable, we ref because we keep the buffer
2452 * out of the scope of this method */
2453 gst_buffer_ref (buf);
2455 /* buffer metadata is writable now, set the caps */
2456 gst_buffer_set_caps (buf, padcaps);
2458 gst_caps_unref (bufcaps);
2460 /* since we keep this buffer out of the scope of this method */
2461 gst_buffer_ref (buf);
2465 GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %s, offset %"
2466 G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT
2467 ", timestamp %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2468 buf, in_caps ? "yes" : "no", GST_BUFFER_OFFSET (buf),
2469 GST_BUFFER_OFFSET_END (buf),
2470 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2471 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2473 /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
2474 * it means we're getting new streamheader buffers, and we should clear
2476 if (in_caps && sink->previous_buffer_in_caps == FALSE) {
2477 GST_DEBUG_OBJECT (sink,
2478 "receiving new IN_CAPS buffers, clearing old streamheader");
2479 g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2480 g_slist_free (sink->streamheader);
2481 sink->streamheader = NULL;
2484 /* save the current in_caps */
2485 sink->previous_buffer_in_caps = in_caps;
2487 /* if the incoming buffer is marked as IN CAPS, then we assume for now
2488 * it's a streamheader that needs to be sent to each new client, so we
2489 * put it on our internal list of streamheader buffers.
2490 * FIXME: we could check if the buffer's contents are in fact part of the
2491 * current streamheader.
2493 * We don't send the buffer to the client, since streamheaders are sent
2494 * separately when necessary. */
2496 GST_DEBUG_OBJECT (sink, "appending IN_CAPS buffer with length %"
2497 G_GSIZE_FORMAT " to streamheader", gst_buffer_get_size (buf));
2498 sink->streamheader = g_slist_append (sink->streamheader, buf);
2500 /* queue the buffer, this is a regular data buffer. */
2501 gst_multi_handle_sink_queue_buffer (sink, buf);
2503 sink->bytes_to_serve += gst_buffer_get_size (buf);
2511 GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
2512 ("Received first buffer without caps set"));
2513 return GST_FLOW_NOT_NEGOTIATED;
2520 gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
2521 const GValue * value, GParamSpec * pspec)
2523 GstMultiHandleSink *multihandlesink;
2525 multihandlesink = GST_MULTI_HANDLE_SINK (object);
2529 case PROP_BUFFERS_MAX:
2530 multihandlesink->units_max = g_value_get_int (value);
2532 case PROP_BUFFERS_SOFT_MAX:
2533 multihandlesink->units_soft_max = g_value_get_int (value);
2537 multihandlesink->time_min = g_value_get_int64 (value);
2539 case PROP_BYTES_MIN:
2540 multihandlesink->bytes_min = g_value_get_int (value);
2542 case PROP_BUFFERS_MIN:
2543 multihandlesink->buffers_min = g_value_get_int (value);
2546 case PROP_UNIT_TYPE:
2547 multihandlesink->unit_type = g_value_get_enum (value);
2549 case PROP_UNITS_MAX:
2550 multihandlesink->units_max = g_value_get_int64 (value);
2552 case PROP_UNITS_SOFT_MAX:
2553 multihandlesink->units_soft_max = g_value_get_int64 (value);
2556 case PROP_RECOVER_POLICY:
2557 multihandlesink->recover_policy = g_value_get_enum (value);
2560 multihandlesink->timeout = g_value_get_uint64 (value);
2562 case PROP_SYNC_METHOD:
2563 multihandlesink->def_sync_method = g_value_get_enum (value);
2566 case PROP_BURST_FORMAT:
2567 multihandlesink->def_burst_format = g_value_get_enum (value);
2569 case PROP_BURST_VALUE:
2570 multihandlesink->def_burst_value = g_value_get_uint64 (value);
2573 multihandlesink->qos_dscp = g_value_get_int (value);
2574 setup_dscp (multihandlesink);
2576 case PROP_HANDLE_READ:
2577 multihandlesink->handle_read = g_value_get_boolean (value);
2579 case PROP_RESEND_STREAMHEADER:
2580 multihandlesink->resend_streamheader = g_value_get_boolean (value);
2584 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2590 gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
2591 GValue * value, GParamSpec * pspec)
2593 GstMultiHandleSink *multihandlesink;
2595 multihandlesink = GST_MULTI_HANDLE_SINK (object);
2599 case PROP_BUFFERS_MAX:
2600 g_value_set_int (value, multihandlesink->units_max);
2602 case PROP_BUFFERS_SOFT_MAX:
2603 g_value_set_int (value, multihandlesink->units_soft_max);
2607 g_value_set_int64 (value, multihandlesink->time_min);
2609 case PROP_BYTES_MIN:
2610 g_value_set_int (value, multihandlesink->bytes_min);
2612 case PROP_BUFFERS_MIN:
2613 g_value_set_int (value, multihandlesink->buffers_min);
2616 case PROP_BUFFERS_QUEUED:
2617 g_value_set_uint (value, multihandlesink->buffers_queued);
2619 case PROP_BYTES_QUEUED:
2620 g_value_set_uint (value, multihandlesink->bytes_queued);
2622 case PROP_TIME_QUEUED:
2623 g_value_set_uint64 (value, multihandlesink->time_queued);
2625 case PROP_UNIT_TYPE:
2626 g_value_set_enum (value, multihandlesink->unit_type);
2628 case PROP_UNITS_MAX:
2629 g_value_set_int64 (value, multihandlesink->units_max);
2631 case PROP_UNITS_SOFT_MAX:
2632 g_value_set_int64 (value, multihandlesink->units_soft_max);
2635 case PROP_RECOVER_POLICY:
2636 g_value_set_enum (value, multihandlesink->recover_policy);
2639 g_value_set_uint64 (value, multihandlesink->timeout);
2641 case PROP_SYNC_METHOD:
2642 g_value_set_enum (value, multihandlesink->def_sync_method);
2644 case PROP_BYTES_TO_SERVE:
2645 g_value_set_uint64 (value, multihandlesink->bytes_to_serve);
2647 case PROP_BYTES_SERVED:
2648 g_value_set_uint64 (value, multihandlesink->bytes_served);
2651 case PROP_BURST_FORMAT:
2652 g_value_set_enum (value, multihandlesink->def_burst_format);
2654 case PROP_BURST_VALUE:
2655 g_value_set_uint64 (value, multihandlesink->def_burst_value);
2658 g_value_set_int (value, multihandlesink->qos_dscp);
2660 case PROP_HANDLE_READ:
2661 g_value_set_boolean (value, multihandlesink->handle_read);
2663 case PROP_RESEND_STREAMHEADER:
2664 g_value_set_boolean (value, multihandlesink->resend_streamheader);
2666 case PROP_NUM_SOCKETS:
2667 g_value_set_uint (value,
2668 g_hash_table_size (multihandlesink->socket_hash));
2672 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2679 /* create a socket for sending to remote machine */
2681 gst_multi_handle_sink_start (GstBaseSink * bsink)
2683 GstMultiHandleSinkClass *fclass;
2684 GstMultiHandleSink *this;
2687 if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2690 this = GST_MULTI_HANDLE_SINK (bsink);
2691 fclass = GST_MULTI_HANDLE_SINK_GET_CLASS (this);
2693 GST_INFO_OBJECT (this, "starting");
2695 this->main_context = g_main_context_new ();
2697 CLIENTS_LOCK (this);
2698 for (clients = this->clients; clients; clients = clients->next) {
2699 GstSocketClient *client;
2701 client = clients->data;
2705 g_socket_create_source (client->socket,
2706 G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP, this->cancellable);
2707 g_source_set_callback (client->source,
2708 (GSourceFunc) gst_multi_handle_sink_socket_condition,
2709 gst_object_ref (this), (GDestroyNotify) gst_object_unref);
2710 g_source_attach (client->source, this->main_context);
2712 CLIENTS_UNLOCK (this);
2714 this->streamheader = NULL;
2715 this->bytes_to_serve = 0;
2716 this->bytes_served = 0;
2719 fclass->init (this);
2722 this->running = TRUE;
2724 this->thread = g_thread_new ("multisocketsink",
2725 (GThreadFunc) gst_multi_handle_sink_thread, this);
2727 GST_OBJECT_FLAG_SET (this, GST_MULTI_HANDLE_SINK_OPEN);
2733 multisocketsink_hash_remove (gpointer key, gpointer value, gpointer data)
2741 gst_multi_handle_sink_stop (GstBaseSink * bsink)
2743 GstMultiHandleSinkClass *fclass;
2744 GstMultiHandleSink *this;
2748 this = GST_MULTI_HANDLE_SINK (bsink);
2749 fclass = GST_MULTI_HANDLE_SINK_GET_CLASS (this);
2751 if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2754 this->running = FALSE;
2756 if (this->main_context)
2757 g_main_context_wakeup (this->main_context);
2760 GST_DEBUG_OBJECT (this, "joining thread");
2761 g_thread_join (this->thread);
2762 GST_DEBUG_OBJECT (this, "joined thread");
2763 this->thread = NULL;
2766 /* free the clients */
2767 fclass->clear (this);
2769 if (this->streamheader) {
2770 g_slist_foreach (this->streamheader, (GFunc) gst_mini_object_unref, NULL);
2771 g_slist_free (this->streamheader);
2772 this->streamheader = NULL;
2776 fclass->close (this);
2778 if (this->main_context) {
2779 g_main_context_unref (this->main_context);
2780 this->main_context = NULL;
2783 g_hash_table_foreach_remove (this->socket_hash, multisocketsink_hash_remove,
2786 /* remove all queued buffers */
2787 if (this->bufqueue) {
2788 GST_DEBUG_OBJECT (this, "Emptying bufqueue with %d buffers",
2789 this->bufqueue->len);
2790 for (i = this->bufqueue->len - 1; i >= 0; --i) {
2791 buf = g_array_index (this->bufqueue, GstBuffer *, i);
2792 GST_LOG_OBJECT (this, "Removing buffer %p (%d) with refcount %d", buf, i,
2793 GST_MINI_OBJECT_REFCOUNT (buf));
2794 gst_buffer_unref (buf);
2795 this->bufqueue = g_array_remove_index (this->bufqueue, i);
2797 /* freeing the array is done in _finalize */
2799 GST_OBJECT_FLAG_UNSET (this, GST_MULTI_HANDLE_SINK_OPEN);
2806 static GstStateChangeReturn
2807 gst_multi_handle_sink_change_state (GstElement * element,
2808 GstStateChange transition)
2810 GstMultiHandleSink *sink;
2811 GstStateChangeReturn ret;
2813 sink = GST_MULTI_HANDLE_SINK (element);
2815 /* we disallow changing the state from the streaming thread */
2816 if (g_thread_self () == sink->thread)
2817 return GST_STATE_CHANGE_FAILURE;
2820 switch (transition) {
2821 case GST_STATE_CHANGE_NULL_TO_READY:
2822 if (!gst_multi_handle_sink_start (GST_BASE_SINK (sink)))
2825 case GST_STATE_CHANGE_READY_TO_PAUSED:
2827 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2833 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2835 switch (transition) {
2836 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2838 case GST_STATE_CHANGE_PAUSED_TO_READY:
2840 case GST_STATE_CHANGE_READY_TO_NULL:
2841 gst_multi_handle_sink_stop (GST_BASE_SINK (sink));
2851 /* error message was posted */
2852 return GST_STATE_CHANGE_FAILURE;
2857 gst_multi_handle_sink_unlock (GstBaseSink * bsink)
2859 GstMultiHandleSink *sink;
2861 sink = GST_MULTI_HANDLE_SINK (bsink);
2863 GST_DEBUG_OBJECT (sink, "set to flushing");
2864 g_cancellable_cancel (sink->cancellable);
2865 if (sink->main_context)
2866 g_main_context_wakeup (sink->main_context);
2871 /* will be called only between calls to start() and stop() */
2873 gst_multi_handle_sink_unlock_stop (GstBaseSink * bsink)
2875 GstMultiHandleSink *sink;
2877 sink = GST_MULTI_HANDLE_SINK (bsink);
2879 GST_DEBUG_OBJECT (sink, "unset flushing");
2880 g_cancellable_reset (sink->cancellable);