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