Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gstreamer.git] / gst / tcp / gstmultifdsink.c
1 /* GStreamer
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  *
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.
10  *
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.
15  *
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.
20  */
21
22 /**
23  * SECTION:element-multifdsink
24  * @see_also: tcpserversink
25  *
26  * This plugin writes incoming data to a set of file descriptors. The
27  * file descriptors can be added to multifdsink by emitting the #GstMultiFdSink::add signal. 
28  * For each descriptor added, the #GstMultiFdSink::client-added signal will be called.
29  *
30  * As of version 0.10.8, a client can also be added with the #GstMultiFdSink::add-full signal
31  * that allows for more control over what and how much data a client 
32  * initially receives.
33  *
34  * Clients can be removed from multifdsink by emitting the #GstMultiFdSink::remove signal. For
35  * each descriptor removed, the #GstMultiFdSink::client-removed signal will be called. The
36  * #GstMultiFdSink::client-removed signal can also be fired when multifdsink decides that a
37  * client is not active anymore or, depending on the value of the
38  * #GstMultiFdSink:recover-policy property, if the client is reading too slowly.
39  * In all cases, multifdsink will never close a file descriptor itself.
40  * The user of multifdsink is responsible for closing all file descriptors.
41  * This can for example be done in response to the #GstMultiFdSink::client-fd-removed signal.
42  * Note that multifdsink still has a reference to the file descriptor when the
43  * #GstMultiFdSink::client-removed signal is emitted, so that "get-stats" can be performed on
44  * the descriptor; it is therefore not safe to close the file descriptor in
45  * the #GstMultiFdSink::client-removed signal handler, and you should use the 
46  * #GstMultiFdSink::client-fd-removed signal to safely close the fd.
47  *
48  * Multifdsink internally keeps a queue of the incoming buffers and uses a
49  * separate thread to send the buffers to the clients. This ensures that no
50  * client write can block the pipeline and that clients can read with different
51  * speeds.
52  *
53  * When adding a client to multifdsink, the #GstMultiFdSink:sync-method property will define
54  * which buffer in the queued buffers will be sent first to the client. Clients 
55  * can be sent the most recent buffer (which might not be decodable by the 
56  * client if it is not a keyframe), the next keyframe received in 
57  * multifdsink (which can take some time depending on the keyframe rate), or the
58  * last received keyframe (which will cause a simple burst-on-connect). 
59  * Multifdsink will always keep at least one keyframe in its internal buffers
60  * when the sync-mode is set to latest-keyframe.
61  *
62  * As of version 0.10.8, there are additional values for the #GstMultiFdSink:sync-method 
63  * property to allow finer control over burst-on-connect behaviour. By selecting
64  * the 'burst' method a minimum burst size can be chosen, 'burst-keyframe'
65  * additionally requires that the burst begin with a keyframe, and 
66  * 'burst-with-keyframe' attempts to burst beginning with a keyframe, but will
67  * prefer a minimum burst size even if it requires not starting with a keyframe.
68  *
69  * Multifdsink can be instructed to keep at least a minimum amount of data
70  * expressed in time or byte units in its internal queues with the the 
71  * #GstMultiFdSink:time-min and #GstMultiFdSink:bytes-min properties respectively.
72  * These properties are useful if the application adds clients with the 
73  * #GstMultiFdSink::add-full signal to make sure that a burst connect can
74  * actually be honored. 
75  *
76  * When streaming data, clients are allowed to read at a different rate than
77  * the rate at which multifdsink receives data. If the client is reading too
78  * fast, no data will be send to the client until multifdsink receives more
79  * data. If the client, however, reads too slowly, data for that client will be 
80  * queued up in multifdsink. Two properties control the amount of data 
81  * (buffers) that is queued in multifdsink: #GstMultiFdSink:buffers-max and 
82  * #GstMultiFdSink:buffers-soft-max. A client that falls behind by
83  * #GstMultiFdSink:buffers-max is removed from multifdsink forcibly.
84  *
85  * A client with a lag of at least #GstMultiFdSink:buffers-soft-max enters the recovery
86  * procedure which is controlled with the #GstMultiFdSink:recover-policy property.
87  * A recover policy of NONE will do nothing, RESYNC_LATEST will send the most recently
88  * received buffer as the next buffer for the client, RESYNC_SOFT_LIMIT
89  * positions the client to the soft limit in the buffer queue and
90  * RESYNC_KEYFRAME positions the client at the most recent keyframe in the
91  * buffer queue.
92  *
93  * multifdsink will by default synchronize on the clock before serving the 
94  * buffers to the clients. This behaviour can be disabled by setting the sync 
95  * property to FALSE. Multifdsink will by default not do QoS and will never
96  * drop late buffers.
97  *
98  * Last reviewed on 2006-09-12 (0.10.10)
99  */
100
101 #ifdef HAVE_CONFIG_H
102 #include "config.h"
103 #endif
104 #include <gst/gst-i18n-plugin.h>
105
106 #include <sys/ioctl.h>
107
108 #ifdef HAVE_UNISTD_H
109 #include <unistd.h>
110 #endif
111
112 #include <fcntl.h>
113 #include <sys/types.h>
114 #include <sys/socket.h>
115 #include <sys/stat.h>
116 #include <netinet/in.h>
117
118 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
119 #include <sys/filio.h>
120 #endif
121
122 #include "gstmultifdsink.h"
123 #include "gsttcp-marshal.h"
124
125 #define NOT_IMPLEMENTED 0
126
127 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
128     GST_PAD_SINK,
129     GST_PAD_ALWAYS,
130     GST_STATIC_CAPS_ANY);
131
132 GST_DEBUG_CATEGORY_STATIC (multifdsink_debug);
133 #define GST_CAT_DEFAULT (multifdsink_debug)
134
135 /* MultiFdSink signals and args */
136 enum
137 {
138   /* methods */
139   SIGNAL_ADD,
140   SIGNAL_ADD_BURST,
141   SIGNAL_REMOVE,
142   SIGNAL_REMOVE_FLUSH,
143   SIGNAL_CLEAR,
144   SIGNAL_GET_STATS,
145
146   /* signals */
147   SIGNAL_CLIENT_ADDED,
148   SIGNAL_CLIENT_REMOVED,
149   SIGNAL_CLIENT_FD_REMOVED,
150
151   LAST_SIGNAL
152 };
153
154
155 /* this is really arbitrarily chosen */
156 #define DEFAULT_MODE                    1
157 #define DEFAULT_BUFFERS_MAX             -1
158 #define DEFAULT_BUFFERS_SOFT_MAX        -1
159 #define DEFAULT_TIME_MIN                -1
160 #define DEFAULT_BYTES_MIN               -1
161 #define DEFAULT_BUFFERS_MIN             -1
162 #define DEFAULT_UNIT_TYPE               GST_TCP_UNIT_TYPE_BUFFERS
163 #define DEFAULT_UNITS_MAX               -1
164 #define DEFAULT_UNITS_SOFT_MAX          -1
165 #define DEFAULT_RECOVER_POLICY          GST_RECOVER_POLICY_NONE
166 #define DEFAULT_TIMEOUT                 0
167 #define DEFAULT_SYNC_METHOD             GST_SYNC_METHOD_LATEST
168
169 #define DEFAULT_BURST_UNIT              GST_TCP_UNIT_TYPE_UNDEFINED
170 #define DEFAULT_BURST_VALUE             0
171
172 #define DEFAULT_QOS_DSCP                -1
173 #define DEFAULT_HANDLE_READ             TRUE
174
175 #define DEFAULT_RESEND_STREAMHEADER      TRUE
176
177 enum
178 {
179   PROP_0,
180   PROP_MODE,
181   PROP_BUFFERS_QUEUED,
182   PROP_BYTES_QUEUED,
183   PROP_TIME_QUEUED,
184
185   PROP_UNIT_TYPE,
186   PROP_UNITS_MAX,
187   PROP_UNITS_SOFT_MAX,
188
189   PROP_BUFFERS_MAX,
190   PROP_BUFFERS_SOFT_MAX,
191
192   PROP_TIME_MIN,
193   PROP_BYTES_MIN,
194   PROP_BUFFERS_MIN,
195
196   PROP_RECOVER_POLICY,
197   PROP_TIMEOUT,
198   PROP_SYNC_METHOD,
199   PROP_BYTES_TO_SERVE,
200   PROP_BYTES_SERVED,
201
202   PROP_BURST_UNIT,
203   PROP_BURST_VALUE,
204
205   PROP_QOS_DSCP,
206
207   PROP_HANDLE_READ,
208
209   PROP_RESEND_STREAMHEADER,
210
211   PROP_NUM_FDS,
212
213   PROP_LAST
214 };
215
216 /* For backward compat, we can't really select the poll mode anymore with
217  * GstPoll. */
218 #define GST_TYPE_FDSET_MODE (gst_fdset_mode_get_type())
219 static GType
220 gst_fdset_mode_get_type (void)
221 {
222   static GType fdset_mode_type = 0;
223   static const GEnumValue fdset_mode[] = {
224     {0, "Select", "select"},
225     {1, "Poll", "poll"},
226     {2, "EPoll", "epoll"},
227     {0, NULL, NULL},
228   };
229
230   if (!fdset_mode_type) {
231     fdset_mode_type = g_enum_register_static ("GstFDSetMode", fdset_mode);
232   }
233   return fdset_mode_type;
234 }
235
236 #define GST_TYPE_RECOVER_POLICY (gst_recover_policy_get_type())
237 static GType
238 gst_recover_policy_get_type (void)
239 {
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"},
250     {0, NULL, NULL},
251   };
252
253   if (!recover_policy_type) {
254     recover_policy_type =
255         g_enum_register_static ("GstRecoverPolicy", recover_policy);
256   }
257   return recover_policy_type;
258 }
259
260 #define GST_TYPE_SYNC_METHOD (gst_sync_method_get_type())
261 static GType
262 gst_sync_method_get_type (void)
263 {
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)",
272         "latest-keyframe"},
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",
276         "burst-keyframe"},
277     {GST_SYNC_METHOD_BURST_WITH_KEYFRAME,
278           "Serve burst-value data preferably starting on a keyframe",
279         "burst-with-keyframe"},
280     {0, NULL, NULL},
281   };
282
283   if (!sync_method_type) {
284     sync_method_type = g_enum_register_static ("GstSyncMethod", sync_method);
285   }
286   return sync_method_type;
287 }
288
289 #define GST_TYPE_UNIT_TYPE (gst_unit_type_get_type())
290 static GType
291 gst_unit_type_get_type (void)
292 {
293   static GType unit_type_type = 0;
294   static const GEnumValue unit_type[] = {
295     {GST_TCP_UNIT_TYPE_UNDEFINED, "Undefined", "undefined"},
296     {GST_TCP_UNIT_TYPE_BUFFERS, "Buffers", "buffers"},
297     {GST_TCP_UNIT_TYPE_BYTES, "Bytes", "bytes"},
298     {GST_TCP_UNIT_TYPE_TIME, "Time", "time"},
299     {0, NULL, NULL},
300   };
301
302   if (!unit_type_type) {
303     unit_type_type = g_enum_register_static ("GstTCPUnitType", unit_type);
304   }
305   return unit_type_type;
306 }
307
308 #define GST_TYPE_CLIENT_STATUS (gst_client_status_get_type())
309 static GType
310 gst_client_status_get_type (void)
311 {
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"},
320     {GST_CLIENT_STATUS_FLUSHING, "Flushing", "flushing"},
321     {0, NULL, NULL},
322   };
323
324   if (!client_status_type) {
325     client_status_type =
326         g_enum_register_static ("GstClientStatus", client_status);
327   }
328   return client_status_type;
329 }
330
331 static void gst_multi_fd_sink_finalize (GObject * object);
332
333 static void gst_multi_fd_sink_remove_client_link (GstMultiFdSink * sink,
334     GList * link);
335
336 static GstFlowReturn gst_multi_fd_sink_render (GstBaseSink * bsink,
337     GstBuffer * buf);
338 static GstStateChangeReturn gst_multi_fd_sink_change_state (GstElement *
339     element, GstStateChange transition);
340
341 static void gst_multi_fd_sink_set_property (GObject * object, guint prop_id,
342     const GValue * value, GParamSpec * pspec);
343 static void gst_multi_fd_sink_get_property (GObject * object, guint prop_id,
344     GValue * value, GParamSpec * pspec);
345
346 #define gst_multi_fd_sink_parent_class parent_class
347 G_DEFINE_TYPE (GstMultiFdSink, gst_multi_fd_sink, GST_TYPE_BASE_SINK);
348
349 static guint gst_multi_fd_sink_signals[LAST_SIGNAL] = { 0 };
350
351 static void
352 gst_multi_fd_sink_class_init (GstMultiFdSinkClass * klass)
353 {
354   GObjectClass *gobject_class;
355   GstElementClass *gstelement_class;
356   GstBaseSinkClass *gstbasesink_class;
357
358   gobject_class = (GObjectClass *) klass;
359   gstelement_class = (GstElementClass *) klass;
360   gstbasesink_class = (GstBaseSinkClass *) klass;
361
362   gobject_class->set_property = gst_multi_fd_sink_set_property;
363   gobject_class->get_property = gst_multi_fd_sink_get_property;
364   gobject_class->finalize = gst_multi_fd_sink_finalize;
365
366   /**
367    * GstMultiFdSink::mode
368    *
369    * The mode for selecting activity on the fds. 
370    *
371    * This property is deprecated since 0.10.18, if will now automatically
372    * select and use the most optimal method.
373    */
374   g_object_class_install_property (gobject_class, PROP_MODE,
375       g_param_spec_enum ("mode", "Mode",
376           "The mode for selecting activity on the fds (deprecated)",
377           GST_TYPE_FDSET_MODE, DEFAULT_MODE,
378           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
379
380   g_object_class_install_property (gobject_class, PROP_BUFFERS_MAX,
381       g_param_spec_int ("buffers-max", "Buffers max",
382           "max number of buffers to queue for a client (-1 = no limit)", -1,
383           G_MAXINT, DEFAULT_BUFFERS_MAX,
384           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
385   g_object_class_install_property (gobject_class, PROP_BUFFERS_SOFT_MAX,
386       g_param_spec_int ("buffers-soft-max", "Buffers soft max",
387           "Recover client when going over this limit (-1 = no limit)", -1,
388           G_MAXINT, DEFAULT_BUFFERS_SOFT_MAX,
389           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
390
391   g_object_class_install_property (gobject_class, PROP_BYTES_MIN,
392       g_param_spec_int ("bytes-min", "Bytes min",
393           "min number of bytes to queue (-1 = as little as possible)", -1,
394           G_MAXINT, DEFAULT_BYTES_MIN,
395           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
396   g_object_class_install_property (gobject_class, PROP_TIME_MIN,
397       g_param_spec_int64 ("time-min", "Time min",
398           "min number of time to queue (-1 = as little as possible)", -1,
399           G_MAXINT64, DEFAULT_TIME_MIN,
400           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
401   g_object_class_install_property (gobject_class, PROP_BUFFERS_MIN,
402       g_param_spec_int ("buffers-min", "Buffers min",
403           "min number of buffers to queue (-1 = as few as possible)", -1,
404           G_MAXINT, DEFAULT_BUFFERS_MIN,
405           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
406
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,
411           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
412   g_object_class_install_property (gobject_class, PROP_UNITS_MAX,
413       g_param_spec_int64 ("units-max", "Units max",
414           "max number of units to queue (-1 = no limit)", -1, G_MAXINT64,
415           DEFAULT_UNITS_MAX, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
416   g_object_class_install_property (gobject_class, PROP_UNITS_SOFT_MAX,
417       g_param_spec_int64 ("units-soft-max", "Units soft max",
418           "Recover client when going over this limit (-1 = no limit)", -1,
419           G_MAXINT64, DEFAULT_UNITS_SOFT_MAX,
420           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
421
422   g_object_class_install_property (gobject_class, PROP_BUFFERS_QUEUED,
423       g_param_spec_uint ("buffers-queued", "Buffers queued",
424           "Number of buffers currently queued", 0, G_MAXUINT, 0,
425           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
426 #if NOT_IMPLEMENTED
427   g_object_class_install_property (gobject_class, PROP_BYTES_QUEUED,
428       g_param_spec_uint ("bytes-queued", "Bytes queued",
429           "Number of bytes currently queued", 0, G_MAXUINT, 0,
430           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
431   g_object_class_install_property (gobject_class, PROP_TIME_QUEUED,
432       g_param_spec_uint64 ("time-queued", "Time queued",
433           "Number of time currently queued", 0, G_MAXUINT64, 0,
434           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
435 #endif
436
437   g_object_class_install_property (gobject_class, PROP_RECOVER_POLICY,
438       g_param_spec_enum ("recover-policy", "Recover Policy",
439           "How to recover when client reaches the soft max",
440           GST_TYPE_RECOVER_POLICY, DEFAULT_RECOVER_POLICY,
441           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
442   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
443       g_param_spec_uint64 ("timeout", "Timeout",
444           "Maximum inactivity timeout in nanoseconds for a client (0 = no limit)",
445           0, G_MAXUINT64, DEFAULT_TIMEOUT,
446           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
447   g_object_class_install_property (gobject_class, PROP_SYNC_METHOD,
448       g_param_spec_enum ("sync-method", "Sync Method",
449           "How to sync new clients to the stream", GST_TYPE_SYNC_METHOD,
450           DEFAULT_SYNC_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
451   g_object_class_install_property (gobject_class, PROP_BYTES_TO_SERVE,
452       g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
453           "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
454           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
455   g_object_class_install_property (gobject_class, PROP_BYTES_SERVED,
456       g_param_spec_uint64 ("bytes-served", "Bytes served",
457           "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
458           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
459
460   g_object_class_install_property (gobject_class, PROP_BURST_UNIT,
461       g_param_spec_enum ("burst-unit", "Burst unit",
462           "The format of the burst units (when sync-method is burst[[-with]-keyframe])",
463           GST_TYPE_UNIT_TYPE, DEFAULT_BURST_UNIT,
464           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
465   g_object_class_install_property (gobject_class, PROP_BURST_VALUE,
466       g_param_spec_uint64 ("burst-value", "Burst value",
467           "The amount of burst expressed in burst-unit", 0, G_MAXUINT64,
468           DEFAULT_BURST_VALUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
469
470   g_object_class_install_property (gobject_class, PROP_QOS_DSCP,
471       g_param_spec_int ("qos-dscp", "QoS diff srv code point",
472           "Quality of Service, differentiated services code point (-1 default)",
473           -1, 63, DEFAULT_QOS_DSCP,
474           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
475   /**
476    * GstMultiFdSink::handle-read
477    *
478    * Handle read requests from clients and discard the data.
479    *
480    * Since: 0.10.23
481    */
482   g_object_class_install_property (gobject_class, PROP_HANDLE_READ,
483       g_param_spec_boolean ("handle-read", "Handle Read",
484           "Handle client reads and discard the data",
485           DEFAULT_HANDLE_READ, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
486   /**
487    * GstMultiFdSink::resend-streamheader
488    *
489    * Resend the streamheaders to existing clients when they change.
490    *
491    * Since: 0.10.23
492    */
493   g_object_class_install_property (gobject_class, PROP_RESEND_STREAMHEADER,
494       g_param_spec_boolean ("resend-streamheader", "Resend streamheader",
495           "Resend the streamheader if it changes in the caps",
496           DEFAULT_RESEND_STREAMHEADER,
497           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
498
499   g_object_class_install_property (gobject_class, PROP_NUM_FDS,
500       g_param_spec_uint ("num-fds", "Number of fds",
501           "The current number of client file descriptors.",
502           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
503
504   /**
505    * GstMultiFdSink::add:
506    * @gstmultifdsink: the multifdsink element to emit this signal on
507    * @fd:             the file descriptor to add to multifdsink
508    *
509    * Hand the given open file descriptor to multifdsink to write to.
510    */
511   gst_multi_fd_sink_signals[SIGNAL_ADD] =
512       g_signal_new ("add", G_TYPE_FROM_CLASS (klass),
513       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstMultiFdSinkClass,
514           add), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1,
515       G_TYPE_INT);
516   /**
517    * GstMultiFdSink::add-full:
518    * @gstmultifdsink: the multifdsink element to emit this signal on
519    * @fd:             the file descriptor to add to multifdsink
520    * @sync:           the sync method to use
521    * @unit_type_min:  the unit-type of @value_min
522    * @value_min:      the minimum amount of data to burst expressed in
523    *                  @unit_type_min units.
524    * @unit_type_max:  the unit-type of @value_max
525    * @value_max:      the maximum amount of data to burst expressed in
526    *                  @unit_type_max units.
527    *
528    * Hand the given open file descriptor to multifdsink to write to and
529    * specify the burst parameters for the new connection.
530    */
531   gst_multi_fd_sink_signals[SIGNAL_ADD_BURST] =
532       g_signal_new ("add-full", G_TYPE_FROM_CLASS (klass),
533       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstMultiFdSinkClass,
534           add_full), NULL, NULL,
535       gst_tcp_marshal_VOID__INT_ENUM_INT_UINT64_INT_UINT64, G_TYPE_NONE, 6,
536       G_TYPE_INT, GST_TYPE_SYNC_METHOD, GST_TYPE_UNIT_TYPE, G_TYPE_UINT64,
537       GST_TYPE_UNIT_TYPE, G_TYPE_UINT64);
538   /**
539    * GstMultiFdSink::remove:
540    * @gstmultifdsink: the multifdsink element to emit this signal on
541    * @fd:             the file descriptor to remove from multifdsink
542    *
543    * Remove the given open file descriptor from multifdsink.
544    */
545   gst_multi_fd_sink_signals[SIGNAL_REMOVE] =
546       g_signal_new ("remove", G_TYPE_FROM_CLASS (klass),
547       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstMultiFdSinkClass,
548           remove), NULL, NULL, gst_tcp_marshal_VOID__INT, G_TYPE_NONE, 1,
549       G_TYPE_INT);
550   /**
551    * GstMultiFdSink::remove-flush:
552    * @gstmultifdsink: the multifdsink element to emit this signal on
553    * @fd:             the file descriptor to remove from multifdsink
554    *
555    * Remove the given open file descriptor from multifdsink after flushing all
556    * the pending data to the fd.
557    */
558   gst_multi_fd_sink_signals[SIGNAL_REMOVE_FLUSH] =
559       g_signal_new ("remove-flush", G_TYPE_FROM_CLASS (klass),
560       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstMultiFdSinkClass,
561           remove_flush), NULL, NULL, gst_tcp_marshal_VOID__INT, G_TYPE_NONE, 1,
562       G_TYPE_INT);
563   /**
564    * GstMultiFdSink::clear:
565    * @gstmultifdsink: the multifdsink element to emit this signal on
566    *
567    * Remove all file descriptors from multifdsink.  Since multifdsink did not
568    * open fd's itself, it does not explicitly close the fd.  The application
569    * should do so by connecting to the client-fd-removed callback.
570    */
571   gst_multi_fd_sink_signals[SIGNAL_CLEAR] =
572       g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
573       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstMultiFdSinkClass,
574           clear), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
575
576   /**
577    * GstMultiFdSink::get-stats:
578    * @gstmultifdsink: the multifdsink element to emit this signal on
579    * @fd:             the file descriptor to get stats of from multifdsink
580    *
581    * Get statistics about @fd. This function returns a GValueArray to ease
582    * automatic wrapping for bindings.
583    *
584    * Returns: a GValueArray with the statistics. The array contains guint64
585    *     values that represent respectively: total number of bytes sent, time
586    *     when the client was added, time when the client was
587    *     disconnected/removed, time the client is/was active, last activity
588    *     time (in epoch seconds), number of buffers dropped.
589    *     All times are expressed in nanoseconds (GstClockTime).
590    *     The array can be 0-length if the client was not found.
591    */
592   gst_multi_fd_sink_signals[SIGNAL_GET_STATS] =
593       g_signal_new ("get-stats", G_TYPE_FROM_CLASS (klass),
594       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (GstMultiFdSinkClass,
595           get_stats), NULL, NULL, gst_tcp_marshal_BOXED__INT,
596       G_TYPE_VALUE_ARRAY, 1, G_TYPE_INT);
597
598   /**
599    * GstMultiFdSink::client-added:
600    * @gstmultifdsink: the multifdsink element that emitted this signal
601    * @fd:             the file descriptor that was added to multifdsink
602    *
603    * The given file descriptor was added to multifdsink. This signal will
604    * be emitted from the streaming thread so application should be prepared
605    * for that.
606    */
607   gst_multi_fd_sink_signals[SIGNAL_CLIENT_ADDED] =
608       g_signal_new ("client-added", G_TYPE_FROM_CLASS (klass),
609       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiFdSinkClass, client_added),
610       NULL, NULL, gst_tcp_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT);
611   /**
612    * GstMultiFdSink::client-removed:
613    * @gstmultifdsink: the multifdsink element that emitted this signal
614    * @fd:             the file descriptor that is to be removed from multifdsink
615    * @status:         the reason why the client was removed
616    *
617    * The given file descriptor is about to be removed from multifdsink. This
618    * signal will be emitted from the streaming thread so applications should
619    * be prepared for that.
620    *
621    * @gstmultifdsink still holds a handle to @fd so it is possible to call
622    * the get-stats signal from this callback. For the same reason it is
623    * not safe to close() and reuse @fd in this callback.
624    */
625   gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED] =
626       g_signal_new ("client-removed", G_TYPE_FROM_CLASS (klass),
627       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiFdSinkClass,
628           client_removed), NULL, NULL, gst_tcp_marshal_VOID__INT_BOXED,
629       G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CLIENT_STATUS);
630   /**
631    * GstMultiFdSink::client-fd-removed:
632    * @gstmultifdsink: the multifdsink element that emitted this signal
633    * @fd:             the file descriptor that was removed from multifdsink
634    *
635    * The given file descriptor was removed from multifdsink. This signal will
636    * be emitted from the streaming thread so applications should be prepared
637    * for that.
638    *
639    * In this callback, @gstmultifdsink has removed all the information
640    * associated with @fd and it is therefore not possible to call get-stats
641    * with @fd. It is however safe to close() and reuse @fd in the callback.
642    *
643    * Since: 0.10.7
644    */
645   gst_multi_fd_sink_signals[SIGNAL_CLIENT_FD_REMOVED] =
646       g_signal_new ("client-fd-removed", G_TYPE_FROM_CLASS (klass),
647       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstMultiFdSinkClass,
648           client_fd_removed), NULL, NULL, gst_tcp_marshal_VOID__INT,
649       G_TYPE_NONE, 1, G_TYPE_INT);
650
651   gst_element_class_add_pad_template (gstelement_class,
652       gst_static_pad_template_get (&sinktemplate));
653
654   gst_element_class_set_details_simple (gstelement_class,
655       "Multi filedescriptor sink", "Sink/Network",
656       "Send data to multiple filedescriptors",
657       "Thomas Vander Stichele <thomas at apestaart dot org>, "
658       "Wim Taymans <wim@fluendo.com>");
659
660   gstelement_class->change_state =
661       GST_DEBUG_FUNCPTR (gst_multi_fd_sink_change_state);
662
663   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_render);
664
665   klass->add = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_add);
666   klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_add_full);
667   klass->remove = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_remove);
668   klass->remove_flush = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_remove_flush);
669   klass->clear = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_clear);
670   klass->get_stats = GST_DEBUG_FUNCPTR (gst_multi_fd_sink_get_stats);
671
672   GST_DEBUG_CATEGORY_INIT (multifdsink_debug, "multifdsink", 0, "FD sink");
673 }
674
675 static void
676 gst_multi_fd_sink_init (GstMultiFdSink * this)
677 {
678   GST_OBJECT_FLAG_UNSET (this, GST_MULTI_FD_SINK_OPEN);
679
680   this->mode = DEFAULT_MODE;
681
682   CLIENTS_LOCK_INIT (this);
683   this->clients = NULL;
684   this->fd_hash = g_hash_table_new (g_int_hash, g_int_equal);
685
686   this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
687   this->unit_type = DEFAULT_UNIT_TYPE;
688   this->units_max = DEFAULT_UNITS_MAX;
689   this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
690   this->time_min = DEFAULT_TIME_MIN;
691   this->bytes_min = DEFAULT_BYTES_MIN;
692   this->buffers_min = DEFAULT_BUFFERS_MIN;
693   this->recover_policy = DEFAULT_RECOVER_POLICY;
694
695   this->timeout = DEFAULT_TIMEOUT;
696   this->def_sync_method = DEFAULT_SYNC_METHOD;
697   this->def_burst_unit = DEFAULT_BURST_UNIT;
698   this->def_burst_value = DEFAULT_BURST_VALUE;
699
700   this->qos_dscp = DEFAULT_QOS_DSCP;
701   this->handle_read = DEFAULT_HANDLE_READ;
702
703   this->resend_streamheader = DEFAULT_RESEND_STREAMHEADER;
704
705   this->header_flags = 0;
706 }
707
708 static void
709 gst_multi_fd_sink_finalize (GObject * object)
710 {
711   GstMultiFdSink *this;
712
713   this = GST_MULTI_FD_SINK (object);
714
715   CLIENTS_LOCK_FREE (this);
716   g_hash_table_destroy (this->fd_hash);
717   g_array_free (this->bufqueue, TRUE);
718
719   G_OBJECT_CLASS (parent_class)->finalize (object);
720 }
721
722 static gint
723 setup_dscp_client (GstMultiFdSink * sink, GstTCPClient * client)
724 {
725   gint tos;
726   gint ret;
727   union gst_sockaddr
728   {
729     struct sockaddr sa;
730     struct sockaddr_in6 sa_in6;
731     struct sockaddr_storage sa_stor;
732   } sa;
733   socklen_t slen = sizeof (sa);
734   gint af;
735
736   /* don't touch */
737   if (sink->qos_dscp < 0)
738     return 0;
739
740   if ((ret = getsockname (client->fd.fd, &sa.sa, &slen)) < 0) {
741     GST_DEBUG_OBJECT (sink, "could not get sockname: %s", g_strerror (errno));
742     return ret;
743   }
744
745   af = sa.sa.sa_family;
746
747   /* if this is an IPv4-mapped address then do IPv4 QoS */
748   if (af == AF_INET6) {
749
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");
753       af = AF_INET;
754     }
755   }
756
757   /* extract and shift 6 bits of the DSCP */
758   tos = (sink->qos_dscp & 0x3f) << 2;
759
760   switch (af) {
761     case AF_INET:
762       ret = setsockopt (client->fd.fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos));
763       break;
764     case AF_INET6:
765 #ifdef IPV6_TCLASS
766       ret =
767           setsockopt (client->fd.fd, IPPROTO_IPV6, IPV6_TCLASS, &tos,
768           sizeof (tos));
769       break;
770 #endif
771     default:
772       ret = 0;
773       GST_ERROR_OBJECT (sink, "unsupported AF");
774       break;
775   }
776   if (ret)
777     GST_DEBUG_OBJECT (sink, "could not set DSCP: %s", g_strerror (errno));
778
779   return ret;
780 }
781
782
783 static void
784 setup_dscp (GstMultiFdSink * sink)
785 {
786   GList *clients, *next;
787
788   CLIENTS_LOCK (sink);
789   for (clients = sink->clients; clients; clients = next) {
790     GstTCPClient *client;
791
792     client = (GstTCPClient *) clients->data;
793     next = g_list_next (clients);
794
795     setup_dscp_client (sink, client);
796   }
797   CLIENTS_UNLOCK (sink);
798 }
799
800 /* "add-full" signal implementation */
801 void
802 gst_multi_fd_sink_add_full (GstMultiFdSink * sink, int fd,
803     GstSyncMethod sync_method, GstTCPUnitType min_unit, guint64 min_value,
804     GstTCPUnitType max_unit, guint64 max_value)
805 {
806   GstTCPClient *client;
807   GList *clink;
808   GTimeVal now;
809   gint flags;
810   struct stat statbuf;
811
812   GST_DEBUG_OBJECT (sink, "[fd %5d] adding client, sync_method %d, "
813       "min_unit %d, min_value %" G_GUINT64_FORMAT
814       ", max_unit %d, max_value %" G_GUINT64_FORMAT, fd, sync_method,
815       min_unit, min_value, max_unit, max_value);
816
817   /* do limits check if we can */
818   if (min_unit == max_unit) {
819     if (max_value != -1 && min_value != -1 && max_value < min_value)
820       goto wrong_limits;
821   }
822
823   /* create client datastructure */
824   client = g_new0 (GstTCPClient, 1);
825   client->fd.fd = fd;
826   client->status = GST_CLIENT_STATUS_OK;
827   client->bufpos = -1;
828   client->flushcount = -1;
829   client->bufoffset = 0;
830   client->sending = NULL;
831   client->bytes_sent = 0;
832   client->dropped_buffers = 0;
833   client->avg_queue_size = 0;
834   client->first_buffer_ts = GST_CLOCK_TIME_NONE;
835   client->last_buffer_ts = GST_CLOCK_TIME_NONE;
836   client->new_connection = TRUE;
837   client->burst_min_unit = min_unit;
838   client->burst_min_value = min_value;
839   client->burst_max_unit = max_unit;
840   client->burst_max_value = max_value;
841   client->sync_method = sync_method;
842   client->currently_removing = FALSE;
843
844   /* update start time */
845   g_get_current_time (&now);
846   client->connect_time = GST_TIMEVAL_TO_TIME (now);
847   client->disconnect_time = 0;
848   /* set last activity time to connect time */
849   client->last_activity_time = client->connect_time;
850
851   CLIENTS_LOCK (sink);
852
853   /* check the hash to find a duplicate fd */
854   clink = g_hash_table_lookup (sink->fd_hash, &client->fd.fd);
855   if (clink != NULL)
856     goto duplicate;
857
858   /* we can add the fd now */
859   clink = sink->clients = g_list_prepend (sink->clients, client);
860   g_hash_table_insert (sink->fd_hash, &client->fd.fd, clink);
861   sink->clients_cookie++;
862
863   /* set the socket to non blocking */
864   if (fcntl (fd, F_SETFL, O_NONBLOCK) < 0) {
865     GST_ERROR_OBJECT (sink, "failed to make socket %d non-blocking: %s", fd,
866         g_strerror (errno));
867   }
868
869   /* we always read from a client */
870   gst_poll_add_fd (sink->fdset, &client->fd);
871
872   /* we don't try to read from write only fds */
873   if (sink->handle_read) {
874     flags = fcntl (fd, F_GETFL, 0);
875     if ((flags & O_ACCMODE) != O_WRONLY) {
876       gst_poll_fd_ctl_read (sink->fdset, &client->fd, TRUE);
877     }
878   }
879   /* figure out the mode, can't use send() for non sockets */
880   if (fstat (fd, &statbuf) == 0 && S_ISSOCK (statbuf.st_mode)) {
881     client->is_socket = TRUE;
882     setup_dscp_client (sink, client);
883   }
884
885   gst_poll_restart (sink->fdset);
886
887   CLIENTS_UNLOCK (sink);
888
889   g_signal_emit (G_OBJECT (sink),
890       gst_multi_fd_sink_signals[SIGNAL_CLIENT_ADDED], 0, fd);
891
892   return;
893
894   /* errors */
895 wrong_limits:
896   {
897     GST_WARNING_OBJECT (sink,
898         "[fd %5d] wrong values min =%" G_GUINT64_FORMAT ", max=%"
899         G_GUINT64_FORMAT ", unit %d specified when adding client", fd,
900         min_value, max_value, min_unit);
901     return;
902   }
903 duplicate:
904   {
905     client->status = GST_CLIENT_STATUS_DUPLICATE;
906     CLIENTS_UNLOCK (sink);
907     GST_WARNING_OBJECT (sink, "[fd %5d] duplicate client found, refusing", fd);
908     g_signal_emit (G_OBJECT (sink),
909         gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED], 0, fd,
910         client->status);
911     g_free (client);
912     return;
913   }
914 }
915
916 /* "add" signal implemntation */
917 void
918 gst_multi_fd_sink_add (GstMultiFdSink * sink, int fd)
919 {
920   gst_multi_fd_sink_add_full (sink, fd, sink->def_sync_method,
921       sink->def_burst_unit, sink->def_burst_value, sink->def_burst_unit, -1);
922 }
923
924 /* "remove" signal implementation */
925 void
926 gst_multi_fd_sink_remove (GstMultiFdSink * sink, int fd)
927 {
928   GList *clink;
929
930   GST_DEBUG_OBJECT (sink, "[fd %5d] removing client", fd);
931
932   CLIENTS_LOCK (sink);
933   clink = g_hash_table_lookup (sink->fd_hash, &fd);
934   if (clink != NULL) {
935     GstTCPClient *client = (GstTCPClient *) clink->data;
936
937     if (client->status != GST_CLIENT_STATUS_OK) {
938       GST_INFO_OBJECT (sink,
939           "[fd %5d] Client already disconnecting with status %d",
940           fd, client->status);
941       goto done;
942     }
943
944     client->status = GST_CLIENT_STATUS_REMOVED;
945     gst_multi_fd_sink_remove_client_link (sink, clink);
946     gst_poll_restart (sink->fdset);
947   } else {
948     GST_WARNING_OBJECT (sink, "[fd %5d] no client with this fd found!", fd);
949   }
950
951 done:
952   CLIENTS_UNLOCK (sink);
953 }
954
955 /* "remove-flush" signal implementation */
956 void
957 gst_multi_fd_sink_remove_flush (GstMultiFdSink * sink, int fd)
958 {
959   GList *clink;
960
961   GST_DEBUG_OBJECT (sink, "[fd %5d] flushing client", fd);
962
963   CLIENTS_LOCK (sink);
964   clink = g_hash_table_lookup (sink->fd_hash, &fd);
965   if (clink != NULL) {
966     GstTCPClient *client = (GstTCPClient *) clink->data;
967
968     if (client->status != GST_CLIENT_STATUS_OK) {
969       GST_INFO_OBJECT (sink,
970           "[fd %5d] Client already disconnecting with status %d",
971           fd, client->status);
972       goto done;
973     }
974
975     /* take the position of the client as the number of buffers left to flush.
976      * If the client was at position -1, we flush 0 buffers, 0 == flush 1
977      * buffer, etc... */
978     client->flushcount = client->bufpos + 1;
979     /* mark client as flushing. We can not remove the client right away because
980      * it might have some buffers to flush in the ->sending queue. */
981     client->status = GST_CLIENT_STATUS_FLUSHING;
982   } else {
983     GST_WARNING_OBJECT (sink, "[fd %5d] no client with this fd found!", fd);
984   }
985 done:
986   CLIENTS_UNLOCK (sink);
987 }
988
989 /* can be called both through the signal (i.e. from any thread) or when 
990  * stopping, after the writing thread has shut down */
991 void
992 gst_multi_fd_sink_clear (GstMultiFdSink * sink)
993 {
994   GList *clients, *next;
995   guint32 cookie;
996
997   GST_DEBUG_OBJECT (sink, "clearing all clients");
998
999   CLIENTS_LOCK (sink);
1000 restart:
1001   cookie = sink->clients_cookie;
1002   for (clients = sink->clients; clients; clients = next) {
1003     GstTCPClient *client;
1004
1005     if (cookie != sink->clients_cookie) {
1006       GST_DEBUG_OBJECT (sink, "cookie changed while removing all clients");
1007       goto restart;
1008     }
1009
1010     client = (GstTCPClient *) clients->data;
1011     next = g_list_next (clients);
1012
1013     client->status = GST_CLIENT_STATUS_REMOVED;
1014     gst_multi_fd_sink_remove_client_link (sink, clients);
1015   }
1016   gst_poll_restart (sink->fdset);
1017   CLIENTS_UNLOCK (sink);
1018 }
1019
1020 /* "get-stats" signal implementation
1021  * the array returned contains:
1022  *
1023  * guint64 : bytes_sent
1024  * guint64 : connect time (in nanoseconds, since Epoch)
1025  * guint64 : disconnect time (in nanoseconds, since Epoch)
1026  * guint64 : time the client is/was connected (in nanoseconds)
1027  * guint64 : last activity time (in nanoseconds, since Epoch)
1028  * guint64 : buffers dropped due to recovery
1029  * guint64 : timestamp of the first buffer sent (in nanoseconds)
1030  * guint64 : timestamp of the last buffer sent (in nanoseconds)
1031  */
1032 GValueArray *
1033 gst_multi_fd_sink_get_stats (GstMultiFdSink * sink, int fd)
1034 {
1035   GstTCPClient *client;
1036   GValueArray *result = NULL;
1037   GList *clink;
1038
1039   CLIENTS_LOCK (sink);
1040   clink = g_hash_table_lookup (sink->fd_hash, &fd);
1041   if (clink == NULL)
1042     goto noclient;
1043
1044   client = (GstTCPClient *) clink->data;
1045   if (client != NULL) {
1046     GValue value = { 0 };
1047     guint64 interval;
1048
1049     result = g_value_array_new (7);
1050
1051     g_value_init (&value, G_TYPE_UINT64);
1052     g_value_set_uint64 (&value, client->bytes_sent);
1053     result = g_value_array_append (result, &value);
1054     g_value_unset (&value);
1055     g_value_init (&value, G_TYPE_UINT64);
1056     g_value_set_uint64 (&value, client->connect_time);
1057     result = g_value_array_append (result, &value);
1058     g_value_unset (&value);
1059     if (client->disconnect_time == 0) {
1060       GTimeVal nowtv;
1061
1062       g_get_current_time (&nowtv);
1063
1064       interval = GST_TIMEVAL_TO_TIME (nowtv) - client->connect_time;
1065     } else {
1066       interval = client->disconnect_time - client->connect_time;
1067     }
1068     g_value_init (&value, G_TYPE_UINT64);
1069     g_value_set_uint64 (&value, client->disconnect_time);
1070     result = g_value_array_append (result, &value);
1071     g_value_unset (&value);
1072     g_value_init (&value, G_TYPE_UINT64);
1073     g_value_set_uint64 (&value, interval);
1074     result = g_value_array_append (result, &value);
1075     g_value_unset (&value);
1076     g_value_init (&value, G_TYPE_UINT64);
1077     g_value_set_uint64 (&value, client->last_activity_time);
1078     result = g_value_array_append (result, &value);
1079     g_value_unset (&value);
1080     g_value_init (&value, G_TYPE_UINT64);
1081     g_value_set_uint64 (&value, client->dropped_buffers);
1082     result = g_value_array_append (result, &value);
1083     g_value_unset (&value);
1084     g_value_init (&value, G_TYPE_UINT64);
1085     g_value_set_uint64 (&value, client->first_buffer_ts);
1086     result = g_value_array_append (result, &value);
1087     g_value_unset (&value);
1088     g_value_init (&value, G_TYPE_UINT64);
1089     g_value_set_uint64 (&value, client->last_buffer_ts);
1090     result = g_value_array_append (result, &value);
1091   }
1092
1093 noclient:
1094   CLIENTS_UNLOCK (sink);
1095
1096   /* python doesn't like a NULL pointer yet */
1097   if (result == NULL) {
1098     GST_WARNING_OBJECT (sink, "[fd %5d] no client with this found!", fd);
1099     result = g_value_array_new (0);
1100   }
1101
1102   return result;
1103 }
1104
1105 /* should be called with the clientslock helt.
1106  * Note that we don't close the fd as we didn't open it in the first
1107  * place. An application should connect to the client-fd-removed signal and
1108  * close the fd itself.
1109  */
1110 static void
1111 gst_multi_fd_sink_remove_client_link (GstMultiFdSink * sink, GList * link)
1112 {
1113   int fd;
1114   GTimeVal now;
1115   GstTCPClient *client = (GstTCPClient *) link->data;
1116   GstMultiFdSinkClass *fclass;
1117
1118   fclass = GST_MULTI_FD_SINK_GET_CLASS (sink);
1119
1120   fd = client->fd.fd;
1121
1122   if (client->currently_removing) {
1123     GST_WARNING_OBJECT (sink, "[fd %5d] client is already being removed", fd);
1124     return;
1125   } else {
1126     client->currently_removing = TRUE;
1127   }
1128
1129   /* FIXME: if we keep track of ip we can log it here and signal */
1130   switch (client->status) {
1131     case GST_CLIENT_STATUS_OK:
1132       GST_WARNING_OBJECT (sink, "[fd %5d] removing client %p for no reason",
1133           fd, client);
1134       break;
1135     case GST_CLIENT_STATUS_CLOSED:
1136       GST_DEBUG_OBJECT (sink, "[fd %5d] removing client %p because of close",
1137           fd, client);
1138       break;
1139     case GST_CLIENT_STATUS_REMOVED:
1140       GST_DEBUG_OBJECT (sink,
1141           "[fd %5d] removing client %p because the app removed it", fd, client);
1142       break;
1143     case GST_CLIENT_STATUS_SLOW:
1144       GST_INFO_OBJECT (sink,
1145           "[fd %5d] removing client %p because it was too slow", fd, client);
1146       break;
1147     case GST_CLIENT_STATUS_ERROR:
1148       GST_WARNING_OBJECT (sink,
1149           "[fd %5d] removing client %p because of error", fd, client);
1150       break;
1151     case GST_CLIENT_STATUS_FLUSHING:
1152     default:
1153       GST_WARNING_OBJECT (sink,
1154           "[fd %5d] removing client %p with invalid reason %d", fd, client,
1155           client->status);
1156       break;
1157   }
1158
1159   gst_poll_remove_fd (sink->fdset, &client->fd);
1160
1161   g_get_current_time (&now);
1162   client->disconnect_time = GST_TIMEVAL_TO_TIME (now);
1163
1164   /* free client buffers */
1165   g_slist_foreach (client->sending, (GFunc) gst_mini_object_unref, NULL);
1166   g_slist_free (client->sending);
1167   client->sending = NULL;
1168
1169   if (client->caps)
1170     gst_caps_unref (client->caps);
1171   client->caps = NULL;
1172
1173   /* unlock the mutex before signaling because the signal handler
1174    * might query some properties */
1175   CLIENTS_UNLOCK (sink);
1176
1177   g_signal_emit (G_OBJECT (sink),
1178       gst_multi_fd_sink_signals[SIGNAL_CLIENT_REMOVED], 0, fd, client->status);
1179
1180   /* lock again before we remove the client completely */
1181   CLIENTS_LOCK (sink);
1182
1183   /* fd cannot be reused in the above signal callback so we can safely
1184    * remove it from the hashtable here */
1185   if (!g_hash_table_remove (sink->fd_hash, &client->fd.fd)) {
1186     GST_WARNING_OBJECT (sink,
1187         "[fd %5d] error removing client %p from hash", client->fd.fd, client);
1188   }
1189   /* after releasing the lock above, the link could be invalid, more
1190    * precisely, the next and prev pointers could point to invalid list
1191    * links. One optimisation could be to add a cookie to the linked list
1192    * and take a shortcut when it did not change between unlocking and locking
1193    * our mutex. For now we just walk the list again. */
1194   sink->clients = g_list_remove (sink->clients, client);
1195   sink->clients_cookie++;
1196
1197   if (fclass->removed)
1198     fclass->removed (sink, client->fd.fd);
1199
1200   g_free (client);
1201   CLIENTS_UNLOCK (sink);
1202
1203   /* and the fd is really gone now */
1204   g_signal_emit (G_OBJECT (sink),
1205       gst_multi_fd_sink_signals[SIGNAL_CLIENT_FD_REMOVED], 0, fd);
1206
1207   CLIENTS_LOCK (sink);
1208 }
1209
1210 /* handle a read on a client fd,
1211  * which either indicates a close or should be ignored
1212  * returns FALSE if some error occured or the client closed. */
1213 static gboolean
1214 gst_multi_fd_sink_handle_client_read (GstMultiFdSink * sink,
1215     GstTCPClient * client)
1216 {
1217   int avail, fd;
1218   gboolean ret;
1219
1220   fd = client->fd.fd;
1221
1222   if (ioctl (fd, FIONREAD, &avail) < 0)
1223     goto ioctl_failed;
1224
1225   GST_DEBUG_OBJECT (sink, "[fd %5d] select reports client read of %d bytes",
1226       fd, avail);
1227
1228   ret = TRUE;
1229
1230   if (avail == 0) {
1231     /* client sent close, so remove it */
1232     GST_DEBUG_OBJECT (sink, "[fd %5d] client asked for close, removing", fd);
1233     client->status = GST_CLIENT_STATUS_CLOSED;
1234     ret = FALSE;
1235   } else if (avail < 0) {
1236     GST_WARNING_OBJECT (sink, "[fd %5d] avail < 0, removing", fd);
1237     client->status = GST_CLIENT_STATUS_ERROR;
1238     ret = FALSE;
1239   } else {
1240     guint8 dummy[512];
1241     gint nread;
1242
1243     /* just Read 'n' Drop, could also just drop the client as it's not supposed
1244      * to write to us except for closing the socket, I guess it's because we
1245      * like to listen to our customers. */
1246     do {
1247       /* this is the maximum we can read */
1248       gint to_read = MIN (avail, 512);
1249
1250       GST_DEBUG_OBJECT (sink, "[fd %5d] client wants us to read %d bytes",
1251           fd, to_read);
1252
1253       nread = read (fd, dummy, to_read);
1254       if (nread < -1) {
1255         GST_WARNING_OBJECT (sink, "[fd %5d] could not read %d bytes: %s (%d)",
1256             fd, to_read, g_strerror (errno), errno);
1257         client->status = GST_CLIENT_STATUS_ERROR;
1258         ret = FALSE;
1259         break;
1260       } else if (nread == 0) {
1261         GST_WARNING_OBJECT (sink, "[fd %5d] 0 bytes in read, removing", fd);
1262         client->status = GST_CLIENT_STATUS_ERROR;
1263         ret = FALSE;
1264         break;
1265       }
1266       avail -= nread;
1267     }
1268     while (avail > 0);
1269   }
1270   return ret;
1271
1272   /* ERRORS */
1273 ioctl_failed:
1274   {
1275     GST_WARNING_OBJECT (sink, "[fd %5d] ioctl failed: %s (%d)",
1276         fd, g_strerror (errno), errno);
1277     client->status = GST_CLIENT_STATUS_ERROR;
1278     return FALSE;
1279   }
1280 }
1281
1282 static gboolean
1283 is_sync_frame (GstMultiFdSink * sink, GstBuffer * buffer)
1284 {
1285   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1286     return FALSE;
1287   } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_IN_CAPS)) {
1288     return TRUE;
1289   }
1290
1291   return FALSE;
1292 }
1293
1294 /* queue the given buffer for the given client, possibly adding the GDP
1295  * header if GDP is being used */
1296 static gboolean
1297 gst_multi_fd_sink_client_queue_buffer (GstMultiFdSink * sink,
1298     GstTCPClient * client, GstBuffer * buffer)
1299 {
1300   GstCaps *caps;
1301
1302   /* TRUE: send them if the new caps have them */
1303   gboolean send_streamheader = FALSE;
1304   GstStructure *s;
1305
1306 #if 0
1307   /* before we queue the buffer, we check if we need to queue streamheader
1308    * buffers (because it's a new client, or because they changed) */
1309   caps = gst_buffer_get_caps (buffer);  /* cleaned up after streamheader */
1310 #else
1311   caps = NULL;
1312 #endif
1313   if (!client->caps) {
1314     GST_DEBUG_OBJECT (sink,
1315         "[fd %5d] no previous caps for this client, send streamheader",
1316         client->fd.fd);
1317     send_streamheader = TRUE;
1318     client->caps = gst_caps_ref (caps);
1319   } else {
1320     /* there were previous caps recorded, so compare */
1321     if (!gst_caps_is_equal (caps, client->caps)) {
1322       const GValue *sh1, *sh2;
1323
1324       /* caps are not equal, but could still have the same streamheader */
1325       s = gst_caps_get_structure (caps, 0);
1326       if (!gst_structure_has_field (s, "streamheader")) {
1327         /* no new streamheader, so nothing new to send */
1328         GST_DEBUG_OBJECT (sink,
1329             "[fd %5d] new caps do not have streamheader, not sending",
1330             client->fd.fd);
1331       } else {
1332         /* there is a new streamheader */
1333         s = gst_caps_get_structure (client->caps, 0);
1334         if (!gst_structure_has_field (s, "streamheader")) {
1335           /* no previous streamheader, so send the new one */
1336           GST_DEBUG_OBJECT (sink,
1337               "[fd %5d] previous caps did not have streamheader, sending",
1338               client->fd.fd);
1339           send_streamheader = TRUE;
1340         } else {
1341           /* both old and new caps have streamheader set */
1342           if (!sink->resend_streamheader) {
1343             GST_DEBUG_OBJECT (sink,
1344                 "[fd %5d] asked to not resend the streamheader, not sending",
1345                 client->fd.fd);
1346             send_streamheader = FALSE;
1347           } else {
1348             sh1 = gst_structure_get_value (s, "streamheader");
1349             s = gst_caps_get_structure (caps, 0);
1350             sh2 = gst_structure_get_value (s, "streamheader");
1351             if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1352               GST_DEBUG_OBJECT (sink,
1353                   "[fd %5d] new streamheader different from old, sending",
1354                   client->fd.fd);
1355               send_streamheader = TRUE;
1356             }
1357           }
1358         }
1359       }
1360     }
1361     /* Replace the old caps */
1362     gst_caps_unref (client->caps);
1363     client->caps = gst_caps_ref (caps);
1364   }
1365
1366   if (G_UNLIKELY (send_streamheader)) {
1367     const GValue *sh;
1368     GArray *buffers;
1369     int i;
1370
1371     GST_LOG_OBJECT (sink,
1372         "[fd %5d] sending streamheader from caps %" GST_PTR_FORMAT,
1373         client->fd.fd, caps);
1374     s = gst_caps_get_structure (caps, 0);
1375     if (!gst_structure_has_field (s, "streamheader")) {
1376       GST_DEBUG_OBJECT (sink,
1377           "[fd %5d] no new streamheader, so nothing to send", client->fd.fd);
1378     } else {
1379       GST_LOG_OBJECT (sink,
1380           "[fd %5d] sending streamheader from caps %" GST_PTR_FORMAT,
1381           client->fd.fd, caps);
1382       sh = gst_structure_get_value (s, "streamheader");
1383       g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1384       buffers = g_value_peek_pointer (sh);
1385       GST_DEBUG_OBJECT (sink, "%d streamheader buffers", buffers->len);
1386       for (i = 0; i < buffers->len; ++i) {
1387         GValue *bufval;
1388         GstBuffer *buffer;
1389
1390         bufval = &g_array_index (buffers, GValue, i);
1391         g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1392         buffer = g_value_peek_pointer (bufval);
1393         GST_DEBUG_OBJECT (sink,
1394             "[fd %5d] queueing streamheader buffer of length %" G_GSIZE_FORMAT,
1395             client->fd.fd, gst_buffer_get_size (buffer));
1396         gst_buffer_ref (buffer);
1397
1398         client->sending = g_slist_append (client->sending, buffer);
1399       }
1400     }
1401   }
1402
1403   gst_caps_unref (caps);
1404   caps = NULL;
1405
1406   GST_LOG_OBJECT (sink, "[fd %5d] queueing buffer of length %" G_GSIZE_FORMAT,
1407       client->fd.fd, gst_buffer_get_size (buffer));
1408
1409   gst_buffer_ref (buffer);
1410   client->sending = g_slist_append (client->sending, buffer);
1411
1412   return TRUE;
1413 }
1414
1415 /* find the keyframe in the list of buffers starting the
1416  * search from @idx. @direction as -1 will search backwards, 
1417  * 1 will search forwards.
1418  * Returns: the index or -1 if there is no keyframe after idx.
1419  */
1420 static gint
1421 find_syncframe (GstMultiFdSink * sink, gint idx, gint direction)
1422 {
1423   gint i, len, result;
1424
1425   /* take length of queued buffers */
1426   len = sink->bufqueue->len;
1427
1428   /* assume we don't find a keyframe */
1429   result = -1;
1430
1431   /* then loop over all buffers to find the first keyframe */
1432   for (i = idx; i >= 0 && i < len; i += direction) {
1433     GstBuffer *buf;
1434
1435     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1436     if (is_sync_frame (sink, buf)) {
1437       GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1438           i, idx, direction);
1439       result = i;
1440       break;
1441     }
1442   }
1443   return result;
1444 }
1445
1446 #define find_next_syncframe(s,i)        find_syncframe(s,i,1)
1447 #define find_prev_syncframe(s,i)        find_syncframe(s,i,-1)
1448
1449 /* Get the number of buffers from the buffer queue needed to satisfy
1450  * the maximum max in the configured units.
1451  * If units are not BUFFERS, and there are insufficient buffers in the
1452  * queue to satify the limit, return len(queue) + 1 */
1453 static gint
1454 get_buffers_max (GstMultiFdSink * sink, gint64 max)
1455 {
1456   switch (sink->unit_type) {
1457     case GST_TCP_UNIT_TYPE_BUFFERS:
1458       return max;
1459     case GST_TCP_UNIT_TYPE_TIME:
1460     {
1461       GstBuffer *buf;
1462       int i;
1463       int len;
1464       gint64 diff;
1465       GstClockTime first = GST_CLOCK_TIME_NONE;
1466
1467       len = sink->bufqueue->len;
1468
1469       for (i = 0; i < len; i++) {
1470         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1471         if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1472           if (first == -1)
1473             first = GST_BUFFER_TIMESTAMP (buf);
1474
1475           diff = first - GST_BUFFER_TIMESTAMP (buf);
1476
1477           if (diff > max)
1478             return i + 1;
1479         }
1480       }
1481       return len + 1;
1482     }
1483     case GST_TCP_UNIT_TYPE_BYTES:
1484     {
1485       GstBuffer *buf;
1486       int i;
1487       int len;
1488       gint acc = 0;
1489
1490       len = sink->bufqueue->len;
1491
1492       for (i = 0; i < len; i++) {
1493         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1494         acc += gst_buffer_get_size (buf);
1495
1496         if (acc > max)
1497           return i + 1;
1498       }
1499       return len + 1;
1500     }
1501     default:
1502       return max;
1503   }
1504 }
1505
1506 /* find the positions in the buffer queue where *_min and *_max
1507  * is satisfied
1508  */
1509 /* count the amount of data in the buffers and return the index
1510  * that satifies the given limits.
1511  *
1512  * Returns: index @idx in the buffer queue so that the given limits are
1513  * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1514  * enough data was in the queue.
1515  *
1516  * FIXME, this code might now work if any of the units is in buffers...
1517  */
1518 static gboolean
1519 find_limits (GstMultiFdSink * sink,
1520     gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1521     gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1522 {
1523   GstClockTime first, time;
1524   gint i, len, bytes;
1525   gboolean result, max_hit;
1526
1527   /* take length of queue */
1528   len = sink->bufqueue->len;
1529
1530   /* this must hold */
1531   g_assert (len > 0);
1532
1533   GST_LOG_OBJECT (sink,
1534       "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1535       ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1536       buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1537       GST_TIME_ARGS (time_max));
1538
1539   /* do the trivial buffer limit test */
1540   if (buffers_min != -1 && len < buffers_min) {
1541     *min_idx = len - 1;
1542     *max_idx = len - 1;
1543     return FALSE;
1544   }
1545
1546   result = FALSE;
1547   /* else count bytes and time */
1548   first = -1;
1549   bytes = 0;
1550   /* unset limits */
1551   *min_idx = -1;
1552   *max_idx = -1;
1553   max_hit = FALSE;
1554
1555   i = 0;
1556   /* loop through the buffers, when a limit is ok, mark it 
1557    * as -1, we have at least one buffer in the queue. */
1558   do {
1559     GstBuffer *buf;
1560
1561     /* if we checked all min limits, update result */
1562     if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1563       /* don't go below 0 */
1564       *min_idx = MAX (i - 1, 0);
1565     }
1566     /* if we reached one max limit break out */
1567     if (max_hit) {
1568       /* i > 0 when we get here, we subtract one to get the position
1569        * of the previous buffer. */
1570       *max_idx = i - 1;
1571       /* we have valid complete result if we found a min_idx too */
1572       result = *min_idx != -1;
1573       break;
1574     }
1575     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1576
1577     bytes += gst_buffer_get_size (buf);
1578
1579     /* take timestamp and save for the base first timestamp */
1580     if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1581       GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1582           GST_TIME_ARGS (time));
1583       if (first == -1)
1584         first = time;
1585
1586       /* increase max usage if we did not fill enough. Note that
1587        * buffers are sorted from new to old, so the first timestamp is
1588        * bigger than the next one. */
1589       if (time_min != -1 && first - time >= time_min)
1590         time_min = -1;
1591       if (time_max != -1 && first - time >= time_max)
1592         max_hit = TRUE;
1593     } else {
1594       GST_LOG_OBJECT (sink, "No timestamp on buffer");
1595     }
1596     /* time is OK or unknown, check and increase if not enough bytes */
1597     if (bytes_min != -1) {
1598       if (bytes >= bytes_min)
1599         bytes_min = -1;
1600     }
1601     if (bytes_max != -1) {
1602       if (bytes >= bytes_max) {
1603         max_hit = TRUE;
1604       }
1605     }
1606     i++;
1607   }
1608   while (i < len);
1609
1610   /* if we did not hit the max or min limit, set to buffer size */
1611   if (*max_idx == -1)
1612     *max_idx = len - 1;
1613   /* make sure min does not exceed max */
1614   if (*min_idx == -1)
1615     *min_idx = *max_idx;
1616
1617   return result;
1618 }
1619
1620 /* parse the unit/value pair and assign it to the result value of the
1621  * right type, leave the other values untouched 
1622  *
1623  * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1624  */
1625 static gboolean
1626 assign_value (GstTCPUnitType unit, guint64 value, gint * bytes, gint * buffers,
1627     GstClockTime * time)
1628 {
1629   gboolean res = TRUE;
1630
1631   /* set only the limit of the given format to the given value */
1632   switch (unit) {
1633     case GST_TCP_UNIT_TYPE_BUFFERS:
1634       *buffers = (gint) value;
1635       break;
1636     case GST_TCP_UNIT_TYPE_TIME:
1637       *time = value;
1638       break;
1639     case GST_TCP_UNIT_TYPE_BYTES:
1640       *bytes = (gint) value;
1641       break;
1642     case GST_TCP_UNIT_TYPE_UNDEFINED:
1643     default:
1644       res = FALSE;
1645       break;
1646   }
1647   return res;
1648 }
1649
1650 /* count the index in the buffer queue to satisfy the given unit
1651  * and value pair starting from buffer at index 0.
1652  *
1653  * Returns: TRUE if there was enough data in the queue to satisfy the
1654  * burst values. @idx contains the index in the buffer that contains enough
1655  * data to satisfy the limits or the last buffer in the queue when the
1656  * function returns FALSE.
1657  */
1658 static gboolean
1659 count_burst_unit (GstMultiFdSink * sink, gint * min_idx,
1660     GstTCPUnitType min_unit, guint64 min_value, gint * max_idx,
1661     GstTCPUnitType max_unit, guint64 max_value)
1662 {
1663   gint bytes_min = -1, buffers_min = -1;
1664   gint bytes_max = -1, buffers_max = -1;
1665   GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1666
1667   assign_value (min_unit, min_value, &bytes_min, &buffers_min, &time_min);
1668   assign_value (max_unit, max_value, &bytes_max, &buffers_max, &time_max);
1669
1670   return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1671       max_idx, bytes_max, buffers_max, time_max);
1672 }
1673
1674 /* decide where in the current buffer queue this new client should start
1675  * receiving buffers from.
1676  * This function is called whenever a client is connected and has not yet
1677  * received a buffer.
1678  * If this returns -1, it means that we haven't found a good point to
1679  * start streaming from yet, and this function should be called again later
1680  * when more buffers have arrived.
1681  */
1682 static gint
1683 gst_multi_fd_sink_new_client (GstMultiFdSink * sink, GstTCPClient * client)
1684 {
1685   gint result;
1686
1687   GST_DEBUG_OBJECT (sink,
1688       "[fd %5d] new client, deciding where to start in queue", client->fd.fd);
1689   GST_DEBUG_OBJECT (sink, "queue is currently %d buffers long",
1690       sink->bufqueue->len);
1691   switch (client->sync_method) {
1692     case GST_SYNC_METHOD_LATEST:
1693       /* no syncing, we are happy with whatever the client is going to get */
1694       result = client->bufpos;
1695       GST_DEBUG_OBJECT (sink,
1696           "[fd %5d] SYNC_METHOD_LATEST, position %d", client->fd.fd, result);
1697       break;
1698     case GST_SYNC_METHOD_NEXT_KEYFRAME:
1699     {
1700       /* if one of the new buffers (between client->bufpos and 0) in the queue
1701        * is a sync point, we can proceed, otherwise we need to keep waiting */
1702       GST_LOG_OBJECT (sink,
1703           "[fd %5d] new client, bufpos %d, waiting for keyframe", client->fd.fd,
1704           client->bufpos);
1705
1706       result = find_prev_syncframe (sink, client->bufpos);
1707       if (result != -1) {
1708         GST_DEBUG_OBJECT (sink,
1709             "[fd %5d] SYNC_METHOD_NEXT_KEYFRAME: result %d",
1710             client->fd.fd, result);
1711         break;
1712       }
1713
1714       /* client is not on a syncbuffer, need to skip these buffers and
1715        * wait some more */
1716       GST_LOG_OBJECT (sink,
1717           "[fd %5d] new client, skipping buffer(s), no syncpoint found",
1718           client->fd.fd);
1719       client->bufpos = -1;
1720       break;
1721     }
1722     case GST_SYNC_METHOD_LATEST_KEYFRAME:
1723     {
1724       GST_DEBUG_OBJECT (sink,
1725           "[fd %5d] SYNC_METHOD_LATEST_KEYFRAME", client->fd.fd);
1726
1727       /* for new clients we initially scan the complete buffer queue for
1728        * a sync point when a buffer is added. If we don't find a keyframe,
1729        * we need to wait for the next keyframe and so we change the client's
1730        * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1731        */
1732       result = find_next_syncframe (sink, 0);
1733       if (result != -1) {
1734         GST_DEBUG_OBJECT (sink,
1735             "[fd %5d] SYNC_METHOD_LATEST_KEYFRAME: result %d", client->fd.fd,
1736             result);
1737         break;
1738       }
1739
1740       GST_DEBUG_OBJECT (sink,
1741           "[fd %5d] SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1742           "switching to SYNC_METHOD_NEXT_KEYFRAME", client->fd.fd);
1743       /* throw client to the waiting state */
1744       client->bufpos = -1;
1745       /* and make client sync to next keyframe */
1746       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1747       break;
1748     }
1749     case GST_SYNC_METHOD_BURST:
1750     {
1751       gboolean ok;
1752       gint max;
1753
1754       /* move to the position where we satisfy the client's burst
1755        * parameters. If we could not satisfy the parameters because there
1756        * is not enough data, we just send what we have (which is in result).
1757        * We use the max value to limit the search
1758        */
1759       ok = count_burst_unit (sink, &result, client->burst_min_unit,
1760           client->burst_min_value, &max, client->burst_max_unit,
1761           client->burst_max_value);
1762       GST_DEBUG_OBJECT (sink,
1763           "[fd %5d] SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1764           client->fd.fd, ok, result);
1765
1766       GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1767
1768       /* we hit the max and it is below the min, use that then */
1769       if (max != -1 && max <= result) {
1770         result = MAX (max - 1, 0);
1771         GST_DEBUG_OBJECT (sink,
1772             "[fd %5d] SYNC_METHOD_BURST: result above max, taken down to %d",
1773             client->fd.fd, result);
1774       }
1775       break;
1776     }
1777     case GST_SYNC_METHOD_BURST_KEYFRAME:
1778     {
1779       gint min_idx, max_idx;
1780       gint next_syncframe, prev_syncframe;
1781
1782       /* BURST_KEYFRAME:
1783        *
1784        * _always_ start sending a keyframe to the client. We first search
1785        * a keyframe between min/max limits. If there is none, we send it the
1786        * last keyframe before min. If there is none, the behaviour is like
1787        * NEXT_KEYFRAME.
1788        */
1789       /* gather burst limits */
1790       count_burst_unit (sink, &min_idx, client->burst_min_unit,
1791           client->burst_min_value, &max_idx, client->burst_max_unit,
1792           client->burst_max_value);
1793
1794       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1795
1796       /* first find a keyframe after min_idx */
1797       next_syncframe = find_next_syncframe (sink, min_idx);
1798       if (next_syncframe != -1 && next_syncframe < max_idx) {
1799         /* we have a valid keyframe and it's below the max */
1800         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1801         result = next_syncframe;
1802         break;
1803       }
1804
1805       /* no valid keyframe, try to find one below min */
1806       prev_syncframe = find_prev_syncframe (sink, min_idx);
1807       if (prev_syncframe != -1) {
1808         GST_WARNING_OBJECT (sink,
1809             "using keyframe below min in BURST_KEYFRAME sync mode");
1810         result = prev_syncframe;
1811         break;
1812       }
1813
1814       /* no prev keyframe or not enough data  */
1815       GST_WARNING_OBJECT (sink,
1816           "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1817
1818       /* throw client to the waiting state */
1819       client->bufpos = -1;
1820       /* and make client sync to next keyframe */
1821       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1822       result = -1;
1823       break;
1824     }
1825     case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1826     {
1827       gint min_idx, max_idx;
1828       gint next_syncframe;
1829
1830       /* BURST_WITH_KEYFRAME:
1831        *
1832        * try to start sending a keyframe to the client. We first search
1833        * a keyframe between min/max limits. If there is none, we send it the
1834        * amount of data up 'till min.
1835        */
1836       /* gather enough data to burst */
1837       count_burst_unit (sink, &min_idx, client->burst_min_unit,
1838           client->burst_min_value, &max_idx, client->burst_max_unit,
1839           client->burst_max_value);
1840
1841       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1842
1843       /* first find a keyframe after min_idx */
1844       next_syncframe = find_next_syncframe (sink, min_idx);
1845       if (next_syncframe != -1 && next_syncframe < max_idx) {
1846         /* we have a valid keyframe and it's below the max */
1847         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1848         result = next_syncframe;
1849         break;
1850       }
1851
1852       /* no keyframe, send data from min_idx */
1853       GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1854
1855       /* make sure we don't go over the max limit */
1856       if (max_idx != -1 && max_idx <= min_idx) {
1857         result = MAX (max_idx - 1, 0);
1858       } else {
1859         result = min_idx;
1860       }
1861
1862       break;
1863     }
1864     default:
1865       g_warning ("unknown sync method %d", client->sync_method);
1866       result = client->bufpos;
1867       break;
1868   }
1869   return result;
1870 }
1871
1872 /* Handle a write on a client,
1873  * which indicates a read request from a client.
1874  *
1875  * For each client we maintain a queue of GstBuffers that contain the raw bytes
1876  * we need to send to the client. In the case of the GDP protocol, we create
1877  * buffers out of the header bytes so that we can focus only on sending
1878  * buffers.
1879  *
1880  * We first check to see if we need to send caps (in GDP) and streamheaders.
1881  * If so, we queue them.
1882  *
1883  * Then we run into the main loop that tries to send as many buffers as
1884  * possible. It will first exhaust the client->sending queue and if the queue
1885  * is empty, it will pick a buffer from the global queue.
1886  *
1887  * Sending the buffers from the client->sending queue is basically writing
1888  * the bytes to the socket and maintaining a count of the bytes that were
1889  * sent. When the buffer is completely sent, it is removed from the
1890  * client->sending queue and we try to pick a new buffer for sending.
1891  *
1892  * When the sending returns a partial buffer we stop sending more data as
1893  * the next send operation could block.
1894  *
1895  * This functions returns FALSE if some error occured.
1896  */
1897 static gboolean
1898 gst_multi_fd_sink_handle_client_write (GstMultiFdSink * sink,
1899     GstTCPClient * client)
1900 {
1901   int fd = client->fd.fd;
1902   gboolean more;
1903   gboolean flushing;
1904   GstClockTime now;
1905   GTimeVal nowtv;
1906
1907   g_get_current_time (&nowtv);
1908   now = GST_TIMEVAL_TO_TIME (nowtv);
1909
1910   flushing = client->status == GST_CLIENT_STATUS_FLUSHING;
1911
1912   more = TRUE;
1913   do {
1914     gint maxsize;
1915
1916     if (!client->sending) {
1917       /* client is not working on a buffer */
1918       if (client->bufpos == -1) {
1919         /* client is too fast, remove from write queue until new buffer is
1920          * available */
1921         gst_poll_fd_ctl_write (sink->fdset, &client->fd, FALSE);
1922         /* if we flushed out all of the client buffers, we can stop */
1923         if (client->flushcount == 0)
1924           goto flushed;
1925
1926         return TRUE;
1927       } else {
1928         /* client can pick a buffer from the global queue */
1929         GstBuffer *buf;
1930         GstClockTime timestamp;
1931
1932         /* for new connections, we need to find a good spot in the
1933          * bufqueue to start streaming from */
1934         if (client->new_connection && !flushing) {
1935           gint position = gst_multi_fd_sink_new_client (sink, client);
1936
1937           if (position >= 0) {
1938             /* we got a valid spot in the queue */
1939             client->new_connection = FALSE;
1940             client->bufpos = position;
1941           } else {
1942             /* cannot send data to this client yet */
1943             gst_poll_fd_ctl_write (sink->fdset, &client->fd, FALSE);
1944             return TRUE;
1945           }
1946         }
1947
1948         /* we flushed all remaining buffers, no need to get a new one */
1949         if (client->flushcount == 0)
1950           goto flushed;
1951
1952         /* grab buffer */
1953         buf = g_array_index (sink->bufqueue, GstBuffer *, client->bufpos);
1954         client->bufpos--;
1955
1956         /* update stats */
1957         timestamp = GST_BUFFER_TIMESTAMP (buf);
1958         if (client->first_buffer_ts == GST_CLOCK_TIME_NONE)
1959           client->first_buffer_ts = timestamp;
1960         if (timestamp != -1)
1961           client->last_buffer_ts = timestamp;
1962
1963         /* decrease flushcount */
1964         if (client->flushcount != -1)
1965           client->flushcount--;
1966
1967         GST_LOG_OBJECT (sink, "[fd %5d] client %p at position %d",
1968             fd, client, client->bufpos);
1969
1970         /* queueing a buffer will ref it */
1971         gst_multi_fd_sink_client_queue_buffer (sink, client, buf);
1972
1973         /* need to start from the first byte for this new buffer */
1974         client->bufoffset = 0;
1975       }
1976     }
1977
1978     /* see if we need to send something */
1979     if (client->sending) {
1980       ssize_t wrote;
1981       GstBuffer *head;
1982       guint8 *data;
1983       gsize size;
1984
1985       /* pick first buffer from list */
1986       head = GST_BUFFER (client->sending->data);
1987
1988       data = gst_buffer_map (head, &size, NULL, GST_MAP_READ);
1989       maxsize = size - client->bufoffset;
1990
1991       /* try to write the complete buffer */
1992 #ifdef MSG_NOSIGNAL
1993 #define FLAGS MSG_NOSIGNAL
1994 #else
1995 #define FLAGS 0
1996 #endif
1997       if (client->is_socket) {
1998         wrote = send (fd, data + client->bufoffset, maxsize, FLAGS);
1999       } else {
2000         wrote = write (fd, data + client->bufoffset, maxsize);
2001       }
2002       gst_buffer_unmap (head, data, size);
2003
2004       if (wrote < 0) {
2005         /* hmm error.. */
2006         if (errno == EAGAIN) {
2007           /* nothing serious, resource was unavailable, try again later */
2008           more = FALSE;
2009         } else if (errno == ECONNRESET) {
2010           goto connection_reset;
2011         } else {
2012           goto write_error;
2013         }
2014       } else {
2015         if (wrote < maxsize) {
2016           /* partial write means that the client cannot read more and we should
2017            * stop sending more */
2018           GST_LOG_OBJECT (sink,
2019               "partial write on %d of %" G_GSSIZE_FORMAT " bytes", fd, wrote);
2020           client->bufoffset += wrote;
2021           more = FALSE;
2022         } else {
2023           /* complete buffer was written, we can proceed to the next one */
2024           client->sending = g_slist_remove (client->sending, head);
2025           gst_buffer_unref (head);
2026           /* make sure we start from byte 0 for the next buffer */
2027           client->bufoffset = 0;
2028         }
2029         /* update stats */
2030         client->bytes_sent += wrote;
2031         client->last_activity_time = now;
2032         sink->bytes_served += wrote;
2033       }
2034     }
2035   } while (more);
2036
2037   return TRUE;
2038
2039   /* ERRORS */
2040 flushed:
2041   {
2042     GST_DEBUG_OBJECT (sink, "[fd %5d] flushed, removing", fd);
2043     client->status = GST_CLIENT_STATUS_REMOVED;
2044     return FALSE;
2045   }
2046 connection_reset:
2047   {
2048     GST_DEBUG_OBJECT (sink, "[fd %5d] connection reset by peer, removing", fd);
2049     client->status = GST_CLIENT_STATUS_CLOSED;
2050     return FALSE;
2051   }
2052 write_error:
2053   {
2054     GST_WARNING_OBJECT (sink,
2055         "[fd %5d] could not write, removing client: %s (%d)", fd,
2056         g_strerror (errno), errno);
2057     client->status = GST_CLIENT_STATUS_ERROR;
2058     return FALSE;
2059   }
2060 }
2061
2062 /* calculate the new position for a client after recovery. This function
2063  * does not update the client position but merely returns the required
2064  * position.
2065  */
2066 static gint
2067 gst_multi_fd_sink_recover_client (GstMultiFdSink * sink, GstTCPClient * client)
2068 {
2069   gint newbufpos;
2070
2071   GST_WARNING_OBJECT (sink,
2072       "[fd %5d] client %p is lagging at %d, recover using policy %d",
2073       client->fd.fd, client, client->bufpos, sink->recover_policy);
2074
2075   switch (sink->recover_policy) {
2076     case GST_RECOVER_POLICY_NONE:
2077       /* do nothing, client will catch up or get kicked out when it reaches
2078        * the hard max */
2079       newbufpos = client->bufpos;
2080       break;
2081     case GST_RECOVER_POLICY_RESYNC_LATEST:
2082       /* move to beginning of queue */
2083       newbufpos = -1;
2084       break;
2085     case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
2086       /* move to beginning of soft max */
2087       newbufpos = get_buffers_max (sink, sink->units_soft_max);
2088       break;
2089     case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
2090       /* find keyframe in buffers, we search backwards to find the
2091        * closest keyframe relative to what this client already received. */
2092       newbufpos = MIN (sink->bufqueue->len - 1,
2093           get_buffers_max (sink, sink->units_soft_max) - 1);
2094
2095       while (newbufpos >= 0) {
2096         GstBuffer *buf;
2097
2098         buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
2099         if (is_sync_frame (sink, buf)) {
2100           /* found a buffer that is not a delta unit */
2101           break;
2102         }
2103         newbufpos--;
2104       }
2105       break;
2106     default:
2107       /* unknown recovery procedure */
2108       newbufpos = get_buffers_max (sink, sink->units_soft_max);
2109       break;
2110   }
2111   return newbufpos;
2112 }
2113
2114 /* Queue a buffer on the global queue.
2115  *
2116  * This function adds the buffer to the front of a GArray. It removes the
2117  * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
2118  * Note that unreffing the buffer is not a problem as clients who
2119  * started writing out this buffer will still have a reference to it in the
2120  * client->sending queue.
2121  *
2122  * After adding the buffer, we update all client positions in the queue. If
2123  * a client moves over the soft max, we start the recovery procedure for this
2124  * slow client. If it goes over the hard max, it is put into the slow list
2125  * and removed.
2126  *
2127  * Special care is taken of clients that were waiting for a new buffer (they
2128  * had a position of -1) because they can proceed after adding this new buffer.
2129  * This is done by adding the client back into the write fd_set and signalling
2130  * the select thread that the fd_set changed.
2131  */
2132 static void
2133 gst_multi_fd_sink_queue_buffer (GstMultiFdSink * sink, GstBuffer * buf)
2134 {
2135   GList *clients, *next;
2136   gint queuelen;
2137   gboolean need_signal = FALSE;
2138   gint max_buffer_usage;
2139   gint i;
2140   GTimeVal nowtv;
2141   GstClockTime now;
2142   gint max_buffers, soft_max_buffers;
2143   guint cookie;
2144
2145   g_get_current_time (&nowtv);
2146   now = GST_TIMEVAL_TO_TIME (nowtv);
2147
2148   CLIENTS_LOCK (sink);
2149   /* add buffer to queue */
2150   g_array_prepend_val (sink->bufqueue, buf);
2151   queuelen = sink->bufqueue->len;
2152
2153   if (sink->units_max > 0)
2154     max_buffers = get_buffers_max (sink, sink->units_max);
2155   else
2156     max_buffers = -1;
2157
2158   if (sink->units_soft_max > 0)
2159     soft_max_buffers = get_buffers_max (sink, sink->units_soft_max);
2160   else
2161     soft_max_buffers = -1;
2162   GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
2163       soft_max_buffers);
2164
2165   /* then loop over the clients and update the positions */
2166   max_buffer_usage = 0;
2167
2168 restart:
2169   cookie = sink->clients_cookie;
2170   for (clients = sink->clients; clients; clients = next) {
2171     GstTCPClient *client;
2172
2173     if (cookie != sink->clients_cookie) {
2174       GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
2175       goto restart;
2176     }
2177
2178     client = (GstTCPClient *) clients->data;
2179     next = g_list_next (clients);
2180
2181     client->bufpos++;
2182     GST_LOG_OBJECT (sink, "[fd %5d] client %p at position %d",
2183         client->fd.fd, client, client->bufpos);
2184     /* check soft max if needed, recover client */
2185     if (soft_max_buffers > 0 && client->bufpos >= soft_max_buffers) {
2186       gint newpos;
2187
2188       newpos = gst_multi_fd_sink_recover_client (sink, client);
2189       if (newpos != client->bufpos) {
2190         client->dropped_buffers += client->bufpos - newpos;
2191         client->bufpos = newpos;
2192         client->discont = TRUE;
2193         GST_INFO_OBJECT (sink, "[fd %5d] client %p position reset to %d",
2194             client->fd.fd, client, client->bufpos);
2195       } else {
2196         GST_INFO_OBJECT (sink,
2197             "[fd %5d] client %p not recovering position",
2198             client->fd.fd, client);
2199       }
2200     }
2201     /* check hard max and timeout, remove client */
2202     if ((max_buffers > 0 && client->bufpos >= max_buffers) ||
2203         (sink->timeout > 0
2204             && now - client->last_activity_time > sink->timeout)) {
2205       /* remove client */
2206       GST_WARNING_OBJECT (sink, "[fd %5d] client %p is too slow, removing",
2207           client->fd.fd, client);
2208       /* remove the client, the fd set will be cleared and the select thread
2209        * will be signaled */
2210       client->status = GST_CLIENT_STATUS_SLOW;
2211       /* set client to invalid position while being removed */
2212       client->bufpos = -1;
2213       gst_multi_fd_sink_remove_client_link (sink, clients);
2214       need_signal = TRUE;
2215       continue;
2216     } else if (client->bufpos == 0 || client->new_connection) {
2217       /* can send data to this client now. need to signal the select thread that
2218        * the fd_set changed */
2219       gst_poll_fd_ctl_write (sink->fdset, &client->fd, TRUE);
2220       need_signal = TRUE;
2221     }
2222     /* keep track of maximum buffer usage */
2223     if (client->bufpos > max_buffer_usage) {
2224       max_buffer_usage = client->bufpos;
2225     }
2226   }
2227
2228   /* make sure we respect bytes-min, buffers-min and time-min when they are set */
2229   {
2230     gint usage, max;
2231
2232     GST_LOG_OBJECT (sink,
2233         "extending queue %d to respect time_min %" GST_TIME_FORMAT
2234         ", bytes_min %d, buffers_min %d", max_buffer_usage,
2235         GST_TIME_ARGS (sink->time_min), sink->bytes_min, sink->buffers_min);
2236
2237     /* get index where the limits are ok, we don't really care if all limits
2238      * are ok, we just queue as much as we need. We also don't compare against
2239      * the max limits. */
2240     find_limits (sink, &usage, sink->bytes_min, sink->buffers_min,
2241         sink->time_min, &max, -1, -1, -1);
2242
2243     max_buffer_usage = MAX (max_buffer_usage, usage + 1);
2244     GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
2245   }
2246
2247   /* now look for sync points and make sure there is at least one
2248    * sync point in the queue. We only do this if the LATEST_KEYFRAME or 
2249    * BURST_KEYFRAME mode is selected */
2250   if (sink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
2251       sink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
2252     /* no point in searching beyond the queue length */
2253     gint limit = queuelen;
2254     GstBuffer *buf;
2255
2256     /* no point in searching beyond the soft-max if any. */
2257     if (soft_max_buffers > 0) {
2258       limit = MIN (limit, soft_max_buffers);
2259     }
2260     GST_LOG_OBJECT (sink,
2261         "extending queue to include sync point, now at %d, limit is %d",
2262         max_buffer_usage, limit);
2263     for (i = 0; i < limit; i++) {
2264       buf = g_array_index (sink->bufqueue, GstBuffer *, i);
2265       if (is_sync_frame (sink, buf)) {
2266         /* found a sync frame, now extend the buffer usage to
2267          * include at least this frame. */
2268         max_buffer_usage = MAX (max_buffer_usage, i);
2269         break;
2270       }
2271     }
2272     GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
2273   }
2274
2275   GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
2276
2277   /* nobody is referencing units after max_buffer_usage so we can
2278    * remove them from the queue. We remove them in reverse order as
2279    * this is the most optimal for GArray. */
2280   for (i = queuelen - 1; i > max_buffer_usage; i--) {
2281     GstBuffer *old;
2282
2283     /* queue exceeded max size */
2284     queuelen--;
2285     old = g_array_index (sink->bufqueue, GstBuffer *, i);
2286     sink->bufqueue = g_array_remove_index (sink->bufqueue, i);
2287
2288     /* unref tail buffer */
2289     gst_buffer_unref (old);
2290   }
2291   /* save for stats */
2292   sink->buffers_queued = max_buffer_usage;
2293   CLIENTS_UNLOCK (sink);
2294
2295   /* and send a signal to thread if fd_set changed */
2296   if (need_signal) {
2297     gst_poll_restart (sink->fdset);
2298   }
2299 }
2300
2301 /* Handle the clients. Basically does a blocking select for one
2302  * of the client fds to become read or writable. We also have a
2303  * filedescriptor to receive commands on that we need to check.
2304  *
2305  * After going out of the select call, we read and write to all
2306  * clients that can do so. Badly behaving clients are put on a
2307  * garbage list and removed.
2308  */
2309 static void
2310 gst_multi_fd_sink_handle_clients (GstMultiFdSink * sink)
2311 {
2312   int result;
2313   GList *clients, *next;
2314   gboolean try_again;
2315   GstMultiFdSinkClass *fclass;
2316   guint cookie;
2317
2318   fclass = GST_MULTI_FD_SINK_GET_CLASS (sink);
2319
2320   do {
2321     try_again = FALSE;
2322
2323     /* check for:
2324      * - server socket input (ie, new client connections)
2325      * - client socket input (ie, clients saying goodbye)
2326      * - client socket output (ie, client reads)          */
2327     GST_LOG_OBJECT (sink, "waiting on action on fdset");
2328
2329     result = gst_poll_wait (sink->fdset, sink->timeout != 0 ? sink->timeout :
2330         GST_CLOCK_TIME_NONE);
2331
2332     /* Handle the special case in which the sink is not receiving more buffers
2333      * and will not disconnect innactive client in the streaming thread. */
2334     if (G_UNLIKELY (result == 0)) {
2335       GstClockTime now;
2336       GTimeVal nowtv;
2337
2338       g_get_current_time (&nowtv);
2339       now = GST_TIMEVAL_TO_TIME (nowtv);
2340
2341       CLIENTS_LOCK (sink);
2342       for (clients = sink->clients; clients; clients = next) {
2343         GstTCPClient *client;
2344
2345         client = (GstTCPClient *) clients->data;
2346         next = g_list_next (clients);
2347         if (sink->timeout > 0
2348             && now - client->last_activity_time > sink->timeout) {
2349           client->status = GST_CLIENT_STATUS_SLOW;
2350           gst_multi_fd_sink_remove_client_link (sink, clients);
2351         }
2352       }
2353       CLIENTS_UNLOCK (sink);
2354       return;
2355     } else if (result < 0) {
2356       GST_WARNING_OBJECT (sink, "wait failed: %s (%d)", g_strerror (errno),
2357           errno);
2358       if (errno == EBADF) {
2359         /* ok, so one or more of the fds is invalid. We loop over them to find
2360          * the ones that give an error to the F_GETFL fcntl. */
2361         CLIENTS_LOCK (sink);
2362       restart:
2363         cookie = sink->clients_cookie;
2364         for (clients = sink->clients; clients; clients = next) {
2365           GstTCPClient *client;
2366           int fd;
2367           long flags;
2368           int res;
2369
2370           if (cookie != sink->clients_cookie) {
2371             GST_DEBUG_OBJECT (sink, "Cookie changed finding bad fd");
2372             goto restart;
2373           }
2374
2375           client = (GstTCPClient *) clients->data;
2376           next = g_list_next (clients);
2377
2378           fd = client->fd.fd;
2379
2380           res = fcntl (fd, F_GETFL, &flags);
2381           if (res == -1) {
2382             GST_WARNING_OBJECT (sink, "fnctl failed for %d, removing: %s (%d)",
2383                 fd, g_strerror (errno), errno);
2384             if (errno == EBADF) {
2385               client->status = GST_CLIENT_STATUS_ERROR;
2386               /* releases the CLIENTS lock */
2387               gst_multi_fd_sink_remove_client_link (sink, clients);
2388             }
2389           }
2390         }
2391         CLIENTS_UNLOCK (sink);
2392         /* after this, go back in the select loop as the read/writefds
2393          * are not valid */
2394         try_again = TRUE;
2395       } else if (errno == EINTR) {
2396         /* interrupted system call, just redo the wait */
2397         try_again = TRUE;
2398       } else if (errno == EBUSY) {
2399         /* the call to gst_poll_wait() was flushed */
2400         return;
2401       } else {
2402         /* this is quite bad... */
2403         GST_ELEMENT_ERROR (sink, RESOURCE, READ, (NULL),
2404             ("select failed: %s (%d)", g_strerror (errno), errno));
2405         return;
2406       }
2407     } else {
2408       GST_LOG_OBJECT (sink, "wait done: %d sockets with events", result);
2409     }
2410   } while (try_again);
2411
2412   /* subclasses can check fdset with this virtual function */
2413   if (fclass->wait)
2414     fclass->wait (sink, sink->fdset);
2415
2416   /* Check the clients */
2417   CLIENTS_LOCK (sink);
2418
2419 restart2:
2420   cookie = sink->clients_cookie;
2421   for (clients = sink->clients; clients; clients = next) {
2422     GstTCPClient *client;
2423
2424     if (sink->clients_cookie != cookie) {
2425       GST_DEBUG_OBJECT (sink, "Restarting loop, cookie out of date");
2426       goto restart2;
2427     }
2428
2429     client = (GstTCPClient *) clients->data;
2430     next = g_list_next (clients);
2431
2432     if (client->status != GST_CLIENT_STATUS_FLUSHING
2433         && client->status != GST_CLIENT_STATUS_OK) {
2434       gst_multi_fd_sink_remove_client_link (sink, clients);
2435       continue;
2436     }
2437
2438     if (gst_poll_fd_has_closed (sink->fdset, &client->fd)) {
2439       client->status = GST_CLIENT_STATUS_CLOSED;
2440       gst_multi_fd_sink_remove_client_link (sink, clients);
2441       continue;
2442     }
2443     if (gst_poll_fd_has_error (sink->fdset, &client->fd)) {
2444       GST_WARNING_OBJECT (sink, "gst_poll_fd_has_error for %d", client->fd.fd);
2445       client->status = GST_CLIENT_STATUS_ERROR;
2446       gst_multi_fd_sink_remove_client_link (sink, clients);
2447       continue;
2448     }
2449     if (gst_poll_fd_can_read (sink->fdset, &client->fd)) {
2450       /* handle client read */
2451       if (!gst_multi_fd_sink_handle_client_read (sink, client)) {
2452         gst_multi_fd_sink_remove_client_link (sink, clients);
2453         continue;
2454       }
2455     }
2456     if (gst_poll_fd_can_write (sink->fdset, &client->fd)) {
2457       /* handle client write */
2458       if (!gst_multi_fd_sink_handle_client_write (sink, client)) {
2459         gst_multi_fd_sink_remove_client_link (sink, clients);
2460         continue;
2461       }
2462     }
2463   }
2464   CLIENTS_UNLOCK (sink);
2465 }
2466
2467 /* we handle the client communication in another thread so that we do not block
2468  * the gstreamer thread while we select() on the client fds */
2469 static gpointer
2470 gst_multi_fd_sink_thread (GstMultiFdSink * sink)
2471 {
2472   while (sink->running) {
2473     gst_multi_fd_sink_handle_clients (sink);
2474   }
2475   return NULL;
2476 }
2477
2478 static GstFlowReturn
2479 gst_multi_fd_sink_render (GstBaseSink * bsink, GstBuffer * buf)
2480 {
2481   GstMultiFdSink *sink;
2482   gboolean in_caps;
2483 #if 0
2484   GstCaps *bufcaps, *padcaps;
2485 #endif
2486
2487   sink = GST_MULTI_FD_SINK (bsink);
2488
2489   g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink, GST_MULTI_FD_SINK_OPEN),
2490       GST_FLOW_WRONG_STATE);
2491
2492 #if 0
2493   /* since we check every buffer for streamheader caps, we need to make
2494    * sure every buffer has caps set */
2495   bufcaps = gst_buffer_get_caps (buf);
2496   padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
2497
2498   /* make sure we have caps on the pad */
2499   if (!padcaps && !bufcaps)
2500     goto no_caps;
2501 #endif
2502
2503   /* get IN_CAPS first, code below might mess with the flags */
2504   in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
2505
2506 #if 0
2507   /* stamp the buffer with previous caps if no caps set */
2508   if (!bufcaps) {
2509     if (!gst_buffer_is_writable (buf)) {
2510       /* metadata is not writable, copy will be made and original buffer
2511        * will be unreffed so we need to ref so that we don't lose the
2512        * buffer in the render method. */
2513       gst_buffer_ref (buf);
2514       /* the new buffer is ours only, we keep it out of the scope of this
2515        * function */
2516       buf = gst_buffer_make_writable (buf);
2517     } else {
2518       /* else the metadata is writable, we ref because we keep the buffer
2519        * out of the scope of this method */
2520       gst_buffer_ref (buf);
2521     }
2522     /* buffer metadata is writable now, set the caps */
2523     gst_buffer_set_caps (buf, padcaps);
2524   } else {
2525     gst_caps_unref (bufcaps);
2526
2527     /* since we keep this buffer out of the scope of this method */
2528     gst_buffer_ref (buf);
2529   }
2530 #endif
2531
2532   GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %s, offset %"
2533       G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT
2534       ", timestamp %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2535       buf, in_caps ? "yes" : "no", GST_BUFFER_OFFSET (buf),
2536       GST_BUFFER_OFFSET_END (buf),
2537       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
2538       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2539
2540   /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
2541    * it means we're getting new streamheader buffers, and we should clear
2542    * the old ones */
2543   if (in_caps && sink->previous_buffer_in_caps == FALSE) {
2544     GST_DEBUG_OBJECT (sink,
2545         "receiving new IN_CAPS buffers, clearing old streamheader");
2546     g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2547     g_slist_free (sink->streamheader);
2548     sink->streamheader = NULL;
2549   }
2550
2551   /* save the current in_caps */
2552   sink->previous_buffer_in_caps = in_caps;
2553
2554   /* if the incoming buffer is marked as IN CAPS, then we assume for now
2555    * it's a streamheader that needs to be sent to each new client, so we
2556    * put it on our internal list of streamheader buffers.
2557    * FIXME: we could check if the buffer's contents are in fact part of the
2558    * current streamheader.
2559    *
2560    * We don't send the buffer to the client, since streamheaders are sent
2561    * separately when necessary. */
2562   if (in_caps) {
2563     GST_DEBUG_OBJECT (sink, "appending IN_CAPS buffer with length %"
2564         G_GSIZE_FORMAT " to streamheader", gst_buffer_get_size (buf));
2565     sink->streamheader = g_slist_append (sink->streamheader, buf);
2566   } else {
2567     /* queue the buffer, this is a regular data buffer. */
2568     gst_multi_fd_sink_queue_buffer (sink, buf);
2569
2570     sink->bytes_to_serve += gst_buffer_get_size (buf);
2571   }
2572   return GST_FLOW_OK;
2573
2574   /* ERRORS */
2575 #if 0
2576 no_caps:
2577   {
2578     GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
2579         ("Received first buffer without caps set"));
2580     return GST_FLOW_NOT_NEGOTIATED;
2581   }
2582 #endif
2583 }
2584
2585 static void
2586 gst_multi_fd_sink_set_property (GObject * object, guint prop_id,
2587     const GValue * value, GParamSpec * pspec)
2588 {
2589   GstMultiFdSink *multifdsink;
2590
2591   multifdsink = GST_MULTI_FD_SINK (object);
2592
2593   switch (prop_id) {
2594     case PROP_MODE:
2595       multifdsink->mode = g_value_get_enum (value);
2596       break;
2597     case PROP_BUFFERS_MAX:
2598       multifdsink->units_max = g_value_get_int (value);
2599       break;
2600     case PROP_BUFFERS_SOFT_MAX:
2601       multifdsink->units_soft_max = g_value_get_int (value);
2602       break;
2603     case PROP_TIME_MIN:
2604       multifdsink->time_min = g_value_get_int64 (value);
2605       break;
2606     case PROP_BYTES_MIN:
2607       multifdsink->bytes_min = g_value_get_int (value);
2608       break;
2609     case PROP_BUFFERS_MIN:
2610       multifdsink->buffers_min = g_value_get_int (value);
2611       break;
2612     case PROP_UNIT_TYPE:
2613       multifdsink->unit_type = g_value_get_enum (value);
2614       break;
2615     case PROP_UNITS_MAX:
2616       multifdsink->units_max = g_value_get_int64 (value);
2617       break;
2618     case PROP_UNITS_SOFT_MAX:
2619       multifdsink->units_soft_max = g_value_get_int64 (value);
2620       break;
2621     case PROP_RECOVER_POLICY:
2622       multifdsink->recover_policy = g_value_get_enum (value);
2623       break;
2624     case PROP_TIMEOUT:
2625       multifdsink->timeout = g_value_get_uint64 (value);
2626       break;
2627     case PROP_SYNC_METHOD:
2628       multifdsink->def_sync_method = g_value_get_enum (value);
2629       break;
2630     case PROP_BURST_UNIT:
2631       multifdsink->def_burst_unit = g_value_get_enum (value);
2632       break;
2633     case PROP_BURST_VALUE:
2634       multifdsink->def_burst_value = g_value_get_uint64 (value);
2635       break;
2636     case PROP_QOS_DSCP:
2637       multifdsink->qos_dscp = g_value_get_int (value);
2638       setup_dscp (multifdsink);
2639       break;
2640     case PROP_HANDLE_READ:
2641       multifdsink->handle_read = g_value_get_boolean (value);
2642       break;
2643     case PROP_RESEND_STREAMHEADER:
2644       multifdsink->resend_streamheader = g_value_get_boolean (value);
2645       break;
2646
2647     default:
2648       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2649       break;
2650   }
2651 }
2652
2653 static void
2654 gst_multi_fd_sink_get_property (GObject * object, guint prop_id, GValue * value,
2655     GParamSpec * pspec)
2656 {
2657   GstMultiFdSink *multifdsink;
2658
2659   multifdsink = GST_MULTI_FD_SINK (object);
2660
2661   switch (prop_id) {
2662     case PROP_MODE:
2663       g_value_set_enum (value, multifdsink->mode);
2664       break;
2665     case PROP_BUFFERS_MAX:
2666       g_value_set_int (value, multifdsink->units_max);
2667       break;
2668     case PROP_BUFFERS_SOFT_MAX:
2669       g_value_set_int (value, multifdsink->units_soft_max);
2670       break;
2671     case PROP_TIME_MIN:
2672       g_value_set_int64 (value, multifdsink->time_min);
2673       break;
2674     case PROP_BYTES_MIN:
2675       g_value_set_int (value, multifdsink->bytes_min);
2676       break;
2677     case PROP_BUFFERS_MIN:
2678       g_value_set_int (value, multifdsink->buffers_min);
2679       break;
2680     case PROP_BUFFERS_QUEUED:
2681       g_value_set_uint (value, multifdsink->buffers_queued);
2682       break;
2683     case PROP_BYTES_QUEUED:
2684       g_value_set_uint (value, multifdsink->bytes_queued);
2685       break;
2686     case PROP_TIME_QUEUED:
2687       g_value_set_uint64 (value, multifdsink->time_queued);
2688       break;
2689     case PROP_UNIT_TYPE:
2690       g_value_set_enum (value, multifdsink->unit_type);
2691       break;
2692     case PROP_UNITS_MAX:
2693       g_value_set_int64 (value, multifdsink->units_max);
2694       break;
2695     case PROP_UNITS_SOFT_MAX:
2696       g_value_set_int64 (value, multifdsink->units_soft_max);
2697       break;
2698     case PROP_RECOVER_POLICY:
2699       g_value_set_enum (value, multifdsink->recover_policy);
2700       break;
2701     case PROP_TIMEOUT:
2702       g_value_set_uint64 (value, multifdsink->timeout);
2703       break;
2704     case PROP_SYNC_METHOD:
2705       g_value_set_enum (value, multifdsink->def_sync_method);
2706       break;
2707     case PROP_BYTES_TO_SERVE:
2708       g_value_set_uint64 (value, multifdsink->bytes_to_serve);
2709       break;
2710     case PROP_BYTES_SERVED:
2711       g_value_set_uint64 (value, multifdsink->bytes_served);
2712       break;
2713     case PROP_BURST_UNIT:
2714       g_value_set_enum (value, multifdsink->def_burst_unit);
2715       break;
2716     case PROP_BURST_VALUE:
2717       g_value_set_uint64 (value, multifdsink->def_burst_value);
2718       break;
2719     case PROP_QOS_DSCP:
2720       g_value_set_int (value, multifdsink->qos_dscp);
2721       break;
2722     case PROP_HANDLE_READ:
2723       g_value_set_boolean (value, multifdsink->handle_read);
2724       break;
2725     case PROP_RESEND_STREAMHEADER:
2726       g_value_set_boolean (value, multifdsink->resend_streamheader);
2727       break;
2728     case PROP_NUM_FDS:
2729       g_value_set_uint (value, g_hash_table_size (multifdsink->fd_hash));
2730       break;
2731
2732     default:
2733       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2734       break;
2735   }
2736 }
2737
2738
2739 /* create a socket for sending to remote machine */
2740 static gboolean
2741 gst_multi_fd_sink_start (GstBaseSink * bsink)
2742 {
2743   GstMultiFdSinkClass *fclass;
2744   GstMultiFdSink *this;
2745
2746   if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_FD_SINK_OPEN))
2747     return TRUE;
2748
2749   this = GST_MULTI_FD_SINK (bsink);
2750   fclass = GST_MULTI_FD_SINK_GET_CLASS (this);
2751
2752   GST_INFO_OBJECT (this, "starting in mode %d", this->mode);
2753   if ((this->fdset = gst_poll_new (TRUE)) == NULL)
2754     goto socket_pair;
2755
2756   this->streamheader = NULL;
2757   this->bytes_to_serve = 0;
2758   this->bytes_served = 0;
2759
2760   if (fclass->init) {
2761     fclass->init (this);
2762   }
2763
2764   this->running = TRUE;
2765   this->thread = g_thread_create ((GThreadFunc) gst_multi_fd_sink_thread,
2766       this, TRUE, NULL);
2767
2768   GST_OBJECT_FLAG_SET (this, GST_MULTI_FD_SINK_OPEN);
2769
2770   return TRUE;
2771
2772   /* ERRORS */
2773 socket_pair:
2774   {
2775     GST_ELEMENT_ERROR (this, RESOURCE, OPEN_READ_WRITE, (NULL),
2776         GST_ERROR_SYSTEM);
2777     return FALSE;
2778   }
2779 }
2780
2781 static gboolean
2782 multifdsink_hash_remove (gpointer key, gpointer value, gpointer data)
2783 {
2784   return TRUE;
2785 }
2786
2787 static gboolean
2788 gst_multi_fd_sink_stop (GstBaseSink * bsink)
2789 {
2790   GstMultiFdSinkClass *fclass;
2791   GstMultiFdSink *this;
2792   GstBuffer *buf;
2793   int i;
2794
2795   this = GST_MULTI_FD_SINK (bsink);
2796   fclass = GST_MULTI_FD_SINK_GET_CLASS (this);
2797
2798   if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_FD_SINK_OPEN))
2799     return TRUE;
2800
2801   this->running = FALSE;
2802
2803   gst_poll_set_flushing (this->fdset, TRUE);
2804   if (this->thread) {
2805     GST_DEBUG_OBJECT (this, "joining thread");
2806     g_thread_join (this->thread);
2807     GST_DEBUG_OBJECT (this, "joined thread");
2808     this->thread = NULL;
2809   }
2810
2811   /* free the clients */
2812   gst_multi_fd_sink_clear (this);
2813
2814   if (this->streamheader) {
2815     g_slist_foreach (this->streamheader, (GFunc) gst_mini_object_unref, NULL);
2816     g_slist_free (this->streamheader);
2817     this->streamheader = NULL;
2818   }
2819
2820   if (fclass->close)
2821     fclass->close (this);
2822
2823   if (this->fdset) {
2824     gst_poll_free (this->fdset);
2825     this->fdset = NULL;
2826   }
2827   g_hash_table_foreach_remove (this->fd_hash, multifdsink_hash_remove, this);
2828
2829   /* remove all queued buffers */
2830   if (this->bufqueue) {
2831     GST_DEBUG_OBJECT (this, "Emptying bufqueue with %d buffers",
2832         this->bufqueue->len);
2833     for (i = this->bufqueue->len - 1; i >= 0; --i) {
2834       buf = g_array_index (this->bufqueue, GstBuffer *, i);
2835       GST_LOG_OBJECT (this, "Removing buffer %p (%d) with refcount %d", buf, i,
2836           GST_MINI_OBJECT_REFCOUNT (buf));
2837       gst_buffer_unref (buf);
2838       this->bufqueue = g_array_remove_index (this->bufqueue, i);
2839     }
2840     /* freeing the array is done in _finalize */
2841   }
2842   GST_OBJECT_FLAG_UNSET (this, GST_MULTI_FD_SINK_OPEN);
2843
2844   return TRUE;
2845 }
2846
2847 static GstStateChangeReturn
2848 gst_multi_fd_sink_change_state (GstElement * element, GstStateChange transition)
2849 {
2850   GstMultiFdSink *sink;
2851   GstStateChangeReturn ret;
2852
2853   sink = GST_MULTI_FD_SINK (element);
2854
2855   /* we disallow changing the state from the streaming thread */
2856   if (g_thread_self () == sink->thread)
2857     return GST_STATE_CHANGE_FAILURE;
2858
2859
2860   switch (transition) {
2861     case GST_STATE_CHANGE_NULL_TO_READY:
2862       if (!gst_multi_fd_sink_start (GST_BASE_SINK (sink)))
2863         goto start_failed;
2864       break;
2865     case GST_STATE_CHANGE_READY_TO_PAUSED:
2866       break;
2867     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2868       break;
2869     default:
2870       break;
2871   }
2872
2873   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2874
2875   switch (transition) {
2876     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2877       break;
2878     case GST_STATE_CHANGE_PAUSED_TO_READY:
2879       break;
2880     case GST_STATE_CHANGE_READY_TO_NULL:
2881       gst_multi_fd_sink_stop (GST_BASE_SINK (sink));
2882       break;
2883     default:
2884       break;
2885   }
2886   return ret;
2887
2888   /* ERRORS */
2889 start_failed:
2890   {
2891     /* error message was posted */
2892     return GST_STATE_CHANGE_FAILURE;
2893   }
2894 }