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