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