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