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