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>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
23 * SECTION:element-multifdsink
24 * @short_description: Send data to multiple file descriptors
25 * @see_also: tcpserversink
29 * This plugin writes incoming data to a set of file descriptors. The
30 * file descriptors can be added to multifdsink by emitting the "add" signal.
31 * For each descriptor added, the "client-added" signal will be called.
34 * As of version 0.10.8, a client can also be added with the "add-full" signal
35 * that allows for more control over what and how much data a client
39 * Clients can be removed from multifdsink by emitting the "remove" signal. For
40 * each descriptor removed, the "client-removed" signal will be called. The
41 * "client-removed" signal can also be fired when multifdsink decides that a
42 * client is not active anymore or, depending on the value of the
43 * "recover-policy" property, if the client is reading too slowly.
44 * In all cases, multifdsink will never close a file descriptor itself.
45 * The user of multifdsink is responsible for closing all file descriptors.
46 * This can for example be done in response to the "client-fd-removed" signal.
47 * Note that multifdsink still has a reference to the file descriptor when the
48 * "client-removed" signal is emitted, so that "get-stats" can be performed on
49 * the descriptor; it is therefore not safe to close the file descriptor in
50 * the "client-removed" signal handler, and you should use the
51 * "client-fd-removed" signal to safely close the fd.
54 * Multifdsink internally keeps a queue of the incoming buffers and uses a
55 * separate thread to send the buffers to the clients. This ensures that no
56 * client write can block the pipeline and that clients can read with different
60 * When adding a client to multifdsink, the "sync-method" property will define
61 * which buffer in the queued buffers will be sent first to the client. Clients
62 * can be sent the most recent buffer (which might not be decodable by the
63 * client if it is not a keyframe), the next keyframe received in
64 * multifdsink (which can take some time depending on the keyframe rate), or the
65 * last received keyframe (which will cause a simple burst-on-connect).
66 * Multifdsink will always keep at least one keyframe in its internal buffers
67 * when the sync-mode is set to latest-keyframe.
70 * As of version 0.10.8, there are additional values for the sync-method
71 * property to allow finer control over burst-on-connect behaviour. By selecting
72 * the 'burst' method a minimum burst size can be chosen, 'burst-keyframe'
73 * additionally requires that the burst begin with a keyframe, and
74 * 'burst-with-keyframe' attempts to burst beginning with a keyframe, but will
75 * prefer a minimum burst size even if it requires not starting with a keyframe.
78 * Multifdsink can be instructed to keep at least a minimum amount of data
79 * expressed in time or byte units in its internal queues with the the
80 * "time-min" and "bytes-min" properties respectively. These properties are
81 * useful if the application adds clients with the "add-full" signal to
82 * make sure that a burst connect can actually be honored.
85 * When streaming data, clients are allowed to read at a different rate than
86 * the rate at which multifdsink receives data. If the client is reading too
87 * fast, no data will be send to the client until multifdsink receives more
88 * data. If the client, however, reads too slowly, data for that client will be
89 * queued up in multifdsink. Two properties control the amount of data
90 * (buffers) that is queued in multifdsink: "buffers-max" and
91 * "buffers-soft-max". A client that falls behind by "buffers-max" is removed
92 * from multifdsink forcibly.
95 * A client with a lag of at least "buffers-soft-max" enters the recovery
96 * procedure which is controlled with the "recover-policy" property. A recover
97 * policy of NONE will do nothing, RESYNC_LATEST will send the most recently
98 * received buffer as the next buffer for the client, RESYNC_SOFT_LIMIT
99 * positions the client to the soft limit in the buffer queue and
100 * RESYNC_KEYFRAME positions the client at the most recent keyframe in the
104 * multifdsink will by default synchronize on the clock before serving the
105 * buffers to the clients. This behaviour can be disabled by setting the sync
106 * property to FALSE. Multifdsink will by default not do QoS and will never
111 * Last reviewed on 2006-09-12 (0.10.10)
117 #include <gst/gst-i18n-plugin.h>
119 #include <sys/ioctl.h>
122 #include <sys/types.h>
123 #include <sys/socket.h>
124 #include <sys/stat.h>
126 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
127 #include <sys/filio.h>
130 #include "gstmultifdsink.h"
131 #include "gsttcp-marshal.h"
133 #define NOT_IMPLEMENTED 0
135 /* the select call is also performed on the control sockets, that way
136 * we can send special commands to unblock or restart the select call */
137 #define CONTROL_RESTART 'R' /* restart the select call */
138 #define CONTROL_STOP 'S' /* stop the select call */
139 #define CONTROL_SOCKETS(sink) sink->control_sock
140 #define WRITE_SOCKET(sink) sink->control_sock[1]
141 #define READ_SOCKET(sink) sink->control_sock[0]
143 #define SEND_COMMAND(sink, command) \
145 unsigned char c; c = command; \
146 write (WRITE_SOCKET(sink).fd, &c, 1); \
149 #define READ_COMMAND(sink, command, res) \
151 res = read(READ_SOCKET(sink).fd, &command, 1);\
154 /* elementfactory information */
155 static const GstElementDetails gst_multi_fd_sink_details =
156 GST_ELEMENT_DETAILS ("Multi filedescriptor sink",
158 "Send data to multiple filedescriptors",
159 "Thomas Vander Stichele <thomas at apestaart dot org>, "
160 "Wim Taymans <wim@fluendo.com>");
162 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
165 GST_STATIC_CAPS_ANY);
167 GST_DEBUG_CATEGORY_STATIC (multifdsink_debug);
168 #define GST_CAT_DEFAULT (multifdsink_debug)
170 /* MultiFdSink signals and args */
182 SIGNAL_CLIENT_REMOVED,
183 SIGNAL_CLIENT_FD_REMOVED,
188 /* this is really arbitrarily chosen */
189 #define DEFAULT_PROTOCOL GST_TCP_PROTOCOL_NONE
190 #define DEFAULT_MODE GST_FDSET_MODE_POLL
191 #define DEFAULT_BUFFERS_MAX -1
192 #define DEFAULT_BUFFERS_SOFT_MAX -1
193 #define DEFAULT_TIME_MIN -1
194 #define DEFAULT_BYTES_MIN -1
195 #define DEFAULT_BUFFERS_MIN -1
196 #define DEFAULT_UNIT_TYPE GST_UNIT_TYPE_BUFFERS
197 #define DEFAULT_UNITS_MAX -1
198 #define DEFAULT_UNITS_SOFT_MAX -1
199 #define DEFAULT_RECOVER_POLICY GST_RECOVER_POLICY_NONE
200 #define DEFAULT_TIMEOUT 0
201 #define DEFAULT_SYNC_METHOD GST_SYNC_METHOD_LATEST
203 #define DEFAULT_BURST_UNIT GST_UNIT_TYPE_UNDEFINED
204 #define DEFAULT_BURST_VALUE 0
220 PROP_BUFFERS_SOFT_MAX,
236 #define GST_TYPE_RECOVER_POLICY (gst_recover_policy_get_type())
238 gst_recover_policy_get_type (void)
240 static GType recover_policy_type = 0;
241 static const GEnumValue recover_policy[] = {
242 {GST_RECOVER_POLICY_NONE,
243 "Do not try to recover", "none"},
244 {GST_RECOVER_POLICY_RESYNC_LATEST,
245 "Resync client to latest buffer", "latest"},
246 {GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT,
247 "Resync client to soft limit", "soft-limit"},
248 {GST_RECOVER_POLICY_RESYNC_KEYFRAME,
249 "Resync client to most recent keyframe", "keyframe"},
253 if (!recover_policy_type) {
254 recover_policy_type =
255 g_enum_register_static ("GstRecoverPolicy", recover_policy);
257 return recover_policy_type;
260 #define GST_TYPE_SYNC_METHOD (gst_sync_method_get_type())
262 gst_sync_method_get_type (void)
264 static GType sync_method_type = 0;
265 static const GEnumValue sync_method[] = {
266 {GST_SYNC_METHOD_LATEST,
267 "Serve starting from the latest buffer", "latest"},
268 {GST_SYNC_METHOD_NEXT_KEYFRAME,
269 "Serve starting from the next keyframe", "next-keyframe"},
270 {GST_SYNC_METHOD_LATEST_KEYFRAME,
271 "Serve everything since the latest keyframe (burst)",
273 {GST_SYNC_METHOD_BURST, "Serve burst-value data to client", "burst"},
274 {GST_SYNC_METHOD_BURST_KEYFRAME,
275 "Serve burst-value data starting on a keyframe",
277 {GST_SYNC_METHOD_BURST_WITH_KEYFRAME,
278 "Serve burst-value data preferably starting on a keyframe",
279 "burst-with-keyframe"},
283 if (!sync_method_type) {
284 sync_method_type = g_enum_register_static ("GstSyncMethod", sync_method);
286 return sync_method_type;
289 #define GST_TYPE_UNIT_TYPE (gst_unit_type_get_type())
291 gst_unit_type_get_type (void)
293 static GType unit_type_type = 0;
294 static const GEnumValue unit_type[] = {
295 {GST_UNIT_TYPE_UNDEFINED, "Undefined", "undefined"},
296 {GST_UNIT_TYPE_BUFFERS, "Buffers", "buffers"},
297 {GST_UNIT_TYPE_BYTES, "Bytes", "bytes"},
298 {GST_UNIT_TYPE_TIME, "Time", "time"},
302 if (!unit_type_type) {
303 unit_type_type = g_enum_register_static ("GstTCPUnitType", unit_type);
305 return unit_type_type;
308 #define GST_TYPE_CLIENT_STATUS (gst_client_status_get_type())
310 gst_client_status_get_type (void)
312 static GType client_status_type = 0;
313 static const GEnumValue client_status[] = {
314 {GST_CLIENT_STATUS_OK, "ok", "ok"},
315 {GST_CLIENT_STATUS_CLOSED, "Closed", "closed"},
316 {GST_CLIENT_STATUS_REMOVED, "Removed", "removed"},
317 {GST_CLIENT_STATUS_SLOW, "Too slow", "slow"},
318 {GST_CLIENT_STATUS_ERROR, "Error", "error"},
319 {GST_CLIENT_STATUS_DUPLICATE, "Duplicate", "duplicate"},
323 if (!client_status_type) {
325 g_enum_register_static ("GstClientStatus", client_status);
327 return client_status_type;
330 static void gst_multi_fd_sink_finalize (GObject * object);
332 static void gst_multi_fd_sink_remove_client_link (GstMultiFdSink * sink,
335 static GstFlowReturn gst_multi_fd_sink_render (GstBaseSink * bsink,
337 static GstStateChangeReturn gst_multi_fd_sink_change_state (GstElement *
338 element, GstStateChange transition);
340 static void gst_multi_fd_sink_set_property (GObject * object, guint prop_id,
341 const GValue * value, GParamSpec * pspec);
342 static void gst_multi_fd_sink_get_property (GObject * object, guint prop_id,
343 GValue * value, GParamSpec * pspec);
345 GST_BOILERPLATE (GstMultiFdSink, gst_multi_fd_sink, GstBaseSink,
348 static guint gst_multi_fd_sink_signals[LAST_SIGNAL] = { 0 };
351 gst_multi_fd_sink_base_init (gpointer g_class)
353 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
355 gst_element_class_add_pad_template (element_class,
356 gst_static_pad_template_get (&sinktemplate));
358 gst_element_class_set_details (element_class, &gst_multi_fd_sink_details);
362 gst_multi_fd_sink_class_init (GstMultiFdSinkClass * klass)
364 GObjectClass *gobject_class;
365 GstElementClass *gstelement_class;
366 GstBaseSinkClass *gstbasesink_class;
368 gobject_class = (GObjectClass *) klass;
369 gstelement_class = (GstElementClass *) klass;
370 gstbasesink_class = (GstBaseSinkClass *) klass;
372 gobject_class->set_property = gst_multi_fd_sink_set_property;
373 gobject_class->get_property = gst_multi_fd_sink_get_property;
374 gobject_class->finalize = gst_multi_fd_sink_finalize;
376 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
377 g_param_spec_enum ("protocol", "Protocol", "The protocol to wrap data in",
378 GST_TYPE_TCP_PROTOCOL, DEFAULT_PROTOCOL, G_PARAM_READWRITE));
379 g_object_class_install_property (gobject_class, PROP_MODE,
380 g_param_spec_enum ("mode", "Mode",
381 "The mode for selecting activity on the fds", GST_TYPE_FDSET_MODE,
382 DEFAULT_MODE, G_PARAM_READWRITE));
384 g_object_class_install_property (gobject_class, PROP_BUFFERS_MAX,
385 g_param_spec_int ("buffers-max", "Buffers max",
386 "max number of buffers to queue for a client (-1 = no limit)", -1,
387 G_MAXINT, DEFAULT_BUFFERS_MAX, G_PARAM_READWRITE));
388 g_object_class_install_property (gobject_class,
389 PROP_BUFFERS_SOFT_MAX, g_param_spec_int ("buffers-soft-max",
391 "Recover client when going over this limit (-1 = no limit)", -1,
392 G_MAXINT, DEFAULT_BUFFERS_SOFT_MAX, G_PARAM_READWRITE));
394 g_object_class_install_property (gobject_class, PROP_BYTES_MIN,
395 g_param_spec_int ("bytes-min", "Bytes min",
396 "min number of bytes to queue (-1 = as little as possible)", -1,
397 G_MAXINT, DEFAULT_BYTES_MIN, G_PARAM_READWRITE));
398 g_object_class_install_property (gobject_class, PROP_TIME_MIN,
399 g_param_spec_int64 ("time-min", "Time min",
400 "min number of time to queue (-1 = as little as possible)", -1,
401 G_MAXINT64, DEFAULT_TIME_MIN, G_PARAM_READWRITE));
402 g_object_class_install_property (gobject_class, PROP_BUFFERS_MIN,
403 g_param_spec_int ("buffers-min", "Buffers min",
404 "min number of buffers to queue (-1 = as few as possible)", -1,
405 G_MAXINT, DEFAULT_BUFFERS_MIN, G_PARAM_READWRITE));
407 g_object_class_install_property (gobject_class, PROP_UNIT_TYPE,
408 g_param_spec_enum ("unit-type", "Units type",
409 "The unit to measure the max/soft-max/queued properties",
410 GST_TYPE_UNIT_TYPE, DEFAULT_UNIT_TYPE, G_PARAM_READWRITE));
411 g_object_class_install_property (gobject_class, PROP_UNITS_MAX,
412 g_param_spec_int64 ("units-max", "Units max",
413 "max number of units to queue (-1 = no limit)", -1, G_MAXINT64,
414 DEFAULT_UNITS_MAX, G_PARAM_READWRITE));
415 g_object_class_install_property (gobject_class, PROP_UNITS_SOFT_MAX,
416 g_param_spec_int64 ("units-soft-max", "Units soft max",
417 "Recover client when going over this limit (-1 = no limit)", -1,
418 G_MAXINT64, DEFAULT_UNITS_SOFT_MAX, G_PARAM_READWRITE));
420 g_object_class_install_property (gobject_class, PROP_BUFFERS_QUEUED,
421 g_param_spec_uint ("buffers-queued", "Buffers queued",
422 "Number of buffers currently queued", 0, G_MAXUINT, 0,
425 g_object_class_install_property (gobject_class, PROP_BYTES_QUEUED,
426 g_param_spec_uint ("bytes-queued", "Bytes queued",
427 "Number of bytes currently queued", 0, G_MAXUINT, 0,
429 g_object_class_install_property (gobject_class, PROP_TIME_QUEUED,
430 g_param_spec_uint64 ("time-queued", "Time queued",
431 "Number of time currently queued", 0, G_MAXUINT64, 0,
435 g_object_class_install_property (gobject_class, PROP_RECOVER_POLICY,
436 g_param_spec_enum ("recover-policy", "Recover Policy",
437 "How to recover when client reaches the soft max",
438 GST_TYPE_RECOVER_POLICY, DEFAULT_RECOVER_POLICY, G_PARAM_READWRITE));
439 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
440 g_param_spec_uint64 ("timeout", "Timeout",
441 "Maximum inactivity timeout in nanoseconds for a client (0 = no limit)",
442 0, G_MAXUINT64, DEFAULT_TIMEOUT, G_PARAM_READWRITE));
443 g_object_class_install_property (gobject_class, PROP_SYNC_METHOD,
444 g_param_spec_enum ("sync-method", "Sync Method",
445 "How to sync new clients to the stream",
446 GST_TYPE_SYNC_METHOD, DEFAULT_SYNC_METHOD, G_PARAM_READWRITE));
447 g_object_class_install_property (gobject_class, PROP_BYTES_TO_SERVE,
448 g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
449 "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
451 g_object_class_install_property (gobject_class, PROP_BYTES_SERVED,
452 g_param_spec_uint64 ("bytes-served", "Bytes served",
453 "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
456 g_object_class_install_property (gobject_class, PROP_BURST_UNIT,
457 g_param_spec_enum ("burst-unit", "Burst unit",
458 "The format of the burst units (when sync-method is burst[[-with]-keyframe])",
459 GST_TYPE_UNIT_TYPE, DEFAULT_BURST_UNIT, G_PARAM_READWRITE));
460 g_object_class_install_property (gobject_class, PROP_BURST_VALUE,
461 g_param_spec_uint64 ("burst-value", "Burst value",
462 "The amount of burst expressed in burst-unit",
463 0, G_MAXUINT64, DEFAULT_BURST_VALUE, G_PARAM_READWRITE));
466 * GstMultiFdSink::add:
467 * @gstmultifdsink: the multifdsink element to emit this signal on
468 * @fd: the file descriptor to add to multifdsink
470 * Hand the given open file descriptor to multifdsink to write to.
472 gst_multi_fd_sink_signals[SIGNAL_ADD] =
473 g_signal_new ("add", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
474 G_STRUCT_OFFSET (GstMultiFdSinkClass, add),
475 NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT);
477 * GstMultiFdSink::add-full:
478 * @gstmultifdsink: the multifdsink element to emit this signal on
479 * @fd: the file descriptor to add to multifdsink
480 * @keyframe: start bursting from a keyframe
481 * @unit_type_min: the unit-type of @value_min
482 * @value_min: the minimum amount of data to burst expressed in
483 * @unit_type_min units.
484 * @unit_type_max: the unit-type of @value_max
485 * @value_max: the maximum amount of data to burst expressed in
486 * @unit_type_max units.
488 * Hand the given open file descriptor to multifdsink to write to and
489 * specify the burst parameters for the new connection.
491 gst_multi_fd_sink_signals[SIGNAL_ADD_BURST] =
492 g_signal_new ("add-full", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
493 G_STRUCT_OFFSET (GstMultiFdSinkClass, add_full),
494 NULL, NULL, gst_tcp_marshal_VOID__INT_BOOLEAN_INT_UINT64_INT_UINT64,
495 G_TYPE_NONE, 6, G_TYPE_INT, G_TYPE_BOOLEAN, GST_TYPE_UNIT_TYPE,
496 G_TYPE_UINT64, GST_TYPE_UNIT_TYPE, G_TYPE_UINT64);
498 * GstMultiFdSink::remove:
499 * @gstmultifdsink: the multifdsink element to emit this signal on
500 * @fd: the file descriptor to remove from multifdsink
502 * Remove the given open file descriptor from multifdsink.
504 gst_multi_fd_sink_signals[SIGNAL_REMOVE] =
505 g_signal_new ("remove", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
506 G_STRUCT_OFFSET (GstMultiFdSinkClass, remove),
507 NULL, NULL, gst_tcp_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT);
509 * GstMultiFdSink::clear:
510 * @gstmultifdsink: the multifdsink element to emit this signal on
512 * Remove all file descriptors from multifdsink. Since multifdsink did not
513 * open fd's itself, it does not explicitly close the fd. The application
514 * should do so by connecting to the client-fd-removed callback.
516 gst_multi_fd_sink_signals[SIGNAL_CLEAR] =
517 g_signal_new ("clear", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
518 G_STRUCT_OFFSET (GstMultiFdSinkClass, clear),
519 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
522 * GstMultiFdSink::get-stats:
523 * @gstmultifdsink: the multifdsink element to emit this signal on
524 * @fd: the file descriptor to get stats of from multifdsink
526 * Get statistics about @fd. This function returns a GValueArray to ease
527 * automatic wrapping for bindings.
529 * Returns: a GValueArray with the statistics. The array contains guint64
530 * values that represent respectively: total number of bytes sent, time
531 * when the client was added, time when the client was
532 * disconnected/removed, time the client is/was active, last activity
533 * time (in epoch seconds), number of buffers dropped.
534 * All times are expressed in nanoseconds (GstClockTime).
535 * The array can be 0-length if the client was not found.
537 gst_multi_fd_sink_signals[SIGNAL_GET_STATS] =
538 g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
539 G_STRUCT_OFFSET (GstMultiFdSinkClass, get_stats),
540 NULL, NULL, gst_tcp_marshal_BOXED__INT, G_TYPE_VALUE_ARRAY, 1,
544 * GstMultiFdSink::client-added:
545 * @gstmultifdsink: the multifdsink element that emitted this signal
546 * @fd: the file descriptor that was added to multifdsink
548 * The given file descriptor was added to multifdsink. This signal will
549 * be emitted from the streaming thread so application should be prepared
552 gst_multi_fd_sink_signals[SIGNAL_CLIENT_ADDED] =
553 g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
554 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiFdSinkClass, client_added),
555 NULL, NULL, gst_tcp_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT);
557 * GstMultiFdSink::client-removed:
558 * @gstmultifdsink: the multifdsink element that emitted this signal
559 * @fd: the file descriptor that is to be removed from multifdsink
560 * @status: the reason why the client was removed
562 * The given file descriptor is about to be removed from multifdsink. This
563 * signal will be emitted from the streaming thread so applications should
564 * be prepared for that.
566 * @gstmultifdsink still holds a handle to @fd so it is possible to call
567 * the get-stats signal from this callback. For the same reason it is
568 * not safe to close() and reuse @fd in this callback.
570 gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED] =
571 g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
572 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiFdSinkClass,
573 client_removed), NULL, NULL, gst_tcp_marshal_VOID__INT_BOXED,
574 G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CLIENT_STATUS);
576 * GstMultiFdSink::client-fd-removed:
577 * @gstmultifdsink: the multifdsink element that emitted this signal
578 * @fd: the file descriptor that was removed from multifdsink
580 * The given file descriptor was removed from multifdsink. This signal will
581 * be emitted from the streaming thread so applications should be prepared
584 * In this callback, @gstmultifdsink has removed all the information
585 * associated with @fd and it is therefore not possible to call get-stats
586 * with @fd. It is however safe to close() and reuse @fd in the callback.
590 gst_multi_fd_sink_signals[SIGNAL_CLIENT_FD_REMOVED] =
591 g_signal_new ("client-fd-removed", G_TYPE_FROM_CLASS (klass),
592 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiFdSinkClass,
593 client_fd_removed), NULL, NULL, gst_tcp_marshal_VOID__INT,
594 G_TYPE_NONE, 1, G_TYPE_INT);
596 gstelement_class->change_state =
597 GST_DEBUG_FUNCPTR (gst_multi_fd_sink_change_state);
599 gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_render);
601 klass->add = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_add);
602 klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_add_full);
603 klass->remove = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_remove);
604 klass->clear = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_clear);
605 klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_get_stats);
607 GST_DEBUG_CATEGORY_INIT (multifdsink_debug, "multifdsink", 0, "FD sink");
611 gst_multi_fd_sink_init (GstMultiFdSink * this, GstMultiFdSinkClass * klass)
613 GST_OBJECT_FLAG_UNSET (this, GST_MULTI_FD_SINK_OPEN);
615 this->protocol = DEFAULT_PROTOCOL;
616 this->mode = DEFAULT_MODE;
618 CLIENTS_LOCK_INIT (this);
619 this->clients = NULL;
620 this->fd_hash = g_hash_table_new (g_int_hash, g_int_equal);
622 this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
623 this->unit_type = DEFAULT_UNIT_TYPE;
624 this->units_max = DEFAULT_UNITS_MAX;
625 this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
626 this->time_min = DEFAULT_TIME_MIN;
627 this->bytes_min = DEFAULT_BYTES_MIN;
628 this->buffers_min = DEFAULT_BUFFERS_MIN;
629 this->recover_policy = DEFAULT_RECOVER_POLICY;
631 this->timeout = DEFAULT_TIMEOUT;
632 this->def_sync_method = DEFAULT_SYNC_METHOD;
633 this->def_burst_unit = DEFAULT_BURST_UNIT;
634 this->def_burst_value = DEFAULT_BURST_VALUE;
636 this->header_flags = 0;
640 gst_multi_fd_sink_finalize (GObject * object)
642 GstMultiFdSink *this;
644 this = GST_MULTI_FD_SINK (object);
646 CLIENTS_LOCK_FREE (this);
647 g_hash_table_destroy (this->fd_hash);
648 g_array_free (this->bufqueue, TRUE);
650 G_OBJECT_CLASS (parent_class)->finalize (object);
653 /* "add-full" signal implementation */
655 gst_multi_fd_sink_add_full (GstMultiFdSink * sink, int fd,
656 GstSyncMethod sync_method, GstUnitType min_unit, guint64 min_value,
657 GstUnitType max_unit, guint64 max_value)
659 GstTCPClient *client;
665 GST_DEBUG_OBJECT (sink, "[fd %5d] adding client, sync_method %d, "
666 "min_unit %d, min_value %" G_GUINT64_FORMAT
667 ", max_unit %d, max_value %" G_GUINT64_FORMAT, fd, sync_method,
668 min_unit, min_value, max_unit, max_value);
670 /* do limits check if we can */
671 if (min_unit == max_unit) {
672 if (max_value != -1 && min_value != -1 && max_value < min_value)
676 /* create client datastructure */
677 client = g_new0 (GstTCPClient, 1);
679 client->status = GST_CLIENT_STATUS_OK;
681 client->bufoffset = 0;
682 client->sending = NULL;
683 client->bytes_sent = 0;
684 client->dropped_buffers = 0;
685 client->avg_queue_size = 0;
686 client->new_connection = TRUE;
687 client->burst_min_unit = min_unit;
688 client->burst_min_value = min_value;
689 client->burst_max_unit = max_unit;
690 client->burst_max_value = max_value;
691 client->sync_method = sync_method;
692 client->currently_removing = FALSE;
694 /* update start time */
695 g_get_current_time (&now);
696 client->connect_time = GST_TIMEVAL_TO_TIME (now);
697 client->disconnect_time = 0;
698 /* set last activity time to connect time */
699 client->last_activity_time = client->connect_time;
703 /* check the hash to find a duplicate fd */
704 clink = g_hash_table_lookup (sink->fd_hash, &client->fd.fd);
708 /* we can add the fd now */
709 clink = sink->clients = g_list_prepend (sink->clients, client);
710 g_hash_table_insert (sink->fd_hash, &client->fd.fd, clink);
711 sink->clients_cookie++;
713 /* set the socket to non blocking */
714 res = fcntl (fd, F_SETFL, O_NONBLOCK);
715 /* we always read from a client */
716 gst_fdset_add_fd (sink->fdset, &client->fd);
718 /* we don't try to read from write only fds */
719 flags = fcntl (fd, F_GETFL, 0);
720 if ((flags & O_ACCMODE) != O_WRONLY) {
721 gst_fdset_fd_ctl_read (sink->fdset, &client->fd, TRUE);
723 /* figure out the mode, can't use send() for non sockets */
724 res = fstat (fd, &statbuf);
725 if (S_ISSOCK (statbuf.st_mode)) {
726 client->is_socket = TRUE;
729 SEND_COMMAND (sink, CONTROL_RESTART);
731 CLIENTS_UNLOCK (sink);
733 g_signal_emit (G_OBJECT (sink),
734 gst_multi_fd_sink_signals[SIGNAL_CLIENT_ADDED], 0, fd);
741 GST_WARNING_OBJECT (sink,
742 "[fd %5d] wrong values min =%" G_GUINT64_FORMAT ", max=%"
743 G_GUINT64_FORMAT ", unit %d specified when adding client", fd,
744 min_value, max_value, min_unit);
749 client->status = GST_CLIENT_STATUS_DUPLICATE;
750 CLIENTS_UNLOCK (sink);
751 GST_WARNING_OBJECT (sink, "[fd %5d] duplicate client found, refusing", fd);
752 g_signal_emit (G_OBJECT (sink),
753 gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED], 0, fd,
760 /* "add" signal implemntation */
762 gst_multi_fd_sink_add (GstMultiFdSink * sink, int fd)
764 gst_multi_fd_sink_add_full (sink, fd, sink->def_sync_method,
765 sink->def_burst_unit, sink->def_burst_value, sink->def_burst_unit, -1);
768 /* "remove" signal implementation */
770 gst_multi_fd_sink_remove (GstMultiFdSink * sink, int fd)
774 GST_DEBUG_OBJECT (sink, "[fd %5d] removing client", fd);
777 clink = g_hash_table_lookup (sink->fd_hash, &fd);
779 GstTCPClient *client = (GstTCPClient *) clink->data;
781 if (client->status != GST_CLIENT_STATUS_OK) {
782 GST_INFO_OBJECT (sink,
783 "[fd %5d] Client already disconnecting with status %d",
788 client->status = GST_CLIENT_STATUS_REMOVED;
789 gst_multi_fd_sink_remove_client_link (sink, clink);
790 SEND_COMMAND (sink, CONTROL_RESTART);
792 GST_WARNING_OBJECT (sink, "[fd %5d] no client with this fd found!", fd);
796 CLIENTS_UNLOCK (sink);
799 /* can be called both through the signal (i.e. from any thread) or when
800 * stopping, after the writing thread has shut down */
802 gst_multi_fd_sink_clear (GstMultiFdSink * sink)
804 GList *clients, *next;
807 GST_DEBUG_OBJECT (sink, "clearing all clients");
811 cookie = sink->clients_cookie;
812 for (clients = sink->clients; clients; clients = next) {
813 GstTCPClient *client;
815 if (cookie != sink->clients_cookie) {
816 GST_DEBUG_OBJECT (sink, "cookie changed while removing all clients");
820 client = (GstTCPClient *) clients->data;
821 next = g_list_next (clients);
823 client->status = GST_CLIENT_STATUS_REMOVED;
824 gst_multi_fd_sink_remove_client_link (sink, clients);
826 SEND_COMMAND (sink, CONTROL_RESTART);
827 CLIENTS_UNLOCK (sink);
830 /* "get-stats" signal implementation
831 * the array returned contains:
833 * guint64 : bytes_sent
834 * guint64 : connect time (in nanoseconds, since Epoch)
835 * guint64 : disconnect time (in nanoseconds, since Epoch)
836 * guint64 : time the client is/was connected (in nanoseconds)
837 * guint64 : last activity time (in nanoseconds, since Epoch)
838 * guint64 : buffers dropped due to recovery
841 gst_multi_fd_sink_get_stats (GstMultiFdSink * sink, int fd)
843 GstTCPClient *client;
844 GValueArray *result = NULL;
848 clink = g_hash_table_lookup (sink->fd_hash, &fd);
852 client = (GstTCPClient *) clink->data;
853 if (client != NULL) {
854 GValue value = { 0 };
857 result = g_value_array_new (5);
859 g_value_init (&value, G_TYPE_UINT64);
860 g_value_set_uint64 (&value, client->bytes_sent);
861 result = g_value_array_append (result, &value);
862 g_value_unset (&value);
863 g_value_init (&value, G_TYPE_UINT64);
864 g_value_set_uint64 (&value, client->connect_time);
865 result = g_value_array_append (result, &value);
866 g_value_unset (&value);
867 if (client->disconnect_time == 0) {
870 g_get_current_time (&nowtv);
872 interval = GST_TIMEVAL_TO_TIME (nowtv) - client->connect_time;
874 interval = client->disconnect_time - client->connect_time;
876 g_value_init (&value, G_TYPE_UINT64);
877 g_value_set_uint64 (&value, client->disconnect_time);
878 result = g_value_array_append (result, &value);
879 g_value_unset (&value);
880 g_value_init (&value, G_TYPE_UINT64);
881 g_value_set_uint64 (&value, interval);
882 result = g_value_array_append (result, &value);
883 g_value_unset (&value);
884 g_value_init (&value, G_TYPE_UINT64);
885 g_value_set_uint64 (&value, client->last_activity_time);
886 result = g_value_array_append (result, &value);
887 g_value_unset (&value);
888 g_value_init (&value, G_TYPE_UINT64);
889 g_value_set_uint64 (&value, client->dropped_buffers);
890 result = g_value_array_append (result, &value);
894 CLIENTS_UNLOCK (sink);
896 /* python doesn't like a NULL pointer yet */
897 if (result == NULL) {
898 GST_WARNING_OBJECT (sink, "[fd %5d] no client with this found!", fd);
899 result = g_value_array_new (0);
905 /* should be called with the clientslock helt.
906 * Note that we don't close the fd as we didn't open it in the first
907 * place. An application should connect to the client-fd-removed signal and
908 * close the fd itself.
911 gst_multi_fd_sink_remove_client_link (GstMultiFdSink * sink, GList * link)
915 GstTCPClient *client = (GstTCPClient *) link->data;
916 GstMultiFdSinkClass *fclass;
918 fclass = GST_MULTI_FD_SINK_GET_CLASS (sink);
922 if (client->currently_removing) {
923 GST_WARNING_OBJECT (sink, "[fd %5d] client is already being removed", fd);
926 client->currently_removing = TRUE;
929 /* FIXME: if we keep track of ip we can log it here and signal */
930 switch (client->status) {
931 case GST_CLIENT_STATUS_OK:
932 GST_WARNING_OBJECT (sink, "[fd %5d] removing client %p for no reason",
935 case GST_CLIENT_STATUS_CLOSED:
936 GST_DEBUG_OBJECT (sink, "[fd %5d] removing client %p because of close",
939 case GST_CLIENT_STATUS_REMOVED:
940 GST_DEBUG_OBJECT (sink,
941 "[fd %5d] removing client %p because the app removed it", fd, client);
943 case GST_CLIENT_STATUS_SLOW:
944 GST_INFO_OBJECT (sink,
945 "[fd %5d] removing client %p because it was too slow", fd, client);
947 case GST_CLIENT_STATUS_ERROR:
948 GST_WARNING_OBJECT (sink,
949 "[fd %5d] removing client %p because of error", fd, client);
952 GST_WARNING_OBJECT (sink,
953 "[fd %5d] removing client %p with invalid reason", fd, client);
957 gst_fdset_remove_fd (sink->fdset, &client->fd);
959 g_get_current_time (&now);
960 client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
962 /* free client buffers */
963 g_slist_foreach (client->sending, (GFunc) gst_mini_object_unref, NULL);
964 g_slist_free (client->sending);
965 client->sending = NULL;
968 gst_caps_unref (client->caps);
971 /* unlock the mutex before signaling because the signal handler
972 * might query some properties */
973 CLIENTS_UNLOCK (sink);
975 g_signal_emit (G_OBJECT (sink),
976 gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED], 0, fd, client->status);
978 /* lock again before we remove the client completely */
981 /* fd cannot be reused in the above signal callback so we can safely
982 * remove it from the hashtable here */
983 if (!g_hash_table_remove (sink->fd_hash, &client->fd.fd)) {
984 GST_WARNING_OBJECT (sink,
985 "[fd %5d] error removing client %p from hash", client->fd.fd, client);
987 /* after releasing the lock above, the link could be invalid, more
988 * precisely, the next and prev pointers could point to invalid list
989 * links. One optimisation could be to add a cookie to the linked list
990 * and take a shortcut when it did not change between unlocking and locking
991 * our mutex. For now we just walk the list again. */
992 sink->clients = g_list_remove (sink->clients, client);
993 sink->clients_cookie++;
996 fclass->removed (sink, client->fd.fd);
999 CLIENTS_UNLOCK (sink);
1001 /* and the fd is really gone now */
1002 g_signal_emit (G_OBJECT (sink),
1003 gst_multi_fd_sink_signals[SIGNAL_CLIENT_FD_REMOVED], 0, fd);
1005 CLIENTS_LOCK (sink);
1008 /* handle a read on a client fd,
1009 * which either indicates a close or should be ignored
1010 * returns FALSE if some error occured or the client closed. */
1012 gst_multi_fd_sink_handle_client_read (GstMultiFdSink * sink,
1013 GstTCPClient * client)
1020 if (ioctl (fd, FIONREAD, &avail) < 0)
1023 GST_DEBUG_OBJECT (sink, "[fd %5d] select reports client read of %d bytes",
1029 /* client sent close, so remove it */
1030 GST_DEBUG_OBJECT (sink, "[fd %5d] client asked for close, removing", fd);
1031 client->status = GST_CLIENT_STATUS_CLOSED;
1033 } else if (avail < 0) {
1034 GST_WARNING_OBJECT (sink, "[fd %5d] avail < 0, removing", fd);
1035 client->status = GST_CLIENT_STATUS_ERROR;
1041 /* just Read 'n' Drop, could also just drop the client as it's not supposed
1042 * to write to us except for closing the socket, I guess it's because we
1043 * like to listen to our customers. */
1045 /* this is the maximum we can read */
1046 gint to_read = MIN (avail, 512);
1048 GST_DEBUG_OBJECT (sink, "[fd %5d] client wants us to read %d bytes",
1051 nread = read (fd, dummy, to_read);
1053 GST_WARNING_OBJECT (sink, "[fd %5d] could not read %d bytes: %s (%d)",
1054 fd, to_read, g_strerror (errno), errno);
1055 client->status = GST_CLIENT_STATUS_ERROR;
1058 } else if (nread == 0) {
1059 GST_WARNING_OBJECT (sink, "[fd %5d] 0 bytes in read, removing", fd);
1060 client->status = GST_CLIENT_STATUS_ERROR;
1073 GST_WARNING_OBJECT (sink, "[fd %5d] ioctl failed: %s (%d)",
1074 fd, g_strerror (errno), errno);
1075 client->status = GST_CLIENT_STATUS_ERROR;
1080 /* Queue raw data for this client, creating a new buffer.
1081 * This takes ownership of the data by
1082 * setting it as GST_BUFFER_MALLOCDATA() on the created buffer so
1083 * be sure to pass g_free()-able @data.
1086 gst_multi_fd_sink_client_queue_data (GstMultiFdSink * sink,
1087 GstTCPClient * client, gchar * data, gint len)
1091 buf = gst_buffer_new ();
1092 GST_BUFFER_DATA (buf) = (guint8 *) data;
1093 GST_BUFFER_MALLOCDATA (buf) = (guint8 *) data;
1094 GST_BUFFER_SIZE (buf) = len;
1096 GST_LOG_OBJECT (sink, "[fd %5d] queueing data of length %d",
1097 client->fd.fd, len);
1099 client->sending = g_slist_append (client->sending, buf);
1104 /* GDP-encode given caps and queue them for sending */
1106 gst_multi_fd_sink_client_queue_caps (GstMultiFdSink * sink,
1107 GstTCPClient * client, const GstCaps * caps)
1114 g_return_val_if_fail (caps != NULL, FALSE);
1116 string = gst_caps_to_string (caps);
1117 GST_DEBUG_OBJECT (sink, "[fd %5d] Queueing caps %s through GDP",
1118 client->fd.fd, string);
1121 if (!gst_dp_packet_from_caps (caps, sink->header_flags, &length, &header,
1123 GST_DEBUG_OBJECT (sink, "Could not create GDP packet from caps");
1126 gst_multi_fd_sink_client_queue_data (sink, client, (gchar *) header, length);
1128 length = gst_dp_header_payload_length (header);
1129 gst_multi_fd_sink_client_queue_data (sink, client, (gchar *) payload, length);
1135 is_sync_frame (GstMultiFdSink * sink, GstBuffer * buffer)
1137 if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1139 } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_IN_CAPS)) {
1146 /* queue the given buffer for the given client, possibly adding the GDP
1147 * header if GDP is being used */
1149 gst_multi_fd_sink_client_queue_buffer (GstMultiFdSink * sink,
1150 GstTCPClient * client, GstBuffer * buffer)
1154 /* TRUE: send them if the new caps have them */
1155 gboolean send_streamheader = FALSE;
1158 /* before we queue the buffer, we check if we need to queue streamheader
1159 * buffers (because it's a new client, or because they changed) */
1160 caps = gst_buffer_get_caps (buffer); /* cleaned up after streamheader */
1161 if (!client->caps) {
1162 GST_LOG_OBJECT (sink,
1163 "[fd %5d] no previous caps for this client, send streamheader",
1165 send_streamheader = TRUE;
1166 client->caps = gst_caps_ref (caps);
1168 /* there were previous caps recorded, so compare */
1169 if (!gst_caps_is_equal (caps, client->caps)) {
1170 const GValue *sh1, *sh2;
1172 /* caps are not equal, but could still have the same streamheader */
1173 s = gst_caps_get_structure (caps, 0);
1174 if (!gst_structure_has_field (s, "streamheader")) {
1175 /* no new streamheader, so nothing new to send */
1176 GST_LOG_OBJECT (sink,
1177 "[fd %5d] new caps do not have streamheader, not sending",
1180 /* there is a new streamheader */
1181 s = gst_caps_get_structure (client->caps, 0);
1182 if (!gst_structure_has_field (s, "streamheader")) {
1183 /* no previous streamheader, so send the new one */
1184 GST_LOG_OBJECT (sink,
1185 "[fd %5d] previous caps did not have streamheader, sending",
1187 send_streamheader = TRUE;
1189 /* both old and new caps have streamheader set */
1190 sh1 = gst_structure_get_value (s, "streamheader");
1191 s = gst_caps_get_structure (caps, 0);
1192 sh2 = gst_structure_get_value (s, "streamheader");
1193 if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1194 GST_LOG_OBJECT (sink,
1195 "[fd %5d] new streamheader different from old, sending",
1197 send_streamheader = TRUE;
1202 /* Replace the old caps */
1203 gst_caps_unref (client->caps);
1204 client->caps = gst_caps_ref (caps);
1207 if (G_UNLIKELY (send_streamheader)) {
1212 GST_LOG_OBJECT (sink,
1213 "[fd %5d] sending streamheader from caps %" GST_PTR_FORMAT,
1214 client->fd.fd, caps);
1215 s = gst_caps_get_structure (caps, 0);
1216 if (!gst_structure_has_field (s, "streamheader")) {
1217 GST_LOG_OBJECT (sink,
1218 "[fd %5d] no new streamheader, so nothing to send", client->fd.fd);
1220 GST_LOG_OBJECT (sink,
1221 "[fd %5d] sending streamheader from caps %" GST_PTR_FORMAT,
1222 client->fd.fd, caps);
1223 sh = gst_structure_get_value (s, "streamheader");
1224 g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1225 buffers = g_value_peek_pointer (sh);
1226 for (i = 0; i < buffers->len; ++i) {
1230 bufval = &g_array_index (buffers, GValue, i);
1231 g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1232 buffer = g_value_peek_pointer (bufval);
1233 GST_LOG_OBJECT (sink,
1234 "[fd %5d] queueing streamheader buffer of length %d",
1235 client->fd.fd, GST_BUFFER_SIZE (buffer));
1236 gst_buffer_ref (buffer);
1238 if (sink->protocol == GST_TCP_PROTOCOL_GDP) {
1242 if (!gst_dp_header_from_buffer (buffer, sink->header_flags, &len,
1244 GST_DEBUG_OBJECT (sink,
1245 "[fd %5d] could not create header, removing client",
1249 gst_multi_fd_sink_client_queue_data (sink, client, (gchar *) header,
1253 client->sending = g_slist_append (client->sending, buffer);
1258 gst_caps_unref (caps);
1260 /* now we can send the buffer, possibly sending a GDP header first */
1261 if (sink->protocol == GST_TCP_PROTOCOL_GDP) {
1265 if (!gst_dp_header_from_buffer (buffer, sink->header_flags, &len, &header)) {
1266 GST_DEBUG_OBJECT (sink,
1267 "[fd %5d] could not create header, removing client", client->fd.fd);
1270 gst_multi_fd_sink_client_queue_data (sink, client, (gchar *) header, len);
1273 GST_LOG_OBJECT (sink, "[fd %5d] queueing buffer of length %d",
1274 client->fd.fd, GST_BUFFER_SIZE (buffer));
1276 gst_buffer_ref (buffer);
1277 client->sending = g_slist_append (client->sending, buffer);
1282 /* find the keyframe in the list of buffers starting the
1283 * search from @idx. @direction as -1 will search backwards,
1284 * 1 will search forwards.
1285 * Returns: the index or -1 if there is no keyframe after idx.
1288 find_syncframe (GstMultiFdSink * sink, gint idx, gint direction)
1290 gint i, len, result;
1292 /* take length of queued buffers */
1293 len = sink->bufqueue->len;
1295 /* assume we don't find a keyframe */
1298 /* then loop over all buffers to find the first keyframe */
1299 for (i = idx; i >= 0 && i < len; i += direction) {
1302 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1303 if (is_sync_frame (sink, buf)) {
1304 GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1313 #define find_next_syncframe(s,i) find_syncframe(s,i,1)
1314 #define find_prev_syncframe(s,i) find_syncframe(s,i,-1)
1316 /* Get the number of buffers from the buffer queue needed to satisfy
1317 * the maximum max in the configured units.
1318 * If units are not BUFFERS, and there are insufficient buffers in the
1319 * queue to satify the limit, return len(queue) + 1 */
1321 get_buffers_max (GstMultiFdSink * sink, gint64 max)
1323 switch (sink->unit_type) {
1324 case GST_UNIT_TYPE_BUFFERS:
1326 case GST_UNIT_TYPE_TIME:
1332 GstClockTime first = GST_CLOCK_TIME_NONE;
1334 len = sink->bufqueue->len;
1336 for (i = 0; i < len; i++) {
1337 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1338 if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1340 first = GST_BUFFER_TIMESTAMP (buf);
1342 diff = first - GST_BUFFER_TIMESTAMP (buf);
1350 case GST_UNIT_TYPE_BYTES:
1357 len = sink->bufqueue->len;
1359 for (i = 0; i < len; i++) {
1360 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1361 acc += GST_BUFFER_SIZE (buf);
1373 /* find the positions in the buffer queue where *_min and *_max
1376 /* count the amount of data in the buffers and return the index
1377 * that satifies the given limits.
1379 * Returns: index @idx in the buffer queue so that the given limits are
1380 * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1381 * enough data was in the queue.
1383 * FIXME, this code might now work if any of the units is in buffers...
1386 find_limits (GstMultiFdSink * sink,
1387 gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1388 gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1390 GstClockTime first, time;
1392 gboolean result, max_hit;
1394 /* take length of queue */
1395 len = sink->bufqueue->len;
1397 /* this must hold */
1400 GST_LOG_OBJECT (sink,
1401 "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1402 ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1403 buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1404 GST_TIME_ARGS (time_max));
1406 /* do the trivial buffer limit test */
1407 if (buffers_min != -1 && len < buffers_min) {
1414 /* else count bytes and time */
1423 /* loop through the buffers, when a limit is ok, mark it
1424 * as -1, we have at least one buffer in the queue. */
1428 /* if we checked all min limits, update result */
1429 if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1430 /* don't go below 0 */
1431 *min_idx = MAX (i - 1, 0);
1433 /* if we reached one max limit break out */
1435 /* i > 0 when we get here, we subtract one to get the position
1436 * of the previous buffer. */
1438 /* we have valid complete result if we found a min_idx too */
1439 result = *min_idx != -1;
1442 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1444 bytes += GST_BUFFER_SIZE (buf);
1446 /* take timestamp and save for the base first timestamp */
1447 if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1448 GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1449 GST_TIME_ARGS (time));
1453 /* increase max usage if we did not fill enough. Note that
1454 * buffers are sorted from new to old, so the first timestamp is
1455 * bigger than the next one. */
1456 if (time_min != -1 && first - time >= time_min)
1458 if (time_max != -1 && first - time >= time_max)
1461 GST_DEBUG_OBJECT (sink, "No timestamp on buffer");
1463 /* time is OK or unknown, check and increase if not enough bytes */
1464 if (bytes_min != -1) {
1465 if (bytes >= bytes_min)
1468 if (bytes_max != -1) {
1469 if (bytes >= bytes_max) {
1477 /* if we did not hit the max or min limit, set to buffer size */
1480 /* make sure min does not exceed max */
1482 *min_idx = *max_idx;
1487 /* parse the unit/value pair and assign it to the result value of the
1488 * right type, leave the other values untouched
1490 * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1493 assign_value (GstUnitType unit, guint64 value, gint * bytes, gint * buffers,
1494 GstClockTime * time)
1496 gboolean res = TRUE;
1498 /* set only the limit of the given format to the given value */
1500 case GST_UNIT_TYPE_BUFFERS:
1501 *buffers = (gint) value;
1503 case GST_UNIT_TYPE_TIME:
1506 case GST_UNIT_TYPE_BYTES:
1507 *bytes = (gint) value;
1509 case GST_UNIT_TYPE_UNDEFINED:
1517 /* count the index in the buffer queue to satisfy the given unit
1518 * and value pair starting from buffer at index 0.
1520 * Returns: TRUE if there was enough data in the queue to satisfy the
1521 * burst values. @idx contains the index in the buffer that contains enough
1522 * data to satisfy the limits or the last buffer in the queue when the
1523 * function returns FALSE.
1526 count_burst_unit (GstMultiFdSink * sink, gint * min_idx, GstUnitType min_unit,
1527 guint64 min_value, gint * max_idx, GstUnitType max_unit, guint64 max_value)
1529 gint bytes_min = -1, buffers_min = -1;
1530 gint bytes_max = -1, buffers_max = -1;
1531 GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1533 assign_value (min_unit, min_value, &bytes_min, &buffers_min, &time_min);
1534 assign_value (max_unit, max_value, &bytes_max, &buffers_max, &time_max);
1536 return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1537 max_idx, bytes_max, buffers_max, time_max);
1540 /* decide where in the current buffer queue this new client should start
1541 * receiving buffers from.
1542 * This function is called whenever a client is connected and has not yet
1543 * received a buffer.
1544 * If this returns -1, it means that we haven't found a good point to
1545 * start streaming from yet, and this function should be called again later
1546 * when more buffers have arrived.
1549 gst_multi_fd_sink_new_client (GstMultiFdSink * sink, GstTCPClient * client)
1553 GST_DEBUG_OBJECT (sink,
1554 "[fd %5d] new client, deciding where to start in queue", client->fd.fd);
1555 switch (client->sync_method) {
1556 case GST_SYNC_METHOD_LATEST:
1557 /* no syncing, we are happy with whatever the client is going to get */
1558 result = client->bufpos;
1559 GST_DEBUG_OBJECT (sink,
1560 "[fd %5d] SYNC_METHOD_LATEST, position %d", client->fd.fd, result);
1562 case GST_SYNC_METHOD_NEXT_KEYFRAME:
1564 /* if one of the new buffers (between client->bufpos and 0) in the queue
1565 * is a sync point, we can proceed, otherwise we need to keep waiting */
1566 GST_LOG_OBJECT (sink,
1567 "[fd %5d] new client, bufpos %d, waiting for keyframe", client->fd.fd,
1570 result = find_prev_syncframe (sink, client->bufpos);
1572 GST_DEBUG_OBJECT (sink,
1573 "[fd %5d] SYNC_METHOD_NEXT_KEYFRAME: result %d",
1574 client->fd.fd, result);
1578 /* client is not on a syncbuffer, need to skip these buffers and
1580 GST_LOG_OBJECT (sink,
1581 "[fd %5d] new client, skipping buffer(s), no syncpoint found",
1583 client->bufpos = -1;
1586 case GST_SYNC_METHOD_LATEST_KEYFRAME:
1588 GST_DEBUG_OBJECT (sink,
1589 "[fd %5d] SYNC_METHOD_LATEST_KEYFRAME", client->fd.fd);
1591 /* for new clients we initially scan the complete buffer queue for
1592 * a sync point when a buffer is added. If we don't find a keyframe,
1593 * we need to wait for the next keyframe and so we change the client's
1594 * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1596 result = find_next_syncframe (sink, 0);
1598 GST_DEBUG_OBJECT (sink,
1599 "[fd %5d] SYNC_METHOD_LATEST_KEYFRAME: result %d", client->fd.fd,
1604 GST_DEBUG_OBJECT (sink,
1605 "[fd %5d] SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1606 "switching to SYNC_METHOD_NEXT_KEYFRAME", client->fd.fd);
1607 /* throw client to the waiting state */
1608 client->bufpos = -1;
1609 /* and make client sync to next keyframe */
1610 client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1613 case GST_SYNC_METHOD_BURST:
1618 /* move to the position where we satisfy the client's burst
1619 * parameters. If we could not satisfy the parameters because there
1620 * is not enough data, we just send what we have (which is in result).
1621 * We use the max value to limit the search
1623 ok = count_burst_unit (sink, &result, client->burst_min_unit,
1624 client->burst_min_value, &max, client->burst_max_unit,
1625 client->burst_max_value);
1626 GST_DEBUG_OBJECT (sink,
1627 "[fd %5d] SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1628 client->fd.fd, ok, result);
1630 GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1632 /* we hit the max and it is below the min, use that then */
1633 if (max != -1 && max <= result) {
1634 result = MAX (max - 1, 0);
1635 GST_DEBUG_OBJECT (sink,
1636 "[fd %5d] SYNC_METHOD_BURST: result above max, taken down to %d",
1637 client->fd.fd, result);
1641 case GST_SYNC_METHOD_BURST_KEYFRAME:
1644 gint min_idx, max_idx;
1645 gint next_syncframe, prev_syncframe;
1649 * _always_ start sending a keyframe to the client. We first search
1650 * a keyframe between min/max limits. If there is none, we send it the
1651 * last keyframe before min. If there is none, the behaviour is like
1654 /* gather burst limits */
1655 ok = count_burst_unit (sink, &min_idx, client->burst_min_unit,
1656 client->burst_min_value, &max_idx, client->burst_max_unit,
1657 client->burst_max_value);
1659 GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1661 /* first find a keyframe after min_idx */
1662 next_syncframe = find_next_syncframe (sink, min_idx);
1663 if (next_syncframe != -1 && next_syncframe < max_idx) {
1664 /* we have a valid keyframe and it's below the max */
1665 GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1666 result = next_syncframe;
1670 /* no valid keyframe, try to find one below min */
1671 prev_syncframe = find_prev_syncframe (sink, min_idx);
1672 if (prev_syncframe != -1) {
1673 GST_WARNING_OBJECT (sink,
1674 "using keyframe below min in BURST_KEYFRAME sync mode");
1675 result = prev_syncframe;
1679 /* no prev keyframe or not enough data */
1680 GST_WARNING_OBJECT (sink,
1681 "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1683 /* throw client to the waiting state */
1684 client->bufpos = -1;
1685 /* and make client sync to next keyframe */
1686 client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1690 case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1693 gint min_idx, max_idx;
1694 gint next_syncframe;
1696 /* BURST_WITH_KEYFRAME:
1698 * try to start sending a keyframe to the client. We first search
1699 * a keyframe between min/max limits. If there is none, we send it the
1700 * amount of data up 'till min.
1702 /* gather enough data to burst */
1703 ok = count_burst_unit (sink, &min_idx, client->burst_min_unit,
1704 client->burst_min_value, &max_idx, client->burst_max_unit,
1705 client->burst_max_value);
1707 GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1709 /* first find a keyframe after min_idx */
1710 next_syncframe = find_next_syncframe (sink, min_idx);
1711 if (next_syncframe != -1 && next_syncframe < max_idx) {
1712 /* we have a valid keyframe and it's below the max */
1713 GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1714 result = next_syncframe;
1718 /* no keyframe, send data from min_idx */
1719 GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1721 /* make sure we don't go over the max limit */
1722 if (max_idx != -1 && max_idx <= min_idx) {
1723 result = MAX (max_idx - 1, 0);
1731 g_warning ("unknown sync method %d", client->sync_method);
1732 result = client->bufpos;
1738 /* Handle a write on a client,
1739 * which indicates a read request from a client.
1741 * For each client we maintain a queue of GstBuffers that contain the raw bytes
1742 * we need to send to the client. In the case of the GDP protocol, we create
1743 * buffers out of the header bytes so that we can focus only on sending
1746 * We first check to see if we need to send caps (in GDP) and streamheaders.
1747 * If so, we queue them.
1749 * Then we run into the main loop that tries to send as many buffers as
1750 * possible. It will first exhaust the client->sending queue and if the queue
1751 * is empty, it will pick a buffer from the global queue.
1753 * Sending the buffers from the client->sending queue is basically writing
1754 * the bytes to the socket and maintaining a count of the bytes that were
1755 * sent. When the buffer is completely sent, it is removed from the
1756 * client->sending queue and we try to pick a new buffer for sending.
1758 * When the sending returns a partial buffer we stop sending more data as
1759 * the next send operation could block.
1761 * This functions returns FALSE if some error occured.
1764 gst_multi_fd_sink_handle_client_write (GstMultiFdSink * sink,
1765 GstTCPClient * client)
1767 int fd = client->fd.fd;
1773 g_get_current_time (&nowtv);
1774 now = GST_TIMEVAL_TO_TIME (nowtv);
1776 /* when using GDP, first check if we have queued caps yet */
1777 if (sink->protocol == GST_TCP_PROTOCOL_GDP) {
1778 if (!client->caps_sent) {
1782 peer = gst_pad_get_peer (GST_BASE_SINK_PAD (sink));
1784 GST_WARNING_OBJECT (sink, "pad has no peer");
1787 gst_object_unref (peer);
1789 caps = gst_pad_get_negotiated_caps (GST_BASE_SINK_PAD (sink));
1791 GST_WARNING_OBJECT (sink, "pad caps not yet negotiated");
1795 /* queue caps for sending */
1796 res = gst_multi_fd_sink_client_queue_caps (sink, client, caps);
1798 gst_caps_unref (caps);
1801 GST_DEBUG_OBJECT (sink, "Failed queueing caps, removing client");
1804 client->caps_sent = TRUE;
1812 if (!client->sending) {
1813 /* client is not working on a buffer */
1814 if (client->bufpos == -1) {
1815 /* client is too fast, remove from write queue until new buffer is
1817 gst_fdset_fd_ctl_write (sink->fdset, &client->fd, FALSE);
1820 /* client can pick a buffer from the global queue */
1823 /* for new connections, we need to find a good spot in the
1824 * bufqueue to start streaming from */
1825 if (client->new_connection) {
1826 gint position = gst_multi_fd_sink_new_client (sink, client);
1828 if (position >= 0) {
1829 /* we got a valid spot in the queue */
1830 client->new_connection = FALSE;
1831 client->bufpos = position;
1833 /* cannot send data to this client yet */
1834 gst_fdset_fd_ctl_write (sink->fdset, &client->fd, FALSE);
1840 buf = g_array_index (sink->bufqueue, GstBuffer *, client->bufpos);
1842 GST_LOG_OBJECT (sink, "[fd %5d] client %p at position %d",
1843 fd, client, client->bufpos);
1845 /* queueing a buffer will ref it */
1846 gst_multi_fd_sink_client_queue_buffer (sink, client, buf);
1848 /* need to start from the first byte for this new buffer */
1849 client->bufoffset = 0;
1853 /* see if we need to send something */
1854 if (client->sending) {
1858 /* pick first buffer from list */
1859 head = GST_BUFFER (client->sending->data);
1860 maxsize = GST_BUFFER_SIZE (head) - client->bufoffset;
1862 /* try to write the complete buffer */
1864 #define FLAGS MSG_NOSIGNAL
1868 if (client->is_socket) {
1870 send (fd, GST_BUFFER_DATA (head) + client->bufoffset, maxsize,
1873 wrote = write (fd, GST_BUFFER_DATA (head) + client->bufoffset, maxsize);
1878 if (errno == EAGAIN) {
1879 /* nothing serious, resource was unavailable, try again later */
1881 } else if (errno == ECONNRESET) {
1882 goto connection_reset;
1887 if (wrote < maxsize) {
1888 /* partial write means that the client cannot read more and we should
1889 * stop sending more */
1890 GST_LOG_OBJECT (sink,
1891 "partial write on %d of %" G_GSSIZE_FORMAT " bytes", fd, wrote);
1892 client->bufoffset += wrote;
1895 /* complete buffer was written, we can proceed to the next one */
1896 client->sending = g_slist_remove (client->sending, head);
1897 gst_buffer_unref (head);
1898 /* make sure we start from byte 0 for the next buffer */
1899 client->bufoffset = 0;
1902 client->bytes_sent += wrote;
1903 client->last_activity_time = now;
1904 sink->bytes_served += wrote;
1914 GST_DEBUG_OBJECT (sink, "[fd %5d] connection reset by peer, removing", fd);
1915 client->status = GST_CLIENT_STATUS_CLOSED;
1920 GST_WARNING_OBJECT (sink,
1921 "[fd %5d] could not write, removing client: %s (%d)", fd,
1922 g_strerror (errno), errno);
1923 client->status = GST_CLIENT_STATUS_ERROR;
1928 /* calculate the new position for a client after recovery. This function
1929 * does not update the client position but merely returns the required
1933 gst_multi_fd_sink_recover_client (GstMultiFdSink * sink, GstTCPClient * client)
1937 GST_WARNING_OBJECT (sink,
1938 "[fd %5d] client %p is lagging at %d, recover using policy %d",
1939 client->fd.fd, client, client->bufpos, sink->recover_policy);
1941 switch (sink->recover_policy) {
1942 case GST_RECOVER_POLICY_NONE:
1943 /* do nothing, client will catch up or get kicked out when it reaches
1945 newbufpos = client->bufpos;
1947 case GST_RECOVER_POLICY_RESYNC_LATEST:
1948 /* move to beginning of queue */
1951 case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
1952 /* move to beginning of soft max */
1953 newbufpos = get_buffers_max (sink, sink->units_soft_max);
1955 case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
1956 /* find keyframe in buffers, we search backwards to find the
1957 * closest keyframe relative to what this client already received. */
1958 newbufpos = MIN (sink->bufqueue->len - 1,
1959 get_buffers_max (sink, sink->units_soft_max) - 1);
1961 while (newbufpos >= 0) {
1964 buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
1965 if (is_sync_frame (sink, buf)) {
1966 /* found a buffer that is not a delta unit */
1973 /* unknown recovery procedure */
1974 newbufpos = get_buffers_max (sink, sink->units_soft_max);
1980 /* Queue a buffer on the global queue.
1982 * This function adds the buffer to the front of a GArray. It removes the
1983 * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
1984 * Note that unreffing the buffer is not a problem as clients who
1985 * started writing out this buffer will still have a reference to it in the
1986 * client->sending queue.
1988 * After adding the buffer, we update all client positions in the queue. If
1989 * a client moves over the soft max, we start the recovery procedure for this
1990 * slow client. If it goes over the hard max, it is put into the slow list
1993 * Special care is taken of clients that were waiting for a new buffer (they
1994 * had a position of -1) because they can proceed after adding this new buffer.
1995 * This is done by adding the client back into the write fd_set and signalling
1996 * the select thread that the fd_set changed.
1999 gst_multi_fd_sink_queue_buffer (GstMultiFdSink * sink, GstBuffer * buf)
2001 GList *clients, *next;
2003 gboolean need_signal = FALSE;
2004 gint max_buffer_usage;
2008 gint max_buffers, soft_max_buffers;
2011 g_get_current_time (&nowtv);
2012 now = GST_TIMEVAL_TO_TIME (nowtv);
2014 CLIENTS_LOCK (sink);
2015 /* add buffer to queue */
2016 g_array_prepend_val (sink->bufqueue, buf);
2017 queuelen = sink->bufqueue->len;
2019 if (sink->units_max > 0)
2020 max_buffers = get_buffers_max (sink, sink->units_max);
2024 if (sink->units_soft_max > 0)
2025 soft_max_buffers = get_buffers_max (sink, sink->units_soft_max);
2027 soft_max_buffers = -1;
2028 GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
2031 /* then loop over the clients and update the positions */
2032 max_buffer_usage = 0;
2035 cookie = sink->clients_cookie;
2036 for (clients = sink->clients; clients; clients = next) {
2037 GstTCPClient *client;
2039 if (cookie != sink->clients_cookie) {
2040 GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
2044 client = (GstTCPClient *) clients->data;
2045 next = g_list_next (clients);
2048 GST_LOG_OBJECT (sink, "[fd %5d] client %p at position %d",
2049 client->fd.fd, client, client->bufpos);
2050 /* check soft max if needed, recover client */
2051 if (soft_max_buffers > 0 && client->bufpos >= soft_max_buffers) {
2054 newpos = gst_multi_fd_sink_recover_client (sink, client);
2055 if (newpos != client->bufpos) {
2056 client->dropped_buffers += client->bufpos - newpos;
2057 client->bufpos = newpos;
2058 client->discont = TRUE;
2059 GST_INFO_OBJECT (sink, "[fd %5d] client %p position reset to %d",
2060 client->fd.fd, client, client->bufpos);
2062 GST_INFO_OBJECT (sink,
2063 "[fd %5d] client %p not recovering position",
2064 client->fd.fd, client);
2067 /* check hard max and timeout, remove client */
2068 if ((max_buffers > 0 && client->bufpos >= max_buffers) ||
2070 && now - client->last_activity_time > sink->timeout)) {
2072 GST_WARNING_OBJECT (sink, "[fd %5d] client %p is too slow, removing",
2073 client->fd.fd, client);
2074 /* remove the client, the fd set will be cleared and the select thread
2075 * will be signaled */
2076 client->status = GST_CLIENT_STATUS_SLOW;
2077 /* set client to invalid position while being removed */
2078 client->bufpos = -1;
2079 gst_multi_fd_sink_remove_client_link (sink, clients);
2082 } else if (client->bufpos == 0 || client->new_connection) {
2083 /* can send data to this client now. need to signal the select thread that
2084 * the fd_set changed */
2085 gst_fdset_fd_ctl_write (sink->fdset, &client->fd, TRUE);
2088 /* keep track of maximum buffer usage */
2089 if (client->bufpos > max_buffer_usage) {
2090 max_buffer_usage = client->bufpos;
2094 /* make sure we respect bytes-min, buffers-min and time-min when they are set */
2098 GST_LOG_OBJECT (sink,
2099 "extending queue %d to respect time_min %" GST_TIME_FORMAT
2100 ", bytes_min %d, buffers_min %d", max_buffer_usage,
2101 GST_TIME_ARGS (sink->time_min), sink->bytes_min, sink->buffers_min);
2103 /* get index where the limits are ok, we don't really care if all limits
2104 * are ok, we just queue as much as we need. We also don't compare against
2105 * the max limits. */
2106 find_limits (sink, &usage, sink->bytes_min, sink->buffers_min,
2107 sink->time_min, &max, -1, -1, -1);
2109 max_buffer_usage = MAX (max_buffer_usage, usage + 1);
2110 GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
2113 /* now look for sync points and make sure there is at least one
2114 * sync point in the queue. We only do this if the LATEST_KEYFRAME or
2115 * BURST_KEYFRAME mode is selected */
2116 if (sink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
2117 sink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
2118 /* no point in searching beyond the queue length */
2119 gint limit = queuelen;
2122 /* no point in searching beyond the soft-max if any. */
2123 if (soft_max_buffers) {
2124 limit = MIN (limit, soft_max_buffers);
2126 GST_LOG_OBJECT (sink, "extending queue to include sync point, now at %d",
2128 for (i = 0; i < limit; i++) {
2129 buf = g_array_index (sink->bufqueue, GstBuffer *, i);
2130 if (is_sync_frame (sink, buf)) {
2131 /* found a sync frame, now extend the buffer usage to
2132 * include at least this frame. */
2133 max_buffer_usage = MAX (max_buffer_usage, i);
2137 GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
2140 GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
2142 /* nobody is referencing units after max_buffer_usage so we can
2143 * remove them from the queue. We remove them in reverse order as
2144 * this is the most optimal for GArray. */
2145 for (i = queuelen - 1; i > max_buffer_usage; i--) {
2148 /* queue exceeded max size */
2150 old = g_array_index (sink->bufqueue, GstBuffer *, i);
2151 sink->bufqueue = g_array_remove_index (sink->bufqueue, i);
2153 /* unref tail buffer */
2154 gst_buffer_unref (old);
2156 /* save for stats */
2157 sink->buffers_queued = max_buffer_usage;
2158 CLIENTS_UNLOCK (sink);
2160 /* and send a signal to thread if fd_set changed */
2162 SEND_COMMAND (sink, CONTROL_RESTART);
2166 /* Handle the clients. Basically does a blocking select for one
2167 * of the client fds to become read or writable. We also have a
2168 * filedescriptor to receive commands on that we need to check.
2170 * After going out of the select call, we read and write to all
2171 * clients that can do so. Badly behaving clients are put on a
2172 * garbage list and removed.
2175 gst_multi_fd_sink_handle_clients (GstMultiFdSink * sink)
2178 GList *clients, *next;
2180 GstMultiFdSinkClass *fclass;
2183 fclass = GST_MULTI_FD_SINK_GET_CLASS (sink);
2186 gboolean stop = FALSE;
2191 * - server socket input (ie, new client connections)
2192 * - client socket input (ie, clients saying goodbye)
2193 * - client socket output (ie, client reads) */
2194 GST_LOG_OBJECT (sink, "waiting on action on fdset");
2195 result = gst_fdset_wait (sink->fdset, -1);
2197 /* < 0 is an error, 0 just means a timeout happened, which is impossible */
2199 GST_WARNING_OBJECT (sink, "wait failed: %s (%d)", g_strerror (errno),
2201 if (errno == EBADF) {
2202 /* ok, so one or more of the fds is invalid. We loop over them to find
2203 * the ones that give an error to the F_GETFL fcntl. */
2204 CLIENTS_LOCK (sink);
2206 cookie = sink->clients_cookie;
2207 for (clients = sink->clients; clients; clients = next) {
2208 GstTCPClient *client;
2213 if (cookie != sink->clients_cookie) {
2214 GST_DEBUG_OBJECT (sink, "Cookie changed finding bad fd");
2218 client = (GstTCPClient *) clients->data;
2219 next = g_list_next (clients);
2223 res = fcntl (fd, F_GETFL, &flags);
2225 GST_WARNING_OBJECT (sink, "fnctl failed for %d, removing: %s (%d)",
2226 fd, g_strerror (errno), errno);
2227 if (errno == EBADF) {
2228 client->status = GST_CLIENT_STATUS_ERROR;
2229 gst_multi_fd_sink_remove_client_link (sink, clients);
2233 CLIENTS_UNLOCK (sink);
2234 /* after this, go back in the select loop as the read/writefds
2237 } else if (errno == EINTR) {
2238 /* interrupted system call, just redo the select */
2241 /* this is quite bad... */
2242 GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
2243 ("select failed: %s (%d)", g_strerror (errno), errno));
2247 GST_LOG_OBJECT (sink, "wait done: %d sockets with events", result);
2248 /* read all commands */
2249 if (gst_fdset_fd_can_read (sink->fdset, &READ_SOCKET (sink))) {
2250 GST_LOG_OBJECT (sink, "have a command");
2255 READ_COMMAND (sink, command, res);
2257 GST_LOG_OBJECT (sink, "no more commands");
2258 /* no more commands */
2263 case CONTROL_RESTART:
2264 GST_LOG_OBJECT (sink, "restart");
2265 /* need to restart the select call as the fd_set changed */
2266 /* if other file descriptors than the READ_SOCKET had activity,
2267 * we don't restart just yet, but handle the other clients first
2273 /* break out of the select loop */
2274 GST_LOG_OBJECT (sink, "stop");
2275 /* stop this function */
2279 GST_WARNING_OBJECT (sink, "unkown");
2280 g_warning ("multifdsink: unknown control message received");
2289 } while (try_again);
2291 /* subclasses can check fdset with this virtual function */
2293 fclass->wait (sink, sink->fdset);
2295 /* Check the clients */
2296 CLIENTS_LOCK (sink);
2299 cookie = sink->clients_cookie;
2300 for (clients = sink->clients; clients; clients = next) {
2301 GstTCPClient *client;
2303 if (sink->clients_cookie != cookie) {
2304 GST_DEBUG_OBJECT (sink, "Restarting loop, cookie out of date");
2308 client = (GstTCPClient *) clients->data;
2309 next = g_list_next (clients);
2311 if (client->status != GST_CLIENT_STATUS_OK) {
2312 gst_multi_fd_sink_remove_client_link (sink, clients);
2316 if (gst_fdset_fd_has_closed (sink->fdset, &client->fd)) {
2317 client->status = GST_CLIENT_STATUS_CLOSED;
2318 gst_multi_fd_sink_remove_client_link (sink, clients);
2321 if (gst_fdset_fd_has_error (sink->fdset, &client->fd)) {
2322 GST_WARNING_OBJECT (sink, "gst_fdset_fd_has_error for %d", client->fd.fd);
2323 client->status = GST_CLIENT_STATUS_ERROR;
2324 gst_multi_fd_sink_remove_client_link (sink, clients);
2327 if (gst_fdset_fd_can_read (sink->fdset, &client->fd)) {
2328 /* handle client read */
2329 if (!gst_multi_fd_sink_handle_client_read (sink, client)) {
2330 gst_multi_fd_sink_remove_client_link (sink, clients);
2334 if (gst_fdset_fd_can_write (sink->fdset, &client->fd)) {
2335 /* handle client write */
2336 if (!gst_multi_fd_sink_handle_client_write (sink, client)) {
2337 gst_multi_fd_sink_remove_client_link (sink, clients);
2342 CLIENTS_UNLOCK (sink);
2345 /* we handle the client communication in another thread so that we do not block
2346 * the gstreamer thread while we select() on the client fds */
2348 gst_multi_fd_sink_thread (GstMultiFdSink * sink)
2350 while (sink->running) {
2351 gst_multi_fd_sink_handle_clients (sink);
2356 static GstFlowReturn
2357 gst_multi_fd_sink_render (GstBaseSink * bsink, GstBuffer * buf)
2359 GstMultiFdSink *sink;
2361 GstCaps *bufcaps, *padcaps;
2363 sink = GST_MULTI_FD_SINK (bsink);
2365 g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink, GST_MULTI_FD_SINK_OPEN),
2366 GST_FLOW_WRONG_STATE);
2368 /* since we check every buffer for streamheader caps, we need to make
2369 * sure every buffer has caps set */
2370 bufcaps = gst_buffer_get_caps (buf);
2371 padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
2373 /* make sure we have caps on the pad */
2374 if (!padcaps && !bufcaps)
2377 /* get IN_CAPS first, code below might mess with the flags */
2378 in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
2380 /* stamp the buffer with previous caps if no caps set */
2382 if (!gst_buffer_is_metadata_writable (buf)) {
2383 /* metadata is not writable, copy will be made and original buffer
2384 * will be unreffed so we need to ref so that we don't lose the
2385 * buffer in the render method. */
2386 gst_buffer_ref (buf);
2387 /* the new buffer is ours only, we keep it out of the scope of this
2389 buf = gst_buffer_make_metadata_writable (buf);
2391 /* else the metadata is writable, we ref because we keep the buffer
2392 * out of the scope of this method */
2393 gst_buffer_ref (buf);
2395 /* buffer metadata is writable now, set the caps */
2396 gst_buffer_set_caps (buf, padcaps);
2398 gst_caps_unref (bufcaps);
2400 /* since we keep this buffer out of the scope of this method */
2401 gst_buffer_ref (buf);
2404 GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %d", buf, in_caps);
2406 /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
2407 * it means we're getting new streamheader buffers, and we should clear
2409 if (in_caps && sink->previous_buffer_in_caps == FALSE) {
2410 GST_DEBUG_OBJECT (sink,
2411 "receiving new IN_CAPS buffers, clearing old streamheader");
2412 g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2413 g_slist_free (sink->streamheader);
2414 sink->streamheader = NULL;
2417 /* save the current in_caps */
2418 sink->previous_buffer_in_caps = in_caps;
2420 /* if the incoming buffer is marked as IN CAPS, then we assume for now
2421 * it's a streamheader that needs to be sent to each new client, so we
2422 * put it on our internal list of streamheader buffers.
2423 * FIXME: we could check if the buffer's contents are in fact part of the
2424 * current streamheader.
2426 * We don't send the buffer to the client, since streamheaders are sent
2427 * separately when necessary. */
2429 GST_DEBUG_OBJECT (sink,
2430 "appending IN_CAPS buffer with length %d to streamheader",
2431 GST_BUFFER_SIZE (buf));
2432 sink->streamheader = g_slist_append (sink->streamheader, buf);
2434 /* queue the buffer, this is a regular data buffer. */
2435 gst_multi_fd_sink_queue_buffer (sink, buf);
2437 sink->bytes_to_serve += GST_BUFFER_SIZE (buf);
2444 GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
2445 ("Received first buffer without caps set"));
2446 return GST_FLOW_NOT_NEGOTIATED;
2451 gst_multi_fd_sink_set_property (GObject * object, guint prop_id,
2452 const GValue * value, GParamSpec * pspec)
2454 GstMultiFdSink *multifdsink;
2456 multifdsink = GST_MULTI_FD_SINK (object);
2460 multifdsink->protocol = g_value_get_enum (value);
2463 multifdsink->mode = g_value_get_enum (value);
2465 case PROP_BUFFERS_MAX:
2466 multifdsink->units_max = g_value_get_int (value);
2468 case PROP_BUFFERS_SOFT_MAX:
2469 multifdsink->units_soft_max = g_value_get_int (value);
2472 multifdsink->time_min = g_value_get_int64 (value);
2474 case PROP_BYTES_MIN:
2475 multifdsink->bytes_min = g_value_get_int (value);
2477 case PROP_BUFFERS_MIN:
2478 multifdsink->buffers_min = g_value_get_int (value);
2480 case PROP_UNIT_TYPE:
2481 multifdsink->unit_type = g_value_get_enum (value);
2483 case PROP_UNITS_MAX:
2484 multifdsink->units_max = g_value_get_int64 (value);
2486 case PROP_UNITS_SOFT_MAX:
2487 multifdsink->units_soft_max = g_value_get_int64 (value);
2489 case PROP_RECOVER_POLICY:
2490 multifdsink->recover_policy = g_value_get_enum (value);
2493 multifdsink->timeout = g_value_get_uint64 (value);
2495 case PROP_SYNC_METHOD:
2496 multifdsink->def_sync_method = g_value_get_enum (value);
2498 case PROP_BURST_UNIT:
2499 multifdsink->def_burst_unit = g_value_get_enum (value);
2501 case PROP_BURST_VALUE:
2502 multifdsink->def_burst_value = g_value_get_uint64 (value);
2506 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2512 gst_multi_fd_sink_get_property (GObject * object, guint prop_id, GValue * value,
2515 GstMultiFdSink *multifdsink;
2517 multifdsink = GST_MULTI_FD_SINK (object);
2521 g_value_set_enum (value, multifdsink->protocol);
2524 g_value_set_enum (value, multifdsink->mode);
2526 case PROP_BUFFERS_MAX:
2527 g_value_set_int (value, multifdsink->units_max);
2529 case PROP_BUFFERS_SOFT_MAX:
2530 g_value_set_int (value, multifdsink->units_soft_max);
2533 g_value_set_int64 (value, multifdsink->time_min);
2535 case PROP_BYTES_MIN:
2536 g_value_set_int (value, multifdsink->bytes_min);
2538 case PROP_BUFFERS_MIN:
2539 g_value_set_int (value, multifdsink->buffers_min);
2541 case PROP_BUFFERS_QUEUED:
2542 g_value_set_uint (value, multifdsink->buffers_queued);
2544 case PROP_BYTES_QUEUED:
2545 g_value_set_uint (value, multifdsink->bytes_queued);
2547 case PROP_TIME_QUEUED:
2548 g_value_set_uint64 (value, multifdsink->time_queued);
2550 case PROP_UNIT_TYPE:
2551 g_value_set_enum (value, multifdsink->unit_type);
2553 case PROP_UNITS_MAX:
2554 g_value_set_int64 (value, multifdsink->units_max);
2556 case PROP_UNITS_SOFT_MAX:
2557 g_value_set_int64 (value, multifdsink->units_soft_max);
2559 case PROP_RECOVER_POLICY:
2560 g_value_set_enum (value, multifdsink->recover_policy);
2563 g_value_set_uint64 (value, multifdsink->timeout);
2565 case PROP_SYNC_METHOD:
2566 g_value_set_enum (value, multifdsink->def_sync_method);
2568 case PROP_BYTES_TO_SERVE:
2569 g_value_set_uint64 (value, multifdsink->bytes_to_serve);
2571 case PROP_BYTES_SERVED:
2572 g_value_set_uint64 (value, multifdsink->bytes_served);
2574 case PROP_BURST_UNIT:
2575 g_value_set_enum (value, multifdsink->def_burst_unit);
2577 case PROP_BURST_VALUE:
2578 g_value_set_uint64 (value, multifdsink->def_burst_value);
2582 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2588 /* create a socket for sending to remote machine */
2590 gst_multi_fd_sink_start (GstBaseSink * bsink)
2592 GstMultiFdSinkClass *fclass;
2593 int control_socket[2];
2594 GstMultiFdSink *this;
2596 if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_FD_SINK_OPEN))
2599 this = GST_MULTI_FD_SINK (bsink);
2600 fclass = GST_MULTI_FD_SINK_GET_CLASS (this);
2602 GST_INFO_OBJECT (this, "starting in mode %d", this->mode);
2603 this->fdset = gst_fdset_new (this->mode);
2605 if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_socket) < 0)
2608 READ_SOCKET (this).fd = control_socket[0];
2609 WRITE_SOCKET (this).fd = control_socket[1];
2611 gst_fdset_add_fd (this->fdset, &READ_SOCKET (this));
2612 gst_fdset_fd_ctl_read (this->fdset, &READ_SOCKET (this), TRUE);
2614 fcntl (READ_SOCKET (this).fd, F_SETFL, O_NONBLOCK);
2615 fcntl (WRITE_SOCKET (this).fd, F_SETFL, O_NONBLOCK);
2617 this->streamheader = NULL;
2618 this->bytes_to_serve = 0;
2619 this->bytes_served = 0;
2622 fclass->init (this);
2625 this->running = TRUE;
2626 this->thread = g_thread_create ((GThreadFunc) gst_multi_fd_sink_thread,
2629 GST_OBJECT_FLAG_SET (this, GST_MULTI_FD_SINK_OPEN);
2636 GST_ELEMENT_ERROR (this, RESOURCE, OPEN_READ_WRITE, (NULL),
2643 multifdsink_hash_remove (gpointer key, gpointer value, gpointer data)
2649 gst_multi_fd_sink_stop (GstBaseSink * bsink)
2651 GstMultiFdSinkClass *fclass;
2652 GstMultiFdSink *this;
2656 this = GST_MULTI_FD_SINK (bsink);
2657 fclass = GST_MULTI_FD_SINK_GET_CLASS (this);
2659 if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_FD_SINK_OPEN))
2662 this->running = FALSE;
2664 SEND_COMMAND (this, CONTROL_STOP);
2666 GST_DEBUG_OBJECT (this, "joining thread");
2667 g_thread_join (this->thread);
2668 GST_DEBUG_OBJECT (this, "joined thread");
2669 this->thread = NULL;
2672 /* free the clients */
2673 gst_multi_fd_sink_clear (this);
2675 close (READ_SOCKET (this).fd);
2676 close (WRITE_SOCKET (this).fd);
2678 if (this->streamheader) {
2679 g_slist_foreach (this->streamheader, (GFunc) gst_mini_object_unref, NULL);
2680 g_slist_free (this->streamheader);
2681 this->streamheader = NULL;
2685 fclass->close (this);
2688 gst_fdset_remove_fd (this->fdset, &READ_SOCKET (this));
2689 gst_fdset_free (this->fdset);
2692 g_hash_table_foreach_remove (this->fd_hash, multifdsink_hash_remove, this);
2694 /* remove all queued buffers */
2695 if (this->bufqueue) {
2696 GST_DEBUG_OBJECT (this, "Emptying bufqueue with %d buffers",
2697 this->bufqueue->len);
2698 for (i = this->bufqueue->len - 1; i >= 0; --i) {
2699 buf = g_array_index (this->bufqueue, GstBuffer *, i);
2700 GST_LOG_OBJECT (this, "Removing buffer %p (%d) with refcount %d", buf, i,
2701 GST_MINI_OBJECT_REFCOUNT (buf));
2702 gst_buffer_unref (buf);
2703 this->bufqueue = g_array_remove_index (this->bufqueue, i);
2705 /* freeing the array is done in _finalize */
2707 GST_OBJECT_FLAG_UNSET (this, GST_MULTI_FD_SINK_OPEN);
2712 static GstStateChangeReturn
2713 gst_multi_fd_sink_change_state (GstElement * element, GstStateChange transition)
2715 GstMultiFdSink *sink;
2716 GstStateChangeReturn ret;
2718 sink = GST_MULTI_FD_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_fd_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_fd_sink_stop (GST_BASE_SINK (sink));
2756 /* error message was posted */
2757 return GST_STATE_CHANGE_FAILURE;