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