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