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