subparse: fix off by one offset calculation
[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., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, 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 #ifdef HAVE_SYS_SOCKET_H
113 #include <sys/socket.h>
114 #endif
115
116 #ifndef G_OS_WIN32
117 #include <netinet/in.h>
118 #endif
119
120 #define NOT_IMPLEMENTED 0
121
122 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
123     GST_PAD_SINK,
124     GST_PAD_ALWAYS,
125     GST_STATIC_CAPS_ANY);
126
127 GST_DEBUG_CATEGORY_STATIC (multihandlesink_debug);
128 #define GST_CAT_DEFAULT (multihandlesink_debug)
129
130 /* MultiHandleSink signals and args */
131 enum
132 {
133   GST_MULTI_SINK_LAST_SIGNAL,
134
135   /* methods */
136   SIGNAL_ADD,
137   SIGNAL_ADD_BURST,
138   SIGNAL_CLEAR,
139
140   /* signals */
141   SIGNAL_CLIENT_ADDED,
142   SIGNAL_CLIENT_REMOVED,
143   SIGNAL_CLIENT_SOCKET_REMOVED,
144
145   LAST_SIGNAL
146 };
147
148
149 /* this is really arbitrarily chosen */
150 #define DEFAULT_BUFFERS_MAX             -1
151 #define DEFAULT_BUFFERS_SOFT_MAX        -1
152 #define DEFAULT_TIME_MIN                -1
153 #define DEFAULT_BYTES_MIN               -1
154 #define DEFAULT_BUFFERS_MIN             -1
155 #define DEFAULT_UNIT_FORMAT               GST_FORMAT_BUFFERS
156 #define DEFAULT_UNITS_MAX               -1
157 #define DEFAULT_UNITS_SOFT_MAX          -1
158 #define DEFAULT_RECOVER_POLICY          GST_RECOVER_POLICY_NONE
159 #define DEFAULT_TIMEOUT                 0
160 #define DEFAULT_SYNC_METHOD             GST_SYNC_METHOD_LATEST
161
162 #define DEFAULT_BURST_FORMAT            GST_FORMAT_UNDEFINED
163 #define DEFAULT_BURST_VALUE             0
164
165 #define DEFAULT_QOS_DSCP                -1
166
167 #define DEFAULT_RESEND_STREAMHEADER      TRUE
168
169 enum
170 {
171   PROP_0,
172   PROP_BUFFERS_QUEUED,
173   PROP_BYTES_QUEUED,
174   PROP_TIME_QUEUED,
175
176   PROP_UNIT_FORMAT,
177   PROP_UNITS_MAX,
178   PROP_UNITS_SOFT_MAX,
179
180   PROP_BUFFERS_MAX,
181   PROP_BUFFERS_SOFT_MAX,
182
183   PROP_TIME_MIN,
184   PROP_BYTES_MIN,
185   PROP_BUFFERS_MIN,
186
187   PROP_RECOVER_POLICY,
188   PROP_TIMEOUT,
189   PROP_SYNC_METHOD,
190   PROP_BYTES_TO_SERVE,
191   PROP_BYTES_SERVED,
192
193   PROP_BURST_FORMAT,
194   PROP_BURST_VALUE,
195
196   PROP_QOS_DSCP,
197
198   PROP_RESEND_STREAMHEADER,
199
200   PROP_NUM_HANDLES,
201
202   PROP_LAST
203 };
204
205 GType
206 gst_multi_handle_sink_recover_policy_get_type (void)
207 {
208   static GType recover_policy_type = 0;
209   static const GEnumValue recover_policy[] = {
210     {GST_RECOVER_POLICY_NONE,
211         "Do not try to recover", "none"},
212     {GST_RECOVER_POLICY_RESYNC_LATEST,
213         "Resync client to latest buffer", "latest"},
214     {GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT,
215         "Resync client to soft limit", "soft-limit"},
216     {GST_RECOVER_POLICY_RESYNC_KEYFRAME,
217         "Resync client to most recent keyframe", "keyframe"},
218     {0, NULL, NULL},
219   };
220
221   if (!recover_policy_type) {
222     recover_policy_type =
223         g_enum_register_static ("GstMultiHandleSinkRecoverPolicy",
224         recover_policy);
225   }
226   return recover_policy_type;
227 }
228
229 GType
230 gst_multi_handle_sink_sync_method_get_type (void)
231 {
232   static GType sync_method_type = 0;
233   static const GEnumValue sync_method[] = {
234     {GST_SYNC_METHOD_LATEST,
235         "Serve starting from the latest buffer", "latest"},
236     {GST_SYNC_METHOD_NEXT_KEYFRAME,
237         "Serve starting from the next keyframe", "next-keyframe"},
238     {GST_SYNC_METHOD_LATEST_KEYFRAME,
239           "Serve everything since the latest keyframe (burst)",
240         "latest-keyframe"},
241     {GST_SYNC_METHOD_BURST, "Serve burst-value data to client", "burst"},
242     {GST_SYNC_METHOD_BURST_KEYFRAME,
243           "Serve burst-value data starting on a keyframe",
244         "burst-keyframe"},
245     {GST_SYNC_METHOD_BURST_WITH_KEYFRAME,
246           "Serve burst-value data preferably starting on a keyframe",
247         "burst-with-keyframe"},
248     {0, NULL, NULL},
249   };
250
251   if (!sync_method_type) {
252     sync_method_type =
253         g_enum_register_static ("GstMultiHandleSinkSyncMethod", sync_method);
254   }
255   return sync_method_type;
256 }
257
258 GType
259 gst_multi_handle_sink_client_status_get_type (void)
260 {
261   static GType client_status_type = 0;
262   static const GEnumValue client_status[] = {
263     {GST_CLIENT_STATUS_OK, "ok", "ok"},
264     {GST_CLIENT_STATUS_CLOSED, "Closed", "closed"},
265     {GST_CLIENT_STATUS_REMOVED, "Removed", "removed"},
266     {GST_CLIENT_STATUS_SLOW, "Too slow", "slow"},
267     {GST_CLIENT_STATUS_ERROR, "Error", "error"},
268     {GST_CLIENT_STATUS_DUPLICATE, "Duplicate", "duplicate"},
269     {GST_CLIENT_STATUS_FLUSHING, "Flushing", "flushing"},
270     {0, NULL, NULL},
271   };
272
273   if (!client_status_type) {
274     client_status_type =
275         g_enum_register_static ("GstMultiHandleSinkClientStatus",
276         client_status);
277   }
278   return client_status_type;
279 }
280
281 static void gst_multi_handle_sink_finalize (GObject * object);
282 static void gst_multi_handle_sink_clear (GstMultiHandleSink * mhsink);
283
284 static GstFlowReturn gst_multi_handle_sink_render (GstBaseSink * bsink,
285     GstBuffer * buf);
286 static void gst_multi_handle_sink_queue_buffer (GstMultiHandleSink * mhsink,
287     GstBuffer * buffer);
288 static gboolean gst_multi_handle_sink_client_queue_buffer (GstMultiHandleSink *
289     mhsink, GstMultiHandleClient * mhclient, GstBuffer * buffer);
290 static GstStateChangeReturn gst_multi_handle_sink_change_state (GstElement *
291     element, GstStateChange transition);
292
293 static void gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
294     const GValue * value, GParamSpec * pspec);
295 static void gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
296     GValue * value, GParamSpec * pspec);
297
298 #define gst_multi_handle_sink_parent_class parent_class
299 G_DEFINE_TYPE (GstMultiHandleSink, gst_multi_handle_sink, GST_TYPE_BASE_SINK);
300
301 static guint gst_multi_handle_sink_signals[LAST_SIGNAL] = { 0 };
302
303 static gint
304 find_syncframe (GstMultiHandleSink * sink, gint idx, gint direction);
305 #define find_next_syncframe(s,i)        find_syncframe(s,i,1)
306 #define find_prev_syncframe(s,i)        find_syncframe(s,i,-1)
307 static gboolean is_sync_frame (GstMultiHandleSink * sink, GstBuffer * buffer);
308 static gboolean gst_multi_handle_sink_stop (GstBaseSink * bsink);
309 static gboolean gst_multi_handle_sink_start (GstBaseSink * bsink);
310 static gint get_buffers_max (GstMultiHandleSink * sink, gint64 max);
311 static gint
312 gst_multi_handle_sink_recover_client (GstMultiHandleSink * sink,
313     GstMultiHandleClient * client);
314 static void gst_multi_handle_sink_setup_dscp (GstMultiHandleSink * mhsink);
315 static gboolean
316 find_limits (GstMultiHandleSink * sink,
317     gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
318     gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max);
319
320
321 static void
322 gst_multi_handle_sink_class_init (GstMultiHandleSinkClass * klass)
323 {
324   GObjectClass *gobject_class;
325   GstElementClass *gstelement_class;
326   GstBaseSinkClass *gstbasesink_class;
327
328   gobject_class = (GObjectClass *) klass;
329   gstelement_class = (GstElementClass *) klass;
330   gstbasesink_class = (GstBaseSinkClass *) klass;
331
332   gobject_class->set_property = gst_multi_handle_sink_set_property;
333   gobject_class->get_property = gst_multi_handle_sink_get_property;
334   gobject_class->finalize = gst_multi_handle_sink_finalize;
335
336   g_object_class_install_property (gobject_class, PROP_BUFFERS_MAX,
337       g_param_spec_int ("buffers-max", "Buffers max",
338           "max number of buffers to queue for a client (-1 = no limit)", -1,
339           G_MAXINT, DEFAULT_BUFFERS_MAX,
340           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341   g_object_class_install_property (gobject_class, PROP_BUFFERS_SOFT_MAX,
342       g_param_spec_int ("buffers-soft-max", "Buffers soft max",
343           "Recover client when going over this limit (-1 = no limit)", -1,
344           G_MAXINT, DEFAULT_BUFFERS_SOFT_MAX,
345           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346
347   g_object_class_install_property (gobject_class, PROP_BYTES_MIN,
348       g_param_spec_int ("bytes-min", "Bytes min",
349           "min number of bytes to queue (-1 = as little as possible)", -1,
350           G_MAXINT, DEFAULT_BYTES_MIN,
351           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352   g_object_class_install_property (gobject_class, PROP_TIME_MIN,
353       g_param_spec_int64 ("time-min", "Time min",
354           "min number of time to queue (-1 = as little as possible)", -1,
355           G_MAXINT64, DEFAULT_TIME_MIN,
356           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
357   g_object_class_install_property (gobject_class, PROP_BUFFERS_MIN,
358       g_param_spec_int ("buffers-min", "Buffers min",
359           "min number of buffers to queue (-1 = as few as possible)", -1,
360           G_MAXINT, DEFAULT_BUFFERS_MIN,
361           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
362
363   g_object_class_install_property (gobject_class, PROP_UNIT_FORMAT,
364       g_param_spec_enum ("unit-format", "Units format",
365           "The unit to measure the max/soft-max/queued properties",
366           GST_TYPE_FORMAT, DEFAULT_UNIT_FORMAT,
367           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
368   g_object_class_install_property (gobject_class, PROP_UNITS_MAX,
369       g_param_spec_int64 ("units-max", "Units max",
370           "max number of units to queue (-1 = no limit)", -1, G_MAXINT64,
371           DEFAULT_UNITS_MAX, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
372   g_object_class_install_property (gobject_class, PROP_UNITS_SOFT_MAX,
373       g_param_spec_int64 ("units-soft-max", "Units soft max",
374           "Recover client when going over this limit (-1 = no limit)", -1,
375           G_MAXINT64, DEFAULT_UNITS_SOFT_MAX,
376           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
377
378   g_object_class_install_property (gobject_class, PROP_BUFFERS_QUEUED,
379       g_param_spec_uint ("buffers-queued", "Buffers queued",
380           "Number of buffers currently queued", 0, G_MAXUINT, 0,
381           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
382 #if NOT_IMPLEMENTED
383   g_object_class_install_property (gobject_class, PROP_BYTES_QUEUED,
384       g_param_spec_uint ("bytes-queued", "Bytes queued",
385           "Number of bytes currently queued", 0, G_MAXUINT, 0,
386           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
387   g_object_class_install_property (gobject_class, PROP_TIME_QUEUED,
388       g_param_spec_uint64 ("time-queued", "Time queued",
389           "Number of time currently queued", 0, G_MAXUINT64, 0,
390           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
391 #endif
392
393   g_object_class_install_property (gobject_class, PROP_RECOVER_POLICY,
394       g_param_spec_enum ("recover-policy", "Recover Policy",
395           "How to recover when client reaches the soft max",
396           GST_TYPE_RECOVER_POLICY, DEFAULT_RECOVER_POLICY,
397           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
398   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
399       g_param_spec_uint64 ("timeout", "Timeout",
400           "Maximum inactivity timeout in nanoseconds for a client (0 = no limit)",
401           0, G_MAXUINT64, DEFAULT_TIMEOUT,
402           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
403   g_object_class_install_property (gobject_class, PROP_SYNC_METHOD,
404       g_param_spec_enum ("sync-method", "Sync Method",
405           "How to sync new clients to the stream", GST_TYPE_SYNC_METHOD,
406           DEFAULT_SYNC_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
407   g_object_class_install_property (gobject_class, PROP_BYTES_TO_SERVE,
408       g_param_spec_uint64 ("bytes-to-serve", "Bytes to serve",
409           "Number of bytes received to serve to clients", 0, G_MAXUINT64, 0,
410           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
411   g_object_class_install_property (gobject_class, PROP_BYTES_SERVED,
412       g_param_spec_uint64 ("bytes-served", "Bytes served",
413           "Total number of bytes send to all clients", 0, G_MAXUINT64, 0,
414           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
415
416   g_object_class_install_property (gobject_class, PROP_BURST_FORMAT,
417       g_param_spec_enum ("burst-format", "Burst format",
418           "The format of the burst units (when sync-method is burst[[-with]-keyframe])",
419           GST_TYPE_FORMAT, DEFAULT_BURST_FORMAT,
420           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
421   g_object_class_install_property (gobject_class, PROP_BURST_VALUE,
422       g_param_spec_uint64 ("burst-value", "Burst value",
423           "The amount of burst expressed in burst-format", 0, G_MAXUINT64,
424           DEFAULT_BURST_VALUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
425
426   g_object_class_install_property (gobject_class, PROP_QOS_DSCP,
427       g_param_spec_int ("qos-dscp", "QoS diff srv code point",
428           "Quality of Service, differentiated services code point (-1 default)",
429           -1, 63, DEFAULT_QOS_DSCP,
430           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
431
432   /**
433    * GstMultiHandleSink::resend-streamheader
434    *
435    * Resend the streamheaders to existing clients when they change.
436    *
437    * Since: 0.10.23
438    */
439   g_object_class_install_property (gobject_class, PROP_RESEND_STREAMHEADER,
440       g_param_spec_boolean ("resend-streamheader", "Resend streamheader",
441           "Resend the streamheader if it changes in the caps",
442           DEFAULT_RESEND_STREAMHEADER,
443           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
444
445   g_object_class_install_property (gobject_class, PROP_NUM_HANDLES,
446       g_param_spec_uint ("num-handles", "Number of handles",
447           "The current number of client handles",
448           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
449
450   /**
451    * GstMultiHandleSink::clear:
452    * @gstmultihandlesink: the multihandlesink element to emit this signal on
453    *
454    * Remove all sockets from multihandlesink.  Since multihandlesink did not
455    * open sockets itself, it does not explicitly close the sockets. The application
456    * should do so by connecting to the client-socket-removed callback.
457    */
458   gst_multi_handle_sink_signals[SIGNAL_CLEAR] =
459       g_signal_new ("clear", G_TYPE_FROM_CLASS (klass),
460       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
461       G_STRUCT_OFFSET (GstMultiHandleSinkClass, clear), NULL, NULL,
462       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
463
464   gst_element_class_add_pad_template (gstelement_class,
465       gst_static_pad_template_get (&sinktemplate));
466
467   gst_element_class_set_static_metadata (gstelement_class,
468       "Multi socket sink", "Sink/Network",
469       "Send data to multiple sockets",
470       "Thomas Vander Stichele <thomas at apestaart dot org>, "
471       "Wim Taymans <wim@fluendo.com>, "
472       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
473
474   gstelement_class->change_state =
475       GST_DEBUG_FUNCPTR (gst_multi_handle_sink_change_state);
476
477   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_render);
478   klass->client_queue_buffer =
479       GST_DEBUG_FUNCPTR (gst_multi_handle_sink_client_queue_buffer);
480
481 #if 0
482   klass->add = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_add);
483   klass->add_full = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_add_full);
484   klass->remove = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_remove);
485   klass->remove_flush = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_remove_flush);
486 #endif
487
488   klass->clear = GST_DEBUG_FUNCPTR (gst_multi_handle_sink_clear);
489
490   GST_DEBUG_CATEGORY_INIT (multihandlesink_debug, "multihandlesink", 0,
491       "Multi socket sink");
492 }
493
494 static void
495 gst_multi_handle_sink_init (GstMultiHandleSink * this)
496 {
497   GST_OBJECT_FLAG_UNSET (this, GST_MULTI_HANDLE_SINK_OPEN);
498
499   CLIENTS_LOCK_INIT (this);
500   this->clients = NULL;
501
502   this->bufqueue = g_array_new (FALSE, TRUE, sizeof (GstBuffer *));
503   this->unit_format = DEFAULT_UNIT_FORMAT;
504   this->units_max = DEFAULT_UNITS_MAX;
505   this->units_soft_max = DEFAULT_UNITS_SOFT_MAX;
506   this->time_min = DEFAULT_TIME_MIN;
507   this->bytes_min = DEFAULT_BYTES_MIN;
508   this->buffers_min = DEFAULT_BUFFERS_MIN;
509   this->recover_policy = DEFAULT_RECOVER_POLICY;
510
511   this->timeout = DEFAULT_TIMEOUT;
512   this->def_sync_method = DEFAULT_SYNC_METHOD;
513
514   this->def_burst_format = DEFAULT_BURST_FORMAT;
515   this->def_burst_value = DEFAULT_BURST_VALUE;
516
517   this->qos_dscp = DEFAULT_QOS_DSCP;
518
519   this->resend_streamheader = DEFAULT_RESEND_STREAMHEADER;
520 }
521
522 static void
523 gst_multi_handle_sink_finalize (GObject * object)
524 {
525   GstMultiHandleSink *this;
526
527   this = GST_MULTI_HANDLE_SINK (object);
528
529   CLIENTS_LOCK_CLEAR (this);
530   g_array_free (this->bufqueue, TRUE);
531   g_hash_table_destroy (this->handle_hash);
532
533   G_OBJECT_CLASS (parent_class)->finalize (object);
534 }
535
536 gint
537 gst_multi_handle_sink_setup_dscp_client (GstMultiHandleSink * sink,
538     GstMultiHandleClient * client)
539 {
540 #if !defined(IP_TOS) || !defined(HAVE_SYS_SOCKET_H)
541   return 0;
542 #else
543   gint tos;
544   gint ret;
545   int fd;
546   union gst_sockaddr
547   {
548     struct sockaddr sa;
549     struct sockaddr_in6 sa_in6;
550     struct sockaddr_storage sa_stor;
551   } sa;
552   socklen_t slen = sizeof (sa);
553   gint af;
554   GstMultiHandleSinkClass *mhsinkclass = GST_MULTI_HANDLE_SINK_GET_CLASS (sink);
555
556   /* don't touch */
557   if (sink->qos_dscp < 0)
558     return 0;
559
560   fd = mhsinkclass->client_get_fd (client);
561
562   if ((ret = getsockname (fd, &sa.sa, &slen)) < 0) {
563     GST_DEBUG_OBJECT (sink, "could not get sockname: %s", g_strerror (errno));
564     return ret;
565   }
566
567   af = sa.sa.sa_family;
568
569   /* if this is an IPv4-mapped address then do IPv4 QoS */
570   if (af == AF_INET6) {
571
572     GST_DEBUG_OBJECT (sink, "check IP6 socket");
573     if (IN6_IS_ADDR_V4MAPPED (&(sa.sa_in6.sin6_addr))) {
574       GST_DEBUG_OBJECT (sink, "mapped to IPV4");
575       af = AF_INET;
576     }
577   }
578
579   /* extract and shift 6 bits of the DSCP */
580   tos = (sink->qos_dscp & 0x3f) << 2;
581
582   switch (af) {
583     case AF_INET:
584       ret = setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos));
585       break;
586     case AF_INET6:
587 #ifdef IPV6_TCLASS
588       ret = setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos));
589       break;
590 #endif
591     default:
592       ret = 0;
593       GST_ERROR_OBJECT (sink, "unsupported AF");
594       break;
595   }
596   if (ret)
597     GST_DEBUG_OBJECT (sink, "could not set DSCP: %s", g_strerror (errno));
598
599   return ret;
600 #endif
601 }
602
603 void
604 gst_multi_handle_sink_client_init (GstMultiHandleClient * client,
605     GstSyncMethod sync_method)
606 {
607   GTimeVal now;
608
609   client->status = GST_CLIENT_STATUS_OK;
610   client->bufpos = -1;
611   client->flushcount = -1;
612   client->bufoffset = 0;
613   client->sending = NULL;
614   client->bytes_sent = 0;
615   client->dropped_buffers = 0;
616   client->avg_queue_size = 0;
617   client->first_buffer_ts = GST_CLOCK_TIME_NONE;
618   client->last_buffer_ts = GST_CLOCK_TIME_NONE;
619   client->new_connection = TRUE;
620   client->sync_method = sync_method;
621   client->currently_removing = FALSE;
622
623   /* update start time */
624   g_get_current_time (&now);
625   client->connect_time = GST_TIMEVAL_TO_TIME (now);
626   client->disconnect_time = 0;
627   /* set last activity time to connect time */
628   client->last_activity_time = client->connect_time;
629 }
630
631 static void
632 gst_multi_handle_sink_setup_dscp (GstMultiHandleSink * mhsink)
633 {
634   GList *clients;
635
636   CLIENTS_LOCK (mhsink);
637   for (clients = mhsink->clients; clients; clients = clients->next) {
638     GstMultiHandleClient *client;
639
640     client = clients->data;
641
642     gst_multi_handle_sink_setup_dscp_client (mhsink, client);
643   }
644   CLIENTS_UNLOCK (mhsink);
645 }
646
647 void
648 gst_multi_handle_sink_add_full (GstMultiHandleSink * sink,
649     GstMultiSinkHandle handle, GstSyncMethod sync_method, GstFormat min_format,
650     guint64 min_value, GstFormat max_format, guint64 max_value)
651 {
652   GstMultiHandleClient *mhclient;
653   GList *clink;
654   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
655   gchar debug[30];
656   GstMultiHandleSinkClass *mhsinkclass =
657       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
658
659   if (!sink->running) {
660     g_warning ("Element %s must be set to READY, PAUSED or PLAYING state "
661         "before clients can be added", GST_OBJECT_NAME (sink));
662     return;
663   }
664
665   mhsinkclass->handle_debug (handle, debug);
666   GST_DEBUG_OBJECT (sink, "%s adding client, sync_method %d, "
667       "min_format %d, min_value %" G_GUINT64_FORMAT
668       ", max_format %d, max_value %" G_GUINT64_FORMAT, debug,
669       sync_method, min_format, min_value, max_format, max_value);
670
671   /* do limits check if we can */
672   if (min_format == max_format) {
673     if (max_value != -1 && min_value != -1 && max_value < min_value)
674       goto wrong_limits;
675   }
676
677   CLIENTS_LOCK (sink);
678
679   /* check the hash to find a duplicate handle */
680   clink = g_hash_table_lookup (mhsink->handle_hash,
681       mhsinkclass->handle_hash_key (handle));
682   if (clink != NULL)
683     goto duplicate;
684
685   mhclient = mhsinkclass->new_client (mhsink, handle, sync_method);
686
687   /* we can add the handle now */
688   clink = mhsink->clients = g_list_prepend (mhsink->clients, mhclient);
689   g_hash_table_insert (mhsink->handle_hash,
690       mhsinkclass->handle_hash_key (mhclient->handle), clink);
691   mhsink->clients_cookie++;
692
693
694   mhclient->burst_min_format = min_format;
695   mhclient->burst_min_value = min_value;
696   mhclient->burst_max_format = max_format;
697   mhclient->burst_max_value = max_value;
698
699   if (mhsinkclass->hash_changed)
700     mhsinkclass->hash_changed (mhsink);
701
702   CLIENTS_UNLOCK (sink);
703
704   mhsinkclass->emit_client_added (mhsink, handle);
705
706   return;
707
708   /* errors */
709 wrong_limits:
710   {
711     GST_WARNING_OBJECT (sink,
712         "%s wrong values min =%" G_GUINT64_FORMAT ", max=%"
713         G_GUINT64_FORMAT ", unit %d specified when adding client",
714         debug, min_value, max_value, min_format);
715     return;
716   }
717 duplicate:
718   {
719     CLIENTS_UNLOCK (sink);
720     GST_WARNING_OBJECT (sink, "%s duplicate client found, refusing", debug);
721     mhsinkclass->emit_client_removed (mhsink, handle,
722         GST_CLIENT_STATUS_DUPLICATE);
723     return;
724   }
725 }
726
727 /* "add" signal implementation */
728 void
729 gst_multi_handle_sink_add (GstMultiHandleSink * sink, GstMultiSinkHandle handle)
730 {
731   gst_multi_handle_sink_add_full (sink, handle, sink->def_sync_method,
732       sink->def_burst_format, sink->def_burst_value, sink->def_burst_format,
733       -1);
734 }
735
736 /* "remove" signal implementation */
737 void
738 gst_multi_handle_sink_remove (GstMultiHandleSink * sink,
739     GstMultiSinkHandle handle)
740 {
741   GList *clink;
742   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
743   GstMultiHandleSinkClass *mhsinkclass =
744       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
745   gchar debug[30];
746
747   mhsinkclass->handle_debug (handle, debug);
748
749   GST_DEBUG_OBJECT (sink, "%s removing client", debug);
750
751   CLIENTS_LOCK (sink);
752   clink = g_hash_table_lookup (mhsink->handle_hash,
753       mhsinkclass->handle_hash_key (handle));
754   if (clink != NULL) {
755     GstMultiHandleClient *mhclient = (GstMultiHandleClient *) clink->data;
756
757     if (mhclient->status != GST_CLIENT_STATUS_OK) {
758       GST_INFO_OBJECT (sink,
759           "%s Client already disconnecting with status %d",
760           debug, mhclient->status);
761       goto done;
762     }
763
764     mhclient->status = GST_CLIENT_STATUS_REMOVED;
765     gst_multi_handle_sink_remove_client_link (GST_MULTI_HANDLE_SINK (sink),
766         clink);
767     if (mhsinkclass->hash_changed)
768       mhsinkclass->hash_changed (mhsink);
769   } else {
770     GST_WARNING_OBJECT (sink, "%s no client with this handle found!", debug);
771   }
772
773 done:
774   CLIENTS_UNLOCK (sink);
775 }
776
777 /* "remove-flush" signal implementation */
778 void
779 gst_multi_handle_sink_remove_flush (GstMultiHandleSink * sink,
780     GstMultiSinkHandle handle)
781 {
782   GList *clink;
783   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
784   GstMultiHandleSinkClass *mhsinkclass =
785       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
786   gchar debug[30];
787
788   mhsinkclass->handle_debug (handle, debug);
789
790   GST_DEBUG_OBJECT (sink, "%s flushing client", debug);
791
792   CLIENTS_LOCK (sink);
793   clink = g_hash_table_lookup (mhsink->handle_hash,
794       mhsinkclass->handle_hash_key (handle));
795   if (clink != NULL) {
796     GstMultiHandleClient *mhclient = (GstMultiHandleClient *) clink->data;
797
798     if (mhclient->status != GST_CLIENT_STATUS_OK) {
799       GST_INFO_OBJECT (sink,
800           "%s Client already disconnecting with status %d",
801           mhclient->debug, mhclient->status);
802       goto done;
803     }
804
805     /* take the position of the client as the number of buffers left to flush.
806      * If the client was at position -1, we flush 0 buffers, 0 == flush 1
807      * buffer, etc... */
808     mhclient->flushcount = mhclient->bufpos + 1;
809     /* mark client as flushing. We can not remove the client right away because
810      * it might have some buffers to flush in the ->sending queue. */
811     mhclient->status = GST_CLIENT_STATUS_FLUSHING;
812   } else {
813     GST_WARNING_OBJECT (sink, "%s no client with this handle found!", debug);
814   }
815 done:
816   CLIENTS_UNLOCK (sink);
817 }
818
819 /* can be called both through the signal (i.e. from any thread) or when 
820  * stopping, after the writing thread has shut down */
821 static void
822 gst_multi_handle_sink_clear (GstMultiHandleSink * mhsink)
823 {
824   GList *clients, *next;
825   guint32 cookie;
826   GstMultiHandleSinkClass *mhsinkclass =
827       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
828
829   GST_DEBUG_OBJECT (mhsink, "clearing all clients");
830
831   CLIENTS_LOCK (mhsink);
832 restart:
833   cookie = mhsink->clients_cookie;
834   for (clients = mhsink->clients; clients; clients = next) {
835     GstMultiHandleClient *mhclient;
836
837     if (cookie != mhsink->clients_cookie) {
838       GST_DEBUG_OBJECT (mhsink, "cookie changed while removing all clients");
839       goto restart;
840     }
841
842     mhclient = (GstMultiHandleClient *) clients->data;
843     next = g_list_next (clients);
844
845     mhclient->status = GST_CLIENT_STATUS_REMOVED;
846     /* the next call changes the list, which is why we iterate
847      * with a temporary next pointer */
848     gst_multi_handle_sink_remove_client_link (mhsink, clients);
849   }
850   if (mhsinkclass->hash_changed)
851     mhsinkclass->hash_changed (mhsink);
852
853   CLIENTS_UNLOCK (mhsink);
854 }
855
856
857 /* "get-stats" signal implementation
858  */
859 GstStructure *
860 gst_multi_handle_sink_get_stats (GstMultiHandleSink * sink,
861     GstMultiSinkHandle handle)
862 {
863   GstMultiHandleClient *client;
864   GstStructure *result = NULL;
865   GList *clink;
866   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (sink);
867   GstMultiHandleSinkClass *mhsinkclass =
868       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
869   gchar debug[30];
870
871   mhsinkclass->handle_debug (handle, debug);
872
873   CLIENTS_LOCK (sink);
874   clink = g_hash_table_lookup (mhsink->handle_hash,
875       mhsinkclass->handle_hash_key (handle));
876   if (clink == NULL)
877     goto noclient;
878
879   client = clink->data;
880   if (client != NULL) {
881     GstMultiHandleClient *mhclient = (GstMultiHandleClient *) client;
882     guint64 interval;
883
884     result = gst_structure_new_empty ("multihandlesink-stats");
885
886     if (mhclient->disconnect_time == 0) {
887       GTimeVal nowtv;
888
889       g_get_current_time (&nowtv);
890
891       interval = GST_TIMEVAL_TO_TIME (nowtv) - mhclient->connect_time;
892     } else {
893       interval = mhclient->disconnect_time - mhclient->connect_time;
894     }
895
896     gst_structure_set (result,
897         "bytes-sent", G_TYPE_UINT64, mhclient->bytes_sent,
898         "connect-time", G_TYPE_UINT64, mhclient->connect_time,
899         "disconnect-time", G_TYPE_UINT64, mhclient->disconnect_time,
900         "connect-duration", G_TYPE_UINT64, interval,
901         "last-activitity-time", G_TYPE_UINT64, mhclient->last_activity_time,
902         "buffers-dropped", G_TYPE_UINT64, mhclient->dropped_buffers,
903         "first-buffer-ts", G_TYPE_UINT64, mhclient->first_buffer_ts,
904         "last-buffer-ts", G_TYPE_UINT64, mhclient->last_buffer_ts, NULL);
905   }
906
907 noclient:
908   CLIENTS_UNLOCK (sink);
909
910   /* python doesn't like a NULL pointer yet */
911   if (result == NULL) {
912     GST_WARNING_OBJECT (sink, "%s no client with this found!", debug);
913     result = gst_structure_new_empty ("multihandlesink-stats");
914   }
915
916   return result;
917 }
918
919 /* should be called with the clientslock held.
920  * Note that we don't close the fd as we didn't open it in the first
921  * place. An application should connect to the client-fd-removed signal and
922  * close the fd itself.
923  */
924 void
925 gst_multi_handle_sink_remove_client_link (GstMultiHandleSink * sink,
926     GList * link)
927 {
928   GTimeVal now;
929   GstMultiHandleClient *mhclient = (GstMultiHandleClient *) link->data;
930   GstMultiHandleSinkClass *mhsinkclass = GST_MULTI_HANDLE_SINK_GET_CLASS (sink);
931
932   if (mhclient->currently_removing) {
933     GST_WARNING_OBJECT (sink, "%s client is already being removed",
934         mhclient->debug);
935     return;
936   } else {
937     mhclient->currently_removing = TRUE;
938   }
939
940   /* FIXME: if we keep track of ip we can log it here and signal */
941   switch (mhclient->status) {
942     case GST_CLIENT_STATUS_OK:
943       GST_WARNING_OBJECT (sink, "%s removing client %p for no reason",
944           mhclient->debug, mhclient);
945       break;
946     case GST_CLIENT_STATUS_CLOSED:
947       GST_DEBUG_OBJECT (sink, "%s removing client %p because of close",
948           mhclient->debug, mhclient);
949       break;
950     case GST_CLIENT_STATUS_REMOVED:
951       GST_DEBUG_OBJECT (sink,
952           "%s removing client %p because the app removed it", mhclient->debug,
953           mhclient);
954       break;
955     case GST_CLIENT_STATUS_SLOW:
956       GST_INFO_OBJECT (sink,
957           "%s removing client %p because it was too slow", mhclient->debug,
958           mhclient);
959       break;
960     case GST_CLIENT_STATUS_ERROR:
961       GST_WARNING_OBJECT (sink,
962           "%s removing client %p because of error", mhclient->debug, mhclient);
963       break;
964     case GST_CLIENT_STATUS_FLUSHING:
965     default:
966       GST_WARNING_OBJECT (sink,
967           "%s removing client %p with invalid reason %d", mhclient->debug,
968           mhclient, mhclient->status);
969       break;
970   }
971
972   mhsinkclass->hash_removing (sink, mhclient);
973
974   g_get_current_time (&now);
975   mhclient->disconnect_time = GST_TIMEVAL_TO_TIME (now);
976
977   /* free client buffers */
978   g_slist_foreach (mhclient->sending, (GFunc) gst_mini_object_unref, NULL);
979   g_slist_free (mhclient->sending);
980   mhclient->sending = NULL;
981
982   if (mhclient->caps)
983     gst_caps_unref (mhclient->caps);
984   mhclient->caps = NULL;
985
986   /* unlock the mutex before signaling because the signal handler
987    * might query some properties */
988   CLIENTS_UNLOCK (sink);
989
990   mhsinkclass->emit_client_removed (sink, mhclient->handle, mhclient->status);
991
992   /* lock again before we remove the client completely */
993   CLIENTS_LOCK (sink);
994
995   /* handle cannot be reused in the above signal callback so we can safely
996    * remove it from the hashtable here */
997   if (!g_hash_table_remove (sink->handle_hash,
998           mhsinkclass->handle_hash_key (mhclient->handle))) {
999     GST_WARNING_OBJECT (sink,
1000         "%s error removing client %p from hash", mhclient->debug, mhclient);
1001   }
1002   /* after releasing the lock above, the link could be invalid, more
1003    * precisely, the next and prev pointers could point to invalid list
1004    * links. One optimisation could be to add a cookie to the linked list
1005    * and take a shortcut when it did not change between unlocking and locking
1006    * our mutex. For now we just walk the list again. */
1007   sink->clients = g_list_remove (sink->clients, mhclient);
1008   sink->clients_cookie++;
1009
1010   if (mhsinkclass->removed)
1011     mhsinkclass->removed (sink, mhclient->handle);
1012
1013   CLIENTS_UNLOCK (sink);
1014
1015   /* sub-class must implement this to emit the client-$handle-removed signal */
1016   g_assert (mhsinkclass->client_free != NULL);
1017
1018   /* and the handle is really gone now */
1019   mhsinkclass->client_free (sink, mhclient);
1020
1021   g_free (mhclient);
1022
1023   CLIENTS_LOCK (sink);
1024 }
1025
1026 static gboolean
1027 gst_multi_handle_sink_client_queue_buffer (GstMultiHandleSink * mhsink,
1028     GstMultiHandleClient * mhclient, GstBuffer * buffer)
1029 {
1030   GstMultiHandleSink *sink = GST_MULTI_HANDLE_SINK (mhsink);
1031   GstCaps *caps;
1032
1033   /* TRUE: send them if the new caps have them */
1034   gboolean send_streamheader = FALSE;
1035   GstStructure *s;
1036
1037   /* before we queue the buffer, we check if we need to queue streamheader
1038    * buffers (because it's a new client, or because they changed) */
1039   caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (sink));
1040
1041   if (!mhclient->caps) {
1042     GST_DEBUG_OBJECT (sink,
1043         "%s no previous caps for this client, send streamheader",
1044         mhclient->debug);
1045     send_streamheader = TRUE;
1046     mhclient->caps = gst_caps_ref (caps);
1047   } else {
1048     /* there were previous caps recorded, so compare */
1049     if (!gst_caps_is_equal (caps, mhclient->caps)) {
1050       const GValue *sh1, *sh2;
1051
1052       /* caps are not equal, but could still have the same streamheader */
1053       s = gst_caps_get_structure (caps, 0);
1054       if (!gst_structure_has_field (s, "streamheader")) {
1055         /* no new streamheader, so nothing new to send */
1056         GST_DEBUG_OBJECT (sink,
1057             "%s new caps do not have streamheader, not sending",
1058             mhclient->debug);
1059       } else {
1060         /* there is a new streamheader */
1061         s = gst_caps_get_structure (mhclient->caps, 0);
1062         if (!gst_structure_has_field (s, "streamheader")) {
1063           /* no previous streamheader, so send the new one */
1064           GST_DEBUG_OBJECT (sink,
1065               "%s previous caps did not have streamheader, sending",
1066               mhclient->debug);
1067           send_streamheader = TRUE;
1068         } else {
1069           /* both old and new caps have streamheader set */
1070           if (!mhsink->resend_streamheader) {
1071             GST_DEBUG_OBJECT (sink,
1072                 "%s asked to not resend the streamheader, not sending",
1073                 mhclient->debug);
1074             send_streamheader = FALSE;
1075           } else {
1076             sh1 = gst_structure_get_value (s, "streamheader");
1077             s = gst_caps_get_structure (caps, 0);
1078             sh2 = gst_structure_get_value (s, "streamheader");
1079             if (gst_value_compare (sh1, sh2) != GST_VALUE_EQUAL) {
1080               GST_DEBUG_OBJECT (sink,
1081                   "%s new streamheader different from old, sending",
1082                   mhclient->debug);
1083               send_streamheader = TRUE;
1084             }
1085           }
1086         }
1087       }
1088     }
1089     /* Replace the old caps */
1090     gst_caps_unref (mhclient->caps);
1091     mhclient->caps = gst_caps_ref (caps);
1092   }
1093
1094   if (G_UNLIKELY (send_streamheader)) {
1095     const GValue *sh;
1096     GArray *buffers;
1097     int i;
1098
1099     GST_LOG_OBJECT (sink,
1100         "%s sending streamheader from caps %" GST_PTR_FORMAT,
1101         mhclient->debug, caps);
1102     s = gst_caps_get_structure (caps, 0);
1103     if (!gst_structure_has_field (s, "streamheader")) {
1104       GST_DEBUG_OBJECT (sink,
1105           "%s no new streamheader, so nothing to send", mhclient->debug);
1106     } else {
1107       GST_LOG_OBJECT (sink,
1108           "%s sending streamheader from caps %" GST_PTR_FORMAT,
1109           mhclient->debug, caps);
1110       sh = gst_structure_get_value (s, "streamheader");
1111       g_assert (G_VALUE_TYPE (sh) == GST_TYPE_ARRAY);
1112       buffers = g_value_peek_pointer (sh);
1113       GST_DEBUG_OBJECT (sink, "%d streamheader buffers", buffers->len);
1114       for (i = 0; i < buffers->len; ++i) {
1115         GValue *bufval;
1116         GstBuffer *buffer;
1117
1118         bufval = &g_array_index (buffers, GValue, i);
1119         g_assert (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER);
1120         buffer = g_value_peek_pointer (bufval);
1121         GST_DEBUG_OBJECT (sink,
1122             "%s queueing streamheader buffer of length %" G_GSIZE_FORMAT,
1123             mhclient->debug, gst_buffer_get_size (buffer));
1124         gst_buffer_ref (buffer);
1125
1126         mhclient->sending = g_slist_append (mhclient->sending, buffer);
1127       }
1128     }
1129   }
1130
1131   gst_caps_unref (caps);
1132   caps = NULL;
1133
1134   GST_LOG_OBJECT (sink, "%s queueing buffer of length %" G_GSIZE_FORMAT,
1135       mhclient->debug, gst_buffer_get_size (buffer));
1136
1137   gst_buffer_ref (buffer);
1138   mhclient->sending = g_slist_append (mhclient->sending, buffer);
1139
1140   return TRUE;
1141 }
1142
1143 static gboolean
1144 is_sync_frame (GstMultiHandleSink * sink, GstBuffer * buffer)
1145 {
1146   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1147     return FALSE;
1148   } else if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_HEADER)) {
1149     return TRUE;
1150   }
1151
1152   return FALSE;
1153 }
1154
1155 /* find the keyframe in the list of buffers starting the
1156  * search from @idx. @direction as -1 will search backwards, 
1157  * 1 will search forwards.
1158  * Returns: the index or -1 if there is no keyframe after idx.
1159  */
1160 gint
1161 find_syncframe (GstMultiHandleSink * sink, gint idx, gint direction)
1162 {
1163   gint i, len, result;
1164
1165   /* take length of queued buffers */
1166   len = sink->bufqueue->len;
1167
1168   /* assume we don't find a keyframe */
1169   result = -1;
1170
1171   /* then loop over all buffers to find the first keyframe */
1172   for (i = idx; i >= 0 && i < len; i += direction) {
1173     GstBuffer *buf;
1174
1175     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1176     if (is_sync_frame (sink, buf)) {
1177       GST_LOG_OBJECT (sink, "found keyframe at %d from %d, direction %d",
1178           i, idx, direction);
1179       result = i;
1180       break;
1181     }
1182   }
1183   return result;
1184 }
1185
1186 /* Get the number of buffers from the buffer queue needed to satisfy
1187  * the maximum max in the configured units.
1188  * If units are not BUFFERS, and there are insufficient buffers in the
1189  * queue to satify the limit, return len(queue) + 1 */
1190 gint
1191 get_buffers_max (GstMultiHandleSink * sink, gint64 max)
1192 {
1193   switch (sink->unit_format) {
1194     case GST_FORMAT_BUFFERS:
1195       return max;
1196     case GST_FORMAT_TIME:
1197     {
1198       GstBuffer *buf;
1199       int i;
1200       int len;
1201       gint64 diff;
1202       GstClockTime first = GST_CLOCK_TIME_NONE;
1203
1204       len = sink->bufqueue->len;
1205
1206       for (i = 0; i < len; i++) {
1207         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1208         if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1209           if (first == -1)
1210             first = GST_BUFFER_TIMESTAMP (buf);
1211
1212           diff = first - GST_BUFFER_TIMESTAMP (buf);
1213
1214           if (diff > max)
1215             return i + 1;
1216         }
1217       }
1218       return len + 1;
1219     }
1220     case GST_FORMAT_BYTES:
1221     {
1222       GstBuffer *buf;
1223       int i;
1224       int len;
1225       gint acc = 0;
1226
1227       len = sink->bufqueue->len;
1228
1229       for (i = 0; i < len; i++) {
1230         buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1231         acc += gst_buffer_get_size (buf);
1232
1233         if (acc > max)
1234           return i + 1;
1235       }
1236       return len + 1;
1237     }
1238     default:
1239       return max;
1240   }
1241 }
1242
1243 /* find the positions in the buffer queue where *_min and *_max
1244  * is satisfied
1245  */
1246 /* count the amount of data in the buffers and return the index
1247  * that satifies the given limits.
1248  *
1249  * Returns: index @idx in the buffer queue so that the given limits are
1250  * satisfied. TRUE if all the limits could be satisfied, FALSE if not
1251  * enough data was in the queue.
1252  *
1253  * FIXME, this code might now work if any of the units is in buffers...
1254  */
1255 gboolean
1256 find_limits (GstMultiHandleSink * sink,
1257     gint * min_idx, gint bytes_min, gint buffers_min, gint64 time_min,
1258     gint * max_idx, gint bytes_max, gint buffers_max, gint64 time_max)
1259 {
1260   GstClockTime first, time;
1261   gint i, len, bytes;
1262   gboolean result, max_hit;
1263
1264   /* take length of queue */
1265   len = sink->bufqueue->len;
1266
1267   /* this must hold */
1268   g_assert (len > 0);
1269
1270   GST_LOG_OBJECT (sink,
1271       "bytes_min %d, buffers_min %d, time_min %" GST_TIME_FORMAT
1272       ", bytes_max %d, buffers_max %d, time_max %" GST_TIME_FORMAT, bytes_min,
1273       buffers_min, GST_TIME_ARGS (time_min), bytes_max, buffers_max,
1274       GST_TIME_ARGS (time_max));
1275
1276   /* do the trivial buffer limit test */
1277   if (buffers_min != -1 && len < buffers_min) {
1278     *min_idx = len - 1;
1279     *max_idx = len - 1;
1280     return FALSE;
1281   }
1282
1283   result = FALSE;
1284   /* else count bytes and time */
1285   first = -1;
1286   bytes = 0;
1287   /* unset limits */
1288   *min_idx = -1;
1289   *max_idx = -1;
1290   max_hit = FALSE;
1291
1292   i = 0;
1293   /* loop through the buffers, when a limit is ok, mark it 
1294    * as -1, we have at least one buffer in the queue. */
1295   do {
1296     GstBuffer *buf;
1297
1298     /* if we checked all min limits, update result */
1299     if (bytes_min == -1 && time_min == -1 && *min_idx == -1) {
1300       /* don't go below 0 */
1301       *min_idx = MAX (i - 1, 0);
1302     }
1303     /* if we reached one max limit break out */
1304     if (max_hit) {
1305       /* i > 0 when we get here, we subtract one to get the position
1306        * of the previous buffer. */
1307       *max_idx = i - 1;
1308       /* we have valid complete result if we found a min_idx too */
1309       result = *min_idx != -1;
1310       break;
1311     }
1312     buf = g_array_index (sink->bufqueue, GstBuffer *, i);
1313
1314     bytes += gst_buffer_get_size (buf);
1315
1316     /* take timestamp and save for the base first timestamp */
1317     if ((time = GST_BUFFER_TIMESTAMP (buf)) != -1) {
1318       GST_LOG_OBJECT (sink, "Ts %" GST_TIME_FORMAT " on buffer",
1319           GST_TIME_ARGS (time));
1320       if (first == -1)
1321         first = time;
1322
1323       /* increase max usage if we did not fill enough. Note that
1324        * buffers are sorted from new to old, so the first timestamp is
1325        * bigger than the next one. */
1326       if (time_min != -1 && first - time >= time_min)
1327         time_min = -1;
1328       if (time_max != -1 && first - time >= time_max)
1329         max_hit = TRUE;
1330     } else {
1331       GST_LOG_OBJECT (sink, "No timestamp on buffer");
1332     }
1333     /* time is OK or unknown, check and increase if not enough bytes */
1334     if (bytes_min != -1) {
1335       if (bytes >= bytes_min)
1336         bytes_min = -1;
1337     }
1338     if (bytes_max != -1) {
1339       if (bytes >= bytes_max) {
1340         max_hit = TRUE;
1341       }
1342     }
1343     i++;
1344   }
1345   while (i < len);
1346
1347   /* if we did not hit the max or min limit, set to buffer size */
1348   if (*max_idx == -1)
1349     *max_idx = len - 1;
1350   /* make sure min does not exceed max */
1351   if (*min_idx == -1)
1352     *min_idx = *max_idx;
1353
1354   return result;
1355 }
1356
1357 /* parse the unit/value pair and assign it to the result value of the
1358  * right type, leave the other values untouched 
1359  *
1360  * Returns: FALSE if the unit is unknown or undefined. TRUE otherwise.
1361  */
1362 static gboolean
1363 assign_value (GstFormat format, guint64 value, gint * bytes, gint * buffers,
1364     GstClockTime * time)
1365 {
1366   gboolean res = TRUE;
1367
1368   /* set only the limit of the given format to the given value */
1369   switch (format) {
1370     case GST_FORMAT_BUFFERS:
1371       *buffers = (gint) value;
1372       break;
1373     case GST_FORMAT_TIME:
1374       *time = value;
1375       break;
1376     case GST_FORMAT_BYTES:
1377       *bytes = (gint) value;
1378       break;
1379     case GST_FORMAT_UNDEFINED:
1380     default:
1381       res = FALSE;
1382       break;
1383   }
1384   return res;
1385 }
1386
1387 /* count the index in the buffer queue to satisfy the given unit
1388  * and value pair starting from buffer at index 0.
1389  *
1390  * Returns: TRUE if there was enough data in the queue to satisfy the
1391  * burst values. @idx contains the index in the buffer that contains enough
1392  * data to satisfy the limits or the last buffer in the queue when the
1393  * function returns FALSE.
1394  */
1395 static gboolean
1396 count_burst_unit (GstMultiHandleSink * sink, gint * min_idx,
1397     GstFormat min_format, guint64 min_value, gint * max_idx,
1398     GstFormat max_format, guint64 max_value)
1399 {
1400   gint bytes_min = -1, buffers_min = -1;
1401   gint bytes_max = -1, buffers_max = -1;
1402   GstClockTime time_min = GST_CLOCK_TIME_NONE, time_max = GST_CLOCK_TIME_NONE;
1403
1404   assign_value (min_format, min_value, &bytes_min, &buffers_min, &time_min);
1405   assign_value (max_format, max_value, &bytes_max, &buffers_max, &time_max);
1406
1407   return find_limits (sink, min_idx, bytes_min, buffers_min, time_min,
1408       max_idx, bytes_max, buffers_max, time_max);
1409 }
1410
1411 /* decide where in the current buffer queue this new client should start
1412  * receiving buffers from.
1413  * This function is called whenever a client is connected and has not yet
1414  * received a buffer.
1415  * If this returns -1, it means that we haven't found a good point to
1416  * start streaming from yet, and this function should be called again later
1417  * when more buffers have arrived.
1418  */
1419 gint
1420 gst_multi_handle_sink_new_client_position (GstMultiHandleSink * sink,
1421     GstMultiHandleClient * client)
1422 {
1423   gint result;
1424
1425   GST_DEBUG_OBJECT (sink,
1426       "%s new client, deciding where to start in queue", client->debug);
1427   GST_DEBUG_OBJECT (sink, "queue is currently %d buffers long",
1428       sink->bufqueue->len);
1429   switch (client->sync_method) {
1430     case GST_SYNC_METHOD_LATEST:
1431       /* no syncing, we are happy with whatever the client is going to get */
1432       result = client->bufpos;
1433       GST_DEBUG_OBJECT (sink,
1434           "%s SYNC_METHOD_LATEST, position %d", client->debug, result);
1435       break;
1436     case GST_SYNC_METHOD_NEXT_KEYFRAME:
1437     {
1438       /* if one of the new buffers (between client->bufpos and 0) in the queue
1439        * is a sync point, we can proceed, otherwise we need to keep waiting */
1440       GST_LOG_OBJECT (sink,
1441           "%s new client, bufpos %d, waiting for keyframe",
1442           client->debug, client->bufpos);
1443
1444       result = find_prev_syncframe (sink, client->bufpos);
1445       if (result != -1) {
1446         GST_DEBUG_OBJECT (sink,
1447             "%s SYNC_METHOD_NEXT_KEYFRAME: result %d", client->debug, result);
1448         break;
1449       }
1450
1451       /* client is not on a syncbuffer, need to skip these buffers and
1452        * wait some more */
1453       GST_LOG_OBJECT (sink,
1454           "%s new client, skipping buffer(s), no syncpoint found",
1455           client->debug);
1456       client->bufpos = -1;
1457       break;
1458     }
1459     case GST_SYNC_METHOD_LATEST_KEYFRAME:
1460     {
1461       GST_DEBUG_OBJECT (sink, "%s SYNC_METHOD_LATEST_KEYFRAME", client->debug);
1462
1463       /* for new clients we initially scan the complete buffer queue for
1464        * a sync point when a buffer is added. If we don't find a keyframe,
1465        * we need to wait for the next keyframe and so we change the client's
1466        * sync method to GST_SYNC_METHOD_NEXT_KEYFRAME.
1467        */
1468       result = find_next_syncframe (sink, 0);
1469       if (result != -1) {
1470         GST_DEBUG_OBJECT (sink,
1471             "%s SYNC_METHOD_LATEST_KEYFRAME: result %d", client->debug, result);
1472         break;
1473       }
1474
1475       GST_DEBUG_OBJECT (sink,
1476           "%s SYNC_METHOD_LATEST_KEYFRAME: no keyframe found, "
1477           "switching to SYNC_METHOD_NEXT_KEYFRAME", client->debug);
1478       /* throw client to the waiting state */
1479       client->bufpos = -1;
1480       /* and make client sync to next keyframe */
1481       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1482       break;
1483     }
1484     case GST_SYNC_METHOD_BURST:
1485     {
1486       gboolean ok;
1487       gint max;
1488
1489       /* move to the position where we satisfy the client's burst
1490        * parameters. If we could not satisfy the parameters because there
1491        * is not enough data, we just send what we have (which is in result).
1492        * We use the max value to limit the search
1493        */
1494       ok = count_burst_unit (sink, &result, client->burst_min_format,
1495           client->burst_min_value, &max, client->burst_max_format,
1496           client->burst_max_value);
1497       GST_DEBUG_OBJECT (sink,
1498           "%s SYNC_METHOD_BURST: burst_unit returned %d, result %d",
1499           client->debug, ok, result);
1500
1501       GST_LOG_OBJECT (sink, "min %d, max %d", result, max);
1502
1503       /* we hit the max and it is below the min, use that then */
1504       if (max != -1 && max <= result) {
1505         result = MAX (max - 1, 0);
1506         GST_DEBUG_OBJECT (sink,
1507             "%s SYNC_METHOD_BURST: result above max, taken down to %d",
1508             client->debug, result);
1509       }
1510       break;
1511     }
1512     case GST_SYNC_METHOD_BURST_KEYFRAME:
1513     {
1514       gint min_idx, max_idx;
1515       gint next_syncframe, prev_syncframe;
1516
1517       /* BURST_KEYFRAME:
1518        *
1519        * _always_ start sending a keyframe to the client. We first search
1520        * a keyframe between min/max limits. If there is none, we send it the
1521        * last keyframe before min. If there is none, the behaviour is like
1522        * NEXT_KEYFRAME.
1523        */
1524       /* gather burst limits */
1525       count_burst_unit (sink, &min_idx, client->burst_min_format,
1526           client->burst_min_value, &max_idx, client->burst_max_format,
1527           client->burst_max_value);
1528
1529       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1530
1531       /* first find a keyframe after min_idx */
1532       next_syncframe = find_next_syncframe (sink, min_idx);
1533       if (next_syncframe != -1 && next_syncframe < max_idx) {
1534         /* we have a valid keyframe and it's below the max */
1535         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1536         result = next_syncframe;
1537         break;
1538       }
1539
1540       /* no valid keyframe, try to find one below min */
1541       prev_syncframe = find_prev_syncframe (sink, min_idx);
1542       if (prev_syncframe != -1) {
1543         GST_WARNING_OBJECT (sink,
1544             "using keyframe below min in BURST_KEYFRAME sync mode");
1545         result = prev_syncframe;
1546         break;
1547       }
1548
1549       /* no prev keyframe or not enough data  */
1550       GST_WARNING_OBJECT (sink,
1551           "no prev keyframe found in BURST_KEYFRAME sync mode, waiting for next");
1552
1553       /* throw client to the waiting state */
1554       client->bufpos = -1;
1555       /* and make client sync to next keyframe */
1556       client->sync_method = GST_SYNC_METHOD_NEXT_KEYFRAME;
1557       result = -1;
1558       break;
1559     }
1560     case GST_SYNC_METHOD_BURST_WITH_KEYFRAME:
1561     {
1562       gint min_idx, max_idx;
1563       gint next_syncframe;
1564
1565       /* BURST_WITH_KEYFRAME:
1566        *
1567        * try to start sending a keyframe to the client. We first search
1568        * a keyframe between min/max limits. If there is none, we send it the
1569        * amount of data up 'till min.
1570        */
1571       /* gather enough data to burst */
1572       count_burst_unit (sink, &min_idx, client->burst_min_format,
1573           client->burst_min_value, &max_idx, client->burst_max_format,
1574           client->burst_max_value);
1575
1576       GST_LOG_OBJECT (sink, "min %d, max %d", min_idx, max_idx);
1577
1578       /* first find a keyframe after min_idx */
1579       next_syncframe = find_next_syncframe (sink, min_idx);
1580       if (next_syncframe != -1 && next_syncframe < max_idx) {
1581         /* we have a valid keyframe and it's below the max */
1582         GST_LOG_OBJECT (sink, "found keyframe in min/max limits");
1583         result = next_syncframe;
1584         break;
1585       }
1586
1587       /* no keyframe, send data from min_idx */
1588       GST_WARNING_OBJECT (sink, "using min in BURST_WITH_KEYFRAME sync mode");
1589
1590       /* make sure we don't go over the max limit */
1591       if (max_idx != -1 && max_idx <= min_idx) {
1592         result = MAX (max_idx - 1, 0);
1593       } else {
1594         result = min_idx;
1595       }
1596
1597       break;
1598     }
1599     default:
1600       g_warning ("unknown sync method %d", client->sync_method);
1601       result = client->bufpos;
1602       break;
1603   }
1604   return result;
1605 }
1606
1607 /* calculate the new position for a client after recovery. This function
1608  * does not update the client position but merely returns the required
1609  * position.
1610  */
1611 gint
1612 gst_multi_handle_sink_recover_client (GstMultiHandleSink * sink,
1613     GstMultiHandleClient * client)
1614 {
1615   gint newbufpos;
1616
1617   GST_WARNING_OBJECT (sink,
1618       "%s client %p is lagging at %d, recover using policy %d",
1619       client->debug, client, client->bufpos, sink->recover_policy);
1620
1621   switch (sink->recover_policy) {
1622     case GST_RECOVER_POLICY_NONE:
1623       /* do nothing, client will catch up or get kicked out when it reaches
1624        * the hard max */
1625       newbufpos = client->bufpos;
1626       break;
1627     case GST_RECOVER_POLICY_RESYNC_LATEST:
1628       /* move to beginning of queue */
1629       newbufpos = -1;
1630       break;
1631     case GST_RECOVER_POLICY_RESYNC_SOFT_LIMIT:
1632       /* move to beginning of soft max */
1633       newbufpos = get_buffers_max (sink, sink->units_soft_max);
1634       break;
1635     case GST_RECOVER_POLICY_RESYNC_KEYFRAME:
1636       /* find keyframe in buffers, we search backwards to find the
1637        * closest keyframe relative to what this client already received. */
1638       newbufpos = MIN (sink->bufqueue->len - 1,
1639           get_buffers_max (sink, sink->units_soft_max) - 1);
1640
1641       while (newbufpos >= 0) {
1642         GstBuffer *buf;
1643
1644         buf = g_array_index (sink->bufqueue, GstBuffer *, newbufpos);
1645         if (is_sync_frame (sink, buf)) {
1646           /* found a buffer that is not a delta unit */
1647           break;
1648         }
1649         newbufpos--;
1650       }
1651       break;
1652     default:
1653       /* unknown recovery procedure */
1654       newbufpos = get_buffers_max (sink, sink->units_soft_max);
1655       break;
1656   }
1657   return newbufpos;
1658 }
1659
1660 /* Queue a buffer on the global queue.
1661  *
1662  * This function adds the buffer to the front of a GArray. It removes the
1663  * tail buffer if the max queue size is exceeded, unreffing the queued buffer.
1664  * Note that unreffing the buffer is not a problem as clients who
1665  * started writing out this buffer will still have a reference to it in the
1666  * mhclient->sending queue.
1667  *
1668  * After adding the buffer, we update all client positions in the queue. If
1669  * a client moves over the soft max, we start the recovery procedure for this
1670  * slow client. If it goes over the hard max, it is put into the slow list
1671  * and removed.
1672  *
1673  * Special care is taken of clients that were waiting for a new buffer (they
1674  * had a position of -1) because they can proceed after adding this new buffer.
1675  * This is done by adding the client back into the write fd_set and signaling
1676  * the select thread that the fd_set changed.
1677  */
1678 static void
1679 gst_multi_handle_sink_queue_buffer (GstMultiHandleSink * mhsink,
1680     GstBuffer * buffer)
1681 {
1682   GList *clients, *next;
1683   gint queuelen;
1684   gboolean hash_changed = FALSE;
1685   gint max_buffer_usage;
1686   gint i;
1687   GTimeVal nowtv;
1688   GstClockTime now;
1689   gint max_buffers, soft_max_buffers;
1690   guint cookie;
1691   GstMultiHandleSink *sink = GST_MULTI_HANDLE_SINK (mhsink);
1692   GstMultiHandleSinkClass *mhsinkclass =
1693       GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
1694
1695   g_get_current_time (&nowtv);
1696   now = GST_TIMEVAL_TO_TIME (nowtv);
1697
1698   CLIENTS_LOCK (mhsink);
1699   /* add buffer to queue */
1700   g_array_prepend_val (mhsink->bufqueue, buffer);
1701   queuelen = mhsink->bufqueue->len;
1702
1703   if (mhsink->units_max > 0)
1704     max_buffers = get_buffers_max (mhsink, mhsink->units_max);
1705   else
1706     max_buffers = -1;
1707
1708   if (mhsink->units_soft_max > 0)
1709     soft_max_buffers = get_buffers_max (mhsink, mhsink->units_soft_max);
1710   else
1711     soft_max_buffers = -1;
1712   GST_LOG_OBJECT (sink, "Using max %d, softmax %d", max_buffers,
1713       soft_max_buffers);
1714
1715   /* then loop over the clients and update the positions */
1716   max_buffer_usage = 0;
1717
1718 restart:
1719   cookie = mhsink->clients_cookie;
1720   for (clients = mhsink->clients; clients; clients = next) {
1721     GstMultiHandleClient *mhclient = clients->data;
1722
1723     if (cookie != mhsink->clients_cookie) {
1724       GST_DEBUG_OBJECT (sink, "Clients cookie outdated, restarting");
1725       goto restart;
1726     }
1727
1728     next = g_list_next (clients);
1729
1730     mhclient->bufpos++;
1731     GST_LOG_OBJECT (sink, "%s client %p at position %d",
1732         mhclient->debug, mhclient, mhclient->bufpos);
1733     /* check soft max if needed, recover client */
1734     if (soft_max_buffers > 0 && mhclient->bufpos >= soft_max_buffers) {
1735       gint newpos;
1736
1737       newpos = gst_multi_handle_sink_recover_client (mhsink, mhclient);
1738       if (newpos != mhclient->bufpos) {
1739         mhclient->dropped_buffers += mhclient->bufpos - newpos;
1740         mhclient->bufpos = newpos;
1741         mhclient->discont = TRUE;
1742         GST_INFO_OBJECT (sink, "%s client %p position reset to %d",
1743             mhclient->debug, mhclient, mhclient->bufpos);
1744       } else {
1745         GST_INFO_OBJECT (sink,
1746             "%s client %p not recovering position", mhclient->debug, mhclient);
1747       }
1748     }
1749     /* check hard max and timeout, remove client */
1750     if ((max_buffers > 0 && mhclient->bufpos >= max_buffers) ||
1751         (mhsink->timeout > 0
1752             && now - mhclient->last_activity_time > mhsink->timeout)) {
1753       /* remove client */
1754       GST_WARNING_OBJECT (sink, "%s client %p is too slow, removing",
1755           mhclient->debug, mhclient);
1756       /* remove the client, the handle set will be cleared and the select thread
1757        * will be signaled */
1758       mhclient->status = GST_CLIENT_STATUS_SLOW;
1759       /* set client to invalid position while being removed */
1760       mhclient->bufpos = -1;
1761       gst_multi_handle_sink_remove_client_link (mhsink, clients);
1762       hash_changed = TRUE;
1763       continue;
1764     } else if (mhclient->bufpos == 0 || mhclient->new_connection) {
1765       /* can send data to this client now. need to signal the select thread that
1766        * the handle_set changed */
1767       mhsinkclass->hash_adding (mhsink, mhclient);
1768       hash_changed = TRUE;
1769     }
1770     /* keep track of maximum buffer usage */
1771     if (mhclient->bufpos > max_buffer_usage) {
1772       max_buffer_usage = mhclient->bufpos;
1773     }
1774   }
1775
1776   /* make sure we respect bytes-min, buffers-min and time-min when they are set */
1777   {
1778     gint usage, max;
1779
1780     GST_LOG_OBJECT (sink,
1781         "extending queue %d to respect time_min %" GST_TIME_FORMAT
1782         ", bytes_min %d, buffers_min %d", max_buffer_usage,
1783         GST_TIME_ARGS (mhsink->time_min), mhsink->bytes_min,
1784         mhsink->buffers_min);
1785
1786     /* get index where the limits are ok, we don't really care if all limits
1787      * are ok, we just queue as much as we need. We also don't compare against
1788      * the max limits. */
1789     find_limits (mhsink, &usage, mhsink->bytes_min, mhsink->buffers_min,
1790         mhsink->time_min, &max, -1, -1, -1);
1791
1792     max_buffer_usage = MAX (max_buffer_usage, usage + 1);
1793     GST_LOG_OBJECT (sink, "extended queue to %d", max_buffer_usage);
1794   }
1795
1796   /* now look for sync points and make sure there is at least one
1797    * sync point in the queue. We only do this if the LATEST_KEYFRAME or 
1798    * BURST_KEYFRAME mode is selected */
1799   if (mhsink->def_sync_method == GST_SYNC_METHOD_LATEST_KEYFRAME ||
1800       mhsink->def_sync_method == GST_SYNC_METHOD_BURST_KEYFRAME) {
1801     /* no point in searching beyond the queue length */
1802     gint limit = queuelen;
1803     GstBuffer *buf;
1804
1805     /* no point in searching beyond the soft-max if any. */
1806     if (soft_max_buffers > 0) {
1807       limit = MIN (limit, soft_max_buffers);
1808     }
1809     GST_LOG_OBJECT (sink,
1810         "extending queue to include sync point, now at %d, limit is %d",
1811         max_buffer_usage, limit);
1812     for (i = 0; i < limit; i++) {
1813       buf = g_array_index (mhsink->bufqueue, GstBuffer *, i);
1814       if (is_sync_frame (mhsink, buf)) {
1815         /* found a sync frame, now extend the buffer usage to
1816          * include at least this frame. */
1817         max_buffer_usage = MAX (max_buffer_usage, i);
1818         break;
1819       }
1820     }
1821     GST_LOG_OBJECT (sink, "max buffer usage is now %d", max_buffer_usage);
1822   }
1823
1824   GST_LOG_OBJECT (sink, "len %d, usage %d", queuelen, max_buffer_usage);
1825
1826   /* nobody is referencing units after max_buffer_usage so we can
1827    * remove them from the queue. We remove them in reverse order as
1828    * this is the most optimal for GArray. */
1829   for (i = queuelen - 1; i > max_buffer_usage; i--) {
1830     GstBuffer *old;
1831
1832     /* queue exceeded max size */
1833     queuelen--;
1834     old = g_array_index (mhsink->bufqueue, GstBuffer *, i);
1835     mhsink->bufqueue = g_array_remove_index (mhsink->bufqueue, i);
1836
1837     /* unref tail buffer */
1838     gst_buffer_unref (old);
1839   }
1840   /* save for stats */
1841   mhsink->buffers_queued = max_buffer_usage;
1842   CLIENTS_UNLOCK (sink);
1843
1844   /* and send a signal to thread if handle_set changed */
1845   if (hash_changed && mhsinkclass->hash_changed) {
1846     mhsinkclass->hash_changed (mhsink);
1847   }
1848 }
1849
1850 static GstFlowReturn
1851 gst_multi_handle_sink_render (GstBaseSink * bsink, GstBuffer * buf)
1852 {
1853   gboolean in_caps;
1854 #if 0
1855   GstCaps *bufcaps, *padcaps;
1856 #endif
1857
1858   GstMultiHandleSink *sink = GST_MULTI_HANDLE_SINK (bsink);
1859
1860   g_return_val_if_fail (GST_OBJECT_FLAG_IS_SET (sink,
1861           GST_MULTI_HANDLE_SINK_OPEN), GST_FLOW_FLUSHING);
1862
1863 #if 0
1864   /* since we check every buffer for streamheader caps, we need to make
1865    * sure every buffer has caps set */
1866   bufcaps = gst_buffer_get_caps (buf);
1867   padcaps = GST_PAD_CAPS (GST_BASE_SINK_PAD (bsink));
1868
1869   /* make sure we have caps on the pad */
1870   if (!padcaps && !bufcaps)
1871     goto no_caps;
1872 #endif
1873
1874   /* get IN_CAPS first, code below might mess with the flags */
1875   in_caps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_HEADER);
1876
1877 #if 0
1878   /* stamp the buffer with previous caps if no caps set */
1879   if (!bufcaps) {
1880     if (!gst_buffer_is_writable (buf)) {
1881       /* metadata is not writable, copy will be made and original buffer
1882        * will be unreffed so we need to ref so that we don't lose the
1883        * buffer in the render method. */
1884       gst_buffer_ref (buf);
1885       /* the new buffer is ours only, we keep it out of the scope of this
1886        * function */
1887       buf = gst_buffer_make_writable (buf);
1888     } else {
1889       /* else the metadata is writable, we ref because we keep the buffer
1890        * out of the scope of this method */
1891       gst_buffer_ref (buf);
1892     }
1893     /* buffer metadata is writable now, set the caps */
1894     gst_buffer_set_caps (buf, padcaps);
1895   } else {
1896     gst_caps_unref (bufcaps);
1897
1898     /* since we keep this buffer out of the scope of this method */
1899     gst_buffer_ref (buf);
1900   }
1901 #endif
1902   gst_buffer_ref (buf);
1903
1904   GST_LOG_OBJECT (sink, "received buffer %p, in_caps: %s, offset %"
1905       G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT
1906       ", timestamp %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1907       buf, in_caps ? "yes" : "no", GST_BUFFER_OFFSET (buf),
1908       GST_BUFFER_OFFSET_END (buf),
1909       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1910       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1911
1912   /* if we get IN_CAPS buffers, but the previous buffer was not IN_CAPS,
1913    * it means we're getting new streamheader buffers, and we should clear
1914    * the old ones */
1915   if (in_caps && sink->previous_buffer_in_caps == FALSE) {
1916     GST_DEBUG_OBJECT (sink,
1917         "receiving new HEADER buffers, clearing old streamheader");
1918     g_slist_foreach (sink->streamheader, (GFunc) gst_mini_object_unref, NULL);
1919     g_slist_free (sink->streamheader);
1920     sink->streamheader = NULL;
1921   }
1922
1923   /* save the current in_caps */
1924   sink->previous_buffer_in_caps = in_caps;
1925
1926   /* if the incoming buffer is marked as IN CAPS, then we assume for now
1927    * it's a streamheader that needs to be sent to each new client, so we
1928    * put it on our internal list of streamheader buffers.
1929    * FIXME: we could check if the buffer's contents are in fact part of the
1930    * current streamheader.
1931    *
1932    * We don't send the buffer to the client, since streamheaders are sent
1933    * separately when necessary. */
1934   if (in_caps) {
1935     GST_DEBUG_OBJECT (sink, "appending HEADER buffer with length %"
1936         G_GSIZE_FORMAT " to streamheader", gst_buffer_get_size (buf));
1937     sink->streamheader = g_slist_append (sink->streamheader, buf);
1938   } else {
1939     /* queue the buffer, this is a regular data buffer. */
1940     gst_multi_handle_sink_queue_buffer (sink, buf);
1941
1942     sink->bytes_to_serve += gst_buffer_get_size (buf);
1943   }
1944   return GST_FLOW_OK;
1945
1946   /* ERRORS */
1947 #if 0
1948 no_caps:
1949   {
1950     GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION, (NULL),
1951         ("Received first buffer without caps set"));
1952     return GST_FLOW_NOT_NEGOTIATED;
1953   }
1954 #endif
1955 }
1956
1957 static void
1958 gst_multi_handle_sink_set_property (GObject * object, guint prop_id,
1959     const GValue * value, GParamSpec * pspec)
1960 {
1961   GstMultiHandleSink *multihandlesink;
1962
1963   multihandlesink = GST_MULTI_HANDLE_SINK (object);
1964
1965   switch (prop_id) {
1966     case PROP_BUFFERS_MAX:
1967       multihandlesink->units_max = g_value_get_int (value);
1968       break;
1969     case PROP_BUFFERS_SOFT_MAX:
1970       multihandlesink->units_soft_max = g_value_get_int (value);
1971       break;
1972     case PROP_TIME_MIN:
1973       multihandlesink->time_min = g_value_get_int64 (value);
1974       break;
1975     case PROP_BYTES_MIN:
1976       multihandlesink->bytes_min = g_value_get_int (value);
1977       break;
1978     case PROP_BUFFERS_MIN:
1979       multihandlesink->buffers_min = g_value_get_int (value);
1980       break;
1981     case PROP_UNIT_FORMAT:
1982       multihandlesink->unit_format = g_value_get_enum (value);
1983       break;
1984     case PROP_UNITS_MAX:
1985       multihandlesink->units_max = g_value_get_int64 (value);
1986       break;
1987     case PROP_UNITS_SOFT_MAX:
1988       multihandlesink->units_soft_max = g_value_get_int64 (value);
1989       break;
1990     case PROP_RECOVER_POLICY:
1991       multihandlesink->recover_policy = g_value_get_enum (value);
1992       break;
1993     case PROP_TIMEOUT:
1994       multihandlesink->timeout = g_value_get_uint64 (value);
1995       break;
1996     case PROP_SYNC_METHOD:
1997       multihandlesink->def_sync_method = g_value_get_enum (value);
1998       break;
1999     case PROP_BURST_FORMAT:
2000       multihandlesink->def_burst_format = g_value_get_enum (value);
2001       break;
2002     case PROP_BURST_VALUE:
2003       multihandlesink->def_burst_value = g_value_get_uint64 (value);
2004       break;
2005     case PROP_QOS_DSCP:
2006       multihandlesink->qos_dscp = g_value_get_int (value);
2007       gst_multi_handle_sink_setup_dscp (multihandlesink);
2008       break;
2009
2010     case PROP_RESEND_STREAMHEADER:
2011       multihandlesink->resend_streamheader = g_value_get_boolean (value);
2012       break;
2013
2014     default:
2015       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2016       break;
2017   }
2018 }
2019
2020 static void
2021 gst_multi_handle_sink_get_property (GObject * object, guint prop_id,
2022     GValue * value, GParamSpec * pspec)
2023 {
2024   GstMultiHandleSink *multihandlesink;
2025
2026   multihandlesink = GST_MULTI_HANDLE_SINK (object);
2027
2028   switch (prop_id) {
2029     case PROP_BUFFERS_MAX:
2030       g_value_set_int (value, multihandlesink->units_max);
2031       break;
2032     case PROP_BUFFERS_SOFT_MAX:
2033       g_value_set_int (value, multihandlesink->units_soft_max);
2034       break;
2035     case PROP_TIME_MIN:
2036       g_value_set_int64 (value, multihandlesink->time_min);
2037       break;
2038     case PROP_BYTES_MIN:
2039       g_value_set_int (value, multihandlesink->bytes_min);
2040       break;
2041     case PROP_BUFFERS_MIN:
2042       g_value_set_int (value, multihandlesink->buffers_min);
2043       break;
2044     case PROP_BUFFERS_QUEUED:
2045       g_value_set_uint (value, multihandlesink->buffers_queued);
2046       break;
2047     case PROP_BYTES_QUEUED:
2048       g_value_set_uint (value, multihandlesink->bytes_queued);
2049       break;
2050     case PROP_TIME_QUEUED:
2051       g_value_set_uint64 (value, multihandlesink->time_queued);
2052       break;
2053     case PROP_UNIT_FORMAT:
2054       g_value_set_enum (value, multihandlesink->unit_format);
2055       break;
2056     case PROP_UNITS_MAX:
2057       g_value_set_int64 (value, multihandlesink->units_max);
2058       break;
2059     case PROP_UNITS_SOFT_MAX:
2060       g_value_set_int64 (value, multihandlesink->units_soft_max);
2061       break;
2062     case PROP_RECOVER_POLICY:
2063       g_value_set_enum (value, multihandlesink->recover_policy);
2064       break;
2065     case PROP_TIMEOUT:
2066       g_value_set_uint64 (value, multihandlesink->timeout);
2067       break;
2068     case PROP_SYNC_METHOD:
2069       g_value_set_enum (value, multihandlesink->def_sync_method);
2070       break;
2071     case PROP_BYTES_TO_SERVE:
2072       g_value_set_uint64 (value, multihandlesink->bytes_to_serve);
2073       break;
2074     case PROP_BYTES_SERVED:
2075       g_value_set_uint64 (value, multihandlesink->bytes_served);
2076       break;
2077     case PROP_BURST_FORMAT:
2078       g_value_set_enum (value, multihandlesink->def_burst_format);
2079       break;
2080     case PROP_BURST_VALUE:
2081       g_value_set_uint64 (value, multihandlesink->def_burst_value);
2082       break;
2083     case PROP_QOS_DSCP:
2084       g_value_set_int (value, multihandlesink->qos_dscp);
2085       break;
2086     case PROP_RESEND_STREAMHEADER:
2087       g_value_set_boolean (value, multihandlesink->resend_streamheader);
2088       break;
2089     case PROP_NUM_HANDLES:
2090       g_value_set_uint (value,
2091           g_hash_table_size (multihandlesink->handle_hash));
2092       break;
2093     default:
2094       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2095       break;
2096   }
2097 }
2098
2099 /* create a socket for sending to remote machine */
2100 static gboolean
2101 gst_multi_handle_sink_start (GstBaseSink * bsink)
2102 {
2103   GstMultiHandleSinkClass *mhsclass;
2104   GstMultiHandleSink *mhsink;
2105
2106   if (GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2107     return TRUE;
2108
2109   mhsink = GST_MULTI_HANDLE_SINK (bsink);
2110   mhsclass = GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
2111
2112   if (!mhsclass->start_pre (mhsink))
2113     return FALSE;
2114
2115   mhsink->streamheader = NULL;
2116   mhsink->bytes_to_serve = 0;
2117   mhsink->bytes_served = 0;
2118
2119   if (mhsclass->init) {
2120     mhsclass->init (mhsink);
2121   }
2122
2123   mhsink->running = TRUE;
2124
2125   mhsink->thread = g_thread_new ("multihandlesink",
2126       (GThreadFunc) mhsclass->thread, mhsink);
2127
2128   GST_OBJECT_FLAG_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN);
2129
2130   return TRUE;
2131 }
2132
2133 static gboolean
2134 gst_multi_handle_sink_stop (GstBaseSink * bsink)
2135 {
2136   GstMultiHandleSinkClass *mhclass;
2137   GstBuffer *buf;
2138   gint i;
2139   GstMultiHandleSink *mhsink = GST_MULTI_HANDLE_SINK (bsink);
2140
2141   mhclass = GST_MULTI_HANDLE_SINK_GET_CLASS (mhsink);
2142
2143   if (!GST_OBJECT_FLAG_IS_SET (bsink, GST_MULTI_HANDLE_SINK_OPEN))
2144     return TRUE;
2145
2146   mhsink->running = FALSE;
2147
2148   mhclass->stop_pre (mhsink);
2149
2150   if (mhsink->thread) {
2151     GST_DEBUG_OBJECT (mhsink, "joining thread");
2152     g_thread_join (mhsink->thread);
2153     GST_DEBUG_OBJECT (mhsink, "joined thread");
2154     mhsink->thread = NULL;
2155   }
2156
2157   /* free the clients */
2158   mhclass->clear (GST_MULTI_HANDLE_SINK (mhsink));
2159
2160   if (mhsink->streamheader) {
2161     g_slist_foreach (mhsink->streamheader, (GFunc) gst_mini_object_unref, NULL);
2162     g_slist_free (mhsink->streamheader);
2163     mhsink->streamheader = NULL;
2164   }
2165
2166   if (mhclass->close)
2167     mhclass->close (mhsink);
2168
2169   mhclass->stop_post (mhsink);
2170
2171   /* remove all queued buffers */
2172   if (mhsink->bufqueue) {
2173     GST_DEBUG_OBJECT (mhsink, "Emptying bufqueue with %d buffers",
2174         mhsink->bufqueue->len);
2175     for (i = mhsink->bufqueue->len - 1; i >= 0; --i) {
2176       buf = g_array_index (mhsink->bufqueue, GstBuffer *, i);
2177       GST_LOG_OBJECT (mhsink, "Removing buffer %p (%d) with refcount %d", buf,
2178           i, GST_MINI_OBJECT_REFCOUNT (buf));
2179       gst_buffer_unref (buf);
2180       mhsink->bufqueue = g_array_remove_index (mhsink->bufqueue, i);
2181     }
2182     /* freeing the array is done in _finalize */
2183   }
2184   GST_OBJECT_FLAG_UNSET (mhsink, GST_MULTI_HANDLE_SINK_OPEN);
2185
2186   return TRUE;
2187 }
2188
2189 static GstStateChangeReturn
2190 gst_multi_handle_sink_change_state (GstElement * element,
2191     GstStateChange transition)
2192 {
2193   GstMultiHandleSink *sink;
2194   GstStateChangeReturn ret;
2195
2196   sink = GST_MULTI_HANDLE_SINK (element);
2197
2198   /* we disallow changing the state from the streaming thread */
2199   if (g_thread_self () == sink->thread)
2200     return GST_STATE_CHANGE_FAILURE;
2201
2202
2203   switch (transition) {
2204     case GST_STATE_CHANGE_NULL_TO_READY:
2205       if (!gst_multi_handle_sink_start (GST_BASE_SINK (sink)))
2206         goto start_failed;
2207       break;
2208     case GST_STATE_CHANGE_READY_TO_PAUSED:
2209       break;
2210     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2211       break;
2212     default:
2213       break;
2214   }
2215
2216   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2217
2218   switch (transition) {
2219     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2220       break;
2221     case GST_STATE_CHANGE_PAUSED_TO_READY:
2222       break;
2223     case GST_STATE_CHANGE_READY_TO_NULL:
2224       gst_multi_handle_sink_stop (GST_BASE_SINK (sink));
2225       break;
2226     default:
2227       break;
2228   }
2229   return ret;
2230
2231   /* ERRORS */
2232 start_failed:
2233   {
2234     /* error message was posted */
2235     return GST_STATE_CHANGE_FAILURE;
2236   }
2237 }