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