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