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