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